content
stringlengths
86
88.9k
title
stringlengths
0
150
question
stringlengths
1
35.8k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
30
130
Q: Java Evaluating a mathematical expression using prefix notation Using the following input string * + 16 4 + 3 1 and these instructions: A prefix expression is where the operator comes first. For example, + 5 7 would be 12. I am able to successfully generate the expected output of 80 with my current code, which I will post below. However, with another input string * + 16 * + 16 4 + 3 1 + 3 1 my output is 576, where it is expected to be 384. I'm not quite sure where I went wrong with my algorithm. public class QueueUtils { public static Queue<String> build(String line) { Queue<String> queue = new LinkedList<>(); Scanner scanner = new Scanner(line); while (scanner.hasNext()) { String token = scanner.next(); queue.add(token); } return queue; } public static int eval(Queue<String> s) { List<String> list = new ArrayList<>(s); List<String> operators = new ArrayList<>(); operators.add("+"); operators.add("-"); operators.add("*"); int n = eval(list, operators); return n; } private static Integer eval(List<String> list, List<String> operators) { for (int i = 0; i < list.size(); i++) { String current = list.get(i); String prev = null; String next = null; String nextNext = null; if (i != 0) { prev = list.get(i - 1); } if (i != list.size() - 1) { next = list.get(i + 1); } if (i < list.size() - 2) { nextNext = list.get(i + 2); } if (operators.contains(prev) && prev != null) { if (!operators.contains(current)) { int a = Integer.parseInt(current); if (!operators.contains(next) && next != null) { int b = Integer.parseInt(next); Integer result = doOperation(prev, a, b); list.remove(current); list.remove(next); list.add(i, result.toString()); eval(list, operators); } if (next == null) { list.remove(prev); } } else { if (!operators.contains(next)) { if (operators.contains(nextNext)) { list.remove(current); eval(list, operators); } } } } else { if (operators.contains(current)) { if (!operators.contains(next)) { if (operators.contains(nextNext) || nextNext == null) { if (prev != null) { list.remove(current); eval(list, operators); } } } } } } return Integer.parseInt(list.get(0)); } private static int doOperation(String operator, int a, int b) { int n = 0; if (operator.equals("+")) { n = a + b; } else if (operator.equals("-")) { n = a - b; } else if (operator.equals("*")) { n = a * b; } return n; } } Calling code: public class Demo2 { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); System.out.println("Enter an expression in prefix form (operator comes first)"); String line = keyboard.nextLine(); Queue<String> q = QueueUtils.build(line); int result = QueueUtils.eval(q); System.out.println(result); } } A: So in order to solve this you need first need to reverse your input (so * + 16 * + 16 4 + 3 1 + 3 1 will become 1 3 + 1 3 + 4 16 + * 16 + *) and then use a bit of recursion to work your operations in groups of three. So 1 3 + 1 3 + 4 16 + * 16 + * 4 4 20 * 16 + * 4 [80 16 + *] // we can't do anything with 4 4 20, so we just move on one. 4 [96 *] 4 96 * 384 Here's the code: import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class InputFunction { private int doOperation(int a, int b, String operator) throws Exception { int result; if("+".equals(operator)){ result = a + b; } else if("-".equals(operator)){ result = a - b; } else if("*".equals(operator)){ result = a * b; } else { throw new Exception("Unsupported operator \"" + operator + "\""); } return result; } private List<String> evaluate(List<String> function) throws Exception { List<String> processed = new ArrayList<>(); if(function.size() <= 2) { return function; } else { for (int i = 0; i < function.size(); i += 3) { String a = function.get(i); if ((i + 1) < function.size()) { String b = function.get(i + 1); if ((i + 2) < function.size()) { String c = function.get(i + 2); if (a.matches("\\d+") && b.matches("\\d+") && !c.matches("\\d+")) { processed.add(String.valueOf(doOperation(Integer.valueOf(a), Integer.valueOf(b), c))); } else { processed.add(a); if(c.matches("\\d+")) { processed.addAll(evaluate(function.subList(i + 1, function.size()))); break; } else { processed.add(b); processed.add(c); } } } else { processed.add(a); processed.add(b); } } else { processed.add(a); } } } return evaluate(processed); } private void doFunction(String input) throws Exception{ List<String> function = Arrays.asList(input.split(" ")); Collections.reverse(function); System.out.println(evaluate(function)); } public static void main(String ... args) { InputFunction inputFunction = new InputFunction(); try { inputFunction.doFunction("+ + 5 5 + 5 5"); inputFunction.doFunction("* + 16 * + 16 4 + 3 1 + 3 1"); } catch (Exception e) { e.printStackTrace(); } } } ... admit-ably I've not tried with any examples with a "-", but you should get the idea. A: I know it is a bit too late to answer this, but the answer given does not contain any stacks or queues, and the assignment requires that you use them. so here it is:    public static int eval(Queue<String> s){ Stack<String> list = new Stack<>(); Stack<Integer> saved = new Stack<>(); list.addAll(s); while(!list.isEmpty()){ String val = list.pop(); if(val.equals("+") || val.equals("-") || val.equals("*")){ if(val.equals("+")){ saved.add((saved.pop() + saved.pop())); } if(val.equals("-")){ saved.add((saved.pop() - saved.pop())); } if(val.equals("*")){ saved.add((saved.pop() * saved.pop())); } }else{ saved.add(Integer.parseInt(val)); } } return saved.pop(); }
Java Evaluating a mathematical expression using prefix notation
Using the following input string * + 16 4 + 3 1 and these instructions: A prefix expression is where the operator comes first. For example, + 5 7 would be 12. I am able to successfully generate the expected output of 80 with my current code, which I will post below. However, with another input string * + 16 * + 16 4 + 3 1 + 3 1 my output is 576, where it is expected to be 384. I'm not quite sure where I went wrong with my algorithm. public class QueueUtils { public static Queue<String> build(String line) { Queue<String> queue = new LinkedList<>(); Scanner scanner = new Scanner(line); while (scanner.hasNext()) { String token = scanner.next(); queue.add(token); } return queue; } public static int eval(Queue<String> s) { List<String> list = new ArrayList<>(s); List<String> operators = new ArrayList<>(); operators.add("+"); operators.add("-"); operators.add("*"); int n = eval(list, operators); return n; } private static Integer eval(List<String> list, List<String> operators) { for (int i = 0; i < list.size(); i++) { String current = list.get(i); String prev = null; String next = null; String nextNext = null; if (i != 0) { prev = list.get(i - 1); } if (i != list.size() - 1) { next = list.get(i + 1); } if (i < list.size() - 2) { nextNext = list.get(i + 2); } if (operators.contains(prev) && prev != null) { if (!operators.contains(current)) { int a = Integer.parseInt(current); if (!operators.contains(next) && next != null) { int b = Integer.parseInt(next); Integer result = doOperation(prev, a, b); list.remove(current); list.remove(next); list.add(i, result.toString()); eval(list, operators); } if (next == null) { list.remove(prev); } } else { if (!operators.contains(next)) { if (operators.contains(nextNext)) { list.remove(current); eval(list, operators); } } } } else { if (operators.contains(current)) { if (!operators.contains(next)) { if (operators.contains(nextNext) || nextNext == null) { if (prev != null) { list.remove(current); eval(list, operators); } } } } } } return Integer.parseInt(list.get(0)); } private static int doOperation(String operator, int a, int b) { int n = 0; if (operator.equals("+")) { n = a + b; } else if (operator.equals("-")) { n = a - b; } else if (operator.equals("*")) { n = a * b; } return n; } } Calling code: public class Demo2 { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); System.out.println("Enter an expression in prefix form (operator comes first)"); String line = keyboard.nextLine(); Queue<String> q = QueueUtils.build(line); int result = QueueUtils.eval(q); System.out.println(result); } }
[ "So in order to solve this you need first need to reverse your input (so * + 16 * + 16 4 + 3 1 + 3 1 will become 1 3 + 1 3 + 4 16 + * 16 + *) and then use a bit of recursion to work your operations in groups of three.\nSo \n1 3 + 1 3 + 4 16 + * 16 + *\n4 4 20 * 16 + *\n4 [80 16 + *] // we can't do anything with 4 4 20, so we just move on one.\n4 [96 *]\n4 96 *\n384\n\nHere's the code:\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class InputFunction {\n\n private int doOperation(int a, int b, String operator) throws Exception {\n int result;\n if(\"+\".equals(operator)){\n result = a + b;\n } else if(\"-\".equals(operator)){\n result = a - b;\n } else if(\"*\".equals(operator)){\n result = a * b;\n } else {\n throw new Exception(\"Unsupported operator \\\"\" + operator + \"\\\"\");\n }\n return result;\n }\n\n private List<String> evaluate(List<String> function) throws Exception {\n List<String> processed = new ArrayList<>();\n if(function.size() <= 2) {\n return function;\n } else {\n for (int i = 0; i < function.size(); i += 3) {\n String a = function.get(i);\n if ((i + 1) < function.size()) {\n String b = function.get(i + 1);\n if ((i + 2) < function.size()) {\n String c = function.get(i + 2);\n if (a.matches(\"\\\\d+\") && b.matches(\"\\\\d+\") && !c.matches(\"\\\\d+\")) {\n processed.add(String.valueOf(doOperation(Integer.valueOf(a), Integer.valueOf(b), c)));\n } else {\n processed.add(a);\n if(c.matches(\"\\\\d+\")) {\n processed.addAll(evaluate(function.subList(i + 1, function.size())));\n break;\n } else {\n processed.add(b);\n processed.add(c);\n }\n }\n } else {\n processed.add(a);\n processed.add(b);\n }\n } else {\n processed.add(a);\n }\n }\n }\n return evaluate(processed);\n }\n\n private void doFunction(String input) throws Exception{\n List<String> function = Arrays.asList(input.split(\" \"));\n Collections.reverse(function);\n System.out.println(evaluate(function));\n }\n\n public static void main(String ... args) {\n InputFunction inputFunction = new InputFunction();\n try {\n inputFunction.doFunction(\"+ + 5 5 + 5 5\");\n inputFunction.doFunction(\"* + 16 * + 16 4 + 3 1 + 3 1\");\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n}\n\n... admit-ably I've not tried with any examples with a \"-\", but you should get the idea. \n", "I know it is a bit too late to answer this, but the answer given does not contain any stacks or queues, and the assignment requires that you use them. so here it is:   \n public static int eval(Queue<String> s){\n Stack<String> list = new Stack<>();\n Stack<Integer> saved = new Stack<>();\n list.addAll(s);\n while(!list.isEmpty()){\n String val = list.pop();\n if(val.equals(\"+\") || val.equals(\"-\") || val.equals(\"*\")){\n if(val.equals(\"+\")){\n saved.add((saved.pop() + saved.pop()));\n }\n if(val.equals(\"-\")){\n saved.add((saved.pop() - saved.pop()));\n }\n if(val.equals(\"*\")){\n saved.add((saved.pop() * saved.pop()));\n }\n }else{\n saved.add(Integer.parseInt(val));\n }\n\n }\n\n return saved.pop();\n}\n\n" ]
[ 1, 0 ]
[]
[]
[ "java", "math", "prefix_operator", "token" ]
stackoverflow_0059298622_java_math_prefix_operator_token.txt
Q: How to assign correct projection and extent to a raster using terra r package? I am trying to read a tif file using terra r package using the following code hh <- rast("imagery_HH.tif") #> Warning message: #> [rast] unknown extent hh #> class : SpatRaster #> dimensions : 8371, 8946, 1 (nrow, ncol, nlyr) #> resolution : 1, 1 (x, y) #> extent : 0, 8946, 0, 8371 (xmin, xmax, ymin, ymax) #> coord. ref. : #> source : imagery_HH.tif #> name : imagery_HH Using the function terra::describe("imagery_HH.tif"), I got the following information: [4] "Size is 8946, 8371" [5] "GCP Projection = " [6] "GEOGCRS[\"WGS 84\"," [7] " DATUM[\"World Geodetic System 1984\"," [8] " ELLIPSOID[\"WGS 84\",6378137,298.257223563," [9] " LENGTHUNIT[\"metre\",1]]]," [10] " PRIMEM[\"Greenwich\",0," [11] " ANGLEUNIT[\"degree\",0.0174532925199433]]," [12] " CS[ellipsoidal,2]," [13] " AXIS[\"geodetic latitude (Lat)\",north," [14] " ORDER[1]," [15] " ANGLEUNIT[\"degree\",0.0174532925199433]]," [16] " AXIS[\"geodetic longitude (Lon)\",east," [17] " ORDER[2]," [18] " ANGLEUNIT[\"degree\",0.0174532925199433]]," [19] " USAGE[" [20] " SCOPE[\"Horizontal component of 3D system.\"]," [21] " AREA[\"World.\"]," [22] " BBOX[-90,-180,90,180]]," [23] " ID[\"EPSG\",4326]]" [24] "Data axis to CRS axis mapping: 2,1" If we look closely, we can see that the coordinate reference is missing and the resolution is showing 1 x 1 with the incorrect extent. But if we open the tif file in QGIS, it shows the following properties having a crs of EPSG:4326 Now how to read the tif file with proper coordiante system, resolution and extent using terra R package? Here is the link to download the raster file A: The below suggests that this is not a regular raster. It shows GCPs (coordinates for particular raster cells) and if these are needed you probably do not have a rectangular extent or constant resolution. (I have not checked if they are, but you could). Reading such a file requires a different approach than reading a regular raster file. This is the first time I see a file like this, and "terra" currently does not support it; I will put it on the to-do list. terra::describe("imagery_HH.tif")[31:40] [1] "Data axis to CRS axis mapping: 2,1" [2] "GCP[ 0]: Id=1, Info=" [3] " (0,0) -> (78.591314,29.400624,0)" [4] "GCP[ 1]: Id=2, Info=" [5] " (357.84,0) -> (78.52592634,29.41112936,0)" [6] "GCP[ 2]: Id=3, Info=" [7] " (715.68,0) -> (78.4607346,29.4215638,0)" [8] "GCP[ 3]: Id=4, Info=" [9] " (1073.52,0) -> (78.39539736,29.43198708,0)" [10] "GCP[ 4]: Id=5, Info=" (and so on until line 1383). A: As noted by @bretauv, the projection is loading correctly. I'm not sure why the extent isn't being read correctly by terra::rast, but if it's any consolation, it isn't read by raster::raster, so it's not just a terra problem. In any case, the extent can be set manually if you know the extent, which in this case you do. hh <- terra::rast("imagery_HH.tif") terra::set.ext( x = hh, value = c(76.6811227745188262, 78.59105666365414556, 27.9827663027027924, 29.6529629093873979) )
How to assign correct projection and extent to a raster using terra r package?
I am trying to read a tif file using terra r package using the following code hh <- rast("imagery_HH.tif") #> Warning message: #> [rast] unknown extent hh #> class : SpatRaster #> dimensions : 8371, 8946, 1 (nrow, ncol, nlyr) #> resolution : 1, 1 (x, y) #> extent : 0, 8946, 0, 8371 (xmin, xmax, ymin, ymax) #> coord. ref. : #> source : imagery_HH.tif #> name : imagery_HH Using the function terra::describe("imagery_HH.tif"), I got the following information: [4] "Size is 8946, 8371" [5] "GCP Projection = " [6] "GEOGCRS[\"WGS 84\"," [7] " DATUM[\"World Geodetic System 1984\"," [8] " ELLIPSOID[\"WGS 84\",6378137,298.257223563," [9] " LENGTHUNIT[\"metre\",1]]]," [10] " PRIMEM[\"Greenwich\",0," [11] " ANGLEUNIT[\"degree\",0.0174532925199433]]," [12] " CS[ellipsoidal,2]," [13] " AXIS[\"geodetic latitude (Lat)\",north," [14] " ORDER[1]," [15] " ANGLEUNIT[\"degree\",0.0174532925199433]]," [16] " AXIS[\"geodetic longitude (Lon)\",east," [17] " ORDER[2]," [18] " ANGLEUNIT[\"degree\",0.0174532925199433]]," [19] " USAGE[" [20] " SCOPE[\"Horizontal component of 3D system.\"]," [21] " AREA[\"World.\"]," [22] " BBOX[-90,-180,90,180]]," [23] " ID[\"EPSG\",4326]]" [24] "Data axis to CRS axis mapping: 2,1" If we look closely, we can see that the coordinate reference is missing and the resolution is showing 1 x 1 with the incorrect extent. But if we open the tif file in QGIS, it shows the following properties having a crs of EPSG:4326 Now how to read the tif file with proper coordiante system, resolution and extent using terra R package? Here is the link to download the raster file
[ "The below suggests that this is not a regular raster. It shows GCPs (coordinates for particular raster cells) and if these are needed you probably do not have a rectangular extent or constant resolution. (I have not checked if they are, but you could).\nReading such a file requires a different approach than reading a regular raster file. This is the first time I see a file like this, and \"terra\" currently does not support it; I will put it on the to-do list.\nterra::describe(\"imagery_HH.tif\")[31:40]\n [1] \"Data axis to CRS axis mapping: 2,1\" \n [2] \"GCP[ 0]: Id=1, Info=\" \n [3] \" (0,0) -> (78.591314,29.400624,0)\" \n [4] \"GCP[ 1]: Id=2, Info=\" \n [5] \" (357.84,0) -> (78.52592634,29.41112936,0)\" \n [6] \"GCP[ 2]: Id=3, Info=\" \n [7] \" (715.68,0) -> (78.4607346,29.4215638,0)\" \n [8] \"GCP[ 3]: Id=4, Info=\" \n [9] \" (1073.52,0) -> (78.39539736,29.43198708,0)\"\n[10] \"GCP[ 4]: Id=5, Info=\" \n\n(and so on until line 1383).\n", "As noted by @bretauv, the projection is loading correctly. I'm not sure why the extent isn't being read correctly by terra::rast, but if it's any consolation, it isn't read by raster::raster, so it's not just a terra problem. In any case, the extent can be set manually if you know the extent, which in this case you do.\nhh <- terra::rast(\"imagery_HH.tif\")\nterra::set.ext(\n x = hh, \n value = c(76.6811227745188262,\n 78.59105666365414556,\n 27.9827663027027924,\n 29.6529629093873979)\n)\n\n" ]
[ 1, 0 ]
[]
[]
[ "r", "terra" ]
stackoverflow_0074613690_r_terra.txt
Q: In R, how can I add values onto the end of rows where one value matches that of another data frame? I currently have two data frames that I'm working with. The first is a dataset of MLB baseball games, containing the date of the game and player IDs. Game_Logs Date Batter 1 ID Batter 2 ID May 1 Joe Kevin May 1 John Samuel May 2 Joe Kevin May 2 John Samuel The second dataset contains the players stats for the season. This dataset is scraped from the web and can therefore be updated to contain all the stats for each player up until the date of the game listed. For example, below you can see data frames for two different days. May_1 Batter ID Hits Home Runs Batting Average Joe 15 4 .244 John 18 6 .261 Kevin 29 16 .347 Samuel 7 1 .161 May_2 Batter ID Hits Home Runs Batting Average Joe 16 4 .247 John 19 6 .265 Kevin 30 17 .343 Samuel 9 2 .180 What I would like to do is loop through the list of games and, where the date and batter ID match, add the stats from the second data frame onto the end of the correct row. The part that is troubling me is that for each row in the first data frame, there are multiple Batter IDs that need to be matched. My initial thought would be to use nested loops to do this but I am having trouble coming to a solution that lets me loop through each row in order so that I can limit the number of times I am scraping the data. Here is the start of my initial thought process. for (i in rows) { if (i %in% BatterID){ ... } } Any thoughts? Thanks. A: You need to combine the stats data frames into a single data frame with a Date column, then it's a simple join. Something like this: # put all the stats data frames in a list stats = list(May_1 = May_1, May_2 = May_2) # (in your real case you probably want to use `stats = mget(ls(pattern = ...))` # where `pattern` is a regex pattern to identify these data frames # combine them and get rid of the underscores library(dplyr) library(stringr) stats_df = bind_rows(stats, .id = "Date") %>% mutate(Date = str_replace(Date, pattern = "_", replacement = " ")) # and join Game_Logs %>% left_join( stats_df, by = c("Date", "Batter 1 ID" = "Batter ID") ) %>% left_join( stats_df, by = c("Date", "Batter 2 ID" = "Batter ID", suffix = c(".1", ".2") )
In R, how can I add values onto the end of rows where one value matches that of another data frame?
I currently have two data frames that I'm working with. The first is a dataset of MLB baseball games, containing the date of the game and player IDs. Game_Logs Date Batter 1 ID Batter 2 ID May 1 Joe Kevin May 1 John Samuel May 2 Joe Kevin May 2 John Samuel The second dataset contains the players stats for the season. This dataset is scraped from the web and can therefore be updated to contain all the stats for each player up until the date of the game listed. For example, below you can see data frames for two different days. May_1 Batter ID Hits Home Runs Batting Average Joe 15 4 .244 John 18 6 .261 Kevin 29 16 .347 Samuel 7 1 .161 May_2 Batter ID Hits Home Runs Batting Average Joe 16 4 .247 John 19 6 .265 Kevin 30 17 .343 Samuel 9 2 .180 What I would like to do is loop through the list of games and, where the date and batter ID match, add the stats from the second data frame onto the end of the correct row. The part that is troubling me is that for each row in the first data frame, there are multiple Batter IDs that need to be matched. My initial thought would be to use nested loops to do this but I am having trouble coming to a solution that lets me loop through each row in order so that I can limit the number of times I am scraping the data. Here is the start of my initial thought process. for (i in rows) { if (i %in% BatterID){ ... } } Any thoughts? Thanks.
[ "You need to combine the stats data frames into a single data frame with a Date column, then it's a simple join.\nSomething like this:\n# put all the stats data frames in a list\nstats = list(May_1 = May_1, May_2 = May_2)\n# (in your real case you probably want to use `stats = mget(ls(pattern = ...))`\n# where `pattern` is a regex pattern to identify these data frames\n\n# combine them and get rid of the underscores\nlibrary(dplyr)\nlibrary(stringr)\nstats_df = bind_rows(stats, .id = \"Date\") %>%\n mutate(Date = str_replace(Date, pattern = \"_\", replacement = \" \"))\n\n# and join\nGame_Logs %>%\n left_join(\n stats_df,\n by = c(\"Date\", \"Batter 1 ID\" = \"Batter ID\")\n ) %>%\n left_join(\n stats_df,\n by = c(\"Date\", \"Batter 2 ID\" = \"Batter ID\",\n suffix = c(\".1\", \".2\")\n )\n\n" ]
[ 1 ]
[]
[]
[ "if_statement", "join", "loops", "nested_loops", "r" ]
stackoverflow_0074663656_if_statement_join_loops_nested_loops_r.txt
Q: Does remove() change iteration order in LinkedHashMap? LinkedHashMap has underlying double-linked list, which enables preservation of the insertion order during the iteration. Non-structural changes, i.e. replacement of the value of an already inserted key, does not affect iteration order. However, I am still wondering, whether remove(key) operation changes the iteration order in LinkedHashMap. As I have tested on really small examples, it does not affect the order of the elements, except for the missing element, which is not included during iteration, obviously - but anecdotes are not proofs. Supposedly, removal works as if in LinkedList (where the halves of the list split are at the index of the element are joined together) - on the other hand, the programmer maybe should take into account rehashing or reallocation. I am really confused and after reading the documentation of LinkedHashMap thoroughly, also still very doubtful, as I need a structure which preserves the order of insertion but enables an easy lookup and removal of the entries. A: I am really confused and after reading the documentation of LinkedHashMap thoroughly, also still very doubtful ... Here's the relevant part of the specification. "This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.") The "normally" refers to the fact that you can create a LinkedHashMap in which the iteration order is access-order. That says nothing about the order of remaining entries being changed by deletion. Indeed, if an implementation (hypothetically) did change the order when deleting an entry, that would plainly contradict the unqualified statements about iteration order. In other words, it would not conform to the specification. Conversely, if the spec writers intended that deletion should affect the iteration order, they would have said so explicitly. Just like they did mentioned that "reinsertion" doesn't affect it. As a general rule, specifications are not written to spell out precisely what happens in every possible scenario. If property Y is a logical consequence of a specified property X, then a specification does not need to (and typically won't) state property Y explicitly. It is normal for specification writers to assume that readers will make the correct logical inferences for themselves. A: The remove() method of the LinkedHashMap class in Java does not change the iteration order of the map. When you iterate over a LinkedHashMap, the elements will be returned in the order in which they were inserted. This is because a LinkedHashMap maintains a doubly-linked list internally, which allows it to maintain the insertion order of the elements. When you call the remove() method, the element is removed from the map, but the insertion order of the remaining elements is preserved. Here is an example of how the remove() method works on a LinkedHashMap: LinkedHashMap<String, Integer> map = new LinkedHashMap<>(); map.put("apple", 1); map.put("banana", 2); map.put("cherry", 3); // Remove the "banana" element from the map map.remove("banana"); // Iterate over the map and print the elements for (Map.Entry<String, Integer> entry : map.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } In the example above, we create a LinkedHashMap and add three elements to it. We then remove the "banana" element from the map using the remove() method. Finally, we iterate over the map and print the remaining elements. The output of this code will be apple: 1 cherry: 3 As you can see, the iteration order of the map is preserved, and the elements are returned in the order in which they were inserted. The "banana" element is removed from the map, but the "apple" and "cherry" elements remain in their original positions.
Does remove() change iteration order in LinkedHashMap?
LinkedHashMap has underlying double-linked list, which enables preservation of the insertion order during the iteration. Non-structural changes, i.e. replacement of the value of an already inserted key, does not affect iteration order. However, I am still wondering, whether remove(key) operation changes the iteration order in LinkedHashMap. As I have tested on really small examples, it does not affect the order of the elements, except for the missing element, which is not included during iteration, obviously - but anecdotes are not proofs. Supposedly, removal works as if in LinkedList (where the halves of the list split are at the index of the element are joined together) - on the other hand, the programmer maybe should take into account rehashing or reallocation. I am really confused and after reading the documentation of LinkedHashMap thoroughly, also still very doubtful, as I need a structure which preserves the order of insertion but enables an easy lookup and removal of the entries.
[ "\nI am really confused and after reading the documentation of LinkedHashMap thoroughly, also still very doubtful ...\n\nHere's the relevant part of the specification.\n\n\"This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.\")\n\nThe \"normally\" refers to the fact that you can create a LinkedHashMap in which the iteration order is access-order.\nThat says nothing about the order of remaining entries being changed by deletion. Indeed, if an implementation (hypothetically) did change the order when deleting an entry, that would plainly contradict the unqualified statements about iteration order. In other words, it would not conform to the specification.\nConversely, if the spec writers intended that deletion should affect the iteration order, they would have said so explicitly. Just like they did mentioned that \"reinsertion\" doesn't affect it.\n\nAs a general rule, specifications are not written to spell out precisely what happens in every possible scenario. If property Y is a logical consequence of a specified property X, then a specification does not need to (and typically won't) state property Y explicitly.\nIt is normal for specification writers to assume that readers will make the correct logical inferences for themselves.\n", "The remove() method of the LinkedHashMap class in Java does not change the iteration order of the map. When you iterate over a LinkedHashMap, the elements will be returned in the order in which they were inserted.\nThis is because a LinkedHashMap maintains a doubly-linked list internally, which allows it to maintain the insertion order of the elements. When you call the remove() method, the element is removed from the map, but the insertion order of the remaining elements is preserved.\nHere is an example of how the remove() method works on a LinkedHashMap:\nLinkedHashMap<String, Integer> map = new LinkedHashMap<>();\n\nmap.put(\"apple\", 1);\nmap.put(\"banana\", 2);\nmap.put(\"cherry\", 3);\n\n// Remove the \"banana\" element from the map\nmap.remove(\"banana\");\n\n// Iterate over the map and print the elements\nfor (Map.Entry<String, Integer> entry : map.entrySet()) {\n System.out.println(entry.getKey() + \": \" + entry.getValue());\n}\n\nIn the example above, we create a LinkedHashMap and add three elements to it. We then remove the \"banana\" element from the map using the remove() method. Finally, we iterate over the map and print the remaining elements.\nThe output of this code will be\napple: 1\ncherry: 3\n\nAs you can see, the iteration order of the map is preserved, and the elements are returned in the order in which they were inserted. The \"banana\" element is removed from the map, but the \"apple\" and \"cherry\" elements remain in their original positions.\n" ]
[ 2, 1 ]
[]
[]
[ "iteration", "java", "linkedhashmap" ]
stackoverflow_0074663611_iteration_java_linkedhashmap.txt
Q: Unable to login to Azure Databse using "Azure Active Directory - Integrated" or x86 ODBC connections I’m not able to connect to my Azure database using “Azure Active Directory – Integrated” when using SSMS 17 or x86 ODBC connections, but I’m able to connect with SSMS 19 and x64 ODBC connections. I know this has been discussed extensively before, my issue is similar to this posting: Unable to load adalsql.dll error when calling Invoke-sqlcmd In my case the x86 applications are not working and the x64 are fine. All of this seem to have started after installing SSMS 19, I have: Both x86 and x64 ADAL files, I have also tried with each one without the other on my system: C:\Windows\SysWOW64\AdalSQL.dll C:\Windows\System32\AdalSQL.dll …and their Registry entries is there: [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSADALSQL]\TargetDir = C:\WINDOWS\system32\adalsql.dll [HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\MSADALSQL]\TargetDir = C:\WINDOWS\SysWOW64\adalsql.dll When I use SSMS 17 I get this message: I have removed both SSMS 18 and 19 and started from scratch but that did not help. I have followed the recommendations on the posting above with no luck. It seems that I have everything I need, but I can’t pinpoint what the issue is or what is that I’m missing. A: Please read below. If any of your applications use the Azure Active Directory Authentication Library (ADAL) for authentication and authorization functionality, it's time to migrate them to the Microsoft Authentication Library (MSAL). All Microsoft support and development for ADAL, including security fixes, ends in December, 2022. For more information, please read here. As you can read here Microsoft intended to end support back in June 2022, but it extended support 6 months more. Have you considered to quickly migrating to MSAL.
Unable to login to Azure Databse using "Azure Active Directory - Integrated" or x86 ODBC connections
I’m not able to connect to my Azure database using “Azure Active Directory – Integrated” when using SSMS 17 or x86 ODBC connections, but I’m able to connect with SSMS 19 and x64 ODBC connections. I know this has been discussed extensively before, my issue is similar to this posting: Unable to load adalsql.dll error when calling Invoke-sqlcmd In my case the x86 applications are not working and the x64 are fine. All of this seem to have started after installing SSMS 19, I have: Both x86 and x64 ADAL files, I have also tried with each one without the other on my system: C:\Windows\SysWOW64\AdalSQL.dll C:\Windows\System32\AdalSQL.dll …and their Registry entries is there: [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSADALSQL]\TargetDir = C:\WINDOWS\system32\adalsql.dll [HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\MSADALSQL]\TargetDir = C:\WINDOWS\SysWOW64\adalsql.dll When I use SSMS 17 I get this message: I have removed both SSMS 18 and 19 and started from scratch but that did not help. I have followed the recommendations on the posting above with no luck. It seems that I have everything I need, but I can’t pinpoint what the issue is or what is that I’m missing.
[ "Please read below.\n\nIf any of your applications use the Azure Active Directory Authentication Library (ADAL) for authentication and authorization functionality, it's time to migrate them to the Microsoft Authentication Library (MSAL).\nAll Microsoft support and development for ADAL, including security fixes, ends in December, 2022.\n\nFor more information, please read here.\nAs you can read here Microsoft intended to end support back in June 2022, but it extended support 6 months more. Have you considered to quickly migrating to MSAL.\n" ]
[ 1 ]
[]
[]
[ "azure_active_directory", "azure_sql_database" ]
stackoverflow_0074660113_azure_active_directory_azure_sql_database.txt
Q: How to get the scoreboard to work in Turtle Graphics? **I just need to update the score constantly when the ball crashes into the platform. What also I do not know is how to clone the ball to make multiple balls in the arena If anyone can give some input that would be great also Here is the code I have:** import turtle import random from random import randint import time from turtle import Turtle HEIGHT, WIDTH = 500, 500 screen = turtle.Screen() screen.screensize(HEIGHT, WIDTH) COLORS = 'white', 'green' ,'cyan', 'orange', 'skyblue' screen.bgcolor(random.choice(COLORS)) screen.title("Bounce a ball") CURSOR_SIZE = 20 def tDirection(direct): t.setheading(direct) # make arena def rectangle(): t.pendown() for i in range(2): t.forward(600) t.left(90) t.forward(600) t.left(90) t.penup() #defines new turtle pen = turtle.Turtle() #right and left keys def move_left(): pen.penup() pen.setheading(0) pen.bk(100) def move_right(): pen.penup() pen.setheading(0) pen.fd(100) #plaform########################### pen.penup() pen.goto(0, -250) pen.shape("square") pen.color("black") pen.shapesize(1, 5) screen.listen() screen.onkey(move_right, "Right") screen.onkey(move_left, "Left") ##################################### n = turtle.Turtle() score = 0 n.penup() n.goto(-50,250) n.write("Your score:", font=20) n.hideturtle() #circle###################################### t = Turtle("circle", visible=False) t.speed('fastest') t.pensize(5) t.penup() t.goto(-300, -300) ########################################### rectangle() index = 0 ##################################### t.color('black') t.home() t.showturtle() ##################################### direct = randint(1, 600) tDirection(direct) while True: t.forward(2) ty = t.ycor() def is_collided_with(a, b): return abs(a.xcor() - b.xcor()) < 10 and abs(a.ycor() - b.ycor()) < 10 # breaking out top or bottom if is_collided_with(t, pen): score += 1 print("Coll") continue if not CURSOR_SIZE - 300 <= ty <= 300 - CURSOR_SIZE: index += 1 t.color('pink') angleCurr = t.heading() if 0 < angleCurr < 180: tDirection(0 - angleCurr) else: tDirection(360 - angleCurr) t.forward(2) n.getscreen().update() tx = t.xcor() # breaking out left or right if not CURSOR_SIZE - 300 <= tx <= 300 - CURSOR_SIZE: index += 1 t.color('blue') angleCurr = t.heading() if 0 < angleCurr < 180: tDirection(180 - angleCurr) else: tDirection(540 - angleCurr) t.forward(2) Most of game is working I just do not know how to write a scoreboard and how to make it run smoothly. A: To create a scoreboard in this code, you can add a variable to keep track of the score and display it on the screen. Here is how you can do that: Add a variable to keep track of the score. You can do this by adding the following line at the top of the code, after the import statements: score = 0 Add code to update the score when the ball collides with the platform. You can do this by modifying the is_collided_with() function to increment the score variable by 1 when a collision is detected. The modified function should look like this: def is_collided_with(a, b): if abs(a.xcor() - b.xcor()) < 10 and abs(a.ycor() - b.ycor()) < 10: score += 1 return abs(a.xcor() - b.xcor()) < 10 and abs(a.ycor() - b.ycor()) < 10 Add code to display the score on the screen. You can do this by creating a new Turtle object and using its write() method to write the score to the screen. You can add the following code after the rectangle() function to create the Turtle object and write the score to the screen: # Create a new Turtle object to write the score score_turtle = turtle.Turtle() score_turtle.penup() score_turtle.goto(-50, 250) score_turtle.write("Your score: {}".format(score), font=20) score_turtle.hideturtle() Add code to update the score on the screen. You can do this by adding a line of code to the while loop that updates the score written on the screen. You can add the following line of code inside the while loop, after the continue statement: score_turtle.clear() score_turtle.write("Your score: {}".format(score), font -chatgpt
How to get the scoreboard to work in Turtle Graphics?
**I just need to update the score constantly when the ball crashes into the platform. What also I do not know is how to clone the ball to make multiple balls in the arena If anyone can give some input that would be great also Here is the code I have:** import turtle import random from random import randint import time from turtle import Turtle HEIGHT, WIDTH = 500, 500 screen = turtle.Screen() screen.screensize(HEIGHT, WIDTH) COLORS = 'white', 'green' ,'cyan', 'orange', 'skyblue' screen.bgcolor(random.choice(COLORS)) screen.title("Bounce a ball") CURSOR_SIZE = 20 def tDirection(direct): t.setheading(direct) # make arena def rectangle(): t.pendown() for i in range(2): t.forward(600) t.left(90) t.forward(600) t.left(90) t.penup() #defines new turtle pen = turtle.Turtle() #right and left keys def move_left(): pen.penup() pen.setheading(0) pen.bk(100) def move_right(): pen.penup() pen.setheading(0) pen.fd(100) #plaform########################### pen.penup() pen.goto(0, -250) pen.shape("square") pen.color("black") pen.shapesize(1, 5) screen.listen() screen.onkey(move_right, "Right") screen.onkey(move_left, "Left") ##################################### n = turtle.Turtle() score = 0 n.penup() n.goto(-50,250) n.write("Your score:", font=20) n.hideturtle() #circle###################################### t = Turtle("circle", visible=False) t.speed('fastest') t.pensize(5) t.penup() t.goto(-300, -300) ########################################### rectangle() index = 0 ##################################### t.color('black') t.home() t.showturtle() ##################################### direct = randint(1, 600) tDirection(direct) while True: t.forward(2) ty = t.ycor() def is_collided_with(a, b): return abs(a.xcor() - b.xcor()) < 10 and abs(a.ycor() - b.ycor()) < 10 # breaking out top or bottom if is_collided_with(t, pen): score += 1 print("Coll") continue if not CURSOR_SIZE - 300 <= ty <= 300 - CURSOR_SIZE: index += 1 t.color('pink') angleCurr = t.heading() if 0 < angleCurr < 180: tDirection(0 - angleCurr) else: tDirection(360 - angleCurr) t.forward(2) n.getscreen().update() tx = t.xcor() # breaking out left or right if not CURSOR_SIZE - 300 <= tx <= 300 - CURSOR_SIZE: index += 1 t.color('blue') angleCurr = t.heading() if 0 < angleCurr < 180: tDirection(180 - angleCurr) else: tDirection(540 - angleCurr) t.forward(2) Most of game is working I just do not know how to write a scoreboard and how to make it run smoothly.
[ "To create a scoreboard in this code, you can add a variable to keep track of the score and display it on the screen. Here is how you can do that:\nAdd a variable to keep track of the score. You can do this by adding the following line at the top of the code, after the import statements:\nscore = 0\n\nAdd code to update the score when the ball collides with the platform. You can do this by modifying the is_collided_with() function to increment the score variable by 1 when a collision is detected. The modified function should look like this:\ndef is_collided_with(a, b):\n if abs(a.xcor() - b.xcor()) < 10 and abs(a.ycor() - b.ycor()) < 10:\n score += 1\n return abs(a.xcor() - b.xcor()) < 10 and abs(a.ycor() - b.ycor()) < 10\n\nAdd code to display the score on the screen. You can do this by creating a new Turtle object and using its write() method to write the score to the screen. You can add the following code after the rectangle() function to create the Turtle object and write the score to the screen:\n# Create a new Turtle object to write the score\nscore_turtle = turtle.Turtle()\nscore_turtle.penup()\nscore_turtle.goto(-50, 250)\nscore_turtle.write(\"Your score: {}\".format(score), font=20)\nscore_turtle.hideturtle()\n\nAdd code to update the score on the screen. You can do this by adding a line of code to the while loop that updates the score written on the screen. You can add the following line of code inside the while loop, after the continue statement:\nscore_turtle.clear()\nscore_turtle.write(\"Your score: {}\".format(score), font\n\n\n-chatgpt\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x", "python_turtle", "turtle_graphics" ]
stackoverflow_0074663758_python_python_3.x_python_turtle_turtle_graphics.txt
Q: How to set focus to Vue3 Typescript app to input element on Bootstrap modal when opened I'm trying to do what seems to be a simple and common thing, that is proving to be quite difficult. I simply need a specific text input element to be set to focus upon the modal dialog opening. Here is what I've tried: Use autofocus on the HTML element. <input placeholder="Enter search text" type="text" autofocus class="form-control" v-model="searchterm"/> Does not focus , no errors ... Use v-focus on input element along with a directive. <input placeholder="Enter search text" type="text" v-focus class="form-control" v-model="searchterm"/> <script lang="ts"> import { defineComponent, PropType } from "@vue/runtime-core"; export default defineComponent({ name: "Crops-view", setup() { }, directives: { focus: { mounted: (el) => { el.focus(); console.log("focus set"); }, }, props: { ... ...}, }); </script> This apparently does fire the routine, but does so at initial page load, not at modal dialog open. This obviously won't work if I have multiple dialog boxes, each with its own initial focus. Use watch to trigger a function upon change in dialog visibility <div class="modal fade m-3 p-3 justify-content-center" id="crops-modal" data-bs-backdrop="static" v-show="showCropsModal" > <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <div class="title text-center">Crops</div> </div> <div class="row m-2"> <input placeholder="Enter search text" type="text" class="form-control" v-model="searchterm" /> </div> </div> </div> </div> </div> <script lang="ts"> import { defineComponent, PropType, ref } from "@vue/runtime-core"; export default defineComponent({ name: "Crops-view", setup() { const showCropsModal = true; const cropsearchinput = ref<HTMLInputElement>(); return { showCropsModal, cropsearchinput}; }, watch: { showCropsModal(value) { if (value) { (cropsearchinput.value as HTMLElement).focus(); } }, }, props: { ... ...}, }); </script> Does not compile . I got a lint error 'cropsearchinput' is not defined. I directives, methods, watch, v-focus and autofocus. A: In case someone went to the same issue here's my solution <script setup lang="ts"> import { ref, watch } from 'vue' const modal = ref<boolean>(false) const btn = ref<HTMLButtonElement>() watch(modal, (newVal: boolean) => { if (newVal==true) { setTimeout(() => { btn.value!.focus() }, 100) } }) </script>
How to set focus to Vue3 Typescript app to input element on Bootstrap modal when opened
I'm trying to do what seems to be a simple and common thing, that is proving to be quite difficult. I simply need a specific text input element to be set to focus upon the modal dialog opening. Here is what I've tried: Use autofocus on the HTML element. <input placeholder="Enter search text" type="text" autofocus class="form-control" v-model="searchterm"/> Does not focus , no errors ... Use v-focus on input element along with a directive. <input placeholder="Enter search text" type="text" v-focus class="form-control" v-model="searchterm"/> <script lang="ts"> import { defineComponent, PropType } from "@vue/runtime-core"; export default defineComponent({ name: "Crops-view", setup() { }, directives: { focus: { mounted: (el) => { el.focus(); console.log("focus set"); }, }, props: { ... ...}, }); </script> This apparently does fire the routine, but does so at initial page load, not at modal dialog open. This obviously won't work if I have multiple dialog boxes, each with its own initial focus. Use watch to trigger a function upon change in dialog visibility <div class="modal fade m-3 p-3 justify-content-center" id="crops-modal" data-bs-backdrop="static" v-show="showCropsModal" > <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <div class="title text-center">Crops</div> </div> <div class="row m-2"> <input placeholder="Enter search text" type="text" class="form-control" v-model="searchterm" /> </div> </div> </div> </div> </div> <script lang="ts"> import { defineComponent, PropType, ref } from "@vue/runtime-core"; export default defineComponent({ name: "Crops-view", setup() { const showCropsModal = true; const cropsearchinput = ref<HTMLInputElement>(); return { showCropsModal, cropsearchinput}; }, watch: { showCropsModal(value) { if (value) { (cropsearchinput.value as HTMLElement).focus(); } }, }, props: { ... ...}, }); </script> Does not compile . I got a lint error 'cropsearchinput' is not defined. I directives, methods, watch, v-focus and autofocus.
[ "In case someone went to the same issue\nhere's my solution\n<script setup lang=\"ts\">\nimport { ref, watch } from 'vue'\n\nconst modal = ref<boolean>(false)\nconst btn = ref<HTMLButtonElement>()\n\nwatch(modal, (newVal: boolean) => {\n if (newVal==true) {\n setTimeout(() => {\n btn.value!.focus()\n }, 100)\n }\n})\n</script>\n\n" ]
[ 0 ]
[]
[]
[ "twitter_bootstrap", "typescript", "vue.js" ]
stackoverflow_0071566260_twitter_bootstrap_typescript_vue.js.txt
Q: How can I get number just under a number in equation? How can I get numbers under the numbers in Quarto? I have this so far: \hat{y}_{1t}=-0.980+6.903*10^{-6}JanAprTNLoad_{t,} I cannot find any reference to get the numbers under the numbers in the equations. Thank you!! A: Try with \underset{}{} where contents in first bracket is put under the contents in second bracket. --- title: "Equations" format: html: default pdf: default --- $$ \begin{aligned} \hat{y}_{1t} &= \underset{(0.405)}{-0.980} + \underset{(1.069\times10^{-6}) }{6.903\times10^{-6}}JanAprTNLoad_{t,} \\ \hat{y}_{2t} &= \underset{(0.426)}{-0.217} + \underset{(1.360\times10^{-6}) }{5.596\times10^{-6}}JanMayTNLoad_{t,} \end{aligned} $$
How can I get number just under a number in equation?
How can I get numbers under the numbers in Quarto? I have this so far: \hat{y}_{1t}=-0.980+6.903*10^{-6}JanAprTNLoad_{t,} I cannot find any reference to get the numbers under the numbers in the equations. Thank you!!
[ "Try with \\underset{}{} where contents in first bracket is put under the contents in second bracket.\n---\ntitle: \"Equations\"\nformat: \n html: default\n pdf: default\n---\n\n$$\n\\begin{aligned}\n\\hat{y}_{1t} &= \\underset{(0.405)}{-0.980} + \\underset{(1.069\\times10^{-6}) }{6.903\\times10^{-6}}JanAprTNLoad_{t,} \\\\\n\\hat{y}_{2t} &= \\underset{(0.426)}{-0.217} + \\underset{(1.360\\times10^{-6}) }{5.596\\times10^{-6}}JanMayTNLoad_{t,}\n\\end{aligned}\n$$\n\n\n\n\n" ]
[ 1 ]
[]
[]
[ "equation", "markdown", "quarto" ]
stackoverflow_0074663359_equation_markdown_quarto.txt
Q: Set focus to search text field when we click on select 2 drop down I am using select2.js Version: 3.4.3 with bootstrap I have one drop down. When I click on drop down i got list with search text fields. But I my cursor not focused on search text fields. <form:select path="yearAge" id="yearAgeId" cssClass="form-control search-select static-select"> <form:option value="">Years</form:option> <c:forEach var="i" begin="1" end="125" > <form:option value="${i}" label="${i}"></form:option> </c:forEach> </form:select> $(".search-select.static-select").select2({ placeholder: $(this).attr('placeholder'), allowClear: true }); When I click on dropdown cursor focus should set to search text field automatically . Thank you...!!!!! A: If jQuery 3.6.0 is causing this you can use this: $(document).on('select2:open', () => { document.querySelector('.select2-search__field').focus(); }); A: Try this $(document).on('select2:open', (e) => { const selectId = e.target.id $(".select2-search__field[aria-controls='select2-" + selectId + "-results']").each(function ( key, value, ){ value.focus(); }) }) A: Tested and worked with jQuery 3.6.0: $(document).on("select2:open", () => { document.querySelector(".select2-container--open .select2-search__field").focus() }) A: This issue can be resolve by using the setTimeout() fucntion to delay the focus() execute time, we can achieve this by modifying a function in select2.js at line # 3321 container.on('open', function () { self.$search.attr('tabindex', 0); //self.$search.focus(); remove this line setTimeout(function () { self.$search.focus(); }, 10);//add this line }); A: This how i fix globally $(document).on('select2:open', (e) => { const selectId = e.target.id; $(".select2-search__field[aria-controls='select2-"+selectId+"-results']").each(function (key,value,){ value.focus(); }); }); A: For NPM or Laravel: As I rely on NPM package manager in my Laravel Application, I had to revert jQuery from 3.6 to 3.5.1 in package.json, then run npm install and npm run prod. Then the problem is fixed. "jquery": "^3.6.0" -> "jquery": "3.5.1", A: Just add a custom line of jQuery after you call the select2 function to force focus to the specific search field. Just replace '#target' with the ID of the search inputfield. $( "#target" ).focus(); A: $(document).on('select2:open', (e) => { var c = e.target.parentElement.children for (var i = 0; i < c.length; i++) { if (c[i].tagName === 'SPAN') { c = c[i].children break } } for (var i = 0; i < c.length; i++) { if (c[i].tagName === 'SPAN' && c[i].className === 'selection') { c = c[i].children break } } for (var i = 0; i < c.length; i++) { c = c[i] } $( ".select2-search__field[aria-controls='select2-" + c.getAttribute('aria-owns').replace('select2-', '').replace('-results', '') + "-results']", ).each(function (key, value) { value.focus() }) }) A: The method in this answer broke in iOS/iPadOS 15.4. A working alternative is listening for the click event on the parent directly and firing focus from there: document.querySelector("#your-select-field-id").parentElement.addEventListener("click", function(){ const searchField = document.querySelector('.select2-search__field'); if(searchField){ searchField.focus(); } }); A: Another way to do it is: // Find all existing Select2 instances $('.select2-hidden-accessible') // Attach event handler with some delay, waiting for the search field to be set up .on('select2:open', event => setTimeout( // Trigger focus using DOM API () => $(event.target).data('select2').dropdown.$search.get(0).focus(), 10)); NB: Trigger focus writing .get(0).focus() instead of .trigger('focus') (for using DOM API) because this wouldn't work with JQuery 3.6.0 A: I resolved for a web app like this $(document).on('select2:open', '.select2', function (e) { setTimeout(() => { const $elem = $(this).attr("id"); document.querySelector(`[aria-controls="select2-${$elem}-results"]`).focus(); }); }); A: I try all suggestions from google and stackoverflow and spend 4 hours for that. Only what work is downgrade jQuery from 3.6 to 3.5 "jquery": "^3.6.0" -> "jquery": "3.5.1" Just put this and save time https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js A: $(document).on('select2:open', () => { document.querySelector('.select2-container--open .select2-search__field').focus(); }); mungkin ini membantu
Set focus to search text field when we click on select 2 drop down
I am using select2.js Version: 3.4.3 with bootstrap I have one drop down. When I click on drop down i got list with search text fields. But I my cursor not focused on search text fields. <form:select path="yearAge" id="yearAgeId" cssClass="form-control search-select static-select"> <form:option value="">Years</form:option> <c:forEach var="i" begin="1" end="125" > <form:option value="${i}" label="${i}"></form:option> </c:forEach> </form:select> $(".search-select.static-select").select2({ placeholder: $(this).attr('placeholder'), allowClear: true }); When I click on dropdown cursor focus should set to search text field automatically . Thank you...!!!!!
[ "If jQuery 3.6.0 is causing this you can use this:\n $(document).on('select2:open', () => {\n document.querySelector('.select2-search__field').focus();\n });\n\n", "Try this\n$(document).on('select2:open', (e) => {\n const selectId = e.target.id\n\n $(\".select2-search__field[aria-controls='select2-\" + selectId + \"-results']\").each(function (\n key,\n value,\n ){\n value.focus();\n })\n})\n\n", "Tested and worked with jQuery 3.6.0:\n$(document).on(\"select2:open\", () => {\n document.querySelector(\".select2-container--open .select2-search__field\").focus()\n})\n\n", "This issue can be resolve by using the setTimeout() fucntion to delay the focus() execute time, we can achieve this by modifying a function in select2.js at line # 3321\ncontainer.on('open', function () {\n self.$search.attr('tabindex', 0);\n //self.$search.focus(); remove this line\n setTimeout(function () { self.$search.focus(); }, 10);//add this line\n\n});\n\n", "This how i fix globally\n$(document).on('select2:open', (e) => {\n const selectId = e.target.id;\n $(\".select2-search__field[aria-controls='select2-\"+selectId+\"-results']\").each(function (key,value,){\n value.focus();\n });\n });\n\n", "For NPM or Laravel: As I rely on NPM package manager in my Laravel Application, I had to revert jQuery from 3.6 to 3.5.1 in package.json, then run npm install and npm run prod. Then the problem is fixed.\n\"jquery\": \"^3.6.0\" -> \"jquery\": \"3.5.1\",\n\n", "Just add a custom line of jQuery after you call the select2 function to force focus to the specific search field. Just replace '#target' with the ID of the search inputfield.\n$( \"#target\" ).focus();\n\n", "$(document).on('select2:open', (e) => {\n var c = e.target.parentElement.children\n for (var i = 0; i < c.length; i++) {\n if (c[i].tagName === 'SPAN') {\n c = c[i].children\n break\n }\n }\n for (var i = 0; i < c.length; i++) {\n if (c[i].tagName === 'SPAN' && c[i].className === 'selection') {\n c = c[i].children\n break\n }\n }\n for (var i = 0; i < c.length; i++) {\n c = c[i]\n }\n\n $(\n \".select2-search__field[aria-controls='select2-\" +\n c.getAttribute('aria-owns').replace('select2-', '').replace('-results', '') +\n \"-results']\",\n ).each(function (key, value) {\n value.focus()\n })\n})\n\n", "The method in this answer broke in iOS/iPadOS 15.4.\nA working alternative is listening for the click event on the parent directly and firing focus from there:\ndocument.querySelector(\"#your-select-field-id\").parentElement.addEventListener(\"click\", function(){\n const searchField = document.querySelector('.select2-search__field');\n if(searchField){\n searchField.focus();\n }\n});\n\n", "Another way to do it is:\n// Find all existing Select2 instances\n$('.select2-hidden-accessible')\n // Attach event handler with some delay, waiting for the search field to be set up\n .on('select2:open', event => setTimeout(\n // Trigger focus using DOM API\n () => $(event.target).data('select2').dropdown.$search.get(0).focus(),\n 10));\n\nNB: Trigger focus writing .get(0).focus() instead of .trigger('focus') (for using DOM API) because this wouldn't work with JQuery 3.6.0\n", "I resolved for a web app like this\n $(document).on('select2:open', '.select2', function (e) {\n setTimeout(() => {\n const $elem = $(this).attr(\"id\");\n document.querySelector(`[aria-controls=\"select2-${$elem}-results\"]`).focus();\n });\n});\n\n", "I try all suggestions from google and stackoverflow and spend 4 hours for that.\nOnly what work is downgrade jQuery from 3.6 to 3.5\n\"jquery\": \"^3.6.0\" -> \"jquery\": \"3.5.1\"\n\nJust put this and save time\nhttps://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js\n\n", "$(document).on('select2:open', () => {\n document.querySelector('.select2-container--open .select2-search__field').focus();\n });\n\nmungkin ini membantu\n" ]
[ 59, 18, 9, 5, 4, 2, 1, 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "html", "jquery", "jquery_select2", "twitter_bootstrap" ]
stackoverflow_0025882999_html_jquery_jquery_select2_twitter_bootstrap.txt
Q: How to get value of editor in nextjs I am new in Reacjs and i am working with nextjs, Right now i am trying to save form data using axios (Api), I want to get value of editor, And i want to upload image using API Also, How can i do this ?Here is my current code const handleSubmit = (e: any) => { e.preventDefault(); const data = { first: e.target.name.value, last: e.target.cat_name.value, //Right now getting title,cat_name } //My axios api code here }; Here is editor and file code <div className="form-group"> <label>File upload</label> <input type="file" name="file" className="file-upload-default" /> <div className="input-group col-xs-12"> <input type="text" className="form-control file-upload-info" placeholder="Upload Image" /> <span className="input-group-append"> <button className="file-upload-browse btn btn-primary" type="button" > Upload </button> </span> </div> </div> <Editor onInit={(evt, editor) => editor} initialValue="<p>This is the initial content of the editor.</p>" init={{ height: 500, menubar: false, plugins: [ 'advlist autolink lists link image charmap print preview anchor', 'searchreplace visualblocks code fullscreen', 'insertdatetime media table paste code help wordcount' ], toolbar: 'undo redo | formatselect | ' + 'bold italic backcolor | alignleft aligncenter ' + 'alignright alignjustify | bullist numlist outdent indent | ' + 'removeformat | help', content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:14px }' }} /> A: To get the value of the editor, you can use the getContent method provided by the TinyMCE editor. In your code, you can create a reference to the editor using the onInit callback, and then use this reference to get the editor's content. Here is an example of how you can do this: const handleSubmit = (e: any) => { e.preventDefault(); // create a reference to the editor let editor: any = null; // get the editor's content const content = editor.getContent(); const data = { first: e.target.name.value, last: e.target.cat_name.value, content: content, // add the content to the data object } // send the data to the server using axios // My axios api code here }; <Editor onInit={(evt, ed) => editor = ed} // set the editor reference initialValue="<p>This is the initial content of the editor.</p>" init={{ height: 500, menubar: false, plugins: [ 'advlist autolink lists link image charmap print preview anchor', 'searchreplace visualblocks code fullscreen', 'insertdatetime media table paste code help wordcount' ], toolbar: 'undo redo | formatselect | ' + 'bold italic backcolor | alignleft aligncenter ' + 'alignright alignjustify | bullist numlist outdent indent | ' + 'removeformat | help', content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:14px }' }} /> To upload an image using axios, you can use the FormData object to create a form with the image file and send it to the server using a POST request. The server should then be able to handle the form data and save the image file. Here is an example of how you can do this: const handleSubmit = (e: any) => { e.preventDefault(); // create a FormData object const formData = new FormData(); // add the file to the form data formData.append("file", e.target.file.files[0]); // send the form data to the server using axios axios.post("/upload", formData).then(response => { // handle the server response here }); };
How to get value of editor in nextjs
I am new in Reacjs and i am working with nextjs, Right now i am trying to save form data using axios (Api), I want to get value of editor, And i want to upload image using API Also, How can i do this ?Here is my current code const handleSubmit = (e: any) => { e.preventDefault(); const data = { first: e.target.name.value, last: e.target.cat_name.value, //Right now getting title,cat_name } //My axios api code here }; Here is editor and file code <div className="form-group"> <label>File upload</label> <input type="file" name="file" className="file-upload-default" /> <div className="input-group col-xs-12"> <input type="text" className="form-control file-upload-info" placeholder="Upload Image" /> <span className="input-group-append"> <button className="file-upload-browse btn btn-primary" type="button" > Upload </button> </span> </div> </div> <Editor onInit={(evt, editor) => editor} initialValue="<p>This is the initial content of the editor.</p>" init={{ height: 500, menubar: false, plugins: [ 'advlist autolink lists link image charmap print preview anchor', 'searchreplace visualblocks code fullscreen', 'insertdatetime media table paste code help wordcount' ], toolbar: 'undo redo | formatselect | ' + 'bold italic backcolor | alignleft aligncenter ' + 'alignright alignjustify | bullist numlist outdent indent | ' + 'removeformat | help', content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:14px }' }} />
[ "To get the value of the editor, you can use the getContent method provided by the TinyMCE editor. In your code, you can create a reference to the editor using the onInit callback, and then use this reference to get the editor's content.\nHere is an example of how you can do this:\n const handleSubmit = (e: any) => {\n e.preventDefault();\n\n // create a reference to the editor\n let editor: any = null;\n\n // get the editor's content\n const content = editor.getContent();\n\n const data = {\n first: e.target.name.value,\n last: e.target.cat_name.value,\n content: content, // add the content to the data object\n }\n\n // send the data to the server using axios\n // My axios api code here\n};\n\n<Editor\n onInit={(evt, ed) => editor = ed} // set the editor reference\n initialValue=\"<p>This is the initial content of the editor.</p>\"\n init={{\n height: 500,\n menubar: false,\n plugins: [\n 'advlist autolink lists link image charmap print preview anchor',\n 'searchreplace visualblocks code fullscreen',\n 'insertdatetime media table paste code help wordcount'\n ],\n toolbar: 'undo redo | formatselect | ' +\n 'bold italic backcolor | alignleft aligncenter ' +\n 'alignright alignjustify | bullist numlist outdent indent | ' +\n 'removeformat | help',\n content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:14px }'\n }}\n/>\n\nTo upload an image using axios, you can use the FormData object to create a form with the image file and send it to the server using a POST request. The server should then be able to handle the form data and save the image file.\nHere is an example of how you can do this:\nconst handleSubmit = (e: any) => {\n e.preventDefault();\n\n // create a FormData object\n const formData = new FormData();\n\n // add the file to the form data\n formData.append(\"file\", e.target.file.files[0]);\n\n // send the form data to the server using axios\n axios.post(\"/upload\", formData).then(response => {\n // handle the server response here\n });\n};\n\n" ]
[ 0 ]
[]
[]
[ "javascript", "next.js", "php", "reactjs" ]
stackoverflow_0074663321_javascript_next.js_php_reactjs.txt
Q: I don't understand why my class variables are undefined and can't be accessed I am trying to create a poker game in python using classes. the first thing i am trying to do is to create a deck. this is my code : class Poker: rank = ['A','2','3','4','5','6','7','8','9','T','J','Q','K'] suit = ["D", "C", "S", "H"] original_deck = [(i + j) for i in rank for j in suit] def __init__(self): pass Here, I want the deck to be a class variable since it will never change in my program. Since it'll stay constant, I don't want to include it in my init function. However, when I try to do this, I get this error : Traceback (most recent call last): File "C:\Users\14384\PycharmProjects\Assignment 4\scrap.py", line 2, in <module> class Poker: File "C:\Users\14384\PycharmProjects\Assignment 4\scrap.py", line 5, in Poker original_deck = [(i + j) for i in rank for j in suit] File "C:\Users\14384\PycharmProjects\Assignment 4\scrap.py", line 5, in <listcomp> original_deck = [(i + j) for i in rank for j in suit] NameError: name 'suit' is not defined. Did you mean: 'quit'? When I include my original deck in my init function, it magically works, which I don't understand. Why can't I do this ? A: Use self to reference class attributes. In Python, class attributes should be accessed using the self keyword. This makes the code more readable and helps avoid naming conflicts. You can modify your code to use self to reference the rank and suit attributes like this: class Poker: rank = ['A','2','3','4','5','6','7','8','9','T','J','Q','K'] suit = ["D", "C", "S", "H"] original_deck = [(i + j) for I in self.rank for j in self.suit] def __init__(self): pass Use a list comprehension to create the deck of cards. Your code uses a for loop to create the deck of cards, but this can be done more efficiently using a list comprehension. You can modify your code to use a list comprehension like this: class Poker: rank = ['A','2','3','4','5','6','7','8','9','T','J','Q','K'] suit = ["D", "C", "S", "H"] original_deck = [(i + j) for I in self.rank for j in self.suit] def __init__(self): pass def create_deck(self): self.deck = [card for card in self.original_deck] Use random.shuffle() to shuffle the deck of cards. In Python, the random.shuffle() function can be used to shuffle a list of items in place. This is more efficient than creating a new list of shuffled items and is also more convenient because it modifies the existing list. You can use random.shuffle() to shuffle the deck of cards like this: import random class Poker: rank = ['A','2','3','4','5','6','7','8','9','T','J','Q','K'] suit = ["D", "C", "S", "H"] original_deck = [(i + j) for I in self.rank for j in self.suit] def __init__(self): pass def create_deck(self): self.deck = [card for card in self.original_deck] random.shuffle(self.deck)
I don't understand why my class variables are undefined and can't be accessed
I am trying to create a poker game in python using classes. the first thing i am trying to do is to create a deck. this is my code : class Poker: rank = ['A','2','3','4','5','6','7','8','9','T','J','Q','K'] suit = ["D", "C", "S", "H"] original_deck = [(i + j) for i in rank for j in suit] def __init__(self): pass Here, I want the deck to be a class variable since it will never change in my program. Since it'll stay constant, I don't want to include it in my init function. However, when I try to do this, I get this error : Traceback (most recent call last): File "C:\Users\14384\PycharmProjects\Assignment 4\scrap.py", line 2, in <module> class Poker: File "C:\Users\14384\PycharmProjects\Assignment 4\scrap.py", line 5, in Poker original_deck = [(i + j) for i in rank for j in suit] File "C:\Users\14384\PycharmProjects\Assignment 4\scrap.py", line 5, in <listcomp> original_deck = [(i + j) for i in rank for j in suit] NameError: name 'suit' is not defined. Did you mean: 'quit'? When I include my original deck in my init function, it magically works, which I don't understand. Why can't I do this ?
[ "Use self to reference class attributes. In Python, class attributes should be accessed using the self keyword. This makes the code more readable and helps avoid naming conflicts. You can modify your code to use self to reference the rank and suit attributes like this:\nclass Poker:\n rank = ['A','2','3','4','5','6','7','8','9','T','J','Q','K']\n suit = [\"D\", \"C\", \"S\", \"H\"]\n original_deck = [(i + j) for I in self.rank for j in self.suit]\n def __init__(self):\n pass\n\n\nUse a list comprehension to create the deck of cards. Your code uses a for loop to create the deck of cards, but this can be done more efficiently using a list comprehension. You can modify your code to use a list comprehension like this:\nclass Poker:\n rank = ['A','2','3','4','5','6','7','8','9','T','J','Q','K']\n suit = [\"D\", \"C\", \"S\", \"H\"]\n original_deck = [(i + j) for I in self.rank for j in self.suit]\n def __init__(self):\n pass\n\n def create_deck(self):\n self.deck = [card for card in self.original_deck]\n\n\nUse random.shuffle() to shuffle the deck of cards. In Python, the random.shuffle() function can be used to shuffle a list of items in place. This is more efficient than creating a new list of shuffled items and is also more convenient because it modifies the existing list. You can use random.shuffle() to shuffle the deck of cards like this:\nimport random\n\nclass Poker:\n rank = ['A','2','3','4','5','6','7','8','9','T','J','Q','K']\n suit = [\"D\", \"C\", \"S\", \"H\"]\n original_deck = [(i + j) for I in self.rank for j in self.suit]\n def __init__(self):\n pass\n\n def create_deck(self):\n self.deck = [card for card in self.original_deck]\n random.shuffle(self.deck)\n\n\n" ]
[ 1 ]
[]
[]
[ "class", "oop", "python", "python_3.x", "scope" ]
stackoverflow_0074663772_class_oop_python_python_3.x_scope.txt
Q: How can I use @SuperBuilder and @Data to be able to access a subclasses properties when it is a member of another class? Sorry, my title might be a bit confusing but I am already pretty confused my self and I am not sure how best to word it with out confusing more or using incorrect terms/concepts. Anyways, here is my situation: public class Main { public static void main(String [] args) { City city = getCity(); city.getStation().setPoliceStationName("SFPD") //ERROR? city.setPoliceStationName("SFPD"); //ERROR? } public static City getCity(){ return City .builder() .station(getPoliceStation()) .cityName("CityName") .build(); } public static PoliceStation getPoliceStation(){ return PoliceStation .builder() .policeStationName("NYPD") .build(); } } I have another set of classes here: @Data @SuperBuilder public class City { private String cityName; private Station station; } @Data @SuperBuilder public abstract class Station { private String stationName; } @EqualsAndHashCode(callSuper = true) @Data @SuperBuilder public class PoliceStation extends Station{ private String policeStationName; } I would like to try and be able to modify the name of the police station, but it seems that the type returned is of type Station and not PoliceStation. How can I go about achieving this with a setup similar to this (using lombok)? Thanks A: To be able to access the policeStationName property of the PoliceStation class, you need to make sure that you are calling the correct methods on the correct objects. In your code, you are trying to call the setPoliceStationName method on the station property of the City class, but this property is of type Station and does not have a setPoliceStationName method. To fix this, you can either call the setPoliceStationName method on the PoliceStation object directly, or you can cast the Station object to a PoliceStation object and then call the setPoliceStationName method on the casted object. Here is an example of how you could do this: public class Main { public static void main(String [] args) { City city = getCity(); // Call the setPoliceStationName method on the PoliceStation object directly PoliceStation policeStation = city.getStation(); policeStation.setPoliceStationName("SFPD"); // Or cast the Station object to a PoliceStation object and then call the setPoliceStationName method Station station = city.getStation(); if (station instanceof PoliceStation) { PoliceStation castedStation = (PoliceStation) station; castedStation.setPoliceStationName("SFPD"); } } public static City getCity(){ return City.builder() .station(getPoliceStation()) .cityName("CityName") .build(); } public static PoliceStation getPoliceStation(){ return PoliceStation.builder() .policeStationName("NYPD") .build(); } } In this code, we first call the getStation method on the City object to get the Station object, and then either call the setPoliceStationName method on the PoliceStation object directly, or we cast the Station object to a PoliceStation object and then call the setPoliceStationName method on the casted object. public class Main { public static void main(String [] args) { City city = getCity(); // Use the instanceof operator to check the type of the object returned by getStation() Station station = city.getStation(); if (station instanceof PoliceStation) { // Cast the Station object to a PoliceStation object PoliceStation policeStation = (PoliceStation) station; policeStation.setPoliceStationName("SFPD"); } } public static City getCity(){ return City.builder() .station(getPoliceStation()) .cityName("CityName") .build(); } public static PoliceStation getPoliceStation(){ return PoliceStation.builder() .policeStationName("NYPD") .build(); } } In this code, we use the instanceof operator to check the type of the object returned by getStation() and then cast it to a PoliceStation object if necessary before calling the setPoliceStationName method. This allows you to avoid a typecast error in IntelliJ.
How can I use @SuperBuilder and @Data to be able to access a subclasses properties when it is a member of another class?
Sorry, my title might be a bit confusing but I am already pretty confused my self and I am not sure how best to word it with out confusing more or using incorrect terms/concepts. Anyways, here is my situation: public class Main { public static void main(String [] args) { City city = getCity(); city.getStation().setPoliceStationName("SFPD") //ERROR? city.setPoliceStationName("SFPD"); //ERROR? } public static City getCity(){ return City .builder() .station(getPoliceStation()) .cityName("CityName") .build(); } public static PoliceStation getPoliceStation(){ return PoliceStation .builder() .policeStationName("NYPD") .build(); } } I have another set of classes here: @Data @SuperBuilder public class City { private String cityName; private Station station; } @Data @SuperBuilder public abstract class Station { private String stationName; } @EqualsAndHashCode(callSuper = true) @Data @SuperBuilder public class PoliceStation extends Station{ private String policeStationName; } I would like to try and be able to modify the name of the police station, but it seems that the type returned is of type Station and not PoliceStation. How can I go about achieving this with a setup similar to this (using lombok)? Thanks
[ "To be able to access the policeStationName property of the PoliceStation class, you need to make sure that you are calling the correct methods on the correct objects. In your code, you are trying to call the setPoliceStationName method on the station property of the City class, but this property is of type Station and does not have a setPoliceStationName method.\nTo fix this, you can either call the setPoliceStationName method on the PoliceStation object directly, or you can cast the Station object to a PoliceStation object and then call the setPoliceStationName method on the casted object. Here is an example of how you could do this:\npublic class Main {\n public static void main(String [] args) {\n City city = getCity();\n\n // Call the setPoliceStationName method on the PoliceStation object directly\n PoliceStation policeStation = city.getStation();\n policeStation.setPoliceStationName(\"SFPD\");\n\n // Or cast the Station object to a PoliceStation object and then call the setPoliceStationName method\n Station station = city.getStation();\n if (station instanceof PoliceStation) {\n PoliceStation castedStation = (PoliceStation) station;\n castedStation.setPoliceStationName(\"SFPD\");\n }\n }\n\n public static City getCity(){\n return City.builder()\n .station(getPoliceStation())\n .cityName(\"CityName\")\n .build();\n }\n\n public static PoliceStation getPoliceStation(){\n return PoliceStation.builder()\n .policeStationName(\"NYPD\")\n .build();\n }\n}\n\nIn this code, we first call the getStation method on the City object to get the Station object, and then either call the setPoliceStationName method on the PoliceStation object directly, or we cast the Station object to a PoliceStation object and then call the setPoliceStationName method on the casted object.\npublic class Main {\n public static void main(String [] args) {\n City city = getCity();\n\n // Use the instanceof operator to check the type of the object returned by getStation()\n Station station = city.getStation();\n if (station instanceof PoliceStation) {\n // Cast the Station object to a PoliceStation object\n PoliceStation policeStation = (PoliceStation) station;\n policeStation.setPoliceStationName(\"SFPD\");\n }\n }\n\n public static City getCity(){\n return City.builder()\n .station(getPoliceStation())\n .cityName(\"CityName\")\n .build();\n }\n\n public static PoliceStation getPoliceStation(){\n return PoliceStation.builder()\n .policeStationName(\"NYPD\")\n .build();\n }\n}\n\nIn this code, we use the instanceof operator to check the type of the object returned by getStation() and then cast it to a PoliceStation object if necessary before calling the setPoliceStationName method. This allows you to avoid a typecast error in IntelliJ.\n" ]
[ 1 ]
[]
[]
[ "annotations", "inheritance", "java", "lombok" ]
stackoverflow_0074663687_annotations_inheritance_java_lombok.txt
Q: Make chromatic snapshot docs tab in storybook What i'm looking to achieve I am looking at options for reducing the number of stories we snapshot and test in Chromatic (currently nearing 400). We use storybook for our design system and also for visual testing with Chromatic. Currently our stories are roughly structured as a story for each set of states / major variation of a component. For example our button has: Sizes - sm, m, l, responsive Colours - primary, secondary, danger, etc Layouts - left-icon, right-icon Playground - a story containing single button where you can interact with all the various inputs. Playground stories are already excluded from Chromatic. I was thinking of adding a "visual test" story to each component which would have every variation of the button on a single canvas and then only include the "visual test" stories in the chromatic tests. In the button example this would reduce button snapshots from 3 to 1, and we have other components with way more variations than this. The best solution I found for this is to create a doc page, i really liked the option of using MDX to compose a page that includes multiple stories <Story id="some-component--some-name" /> <Story id="some-component--some-other-name" /> MDX Docs The Problem So far I cannot find anyway to make chromatic take a snapshot of a doc or pure doc page. I have tried making docs the default view in my storybook, and even hiding the canvas tab in my storybook altogether, but it seems Chromatic must parse and render the stories with their own config. The Question Is there a way to force chromatic to take snapshots of doc pages, or even better of "pure documentation" MDX pages (as described in the MDX docs) Alternatively if anyone has any other suggestions about creating a story composed of other stories, that could also be a solution to my problem. Currently the only alternative I see is to duplicate stories, which isn't ideal. A: You can disable all snapshots at ./storybook/preview.js then you enable it for single stories. I just don't know how to achieve that using MDX (which is my case as well) Update: I guess the following does the trick for MDX (if you're disabling all from preview.js then pass { disableSnapshot: false }) <Story name="StoryName" args={{ chromatic: { disableSnapshot: true } }}>...</Story> `` Ref: https://www.chromatic.com/docs/ignoring-elements#ignore-stories A: In the end the solution to this was an add-on called Variants. You can ignore all stories from Chromatic by default and only take snapshots of stories that use the Varitants add-on to display every variant on a single page. storybook-addon-variants
Make chromatic snapshot docs tab in storybook
What i'm looking to achieve I am looking at options for reducing the number of stories we snapshot and test in Chromatic (currently nearing 400). We use storybook for our design system and also for visual testing with Chromatic. Currently our stories are roughly structured as a story for each set of states / major variation of a component. For example our button has: Sizes - sm, m, l, responsive Colours - primary, secondary, danger, etc Layouts - left-icon, right-icon Playground - a story containing single button where you can interact with all the various inputs. Playground stories are already excluded from Chromatic. I was thinking of adding a "visual test" story to each component which would have every variation of the button on a single canvas and then only include the "visual test" stories in the chromatic tests. In the button example this would reduce button snapshots from 3 to 1, and we have other components with way more variations than this. The best solution I found for this is to create a doc page, i really liked the option of using MDX to compose a page that includes multiple stories <Story id="some-component--some-name" /> <Story id="some-component--some-other-name" /> MDX Docs The Problem So far I cannot find anyway to make chromatic take a snapshot of a doc or pure doc page. I have tried making docs the default view in my storybook, and even hiding the canvas tab in my storybook altogether, but it seems Chromatic must parse and render the stories with their own config. The Question Is there a way to force chromatic to take snapshots of doc pages, or even better of "pure documentation" MDX pages (as described in the MDX docs) Alternatively if anyone has any other suggestions about creating a story composed of other stories, that could also be a solution to my problem. Currently the only alternative I see is to duplicate stories, which isn't ideal.
[ "You can disable all snapshots at ./storybook/preview.js then you enable it for single stories. I just don't know how to achieve that using MDX (which is my case as well)\nUpdate: I guess the following does the trick for MDX (if you're disabling all from preview.js then pass { disableSnapshot: false })\n<Story name=\"StoryName\" args={{\n chromatic: { disableSnapshot: true }\n}}>...</Story>\n``\n\nRef: https://www.chromatic.com/docs/ignoring-elements#ignore-stories\n\n", "In the end the solution to this was an add-on called Variants. You can ignore all stories from Chromatic by default and only take snapshots of stories that use the Varitants add-on to display every variant on a single page.\nstorybook-addon-variants\n" ]
[ 1, 0 ]
[]
[]
[ "angular_storybook", "chromatic", "mdxjs", "storybook", "visual_testing" ]
stackoverflow_0074008685_angular_storybook_chromatic_mdxjs_storybook_visual_testing.txt
Q: Does mysqldump -–single-transaction guarantee data integrity? MySQL documentation says --single-transaction This option sets the transaction isolation mode to REPEATABLE READ and sends a START TRANSACTION SQL statement to the server before dumping data. It is useful only with transactional tables such as InnoDB, because then it dumps the consistent state of the database at the time when START TRANSACTION was issued without blocking any applications. My doubt is that, it says the isolation is set as REPEATABLE READ, but this may not guarantee a consistent database state. For example, if we have a table Employee, and a table Hobby, and a table EmployeeHobby which stores employee id and hobby id. When we use –single-transaction (i.e., REPEATABLE READ) to dump the database. Let's denote the transaction as A. In A we first dump table Employee, then some concurrent transaction B insert a new employee into Employee, and B adds related hobby into Hobby and EmployeeHobby (this does not violate REPEATABLE_READ since A never reads Employee afterwards), and then A dump table EmployeeHobby and Hobby. Eventually, the dumped data by A is not consistent, since EmployeeHobby contains the id of a employee that does not exist in Employee. The dumped data is broken, isn't it? What the doc says it dumps the consistent state of the database at the time when START TRANSACTION was issued seems not to be achievable by setting it to be a REPEATABLE READ transaction. A: Yes, using the --single-transaction option with mysqldump guarantees data integrity by creating a consistent snapshot of the database at the time the backup begins. This option causes mysqldump to start a new transaction and perform a consistent snapshot of the database by freezing all non-transactional tables and locking all transactional tables. This ensures that the resulting dump file contains a consistent snapshot of the database, even if the database is being written to during the dump. Here is an example of using mysqldump with the --single-transaction option: mysqldump --single-transaction -u [username] -p [database_name] > [dump_file.sql] In this example, mysqldump connects to the database using the specified username and prompts for the password. It then creates a dump file containing a consistent snapshot of the database. The --single-transaction option causes mysqldump to start a new transaction and create a snapshot of the database by freezing all non-transactional tables and locking all transactional tables. This ensures that the resulting dump file contains a consistent snapshot of the database, even if the database is being written to during the dump. A: REPEATABLE READ ensures that the transaction does not read any changes committed by other sessions after the transaction's snapshot is established. https://dev.mysql.com/doc/refman/8.0/en/innodb-consistent-read.html If the transaction isolation level is REPEATABLE READ (the default level), all consistent reads within the same transaction read the snapshot established by the first such read in that transaction. This includes any reads against other tables. So once mysqldump's snapshot is established, it immediately applies to all InnoDB tables on that MySQL instance, even tables that it hasn't read yet.
Does mysqldump -–single-transaction guarantee data integrity?
MySQL documentation says --single-transaction This option sets the transaction isolation mode to REPEATABLE READ and sends a START TRANSACTION SQL statement to the server before dumping data. It is useful only with transactional tables such as InnoDB, because then it dumps the consistent state of the database at the time when START TRANSACTION was issued without blocking any applications. My doubt is that, it says the isolation is set as REPEATABLE READ, but this may not guarantee a consistent database state. For example, if we have a table Employee, and a table Hobby, and a table EmployeeHobby which stores employee id and hobby id. When we use –single-transaction (i.e., REPEATABLE READ) to dump the database. Let's denote the transaction as A. In A we first dump table Employee, then some concurrent transaction B insert a new employee into Employee, and B adds related hobby into Hobby and EmployeeHobby (this does not violate REPEATABLE_READ since A never reads Employee afterwards), and then A dump table EmployeeHobby and Hobby. Eventually, the dumped data by A is not consistent, since EmployeeHobby contains the id of a employee that does not exist in Employee. The dumped data is broken, isn't it? What the doc says it dumps the consistent state of the database at the time when START TRANSACTION was issued seems not to be achievable by setting it to be a REPEATABLE READ transaction.
[ "Yes, using the --single-transaction option with mysqldump guarantees data integrity by creating a consistent snapshot of the database at the time the backup begins. This option causes mysqldump to start a new transaction and perform a consistent snapshot of the database by freezing all non-transactional tables and locking all transactional tables. This ensures that the resulting dump file contains a consistent snapshot of the database, even if the database is being written to during the dump.\nHere is an example of using mysqldump with the --single-transaction option:\nmysqldump --single-transaction -u [username] -p [database_name] > [dump_file.sql]\n\nIn this example, mysqldump connects to the database using the specified username and prompts for the password. It then creates a dump file containing a consistent snapshot of the database. The --single-transaction option causes mysqldump to start a new transaction and create a snapshot of the database by freezing all non-transactional tables and locking all transactional tables. This ensures that the resulting dump file contains a consistent snapshot of the database, even if the database is being written to during the dump.\n", "REPEATABLE READ ensures that the transaction does not read any changes committed by other sessions after the transaction's snapshot is established.\nhttps://dev.mysql.com/doc/refman/8.0/en/innodb-consistent-read.html\n\nIf the transaction isolation level is REPEATABLE READ (the default level), all consistent reads within the same transaction read the snapshot established by the first such read in that transaction.\n\nThis includes any reads against other tables. So once mysqldump's snapshot is established, it immediately applies to all InnoDB tables on that MySQL instance, even tables that it hasn't read yet.\n" ]
[ 0, 0 ]
[]
[]
[ "isolation_level", "mysql" ]
stackoverflow_0074663674_isolation_level_mysql.txt
Q: neovim gutter displaying unknown tag ">>" I'm using nvim with some presets that I copied from other's vimrc. I cannot understand why the gutter (aka SignColumn) on the left side shows ">>" for some lines. Normally the gutter is used by GitGutter for its "+", "-", and "~". Whenever I'm editing git files, the gutter works correctly, but when I'm editing normal files the ">>" shows up. What's going on? Google search didn't find any reference to ">>" in the vim/nvim gutter (aka SignColumn). A: Stubborn Googling yielded an obscure link to an old thread with a gold nugget inside. :sign list Listed the plug-in that defined the ">>" symbol, Coc (Code Completion Engine). More specifically, generated by CocError, CocInfo, and CocHint. Further inspection shows that cSpell "Unknown word" message was the culprit. :CocDisable Eliminated those annoying ">>" signs. I'd think Coc would be smart enough to know that I wasn't writing any code. Edit: Perusing the :help sign-support as suggested by romainl also revealed the :sign list command.
neovim gutter displaying unknown tag ">>"
I'm using nvim with some presets that I copied from other's vimrc. I cannot understand why the gutter (aka SignColumn) on the left side shows ">>" for some lines. Normally the gutter is used by GitGutter for its "+", "-", and "~". Whenever I'm editing git files, the gutter works correctly, but when I'm editing normal files the ">>" shows up. What's going on? Google search didn't find any reference to ">>" in the vim/nvim gutter (aka SignColumn).
[ "Stubborn Googling yielded an obscure link to an old thread with a gold nugget inside.\n:sign list\n\nListed the plug-in that defined the \">>\" symbol, Coc (Code Completion Engine). More specifically, generated by CocError, CocInfo, and CocHint. Further inspection shows that cSpell \"Unknown word\" message was the culprit.\n:CocDisable\n\nEliminated those annoying \">>\" signs. I'd think Coc would be smart enough to know that I wasn't writing any code.\nEdit: Perusing the :help sign-support as suggested by romainl also revealed the :sign list command.\n" ]
[ 0 ]
[]
[]
[ "neovim" ]
stackoverflow_0074658980_neovim.txt
Q: How do I create a function that will end the program? I have difficulties creating a counter (which is errorCount) for my while loop statement. I want my counter to function so that if the user answered a question incorrectly 5 times the program will terminate. furthermore, I have 3 questions for the user and I want to accumulate all the errorCounts so that if it hit 5 the program will terminate. for example: if the user answers question 1 incorrectly twice then the errorCount will be two. If the user answers question 2 incorrectly three times then the program will be terminated. However, the program is allowing the user to make 5 mistakes for every problem. # Level 5: print("You have the jewel in your possession, and defeated Joker at his own game") print("You now hold the precious jewel in your hands, but it's not over, you must leave the maze!") print("*You must now choose 'Right', 'Left', or 'Straight' as you exit the maze. Keep trying until you find your path.*") # put an error limit # space everything out to make it look more neat # Make sure you can fail the level **errorCount = 0** position = 0 while True: answer1 = input("Choose either Right, Left, Straight: ") try: if answer1.lower() == "right": print("You have chosen the correct path, now you proceed to the next step!") print() break * if errorCount == 5: print("you made too many mistakes and got captured, you have to restart")* elif answer1.lower() == "left": print("You see a boulder blocking your path which forces you to go back.") errorCount = 1 + errorCount elif answer1.lower() == "straight": print("On your way to the next stage you are exposed to a toxic gas that forces you to go back .") errorCount = 1 + errorCount else: print("Wrong input. Please try again..") errorCount = 1 + errorCount except Exception: print("Wrong input. Please try again..") # if errors >= 5: while True: answer1 = input("Choose either Right, Left, Straight: ") if errorCount == 5: print("you made too many mistakes and got captured, you have to restart") try: if answer1.lower() == "straight": print("You have chosen the correct path, now you proceed to the next step!") break elif answer1.lower() == "left": print("You chose the wrong path, go back") errorCount = 1 + errorCount elif answer1.lower() == "right": print("You chose the wrong path, go back") errorCount = 1 + errorCount else: print("Wrong input. Please try again..") errorCount = 1 + errorCount except Exception: print("Wrong input. Please try again..") print("You are now on the third stage, you notice a screen that is asking you a riddle") while True: riddle1 = input("What gets wet when drying? ") if errorCount == 5: print("you made too many mistakes and got captured, you have to restart") try: if riddle1.lower() == "towel": print("You have chosen the correct answer") print("The giant stone blocking the entrance of the maze opens, and the outside lights shine through..") break else: print("Incorrect! Try again..") errorCount = 1 + errorCount print("Heres a hint: You use it after taking a shower...") except Exception: print("Incorrect! Try again..") errorCount = 1 + errorCount I do not know how to fix this issue A: You have overly complicated the code. questions = ["You have the jewel in your possession, and defeated Joker at his own game", "You now hold the precious jewel in your hands, but it's not over, you must leave the maze!", "*You must now choose 'Right', 'Left', or 'Straight' as you exit the maze. Keep trying until you find your path.*"] error_count = 0 for id, query in enumerate(questions): if id == 0: # call method for query 1 # write your while error_count < 5 loop inside the method # return error_count to check. pass elif id == 1: pass elif id == 2: pass if error_count > 5: break You can also raise a User warning if you use try/except. except UserWarning: if error_count > 5: print("you made too many mistakes and got captured, you have to restart") break A: You just forgot to put the errorCount conditional in the last loop, also it is better that you put this before the user input so that it doesn't ask the question 6 times instead of the 5 you want. Finally, it is necessary to add a break at the end of the conditional so that there is not an infinite loop # Level 5: print("You have the jewel in your possession, and defeated Joker at his own game") print("You now hold the precious jewel in your hands, but it's not over, you must leave the maze!") print("*You must now choose 'Right', 'Left', or 'Straight' as you exit the maze. Keep trying until you find your path.*") # put an error limit # space everything out to make it look more neat # Make sure you can fail the level errorCount = 0 position = 0 while True: if errorCount == 5: print("you made too many mistakes and got captured, you have to restart") break answer1 = input("Choose either Right, Left, Straight: ") try: if answer1.lower() == "right": print("You have chosen the correct path, now you proceed to the next step!") print() break elif answer1.lower() == "left": print("You see a boulder blocking your path which forces you to go back.") errorCount = 1 + errorCount elif answer1.lower() == "straight": print("On your way to the next stage you are exposed to a toxic gas that forces you to go back .") errorCount = 1 + errorCount else: print("Wrong input. Please try again..") errorCount = 1 + errorCount except Exception: print("Wrong input. Please try again..") # if errors >= 5: while True: if errorCount == 5: print("you made too many mistakes and got captured, you have to restart") break answer1 = input("Choose either Right, Left, Straight: ") try: if answer1.lower() == "straight": print("You have chosen the correct path, now you proceed to the next step!") break elif answer1.lower() == "left": print("You chose the wrong path, go back") errorCount = 1 + errorCount elif answer1.lower() == "right": print("You chose the wrong path, go back") errorCount = 1 + errorCount else: print("Wrong input. Please try again..") errorCount = 1 + errorCount except Exception: print("Wrong input. Please try again..") print("You are now on the third stage, you notice a screen that is asking you a riddle") while True: if errorCount == 5: print("you made too many mistakes and got captured, you have to restart") break riddle1 = input("What gets wet when drying? ") if errorCount == 5: print("you made too many mistakes and got captured, you have to restart") try: if riddle1.lower() == "towel": print("You have chosen the correct answer") print("The giant stone blocking the entrance of the maze opens, and the outside lights shine through..") break else: print("Incorrect! Try again..") errorCount = 1 + errorCount print("Heres a hint: You use it after taking a shower...") except Exception: print("Incorrect! Try again..") errorCount = 1 + errorCount I recommend that instead of using: errorcount = 1 + errorcount It is better to use: errorcount += 1
How do I create a function that will end the program?
I have difficulties creating a counter (which is errorCount) for my while loop statement. I want my counter to function so that if the user answered a question incorrectly 5 times the program will terminate. furthermore, I have 3 questions for the user and I want to accumulate all the errorCounts so that if it hit 5 the program will terminate. for example: if the user answers question 1 incorrectly twice then the errorCount will be two. If the user answers question 2 incorrectly three times then the program will be terminated. However, the program is allowing the user to make 5 mistakes for every problem. # Level 5: print("You have the jewel in your possession, and defeated Joker at his own game") print("You now hold the precious jewel in your hands, but it's not over, you must leave the maze!") print("*You must now choose 'Right', 'Left', or 'Straight' as you exit the maze. Keep trying until you find your path.*") # put an error limit # space everything out to make it look more neat # Make sure you can fail the level **errorCount = 0** position = 0 while True: answer1 = input("Choose either Right, Left, Straight: ") try: if answer1.lower() == "right": print("You have chosen the correct path, now you proceed to the next step!") print() break * if errorCount == 5: print("you made too many mistakes and got captured, you have to restart")* elif answer1.lower() == "left": print("You see a boulder blocking your path which forces you to go back.") errorCount = 1 + errorCount elif answer1.lower() == "straight": print("On your way to the next stage you are exposed to a toxic gas that forces you to go back .") errorCount = 1 + errorCount else: print("Wrong input. Please try again..") errorCount = 1 + errorCount except Exception: print("Wrong input. Please try again..") # if errors >= 5: while True: answer1 = input("Choose either Right, Left, Straight: ") if errorCount == 5: print("you made too many mistakes and got captured, you have to restart") try: if answer1.lower() == "straight": print("You have chosen the correct path, now you proceed to the next step!") break elif answer1.lower() == "left": print("You chose the wrong path, go back") errorCount = 1 + errorCount elif answer1.lower() == "right": print("You chose the wrong path, go back") errorCount = 1 + errorCount else: print("Wrong input. Please try again..") errorCount = 1 + errorCount except Exception: print("Wrong input. Please try again..") print("You are now on the third stage, you notice a screen that is asking you a riddle") while True: riddle1 = input("What gets wet when drying? ") if errorCount == 5: print("you made too many mistakes and got captured, you have to restart") try: if riddle1.lower() == "towel": print("You have chosen the correct answer") print("The giant stone blocking the entrance of the maze opens, and the outside lights shine through..") break else: print("Incorrect! Try again..") errorCount = 1 + errorCount print("Heres a hint: You use it after taking a shower...") except Exception: print("Incorrect! Try again..") errorCount = 1 + errorCount I do not know how to fix this issue
[ "You have overly complicated the code.\nquestions = [\"You have the jewel in your possession, and defeated Joker at his own game\",\n\"You now hold the precious jewel in your hands, but it's not over, you must leave the maze!\",\n\"*You must now choose 'Right', 'Left', or 'Straight' as you exit the maze. Keep trying until you find your path.*\"]\n\nerror_count = 0\n\nfor id, query in enumerate(questions):\n\n if id == 0:\n # call method for query 1\n # write your while error_count < 5 loop inside the method\n # return error_count to check.\n pass\n elif id == 1:\n pass\n elif id == 2:\n pass\n \n if error_count > 5:\n break\n\nYou can also raise a User warning if you use try/except.\nexcept UserWarning:\n if error_count > 5:\n print(\"you made too many mistakes and got captured, you have to restart\")\n break\n\n", "You just forgot to put the errorCount conditional in the last loop, also it is better that you put this before the user input so that it doesn't ask the question 6 times instead of the 5 you want. Finally, it is necessary to add a break at the end of the conditional so that there is not an infinite loop\n# Level 5:\nprint(\"You have the jewel in your possession, and defeated Joker at his own game\")\nprint(\"You now hold the precious jewel in your hands, but it's not over, you must leave the maze!\")\nprint(\"*You must now choose 'Right', 'Left', or 'Straight' as you exit the maze. Keep trying until you find your path.*\")\n\n# put an error limit\n# space everything out to make it look more neat\n# Make sure you can fail the level\n\nerrorCount = 0\n\nposition = 0\nwhile True:\n if errorCount == 5:\n print(\"you made too many mistakes and got captured, you have to restart\")\n break\n \n answer1 = input(\"Choose either Right, Left, Straight: \")\n \n try:\n if answer1.lower() == \"right\":\n print(\"You have chosen the correct path, now you proceed to the next step!\")\n print()\n break\n \n elif answer1.lower() == \"left\":\n print(\"You see a boulder blocking your path which forces you to go back.\")\n errorCount = 1 + errorCount\n \n elif answer1.lower() == \"straight\":\n print(\"On your way to the next stage you are exposed to a toxic gas that forces you to go back .\")\n errorCount = 1 + errorCount\n \n else:\n print(\"Wrong input. Please try again..\")\n errorCount = 1 + errorCount\n except Exception:\n print(\"Wrong input. Please try again..\")\n\n# if errors >= 5:\n\nwhile True:\n if errorCount == 5:\n print(\"you made too many mistakes and got captured, you have to restart\")\n break\n \n answer1 = input(\"Choose either Right, Left, Straight: \")\n \n try:\n if answer1.lower() == \"straight\":\n print(\"You have chosen the correct path, now you proceed to the next step!\")\n break\n \n elif answer1.lower() == \"left\":\n print(\"You chose the wrong path, go back\")\n errorCount = 1 + errorCount\n \n elif answer1.lower() == \"right\":\n print(\"You chose the wrong path, go back\")\n errorCount = 1 + errorCount\n \n else:\n print(\"Wrong input. Please try again..\")\n errorCount = 1 + errorCount\n \n except Exception:\n print(\"Wrong input. Please try again..\")\n\nprint(\"You are now on the third stage, you notice a screen that is asking you a riddle\")\n\nwhile True:\n if errorCount == 5:\n print(\"you made too many mistakes and got captured, you have to restart\")\n break\n \n riddle1 = input(\"What gets wet when drying? \")\n \n if errorCount == 5:\n print(\"you made too many mistakes and got captured, you have to restart\")\n\n try:\n if riddle1.lower() == \"towel\":\n print(\"You have chosen the correct answer\")\n print(\"The giant stone blocking the entrance of the maze opens, and the outside lights shine through..\")\n break\n \n else:\n print(\"Incorrect! Try again..\")\n errorCount = 1 + errorCount\n print(\"Heres a hint: You use it after taking a shower...\")\n \n except Exception:\n print(\"Incorrect! Try again..\")\n errorCount = 1 + errorCount\n\nI recommend that instead of using:\nerrorcount = 1 + errorcount\n\nIt is better to use:\nerrorcount += 1\n\n" ]
[ 0, 0 ]
[]
[]
[ "for_loop", "if_statement", "python", "spyder", "while_loop" ]
stackoverflow_0074663626_for_loop_if_statement_python_spyder_while_loop.txt
Q: "Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src 'self'" (+ more) I'm currently trying to create a chrome extension. For some reason, I get an error for seemingly no reason. (See title) The HTML popup code: <!DOCTYPE html> <html lang="en_NZ"> <body> <h1>Header</h1> <button id="checkbox"></button> <script src="sripts/settings.js"></script> </body> </html> The settings.js code: document.getElementById("checkbox").addEventListener("click", function() { console.log("hello") }); I'm not even too sure what the exact issue is. Sometimes the extensions page highlights the </body> , and sometimes it highlights the <button id="checkbox"></button> , and sometimes it highlights the </head> . Can anyone help with this? Thanks. A: It looks like you may be missing the closing </head> tag in your HTML. It should be placed just before the <body> tag. Also, in your script tag, you have misspelled "scripts" as "sripts". It should be <script src="scripts/settings.js"></script> instead. <!DOCTYPE html> <html lang="en_NZ"> <head> <title>Your Extension Title</title> </head> <body> <h1>Header</h1> <button id="checkbox"></button> <script src="scripts/settings.js"></script> </body> </html>
"Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src 'self'" (+ more)
I'm currently trying to create a chrome extension. For some reason, I get an error for seemingly no reason. (See title) The HTML popup code: <!DOCTYPE html> <html lang="en_NZ"> <body> <h1>Header</h1> <button id="checkbox"></button> <script src="sripts/settings.js"></script> </body> </html> The settings.js code: document.getElementById("checkbox").addEventListener("click", function() { console.log("hello") }); I'm not even too sure what the exact issue is. Sometimes the extensions page highlights the </body> , and sometimes it highlights the <button id="checkbox"></button> , and sometimes it highlights the </head> . Can anyone help with this? Thanks.
[ "It looks like you may be missing the closing </head> tag in your HTML. It should be placed just before the <body> tag.\nAlso, in your script tag, you have misspelled \"scripts\" as \"sripts\". It should be <script src=\"scripts/settings.js\"></script> instead.\n<!DOCTYPE html>\n<html lang=\"en_NZ\">\n<head>\n <title>Your Extension Title</title>\n</head>\n<body>\n <h1>Header</h1>\n <button id=\"checkbox\"></button>\n <script src=\"scripts/settings.js\"></script>\n</body>\n</html>\n\n" ]
[ 0 ]
[]
[]
[ "google_chrome_extension", "html", "javascript" ]
stackoverflow_0074663784_google_chrome_extension_html_javascript.txt
Q: C++ Primer 5th Ed - Question on accessibility of Derived-to-Base Conversion In chapter 7 (Object Oriented Programming), below is the excerpts of the author when comes to accessibility of Derived-to-Base Conversion. Accessibility of Derived-to-Base Conversion Whether the derived-to-base conversion (§ 15.2.2, p. 597) is accessible depends on which code is trying to use the conversion and may depend on the access specifier used in the derived class’ derivation. Assuming D inherits from B: • User code may use the derived-to-base conversion only if D inherits publicly from B. User code may not use the conversion if D inherits from B using either protected or private. • Member functions and friends of D can use the conversion to B regardless of how D inherits from B. The derived-to-base conversion to a direct base class is always accessible to members and friends of a derived class. • Member functions and friends of classes derived from D may use the derived-tobase conversion if D inherits from B using either public or protected. Such code may not use the conversion if D inherits privately from B. I don't understand the last 2 bullet points. Seems they are related to each other. Appreciate any help with examples on it. Thanks. Final Note: There's another thread with exact identical questions and feedback. Please refer to this link for further reading - Derive* to Base* conversion in member function/friend function of base/derived class A: The last two bullet points are saying that if D inherits privately then the conversion is not available to further-derived types. That is: class B {}; class D : private B {}; class D2 : public D {}; The list is simply formalizing that D2 and any friends do not have access to the B members of D, even though D itself and any friends of D do have such access.
C++ Primer 5th Ed - Question on accessibility of Derived-to-Base Conversion
In chapter 7 (Object Oriented Programming), below is the excerpts of the author when comes to accessibility of Derived-to-Base Conversion. Accessibility of Derived-to-Base Conversion Whether the derived-to-base conversion (§ 15.2.2, p. 597) is accessible depends on which code is trying to use the conversion and may depend on the access specifier used in the derived class’ derivation. Assuming D inherits from B: • User code may use the derived-to-base conversion only if D inherits publicly from B. User code may not use the conversion if D inherits from B using either protected or private. • Member functions and friends of D can use the conversion to B regardless of how D inherits from B. The derived-to-base conversion to a direct base class is always accessible to members and friends of a derived class. • Member functions and friends of classes derived from D may use the derived-tobase conversion if D inherits from B using either public or protected. Such code may not use the conversion if D inherits privately from B. I don't understand the last 2 bullet points. Seems they are related to each other. Appreciate any help with examples on it. Thanks. Final Note: There's another thread with exact identical questions and feedback. Please refer to this link for further reading - Derive* to Base* conversion in member function/friend function of base/derived class
[ "The last two bullet points are saying that if D inherits privately then the conversion is not available to further-derived types.\nThat is:\nclass B\n{};\nclass D : private B\n{};\nclass D2 : public D\n{};\n\nThe list is simply formalizing that D2 and any friends do not have access to the B members of D, even though D itself and any friends of D do have such access.\n" ]
[ 1 ]
[]
[]
[ "c++", "c++11", "c++17", "c++20" ]
stackoverflow_0074663787_c++_c++11_c++17_c++20.txt
Q: Windows Command prompt/batch file to set special folder locations (e.g. desktop) I'm looking for a command or piece I can use in a Windows batch file to set the location of the special user folders (desktop, documents, downloads etc.). I can currently change this in Windows Explorer by right clicking on Desktop and changing the location from the default (C:\users\user\Desktop) to my alternative on the X: drive. However, I need the batch file to execute this change for me. I’ve looked everywhere for an answer to this question and have resorted to Stack as I thought somebody more experienced in cmd/bat/power shell code would know the answer and support others (the whole reason for this site) All help appreciated!
Windows Command prompt/batch file to set special folder locations (e.g. desktop)
I'm looking for a command or piece I can use in a Windows batch file to set the location of the special user folders (desktop, documents, downloads etc.). I can currently change this in Windows Explorer by right clicking on Desktop and changing the location from the default (C:\users\user\Desktop) to my alternative on the X: drive. However, I need the batch file to execute this change for me. I’ve looked everywhere for an answer to this question and have resorted to Stack as I thought somebody more experienced in cmd/bat/power shell code would know the answer and support others (the whole reason for this site) All help appreciated!
[]
[]
[ "Perhaps this function in powershell does not answer your question, but just only I got the hint of the user \"Qwerty\" in his comment above :\n\nPowershell Code :\nFunction Get-RegistryData {\nParam(\n [Parameter(\n Mandatory=$true)]\n [string]$RegistryPath #enter the full registry path including the Root key, eg HKEY_LOCAL_MACHINE\n)\n $Registrykeys = Get-Item -Path \"Registry::$RegistryPath\" \n $Registrykeys | Select-Object -ExpandProperty Property | \n\n ForEach-Object {\n $name = $_\n $data = \"\" | Select-Object -Property Name, Path, Type, Data #creates an empty \n $data.Name = $name\n $data.Type = $Registrykeys.GetValueKind($name)\n $data.Data = $Registrykeys.GetValue($name)\n $data.Path = \"Registry::$Registrykeys\"\n $data\n \n }\n}\n\nGet-RegistryData \"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders\" | Select-Object Name,Data\n\n" ]
[ -1 ]
[ "batch_file", "command_prompt", "microsoft_file_explorer", "windows" ]
stackoverflow_0074660521_batch_file_command_prompt_microsoft_file_explorer_windows.txt
Q: Using JS Object Based Multidimensional Arrays to Collect, Store, and View Data in a PDF Form I have an interactive PDF form created in Acrobat that employs a multidimensional object to collect, store, and populate form fields used to view the data. The form serves as a password manager to view individual password records whereby I have recently completed the lookup record page view that works like a charm. The only issue I've run into thus far is my inability to delete a record selected in the lookup view in which event I initially thought I'd be able to use the JS array.splice() method to simply delete a line item in the object array that stores the data for the particular record I want to delete. Come to learn that the script used to create the object that stores the data still remains inside the form whereby literally nothing has changed. Upon further study, I am inclined to believe that the form is essentially serving as a window to view the information stored in the object and for whatever reason invoking a script using the JS slice() method has no effect whatsoever on the script that created the object to begin with. Hence, in order to make this work, it appears I need to be able to rewrite/replace the script minus the object property/s that hold the data for the record to be deleted. Sorry for the novel. Any comments or suggestions regarding this subject matter are most appreciated. Thank you ahead of time. Created a script using the JS splice() method in a futile attempt to remove data from an object used to collect and store data inside an interactive PDF form. A: From Adobe's Docs: You can use the Document JavaScript dialog box to add, edit, or delete scripts in your current document. To open the dialog box, choose Tools > JavaScript > Document JavaScript. Here https://helpx.adobe.com/uk/acrobat/using/add-debug-javascript.html I've never used Adobe Acrobat, but if you need to edit a script in a PDF, that's probably where to get at it. If you post the script's code, someone might be able to help you. It's almost impossible to get an answer to any question without posting code.
Using JS Object Based Multidimensional Arrays to Collect, Store, and View Data in a PDF Form
I have an interactive PDF form created in Acrobat that employs a multidimensional object to collect, store, and populate form fields used to view the data. The form serves as a password manager to view individual password records whereby I have recently completed the lookup record page view that works like a charm. The only issue I've run into thus far is my inability to delete a record selected in the lookup view in which event I initially thought I'd be able to use the JS array.splice() method to simply delete a line item in the object array that stores the data for the particular record I want to delete. Come to learn that the script used to create the object that stores the data still remains inside the form whereby literally nothing has changed. Upon further study, I am inclined to believe that the form is essentially serving as a window to view the information stored in the object and for whatever reason invoking a script using the JS slice() method has no effect whatsoever on the script that created the object to begin with. Hence, in order to make this work, it appears I need to be able to rewrite/replace the script minus the object property/s that hold the data for the record to be deleted. Sorry for the novel. Any comments or suggestions regarding this subject matter are most appreciated. Thank you ahead of time. Created a script using the JS splice() method in a futile attempt to remove data from an object used to collect and store data inside an interactive PDF form.
[ "From Adobe's Docs:\n\nYou can use the Document JavaScript dialog box to add, edit, or delete scripts in your current document.\nTo open the dialog box, choose Tools > JavaScript > Document JavaScript.\n\nHere https://helpx.adobe.com/uk/acrobat/using/add-debug-javascript.html\nI've never used Adobe Acrobat, but if you need to edit a script in a PDF, that's probably where to get at it.\nIf you post the script's code, someone might be able to help you. It's almost impossible to get an answer to any question without posting code.\n" ]
[ 0 ]
[]
[]
[ "javascript", "multidimensional_array", "object", "pdf" ]
stackoverflow_0074663741_javascript_multidimensional_array_object_pdf.txt
Q: reviews of a firm My goal is to scrape the entire reviews of this firm. I tried manipulating @Driftr95 codes: def extract(pg): headers = {'user-agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'} url = f'https://www.glassdoor.com/Reviews/3M-Reviews-E446_P{pg}.htm?filter.iso3Language=eng' # f'https://www.glassdoor.com/Reviews/Google-Engineering-Reviews-EI_IE9079.0,6_DEPT1007_IP{pg}.htm?sort.sortType=RD&sort.ascending=false&filter.iso3Language=eng' r = requests.get(url, headers, timeout=(3.05, 27)) soup = BeautifulSoup(r.content, 'html.parser')# this a soup function that retuen the whole html return soup for j in range(1,21,10): for i in range(j+1,j+11,1): #3M: 4251 reviews soup = extract( f'https://www.glassdoor.com/Reviews/3M-Reviews-E446_P{i}.htm?filter.iso3Language=eng') print(f' page {i}') for r in soup.select('li[id^="empReview_"]'): rDet = {'reviewId': r.get('id')} for sr in r.select(subRatSel): k = sr.select_one('div:first-of-type').get_text(' ').strip() sval = getDECstars(sr.select_one('div:nth-of-type(2)'), soup) rDet[f'[rating] {k}'] = sval for k, sel in refDict.items(): sval = r.select_one(sel) if sval: sval = sval.get_text(' ').strip() rDet[k] = sval empRevs.append(rDet) In the case where not all the subratings are always available, all four subratings will turn out to be N.A. A: All four subratings will turn out to be N.A. there were some things that I didn't account for because I hadn't encountered them before, but the updated version of getDECstars shouldn't have that issue. (If you use the longer version with argument isv=True, it's easier to debug and figure out what's missing from the code...) I scraped 200 reviews in this case, and it turned out that only 170 unique reviews Duplicates are fairly easy to avoid by maintaining a list of reviewIds that have already been added and checking against it before adding a new review to empRevs scrapedIds = [] # for... # for ### # soup = extract... # for r in ... if r.get('id') in scrapedIds: continue # skip duplicate ## rDet = ..... ## AND REST OF INNER FOR-LOOP ## empRevs.append(rDet) scrapedIds.append(rDet['reviewId']) # add to list of ids to check against Https tends to time out after 100 rounds... You could try adding breaks and switching out user-agents every 50 [or 5 or 10 or...] requests, but I'm quick to resort to selenium at times like this; this is my suggested solution - if you just call it like this and pass a url to start with: ## PASTE [OR DOWNLOAD&IMPORT] from https://pastebin.com/RsFHWNnt ## startUrl = 'https://www.glassdoor.com/Reviews/3M-Reviews-E446.htm?sort.sortType=RD&sort.ascending=false&filter.iso3Language=eng' scrape_gdRevs(startUrl, 'empRevs_3M.csv', maxScrapes=1000, constBreak=False) [last 3 lines of] printed output: total reviews: 4252 total reviews scraped this run: 4252 total reviews scraped over all time: 4252 It clicks through the pages until it reaches the last page (or maxes out maxScrapes). You do have to log in at the beginning though, so fill out login_to_gd with your username and password or log in manually by replacing the login_to_gd(driverG) line with the input(...) line that waits for you to login [then press ENTER in the terminal] before continuing. I think cookies can also be used instead (with requests), but I'm not good at handling that. If you figure it out, then you can use some version of linkToSoup or your extract(pg); then, you'll have to comment out or remove the lines ending in ## for selenium and uncomment [or follow instructions from] the lines that end with ## without selenium. [But please note that I've only fully tested the selenium version.] The CSVs [like "empRevs_3M.csv" and "scrapeLogs_empRevs_3M.csv" in this example] are updated after every page-scrape, so even if the program crashes [or you decide to interrupt it], it will have saved upto the previous scrape. Since it also tries to load form the CSVs at the beginning, you can just continue it later (just set startUrl to the url of the page you want to continue from - but even if it's at page 1, remember that duplicates will be ignored, so it's okay - it'll just waste some time though).
reviews of a firm
My goal is to scrape the entire reviews of this firm. I tried manipulating @Driftr95 codes: def extract(pg): headers = {'user-agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'} url = f'https://www.glassdoor.com/Reviews/3M-Reviews-E446_P{pg}.htm?filter.iso3Language=eng' # f'https://www.glassdoor.com/Reviews/Google-Engineering-Reviews-EI_IE9079.0,6_DEPT1007_IP{pg}.htm?sort.sortType=RD&sort.ascending=false&filter.iso3Language=eng' r = requests.get(url, headers, timeout=(3.05, 27)) soup = BeautifulSoup(r.content, 'html.parser')# this a soup function that retuen the whole html return soup for j in range(1,21,10): for i in range(j+1,j+11,1): #3M: 4251 reviews soup = extract( f'https://www.glassdoor.com/Reviews/3M-Reviews-E446_P{i}.htm?filter.iso3Language=eng') print(f' page {i}') for r in soup.select('li[id^="empReview_"]'): rDet = {'reviewId': r.get('id')} for sr in r.select(subRatSel): k = sr.select_one('div:first-of-type').get_text(' ').strip() sval = getDECstars(sr.select_one('div:nth-of-type(2)'), soup) rDet[f'[rating] {k}'] = sval for k, sel in refDict.items(): sval = r.select_one(sel) if sval: sval = sval.get_text(' ').strip() rDet[k] = sval empRevs.append(rDet) In the case where not all the subratings are always available, all four subratings will turn out to be N.A.
[ "\nAll four subratings will turn out to be N.A.\n\nthere were some things that I didn't account for because I hadn't encountered them before, but the updated version of getDECstars shouldn't have that issue. (If you use the longer version with argument isv=True, it's easier to debug and figure out what's missing from the code...)\n\n\nI scraped 200 reviews in this case, and it turned out that only 170 unique reviews\n\nDuplicates are fairly easy to avoid by maintaining a list of reviewIds that have already been added and checking against it before adding a new review to empRevs\nscrapedIds = []\n# for...\n # for ###\n # soup = extract...\n\n # for r in ...\n if r.get('id') in scrapedIds: continue # skip duplicate\n ## rDet = ..... ## AND REST OF INNER FOR-LOOP ##\n\n empRevs.append(rDet) \n scrapedIds.append(rDet['reviewId']) # add to list of ids to check against\n\n\n\nHttps tends to time out after 100 rounds...\n\nYou could try adding breaks and switching out user-agents every 50 [or 5 or 10 or...] requests, but I'm quick to resort to selenium at times like this; this is my suggested solution - if you just call it like this and pass a url to start with:\n## PASTE [OR DOWNLOAD&IMPORT] from https://pastebin.com/RsFHWNnt ##\n\nstartUrl = 'https://www.glassdoor.com/Reviews/3M-Reviews-E446.htm?sort.sortType=RD&sort.ascending=false&filter.iso3Language=eng'\nscrape_gdRevs(startUrl, 'empRevs_3M.csv', maxScrapes=1000, constBreak=False)\n\n\n[last 3 lines of] printed output:\n total reviews: 4252\ntotal reviews scraped this run: 4252\ntotal reviews scraped over all time: 4252\n\n\nIt clicks through the pages until it reaches the last page (or maxes out maxScrapes). You do have to log in at the beginning though, so fill out login_to_gd with your username and password or log in manually by replacing the login_to_gd(driverG) line with the input(...) line that waits for you to login [then press ENTER in the terminal] before continuing.\nI think cookies can also be used instead (with requests), but I'm not good at handling that. If you figure it out, then you can use some version of linkToSoup or your extract(pg); then, you'll have to comment out or remove the lines ending in ## for selenium and uncomment [or follow instructions from] the lines that end with ## without selenium. [But please note that I've only fully tested the selenium version.]\nThe CSVs [like \"empRevs_3M.csv\" and \"scrapeLogs_empRevs_3M.csv\" in this example] are updated after every page-scrape, so even if the program crashes [or you decide to interrupt it], it will have saved upto the previous scrape. Since it also tries to load form the CSVs at the beginning, you can just continue it later (just set startUrl to the url of the page you want to continue from - but even if it's at page 1, remember that duplicates will be ignored, so it's okay - it'll just waste some time though).\n" ]
[ 0 ]
[]
[]
[ "beautifulsoup", "python", "selenium", "web_scraping" ]
stackoverflow_0074650912_beautifulsoup_python_selenium_web_scraping.txt
Q: Vue 3 / Nuxt 3 Scoped slot with generic data type inferred from props I want to implement a carousel component in Nuxt v3. The component receives an array of items. The component only implements the logic, not the styling or structuring. Here is my component now: components/tdx/carousel.vue <template> <div> <slot name="last"></slot> <div v-for="item in items"> <slot name="item" v-bind="item" ></slot> </div> <slot name="next"></slot> </div> </template> <script setup lang="ts"> const props = defineProps({ items: { type: [], required: true, }, spotlight: { type: Number, default: 1, validator(value: number) { return value > 0; }, }, }); </script> The logic of the carousel here is not important. In the parent component I then can use the component like this: <template> <div class="container"> <TdxCarousel :items="exampleArray"> <template #item="{ title, description }"> <p class="font-semibold text-2xl">{{ title }}</p> <hr /> <p>{{ description }}</p> </template> </TdxCarousel> </div> </template> <script setup lang="ts"> const exampleArray = ref([ { title: 'Item 1', description: 'Desc of item 1', }, { title: 'Item 2', description: 'Desc of item 2', }, ]); </script> This works fine. What I want in addition to this is typings. The types of title and description are of course any since in the props of carousel.vue the type of the items is unknown[]. I found this article that show how to make a generic component but I don't want this since I would have to mess with the auto import system from nuxt. How can I achieve type inference from the given items in the carousel.vue props? A: You need to define a generic parameter. This isn't officially supported yet. However, there is currently an RFC for how generic components should be supported. If you use VSCode and Volar, Volar currently has an experimental flag you can use to try it out. First, enable the experimentalRfc436 option your tsconfig.json under vueCompilerOptions. // tsconfig.json { // ... "vueCompilerOptions": { "experimentalRfc436": true } } Then you need to modify your carousel.vue component to use the generic attribute in the <script setup> tag, as well as convert it to use type-based method for defineProps in order for it to pick up on the generic properly. <template> <div> <slot name="last"></slot> <div v-for="item in items"> <slot name="item" v-bind="item"> </slot> </div> <slot name="next"></slot> </div> </template> <script setup lang="ts" generic="T extends any"> withDefaults( defineProps<{ items: T[]; spotlight?: number }>(), { spotlight: 1, }); </script> Now, the props on the slot should properly be inferred from the type of items.
Vue 3 / Nuxt 3 Scoped slot with generic data type inferred from props
I want to implement a carousel component in Nuxt v3. The component receives an array of items. The component only implements the logic, not the styling or structuring. Here is my component now: components/tdx/carousel.vue <template> <div> <slot name="last"></slot> <div v-for="item in items"> <slot name="item" v-bind="item" ></slot> </div> <slot name="next"></slot> </div> </template> <script setup lang="ts"> const props = defineProps({ items: { type: [], required: true, }, spotlight: { type: Number, default: 1, validator(value: number) { return value > 0; }, }, }); </script> The logic of the carousel here is not important. In the parent component I then can use the component like this: <template> <div class="container"> <TdxCarousel :items="exampleArray"> <template #item="{ title, description }"> <p class="font-semibold text-2xl">{{ title }}</p> <hr /> <p>{{ description }}</p> </template> </TdxCarousel> </div> </template> <script setup lang="ts"> const exampleArray = ref([ { title: 'Item 1', description: 'Desc of item 1', }, { title: 'Item 2', description: 'Desc of item 2', }, ]); </script> This works fine. What I want in addition to this is typings. The types of title and description are of course any since in the props of carousel.vue the type of the items is unknown[]. I found this article that show how to make a generic component but I don't want this since I would have to mess with the auto import system from nuxt. How can I achieve type inference from the given items in the carousel.vue props?
[ "You need to define a generic parameter. This isn't officially supported yet. However, there is currently an RFC for how generic components should be supported.\nIf you use VSCode and Volar, Volar currently has an experimental flag you can use to try it out.\nFirst, enable the experimentalRfc436 option your tsconfig.json under vueCompilerOptions.\n// tsconfig.json\n{\n // ...\n \"vueCompilerOptions\": {\n \"experimentalRfc436\": true\n }\n}\n\nThen you need to modify your carousel.vue component to use the generic attribute in the <script setup> tag, as well as convert it to use type-based method for defineProps in order for it to pick up on the generic properly.\n<template>\n <div>\n <slot name=\"last\"></slot>\n <div v-for=\"item in items\">\n <slot\n name=\"item\"\n v-bind=\"item\">\n </slot>\n </div>\n <slot name=\"next\"></slot>\n </div>\n</template>\n<script setup lang=\"ts\" generic=\"T extends any\">\nwithDefaults(\n defineProps<{ items: T[]; spotlight?: number }>(), {\n spotlight: 1,\n});\n</script>\n\nNow, the props on the slot should properly be inferred from the type of items.\n\n\n" ]
[ 0 ]
[]
[]
[ "nuxt.js", "nuxtjs3", "typescript", "vue.js", "vuejs3" ]
stackoverflow_0074025876_nuxt.js_nuxtjs3_typescript_vue.js_vuejs3.txt
Q: Angular - Count number of files in a list based on extension I have a data list as below : List: [0]: file_name : a.jpg, category : social; [1]: file_name : b.png, category : digital; [2]: file_name : c.tif, category : social; [3]: file_name : a.jpg, category : digital; I need to create an array which will have extension and its count. Below is the expected output : fileListCount = [ {name: 'jpg', completed: false, count: '5'}, {name: 'pdf', completed: false, count: '4'}, {name: 'tif', completed: false, count: '3'}, {name: 'mp4', completed: false, count: '2'}, {name: 'docx', completed: false, count: '1'}, {name: 'doc', completed: false, count: '10'} ]; The problem is i am unable to find a dynamic solution for counting the extensions in the list. I am hardcoding and that can cause an issue. Any help or leads much appreciated : obj : { name: string; checked: false; count: number; } myList = []; let count=0; let pngArr:string[] let jpgArr:string[] let tifArr:string[] for (let entry of this.masterList) { debugger; let ext:string = entry.file_name.split('.').pop(); if(ext == 'png') { pngArr.push(ext); } if(ext== "jpeg") { jpgArr.push(ext); } if(ext== "tif") { tifArr.push(ext); } } this.obj.name = "jpg"; this.obj.count = jpgArr.length; this.myList.push(this.obj); A: To count the number of files with a specific extension, you can use a JavaScript object to store the count of each extension. First, create an empty extensions object. Then, iterate over each file in your list and use the split method to get the extension of the file. If the extension is not already a property of the extensions object, you can add it and set its value to 1. Otherwise, you can increment the count of the extension by 1. After iterating over the entire list, you can use the Object.entries method to get the key-value pairs of the extensions object, then use Array.map to create an array of objects with the structure you described in your expected output: const fileList = [ { file_name: 'a.jpg', category: 'social' }, { file_name: 'b.png', category: 'digital' }, { file_name: 'c.tif', category: 'social' }, { file_name: 'a.jpg', category: 'digital' }, ]; // Create an empty object to store the counts const extensions = {}; // Iterate over each file in the list for (const file of fileList) { // Use the split method to get the file extension const ext = file.file_name.split('.').pop(); // If the extension is not already a property of the object, add it and set its value to 1 if (!extensions[ext]) { extensions[ext] = 1; } else { // Otherwise, increment the count of the extension by 1 extensions[ext]++; } } // Use Object.entries to get the key-value pairs of the object const extensionCounts = Object.entries(extensions); // Use Array.map to create an array of objects with the structure you described const fileListCount = extensionCounts.map(([name, count]) => ({ name, completed: false, count, })); console.log(fileListCount); // Output: [ // { name: 'jpg', completed: false, count: 2 }, // { name: 'png', completed: false, count: 1 }, // { name: 'tif', completed: false, count: 1 }, // ]
Angular - Count number of files in a list based on extension
I have a data list as below : List: [0]: file_name : a.jpg, category : social; [1]: file_name : b.png, category : digital; [2]: file_name : c.tif, category : social; [3]: file_name : a.jpg, category : digital; I need to create an array which will have extension and its count. Below is the expected output : fileListCount = [ {name: 'jpg', completed: false, count: '5'}, {name: 'pdf', completed: false, count: '4'}, {name: 'tif', completed: false, count: '3'}, {name: 'mp4', completed: false, count: '2'}, {name: 'docx', completed: false, count: '1'}, {name: 'doc', completed: false, count: '10'} ]; The problem is i am unable to find a dynamic solution for counting the extensions in the list. I am hardcoding and that can cause an issue. Any help or leads much appreciated : obj : { name: string; checked: false; count: number; } myList = []; let count=0; let pngArr:string[] let jpgArr:string[] let tifArr:string[] for (let entry of this.masterList) { debugger; let ext:string = entry.file_name.split('.').pop(); if(ext == 'png') { pngArr.push(ext); } if(ext== "jpeg") { jpgArr.push(ext); } if(ext== "tif") { tifArr.push(ext); } } this.obj.name = "jpg"; this.obj.count = jpgArr.length; this.myList.push(this.obj);
[ "To count the number of files with a specific extension, you can use a JavaScript object to store the count of each extension.\nFirst, create an empty extensions object. Then, iterate over each file in your list and use the split method to get the extension of the file. If the extension is not already a property of the extensions object, you can add it and set its value to 1. Otherwise, you can increment the count of the extension by 1.\nAfter iterating over the entire list, you can use the Object.entries method to get the key-value pairs of the extensions object, then use Array.map to create an array of objects with the structure you described in your expected output:\nconst fileList = [\n { file_name: 'a.jpg', category: 'social' },\n { file_name: 'b.png', category: 'digital' },\n { file_name: 'c.tif', category: 'social' },\n { file_name: 'a.jpg', category: 'digital' },\n];\n\n// Create an empty object to store the counts\nconst extensions = {};\n\n// Iterate over each file in the list\nfor (const file of fileList) {\n // Use the split method to get the file extension\n const ext = file.file_name.split('.').pop();\n\n // If the extension is not already a property of the object, add it and set its value to 1\n if (!extensions[ext]) {\n extensions[ext] = 1;\n } else {\n // Otherwise, increment the count of the extension by 1\n extensions[ext]++;\n }\n}\n\n// Use Object.entries to get the key-value pairs of the object\nconst extensionCounts = Object.entries(extensions);\n\n// Use Array.map to create an array of objects with the structure you described\nconst fileListCount = extensionCounts.map(([name, count]) => ({\n name,\n completed: false,\n count,\n}));\n\nconsole.log(fileListCount);\n\n// Output: [\n// { name: 'jpg', completed: false, count: 2 },\n// { name: 'png', completed: false, count: 1 },\n// { name: 'tif', completed: false, count: 1 },\n// ]\n\n" ]
[ 1 ]
[]
[]
[ "angular", "arrays", "javascript" ]
stackoverflow_0074663757_angular_arrays_javascript.txt
Q: Join cells from Pandas data frame and safe as one string or .txt file I am trying to extract data from a data frame in Pandas and merge the results into one string (or .txt file) Data Frame: NUM LETTER 0 4 Z 1 5 U 2 6 A 3 7 P 4 1 B 5 4 P 6 5 L 7 6 T 8 7 V 9 1 E Script so far: data = pd.read_csv("TEST.csv") fdata = data[data["LETTER"].str.contains("A|E|L|P")] ffdata = fdata.RESULT.to_string() print(ffdata) Running the script on TEST.csv gives me this result: LETTER 2 A 3 P 5 P 6 L 9 E Next, I want to join the data from the filtered cells and join them into one string: --> "APPLE", optional with saving them as .txt to use them later. How do I proceed from here? I was thinking about iterating over the data frame and use join, but I have no idea how to implement this. Any clues? A: Based on @Frodnar's answer, this is the code that works: data = pd.read_csv("TEST.csv") fdata = data[data["LETTER"].str.contains("A|E|L|P")] ffdata = ''.join(fdata.LETTER.to_list()) print(ffdata) which gives the output 'APPLE' Thank you for your help!!
Join cells from Pandas data frame and safe as one string or .txt file
I am trying to extract data from a data frame in Pandas and merge the results into one string (or .txt file) Data Frame: NUM LETTER 0 4 Z 1 5 U 2 6 A 3 7 P 4 1 B 5 4 P 6 5 L 7 6 T 8 7 V 9 1 E Script so far: data = pd.read_csv("TEST.csv") fdata = data[data["LETTER"].str.contains("A|E|L|P")] ffdata = fdata.RESULT.to_string() print(ffdata) Running the script on TEST.csv gives me this result: LETTER 2 A 3 P 5 P 6 L 9 E Next, I want to join the data from the filtered cells and join them into one string: --> "APPLE", optional with saving them as .txt to use them later. How do I proceed from here? I was thinking about iterating over the data frame and use join, but I have no idea how to implement this. Any clues?
[ "Based on @Frodnar's answer, this is the code that works:\ndata = pd.read_csv(\"TEST.csv\")\nfdata = data[data[\"LETTER\"].str.contains(\"A|E|L|P\")]\nffdata = ''.join(fdata.LETTER.to_list())\nprint(ffdata)\n\nwhich gives the output 'APPLE'\nThank you for your help!!\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "string" ]
stackoverflow_0074595701_dataframe_pandas_string.txt
Q: I'm finding it hard to understand how functions work. Would someome mind explaining them? Please excuse the extra modulus. I've taken a small part of my code out to convert it into functions to make my code less messy. However I'm finding it really hard to understand how I put values in and take them out to print or do things with. See the code I'm using below. VideoURL would be replaced with a url of a video. ` from urllib.request import urlopen from bs4 import BeautifulSoup import requests from pytube import YouTube from pytube import Channel channelURL = "videoURL" YouTubeDomain = "https://www.youtube.com/channel/" def BeautifulSoup(Link): soup = BeautifulSoup(requests.get(Link, cookies={'CONSENT': 'YES+1'}).text, "html.parser") data = re.search(r"var ytInitialData = ({.*});", str(soup.prettify())).group(1) json_data = json.loads(data) channel_id = json_data["header"]["c4TabbedHeaderRenderer"]["channelId"] channel_name = json_data["header"]["c4TabbedHeaderRenderer"]["title"] channel_logo = json_data["header"]["c4TabbedHeaderRenderer"]["avatar"]["thumbnails"][2]["url"] channel_id_link = YouTubeDomain+channel_id print("Channel ID: "+channel_id) print("Channel Name: "+channel_name) print("Channel Logo: "+channel_logo) print("Channel ID: "+channel_id_link) def vVersion(*arg): YTV = YouTube(channelURL) channel_id = YTV.channel_id channel_id_link = YTV.channel_url c = Channel(channel_id_link) channel_name =c.channel_name return channel_id_link, channelURL channel_id_link, video = vVersion() print(channel_id_link) Link = channel_id_link print(Link) Test = print(BeautifulSoup(Link)) Test() So the errors I keep getting are about having too many or too few args for the functions . Here's the current error: ` BeautifulSoup() takes 1 positional argument but 2 were given File "C:\Users\Admin\test\video1.py", line 26, in BeautifulSoup soup = BeautifulSoup(requests.get(Link, cookies={'CONSENT': 'YES+1'}).text, "html.parser") File "C:\Users\Admin\test\video1.py", line 53, in <module> Test = print(BeautifulSoup(Link)) `I know I'm missing something very simple. Any help would be welcome, thank you! ` I have tried to take the code out of my main code to isolate the issue. I was expecting to gain a perspective on the issue. I tried the following code to train myself on functions but it didn't really help me fix the issue I'm having with my project. def test(): name = (input("Enter your name?")) favNumber = (input("Please enter your best number?")) return name, favNumber name, favNumber = test() print(name) print(float(favNumber)) A: It's because you have named your function as BeautifulSoup which is as same as the name of the function from the library you have imported. Instead of using the function BeautifulSoup from bs4, it is now running the code you have defined which takes only one argument. So give your function another name.
I'm finding it hard to understand how functions work. Would someome mind explaining them?
Please excuse the extra modulus. I've taken a small part of my code out to convert it into functions to make my code less messy. However I'm finding it really hard to understand how I put values in and take them out to print or do things with. See the code I'm using below. VideoURL would be replaced with a url of a video. ` from urllib.request import urlopen from bs4 import BeautifulSoup import requests from pytube import YouTube from pytube import Channel channelURL = "videoURL" YouTubeDomain = "https://www.youtube.com/channel/" def BeautifulSoup(Link): soup = BeautifulSoup(requests.get(Link, cookies={'CONSENT': 'YES+1'}).text, "html.parser") data = re.search(r"var ytInitialData = ({.*});", str(soup.prettify())).group(1) json_data = json.loads(data) channel_id = json_data["header"]["c4TabbedHeaderRenderer"]["channelId"] channel_name = json_data["header"]["c4TabbedHeaderRenderer"]["title"] channel_logo = json_data["header"]["c4TabbedHeaderRenderer"]["avatar"]["thumbnails"][2]["url"] channel_id_link = YouTubeDomain+channel_id print("Channel ID: "+channel_id) print("Channel Name: "+channel_name) print("Channel Logo: "+channel_logo) print("Channel ID: "+channel_id_link) def vVersion(*arg): YTV = YouTube(channelURL) channel_id = YTV.channel_id channel_id_link = YTV.channel_url c = Channel(channel_id_link) channel_name =c.channel_name return channel_id_link, channelURL channel_id_link, video = vVersion() print(channel_id_link) Link = channel_id_link print(Link) Test = print(BeautifulSoup(Link)) Test() So the errors I keep getting are about having too many or too few args for the functions . Here's the current error: ` BeautifulSoup() takes 1 positional argument but 2 were given File "C:\Users\Admin\test\video1.py", line 26, in BeautifulSoup soup = BeautifulSoup(requests.get(Link, cookies={'CONSENT': 'YES+1'}).text, "html.parser") File "C:\Users\Admin\test\video1.py", line 53, in <module> Test = print(BeautifulSoup(Link)) `I know I'm missing something very simple. Any help would be welcome, thank you! ` I have tried to take the code out of my main code to isolate the issue. I was expecting to gain a perspective on the issue. I tried the following code to train myself on functions but it didn't really help me fix the issue I'm having with my project. def test(): name = (input("Enter your name?")) favNumber = (input("Please enter your best number?")) return name, favNumber name, favNumber = test() print(name) print(float(favNumber))
[ "It's because you have named your function as BeautifulSoup which is as same as the name of the function from the library you have imported. Instead of using the function BeautifulSoup from bs4, it is now running the code you have defined which takes only one argument. So give your function another name.\n" ]
[ 0 ]
[]
[]
[ "beautifulsoup", "function", "python", "pytube" ]
stackoverflow_0074663775_beautifulsoup_function_python_pytube.txt
Q: gRpc transcoding is not working- unable to find annotation.proto and http.proto are thrown I'm trying to do gRpc Transcoding with .NET 7. I'm following the article Here. I'm also referring to the sample implementation here. After I added the proto files annotation.proto and http.proto and include the annotations.proto to the main proto file. I get the error Rebuild started... 1>------ Rebuild All started: Project: CacheService, Configuration: Debug Any CPU ------ Restored C:\CarryCase\Venkatesh\M2c\grpc\net7\CacheService\CacheService.csproj (in 40 ms). 1>google/api/annotations.proto : error : File not found. 1>Protos/cache.proto(2,1): error : Import "google/api/annotations.proto" was not found or had errors. 1>Done building project "CacheService.csproj" -- FAILED. ========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ========== ========== Elapsed 00:00.428 ========== The code for the same is available at here (grpc-transcoding) I tried to create a gRPC transcoding code with .NET 7. But the proto definitions are not getting properly included resulting in error. I would expect it to work as told in reference articles A: Answering my own question here. I had worked with grpc-dotnet team. Detailed solutions is at (https://github.com/grpc/grpc-dotnet/issues/1965). My proto files are in folder structure With this structure in cache.protos we need to use Protos/google/api/annotations.proto and in annotations.proto we need to use Protos/google/api/http.proto. Also there was a message CustomHttpPattern missing that I added from the appropriate repo. The completed solution is available on my public github repo https://github.com/VenkateshSrini/GRpcFileCache/tree/gRpc-transcoding
gRpc transcoding is not working- unable to find annotation.proto and http.proto are thrown
I'm trying to do gRpc Transcoding with .NET 7. I'm following the article Here. I'm also referring to the sample implementation here. After I added the proto files annotation.proto and http.proto and include the annotations.proto to the main proto file. I get the error Rebuild started... 1>------ Rebuild All started: Project: CacheService, Configuration: Debug Any CPU ------ Restored C:\CarryCase\Venkatesh\M2c\grpc\net7\CacheService\CacheService.csproj (in 40 ms). 1>google/api/annotations.proto : error : File not found. 1>Protos/cache.proto(2,1): error : Import "google/api/annotations.proto" was not found or had errors. 1>Done building project "CacheService.csproj" -- FAILED. ========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ========== ========== Elapsed 00:00.428 ========== The code for the same is available at here (grpc-transcoding) I tried to create a gRPC transcoding code with .NET 7. But the proto definitions are not getting properly included resulting in error. I would expect it to work as told in reference articles
[ "Answering my own question here. I had worked with grpc-dotnet team. Detailed solutions is at (https://github.com/grpc/grpc-dotnet/issues/1965). My proto files are in folder structure\n\nWith this structure in cache.protos we need to use Protos/google/api/annotations.proto and in annotations.proto we need to use Protos/google/api/http.proto. Also there was a message CustomHttpPattern missing that I added from the appropriate repo. The completed solution is available on my public github repo https://github.com/VenkateshSrini/GRpcFileCache/tree/gRpc-transcoding\n" ]
[ 0 ]
[]
[]
[ ".net_7.0", "grpc_dotnet" ]
stackoverflow_0074587248_.net_7.0_grpc_dotnet.txt
Q: How to Split a column into two by comma delimiter, and put a value without comma in second column and not in first? I have a column in a df that I want to split into two columns splitting by comma delimiter. If the value in that column does not have a comma I want to put that into the second column instead of first. Origin New York, USA England Russia London, England California, USA USA I want the result to be: Location Country New York USA NaN England NaN Russia London England California USA NaN USA I used this code df['Location'], df['Country'] = df['Origin'].str.split(',', 1) A: We can try using str.extract here: df["Location"] = df["Origin"].str.extract(r'(.*),') df["Country"] = df["Origin"].str.extract(r'(\w+(?: \w+)*)$') A: Here is a way by using str.extract() and named groups df['Origin'].str.extract(r'(?P<Location>[A-Za-z ]+(?=,))?(?:, )?(?P<Country>\w+)') Output: Location Country 0 New York USA 1 NaN England 2 NaN Russia 3 London England 4 California USA 5 NaN USA
How to Split a column into two by comma delimiter, and put a value without comma in second column and not in first?
I have a column in a df that I want to split into two columns splitting by comma delimiter. If the value in that column does not have a comma I want to put that into the second column instead of first. Origin New York, USA England Russia London, England California, USA USA I want the result to be: Location Country New York USA NaN England NaN Russia London England California USA NaN USA I used this code df['Location'], df['Country'] = df['Origin'].str.split(',', 1)
[ "We can try using str.extract here:\ndf[\"Location\"] = df[\"Origin\"].str.extract(r'(.*),')\ndf[\"Country\"] = df[\"Origin\"].str.extract(r'(\\w+(?: \\w+)*)$')\n\n", "Here is a way by using str.extract() and named groups\ndf['Origin'].str.extract(r'(?P<Location>[A-Za-z ]+(?=,))?(?:, )?(?P<Country>\\w+)')\n\nOutput:\n Location Country\n0 New York USA\n1 NaN England\n2 NaN Russia\n3 London England\n4 California USA\n5 NaN USA\n\n" ]
[ 2, 0 ]
[]
[]
[ "multiple_columns", "pandas", "python", "split" ]
stackoverflow_0070795642_multiple_columns_pandas_python_split.txt
Q: How to access Vuex module getters and mutations? I'm trying to switch to using Vuex instead of my homegrown store object, and I must say I'm not finding the docs as clear as elsewhere in the Vue.js world. Let's say I have a Vuex module called 'products', with its own state, mutations, getters, etc. How do I reference an action in that module called, say, 'clearWorking Data'? The docs give this example of accessing a module's state: store.state.a // -> moduleA's state But nothing I can see about getters, mutations, actions, etc. A: In Addition to the accepted answer I wanna provide you with a workarround for the getter which is missing in the answer. Debug the Store In any case you can call console.log(this.$store) to debug the Store. If you do so you will see the getters are prefixed with the namespace in their name. Access namespaced getter this.$store.getters['yourModuleName/someGetterMethod'] Dispatch namespaced this.$store.dispatch('yourModuleName/doSomething') Dispatch namespaced with params this.$store.getters['yourModuleName/someGetterMethod'](myParam) Conclusion The key is to handle the namespace like a file System like Justin explained. Edit: found a nice library for handling vuex Store In addition to the basic knowledge I'd like to add this vuex library as a nice addition for working effectivly and fast with the vuex store. https://github.com/davestewart/vuex-pathify . It looks pretty interesting and cares much of the configuration for you and also allows you to handle 2waybinding directly with vuex. ** Edit: Thanks to the other Answers. Added Dispatching method with params for wholeness. A: In your example it would be store.dispatch('products/clearWorkingData') you can think of actions/mutations as a file system in a way. The deeper the modules are nested the deeper in the tree they are. so you could go store.commit('first/second/third/method') if you had a tree that was three levels deep. A: As another addition to the accepted answer, if you need to pass parameter(s) to the getter (for instance to fetch a specific item from the store collection), you need to pass it as follows: this.$store.getters['yourModuleName/someGetterMethod'](myParam) I don't think I like this notation very much, but it is what it is - at least for the moment. A: Try this approach! getCounter(){ return this.$store.getters['auth/getToken']; } auth is my module name and getToken is my getter. A: Using Vuex mapGetters and mapActions you can now do this pretty easily. But I agree, it still isn't very obvious in the documentation. Assuming your store module 'products' has a getter called 'mostPopular' and an action called 'clearWorkingData': <template> <div> <p>{{mostPopularProduct}}<p> <p><button @click="clearProductData">Clear data</button></p> </div> </template> <script> import { mapGetters, mapActions } from "vuex"; export default { computed: mapGetters({ mostPopularProduct: "products/mostPopular" }), methods: mapActions({ clearProductData: "products/clearWorkingData" }) } </script> A: The mapGetters helper simply maps store getters to local computed properties: import { mapGetters } from 'vuex' export default { // ... computed: { // mix the getters into computed with object spread operator ...mapGetters([ 'doneTodosCount', 'anotherGetter', // ... ]) } } If you want to map a getter to a different name, use an object: ...mapGetters({ // map `this.doneCount` to `this.$store.getters.doneTodosCount` doneCount: 'doneTodosCount' }) A: You have to be aware of using namespaced: true when configuring particular store object A: In Addition to the accepted answer, I feel it's not a good idea to mutate the state and commit the mutation directly in component. Thumb rule I follow is, Always use an action to commit the mutation and state only mutate inside mutations. Use getters to get a transformed state. Getters can be mapped to computed using mapGetters and actions can be mapped to methods using mapActions as below example // component.vue // namespace_name=products <template> <div> <p> This is awesome product {{getRecentProduct}} </p> </div> <button @click="onButtonClick()"> Clear recent</button> </template> <script> import { mapGetters, mapActions } from "vuex"; export default { computed: { ...mapGetters({ getRecentProduct: "products/getRecentProduct", }), anotherComputed(){ return "anotherOne" } }, methods: { ...mapActions({ clearRecentProduct: "products/clearRecentProduct", }), onButtonClick(){ this.clearRecentProduct(); /// Dispatch the action }, anotherMethods(){ console.log(this.getRecentProduct); // Access computed props } } }; </script> A: Here's how you can access vuex Getters & Mutations using Composition API (setup) <script setup> import { useStore } from 'vuex' const store = useStore(); var value = store.getters['subModuleName/getterMethod']; store.commit['subModuleName/MutationMethod']; </script>
How to access Vuex module getters and mutations?
I'm trying to switch to using Vuex instead of my homegrown store object, and I must say I'm not finding the docs as clear as elsewhere in the Vue.js world. Let's say I have a Vuex module called 'products', with its own state, mutations, getters, etc. How do I reference an action in that module called, say, 'clearWorking Data'? The docs give this example of accessing a module's state: store.state.a // -> moduleA's state But nothing I can see about getters, mutations, actions, etc.
[ "In Addition to the accepted answer I wanna provide you with a workarround for the getter which is missing in the answer.\nDebug the Store\nIn any case you can call console.log(this.$store) to debug the Store.\nIf you do so you will see the getters are prefixed with the namespace in their name.\n\nAccess namespaced getter\nthis.$store.getters['yourModuleName/someGetterMethod']\n\nDispatch namespaced\nthis.$store.dispatch('yourModuleName/doSomething')\n\nDispatch namespaced with params\nthis.$store.getters['yourModuleName/someGetterMethod'](myParam)\n\nConclusion\nThe key is to handle the namespace like a file System like Justin explained.\nEdit: found a nice library for handling vuex Store\nIn addition to the basic knowledge I'd like to add this vuex library as a nice addition for working effectivly and fast with the vuex store. https://github.com/davestewart/vuex-pathify .\nIt looks pretty interesting and cares much of the configuration for you and also allows you to handle 2waybinding directly with vuex.\n** Edit: Thanks to the other Answers. Added Dispatching method with params for wholeness.\n", "In your example it would be store.dispatch('products/clearWorkingData') you can think of actions/mutations as a file system in a way. The deeper the modules are nested the deeper in the tree they are.\nso you could go store.commit('first/second/third/method') if you had a tree that was three levels deep.\n", "As another addition to the accepted answer, if you need to pass parameter(s) to the getter (for instance to fetch a specific item from the store collection), you need to pass it as follows:\nthis.$store.getters['yourModuleName/someGetterMethod'](myParam)\n\nI don't think I like this notation very much, but it is what it is - at least for the moment.\n", "Try this approach!\ngetCounter(){\n return this.$store.getters['auth/getToken']; \n}\n\nauth is my module name and getToken is my getter.\n", "Using Vuex mapGetters and mapActions you can now do this pretty easily. But I agree, it still isn't very obvious in the documentation.\nAssuming your store module 'products' has a getter called 'mostPopular' and an action called 'clearWorkingData':\n<template>\n <div>\n <p>{{mostPopularProduct}}<p>\n <p><button @click=\"clearProductData\">Clear data</button></p>\n </div>\n</template>\n<script>\nimport { mapGetters, mapActions } from \"vuex\";\n\nexport default {\n computed: mapGetters({\n mostPopularProduct: \"products/mostPopular\"\n }),\n methods: mapActions({\n clearProductData: \"products/clearWorkingData\"\n })\n}\n</script>\n\n", "The mapGetters helper simply maps store getters to local computed properties:\n import { mapGetters } from 'vuex'\n\n export default {\n // ...\n computed: {\n // mix the getters into computed with object spread operator\n ...mapGetters([\n 'doneTodosCount',\n 'anotherGetter',\n // ...\n ])\n }\n}\nIf you want to map a getter to a different name, use an object:\n\n ...mapGetters({\n // map `this.doneCount` to `this.$store.getters.doneTodosCount`\n doneCount: 'doneTodosCount'\n})\n\n", "You have to be aware of using namespaced: true when configuring particular store object\n", "In Addition to the accepted answer, I feel it's not a good idea to mutate the state and commit the mutation directly in component. Thumb rule I follow is, Always use an action to commit the mutation and state only mutate inside mutations.\nUse getters to get a transformed state.\nGetters can be mapped to computed using mapGetters and actions can be mapped to methods using mapActions as below example\n// component.vue\n// namespace_name=products\n\n<template>\n <div>\n <p> This is awesome product {{getRecentProduct}} </p>\n </div>\n <button @click=\"onButtonClick()\"> Clear recent</button>\n</template>\n<script>\nimport { mapGetters, mapActions } from \"vuex\";\n\nexport default {\n computed: {\n ...mapGetters({\n getRecentProduct: \"products/getRecentProduct\",\n }),\n anotherComputed(){\n return \"anotherOne\"\n }\n },\n methods: {\n ...mapActions({\n clearRecentProduct: \"products/clearRecentProduct\",\n }),\n onButtonClick(){\n this.clearRecentProduct(); /// Dispatch the action \n },\n anotherMethods(){\n console.log(this.getRecentProduct); // Access computed props\n }\n }\n};\n</script>\n\n\n", "Here's how you can access vuex Getters & Mutations using Composition API (setup)\n<script setup>\nimport { useStore } from 'vuex'\n\nconst store = useStore();\n\nvar value = store.getters['subModuleName/getterMethod'];\n\nstore.commit['subModuleName/MutationMethod'];\n\n</script>\n\n" ]
[ 185, 42, 30, 20, 14, 1, 1, 0, 0 ]
[]
[]
[ "vue.js", "vuex" ]
stackoverflow_0041833424_vue.js_vuex.txt
Q: Can someone explain why this doeasn't work? The default constructor of "B" cannot be referenced -- it is a deleted function I'm currently making c++ project but this error is bothering me for long time and i cannot figure out why this doesn't work. I was searching about this error but still i don't understand it. Thanks in advance. #include <iostream> using namespace std; class A { public: int a = 0; A(int _a) : a(a) {} }; class B { public: A a; void test() { A a1(6); a = a1; } }; int main() { B b1; b1.test(); return 0; } I tried to initialized value in constructor in class and this worked but what if i don't want to do this? A: A doesn't have a default constructor so it cannot be default constructed. A class object must be fully initialized before entering the body of the constructor which means that in B you need to initialize a (either with data member init or with constructor list initialization). If for whatever reason you want to delay the initialization of a you have a few options. Depending on the semantics of it you could make it std::optional<A> a or std::unique_ptr<A>. A: First, your member initialization list in A's converting constructor is wrong. a(a) should be a(_a) instead. Second, A has a user-defined constructor, so its compiler-generated default constructor is implicitly delete'd. Thus, B::a can't be default-constructed, so B's compiler-generated default constructor is also implicitly delete'd. Thus, b1 in main() can't be default-constructed, either. If you want A to be default-constructible, you need to either: add a default constructor explicitly: class A { public: int a = 0; A() {}; // or: A() = default; // <-- HERE A(int _a) : a(_a) {} }; Change your converting constructor so it can also act as a default constructor: class A { public: int a = 0; A(int _a = 0) : a(_a) {} // <-- HERE }; Otherwise, you will have to add a default constructor to B to construct B::a with a value: class B { public: A a; B() : a(0) {} // <-- HERE void test() { A a1(6); a = a1; } };
Can someone explain why this doeasn't work? The default constructor of "B" cannot be referenced -- it is a deleted function
I'm currently making c++ project but this error is bothering me for long time and i cannot figure out why this doesn't work. I was searching about this error but still i don't understand it. Thanks in advance. #include <iostream> using namespace std; class A { public: int a = 0; A(int _a) : a(a) {} }; class B { public: A a; void test() { A a1(6); a = a1; } }; int main() { B b1; b1.test(); return 0; } I tried to initialized value in constructor in class and this worked but what if i don't want to do this?
[ "A doesn't have a default constructor so it cannot be default constructed.\nA class object must be fully initialized before entering the body of the constructor which means that in B you need to initialize a (either with data member init or with constructor list initialization).\nIf for whatever reason you want to delay the initialization of a you have a few options. Depending on the semantics of it you could make it std::optional<A> a or std::unique_ptr<A>.\n", "First, your member initialization list in A's converting constructor is wrong. a(a) should be a(_a) instead.\nSecond, A has a user-defined constructor, so its compiler-generated default constructor is implicitly delete'd.\nThus, B::a can't be default-constructed, so B's compiler-generated default constructor is also implicitly delete'd.\nThus, b1 in main() can't be default-constructed, either.\nIf you want A to be default-constructible, you need to either:\n\nadd a default constructor explicitly:\n\nclass A\n{\npublic:\n int a = 0;\n A() {}; // or: A() = default; // <-- HERE\n A(int _a) : a(_a) {}\n};\n\n\nChange your converting constructor so it can also act as a default constructor:\n\nclass A\n{\npublic:\n int a = 0;\n A(int _a = 0) : a(_a) {} // <-- HERE\n};\n\nOtherwise, you will have to add a default constructor to B to construct B::a with a value:\nclass B\n{\npublic:\n A a;\n B() : a(0) {} // <-- HERE\n void test()\n {\n A a1(6);\n a = a1;\n }\n};\n\n" ]
[ 2, 0 ]
[]
[]
[ "c++", "constructor", "default_constructor", "oop" ]
stackoverflow_0074661843_c++_constructor_default_constructor_oop.txt
Q: fresh laravel throught docker installation failing by searching for octan I run command to get new laravel 9 setup under docker with only mysql and redis containers by doing curl -s "https://laravel.build/example-app??with=mysql,redis" | bash, after that I run cd example-app && ./vendor/bin/sail up, and for some reason my php-fpm container not running correctly, I'm getting error: example-app-laravel.test-1 | 2022-08-04 20:59:27,326 INFO spawned: 'php' with pid 44 example-app-laravel.test-1 | example-app-laravel.test-1 | ERROR There are no commands defined in the "octane" namespace. example-app-laravel.test-1 | example-app-laravel.test-1 | 2022-08-04 20:59:28,193 INFO exited: php (exit status 1; not expected) but I do not use octane in this setup, I did not install it, I do not have it in compose.json. Okay to be clear I have another laravel project with octane,but it's not running, I have up and running only containers related to the current laravel setup, so why does it want octane from me? how can I run fresh laravel? A: Same here. I installed Octane in another Laravel project with sail and cannot start a fresh new Laravel project. Solution: run ./vendor/bin/sail build --no-cache under the new project. Try to start the server again ./vendor/bin/sail up
fresh laravel throught docker installation failing by searching for octan
I run command to get new laravel 9 setup under docker with only mysql and redis containers by doing curl -s "https://laravel.build/example-app??with=mysql,redis" | bash, after that I run cd example-app && ./vendor/bin/sail up, and for some reason my php-fpm container not running correctly, I'm getting error: example-app-laravel.test-1 | 2022-08-04 20:59:27,326 INFO spawned: 'php' with pid 44 example-app-laravel.test-1 | example-app-laravel.test-1 | ERROR There are no commands defined in the "octane" namespace. example-app-laravel.test-1 | example-app-laravel.test-1 | 2022-08-04 20:59:28,193 INFO exited: php (exit status 1; not expected) but I do not use octane in this setup, I did not install it, I do not have it in compose.json. Okay to be clear I have another laravel project with octane,but it's not running, I have up and running only containers related to the current laravel setup, so why does it want octane from me? how can I run fresh laravel?
[ "Same here. I installed Octane in another Laravel project with sail and cannot start a fresh new Laravel project.\nSolution: run ./vendor/bin/sail build --no-cache under the new project.\nTry to start the server again ./vendor/bin/sail up\n" ]
[ 0 ]
[]
[]
[ "docker", "laravel", "laravel_octane", "laravel_sail", "php" ]
stackoverflow_0073242261_docker_laravel_laravel_octane_laravel_sail_php.txt
Q: What's the need to use Upcasting in java? I've gone through most of the papers in the net, but I'm still not able to understand, why we have to use upcasting. class Animal { public void callme() { System.out.println("In callme of Animal"); } } class Dog extends Animal { public void callme() { System.out.println("In callme of Dog"); } public void callme2() { System.out.println("In callme2 of Dog"); } } public class UseAnimlas { public static void main (String [] args) { Dog d = new Dog(); Animal a = (Animal)d; d.callme(); a.callme(); ((Dog) a).callme2(); } } You can consider this example for upcasting. What's the use of upcasting here? Both d and a giving the same output! A: In most situations, an explicit upcast is entirely unnecessary and has no effect. In your example, the explicit upcast Animal a = (Animal)d; could be replaced with this: Animal a = d; // implicit upcast The purpose of an implicit upcast (for a Java object type) is to "forget" static type information so that an object with a specific type can be used in a situation that requires a more general type. This affects compile-time type checking and overload resolution, but not run-time behavior. (For a primitive type, an upcast results in a conversion, and can in some cases result in loss of precision; e.g. long -> float.) However, there are situations where the presence of an explicit upcast changes the meaning of the statement / expression. One situation where it is necessary to use upcasting in Java is when you want to force a specific method overload to be used; e.g. suppose that we have overloaded methods: public void doIt(Object o)... public void doIt(String s)... If I have a String and I want to call the first overload rather than the second, I have to do this: String arg = ... doIt((Object) arg); A related case is: doIt((Object) null); where the code won't compile without the type cast. I'm not sure if this counts as an upcast (see JLS 5.1.13 last paragraph) but it should be mentioned anyway. A second situation involves varadic parameters: public void doIt(Object... args)... Object[] foo = ... doIt(foo); // passes foo as the argument array doIt((Object) foo); // passes new Object[]{foo} as the argument array. A third situation is when performing operations on primitive numeric types; e.g. int i1 = ... int i2 = ... long res = i1 + i2; // 32 bit signed arithmetic ... might overflow long res2 = ((long) i1) + i2; // 64 bit signed arithmetic ... won't overflow A: What's the need to use Upcasting in java? Not sure if you got the terminology right, but here is a quote to clarify: upcasting Doing a cast from a derived class to a more general base class. And here's one scenario where it actually matters: class A { } class B extends A { } public class Test { static void method(A a) { System.out.println("Method A"); } static void method(B b) { System.out.println("Method B"); } public static void main(String[] args) { B b = new B(); method(b); // "Method B" // upcasting a B into an A: method((A) b); // "Method A" } } Another more subtle situation (related to access modifiers) is described here: Java Oddity: How an upcast can save the day A: Upcasting has absolutely no meaning in your example (in fact I can't imagine any case where it has any) and should be avoided as it only confuses developers. Some IDEs (IntelliJ for sure) will issue a warning in this line and suggest removing upcasting). EDIT: This code gives the same results because all object methods in Java are virtual, which means the target method is discovered by the actual type of the object at runtime rather than by reference type. Try making callme() static and see what happens. A: Upcasting can be necessary when you have overloaded methods and do not want to call the specialized one, like aioobe wrote. (You could have assigned to a new variable of type A instead there.) Another example where an upcast was necessary involved the ?: operator, but I don't remember it now. And sometimes you need upcasts in the case of varargs-methods: public void doSomething(Object... bla) {} If we want to pass an Object[] array as a single parameter (not its objects as individual ones), we must write either doSomething((Object)array); or doSomething(new Object[]{array}); A: Consider a scenario, Bank is a class that provides method to get the rate of interest. But, rate of interest may differ according to banks. For example, SBI, ICICI and AXIS banks are providing 8.4%, 7.3% and 9.7% rate of interest. class Bank{ float getRateOfInterest(){return 0;} } class SBI extends Bank{ float getRateOfInterest(){return 8.4f;} } class ICICI extends Bank{ float getRateOfInterest(){return 7.3f;} } class AXIS extends Bank{ float getRateOfInterest(){return 9.7f;} } class TestPolymorphism{ public static void main(String args[]){ Bank b; b=new SBI(); System.out.println("SBI Rate of Interest: "+b.getRateOfInterest()); b=new ICICI(); System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest()); b=new AXIS(); System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest()); } } Output: SBI Rate of Interest: 8.4 ICICI Rate of Interest: 7.3 AXIS Rate of Interest: 9.7 A: Some answers: Upcasting happens implicitly any time you pass a specific object to a method accepting a more generic object. In your example, when you pass a Dog to a method accepting an Animal, upcasting happens although you don't do it explicitly with parentheses. As mentioned by others here, in method overloading scenarios where you have general and specific methods. In your example, imagine a method accepting a Dog, and another with the same name accepting an Animal. If for some reason you need to call the general version, you need to explicitly upcast your object. Explicit upcasting can be used as a form of documentation; if at some point in your code you no longer need refer to a Dog as a Dog but continue treating it as an Animal, it may be a good idea to upcast to let other developers understand what's going on. A: A Simple explaination of Upcasting is... There are 2 classes one is parent class (Demo1) second is its subclass (Demo). If Method run1 does not have parameters then the output of method will be same. There is no use of Upcasting. class Demo1{ void run1(){ System.out.println("hello"); } } class Demo extends Demo1 { void run1(){ System.out.println("hello1"); } public static void main(String args[]){ Demo d = new Demo(); d.run1(); Demo1 d1 = new Demo(); d1.run1(); } } Output for d.run1(); and d1.run1(); will be same. output: hello1 If we uses Parameterised overloading then the use of upcasting can be seen clearly. There is the sense for Upcasting. class Demo1{ void run1(int a){ System.out.println(a); } } class Demo extends Demo1 { void run1(String b){ System.out.println(b); } public static void main(String args[]){ Demo d = new Demo(); d.run1("b"); Demo1 d1 = new Demo(); d1.run1(2); } } Output for d.run1(); and d1.run1(); will be Different. output: b 2 A: Given that Java's objects methods are virtual by default, I do not see any use for upcasting at all. Where have you seen tutorials reporting that upcasting was necessary? That is the first time I hear of it for Java. (Note that it has a meaning in C# or C++ - but it is usually a mark of bad design.) A: When we upcast, we can only access the over-ridden methods but not all the methods of the child class. Example code: //class 1 public class Class1 { protected int value; public Class1(int value) { this.value = value; } protected int getValue() { return value; } } // class 2 public class Class2 extends Class1 { public Class2(int value) { super(value); } @Override public int getValue() { return super.getValue()+1; } public int getHundred() { return 100; } } //Main method public class Main { public static void main(String args[]) { Class1 cls2 = new Class2(10); cls2.getValue(); cls2.getHundred() // gives compile error } }
What's the need to use Upcasting in java?
I've gone through most of the papers in the net, but I'm still not able to understand, why we have to use upcasting. class Animal { public void callme() { System.out.println("In callme of Animal"); } } class Dog extends Animal { public void callme() { System.out.println("In callme of Dog"); } public void callme2() { System.out.println("In callme2 of Dog"); } } public class UseAnimlas { public static void main (String [] args) { Dog d = new Dog(); Animal a = (Animal)d; d.callme(); a.callme(); ((Dog) a).callme2(); } } You can consider this example for upcasting. What's the use of upcasting here? Both d and a giving the same output!
[ "In most situations, an explicit upcast is entirely unnecessary and has no effect.\nIn your example, the explicit upcast\n Animal a = (Animal)d;\n\ncould be replaced with this:\n Animal a = d; // implicit upcast\n\nThe purpose of an implicit upcast (for a Java object type) is to \"forget\" static type information so that an object with a specific type can be used in a situation that requires a more general type. This affects compile-time type checking and overload resolution, but not run-time behavior.\n(For a primitive type, an upcast results in a conversion, and can in some cases result in loss of precision; e.g. long -> float.)\n\nHowever, there are situations where the presence of an explicit upcast changes the meaning of the statement / expression.\nOne situation where it is necessary to use upcasting in Java is when you want to force a specific method overload to be used; e.g. suppose that we have overloaded methods:\npublic void doIt(Object o)...\npublic void doIt(String s)...\n\nIf I have a String and I want to call the first overload rather than the second, I have to do this:\nString arg = ...\n\ndoIt((Object) arg);\n\nA related case is:\ndoIt((Object) null);\n\nwhere the code won't compile without the type cast. I'm not sure if this counts as an upcast (see JLS 5.1.13 last paragraph) but it should be mentioned anyway.\nA second situation involves varadic parameters:\npublic void doIt(Object... args)...\n\nObject[] foo = ...\n\ndoIt(foo); // passes foo as the argument array\ndoIt((Object) foo); // passes new Object[]{foo} as the argument array.\n\nA third situation is when performing operations on primitive numeric types; e.g.\nint i1 = ...\nint i2 = ...\nlong res = i1 + i2; // 32 bit signed arithmetic ... might overflow\nlong res2 = ((long) i1) + i2; // 64 bit signed arithmetic ... won't overflow\n\n", "\nWhat's the need to use Upcasting in java?\n\nNot sure if you got the terminology right, but here is a quote to clarify:\n\nupcasting\nDoing a cast from a derived class to a more general base class. \n\nAnd here's one scenario where it actually matters:\nclass A {\n}\n\nclass B extends A {\n}\n\npublic class Test {\n\n static void method(A a) {\n System.out.println(\"Method A\");\n }\n\n static void method(B b) {\n System.out.println(\"Method B\");\n }\n\n public static void main(String[] args) {\n B b = new B();\n method(b); // \"Method B\"\n\n // upcasting a B into an A:\n method((A) b); // \"Method A\"\n }\n}\n\nAnother more subtle situation (related to access modifiers) is described here: Java Oddity: How an upcast can save the day\n", "Upcasting has absolutely no meaning in your example (in fact I can't imagine any case where it has any) and should be avoided as it only confuses developers. Some IDEs (IntelliJ for sure) will issue a warning in this line and suggest removing upcasting).\nEDIT: This code gives the same results because all object methods in Java are virtual, which means the target method is discovered by the actual type of the object at runtime rather than by reference type. Try making callme() static and see what happens.\n", "Upcasting can be necessary when you have overloaded methods and do not want to call the specialized one, like aioobe wrote. (You could have assigned to a new variable of type A instead there.)\nAnother example where an upcast was necessary involved the ?: operator, but I don't remember it now. And sometimes you need upcasts in the case of varargs-methods:\npublic void doSomething(Object... bla) {}\n\nIf we want to pass an Object[] array as a single parameter (not its objects as individual ones), we must write either \ndoSomething((Object)array);\n\nor\ndoSomething(new Object[]{array});\n\n", "Consider a scenario, Bank is a class that provides method to get the rate of interest. But, rate of interest may differ according to banks. For example, SBI, ICICI and AXIS banks are providing 8.4%, 7.3% and 9.7% rate of interest.\nclass Bank{ \n float getRateOfInterest(){return 0;} \n}\n\nclass SBI extends Bank{ \n float getRateOfInterest(){return 8.4f;} \n}\n\nclass ICICI extends Bank{ \n float getRateOfInterest(){return 7.3f;} \n}\n\nclass AXIS extends Bank{ \n float getRateOfInterest(){return 9.7f;} \n} \n\nclass TestPolymorphism{ \n public static void main(String args[]){ \n Bank b; \n b=new SBI(); \n System.out.println(\"SBI Rate of Interest: \"+b.getRateOfInterest()); \n b=new ICICI(); \n System.out.println(\"ICICI Rate of Interest: \"+b.getRateOfInterest()); \n b=new AXIS(); \n System.out.println(\"AXIS Rate of Interest: \"+b.getRateOfInterest()); \n } \n}\n\nOutput:\nSBI Rate of Interest: 8.4\nICICI Rate of Interest: 7.3\nAXIS Rate of Interest: 9.7\n\n", "Some answers:\n\nUpcasting happens implicitly any time you pass a specific object to a method accepting a more generic object. In your example, when you pass a Dog to a method accepting an Animal, upcasting happens although you don't do it explicitly with parentheses.\nAs mentioned by others here, in method overloading scenarios where you have general and specific methods. In your example, imagine a method accepting a Dog, and another with the same name accepting an Animal. If for some reason you need to call the general version, you need to explicitly upcast your object.\nExplicit upcasting can be used as a form of documentation; if at some point in your code you no longer need refer to a Dog as a Dog but continue treating it as an Animal, it may be a good idea to upcast to let other developers understand what's going on.\n\n", "A Simple explaination of Upcasting is...\nThere are 2 classes one is parent class (Demo1) second is its subclass (Demo). \n\nIf Method run1 does not have parameters then the output of method will be same. There is no use of Upcasting. \n class Demo1{\n\n void run1(){\n System.out.println(\"hello\"); \n }\n }\n\nclass Demo extends Demo1 {\n\nvoid run1(){\nSystem.out.println(\"hello1\"); \n}\n\npublic static void main(String args[]){\n\n Demo d = new Demo();\n d.run1();\n\n Demo1 d1 = new Demo();\n d1.run1();\n\n }\n }\n\nOutput for d.run1(); and d1.run1(); will be same. \n output: hello1\n\n\nIf we uses Parameterised overloading then the use of upcasting can be seen clearly. There is the sense for Upcasting.\n class Demo1{\n\n void run1(int a){\n\n System.out.println(a); \n }\n }\n\n class Demo extends Demo1 {\n\n void run1(String b){\n\n System.out.println(b); \n }\n\n public static void main(String args[]){\n\n Demo d = new Demo();\n d.run1(\"b\");\n\n Demo1 d1 = new Demo();\n d1.run1(2);\n\n}\n}\n\n\n\nOutput for d.run1(); and d1.run1(); will be Different.\noutput: b\n 2\n\n", "Given that Java's objects methods are virtual by default, I do not see any use for upcasting at all.\nWhere have you seen tutorials reporting that upcasting was necessary? That is the first time I hear of it for Java. (Note that it has a meaning in C# or C++ - but it is usually a mark of bad design.)\n", "When we upcast, we can only access the over-ridden methods but not all the methods of the child class.\nExample code:\n//class 1\npublic class Class1 {\n protected int value;\n\n public Class1(int value) {\n this.value = value;\n }\n\n protected int getValue() {\n return value;\n }\n}\n\n// class 2\npublic class Class2 extends Class1 {\n\n public Class2(int value) {\n super(value);\n }\n\n @Override\n public int getValue() {\n return super.getValue()+1;\n }\n\n public int getHundred() {\n return 100;\n }\n}\n\n\n\n//Main method\npublic class Main {\n public static void main(String args[]) {\n Class1 cls2 = new Class2(10);\n cls2.getValue();\n cls2.getHundred() // gives compile error\n }\n}\n\n" ]
[ 26, 12, 5, 5, 3, 2, 1, 0, 0 ]
[]
[]
[ "java" ]
stackoverflow_0005361999_java.txt
Q: Why can't I install Flutter app in real Android phone? I asked a question and here is another question related to this one. I have uploaded .apk file (build/app/outputs/flutter-apk/app-debug.apk) to Google Drive and downloaded .apk file in real Android phone, but I can't install the application is in a real Android phone. I downloaded the .apk file: When I click on the "app-debug.apk" item, the following screen pops up: When I click the install button, it loads and displays the following screen: Also, the Android version of my Android phone is 8.1.0. I didn't share the code because I don't think the code has anything to do with this. Why can't I install Flutter app in real Android phone? I would appreciate any help. Thank you in advance! A: There are 2 options: You can build your app from Android Studio (or another IDE) - Instead of selecting an emulator, select your own Android phone. You have to switch your phone to Developer mode. Publish your app on Google play console, internal testing or closed testing, add yourself as a tester then install the app. You'll need a Developer account.
Why can't I install Flutter app in real Android phone?
I asked a question and here is another question related to this one. I have uploaded .apk file (build/app/outputs/flutter-apk/app-debug.apk) to Google Drive and downloaded .apk file in real Android phone, but I can't install the application is in a real Android phone. I downloaded the .apk file: When I click on the "app-debug.apk" item, the following screen pops up: When I click the install button, it loads and displays the following screen: Also, the Android version of my Android phone is 8.1.0. I didn't share the code because I don't think the code has anything to do with this. Why can't I install Flutter app in real Android phone? I would appreciate any help. Thank you in advance!
[ "There are 2 options:\n\nYou can build your app from Android Studio (or another IDE) - Instead of selecting an emulator, select your own Android phone. You have to switch your phone to Developer mode.\n\nPublish your app on Google play console, internal testing or closed testing, add yourself as a tester then install the app. You'll need a Developer account.\n\n\n" ]
[ 0 ]
[]
[]
[ "android", "flutter" ]
stackoverflow_0074663783_android_flutter.txt
Q: Are there any Java Frameworks for binary file parsing? My problem is, that I want to parse binary files of different types with a generic parser which is implemented in JAVA. Maybe describing the file format with a configuration file which is read by the parser or creating Java classes which parse the files according to some sort of parsing rules. I have searched quite a bit on the internet but found almost nothing on this topic. What I have found are just things which deal with compiler-generators (Jay, Cojen, etc.) but I don't think that I can use them to generate something for parsing binary files. But I could be wrong on that assumption. Are there any frameworks which deal especially with easy parsing of binary files or can anyone give me a hint how I could use parser/compiler-generators to do so? Update: I'm looking for something where I can write a config-file like file: header: FIXED("MAGIC") body: content(10) content: value1: BYTE value2: LONG value3: STRING(10) and it generates automatically something which parses files which start with "MAGIC", followed by ten times the content-package (which itself consists of a byte, a long and a 10-byte string). Update2: I found something comparable what I'm looking for, "Construct", but sadly this is a Python-Framework. Maybe this helps someone to get an idea, what I'm looking for. A: Using Preon: public class File { @BoundString(match="MAGIC") private String header; @BoundList(size="10", type=Body.class) private List<Body> body; private static class Body { @Bound byte value1; @Bound long value2; @BoundString(size="10") String value3; } } Decoding data: Codec<File> codec = Codecs.create(File.class); File file = codecs.decode(codec, buffer); Let me know if you are running into problems. A: give a try to preon A: I have used DataInputStream for reading binary files and I write the rules in Java. ;) Binary files can have just about any format so there is no general rule for how to read them. Frameworks don't always make things simpler. In your case, the description file is longer than the code to just read the data using a DataInputStream. public static void parse(DataInput in) throws IOException { // file: // header: FIXED("MAGIC") String header = readAsString(in, 5); assert header.equals("MAGIC"); // body: content(10) // ?? not sure what this means // content: for(int i=0;i<10;i++) { // value1: BYTE byte value1 = in.readByte(); // value2: LONG long value2 = in.readLong(); // value3: STRING(10) String value3 = readAsString(in, 10); } } public static String readAsString(DataInput in, int len) throws IOException { byte[] bytes = new byte[len]; in.readFully(bytes); return new String(bytes); } If you want to have a configuration file you could use a Java Configuration File. http://www.google.co.uk/search?q=java+configuration+file A: Google's Protocol Buffers A: Parser combinator library is an option. JParsec works fine, however it could be slow. A: I have been developing a framework for Java which allows to parse binary data https://github.com/raydac/java-binary-block-parser in the case you should just describe structure of your binary file in pseudolanguage A: Recommend you a java tool(FastProto) to parse binary quickly. import org.indunet.fastproto.annotation.*; public class File { @StringType(offset = 0, length = 5) String header; @BinaryType(offset = 6, length = 1) byte[] body; } byte[] bytes = ... // the file binary File file = FastProto.parse(bytes, File.class); public class Content { @Int8Type(offset = 0) Byte b1; // byte @Int64Type(offset = 1) Long i64; // long @StringType(offset = 9, length = 10) String str; // string } // Then call the parse() 10 more times, each time remove the // parsed part from the body. Content content = FastProto.parse(body, Content.class) If the project can solve your problem, please give a star, thanks. GitHub Repo: https://github.com/indunet/fastproto
Are there any Java Frameworks for binary file parsing?
My problem is, that I want to parse binary files of different types with a generic parser which is implemented in JAVA. Maybe describing the file format with a configuration file which is read by the parser or creating Java classes which parse the files according to some sort of parsing rules. I have searched quite a bit on the internet but found almost nothing on this topic. What I have found are just things which deal with compiler-generators (Jay, Cojen, etc.) but I don't think that I can use them to generate something for parsing binary files. But I could be wrong on that assumption. Are there any frameworks which deal especially with easy parsing of binary files or can anyone give me a hint how I could use parser/compiler-generators to do so? Update: I'm looking for something where I can write a config-file like file: header: FIXED("MAGIC") body: content(10) content: value1: BYTE value2: LONG value3: STRING(10) and it generates automatically something which parses files which start with "MAGIC", followed by ten times the content-package (which itself consists of a byte, a long and a 10-byte string). Update2: I found something comparable what I'm looking for, "Construct", but sadly this is a Python-Framework. Maybe this helps someone to get an idea, what I'm looking for.
[ "Using Preon:\npublic class File {\n\n @BoundString(match=\"MAGIC\")\n private String header;\n\n @BoundList(size=\"10\", type=Body.class)\n private List<Body> body;\n\n private static class Body {\n\n @Bound\n byte value1;\n\n @Bound\n long value2;\n\n @BoundString(size=\"10\")\n String value3;\n\n }\n\n\n}\n\nDecoding data:\nCodec<File> codec = Codecs.create(File.class);\nFile file = codecs.decode(codec, buffer);\n\nLet me know if you are running into problems.\n", "give a try to preon\n", "I have used DataInputStream for reading binary files and I write the rules in Java. ;) Binary files can have just about any format so there is no general rule for how to read them.\nFrameworks don't always make things simpler. In your case, the description file is longer than the code to just read the data using a DataInputStream.\npublic static void parse(DataInput in) throws IOException {\n// file:\n// header: FIXED(\"MAGIC\")\n String header = readAsString(in, 5);\n assert header.equals(\"MAGIC\");\n// body: content(10)\n// ?? not sure what this means\n// content:\n for(int i=0;i<10;i++) {\n// value1: BYTE\n byte value1 = in.readByte();\n// value2: LONG\n long value2 = in.readLong();\n// value3: STRING(10)\n String value3 = readAsString(in, 10);\n }\n}\n\npublic static String readAsString(DataInput in, int len) throws IOException {\n byte[] bytes = new byte[len];\n in.readFully(bytes);\n return new String(bytes);\n}\n\nIf you want to have a configuration file you could use a Java Configuration File. http://www.google.co.uk/search?q=java+configuration+file\n", "Google's Protocol Buffers\n", "Parser combinator library is an option. JParsec works fine, however it could be slow.\n", "I have been developing a framework for Java which allows to parse binary data https://github.com/raydac/java-binary-block-parser\nin the case you should just describe structure of your binary file in pseudolanguage\n", "Recommend you a java tool(FastProto) to parse binary quickly.\nimport org.indunet.fastproto.annotation.*;\n\npublic class File {\n @StringType(offset = 0, length = 5)\n String header;\n\n @BinaryType(offset = 6, length = 1)\n byte[] body;\n}\n\nbyte[] bytes = ... // the file binary\nFile file = FastProto.parse(bytes, File.class);\n\npublic class Content {\n @Int8Type(offset = 0)\n Byte b1; // byte \n \n @Int64Type(offset = 1)\n Long i64; // long\n\n @StringType(offset = 9, length = 10)\n String str; // string\n}\n\n// Then call the parse() 10 more times, each time remove the \n// parsed part from the body.\nContent content = FastProto.parse(body, Content.class)\n\n\nIf the project can solve your problem, please give a star, thanks.\nGitHub Repo: https://github.com/indunet/fastproto\n" ]
[ 12, 11, 9, 3, 1, 1, 0 ]
[ "You can parse binary files with parsers like JavaCC. Here you can find a simple example. Probably it's a bit more difficult than parsing text files.\n", "Have you looking into the world of parsers. A good parser is yacc, and there may be a port of it for java.\n" ]
[ -2, -3 ]
[ "binary_data", "file_io", "java", "parsing" ]
stackoverflow_0000644737_binary_data_file_io_java_parsing.txt
Q: Function extends object with properties of type any vs unknown In the below type definitions why do P1 and P2 have different values? type P1 = (() => 22) extends {[k:string]:any} ? 1:2 //`P1 == 1` type P2 = (() => 22) extends {[k:string]:unknown} ? 1:2 //`P2 == 2` A: See Breaking Change: { [k: string]: unknown } is no longer a wildcard assignment target for an authoritative answer. The index signature {[k: string]: any} behaves specially in Typescript: it's a valid assignment target for any object type. Usually types like () => 22 are not given implicit index signatures, and so it is an error to assign () => 22 to {[k: string]: unknown}. Only when the property type is any do you get the special permissive behavior: let anyRec: { [k: string]: any }; anyRec = () => 22; // okay let unkRec: { [k: string]: unknown }; unkRec = () => 22; // error So that's why P1 and P2 differ. Playground link to code
Function extends object with properties of type any vs unknown
In the below type definitions why do P1 and P2 have different values? type P1 = (() => 22) extends {[k:string]:any} ? 1:2 //`P1 == 1` type P2 = (() => 22) extends {[k:string]:unknown} ? 1:2 //`P2 == 2`
[ "See Breaking Change: { [k: string]: unknown } is no longer a wildcard assignment target for an authoritative answer.\nThe index signature {[k: string]: any} behaves specially in Typescript: it's a valid assignment target for any object type. Usually types like () => 22 are not given implicit index signatures, and so it is an error to assign () => 22 to {[k: string]: unknown}. Only when the property type is any do you get the special permissive behavior:\nlet anyRec: { [k: string]: any };\nanyRec = () => 22; // okay\n\nlet unkRec: { [k: string]: unknown };\nunkRec = () => 22; // error\n\nSo that's why P1 and P2 differ.\nPlayground link to code\n" ]
[ 1 ]
[ "In the first type definition, P1, the type of () => 22 is compared to an object with a string index and a value of any. Since a function can be converted to an object with a call property, the comparison returns true, and P1 is assigned the value of 1.\nIn the second type definition, P2, the type of () => 22 is compared to an object with a string index and a value of unknown. In this case, the comparison returns false, as a function cannot be directly converted to an object with a unknown value. That's why P2 is assigned the value of 2.\n" ]
[ -2 ]
[ "typescript" ]
stackoverflow_0074661730_typescript.txt
Q: Close video player on IOS when ended with html, javascript i am using html,js to create a tag . When i play video on browser of Android Device, open full screen to watch. After video end, it will be close because i used JS on this. But with IOS, i watched with safari, it not close when ended of video, it just stop and doesnt close video player. After researched, i know different between ios player and another device. HTML Code : <video id="my-video" class="video-js"></video> JS Code : player.on('ended', function () { alert("closed ios player") } Some body help me : How to close ios player when end video with html and js IOS Player Im trying to find another help me close ios player when ended video with HTML JS A: Your code isn't closing the video player. Fix: player.on( 'ended', function () { if( Document.exitFullscreen ) Document.exitFullscreen(); if( Document.webkitExitFullscreen ) Document.webkitExitFullscreen(); } );
Close video player on IOS when ended with html, javascript
i am using html,js to create a tag . When i play video on browser of Android Device, open full screen to watch. After video end, it will be close because i used JS on this. But with IOS, i watched with safari, it not close when ended of video, it just stop and doesnt close video player. After researched, i know different between ios player and another device. HTML Code : <video id="my-video" class="video-js"></video> JS Code : player.on('ended', function () { alert("closed ios player") } Some body help me : How to close ios player when end video with html and js IOS Player Im trying to find another help me close ios player when ended video with HTML JS
[ "Your code isn't closing the video player. Fix:\nplayer.on( 'ended', function () {\n if( Document.exitFullscreen ) Document.exitFullscreen();\n if( Document.webkitExitFullscreen ) Document.webkitExitFullscreen();\n} );\n\n" ]
[ 0 ]
[]
[]
[ "html", "ios", "javascript" ]
stackoverflow_0074663738_html_ios_javascript.txt
Q: Set margin on every page dompdf plugin I need to set margin on every page using dompdf like image below (page 2) this my fully code Can anyone help for my problem ? Thanks A: To set the margin on every page when using the DOMPDF plugin, you can use the set_paper() method to specify the page size and margins. This method accepts a string argument that specifies the page size and margins in the format "size:widthxheight;margin:topxrightxbottomxleft". Here is an example of how you can use the set_paper() method to set the margin on every page: // Create a new DOMPDF instance $dompdf = new DOMPDF(); // Set the page size and margins $dompdf->set_paper("A4", "margin:1in"); // Load and render your HTML content $dompdf->load_html($html); $dompdf->render(); // Output the PDF document $dompdf->stream(); In the example above, we create a new DOMPDF instance and use the set_paper() method to set the page size to "A4" and the margins to 1 inch. We then load and render the HTML content, and output the PDF document using the stream() method. You can customize the page size and margins by modifying the arguments passed to the set_paper() method. For example, if you want to set the margins to 0.5 inches on the top and bottom, and 1 inch on the left and right, you can use the following syntax: $dompdf->set_paper("A4", "margin:0.5in 1in"); A: solved the problem by changing some css. @page { margin: 240px 25px 100px 25px; } header { position: fixed; top: -220px; left: 0px; right: 0px; height: 90px; } and delete main css /* main { margin-top: 120px; } */
Set margin on every page dompdf plugin
I need to set margin on every page using dompdf like image below (page 2) this my fully code Can anyone help for my problem ? Thanks
[ "To set the margin on every page when using the DOMPDF plugin, you can use the set_paper() method to specify the page size and margins. This method accepts a string argument that specifies the page size and margins in the format \"size:widthxheight;margin:topxrightxbottomxleft\".\nHere is an example of how you can use the set_paper() method to set the margin on every page:\n// Create a new DOMPDF instance\n$dompdf = new DOMPDF();\n\n// Set the page size and margins\n$dompdf->set_paper(\"A4\", \"margin:1in\");\n\n// Load and render your HTML content\n$dompdf->load_html($html);\n$dompdf->render();\n\n// Output the PDF document\n$dompdf->stream();\n\nIn the example above, we create a new DOMPDF instance and use the set_paper() method to set the page size to \"A4\" and the margins to 1 inch. We then load and render the HTML content, and output the PDF document using the stream() method.\nYou can customize the page size and margins by modifying the arguments passed to the set_paper() method. For example, if you want to set the margins to 0.5 inches on the top and bottom, and 1 inch on the left and right, you can use the following syntax:\n$dompdf->set_paper(\"A4\", \"margin:0.5in 1in\");\n\n", "solved the problem by changing some css.\n@page {\n margin: 240px 25px 100px 25px;\n }\n\n header {\n position: fixed;\n top: -220px;\n left: 0px;\n right: 0px;\n height: 90px;\n }\n\nand delete main css\n/* main {\n margin-top: 120px;\n\n } */\n\n" ]
[ 0, 0 ]
[]
[]
[ "codeigniter", "css", "dompdf", "html", "php" ]
stackoverflow_0074663651_codeigniter_css_dompdf_html_php.txt
Q: Getting multiple variables from a read in line I am having trouble getting multiple number vars from a read in line. For a single value I can do strtol(), but how can I get the float and long values of a sentence that is similar to as follows. Please aim 3.567 degrees at a height of 5 meters. I tried doing two different calls to my buffer sentence, however it got neither of my values. I have no issues with get single values, but with to, I get 0.000 from my strtof call and 0 from mmy strtol call. A: ASSUMING YOU KNOW IN WHICH ORDER THE VALUES WILL BE IN Here is an example of how you can get multiple numeric values from a string: #include <stdio.h> #include <stdlib.h> int main() { // The string to parse char *str = "Please aim 3.567 degrees at a height of 5 meters."; // Variables to store the values float degrees; int height; // Parse the string and store the values in the variables // you can use sscanf, fscanf, scanf sscanf(str, "Please aim %f degrees at a height of %d meters.", &degrees, &height); // Print the values printf("degrees: %f\n", degrees); printf("height: %d\n", height); return 0; } In this code, the sscanf() function is used to parse the string and extract the values of the degrees and height variables. The sscanf() function takes the string to parse as the first argument, and a format string containing the conversion specifiers for the values to extract as the second argument. The & operator is used to pass the addresses of the degrees and height variables, so that the sscanf() function can store the extracted values in those variables. After calling the sscanf() function, the degrees and height variables are printed to the console to verify that the values were extracted correctly. -chatgpt A: Assuming that the input always starts with the string "Please aim ", followed by a floating-point number, followed by the string " degrees at a height of ", followed by an integer, followed by the string " meters.", then you can use the functions strtof and strtol, but you must skip the strings first, for example like this: #include <stdio.h> #include <stdlib.h> #include <string.h> int main( void ) { char *line = "Please aim 3.567 degrees at a height of 5 meters."; char *part1 = "Please aim "; char *part2 = " degrees at a height of "; char *part3 = " meters."; float degrees; long height; size_t part1_len = strlen( part1 ); size_t part2_len = strlen( part2 ); size_t part3_len = strlen( part3 ); //make p point to start of line char *p = line; char *q; //verify that the line starts with part1 and skip it if ( strncmp( p, part1, part1_len ) != 0 ) { fprintf( stderr, "Unable to find part1!\n" ); exit( EXIT_FAILURE ); } p += part1_len; //attempt to convert degrees value and skip it degrees = strtof( p, &q ); if ( p == q ) { fprintf( stderr, "Error converting degrees!\n" ); exit( EXIT_FAILURE ); } p = q; //verify that the line continues with part2 and skip it if ( strncmp( p, part2, part2_len ) != 0 ) { fprintf( stderr, "Unable to find part2!\n" ); exit( EXIT_FAILURE ); } p += part2_len; //attempt to convert height value and skip it height = strtol( p, &q, 10 ); if ( p == q ) { fprintf( stderr, "Error converting height!\n" ); exit( EXIT_FAILURE ); } p = q; //verify that the line continues with part3 and skip it if ( strncmp( p, part3, part3_len ) != 0 ) { fprintf( stderr, "Unable to find part3!\n" ); exit( EXIT_FAILURE ); } p += part3_len; //verify that we have reached the end of the string if ( *p != '\0' ) { fprintf( stderr, "Unexpected character encountered!\n" ); exit( EXIT_FAILURE ); } //print the results printf( "Results:\n" "Degrees: %f\n" "Height: %ld\n", degrees, height ); } This program has the following output: Results: Degrees: 3.567000 Height: 5
Getting multiple variables from a read in line
I am having trouble getting multiple number vars from a read in line. For a single value I can do strtol(), but how can I get the float and long values of a sentence that is similar to as follows. Please aim 3.567 degrees at a height of 5 meters. I tried doing two different calls to my buffer sentence, however it got neither of my values. I have no issues with get single values, but with to, I get 0.000 from my strtof call and 0 from mmy strtol call.
[ "ASSUMING YOU KNOW IN WHICH ORDER THE VALUES WILL BE IN\nHere is an example of how you can get multiple numeric values from a string:\n#include <stdio.h>\n#include <stdlib.h>\n\nint main() {\n // The string to parse\n char *str = \"Please aim 3.567 degrees at a height of 5 meters.\";\n\n // Variables to store the values\n float degrees;\n int height;\n\n // Parse the string and store the values in the variables\n // you can use sscanf, fscanf, scanf\n sscanf(str, \"Please aim %f degrees at a height of %d meters.\", &degrees, &height);\n\n // Print the values\n printf(\"degrees: %f\\n\", degrees);\n printf(\"height: %d\\n\", height);\n\n return 0;\n}\n\n\nIn this code, the sscanf() function is used to parse the string and extract the values of the degrees and height variables. The sscanf() function takes the string to parse as the first argument, and a format string containing the conversion specifiers for the values to extract as the second argument. The & operator is used to pass the addresses of the degrees and height variables, so that the sscanf() function can store the extracted values in those variables.\nAfter calling the sscanf() function, the degrees and height variables are printed to the console to verify that the values were extracted correctly.\n-chatgpt\n", "Assuming that the input always starts with the string \"Please aim \", followed by a floating-point number, followed by the string \" degrees at a height of \", followed by an integer, followed by the string \" meters.\", then you can use the functions strtof and strtol, but you must skip the strings first, for example like this:\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint main( void )\n{\n char *line = \"Please aim 3.567 degrees at a height of 5 meters.\";\n\n char *part1 = \"Please aim \";\n char *part2 = \" degrees at a height of \";\n char *part3 = \" meters.\";\n\n float degrees;\n long height;\n\n size_t part1_len = strlen( part1 );\n size_t part2_len = strlen( part2 );\n size_t part3_len = strlen( part3 );\n\n //make p point to start of line\n char *p = line;\n\n char *q;\n\n //verify that the line starts with part1 and skip it\n if ( strncmp( p, part1, part1_len ) != 0 )\n {\n fprintf( stderr, \"Unable to find part1!\\n\" );\n exit( EXIT_FAILURE );\n }\n p += part1_len;\n\n //attempt to convert degrees value and skip it\n degrees = strtof( p, &q );\n if ( p == q )\n {\n fprintf( stderr, \"Error converting degrees!\\n\" );\n exit( EXIT_FAILURE );\n }\n p = q;\n\n //verify that the line continues with part2 and skip it\n if ( strncmp( p, part2, part2_len ) != 0 )\n {\n fprintf( stderr, \"Unable to find part2!\\n\" );\n exit( EXIT_FAILURE );\n }\n p += part2_len;\n\n //attempt to convert height value and skip it\n height = strtol( p, &q, 10 );\n if ( p == q )\n {\n fprintf( stderr, \"Error converting height!\\n\" );\n exit( EXIT_FAILURE );\n }\n p = q;\n\n //verify that the line continues with part3 and skip it\n if ( strncmp( p, part3, part3_len ) != 0 )\n {\n fprintf( stderr, \"Unable to find part3!\\n\" );\n exit( EXIT_FAILURE );\n }\n p += part3_len;\n\n //verify that we have reached the end of the string\n if ( *p != '\\0' )\n {\n fprintf( stderr, \"Unexpected character encountered!\\n\" );\n exit( EXIT_FAILURE );\n }\n\n //print the results\n printf(\n \"Results:\\n\"\n \"Degrees: %f\\n\"\n \"Height: %ld\\n\",\n degrees, height\n );\n}\n\nThis program has the following output:\nResults:\nDegrees: 3.567000\nHeight: 5\n\n" ]
[ 0, 0 ]
[]
[]
[ "c", "numbers" ]
stackoverflow_0074663709_c_numbers.txt
Q: how can I connect my database to the permission sweetalert2 login form I've been using sweetalert2 login form for the sake of permission, how can I connect my database to the permission sweetalert2 login form. If I click the edit button inside the table, it will pop up the sweetalert2 login form for the permission of admin credentials I have been stucked with this, please help. <button class="btn btn-warning confirmation" href="index.php"><i class="icon-edit"></i></button> <script> $('.confirmation').on('click',function (e) { e.preventDefault(); const href = $(this).attr('href') Swal.fire({ title: 'Admin Permission', html: `<input type="text" id="login" class="swal2-input" placeholder="Username"> <input type="password" id="password" class="swal2-input" placeholder="Password">`, showCancelButton: true, cancelButtonColor: 'gray', confirmButtonText: 'Grant', confirmButtonColor: 'green', focusConfirm: true, showCloseButton: true, customClass: { confirmButton: 'btnconfirm', cancelButton: 'btncancel', title: 'permissiontitle', }, preConfirm: () => { const username = Swal.getPopup().querySelector('#login').value const password = Swal.getPopup().querySelector('#password').value if (!login || !password) { Swal.showValidationMessage(`Please Enter Username and Password`) } return { username: username, password: password } } }).then((result) => { // do something... }) }) </script> A: To connect a database to a login form that uses SweetAlert2 for permission, you can use a server-side language like PHP to query the database and verify the user's credentials. Here is an example of how this might work: In the HTML page that contains the login form, add a form element with the necessary input fields for the username and password, and a submit button. <form id="loginForm"> <input type="text" id="username" placeholder="Username"> <input type="password" id="password" placeholder="Password"> <button type="submit">Log In</button> </form> In the JavaScript code that handles the login form submission, use the SweetAlert2 library to create a permission dialog that asks the user for confirmation before submitting the form. // Get the login form and button const loginForm = document.getElementById('loginForm'); const loginButton = loginForm.querySelector('button'); // Handle the login form submission loginForm.addEventListener('submit', e => { e.preventDefault(); // Show the permission dialog Swal.fire({ title: 'Log In', text: 'Are you sure you want to log in with these credentials?', icon: 'question', showCancelButton: true, confirmButtonText: 'Log In', cancelButtonText: 'Cancel', }).then(result => { // If the user confirms the permission, submit the form if (result.value) { loginForm.submit(); } }); }); In the PHP script that receives the form submission, use the PDO library to connect to the database and query the user's credentials. If the credentials are valid, log the user in and redirect them to the appropriate page. If the credentials are invalid, show an error message and allow the user to try again. <?php // Connect to the database $db = new PDO('mysql:host=localhost;dbname=database_name', 'username', 'password'); // Get the username and password from the form submission $username = $_POST['username']; $password = $_POST['password']; // Check if the username and password are valid $stmt = $db->prepare('SELECT * FROM users WHERE username = :username AND password = :password'); $stmt->bindParam(':username', $username); $stmt->bindParam(':password', $password); $stmt->execute(); $user = $stmt->fetch(); if ($user) { // If the username and password are valid, log the user in and redirect them to the appropriate page session_start(); $_SESSION['user'] = $user; header('Location: dashboard.php'); } else { // If the username and password are invalid, show an error message echo '<p>Invalid username or password. Please try again.</p>'; } This is just a simple example of how you can connect a database to a login form that uses SweetAlert2 for permission. Depending on your specific needs, you may need to adjust the code to fit your requirements.
how can I connect my database to the permission sweetalert2 login form
I've been using sweetalert2 login form for the sake of permission, how can I connect my database to the permission sweetalert2 login form. If I click the edit button inside the table, it will pop up the sweetalert2 login form for the permission of admin credentials I have been stucked with this, please help. <button class="btn btn-warning confirmation" href="index.php"><i class="icon-edit"></i></button> <script> $('.confirmation').on('click',function (e) { e.preventDefault(); const href = $(this).attr('href') Swal.fire({ title: 'Admin Permission', html: `<input type="text" id="login" class="swal2-input" placeholder="Username"> <input type="password" id="password" class="swal2-input" placeholder="Password">`, showCancelButton: true, cancelButtonColor: 'gray', confirmButtonText: 'Grant', confirmButtonColor: 'green', focusConfirm: true, showCloseButton: true, customClass: { confirmButton: 'btnconfirm', cancelButton: 'btncancel', title: 'permissiontitle', }, preConfirm: () => { const username = Swal.getPopup().querySelector('#login').value const password = Swal.getPopup().querySelector('#password').value if (!login || !password) { Swal.showValidationMessage(`Please Enter Username and Password`) } return { username: username, password: password } } }).then((result) => { // do something... }) }) </script>
[ "To connect a database to a login form that uses SweetAlert2 for permission, you can use a server-side language like PHP to query the database and verify the user's credentials. Here is an example of how this might work:\nIn the HTML page that contains the login form, add a form element with the necessary input fields for the username and password, and a submit button.\n<form id=\"loginForm\">\n <input type=\"text\" id=\"username\" placeholder=\"Username\">\n <input type=\"password\" id=\"password\" placeholder=\"Password\">\n <button type=\"submit\">Log In</button>\n</form>\n\nIn the JavaScript code that handles the login form submission, use the SweetAlert2 library to create a permission dialog that asks the user for confirmation before submitting the form.\n// Get the login form and button\nconst loginForm = document.getElementById('loginForm');\nconst loginButton = loginForm.querySelector('button');\n\n// Handle the login form submission\nloginForm.addEventListener('submit', e => {\n e.preventDefault();\n\n // Show the permission dialog\n Swal.fire({\n title: 'Log In',\n text: 'Are you sure you want to log in with these credentials?',\n icon: 'question',\n showCancelButton: true,\n confirmButtonText: 'Log In',\n cancelButtonText: 'Cancel',\n }).then(result => {\n // If the user confirms the permission, submit the form\n if (result.value) {\n loginForm.submit();\n }\n });\n});\n\nIn the PHP script that receives the form submission, use the PDO library to connect to the database and query the user's credentials. If the credentials are valid, log the user in and redirect them to the appropriate page. If the credentials are invalid, show an error message and allow the user to try again.\n<?php\n// Connect to the database\n$db = new PDO('mysql:host=localhost;dbname=database_name', 'username', 'password');\n\n// Get the username and password from the form submission\n$username = $_POST['username'];\n$password = $_POST['password'];\n\n// Check if the username and password are valid\n$stmt = $db->prepare('SELECT * FROM users WHERE username = :username AND password = :password');\n$stmt->bindParam(':username', $username);\n$stmt->bindParam(':password', $password);\n$stmt->execute();\n$user = $stmt->fetch();\n\nif ($user) {\n // If the username and password are valid, log the user in and redirect them to the appropriate page\n session_start();\n $_SESSION['user'] = $user;\n header('Location: dashboard.php');\n} else {\n // If the username and password are invalid, show an error message\n echo '<p>Invalid username or password. Please try again.</p>';\n}\n\nThis is just a simple example of how you can connect a database to a login form that uses SweetAlert2 for permission. Depending on your specific needs, you may need to adjust the code to fit your requirements.\n" ]
[ 0 ]
[]
[]
[ "database", "javascript", "jquery", "mysql", "sweetalert" ]
stackoverflow_0074663828_database_javascript_jquery_mysql_sweetalert.txt
Q: Dynamically update text in HTML I have a Google Docs sidebar that has text input and a search button. After entering a name, the search button will pull data from a Sheets database, and I want it to be able to populate a text display. For example, right now, I have it simply displayed using paragraphs. "Source goes here" would be replaced with the variable data from Google Apps Script. <p> <b>Source:</b> Sources goes here<br> </p> I've seen snippets that talk about using something like: var html = HtmlService.createHtmlOutputFromFile('ToolPage'); var demoValue = "testValue"; html.demoVariable = demoValue; Which would then use html: <p> <b>Source:</b> <span id=demoVariable></span><br> </p> But, I don't get any output. Have I misunderstood something fundamental? Or am I at least on the right track? A: To dynamically update text in an HTML page using data from Google Apps Script (GAS), you can use the google.script.run API to call a GAS function that retrieves the data and then use the innerHTML property of a DOM element to set the text of that element to the retrieved data. Here is an example of how this might work: In the HTML page, add a DOM element that will contain the dynamically updated text. <p id="dynamicText">Loading...</p> In the GAS code, create a function that retrieves the data you want to display in the HTML page. For example, if the data is stored in a Google Sheets spreadsheet, you can use the Sheets API to read the data from the spreadsheet and return it as an array of values. function getData() { // Get the data from the spreadsheet var ss = SpreadsheetApp.openById('SPREADSHEET_ID'); var sheet = ss.getSheetByName('Sheet1'); var data = sheet.getDataRange().getValues(); // Return the data as an array of values return data; } In the JavaScript code that runs on the HTML page, use the google.script.run API to call the GAS function and retrieve the data. Then, use the innerHTML property of the DOM element to set the text of that element to the retrieved data. // Get the DOM element that will contain the dynamic text const dynamicText = document.getElementById('dynamicText'); // Call the GAS function to get the data google.script.run .withSuccessHandler(data => { // Set the text of the DOM element to the retrieved data dynamicText.innerHTML = data.join(', '); }) .getData(); In this example, the getData() function is called using the google.script.run API, and the retrieved data is passed to the success handler function as an array of values. The success handler function then sets the text of the dynamicText element to the retrieved data, using the innerHTML property. You can adjust the code to fit your specific needs, such as using a different data source or formatting the data in a different way. Additionally, you can use additional methods of the google.script.run API, such as withFailureHandler(), to handle errors and other situations.
Dynamically update text in HTML
I have a Google Docs sidebar that has text input and a search button. After entering a name, the search button will pull data from a Sheets database, and I want it to be able to populate a text display. For example, right now, I have it simply displayed using paragraphs. "Source goes here" would be replaced with the variable data from Google Apps Script. <p> <b>Source:</b> Sources goes here<br> </p> I've seen snippets that talk about using something like: var html = HtmlService.createHtmlOutputFromFile('ToolPage'); var demoValue = "testValue"; html.demoVariable = demoValue; Which would then use html: <p> <b>Source:</b> <span id=demoVariable></span><br> </p> But, I don't get any output. Have I misunderstood something fundamental? Or am I at least on the right track?
[ "To dynamically update text in an HTML page using data from Google Apps Script (GAS), you can use the google.script.run API to call a GAS function that retrieves the data and then use the innerHTML property of a DOM element to set the text of that element to the retrieved data. Here is an example of how this might work:\nIn the HTML page, add a DOM element that will contain the dynamically updated text.\n<p id=\"dynamicText\">Loading...</p>\n\nIn the GAS code, create a function that retrieves the data you want to display in the HTML page. For example, if the data is stored in a Google Sheets spreadsheet, you can use the Sheets API to read the data from the spreadsheet and return it as an array of values.\nfunction getData() {\n // Get the data from the spreadsheet\n var ss = SpreadsheetApp.openById('SPREADSHEET_ID');\n var sheet = ss.getSheetByName('Sheet1');\n var data = sheet.getDataRange().getValues();\n\n // Return the data as an array of values\n return data;\n}\n\nIn the JavaScript code that runs on the HTML page, use the google.script.run API to call the GAS function and retrieve the data. Then, use the innerHTML property of the DOM element to set the text of that element to the retrieved data.\n// Get the DOM element that will contain the dynamic text\nconst dynamicText = document.getElementById('dynamicText');\n\n// Call the GAS function to get the data\ngoogle.script.run\n .withSuccessHandler(data => {\n // Set the text of the DOM element to the retrieved data\n dynamicText.innerHTML = data.join(', ');\n })\n .getData();\n\nIn this example, the getData() function is called using the google.script.run API, and the retrieved data is passed to the success handler function as an array of values. The success handler function then sets the text of the dynamicText element to the retrieved data, using the innerHTML property.\nYou can adjust the code to fit your specific needs, such as using a different data source or formatting the data in a different way. Additionally, you can use additional methods of the google.script.run API, such as withFailureHandler(), to handle errors and other situations.\n" ]
[ 0 ]
[]
[]
[ "google_apps_script", "google_docs", "google_sheets", "sidebar", "web_applications" ]
stackoverflow_0074663843_google_apps_script_google_docs_google_sheets_sidebar_web_applications.txt
Q: python requests not work with vpn ProxyError('Cannot connect to proxy.', I use requests with vpn and it show error (Caused by ProxyError('Cannot connect to proxy.', OSError(0, 'Error'))) this is code import requests con = requests.get(url) I can visit url in browser with vpn. I hav to use vpn to requests. use Python 3.7.9 A: using pyPAC works for me... https://pypac.readthedocs.io/en/latest/ from pypac import PACSession from requests.auth import HTTPProxyAuth session = PACSession() r = session.get('http://google.com') you may need to update your python version or use an older version of pyPAC that matches your python version.
python requests not work with vpn ProxyError('Cannot connect to proxy.',
I use requests with vpn and it show error (Caused by ProxyError('Cannot connect to proxy.', OSError(0, 'Error'))) this is code import requests con = requests.get(url) I can visit url in browser with vpn. I hav to use vpn to requests. use Python 3.7.9
[ "using pyPAC works for me...\nhttps://pypac.readthedocs.io/en/latest/\nfrom pypac import PACSession\nfrom requests.auth import HTTPProxyAuth\nsession = PACSession()\nr = session.get('http://google.com')\n\nyou may need to update your python version or use an older version of pyPAC that matches your python version.\n" ]
[ 0 ]
[]
[]
[ "networking", "python", "python_requests", "urllib", "vpn" ]
stackoverflow_0074106849_networking_python_python_requests_urllib_vpn.txt
Q: Understanding Active Storage Direct Upload errors: `Error storing "File_1.jpeg". Status: 0` Our app recently switched to direct uploads to S3 via Rails Active Storage (introduced in Rails 5.2) For the most part, it's working alright, but we're noticing that an error gets thrown around 2% of the time. We've seen the following so far: Status 0 (predominantly with Safari/ Mobile Safari): Error storing "File_1.jpeg". Status: 0 Status 403: Error storing "File_1.jpeg". Status: 403 Error reading: Error reading "File_1.jpeg". I imagine the last error relates to the file itself being invalid or corrupt. However, we're unsure what could be resulting in the first two errors. Searching around, I notice posts mentioning CORS settings being incorrect. However, we've made some configuration changes before on S3, and I would also think that if it was a CORS issue, we'd see failure a lot more frequently. This is what our CORS setting is: <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <MaxAgeSeconds>3000</MaxAgeSeconds> <AllowedHeader>*</AllowedHeader> </CORSRule> <CORSRule> <AllowedOrigin>https://app.ourapp.com</AllowedOrigin> <AllowedMethod>PUT</AllowedMethod> <MaxAgeSeconds>3600</MaxAgeSeconds> <AllowedHeader>Origin</AllowedHeader> <AllowedHeader>Content-Type</AllowedHeader> <AllowedHeader>Content-MD5</AllowedHeader> <AllowedHeader>Content-Disposition</AllowedHeader> </CORSRule> </CORSConfiguration> We noticed in one multi-upload, that a user was able to upload 12 files successfully to active storage, but 1 error-ed out with status 0. The file itself wasn't corrupt or anything. Any clue what could be causing direct upload flakiness sometimes? A: The following worked for me: [ { "AllowedHeaders": [ "Authorization" ], "AllowedMethods": [ "GET" ], "AllowedOrigins": [ "https://example.com" ], "ExposeHeaders": [], "MaxAgeSeconds": 3000 }, { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "PUT" ], "AllowedOrigins": [ "https://example.com" ], "ExposeHeaders": [] } ] Got it from here. A: Error storing "File_1.jpeg". Status: 0 I have seen this error occur for our users when there is a Data Loss Prevention (DLP) tool in place, which prevents sensitive files from leaving their network. If possible, have the user's IT team check their configuration to allow uploading such files. A: Took me 7 hours to solve this. What it wasn't: CORS was the first place I looked, but it had absolutely nothing to do with CORS. The second place I looked was for incorrect AWS keys, but it wasn't that either. Key insight: this was only happening (for me) on edit views, which should submit a PATCH, but when a file was submitted to the form, it was making a POST. That was an important break through, and googling that led me to many ideas. Look carefully at the HTTP verb made when your form submits; if it's a POST when it should be a PATCH, that's where to start looking. I now needed to find out how to make the form understand it needed to patch when a new ActiveStorage attachment was submitted. I changed this <%= form.label :images %> <%= form.file_field :images, multiple: true, direct_upload: true %> to this <%= form.label :images %> <%= form.file_field :images, multiple: true %> And suddenly everything worked. I have absolutely no clue why though! I got the idea from here. Notes Debugging tip: if this problem only happens in production, try emulating it locally by hopping into config/environments/development.rb and setting config.active_storage.service = :amazon (then you can test locally making it much easier to see logs), please be careful though as it may send blobs to your production S3 (mine was a new app so I could afford to send files there willy nilly). A refresher: a _form.html.erb partial will typically submit a POST if the variable is new, otherwise it will submit a PATCH. (see here).
Understanding Active Storage Direct Upload errors: `Error storing "File_1.jpeg". Status: 0`
Our app recently switched to direct uploads to S3 via Rails Active Storage (introduced in Rails 5.2) For the most part, it's working alright, but we're noticing that an error gets thrown around 2% of the time. We've seen the following so far: Status 0 (predominantly with Safari/ Mobile Safari): Error storing "File_1.jpeg". Status: 0 Status 403: Error storing "File_1.jpeg". Status: 403 Error reading: Error reading "File_1.jpeg". I imagine the last error relates to the file itself being invalid or corrupt. However, we're unsure what could be resulting in the first two errors. Searching around, I notice posts mentioning CORS settings being incorrect. However, we've made some configuration changes before on S3, and I would also think that if it was a CORS issue, we'd see failure a lot more frequently. This is what our CORS setting is: <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <MaxAgeSeconds>3000</MaxAgeSeconds> <AllowedHeader>*</AllowedHeader> </CORSRule> <CORSRule> <AllowedOrigin>https://app.ourapp.com</AllowedOrigin> <AllowedMethod>PUT</AllowedMethod> <MaxAgeSeconds>3600</MaxAgeSeconds> <AllowedHeader>Origin</AllowedHeader> <AllowedHeader>Content-Type</AllowedHeader> <AllowedHeader>Content-MD5</AllowedHeader> <AllowedHeader>Content-Disposition</AllowedHeader> </CORSRule> </CORSConfiguration> We noticed in one multi-upload, that a user was able to upload 12 files successfully to active storage, but 1 error-ed out with status 0. The file itself wasn't corrupt or anything. Any clue what could be causing direct upload flakiness sometimes?
[ "The following worked for me:\n[\n {\n \"AllowedHeaders\": [\n \"Authorization\"\n ],\n \"AllowedMethods\": [\n \"GET\"\n ],\n \"AllowedOrigins\": [\n \"https://example.com\"\n ],\n \"ExposeHeaders\": [],\n \"MaxAgeSeconds\": 3000\n },\n {\n \"AllowedHeaders\": [\n \"*\"\n ],\n \"AllowedMethods\": [\n \"PUT\"\n ],\n \"AllowedOrigins\": [\n \"https://example.com\"\n ],\n \"ExposeHeaders\": []\n }\n]\n\nGot it from here.\n", "\nError storing \"File_1.jpeg\". Status: 0\n\nI have seen this error occur for our users when there is a Data Loss Prevention (DLP) tool in place, which prevents sensitive files from leaving their network. If possible, have the user's IT team check their configuration to allow uploading such files.\n", "Took me 7 hours to solve this.\nWhat it wasn't:\n\nCORS was the first place I looked, but it had absolutely nothing to do with CORS.\nThe second place I looked was for incorrect AWS keys, but it wasn't that either.\n\nKey insight: this was only happening (for me) on edit views, which should submit a PATCH, but when a file was submitted to the form, it was making a POST.\nThat was an important break through, and googling that led me to many ideas. Look carefully at the HTTP verb made when your form submits; if it's a POST when it should be a PATCH, that's where to start looking.\n\nI now needed to find out how to make the form understand it needed to patch when a new ActiveStorage attachment was submitted.\nI changed this\n<%= form.label :images %>\n<%= form.file_field :images, multiple: true, direct_upload: true %>\n\nto this\n<%= form.label :images %>\n<%= form.file_field :images, multiple: true %>\n\nAnd suddenly everything worked. I have absolutely no clue why though! I got the idea from here.\n\nNotes\n\nDebugging tip: if this problem only happens in production, try emulating it locally by hopping into config/environments/development.rb and setting config.active_storage.service = :amazon (then you can test locally making it much easier to see logs), please be careful though as it may send blobs to your production S3 (mine was a new app so I could afford to send files there willy nilly).\n\nA refresher: a _form.html.erb partial will typically submit a POST if the variable is new, otherwise it will submit a PATCH. (see here).\n\n\n" ]
[ 0, 0, 0 ]
[]
[]
[ "amazon_s3", "rails_activestorage", "ruby_on_rails_5" ]
stackoverflow_0062272186_amazon_s3_rails_activestorage_ruby_on_rails_5.txt
Q: lerna add : No packages found where can be added have added lerna to my project, i have added a package to my server by running this command successfully: lerna add @types/express --dev But when I want to add another one: lerna add graphql class-validator type-graphql I got this error : info cli using local version of lerna lerna notice cli v3.22.1 lerna WARN No packages found where graphql can be added. Is something missed or wrong for adding the packages? Should I use yarn add instead of leran add? looks it works but I doubt about the packages tree form to be correct A: At the moment, lerna doesn't support adding multiple packages to another package like so: ❌ lerna add '@my-company/{utils,types}' --scope '@my-company/ui' // We have to do this instead lerna add '@my-company/utils' --scope '@my-company/ui' lerna add '@my-company/types' --scope '@my-company/ui' Lerna does support adding 1 package into multiple packages though: lerna add '@my-company/utils --scope '@my-company/{ui,data}' lerna's github discussion on this issue for updates (link) A: Lerna add does not support multiple packages, try doing one at a time. lerna add graphql lerna add class-validator lerna add type-graphql There is an issue to support this on github that will hopefully be resolved one day A: Foreword: The lerna cli is notoriously bad at giving feedback. You get weird errors and warnings that don't seem to make a lot of sense in the context. Why is this happening? I identified the following causes (at one point or another) to all result in this error message: You already added the package to given package. This is somewhat irritating, since with yarn and npm you can (force) re-install a package, instead of having it error out. You tried to add multiple packages in one command (this is also mentioned in other answers and comments here). e.g.: npx lerna add --scope=... packageA packageB NOTE: This is an open issue in the lerna repo. Workarounds are discussed there as well. A: Old question, but I ran into the same issue with "lerna": "^5.5.2" trying to only install a single dependency. Ran lerna repair --verbose and it highlighted issues with the version of Nx. Once fixed I could install deps again. Granted, you might not have Nx integrated, but the repair command will give you more insights into what could potentially be the issue. As per @Domi's answer Lerna's CLI is still not very forthcoming with feedback.
lerna add : No packages found where can be added
have added lerna to my project, i have added a package to my server by running this command successfully: lerna add @types/express --dev But when I want to add another one: lerna add graphql class-validator type-graphql I got this error : info cli using local version of lerna lerna notice cli v3.22.1 lerna WARN No packages found where graphql can be added. Is something missed or wrong for adding the packages? Should I use yarn add instead of leran add? looks it works but I doubt about the packages tree form to be correct
[ "At the moment, lerna doesn't support adding multiple packages to another package like so:\n❌ lerna add '@my-company/{utils,types}' --scope '@my-company/ui' \n\n// We have to do this instead\nlerna add '@my-company/utils' --scope '@my-company/ui' \nlerna add '@my-company/types' --scope '@my-company/ui'\n\nLerna does support adding 1 package into multiple packages though:\nlerna add '@my-company/utils --scope '@my-company/{ui,data}' \n\nlerna's github discussion on this issue for updates (link)\n", "Lerna add does not support multiple packages, try doing one at a time.\nlerna add graphql\nlerna add class-validator\nlerna add type-graphql\n\nThere is an issue to support this on github that will hopefully be resolved one day\n", "Foreword: The lerna cli is notoriously bad at giving feedback. You get weird errors and warnings that don't seem to make a lot of sense in the context.\nWhy is this happening?\nI identified the following causes (at one point or another) to all result in this error message:\n\nYou already added the package to given package.\n\nThis is somewhat irritating, since with yarn and npm you can (force) re-install a package, instead of having it error out.\n\n\nYou tried to add multiple packages in one command (this is also mentioned in other answers and comments here).\n\ne.g.: npx lerna add --scope=... packageA packageB\nNOTE: This is an open issue in the lerna repo. Workarounds are discussed there as well.\n\n\n\n", "Old question, but I ran into the same issue with \"lerna\": \"^5.5.2\" trying to only install a single dependency.\nRan lerna repair --verbose and it highlighted issues with the version of Nx. Once fixed I could install deps again. Granted, you might not have Nx integrated, but the repair command will give you more insights into what could potentially be the issue.\nAs per @Domi's answer Lerna's CLI is still not very forthcoming with feedback.\n" ]
[ 13, 9, 3, 0 ]
[]
[]
[ "lerna", "npm_install", "yarnpkg" ]
stackoverflow_0062980752_lerna_npm_install_yarnpkg.txt
Q: How do I find the other elements in a list given one of them? Given one element in a list, what is the most efficient way that I can find the other elements? (e.g. if a list is l=["A","B","C","D"] and you're given "B", it outputs "A", "C" and "D")? A: Your question-: How do I find the other elements in a list given one of them? Think like.. How can i remove that element in a list to get all other elements in a list [Quite simple to approach now!!] Some methods are:- def method1(test_list, item): #List Comprehension res = [i for i in test_list if i != item] return res def method2(test_list,item): #Filter Function res = list(filter((item).__ne__, test_list)) return res def method3(test_list,item): #Remove Function c=test_list.count(item) for i in range(c): test_list.remove(item) return test_list print(method1(["A","B","C","D"],"B")) print(method2(["A","B","C","D"],"B")) print(method3(["A","B","C","D"],"B")) Output:- ['A', 'C', 'D'] ['A', 'C', 'D'] ['A', 'C', 'D'] A: There are few ways to achieve this, you want to find the other elements excluding the value. eg l1=[1,2,3,4,5] 2 to excluded l1=[1,3,4,5] # a list l1 =["a","b","C","d"] #input of the value to exclude jo = input() l2=[] for i in range(len(l1)): if l1[i]!=jo: l2.append(l1[i]) print(l2)
How do I find the other elements in a list given one of them?
Given one element in a list, what is the most efficient way that I can find the other elements? (e.g. if a list is l=["A","B","C","D"] and you're given "B", it outputs "A", "C" and "D")?
[ "Your question-: How do I find the other elements in a list given one of them?\nThink like.. How can i remove that element in a list to get all other elements in a list [Quite simple to approach now!!]\nSome methods are:-\ndef method1(test_list, item):\n #List Comprehension\n res = [i for i in test_list if i != item]\n return res\n\ndef method2(test_list,item):\n #Filter Function\n res = list(filter((item).__ne__, test_list))\n return res\n\ndef method3(test_list,item):\n #Remove Function\n c=test_list.count(item)\n for i in range(c):\n test_list.remove(item)\n return test_list\n \nprint(method1([\"A\",\"B\",\"C\",\"D\"],\"B\"))\nprint(method2([\"A\",\"B\",\"C\",\"D\"],\"B\"))\nprint(method3([\"A\",\"B\",\"C\",\"D\"],\"B\"))\n\nOutput:-\n['A', 'C', 'D']\n['A', 'C', 'D']\n['A', 'C', 'D']\n\n", "There are few ways to achieve this, you want to find the other elements excluding the value.\neg l1=[1,2,3,4,5]\n2 to excluded\nl1=[1,3,4,5]\n# a list\nl1 =[\"a\",\"b\",\"C\",\"d\"]\n#input of the value to exclude \njo = input()\nl2=[]\nfor i in range(len(l1)):\n if l1[i]!=jo:\n l2.append(l1[i])\nprint(l2) \n\n \n\n" ]
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074663785_python.txt
Q: mysql: delete & order by want to delete duplicate posts using meta as duplcate metric, deleting recent duplicate posts and keeping the original version. However it keeps the most recent duplicate version and deletes the older ones. So I tried adding an "order by" and it doesnt seem to work. DELETE p, pm1 FROM wp_posts p, wp_postmeta pm1, wp_postmeta pm2 WHERE (p.ID = pm1.post_id AND p.post_type = 'post' AND pm1.post_id > pm2.post_id AND pm1.meta_key = 'syndication_permalink' AND pm1.meta_key = pm2.meta_key AND pm1.meta_value = pm2.meta_value) ORDER BY p.ID ASC help appreciated A: You need to use row_number() function Here's a sample WITH cte AS ( SELECT ROW_NUMBER() OVER(PARTITION by ID ORDER BY name) AS Row FROM test ) DELETE FROM cte WHERE Row > 1
mysql: delete & order by
want to delete duplicate posts using meta as duplcate metric, deleting recent duplicate posts and keeping the original version. However it keeps the most recent duplicate version and deletes the older ones. So I tried adding an "order by" and it doesnt seem to work. DELETE p, pm1 FROM wp_posts p, wp_postmeta pm1, wp_postmeta pm2 WHERE (p.ID = pm1.post_id AND p.post_type = 'post' AND pm1.post_id > pm2.post_id AND pm1.meta_key = 'syndication_permalink' AND pm1.meta_key = pm2.meta_key AND pm1.meta_value = pm2.meta_value) ORDER BY p.ID ASC help appreciated
[ "You need to use row_number() function\nHere's a sample\nWITH cte AS\n(\n SELECT ROW_NUMBER() OVER(PARTITION by ID ORDER BY name) AS Row\n FROM test\n)\n\nDELETE FROM cte\nWHERE Row > 1\n\n" ]
[ 0 ]
[]
[]
[ "mysql", "sql", "sql_delete", "sql_order_by" ]
stackoverflow_0074663625_mysql_sql_sql_delete_sql_order_by.txt
Q: pandas loc does not preserve data type Pandas loc indexing does not preserve the datatype of subarrays. Consider the following code: import pandas as pd s = pd.Series([1,2,"hi","bye"]) print(s) # dtype: object print(s.loc[[0]]) # dtype: object print(type(s.loc[0])) # <class 'int'> I would like s.loc[[0]] to return a series with type int, rather than obj as it currently does.
pandas loc does not preserve data type
Pandas loc indexing does not preserve the datatype of subarrays. Consider the following code: import pandas as pd s = pd.Series([1,2,"hi","bye"]) print(s) # dtype: object print(s.loc[[0]]) # dtype: object print(type(s.loc[0])) # <class 'int'> I would like s.loc[[0]] to return a series with type int, rather than obj as it currently does.
[]
[]
[ "You can use the astype(original data type).astype(your prefered data type) in the print clause, e.g. from your case:\nimport pandas as pd\n\ns = pd.Series([1,2,\"hi\",\"bye\"])\nprint(s)\nprint(s.loc[[0]].astype(str).astype(int))\nresult :\n0 1\ndtype: int32\nHere is my answer, hope it be useful\n" ]
[ -1 ]
[ "indexing", "pandas", "types" ]
stackoverflow_0074663669_indexing_pandas_types.txt
Q: only the 1st row in the database can be read Cant get the code to detect all the rows in the database, only the first row. I'm not sure if this is right. I am trying to create a code for logging in. <?php if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['plsubmit'])) { $conn = mysqli_connect('localhost','root', '', 'foodratingdb') or die("Connection Failed" .mysqli_connect_error()); if( isset($_POST['plusername']) && isset($_POST['plpassword'])) { $plusername = $_POST['plusername']; $plpassword = $_POST['plpassword']; $sql = "SELECT username, password_hash FROM register"; $result = mysqli_query($conn,$sql); if(mysqli_num_rows($result) > 0) { $row = mysqli_fetch_assoc($result); if(password_verify($plpassword, $row['password_hash']) && $plusername == $row['username']) { header("Location: index.php"); } else { header("Location: page-login.php?message2=error"); } } } } ?> A: You are only fetching one row from the query. Which is actually what you should do, what you have wrong is not filtering the user in the query. Your query should filter by the username SELECT password_hash FROM register where username = 'some_username'
only the 1st row in the database can be read
Cant get the code to detect all the rows in the database, only the first row. I'm not sure if this is right. I am trying to create a code for logging in. <?php if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['plsubmit'])) { $conn = mysqli_connect('localhost','root', '', 'foodratingdb') or die("Connection Failed" .mysqli_connect_error()); if( isset($_POST['plusername']) && isset($_POST['plpassword'])) { $plusername = $_POST['plusername']; $plpassword = $_POST['plpassword']; $sql = "SELECT username, password_hash FROM register"; $result = mysqli_query($conn,$sql); if(mysqli_num_rows($result) > 0) { $row = mysqli_fetch_assoc($result); if(password_verify($plpassword, $row['password_hash']) && $plusername == $row['username']) { header("Location: index.php"); } else { header("Location: page-login.php?message2=error"); } } } } ?>
[ "You are only fetching one row from the query.\nWhich is actually what you should do, what you have wrong is not filtering the user in the query. Your query should filter by the username\nSELECT password_hash FROM register where username = 'some_username'\n\n" ]
[ 0 ]
[]
[]
[ "php" ]
stackoverflow_0074663875_php.txt
Q: Error occurred during initialization of boot layer- MacOs M2-Eclipse enter image description here I should mention that I am new ad confused. I have VM argument in place but when I ran it, I got this error. Im not sure how to fix it. I tried moving "user library" under module. can someone please help me here? Error occurred during initialization of boot layer java.lang.module.FindException: java.nio.file.FileSystemException: /Users/xxxxx/Downloads/javafx-sdk-19/lib: Operation not permitted Caused by: java.nio.file.FileSystemException: /Users/xxxxx/Downloads/javafx-sdk-19/lib: Operation not permitted A: If you are getting an "Error occurred during initialization of boot layer" error with a "java.nio.file.FileSystemException" message when trying to launch Eclipse on MacOS, it may be because the JavaFX libraries are not readable or writable by the user that is running Eclipse. This error typically occurs when the JavaFX libraries are installed in a location that is not accessible to the user, or when the permissions on the JavaFX libraries are not set correctly. To fix this issue, you can try the following steps: Check the permissions on the JavaFX libraries. To do this, open a terminal window and navigate to the directory where the JavaFX libraries are installed. For example, if the JavaFX libraries are installed in the javafx-sdk-19 directory, you can use the cd command to navigate to that directory as follows: cd /Users/xxxxx/Downloads/javafx-sdk-19 Once you are in the JavaFX directory, run the following command to check the permissions on the lib directory: ls -l lib This will display the permissions for the lib directory, along with the owner and group. If the permissions on the lib directory are not set correctly, you will need to change the permissions to make the directory readable and writable by the user that is running Eclipse. To do this, run the following command: sudo chmod -R u+rwx lib This will give the user read, write, and execute permissions on the lib directory. If the permissions on the lib directory are set correctly, but you are still getting the error, it may be because the JavaFX libraries are installed in a location
Error occurred during initialization of boot layer- MacOs M2-Eclipse
enter image description here I should mention that I am new ad confused. I have VM argument in place but when I ran it, I got this error. Im not sure how to fix it. I tried moving "user library" under module. can someone please help me here? Error occurred during initialization of boot layer java.lang.module.FindException: java.nio.file.FileSystemException: /Users/xxxxx/Downloads/javafx-sdk-19/lib: Operation not permitted Caused by: java.nio.file.FileSystemException: /Users/xxxxx/Downloads/javafx-sdk-19/lib: Operation not permitted
[ "If you are getting an \"Error occurred during initialization of boot layer\" error with a \"java.nio.file.FileSystemException\" message when trying to launch Eclipse on MacOS, it may be because the JavaFX libraries are not readable or writable by the user that is running Eclipse. This error typically occurs when the JavaFX libraries are installed in a location that is not accessible to the user, or when the permissions on the JavaFX libraries are not set correctly.\nTo fix this issue, you can try the following steps:\nCheck the permissions on the JavaFX libraries. To do this, open a terminal window and navigate to the directory where the JavaFX libraries are installed. For example, if the JavaFX libraries are installed in the javafx-sdk-19 directory, you can use the cd command to navigate to that directory as follows:\ncd /Users/xxxxx/Downloads/javafx-sdk-19\n\nOnce you are in the JavaFX directory, run the following command to check the permissions on the lib directory:\nls -l lib\n\nThis will display the permissions for the lib directory, along with the owner and group.\nIf the permissions on the lib directory are not set correctly, you will need to change the permissions to make the directory readable and writable by the user that is running Eclipse. To do this, run the following command:\nsudo chmod -R u+rwx lib\n\nThis will give the user read, write, and execute permissions on the lib directory.\nIf the permissions on the lib directory are set correctly, but you are still getting the error, it may be because the JavaFX libraries are installed in a location\n" ]
[ 0 ]
[]
[]
[ "compiler_errors", "eclipse", "filesystemexception", "macos", "operation" ]
stackoverflow_0074663878_compiler_errors_eclipse_filesystemexception_macos_operation.txt
Q: How to infer property values from arrays of objects in Typescript? I'd like the TypeScript compiler to infer the names of properties on an object so that it's easier to invoke the appropriate functions later. However, despite considering invoking functions, TypeScript doesn't give any intellisense of the functions I can invoke. Taking into account the following example: interface InputBase { alias: string; } const input: Array<InputBase> = [ { alias: 'getNotes' }, { alias: 'getComments' }, ]; const client = input.reduce((acc, curr: InputBase) => { return { ...acc, [curr.alias]: () => { return curr.alias + ' call'; }, }; }, {}); client.getNotes(); My problem is really the lack of inference in the client variable, because currently the data type is {} despite appearing in the terminal {getNotes: ƒ, getComments: ƒ}. How can I resolve this? A: One way to resolve this is to use a type assertion to tell the TypeScript compiler that the type of the client variable is actually an object with the same properties as the InputBase interface. You can do this by either using the as keyword, or the <> syntax. For example, you can use the as keyword like this: const client = input.reduce((acc, curr: InputBase) => { return { ...acc, [curr.alias]: () => { return curr.alias + ' call'; }, } as { [key in InputBase['alias']]: () => string }; }, {}); Now, when you type client., you'll be presented with autocompletion options that match the values of the InputBase.alias property. A: In TypeScript, the type of the client variable in your example would be inferred as {}, because you are creating an object with dynamic property names using the reduce method. In order to provide type information for the client variable, you can use the Record type from TypeScript. This type allows you to define an object type with a set of known keys, and the values can have a specific type. Here is an example of how you could use the Record type to provide type information for the client variable: interface InputBase { alias: string; } const input: Array<InputBase> = [ { alias: 'getNotes' }, { alias: 'getComments' }, ]; // Define the type of the client variable as a Record with string keys and // values that are functions that return a string. const client: Record<string, () => string> = input.reduce((acc, curr: InputBase) => { return { ...acc, [curr.alias]: () => { return curr.alias + ' call'; }, }; }, {}); // Now TypeScript will provide intellisense for the client variable, // and you can see the list of available methods when you type `client.` client.getNotes(); Alternatively, you can use a type assertion to explicitly specify the type of the client variable. This allows you to provide a type for the client variable without using the Record type. Here is an example: interface InputBase { alias: string; } const input: Array<InputBase> = [ { alias: 'getNotes' }, { alias: 'getComments' }, ]; // Use a type assertion to explicitly specify the type of the client variable const client = input.reduce((acc, curr: InputBase) => { return { ...acc, [curr.alias]: () => { return curr.alias + ' call'; }, }; }, {}) as { [key: string]: () => string }; // Now TypeScript will provide intellisense for the client variable, // and you can see the list of available methods when you type `client.` client.getNotes(); I hope this helps! Let me know if you have any other questions.
How to infer property values from arrays of objects in Typescript?
I'd like the TypeScript compiler to infer the names of properties on an object so that it's easier to invoke the appropriate functions later. However, despite considering invoking functions, TypeScript doesn't give any intellisense of the functions I can invoke. Taking into account the following example: interface InputBase { alias: string; } const input: Array<InputBase> = [ { alias: 'getNotes' }, { alias: 'getComments' }, ]; const client = input.reduce((acc, curr: InputBase) => { return { ...acc, [curr.alias]: () => { return curr.alias + ' call'; }, }; }, {}); client.getNotes(); My problem is really the lack of inference in the client variable, because currently the data type is {} despite appearing in the terminal {getNotes: ƒ, getComments: ƒ}. How can I resolve this?
[ "One way to resolve this is to use a type assertion to tell the TypeScript compiler that the type of the client variable is actually an object with the same properties as the InputBase interface.\nYou can do this by either using the as keyword, or the <> syntax.\nFor example, you can use the as keyword like this:\nconst client = input.reduce((acc, curr: InputBase) => {\n return {\n ...acc,\n [curr.alias]: () => {\n return curr.alias + ' call';\n },\n } as { [key in InputBase['alias']]: () => string };\n}, {});\n\nNow, when you type client., you'll be presented with autocompletion options that match the values of the InputBase.alias property.\n", "In TypeScript, the type of the client variable in your example would be inferred as {}, because you are creating an object with dynamic property names using the reduce method.\nIn order to provide type information for the client variable, you can use the Record type from TypeScript. This type allows you to define an object type with a set of known keys, and the values can have a specific type.\nHere is an example of how you could use the Record type to provide type information for the client variable:\ninterface InputBase {\n alias: string;\n}\n\nconst input: Array<InputBase> = [\n { alias: 'getNotes' },\n { alias: 'getComments' },\n];\n\n// Define the type of the client variable as a Record with string keys and\n// values that are functions that return a string.\nconst client: Record<string, () => string> = input.reduce((acc, curr: InputBase) => {\n return {\n ...acc,\n [curr.alias]: () => {\n return curr.alias + ' call';\n },\n };\n}, {});\n\n// Now TypeScript will provide intellisense for the client variable,\n// and you can see the list of available methods when you type `client.`\nclient.getNotes();\n\nAlternatively, you can use a type assertion to explicitly specify the type of the client variable. This allows you to provide a type for the client variable without using the Record type. Here is an example:\ninterface InputBase {\n alias: string;\n}\n\nconst input: Array<InputBase> = [\n { alias: 'getNotes' },\n { alias: 'getComments' },\n];\n\n// Use a type assertion to explicitly specify the type of the client variable\nconst client = input.reduce((acc, curr: InputBase) => {\n return {\n ...acc,\n [curr.alias]: () => {\n return curr.alias + ' call';\n },\n };\n}, {}) as { [key: string]: () => string };\n\n// Now TypeScript will provide intellisense for the client variable,\n// and you can see the list of available methods when you type `client.`\nclient.getNotes();\n\nI hope this helps! Let me know if you have any other questions.\n" ]
[ 0, 0 ]
[]
[]
[ "node.js", "typescript" ]
stackoverflow_0074662904_node.js_typescript.txt
Q: My multi select is not working, and I can't save data into database I tried to make a function that add list of country. But it's not working at the last input (Những ngôn ngữ dịch. I can't save it into database to. What should I do? I tried to add as much as possible country on the last input. But it didn't show. Here are my code: import '../../css/style.css'; import { useEffect } from "react"; import { useState, useSelector } from "react"; import { ajaxCallGetUrlDemo, ajaxCallPost } from "../libs/base"; import Select from 'react-select' import { Const_Libs } from "../libs/Const_Libs"; const ModalAddNgonNgu = (props) => { const { handleGetLanguage } = props; const [ngonNgu, setNgonNgu] = useState({ language_name: '', main_lang: '', title_lang: '', describe_lang: '', author_lang: '', rate_lang: '', reviews_lang: '', // translate_list: [] translate_list: [] }); function SelectMainLanguage() { const [selectedOption, setSelectedOption] = useState({}); const options = [ { value: 'Vietnamese', label: 'Vietnamese' }, { value: 'English', label: 'English' }, { value: 'Chinese', label: 'Chinese' }, { value: 'Japanese', label: 'Japanese' }, { value: 'German', label: 'German' }, ]; const handleChangeOption = () => { return setSelectedOption; } useEffect(() => { if (selectedOption.value) { console.log(selectedOption) setNgonNgu({ ...ngonNgu, main_lang: selectedOption.value }) } }, [selectedOption]) // {console.log(selectedOption)} return ( <Select className={`col-12 o-languages`} value={ngonNgu.main_lang ? { value: ngonNgu.main_lang, label: ngonNgu.main_lang } : { value: "Chọn ngôn ngữ chính", label: "Chọn ngôn ngữ chính" }} onChange={handleChangeOption()} options={options} /> ) } function SelectTransLanguage() { const [selectedOption, setSelectedOption] = useState({}); const options = [ { value: "AF", label: "Afghanistan" }, { value: "AL", label: "Albania" }, { value: "DZ", label: "Algeria" }, { value: "AS", label: "American Samoa" }, { value: "AD", label: "Andorra" }, { value: "AO", label: "Angola" }, { value: "AI", label: "Anguilla" }, { value: "AQ", label: "Antarctica" }, { value: "AG", label: "Antigua And Barbuda" }, { value: "AR", label: "Argentina" }, { value: "AM", label: "Armenia" }, { value: "AW", label: "Aruba" }, { value: "AU", label: "Australia" }, { value: "AT", label: "Austria" }, { value: "AZ", label: "Azerbaijan" }, { value: "BS", label: "Bahamas The" }, { value: "BH", label: "Bahrain" }, { value: "BD", label: "Bangladesh" }, { value: "BB", label: "Barbados" }, { value: "BY", label: "Belarus" }, { value: "BE", label: "Belgium" }, { value: "BZ", label: "Belize" }, { value: "BJ", label: "Benin" }, { value: "BM", label: "Bermuda" }, { value: "BT", label: "Bhutan" }, { value: "BO", label: "Bolivia" }, { value: "BA", label: "Bosnia and Herzegovina" }, { value: "BW", label: "Botswana" }, { value: "BV", label: "Bouvet Island" }, { value: "BR", label: "Brazil" }, { value: "IO", label: "British Indian Ocean Territory" }, { value: "BN", label: "Brunei" }, { value: "BG", label: "Bulgaria" }, { value: "BF", label: "Burkina Faso" }, { value: "BI", label: "Burundi" }, { value: "KH", label: "Cambodia" }, { value: "CM", label: "Cameroon" }, { value: "CA", label: "Canada" }, { value: "CV", label: "Cape Verde" }, { value: "KY", label: "Cayman Islands" }, { value: "CF", label: "Central African Republic" }, { value: "TD", label: "Chad" }, { value: "CL", label: "Chile" }, { value: "CN", label: "China" }, { value: "CX", label: "Christmas Island" }, { value: "CC", label: "Cocos (Keeling) Islands" }, { value: "CO", label: "Colombia" }, { value: "KM", label: "Comoros" }, { value: "CG", label: "Congo" }, { value: "CD", label: "Congo The Democratic Republic Of The" }, { value: "CK", label: "Cook Islands" }, { value: "CR", label: "Costa Rica" }, { value: "CI", label: "Cote D'Ivoire (Ivory Coast)" }, { value: "HR", label: "Croatia (Hrvatska)" }, { value: "CU", label: "Cuba" }, { value: "CY", label: "Cyprus" }, { value: "CZ", label: "Czech Republic" }, { value: "DK", label: "Denmark" }, { value: "DJ", label: "Djibouti" }, { value: "DM", label: "Dominica" }, { value: "DO", label: "Dominican Republic" }, { value: "TP", label: "East Timor" }, { value: "EC", label: "Ecuador" }, { value: "EG", label: "Egypt" }, { value: "SV", label: "El Salvador" }, { value: "GQ", label: "Equatorial Guinea" }, { value: "ER", label: "Eritrea" }, { value: "EE", label: "Estonia" }, { value: "ET", label: "Ethiopia" }, { value: "XA", label: "External Territories of Australia" }, { value: "FK", label: "Falkland Islands" }, { value: "FO", label: "Faroe Islands" }, { value: "FJ", label: "Fiji Islands" }, { value: "FI", label: "Finland" }, { value: "FR", label: "France" }, { value: "GF", label: "French Guiana" }, { value: "PF", label: "French Polynesia" }, { value: "TF", label: "French Southern Territories" }, { value: "GA", label: "Gabon" }, { value: "GM", label: "Gambia The" }, { value: "GE", label: "Georgia" }, { value: "DE", label: "Germany" }, { value: "GH", label: "Ghana" }, { value: "GI", label: "Gibraltar" }, { value: "GR", label: "Greece" }, { value: "GL", label: "Greenland" }, { value: "GD", label: "Grenada" }, { value: "GP", label: "Guadeloupe" }, { value: "GU", label: "Guam" }, { value: "GT", label: "Guatemala" }, { value: "XU", label: "Guernsey and Alderney" }, { value: "GN", label: "Guinea" }, { value: "GW", label: "Guinea-Bissau" }, { value: "GY", label: "Guyana" }, { value: "HT", label: "Haiti" }, { value: "HM", label: "Heard and McDonald Islands" }, { value: "HN", label: "Honduras" }, { value: "HK", label: "Hong Kong S.A.R." }, { value: "HU", label: "Hungary" }, { value: "IS", label: "Iceland" }, { value: "IN", label: "India" }, { value: "ID", label: "Indonesia" }, { value: "IR", label: "Iran" }, { value: "IQ", label: "Iraq" }, { value: "IE", label: "Ireland" }, { value: "IL", label: "Israel" }, { value: "IT", label: "Italy" }, { value: "JM", label: "Jamaica" }, { value: "JP", label: "Japan" }, { value: "XJ", label: "Jersey" }, { value: "JO", label: "Jordan" }, { value: "KZ", label: "Kazakhstan" }, { value: "KE", label: "Kenya" }, { value: "KI", label: "Kiribati" }, { value: "KP", label: "Korea North" }, { value: "KR", label: "Korea South" }, { value: "KW", label: "Kuwait" }, { value: "KG", label: "Kyrgyzstan" }, { value: "LA", label: "Laos" }, { value: "LV", label: "Latvia" }, { value: "LB", label: "Lebanon" }, { value: "LS", label: "Lesotho" }, { value: "LR", label: "Liberia" }, { value: "LY", label: "Libya" }, { value: "LI", label: "Liechtenstein" }, { value: "LT", label: "Lithuania" }, { value: "LU", label: "Luxembourg" }, { value: "MO", label: "Macau S.A.R." }, { value: "MK", label: "Macedonia" }, { value: "MG", label: "Madagascar" }, { value: "MW", label: "Malawi" }, { value: "MY", label: "Malaysia" }, { value: "MV", label: "Maldives" }, { value: "ML", label: "Mali" }, { value: "MT", label: "Malta" }, { value: "XM", label: "Man (Isle of)" }, { value: "MH", label: "Marshall Islands" }, { value: "MQ", label: "Martinique" }, { value: "MR", label: "Mauritania" }, { value: "MU", label: "Mauritius" }, { value: "YT", label: "Mayotte" }, { value: "MX", label: "Mexico" }, { value: "FM", label: "Micronesia" }, { value: "MD", label: "Moldova" }, { value: "MC", label: "Monaco" }, { value: "MN", label: "Mongolia" }, { value: "MS", label: "Montserrat" }, { value: "MA", label: "Morocco" }, { value: "MZ", label: "Mozambique" }, { value: "MM", label: "Myanmar" }, { value: "NA", label: "Namibia" }, { value: "NR", label: "Nauru" }, { value: "NP", label: "Nepal" }, { value: "AN", label: "Netherlands Antilles" }, { value: "NL", label: "Netherlands The" }, { value: "NC", label: "New Caledonia" }, { value: "NZ", label: "New Zealand" }, { value: "NI", label: "Nicaragua" }, { value: "NE", label: "Niger" }, { value: "NG", label: "Nigeria" }, { value: "NU", label: "Niue" }, { value: "NF", label: "Norfolk Island" }, { value: "MP", label: "Northern Mariana Islands" }, { value: "NO", label: "Norway" }, { value: "OM", label: "Oman" }, { value: "PK", label: "Pakistan" }, { value: "PW", label: "Palau" }, { value: "PS", label: "Palestinian Territory Occupied" }, { value: "PA", label: "Panama" }, { value: "PG", label: "Papua new Guinea" }, { value: "PY", label: "Paraguay" }, { value: "PE", label: "Peru" }, { value: "PH", label: "Philippines" }, { value: "PN", label: "Pitcairn Island" }, { value: "PL", label: "Poland" }, { value: "PT", label: "Portugal" }, { value: "PR", label: "Puerto Rico" }, { value: "QA", label: "Qatar" }, { value: "RE", label: "Reunion" }, { value: "RO", label: "Romania" }, { value: "RU", label: "Russia" }, { value: "RW", label: "Rwanda" }, { value: "SH", label: "Saint Helena" }, { value: "KN", label: "Saint Kitts And Nevis" }, { value: "LC", label: "Saint Lucia" }, { value: "PM", label: "Saint Pierre and Miquelon" }, { value: "VC", label: "Saint Vincent And The Grenadines" }, { value: "WS", label: "Samoa" }, { value: "SM", label: "San Marino" }, { value: "ST", label: "Sao Tome and Principe" }, { value: "SA", label: "Saudi Arabia" }, { value: "SN", label: "Senegal" }, { value: "RS", label: "Serbia" }, { value: "SC", label: "Seychelles" }, { value: "SL", label: "Sierra Leone" }, { value: "SG", label: "Singapore" }, { value: "SK", label: "Slovakia" }, { value: "SI", label: "Slovenia" }, { value: "XG", label: "Smaller Territories of the UK" }, { value: "SB", label: "Solomon Islands" }, { value: "SO", label: "Somalia" }, { value: "ZA", label: "South Africa" }, { value: "GS", label: "South Georgia" }, { value: "SS", label: "South Sudan" }, { value: "ES", label: "Spain" }, { value: "LK", label: "Sri Lanka" }, { value: "SD", label: "Sudan" }, { value: "SR", label: "Suriname" }, { value: "SJ", label: "Svalbard And Jan Mayen Islands" }, { value: "SZ", label: "Swaziland" }, { value: "SE", label: "Sweden" }, { value: "CH", label: "Switzerland" }, { value: "SY", label: "Syria" }, { value: "TW", label: "Taiwan" }, { value: "TJ", label: "Tajikistan" }, { value: "TZ", label: "Tanzania" }, { value: "TH", label: "Thailand" }, { value: "TG", label: "Togo" }, { value: "TK", label: "Tokelau" }, { value: "TO", label: "Tonga" }, { value: "TT", label: "Trinidad And Tobago" }, { value: "TN", label: "Tunisia" }, { value: "TR", label: "Turkey" }, { value: "TM", label: "Turkmenistan" }, { value: "TC", label: "Turks And Caicos Islands" }, { value: "TV", label: "Tuvalu" }, { value: "UG", label: "Uganda" }, { value: "UA", label: "Ukraine" }, { value: "AE", label: "United Arab Emirates" }, { value: "GB", label: "United Kingdom" }, { value: "US", label: "United States" }, { value: "UM", label: "United States Minor Outlying Islands" }, { value: "UY", label: "Uruguay" }, { value: "UZ", label: "Uzbekistan" }, { value: "VU", label: "Vanuatu" }, { value: "VA", label: "Vatican City State (Holy See)" }, { value: "VE", label: "Venezuela" }, { value: "VN", label: "Vietnam" }, { value: "VG", label: "Virgin Islands (British)" }, { value: "VI", label: "Virgin Islands (US)" }, { value: "WF", label: "Wallis And Futuna Islands" }, { value: "EH", label: "Western Sahara" }, { value: "YE", label: "Yemen" }, { value: "YU", label: "Yugoslavia" }, { value: "ZM", label: "Zambia" }, { value: "ZW", label: "Zimbabwe" } ]; const handleChangeOption = () => { return setSelectedOption; } useEffect(() => { if (selectedOption.value) { console.log(selectedOption) setNgonNgu({ ...ngonNgu, translate_list: selectedOption.value }) } }, [selectedOption]) {console.log(selectedOption)} return ( <Select className={`col-12 o-languages`} isMulti value={ngonNgu.translate_list ? { value: ngonNgu.translate_list, label: ngonNgu.translate_list } : { value: "Chọn những ngôn ngữ dịch", label: "Chọn những ngôn ngữ dịch" }} onChange={handleChangeOption()} options={options} /> ) } const handleSubmit = () => { let arr = [{ nameLanguage: ngonNgu.language_name, mainLanguage: ngonNgu.main_lang, titleLanguage: ngonNgu.title_lang, descriptionLanguage: ngonNgu.describe_lang, authorLanguage: ngonNgu.author_lang, rateLanguage: ngonNgu.rate_lang, reviewsLanguage: ngonNgu.reviews_lang, transLanguage: ngonNgu.translate_list }] ajaxCallPost(`save-lang`, arr).then(rs => { resetData() handleGetLanguage(); Const_Libs.TOAST.success("Thêm thành công") }) } const resetData = () => { setNgonNgu({ language_name: '', main_lang: '', title_lang: '', describe_lang: '', author_lang: '', rate_lang: '', reviews_lang: '', translate_list: [] }) } return ( <> <button type="button" className="btn btn-primary" data-bs-toggle="modal" data-bs-target="#myModalAddNgonNgu" style={{ fontSize: '14px' }}> Thêm </button> <div> <div className="modal fade" id="myModalAddNgonNgu"> <div className="modal-dialog modal-dialog-centered" style={{ minWidth: '700px' }}> <div className="modal-content"> <div className="modal-header"> <h4 className="modal-title">Thêm ngôn ngữ</h4> <button type="button" className="btn-close" data-bs-dismiss="modal" /> </div> <div className="modal-body"> <form> <div className="col"> <div className="row-2"> <label htmlFor="name-campaign" className="form-label fs-6 fw-bolder">Tên ngôn ngữ</label> <input type="text" className="form-control" id="name-campaign" placeholder="Nhập tên ngôn ngữ...." value={ngonNgu.language_name} onChange={(e) => setNgonNgu({ ...ngonNgu, language_name: e.target.value })} /> </div> <div className="row-2"> <label htmlFor="name-campaign" className="form-label fs-6 fw-bolder">Tiêu đề</label> <input type="text" className="form-control" id="name-campaign" placeholder="Nhập tiêu đề...." value={ngonNgu.title_lang} onChange={(e) => setNgonNgu({ ...ngonNgu, title_lang: e.target.value })} /> </div> <div className="row-2"> <label htmlFor="name-campaign" className="form-label fs-6 fw-bolder">Mô tả</label> <input type="text" className="form-control" id="name-campaign" placeholder="Nhập mô tả...." value={ngonNgu.describe_lang} onChange={(e) => setNgonNgu({ ...ngonNgu, describe_lang: e.target.value })} /> </div> <div className="row-2"> <label htmlFor="name-campaign" className="form-label fs-6 fw-bolder">Tác giả</label> <input type="text" className="form-control" id="name-campaign" placeholder="Nhập tác giả (VD: Author)" value={ngonNgu.author_lang} onChange={(e) => setNgonNgu({ ...ngonNgu, author_lang: e.target.value })} /> </div> <div className="row-2"> <label htmlFor="name-campaign" className="form-label fs-6 fw-bolder">Đánh giá</label> <input type="text" className="form-control" id="name-campaign" placeholder="Nhập đánh giá (VD: Rate)" value={ngonNgu.rate_lang} onChange={(e) => setNgonNgu({ ...ngonNgu, rate_lang: e.target.value })} /> </div> <div className="row-2"> <label htmlFor="name-campaign" className="form-label fs-6 fw-bolder">Lượt đánh giá</label> <input type="text" className="form-control" id="name-campaign" placeholder="Nhập lượt đánh giá (VD: reviews)" value={ngonNgu.reviews_lang} onChange={(e) => setNgonNgu({ ...ngonNgu, reviews_lang: e.target.value })} /> </div> </div> <div className="col"> <div className="row-2"> <label htmlFor="name-campaign" className="form-label fs-6 fw-bolder">Ngôn ngữ chính</label> <SelectMainLanguage /> </div> <div className="row-2"> <label htmlFor="name-campaign" className="form-label fs-6 fw-bolder">Những ngôn ngữ dịch</label> <SelectTransLanguage /> </div> </div> </form> </div> <div className="modal-footer"> <button type="button" className="btn btn-success" data-bs-dismiss="modal" onClick={handleSubmit}>Submit</button> <button type="button" className="btn btn-danger" data-bs-dismiss="modal">Close</button> </div> </div> </div> </div> </div> </> ); } export default ModalAddNgonNgu; The backend is OK, so the problem is this thing. Can you show me the mistake? Thank you A: You should never define a component inside another component. Move both SelectMainLanguage and SelectTransLanguage out of ModalAddNgonNgu. Then connect these two components and ModalAddNgonNgu with props. Like this: const ModalAddNgonNgu = (props) => { const { handleGetLanguage } = props; .... ... rest of the component } // end of ModalAddNgonNgu definition function SelectTransLanguage({setNgonNgu}) { // setNgonNgu comes from ModalAddNgonNgu const [selectedOption, setSelectedOption] = useState({}) .... }
My multi select is not working, and I can't save data into database
I tried to make a function that add list of country. But it's not working at the last input (Những ngôn ngữ dịch. I can't save it into database to. What should I do? I tried to add as much as possible country on the last input. But it didn't show. Here are my code: import '../../css/style.css'; import { useEffect } from "react"; import { useState, useSelector } from "react"; import { ajaxCallGetUrlDemo, ajaxCallPost } from "../libs/base"; import Select from 'react-select' import { Const_Libs } from "../libs/Const_Libs"; const ModalAddNgonNgu = (props) => { const { handleGetLanguage } = props; const [ngonNgu, setNgonNgu] = useState({ language_name: '', main_lang: '', title_lang: '', describe_lang: '', author_lang: '', rate_lang: '', reviews_lang: '', // translate_list: [] translate_list: [] }); function SelectMainLanguage() { const [selectedOption, setSelectedOption] = useState({}); const options = [ { value: 'Vietnamese', label: 'Vietnamese' }, { value: 'English', label: 'English' }, { value: 'Chinese', label: 'Chinese' }, { value: 'Japanese', label: 'Japanese' }, { value: 'German', label: 'German' }, ]; const handleChangeOption = () => { return setSelectedOption; } useEffect(() => { if (selectedOption.value) { console.log(selectedOption) setNgonNgu({ ...ngonNgu, main_lang: selectedOption.value }) } }, [selectedOption]) // {console.log(selectedOption)} return ( <Select className={`col-12 o-languages`} value={ngonNgu.main_lang ? { value: ngonNgu.main_lang, label: ngonNgu.main_lang } : { value: "Chọn ngôn ngữ chính", label: "Chọn ngôn ngữ chính" }} onChange={handleChangeOption()} options={options} /> ) } function SelectTransLanguage() { const [selectedOption, setSelectedOption] = useState({}); const options = [ { value: "AF", label: "Afghanistan" }, { value: "AL", label: "Albania" }, { value: "DZ", label: "Algeria" }, { value: "AS", label: "American Samoa" }, { value: "AD", label: "Andorra" }, { value: "AO", label: "Angola" }, { value: "AI", label: "Anguilla" }, { value: "AQ", label: "Antarctica" }, { value: "AG", label: "Antigua And Barbuda" }, { value: "AR", label: "Argentina" }, { value: "AM", label: "Armenia" }, { value: "AW", label: "Aruba" }, { value: "AU", label: "Australia" }, { value: "AT", label: "Austria" }, { value: "AZ", label: "Azerbaijan" }, { value: "BS", label: "Bahamas The" }, { value: "BH", label: "Bahrain" }, { value: "BD", label: "Bangladesh" }, { value: "BB", label: "Barbados" }, { value: "BY", label: "Belarus" }, { value: "BE", label: "Belgium" }, { value: "BZ", label: "Belize" }, { value: "BJ", label: "Benin" }, { value: "BM", label: "Bermuda" }, { value: "BT", label: "Bhutan" }, { value: "BO", label: "Bolivia" }, { value: "BA", label: "Bosnia and Herzegovina" }, { value: "BW", label: "Botswana" }, { value: "BV", label: "Bouvet Island" }, { value: "BR", label: "Brazil" }, { value: "IO", label: "British Indian Ocean Territory" }, { value: "BN", label: "Brunei" }, { value: "BG", label: "Bulgaria" }, { value: "BF", label: "Burkina Faso" }, { value: "BI", label: "Burundi" }, { value: "KH", label: "Cambodia" }, { value: "CM", label: "Cameroon" }, { value: "CA", label: "Canada" }, { value: "CV", label: "Cape Verde" }, { value: "KY", label: "Cayman Islands" }, { value: "CF", label: "Central African Republic" }, { value: "TD", label: "Chad" }, { value: "CL", label: "Chile" }, { value: "CN", label: "China" }, { value: "CX", label: "Christmas Island" }, { value: "CC", label: "Cocos (Keeling) Islands" }, { value: "CO", label: "Colombia" }, { value: "KM", label: "Comoros" }, { value: "CG", label: "Congo" }, { value: "CD", label: "Congo The Democratic Republic Of The" }, { value: "CK", label: "Cook Islands" }, { value: "CR", label: "Costa Rica" }, { value: "CI", label: "Cote D'Ivoire (Ivory Coast)" }, { value: "HR", label: "Croatia (Hrvatska)" }, { value: "CU", label: "Cuba" }, { value: "CY", label: "Cyprus" }, { value: "CZ", label: "Czech Republic" }, { value: "DK", label: "Denmark" }, { value: "DJ", label: "Djibouti" }, { value: "DM", label: "Dominica" }, { value: "DO", label: "Dominican Republic" }, { value: "TP", label: "East Timor" }, { value: "EC", label: "Ecuador" }, { value: "EG", label: "Egypt" }, { value: "SV", label: "El Salvador" }, { value: "GQ", label: "Equatorial Guinea" }, { value: "ER", label: "Eritrea" }, { value: "EE", label: "Estonia" }, { value: "ET", label: "Ethiopia" }, { value: "XA", label: "External Territories of Australia" }, { value: "FK", label: "Falkland Islands" }, { value: "FO", label: "Faroe Islands" }, { value: "FJ", label: "Fiji Islands" }, { value: "FI", label: "Finland" }, { value: "FR", label: "France" }, { value: "GF", label: "French Guiana" }, { value: "PF", label: "French Polynesia" }, { value: "TF", label: "French Southern Territories" }, { value: "GA", label: "Gabon" }, { value: "GM", label: "Gambia The" }, { value: "GE", label: "Georgia" }, { value: "DE", label: "Germany" }, { value: "GH", label: "Ghana" }, { value: "GI", label: "Gibraltar" }, { value: "GR", label: "Greece" }, { value: "GL", label: "Greenland" }, { value: "GD", label: "Grenada" }, { value: "GP", label: "Guadeloupe" }, { value: "GU", label: "Guam" }, { value: "GT", label: "Guatemala" }, { value: "XU", label: "Guernsey and Alderney" }, { value: "GN", label: "Guinea" }, { value: "GW", label: "Guinea-Bissau" }, { value: "GY", label: "Guyana" }, { value: "HT", label: "Haiti" }, { value: "HM", label: "Heard and McDonald Islands" }, { value: "HN", label: "Honduras" }, { value: "HK", label: "Hong Kong S.A.R." }, { value: "HU", label: "Hungary" }, { value: "IS", label: "Iceland" }, { value: "IN", label: "India" }, { value: "ID", label: "Indonesia" }, { value: "IR", label: "Iran" }, { value: "IQ", label: "Iraq" }, { value: "IE", label: "Ireland" }, { value: "IL", label: "Israel" }, { value: "IT", label: "Italy" }, { value: "JM", label: "Jamaica" }, { value: "JP", label: "Japan" }, { value: "XJ", label: "Jersey" }, { value: "JO", label: "Jordan" }, { value: "KZ", label: "Kazakhstan" }, { value: "KE", label: "Kenya" }, { value: "KI", label: "Kiribati" }, { value: "KP", label: "Korea North" }, { value: "KR", label: "Korea South" }, { value: "KW", label: "Kuwait" }, { value: "KG", label: "Kyrgyzstan" }, { value: "LA", label: "Laos" }, { value: "LV", label: "Latvia" }, { value: "LB", label: "Lebanon" }, { value: "LS", label: "Lesotho" }, { value: "LR", label: "Liberia" }, { value: "LY", label: "Libya" }, { value: "LI", label: "Liechtenstein" }, { value: "LT", label: "Lithuania" }, { value: "LU", label: "Luxembourg" }, { value: "MO", label: "Macau S.A.R." }, { value: "MK", label: "Macedonia" }, { value: "MG", label: "Madagascar" }, { value: "MW", label: "Malawi" }, { value: "MY", label: "Malaysia" }, { value: "MV", label: "Maldives" }, { value: "ML", label: "Mali" }, { value: "MT", label: "Malta" }, { value: "XM", label: "Man (Isle of)" }, { value: "MH", label: "Marshall Islands" }, { value: "MQ", label: "Martinique" }, { value: "MR", label: "Mauritania" }, { value: "MU", label: "Mauritius" }, { value: "YT", label: "Mayotte" }, { value: "MX", label: "Mexico" }, { value: "FM", label: "Micronesia" }, { value: "MD", label: "Moldova" }, { value: "MC", label: "Monaco" }, { value: "MN", label: "Mongolia" }, { value: "MS", label: "Montserrat" }, { value: "MA", label: "Morocco" }, { value: "MZ", label: "Mozambique" }, { value: "MM", label: "Myanmar" }, { value: "NA", label: "Namibia" }, { value: "NR", label: "Nauru" }, { value: "NP", label: "Nepal" }, { value: "AN", label: "Netherlands Antilles" }, { value: "NL", label: "Netherlands The" }, { value: "NC", label: "New Caledonia" }, { value: "NZ", label: "New Zealand" }, { value: "NI", label: "Nicaragua" }, { value: "NE", label: "Niger" }, { value: "NG", label: "Nigeria" }, { value: "NU", label: "Niue" }, { value: "NF", label: "Norfolk Island" }, { value: "MP", label: "Northern Mariana Islands" }, { value: "NO", label: "Norway" }, { value: "OM", label: "Oman" }, { value: "PK", label: "Pakistan" }, { value: "PW", label: "Palau" }, { value: "PS", label: "Palestinian Territory Occupied" }, { value: "PA", label: "Panama" }, { value: "PG", label: "Papua new Guinea" }, { value: "PY", label: "Paraguay" }, { value: "PE", label: "Peru" }, { value: "PH", label: "Philippines" }, { value: "PN", label: "Pitcairn Island" }, { value: "PL", label: "Poland" }, { value: "PT", label: "Portugal" }, { value: "PR", label: "Puerto Rico" }, { value: "QA", label: "Qatar" }, { value: "RE", label: "Reunion" }, { value: "RO", label: "Romania" }, { value: "RU", label: "Russia" }, { value: "RW", label: "Rwanda" }, { value: "SH", label: "Saint Helena" }, { value: "KN", label: "Saint Kitts And Nevis" }, { value: "LC", label: "Saint Lucia" }, { value: "PM", label: "Saint Pierre and Miquelon" }, { value: "VC", label: "Saint Vincent And The Grenadines" }, { value: "WS", label: "Samoa" }, { value: "SM", label: "San Marino" }, { value: "ST", label: "Sao Tome and Principe" }, { value: "SA", label: "Saudi Arabia" }, { value: "SN", label: "Senegal" }, { value: "RS", label: "Serbia" }, { value: "SC", label: "Seychelles" }, { value: "SL", label: "Sierra Leone" }, { value: "SG", label: "Singapore" }, { value: "SK", label: "Slovakia" }, { value: "SI", label: "Slovenia" }, { value: "XG", label: "Smaller Territories of the UK" }, { value: "SB", label: "Solomon Islands" }, { value: "SO", label: "Somalia" }, { value: "ZA", label: "South Africa" }, { value: "GS", label: "South Georgia" }, { value: "SS", label: "South Sudan" }, { value: "ES", label: "Spain" }, { value: "LK", label: "Sri Lanka" }, { value: "SD", label: "Sudan" }, { value: "SR", label: "Suriname" }, { value: "SJ", label: "Svalbard And Jan Mayen Islands" }, { value: "SZ", label: "Swaziland" }, { value: "SE", label: "Sweden" }, { value: "CH", label: "Switzerland" }, { value: "SY", label: "Syria" }, { value: "TW", label: "Taiwan" }, { value: "TJ", label: "Tajikistan" }, { value: "TZ", label: "Tanzania" }, { value: "TH", label: "Thailand" }, { value: "TG", label: "Togo" }, { value: "TK", label: "Tokelau" }, { value: "TO", label: "Tonga" }, { value: "TT", label: "Trinidad And Tobago" }, { value: "TN", label: "Tunisia" }, { value: "TR", label: "Turkey" }, { value: "TM", label: "Turkmenistan" }, { value: "TC", label: "Turks And Caicos Islands" }, { value: "TV", label: "Tuvalu" }, { value: "UG", label: "Uganda" }, { value: "UA", label: "Ukraine" }, { value: "AE", label: "United Arab Emirates" }, { value: "GB", label: "United Kingdom" }, { value: "US", label: "United States" }, { value: "UM", label: "United States Minor Outlying Islands" }, { value: "UY", label: "Uruguay" }, { value: "UZ", label: "Uzbekistan" }, { value: "VU", label: "Vanuatu" }, { value: "VA", label: "Vatican City State (Holy See)" }, { value: "VE", label: "Venezuela" }, { value: "VN", label: "Vietnam" }, { value: "VG", label: "Virgin Islands (British)" }, { value: "VI", label: "Virgin Islands (US)" }, { value: "WF", label: "Wallis And Futuna Islands" }, { value: "EH", label: "Western Sahara" }, { value: "YE", label: "Yemen" }, { value: "YU", label: "Yugoslavia" }, { value: "ZM", label: "Zambia" }, { value: "ZW", label: "Zimbabwe" } ]; const handleChangeOption = () => { return setSelectedOption; } useEffect(() => { if (selectedOption.value) { console.log(selectedOption) setNgonNgu({ ...ngonNgu, translate_list: selectedOption.value }) } }, [selectedOption]) {console.log(selectedOption)} return ( <Select className={`col-12 o-languages`} isMulti value={ngonNgu.translate_list ? { value: ngonNgu.translate_list, label: ngonNgu.translate_list } : { value: "Chọn những ngôn ngữ dịch", label: "Chọn những ngôn ngữ dịch" }} onChange={handleChangeOption()} options={options} /> ) } const handleSubmit = () => { let arr = [{ nameLanguage: ngonNgu.language_name, mainLanguage: ngonNgu.main_lang, titleLanguage: ngonNgu.title_lang, descriptionLanguage: ngonNgu.describe_lang, authorLanguage: ngonNgu.author_lang, rateLanguage: ngonNgu.rate_lang, reviewsLanguage: ngonNgu.reviews_lang, transLanguage: ngonNgu.translate_list }] ajaxCallPost(`save-lang`, arr).then(rs => { resetData() handleGetLanguage(); Const_Libs.TOAST.success("Thêm thành công") }) } const resetData = () => { setNgonNgu({ language_name: '', main_lang: '', title_lang: '', describe_lang: '', author_lang: '', rate_lang: '', reviews_lang: '', translate_list: [] }) } return ( <> <button type="button" className="btn btn-primary" data-bs-toggle="modal" data-bs-target="#myModalAddNgonNgu" style={{ fontSize: '14px' }}> Thêm </button> <div> <div className="modal fade" id="myModalAddNgonNgu"> <div className="modal-dialog modal-dialog-centered" style={{ minWidth: '700px' }}> <div className="modal-content"> <div className="modal-header"> <h4 className="modal-title">Thêm ngôn ngữ</h4> <button type="button" className="btn-close" data-bs-dismiss="modal" /> </div> <div className="modal-body"> <form> <div className="col"> <div className="row-2"> <label htmlFor="name-campaign" className="form-label fs-6 fw-bolder">Tên ngôn ngữ</label> <input type="text" className="form-control" id="name-campaign" placeholder="Nhập tên ngôn ngữ...." value={ngonNgu.language_name} onChange={(e) => setNgonNgu({ ...ngonNgu, language_name: e.target.value })} /> </div> <div className="row-2"> <label htmlFor="name-campaign" className="form-label fs-6 fw-bolder">Tiêu đề</label> <input type="text" className="form-control" id="name-campaign" placeholder="Nhập tiêu đề...." value={ngonNgu.title_lang} onChange={(e) => setNgonNgu({ ...ngonNgu, title_lang: e.target.value })} /> </div> <div className="row-2"> <label htmlFor="name-campaign" className="form-label fs-6 fw-bolder">Mô tả</label> <input type="text" className="form-control" id="name-campaign" placeholder="Nhập mô tả...." value={ngonNgu.describe_lang} onChange={(e) => setNgonNgu({ ...ngonNgu, describe_lang: e.target.value })} /> </div> <div className="row-2"> <label htmlFor="name-campaign" className="form-label fs-6 fw-bolder">Tác giả</label> <input type="text" className="form-control" id="name-campaign" placeholder="Nhập tác giả (VD: Author)" value={ngonNgu.author_lang} onChange={(e) => setNgonNgu({ ...ngonNgu, author_lang: e.target.value })} /> </div> <div className="row-2"> <label htmlFor="name-campaign" className="form-label fs-6 fw-bolder">Đánh giá</label> <input type="text" className="form-control" id="name-campaign" placeholder="Nhập đánh giá (VD: Rate)" value={ngonNgu.rate_lang} onChange={(e) => setNgonNgu({ ...ngonNgu, rate_lang: e.target.value })} /> </div> <div className="row-2"> <label htmlFor="name-campaign" className="form-label fs-6 fw-bolder">Lượt đánh giá</label> <input type="text" className="form-control" id="name-campaign" placeholder="Nhập lượt đánh giá (VD: reviews)" value={ngonNgu.reviews_lang} onChange={(e) => setNgonNgu({ ...ngonNgu, reviews_lang: e.target.value })} /> </div> </div> <div className="col"> <div className="row-2"> <label htmlFor="name-campaign" className="form-label fs-6 fw-bolder">Ngôn ngữ chính</label> <SelectMainLanguage /> </div> <div className="row-2"> <label htmlFor="name-campaign" className="form-label fs-6 fw-bolder">Những ngôn ngữ dịch</label> <SelectTransLanguage /> </div> </div> </form> </div> <div className="modal-footer"> <button type="button" className="btn btn-success" data-bs-dismiss="modal" onClick={handleSubmit}>Submit</button> <button type="button" className="btn btn-danger" data-bs-dismiss="modal">Close</button> </div> </div> </div> </div> </div> </> ); } export default ModalAddNgonNgu; The backend is OK, so the problem is this thing. Can you show me the mistake? Thank you
[ "You should never define a component inside another component.\nMove both SelectMainLanguage and SelectTransLanguage out of ModalAddNgonNgu.\nThen connect these two components and ModalAddNgonNgu with props.\nLike this:\n const ModalAddNgonNgu = (props) => {\n\n const { handleGetLanguage } = props; ....\n\n ... rest of the component\n\n } // end of ModalAddNgonNgu definition\n\nfunction SelectTransLanguage({setNgonNgu}) { // setNgonNgu comes from ModalAddNgonNgu\n\n const [selectedOption, setSelectedOption] = useState({}) ....\n\n }\n\n" ]
[ 0 ]
[]
[]
[ "database", "frontend", "multi_select", "reactjs", "save" ]
stackoverflow_0074663771_database_frontend_multi_select_reactjs_save.txt
Q: Apache/2.4.46 (Ubuntu) Server at Port 80 Error I have uploaded 2 django projects before and worked perfectly fine to the Linode server, but now for some reason I am receiving Error for 403 Port 80 error. I have revisited a tutorial word by word and revised it several times, I am not sure why I keep receving this error: Error for 403 Forbidden You don't have permission to access this resource. Apache/2.4.46 (Ubuntu) Server at Port 80 Here is the config file: <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/ahesham/Portfolio/static <Directory /home/ahesham/Portfolio/static> Require all granted </Directory> Alias /media /home/ahesham/Portfolio/media <Directory /home/ahesham/Portfolio/media> Require all granted </Directory> <Directory /home/ahesham/Portfolio/Portfolio> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/ahesham/Portfolio/Portfolio/wsgi.py WSGIDaemonProcess Portfolio python-path=/home/ahesham/Portfolio python-home=/home/ahesham/Portfolio/venv WSGIProcessGroup Portfolio </VirtualHost> In the error.log Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' when i type ls -la total 36 drwxr-x--- 5 ahesham ahesham 4096 Aug 6 23:08 . drwxr-xr-x 3 root root 4096 Aug 5 02:30 .. -rw------- 1 ahesham ahesham 2115 Aug 7 02:20 .bash_history -rw-r--r-- 1 ahesham ahesham 220 Aug 5 02:30 .bash_logout -rw-r--r-- 1 ahesham ahesham 3771 Aug 5 02:30 .bashrc drwx------ 3 ahesham ahesham 4096 Aug 6 12:53 .cache drwxrwxr-x 10 ahesham www-data 4096 Aug 6 20:15 Portfolio -rw-r--r-- 1 ahesham ahesham 807 Aug 5 02:30 .profile drwx------ 2 ahesham ahesham 4096 Aug 5 02:41 .ssh -rw-r--r-- 1 ahesham ahesham 0 Aug 5 02:42 .sudo_as_admin_successful when I try the project on an 8000 server it is woking perfectly fine other wise when I change the following commands: sudo ufw delete allow 8000 sudo ufw allow http/tcp sudo service apache2 restart My question is what am I doing wrong and how to fix it? Please let me know if there are further information required to help assist fixing it A: type cd /etc/apache2/sites-available/ sudo cp 000-default.conf Portfolio.conf and add ServerName server_domain_name_or_IP <Directory /var/www/html/> AllowOverride All </Directory> A: Hi I'm pretty sure you encountered the same issue as i did when follow Corey Schafer's Django tutorial on deploy django on linux server. The issue was the permission settings on the Django project folder which Corey didn't mention in his video but if you run: sudo chmod -R 775 ~/django_project/ This will fix the issue. Credit to: mod_wsgi - Permission denied - Unable to start Python home
Apache/2.4.46 (Ubuntu) Server at Port 80 Error
I have uploaded 2 django projects before and worked perfectly fine to the Linode server, but now for some reason I am receiving Error for 403 Port 80 error. I have revisited a tutorial word by word and revised it several times, I am not sure why I keep receving this error: Error for 403 Forbidden You don't have permission to access this resource. Apache/2.4.46 (Ubuntu) Server at Port 80 Here is the config file: <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/ahesham/Portfolio/static <Directory /home/ahesham/Portfolio/static> Require all granted </Directory> Alias /media /home/ahesham/Portfolio/media <Directory /home/ahesham/Portfolio/media> Require all granted </Directory> <Directory /home/ahesham/Portfolio/Portfolio> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/ahesham/Portfolio/Portfolio/wsgi.py WSGIDaemonProcess Portfolio python-path=/home/ahesham/Portfolio python-home=/home/ahesham/Portfolio/venv WSGIProcessGroup Portfolio </VirtualHost> In the error.log Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' when i type ls -la total 36 drwxr-x--- 5 ahesham ahesham 4096 Aug 6 23:08 . drwxr-xr-x 3 root root 4096 Aug 5 02:30 .. -rw------- 1 ahesham ahesham 2115 Aug 7 02:20 .bash_history -rw-r--r-- 1 ahesham ahesham 220 Aug 5 02:30 .bash_logout -rw-r--r-- 1 ahesham ahesham 3771 Aug 5 02:30 .bashrc drwx------ 3 ahesham ahesham 4096 Aug 6 12:53 .cache drwxrwxr-x 10 ahesham www-data 4096 Aug 6 20:15 Portfolio -rw-r--r-- 1 ahesham ahesham 807 Aug 5 02:30 .profile drwx------ 2 ahesham ahesham 4096 Aug 5 02:41 .ssh -rw-r--r-- 1 ahesham ahesham 0 Aug 5 02:42 .sudo_as_admin_successful when I try the project on an 8000 server it is woking perfectly fine other wise when I change the following commands: sudo ufw delete allow 8000 sudo ufw allow http/tcp sudo service apache2 restart My question is what am I doing wrong and how to fix it? Please let me know if there are further information required to help assist fixing it
[ "type cd /etc/apache2/sites-available/\nsudo cp 000-default.conf Portfolio.conf\nand add\n ServerName server_domain_name_or_IP\n <Directory /var/www/html/>\n AllowOverride All\n </Directory>\n\n", "Hi I'm pretty sure you encountered the same issue as i did when follow Corey Schafer's Django tutorial on deploy django on linux server.\nThe issue was the permission settings on the Django project folder which Corey didn't mention in his video but if you run:\nsudo chmod -R 775 ~/django_project/\n\nThis will fix the issue.\nCredit to:\n\nmod_wsgi - Permission denied - Unable to start Python home\n\n" ]
[ 0, 0 ]
[]
[]
[ "apache", "linode" ]
stackoverflow_0068688423_apache_linode.txt
Q: How would you iterate through a 2D array by going down through columns? I want this for a ragged array but seeing in a regular array first might work I would like my array to from index to index like thisfor example: (0,0), (1,0), (2,0) etc. I've tried what seems like it should be the right way, but my loops stop after the first column and I get an index out of bounds exception. Here's what I did: int[][] array2d = { {4,5, 3,8}, {8,3,99,6}, {5,7, 9,1} }; int currentRow = 0; for (int currentColumn = 0; currentColumn < (array2d[currentRow].length); currentColumn++) { for(currentRow = 0; currentRow < array2d.length; currentRow++) { System.out.println(array2d[currentRow][currentColumn]); } } A: First, let's address a bug in your code. Consider this loop: int i; for (i = 0; i < 10; i++) { /* loop body */ } The loop runs until i < 10 evaluates to false. In this example, when the loop exits, i will have a value of 10. Consider the inner loop in your code: for (currentRow = 0; currentRow < array2d.length; currentRow++) When this loop exits, currentRow will be equal to array2d.length. Then, control will return to the outer loop. When it does, in the control expression currentColumn < (array2d[currentRow].length), this part array2d[currentRow] will throw an IndexOutOfBoundsException. As you already know, here is the standard way of going through a 2D array in row by column order is like this: for (int row = 0; row < array2d.length; row++) { for (int column = 0; column < array2d[row].length; column++ { // things to do in inner loop } If you wanted to process a rectangular 2D array in column order, the code might look like this: for (int column = 0; column < array2d[0].length; column++) { for (int row = 0; row < array2d.length; row++) { // loop body } } But, what if the array is ragged? Start by finding the row with the maximum number of columns at the start: int maxColumns = 0; for (int i = 0; i < array.length; i++) { maxColumns = Math.max (maxColumns, array2d[i].length); } Then, your code might look something like this: for (int column = 0; column < maxColumns; column++) { for (int row = 0; row < array2d.length; row++) { if (column < array2d[row].length) { // do something with array2d [row][column] } else { // do something for the case where // array2d [row] doesn't have a value in "column" } } } An alternative might be to try to trap an ArrayIndexOutOfBoundsException. However, that might be regarded as a poor programming practice. A: int[][] array2d = { {1,2,3,4}, {5,6,7,8}, { 9,10,11,12} }; int r=array2d.length,c=array2d[0].length; for (int i=0;i<c;i++) { for(int j=0;j<r;j++) { System.out.print(array2d[j][i]+" "); } System.out.println(); } You've ran the columns before the rows and because its a 2d array of length 3x4 , Its giving a indexOutOfBoundsException whilest iterating through the array. A: You need to get the maximum number of columns before printing. public static void main(String[] args) { int[][] array2d = { {4, 5, 3, 8}, {}, {8, 6}, {2}, {5, 7, 9, 1, 0} }; int maxRow = array2d.length; int maxColumn = array2d[0].length; for (int r = 1; r < maxRow; ++r) maxColumn = Math.max(maxColumn, array2d[r].length); for (int c = 0; c < maxColumn; ++c) { for (int r = 0; r < maxRow; ++r) if (c < array2d[r].length) System.out.print(array2d[r][c] + " "); else System.out.print("* "); System.out.println(); } } output: 4 * 8 2 5 5 * 6 * 7 3 * * * 9 8 * * * 1 * * * * 0 Or you can get away with it by scanning the row one more time. public static void main(String[] args) { int[][] array2d = { {4, 5, 3, 8}, {}, {8, 6}, {2}, {5, 7, 9, 1, 0} }; int rowSie = array2d.length; for (int c = 0; true; ++c) { StringBuilder sb = new StringBuilder(); boolean out = false; for (int r = 0; r < rowSie; ++r) if (c < array2d[r].length) { sb.append(array2d[r][c]).append(" "); out = true; } else sb.append("* "); if (!out) break; System.out.println(sb); } } output: 4 * 8 2 5 5 * 6 * 7 3 * * * 9 8 * * * 1 * * * * 0
How would you iterate through a 2D array by going down through columns? I want this for a ragged array but seeing in a regular array first might work
I would like my array to from index to index like thisfor example: (0,0), (1,0), (2,0) etc. I've tried what seems like it should be the right way, but my loops stop after the first column and I get an index out of bounds exception. Here's what I did: int[][] array2d = { {4,5, 3,8}, {8,3,99,6}, {5,7, 9,1} }; int currentRow = 0; for (int currentColumn = 0; currentColumn < (array2d[currentRow].length); currentColumn++) { for(currentRow = 0; currentRow < array2d.length; currentRow++) { System.out.println(array2d[currentRow][currentColumn]); } }
[ "First, let's address a bug in your code. Consider this loop:\nint i;\nfor (i = 0; i < 10; i++) { /* loop body */ }\n\nThe loop runs until i < 10 evaluates to false. In this example, when the loop exits, i will have a value of 10.\nConsider the inner loop in your code:\n for (currentRow = 0; currentRow < array2d.length; currentRow++) \n\nWhen this loop exits, currentRow will be equal to array2d.length. Then, control will return to the outer loop. When it does, in the control expression currentColumn < (array2d[currentRow].length), this part array2d[currentRow] will throw an IndexOutOfBoundsException.\nAs you already know, here is the standard way of going through a 2D array in row by column order is like this:\n for (int row = 0; row < array2d.length; row++) { \n for (int column = 0; column < array2d[row].length; column++ { \n // things to do in inner loop\n }\n\nIf you wanted to process a rectangular 2D array in column order, the code might look like this:\n for (int column = 0; column < array2d[0].length; column++) { \n for (int row = 0; row < array2d.length; row++) {\n // loop body\n }\n }\n\nBut, what if the array is ragged?\nStart by finding the row with the maximum number of columns at the start:\n int maxColumns = 0;\n for (int i = 0; i < array.length; i++) { \n maxColumns = Math.max (maxColumns, array2d[i].length);\n }\n\nThen, your code might look something like this:\n for (int column = 0; column < maxColumns; column++) { \n for (int row = 0; row < array2d.length; row++) { \n if (column < array2d[row].length) {\n // do something with array2d [row][column]\n } else { \n // do something for the case where \n // array2d [row] doesn't have a value in \"column\" \n }\n }\n }\n\nAn alternative might be to try to trap an ArrayIndexOutOfBoundsException. However, that might be regarded as a poor programming practice.\n", " int[][] array2d =\n {\n {1,2,3,4},\n {5,6,7,8},\n { 9,10,11,12}\n };\n int r=array2d.length,c=array2d[0].length;\n for (int i=0;i<c;i++)\n {\n for(int j=0;j<r;j++)\n {\n System.out.print(array2d[j][i]+\" \");\n }\n System.out.println();\n }\n\nYou've ran the columns before the rows and because its a 2d array of length 3x4 , Its giving a indexOutOfBoundsException whilest iterating through the array.\n", "You need to get the maximum number of columns before printing.\npublic static void main(String[] args) {\n int[][] array2d = {\n {4, 5, 3, 8},\n {},\n {8, 6},\n {2},\n {5, 7, 9, 1, 0}\n };\n int maxRow = array2d.length;\n int maxColumn = array2d[0].length;\n for (int r = 1; r < maxRow; ++r)\n maxColumn = Math.max(maxColumn, array2d[r].length);\n for (int c = 0; c < maxColumn; ++c) {\n for (int r = 0; r < maxRow; ++r)\n if (c < array2d[r].length)\n System.out.print(array2d[r][c] + \" \");\n else\n System.out.print(\"* \");\n System.out.println();\n }\n}\n\noutput:\n4 * 8 2 5 \n5 * 6 * 7 \n3 * * * 9 \n8 * * * 1 \n* * * * 0 \n\nOr you can get away with it by scanning the row one more time.\npublic static void main(String[] args) {\n int[][] array2d = {\n {4, 5, 3, 8},\n {},\n {8, 6},\n {2},\n {5, 7, 9, 1, 0}\n };\n int rowSie = array2d.length;\n for (int c = 0; true; ++c) {\n StringBuilder sb = new StringBuilder();\n boolean out = false;\n for (int r = 0; r < rowSie; ++r)\n if (c < array2d[r].length) {\n sb.append(array2d[r][c]).append(\" \");\n out = true;\n } else\n sb.append(\"* \");\n if (!out)\n break;\n System.out.println(sb);\n }\n}\n\noutput:\n4 * 8 2 5 \n5 * 6 * 7 \n3 * * * 9 \n8 * * * 1 \n* * * * 0 \n\n" ]
[ 1, 0, 0 ]
[]
[]
[ "java", "multidimensional_array", "nested_for_loop", "ragged" ]
stackoverflow_0074663643_java_multidimensional_array_nested_for_loop_ragged.txt
Q: Parsing binary data in java received over TCP socket server I have a socket server which keeps listening to incoming requests. The data received will be in the form of binary array of bytes. Data format is something like this. 2321902321221200AA Whereas 1 byte is data begin 4 bits is version 4 bits is data return type 5 bytes are product code 2 bytes data length The question is, how to parse the data and segregate the parameters. Thanks in advance!! A: Try java.io.DataInputStream: DataInputStream dis = new DataInputStream(in); byte b = dis.readByte(); int version = (b >> 4) & 0xF; int returnType = b & 0xF; byte[] productCode = new byte[5]; dis.readFully(productCode); int len = dis.readShort() & 0xFFFF; A: if use the java binary block parser then code will look like class Parsed { @Bin byte begin; @Bin(type = BinType.BIT) int version; @Bin(type = BinType.BIT) int returnType; @Bin byte [] productCode; @Bin(type = BinType.USHORT) int dataLength; } final Parsed parsed = JBBPParser.prepare("byte begin; bit:4 version; bit:4 returnType; byte [5] productCode; ushort dataLength;") .parse(new byte[]{0x23,0x21,(byte)0x90,0x23,0x21,0x22,0x12,0x00,(byte)0xAA}) .mapTo(Parsed.class); assertEquals(0x23, parsed.begin); assertEquals(0x01, parsed.version); assertEquals(0x02, parsed.returnType); assertArrayEquals(new byte[]{(byte)0x90,0x23,0x21,0x22,0x12}, parsed.productCode); assertEquals(0x00AA,parsed.dataLength); A: try { char [] cbuf = new char[16]; char databegin = cbuf[0]; char [] version = Arrays.copyOfRange(cbuf, 1, 6) char [] product_typep = Arrays.copyOfRange(cbuf, 7, 12) char []data_lendth = Arrays.copyOfRange(cbuf, 13, 15) } catch(Error e){ System.out.println(e); } A: byte [] data = receiveData (); int dataBegin = data [0]; // Once field is 1-byte, it is simple! int version = data [1] & 0x0F; // Use shift (>>>) and binary "and" (&) int returnCode = // to extract value of fields that are (data [1] >>> 4) & 0x0F; // smaller than one byte byte [] productCode = // Copy fixed-size portions of data new byte [] { // into separate arrays using hardcode data [2], data [3], // (as here), or System.arrayCopy data [4], data [5], // in case field occupies quite data [6]}; // a many bytes. int dataLength = // Use shift (<<) binary or (|) to (data [7] & 0xFF) | // Combine several bytes into one integer ((data [8] & 0xFF) << 8); // We assume little-endian encoding here A: I would got for some king of package reader: class Record { ..... Record static fromBytes(byte[] bytes) { // here use ByteBuffer or DataInputStream to extract filds ...... } } Record readNextRecord(InputStream in) { int len = in.read() && 0xFF; byte[] data = new byte[len]; in.read(data); return Record.fromBytes(data) } { InputStream in = ....; Record r readNextRecord(in); process (r); } Of course you need to add error handling. In general, for something which should run reliable, I will suggest to use NIO framework like Grizzly or Netty. A: Recommend you a java tool(FastProto) to parse binary quickly. import org.indunet.fastproto.annotation.*; public class Request { @UInt8Type(offset = 0) Integer header; // begin @UInt8Type(offset = 1) @DecodingFormula(lambda = "x -> x >> 4") Integer version; // version @UInt8Type(offset = 1) @DecodingFormula(lambda = "x -> x & 0x0F") Integer returnType; // return type @BinaryType(offset = 2, length = 5) byte[] productCode; // product code @UInteger16Type(7) Integer length; // data length } byte[] bytes = ... // the binary received Request request = FastProto.parse(bytes, Request.class); If the project can solve your problem, please give a star, thanks. GitHub Repo: https://github.com/indunet/fastproto
Parsing binary data in java received over TCP socket server
I have a socket server which keeps listening to incoming requests. The data received will be in the form of binary array of bytes. Data format is something like this. 2321902321221200AA Whereas 1 byte is data begin 4 bits is version 4 bits is data return type 5 bytes are product code 2 bytes data length The question is, how to parse the data and segregate the parameters. Thanks in advance!!
[ "Try java.io.DataInputStream:\n DataInputStream dis = new DataInputStream(in);\n byte b = dis.readByte();\n int version = (b >> 4) & 0xF;\n int returnType = b & 0xF;\n byte[] productCode = new byte[5];\n dis.readFully(productCode);\n int len = dis.readShort() & 0xFFFF;\n\n", "if use the java binary block parser then code will look like\nclass Parsed { \n @Bin byte begin; \n @Bin(type = BinType.BIT) int version; \n @Bin(type = BinType.BIT) int returnType;\n @Bin byte [] productCode;\n @Bin(type = BinType.USHORT) int dataLength;\n}\nfinal Parsed parsed = JBBPParser.prepare(\"byte begin; bit:4 version; bit:4 returnType; byte [5] productCode; ushort dataLength;\")\n .parse(new byte[]{0x23,0x21,(byte)0x90,0x23,0x21,0x22,0x12,0x00,(byte)0xAA})\n .mapTo(Parsed.class);\n\nassertEquals(0x23, parsed.begin);\nassertEquals(0x01, parsed.version);\nassertEquals(0x02, parsed.returnType);\nassertArrayEquals(new byte[]{(byte)0x90,0x23,0x21,0x22,0x12}, parsed.productCode);\nassertEquals(0x00AA,parsed.dataLength);\n\n", "try {\n char [] cbuf = new char[16];\n char databegin = cbuf[0];\n char [] version = Arrays.copyOfRange(cbuf, 1, 6) \n char [] product_typep = Arrays.copyOfRange(cbuf, 7, 12)\n char []data_lendth = Arrays.copyOfRange(cbuf, 13, 15)\n\n} catch(Error e){\n System.out.println(e);\n}\n\n", "byte [] data = receiveData ();\n\nint dataBegin = data [0]; // Once field is 1-byte, it is simple!\nint version = data [1] & 0x0F; // Use shift (>>>) and binary \"and\" (&)\nint returnCode = // to extract value of fields that are\n (data [1] >>> 4) & 0x0F; // smaller than one byte\nbyte [] productCode = // Copy fixed-size portions of data\n new byte [] { // into separate arrays using hardcode\n data [2], data [3], // (as here), or System.arrayCopy\n data [4], data [5], // in case field occupies quite\n data [6]}; // a many bytes.\nint dataLength = // Use shift (<<) binary or (|) to \n (data [7] & 0xFF) | // Combine several bytes into one integer\n ((data [8] & 0xFF) << 8); // We assume little-endian encoding here\n\n", "I would got for some king of package reader:\nclass Record {\n\n .....\n\n Record static fromBytes(byte[] bytes) {\n // here use ByteBuffer or DataInputStream to extract filds\n ......\n }\n}\n\n\nRecord readNextRecord(InputStream in) {\n int len = in.read() && 0xFF;\n byte[] data = new byte[len];\n in.read(data);\n return Record.fromBytes(data)\n}\n\n\n\n{\n InputStream in = ....;\n Record r readNextRecord(in);\n process (r);\n}\n\nOf course you need to add error handling. In general, for something which should run reliable, I will suggest to use NIO framework like Grizzly or Netty.\n", "Recommend you a java tool(FastProto) to parse binary quickly.\nimport org.indunet.fastproto.annotation.*;\n\npublic class Request {\n @UInt8Type(offset = 0)\n Integer header; // begin\n \n @UInt8Type(offset = 1)\n @DecodingFormula(lambda = \"x -> x >> 4\")\n Integer version; // version\n\n @UInt8Type(offset = 1)\n @DecodingFormula(lambda = \"x -> x & 0x0F\")\n Integer returnType; // return type\n\n @BinaryType(offset = 2, length = 5)\n byte[] productCode; // product code\n\n @UInteger16Type(7)\n Integer length; // data length\n}\n\n\nbyte[] bytes = ... // the binary received\nRequest request = FastProto.parse(bytes, Request.class);\n\n\nIf the project can solve your problem, please give a star, thanks.\nGitHub Repo: https://github.com/indunet/fastproto\n" ]
[ 1, 1, 0, 0, 0, 0 ]
[ "You might get the data via the ByteArrayOutputStream\nAnd then parse the bytes by applying masks (mainly AND, OR).\nTake a look at This question\nHope this helps\n" ]
[ -1 ]
[ "binary_data", "java", "parsing", "serversocket" ]
stackoverflow_0014795269_binary_data_java_parsing_serversocket.txt
Q: Does a constraint violation always result in a diagnostic? I was wondering what would happen if I left out the parameter declarations in a K&R function definition, so I tried the following: #include <stdio.h> void f(a) // int a; <--- omitting `declaration-list` causes warning in gcc, but nothing in clang { printf("%d", 9); } int main() { f(9); return 0; } When I compile this with gcc 11, a diagnostic is issued in the form of a warning (i.e. warning: type of 'a' defaults to 'int'). However, when I compile it with clang 14, no diagnostic message is issued. This confused me because in the Standard, omitting the declaration-list (which contains the parameter declarations) is a constraint violation (as per C11 6.9.1(6)), which requires a conforming implementation to issue a diagnostic (as per C11 5.1.1.3). So, why didn't clang issue a warning? Have I misinterpreted something? A: clang will generate a warning if compiled with the -pedantic flag. <source>:3:8: warning: parameter 'a' was not declared, defaulting to type 'int' [-Wpedantic] void f(a) ^ 1 warning generated. ASM generation compiler returned: 0 <source>:3:8: warning: parameter 'a' was not declared, defaulting to type 'int' [-Wpedantic] void f(a) ^ 1 warning generated. Execution build compiler returned: 0 Program returned: 0 9 https://godbolt.org/z/e73M1Eq8E
Does a constraint violation always result in a diagnostic?
I was wondering what would happen if I left out the parameter declarations in a K&R function definition, so I tried the following: #include <stdio.h> void f(a) // int a; <--- omitting `declaration-list` causes warning in gcc, but nothing in clang { printf("%d", 9); } int main() { f(9); return 0; } When I compile this with gcc 11, a diagnostic is issued in the form of a warning (i.e. warning: type of 'a' defaults to 'int'). However, when I compile it with clang 14, no diagnostic message is issued. This confused me because in the Standard, omitting the declaration-list (which contains the parameter declarations) is a constraint violation (as per C11 6.9.1(6)), which requires a conforming implementation to issue a diagnostic (as per C11 5.1.1.3). So, why didn't clang issue a warning? Have I misinterpreted something?
[ "clang will generate a warning if compiled with the -pedantic flag.\n<source>:3:8: warning: parameter 'a' was not declared, defaulting to type 'int' [-Wpedantic]\nvoid f(a) \n ^\n1 warning generated.\nASM generation compiler returned: 0\n<source>:3:8: warning: parameter 'a' was not declared, defaulting to type 'int' [-Wpedantic]\nvoid f(a) \n ^\n1 warning generated.\nExecution build compiler returned: 0\nProgram returned: 0\n9\n\nhttps://godbolt.org/z/e73M1Eq8E\n" ]
[ 1 ]
[]
[]
[ "c", "language_lawyer" ]
stackoverflow_0074663869_c_language_lawyer.txt
Q: How do I loop through this dictionary correctly in python? favorite_foods = {'bill': 'cake', 'alex': 'patacones'} for name in favorite_foods: print(f"I dont agree with your favorite food {name.title()}.") for food in (favorite_foods.values()): print(f"{food.title()} is delicious, but not that good!") if food in (favorite_foods.values() endswith(s) print(f"{food.title()} are delicous, but not that good!") How do I loop through this dictionary correctly? I want it to say I dont agree with your favorite food Bill. Cake is delicious but not that good! I dont agree with your favorite food Alex. Patacones are delicious, but not that good! I appreciate all the help. Thank you. The code cycles through all of the values instead of stopping after one. I googled the endswith function to see if I could get the code to print something different if the value ended in 's' but it didnt work. Before I added that line it printed the following. I dont agree with your favorite food Bill. Cake is delicious, but not that good! Cake are delicous, but not that good! Patacones is delicious, but not that good! Patacones are delicous, but not that good! I dont agree with your favorite food Alex. Cake is delicious, but not that good! Cake are delicous, but not that good! Patacones is delicious, but not that good! Patacones are delicous, but not that good! I wanted to find a way to trigger "are" when the value was plural and "is" if the value was singular. A: use .items() to loop through dict. Also, if you want the output to be a long string (i.e., no new line), you can use list and join. favorite_foods = {'bill': 'cake', 'alex': 'patacones'} output = [] for k,v in favorite_foods.items(): output.append(f"I dont agree with your favorite food {k.title()}.") if v[-1] == 's': output.append(f"{v.title()} are delicious, but not that good!") else: output.append(f"{v.title()} is delicious, but not that good!") print(" ".join(output)) output: I dont agree with your favorite food Bill. Cake is delicious, but not that good! I dont agree with your favorite food Alex. Patacones are delicious, but not that good! A: you can use 2 things to make this correct and simpler. Use for key, val in <dict_name>.items() to loop through key, value pairs at the same time. Use ternary operator in cases when you need to choose a value based on a boolean. So for example print(("yum!" if tasteGood else "gross!")) will print "yum!" when tasteGood is True, but print "gross!" when tasteGood is false. So to put everything together favFoods = { 'bill':'cake','alex':'patacones' } for name, food in favFoods.items(): print(f"I dont agree with your favorite food {name.title()}.") print(f"{food.title()} {('are' if food.endswith('s') else 'is')} delicious, but not that good!") A: You had a ton of syntax errors, and also your if statement was trying to be a for loop. This works: favorite_foods = {'bill': 'cake', 'alex': 'patacones'} for name in favorite_foods: print(f"I dont agree with your favorite food {name.title()}.") for food in (favorite_foods.values()): if food.endswith('s'): print(f"{food.title()} are delicous, but not that good!") else: print(f"{food.title()} is delicious, but not that good!")
How do I loop through this dictionary correctly in python?
favorite_foods = {'bill': 'cake', 'alex': 'patacones'} for name in favorite_foods: print(f"I dont agree with your favorite food {name.title()}.") for food in (favorite_foods.values()): print(f"{food.title()} is delicious, but not that good!") if food in (favorite_foods.values() endswith(s) print(f"{food.title()} are delicous, but not that good!") How do I loop through this dictionary correctly? I want it to say I dont agree with your favorite food Bill. Cake is delicious but not that good! I dont agree with your favorite food Alex. Patacones are delicious, but not that good! I appreciate all the help. Thank you. The code cycles through all of the values instead of stopping after one. I googled the endswith function to see if I could get the code to print something different if the value ended in 's' but it didnt work. Before I added that line it printed the following. I dont agree with your favorite food Bill. Cake is delicious, but not that good! Cake are delicous, but not that good! Patacones is delicious, but not that good! Patacones are delicous, but not that good! I dont agree with your favorite food Alex. Cake is delicious, but not that good! Cake are delicous, but not that good! Patacones is delicious, but not that good! Patacones are delicous, but not that good! I wanted to find a way to trigger "are" when the value was plural and "is" if the value was singular.
[ "use .items() to loop through dict. Also, if you want the output to be a long string (i.e., no new line), you can use list and join.\nfavorite_foods = {'bill': 'cake', 'alex': 'patacones'}\n\noutput = []\nfor k,v in favorite_foods.items():\n output.append(f\"I dont agree with your favorite food {k.title()}.\")\n if v[-1] == 's':\n output.append(f\"{v.title()} are delicious, but not that good!\")\n else:\n output.append(f\"{v.title()} is delicious, but not that good!\")\n\nprint(\" \".join(output))\n\noutput:\nI dont agree with your favorite food Bill. Cake is delicious, but not that good! I dont agree with your favorite food Alex. Patacones are delicious, but not that good! \n\n", "you can use 2 things to make this correct and simpler.\nUse for key, val in <dict_name>.items() to loop through key, value pairs at the same time.\nUse ternary operator in cases when you need to choose a value based on a boolean. So for example print((\"yum!\" if tasteGood else \"gross!\")) will print \"yum!\" when tasteGood is True, but print \"gross!\" when tasteGood is false.\nSo to put everything together\nfavFoods = {\n'bill':'cake','alex':'patacones'\n}\n\nfor name, food in favFoods.items():\n print(f\"I dont agree with your favorite food {name.title()}.\")\n print(f\"{food.title()} {('are' if food.endswith('s') else 'is')} delicious, but not that good!\")\n\n", "You had a ton of syntax errors, and also your if statement was trying to be a for loop. This works:\nfavorite_foods = {'bill': 'cake', 'alex': 'patacones'}\n\nfor name in favorite_foods:\n print(f\"I dont agree with your favorite food {name.title()}.\")\n \n for food in (favorite_foods.values()):\n if food.endswith('s'):\n print(f\"{food.title()} are delicous, but not that good!\")\n else:\n print(f\"{food.title()} is delicious, but not that good!\")\n\n" ]
[ 0, 0, 0 ]
[]
[]
[ "dictionary", "loops", "python" ]
stackoverflow_0074663867_dictionary_loops_python.txt
Q: DPDK Multi-process; Kill a primary process and restart as a secondary doesn't work I'm already running up to 4 DPDK processes next to each other without any issues and I can also restart secondary processes successfully. I read here in end of the symmetric multi-process section, that you can destroy the primary process and restart it as a secondary. But when I'm trying to restart the primary process, I run into some problems. For example: Running 2 processes. Each of them will stream data from its own dedicated port to the 0. queue of the virtual function. The goal is now to restart the first process as secondary. After the init of the EAL , mbufs, and rings, I call rte_eal_remote_launch() for each process with its own dedicated lcore which launches a function that does some packet processing. Start primary: $ sudo mp_dpdk_app -l 0-4 -n 2 --proc-type=primary -- -p 3 --num-procs=2 --proc-id=0 Output: EAL init start. EAL: Detected CPU lcores: 64 EAL: Detected NUMA nodes: 2 EAL: Detected shared linkage of DPDK EAL: Multi-process socket /var/run/dpdk/rte/mp_socket EAL: Selected IOVA mode 'PA' EAL: No available 1048576 kB hugepages reported EAL: VFIO support initialized EAL: Using IOMMU type 8 (No-IOMMU) EAL: Probe PCI driver: net_ixgbe_vf (8086:10ed) device: 0000:19:10.0 (socket 0) EAL: Probe PCI driver: net_ixgbe_vf (8086:10ed) device: 0000:19:10.1 (socket 0) TELEMETRY: No legacy callbacks, legacy socket not created EAL Process Type: PRIMARY Start the secondary: $ sudo mp_dpdk_app -l 0-4 -n 2 --proc-type=secondary -- -p 3 --num-procs=2 --proc-id=1 Output: EAL init start. EAL: Detected CPU lcores: 64 EAL: Detected NUMA nodes: 2 EAL: Detected shared linkage of DPDK EAL: Multi-process socket /var/run/dpdk/rte/mp_socket_13330_2fd6664d78de EAL: Selected IOVA mode 'PA' EAL: VFIO support initialized EAL: Using IOMMU type 8 (No-IOMMU) EAL: Probe PCI driver: net_ixgbe_vf (8086:10ed) device: 0000:19:10.0 (socket 0) eth_ixgbevf_dev_init(): No TX queues configured yet. Using default TX function. EAL: Probe PCI driver: net_ixgbe_vf (8086:10ed) device: 0000:19:10.1 (socket 0) eth_ixgbevf_dev_init(): No TX queues configured yet. Using default TX function. EAL Process Type: SECONDARY Kill primary and restart with: $ sudo mp_dpdk_app -l 0-4 -n 2 --proc-type=secondary -- -p 3 --num-procs=2 --proc-id=0 But the init fails with the following output: EAL init start. EAL: Detected CPU lcores: 64 EAL: Detected NUMA nodes: 2 EAL: Detected shared linkage of DPDK EAL: Multi-process socket /var/run/dpdk/rte/mp_socket_13473_2fda4aa02c52 EAL: failed to send to (/var/run/dpdk/rte/mp_socket) due to Connection refused EAL: Fail to send request /var/run/dpdk/rte/mp_socket:bus_vdev_mp vdev_scan(): Failed to request vdev from primary EAL: Selected IOVA mode 'PA' EAL: failed to send to (/var/run/dpdk/rte/mp_socket) due to Connection refused EAL: Fail to send request /var/run/dpdk/rte/mp_socket:eal_vfio_mp_sync EAL: Cannot request default VFIO container fd EAL: VFIO support could not be initialized EAL: Requested device 0000:19:10.0 cannot be used EAL: Requested device 0000:19:10.1 cannot be used EAL: Error - exiting with code: 1 Cause: :: no Ethernet ports found I noticed that a new mp socket is created (mp_socket_13473_2fda4aa02c52). But somehow the EAL tries then to connect to the rte/mp_socket, which was created by the primary process at the beginning and don't use the new one. If I exit the primary process with rte_eal_cleanup() , the /rte/mp_socket is removed and I still can't start a new secondary process due to the error /rte/mp_process does not exist My hardware setup: Network devices using DPDK-compatible driver ============================================ 0000:19:10.0 '82599 Ethernet Controller Virtual Function 10ed' drv=vfio-pci unused=ixgbevf 0000:19:10.1 '82599 Ethernet Controller Virtual Function 10ed' drv=vfio-pci unused=ixgbevf The processes don't have to communicate in-between each other. Can anybody give me a clue about this issue? Any help will be appreciated. A: The short answer to the question In DPDK multiprocess scenario (Primary & 1 or multiple secondary processes), if the DPDK primary process is stopped|killed can restarting the process allows it to communicate with the secondary process? is No, it can not. let me explain this for clarity below Please make use of DPDK documentation on multiprocess, which clarifies it is primary process is one which initializes the huge pages and creates the MP_HANDLE to communicate with the secondary process. In contrast, secondary or multiple secondaries attach with primary using MP_HANDLE. Primary process makes use of PCI, virtual, Hugepage, cores and creates unique file-id in the default path as /var/run/dpdk/{file-prefix}-appname. there ae configuration or conf settings saved in this path, which helps the secondary to make use of the hugepage address to MMAP in shared mode. So when a primary comes up with all the required resource secondary dpdk process make uses pre-initialized environment to run certain subset of DPDK API So when a primary process is stopped|killed, the resource mapping and configuration are not cleaned by default, which allows the existing secondary process to continue working. In case of EAL-ARGS --no-shconf immediate clean up of the folder /var/run/dpdk/{file-prefix}-dpdk is triggered (also does not support secondary process). Thereby starting|restarting a new primary will fail, as the PCI resources, hugepages, cores and file path (/var/run/dpdk/{file-prefix}-appname) already is been used. hence the expectation of restarting primary can it connect to running secondary is not true. There are internal check rte_eal_init routine with the standard DPDK releases.
DPDK Multi-process; Kill a primary process and restart as a secondary doesn't work
I'm already running up to 4 DPDK processes next to each other without any issues and I can also restart secondary processes successfully. I read here in end of the symmetric multi-process section, that you can destroy the primary process and restart it as a secondary. But when I'm trying to restart the primary process, I run into some problems. For example: Running 2 processes. Each of them will stream data from its own dedicated port to the 0. queue of the virtual function. The goal is now to restart the first process as secondary. After the init of the EAL , mbufs, and rings, I call rte_eal_remote_launch() for each process with its own dedicated lcore which launches a function that does some packet processing. Start primary: $ sudo mp_dpdk_app -l 0-4 -n 2 --proc-type=primary -- -p 3 --num-procs=2 --proc-id=0 Output: EAL init start. EAL: Detected CPU lcores: 64 EAL: Detected NUMA nodes: 2 EAL: Detected shared linkage of DPDK EAL: Multi-process socket /var/run/dpdk/rte/mp_socket EAL: Selected IOVA mode 'PA' EAL: No available 1048576 kB hugepages reported EAL: VFIO support initialized EAL: Using IOMMU type 8 (No-IOMMU) EAL: Probe PCI driver: net_ixgbe_vf (8086:10ed) device: 0000:19:10.0 (socket 0) EAL: Probe PCI driver: net_ixgbe_vf (8086:10ed) device: 0000:19:10.1 (socket 0) TELEMETRY: No legacy callbacks, legacy socket not created EAL Process Type: PRIMARY Start the secondary: $ sudo mp_dpdk_app -l 0-4 -n 2 --proc-type=secondary -- -p 3 --num-procs=2 --proc-id=1 Output: EAL init start. EAL: Detected CPU lcores: 64 EAL: Detected NUMA nodes: 2 EAL: Detected shared linkage of DPDK EAL: Multi-process socket /var/run/dpdk/rte/mp_socket_13330_2fd6664d78de EAL: Selected IOVA mode 'PA' EAL: VFIO support initialized EAL: Using IOMMU type 8 (No-IOMMU) EAL: Probe PCI driver: net_ixgbe_vf (8086:10ed) device: 0000:19:10.0 (socket 0) eth_ixgbevf_dev_init(): No TX queues configured yet. Using default TX function. EAL: Probe PCI driver: net_ixgbe_vf (8086:10ed) device: 0000:19:10.1 (socket 0) eth_ixgbevf_dev_init(): No TX queues configured yet. Using default TX function. EAL Process Type: SECONDARY Kill primary and restart with: $ sudo mp_dpdk_app -l 0-4 -n 2 --proc-type=secondary -- -p 3 --num-procs=2 --proc-id=0 But the init fails with the following output: EAL init start. EAL: Detected CPU lcores: 64 EAL: Detected NUMA nodes: 2 EAL: Detected shared linkage of DPDK EAL: Multi-process socket /var/run/dpdk/rte/mp_socket_13473_2fda4aa02c52 EAL: failed to send to (/var/run/dpdk/rte/mp_socket) due to Connection refused EAL: Fail to send request /var/run/dpdk/rte/mp_socket:bus_vdev_mp vdev_scan(): Failed to request vdev from primary EAL: Selected IOVA mode 'PA' EAL: failed to send to (/var/run/dpdk/rte/mp_socket) due to Connection refused EAL: Fail to send request /var/run/dpdk/rte/mp_socket:eal_vfio_mp_sync EAL: Cannot request default VFIO container fd EAL: VFIO support could not be initialized EAL: Requested device 0000:19:10.0 cannot be used EAL: Requested device 0000:19:10.1 cannot be used EAL: Error - exiting with code: 1 Cause: :: no Ethernet ports found I noticed that a new mp socket is created (mp_socket_13473_2fda4aa02c52). But somehow the EAL tries then to connect to the rte/mp_socket, which was created by the primary process at the beginning and don't use the new one. If I exit the primary process with rte_eal_cleanup() , the /rte/mp_socket is removed and I still can't start a new secondary process due to the error /rte/mp_process does not exist My hardware setup: Network devices using DPDK-compatible driver ============================================ 0000:19:10.0 '82599 Ethernet Controller Virtual Function 10ed' drv=vfio-pci unused=ixgbevf 0000:19:10.1 '82599 Ethernet Controller Virtual Function 10ed' drv=vfio-pci unused=ixgbevf The processes don't have to communicate in-between each other. Can anybody give me a clue about this issue? Any help will be appreciated.
[ "The short answer to the question In DPDK multiprocess scenario (Primary & 1 or multiple secondary processes), if the DPDK primary process is stopped|killed can restarting the process allows it to communicate with the secondary process? is No, it can not.\nlet me explain this for clarity below\n\nPlease make use of DPDK documentation on multiprocess, which clarifies it is primary process is one which initializes the huge pages and creates the MP_HANDLE to communicate with the secondary process. In contrast, secondary or multiple secondaries attach with primary using MP_HANDLE.\nPrimary process makes use of PCI, virtual, Hugepage, cores and creates unique file-id in the default path as /var/run/dpdk/{file-prefix}-appname.\nthere ae configuration or conf settings saved in this path, which helps the secondary to make use of the hugepage address to MMAP in shared mode.\nSo when a primary comes up with all the required resource secondary dpdk process make uses pre-initialized environment to run certain subset of DPDK API\n\n\nSo when a primary process is stopped|killed, the resource mapping and configuration are not cleaned by default, which allows the existing secondary process to continue working. In case of EAL-ARGS --no-shconf immediate clean up of the folder /var/run/dpdk/{file-prefix}-dpdk is triggered (also does not support secondary process). Thereby starting|restarting a new primary will fail, as the PCI resources, hugepages, cores and file path (/var/run/dpdk/{file-prefix}-appname) already is been used.\nhence the expectation of restarting primary can it connect to running secondary is not true. There are internal check rte_eal_init routine with the standard DPDK releases.\n" ]
[ 0 ]
[]
[]
[ "dpdk", "dpdk_pmd", "pmd" ]
stackoverflow_0074602244_dpdk_dpdk_pmd_pmd.txt
Q: How can you return the most recent posts from custom post types in random order How can you return the most recent posts from custom post types in random order my code is below: $args2 = array( 'post_type' => array( 'cme-education', 'post', 'media_gallery', 'learning-zone' ), 'posts_per_page' => '1', 'post__not_in' => $clicked_activities_array, //'post__in' => $args1, 'orderby' => 'rand', 'post_date' => 'DESC', 'order' => 'DESC', 'tax_query' => array( array( 'taxonomy' => 'vocabulary_1', 'field' => 'term_id', 'terms' => array(2, 21) ) ) ); A: I managed to solve this by using the date_query argument which accepts a date filter and allowed me to use the orderby => 'rand to get random posts. Anyway for those who may come across a similar issue the code I used is below. $before_date = date('d F Y', strtotime("+2 days")); $after_date = date('d F Y', strtotime("-1 years")); $recently_added_activities = array( 'post_type' => array( 'cme-education', 'post', 'media_gallery', 'learning-zone' ), 'posts_per_page' => '1', 'post__not_in' => $clicked_activities_array, 'orderby' => 'rand', 'date_query' => array( array( 'after' => $after_date, 'before' => $before_date, 'inclusive' => true, ), ), 'order' => 'DESC', 'tax_query' => array( array( 'taxonomy' => 'vocabulary_1', 'field' => 'name', 'terms' => $postTerm ), ), );
How can you return the most recent posts from custom post types in random order
How can you return the most recent posts from custom post types in random order my code is below: $args2 = array( 'post_type' => array( 'cme-education', 'post', 'media_gallery', 'learning-zone' ), 'posts_per_page' => '1', 'post__not_in' => $clicked_activities_array, //'post__in' => $args1, 'orderby' => 'rand', 'post_date' => 'DESC', 'order' => 'DESC', 'tax_query' => array( array( 'taxonomy' => 'vocabulary_1', 'field' => 'term_id', 'terms' => array(2, 21) ) ) );
[ "I managed to solve this by using the date_query argument which accepts a date filter and allowed me to use the orderby => 'rand to get random posts. Anyway for those who may come across a similar issue the code I used is below.\n$before_date = date('d F Y', strtotime(\"+2 days\"));\n$after_date = date('d F Y', strtotime(\"-1 years\"));\n\n$recently_added_activities = array(\n 'post_type' => array( 'cme-education', 'post', 'media_gallery', 'learning-zone' ),\n 'posts_per_page' => '1',\n 'post__not_in' => $clicked_activities_array,\n 'orderby' => 'rand',\n 'date_query' => array(\n array(\n 'after' => $after_date,\n 'before' => $before_date,\n 'inclusive' => true,\n ),\n ),\n 'order' => 'DESC',\n 'tax_query' => array(\n array(\n 'taxonomy' => 'vocabulary_1',\n 'field' => 'name',\n 'terms' => $postTerm\n ),\n ),\n);\n\n" ]
[ 0 ]
[]
[]
[ "php", "wordpress" ]
stackoverflow_0074661354_php_wordpress.txt
Q: Is there any function in excel to find day time between two date and time in Excel? I need a formula to calculate between two date and time excluding lunch time, holidays, weekend and between 09:00 and 18:00 work hours. For example, 25/07/2022 12:00 and 29/07/2022 10:00 and answer has to be 1 day, 06:00 Thanks in advance. I had a formula but it didn't work when hours bigger than 24 hours. A: I don't know how you got to 1 day and 6 hours, but here is a customizable way to filter your time difference calculation: =LET( start,E3, end,E4, holidays,$B$3:$B$5, array,SEQUENCE(INT(end)-INT(start)+1,24,INT(start),TIME(1,0,0)), crit_1,array>=start, crit_2,array<=end, crit_3,WEEKDAY(array,2)<6, crit_4,HOUR(array)>=9, crit_5,HOUR(array)<=18, crit_6,HOUR(array)<>13, crit_7,ISERROR(MATCH(DATE(YEAR(array),MONTH(array),DAY(array)),holidays,0)), result,SUM(crit_1*crit_2*crit_3*crit_4*crit_5*crit_6*crit_7), result ) Limitation This solution only works on an hourly level, i.e. the start and end dates and times will only be considered on a full hour basis. When providing times like 12:45 as input, the 15 minute increment won't be accounted for. Explanation The 4th item in the LET() function SEQUENCE(INT(end)-INT(start)+1,24,INT(start),TIME(1,0,0)) creates an array that contains all hours within the start and end date of the range: (transposed for illustrative purposes) then, based on that array, the different 'crit_n' statements are the individual criteria you mentioned. For example, crit_1,array>=start means that only the dates and times after the start date and time will be counted, or crit_6,HOUR(array)<>13 is the lunch break (assuming the 13th hour is lunch time), ... All of the individual crit_n's are then arrays of the same size containing TRUE and FALSE elements. At the end of the LET() function, by multiplying all the individual crit_n arrays, the product returns a single array that will then only contain those hours where all individual criteria statements are TRUE: So then the SUM() function is simply returning the total number of hours that fit all criteria. Example I assumed lunch hour to be hour 13, and I assumed the 28th to be a holiday within the given range. With those assumptions and the other criteria you already specified above, I'm getting the following result: Which looks like this when going into the formula bar: A: In cell G2, you can put the following formula: =LET(from,A2:A4,to,B2:B4,holidays,C2:C2,startHr,E1,endHr,E2, lunchS, E3, lunchE, E4, CALC, LAMBDA(date,isFrom, LET(noWkDay, NETWORKDAYS(date,date,holidays)=0, IF(noWkDay, 0, LET(d, INT(date), start, d + startHr, end, d + endHr, noOverlap, IF(isFrom, date > end, date < start), lunchDur, lunchE-lunchS, ls, d + lunchS, le, d + lunchE, isInner, IF(isFrom, date > start, date < end), diff, IF(isFrom, end-date-1 - IF(date < ls, lunchDur, 0), date-start-1 - IF(date > le, lunchDur, 0)), IF(noOverlap, -1, IF(isInner, diff, 0)))))), MAP(from,to,LAMBDA(ff,tt, LET(wkdays, NETWORKDAYS(ff,tt,holidays), duration, wkdays + CALC(ff, TRUE) + CALC(tt, FALSE), days, INT(duration), time, duration - TRUNC(duration), TEXT(days, "d") &" days "& TEXT(time, "hh:mm") &" hrs " ))) ) and here is the output: Explanation Used LET function for easy reading and composition. The main idea is first to calculate the number of working days excluding holidays from column value to to column value. We use for that NETWORKDAYS function. Once we have this value for each row, we need to adjust it considering the first day and last day of the interval, in case we cannot count as a full day and instead considering hours. For inner days (not start/end of the interval) it is counted as an entire day. We use MAP function to do the calculation over all values of from and to names. For each corresponding value (ff, tt) we calculate the working days (wkdays). Once we have this value, we use the user LAMBDA function CALC to adjust it. The function has a second input argument isFrom to consider both scenarios, i.e. adjustment at the beginning of the interval (isFrom = TRUE) or to the end of the interval (isFrom=FALSE). The first input argument is the given date. In case the input date of CALC is a non working day, we don't need to make any adjustment. We check it with the name noWkDay. If that is not the case, then we need we need to determine if there is no overlap (noOverlap): IF(isFrom, date > end, date < start) where start, end names correspond to the same date as date, but with different hours corresponding to start Hr and end Hr (E1:E2). For example for the first row, there is no overlap, because the end date doesn't have hour information, i.e. (12:00 AM), in such case the corresponding date should not be taken into account and CALC returns -1, i.e. one day needs to be subtracted. In case we have overlap, then we need to consider the case the working hours are lower than the maximum working hours (from 9:00 to 18:00). It is identified with the name isInner. If that is the case, we calculate the actual hours. We need to subtract 1 because it is going to be one less full working day and instead to consider the corresponding hours (that should be less than 9hrs, which is the maximum workday duration). The calculation is carried under the name diff: IF(isFrom, end-date-1 - IF(date < ls, lunchDur, 0), date-start-1 - IF(date > le, lunchDur, 0)) If the actual start is before the start of the lunch time (ls), then we need to subtract lunch duration (lunchDur). Similarly if the actual end is is after lunch time, we need to discount it too. Finally, we use CALC to calculate the interval duration: wkdays + CALC(ff, TRUE) + CALC(tt, FALSE) Once we have this information, it is just to put in the specified format indicating days and hours. Now let's review some of the sample input data and results: The interval starts on Monday 7/25 and ends on Friday 7/29, therefore we have 5 working days, but 7/26 is a holiday, so the maximum number of working days will be 4 days. For the interval [7/25, 7/29] starts and ends on midnight (12:00 AM), therefore the last day of the interval should not be considered, so actual working days will be 3. Interval [7/25 10:00, 7/29 17:00]. For the start of the interval we cannot count one day, instead 8hrs and for the end of the interval, the same situation 8hrs, so instead of 4days we are goin to have 2days plus 16hrs, but we need to subtract in both cases the lunch duration (1hr) so the final result will be 2 days 14hrs.
Is there any function in excel to find day time between two date and time in Excel?
I need a formula to calculate between two date and time excluding lunch time, holidays, weekend and between 09:00 and 18:00 work hours. For example, 25/07/2022 12:00 and 29/07/2022 10:00 and answer has to be 1 day, 06:00 Thanks in advance. I had a formula but it didn't work when hours bigger than 24 hours.
[ "I don't know how you got to 1 day and 6 hours, but here is a customizable way to filter your time difference calculation:\n=LET(\n start,E3,\n end,E4,\n holidays,$B$3:$B$5,\n array,SEQUENCE(INT(end)-INT(start)+1,24,INT(start),TIME(1,0,0)),\n crit_1,array>=start,\n crit_2,array<=end,\n crit_3,WEEKDAY(array,2)<6,\n crit_4,HOUR(array)>=9,\n crit_5,HOUR(array)<=18,\n crit_6,HOUR(array)<>13,\n crit_7,ISERROR(MATCH(DATE(YEAR(array),MONTH(array),DAY(array)),holidays,0)),\n result,SUM(crit_1*crit_2*crit_3*crit_4*crit_5*crit_6*crit_7),\n result\n)\n\nLimitation\nThis solution only works on an hourly level, i.e. the start and end dates and times will only be considered on a full hour basis. When providing times like 12:45 as input, the 15 minute increment won't be accounted for.\nExplanation\nThe 4th item in the LET() function SEQUENCE(INT(end)-INT(start)+1,24,INT(start),TIME(1,0,0)) creates an array that contains all hours within the start and end date of the range:\n\n(transposed for illustrative purposes)\nthen, based on that array, the different 'crit_n' statements are the individual criteria you mentioned. For example, crit_1,array>=start means that only the dates and times after the start date and time will be counted, or crit_6,HOUR(array)<>13 is the lunch break (assuming the 13th hour is lunch time), ...\nAll of the individual crit_n's are then arrays of the same size containing TRUE and FALSE elements.\nAt the end of the LET() function, by multiplying all the individual crit_n arrays, the product returns a single array that will then only contain those hours where all individual criteria statements are TRUE:\n\nSo then the SUM() function is simply returning the total number of hours that fit all criteria.\nExample\nI assumed lunch hour to be hour 13, and I assumed the 28th to be a holiday within the given range. With those assumptions and the other criteria you already specified above, I'm getting the following result:\n\nWhich looks like this when going into the formula bar:\n\n", "In cell G2, you can put the following formula:\n=LET(from,A2:A4,to,B2:B4,holidays,C2:C2,startHr,E1,endHr,E2, lunchS, E3, lunchE, E4, \n CALC, LAMBDA(date,isFrom, LET(noWkDay, NETWORKDAYS(date,date,holidays)=0,\n IF(noWkDay, 0, LET(d, INT(date), start, d + startHr, end, d + endHr,\n noOverlap, IF(isFrom, date > end, date < start), lunchDur, lunchE-lunchS,\n ls, d + lunchS, le, d + lunchE,\n isInner, IF(isFrom, date > start, date < end),\n diff, IF(isFrom, end-date-1 - IF(date < ls, lunchDur, 0), \n date-start-1 - IF(date > le, lunchDur, 0)),\n IF(noOverlap, -1, IF(isInner, diff, 0)))))),\n MAP(from,to,LAMBDA(ff,tt, LET(wkdays, NETWORKDAYS(ff,tt,holidays),\n duration, wkdays + CALC(ff, TRUE) + CALC(tt, FALSE),\n days, INT(duration), time, duration - TRUNC(duration),\n TEXT(days, \"d\") &\" days \"& TEXT(time, \"hh:mm\") &\" hrs \"\n )))\n)\n\nand here is the output:\n\nExplanation\nUsed LET function for easy reading and composition. The main idea is first to calculate the number of working days excluding holidays from column value to to column value. We use for that NETWORKDAYS function. Once we have this value for each row, we need to adjust it considering the first day and last day of the interval, in case we cannot count as a full day and instead considering hours. For inner days (not start/end of the interval) it is counted as an entire day.\nWe use MAP function to do the calculation over all values of from and to names. For each corresponding value (ff, tt) we calculate the working days (wkdays). Once we have this value, we use the user LAMBDA function CALC to adjust it. The function has a second input argument isFrom to consider both scenarios, i.e. adjustment at the beginning of the interval (isFrom = TRUE) or to the end of the interval (isFrom=FALSE). The first input argument is the given date.\nIn case the input date of CALC is a non working day, we don't need to make any adjustment. We check it with the name noWkDay. If that is not the case, then we need we need to determine if there is no overlap (noOverlap):\nIF(isFrom, date > end, date < start)\n\nwhere start, end names correspond to the same date as date, but with different hours corresponding to start Hr and end Hr (E1:E2). For example for the first row, there is no overlap, because the end date doesn't have hour information, i.e. (12:00 AM), in such case the corresponding date should not be taken into account and CALC returns -1, i.e. one day needs to be subtracted.\nIn case we have overlap, then we need to consider the case the working hours are lower than the maximum working hours (from 9:00 to 18:00). It is identified with the name isInner. If that is the case, we calculate the actual hours. We need to subtract 1 because it is going to be one less full working day and instead to consider the corresponding hours (that should be less than 9hrs, which is the maximum workday duration). The calculation is carried under the name diff:\nIF(isFrom, end-date-1 - IF(date < ls, lunchDur, 0), \n date-start-1 - IF(date > le, lunchDur, 0))\n\nIf the actual start is before the start of the lunch time (ls), then we need to subtract lunch duration (lunchDur). Similarly if the actual end is is after lunch time, we need to discount it too.\nFinally, we use CALC to calculate the interval duration:\nwkdays + CALC(ff, TRUE) + CALC(tt, FALSE)\n\nOnce we have this information, it is just to put in the specified format indicating days and hours.\nNow let's review some of the sample input data and results:\n\nThe interval starts on Monday 7/25 and ends on Friday 7/29, therefore we have 5 working days, but 7/26 is a holiday, so the maximum number of working days will be 4 days.\nFor the interval [7/25, 7/29] starts and ends on midnight (12:00 AM), therefore the last day of the interval should not be considered, so actual working days will be 3.\nInterval [7/25 10:00, 7/29 17:00]. For the start of the interval we cannot count one day, instead 8hrs and for the end of the interval, the same situation 8hrs, so instead of 4days we are goin to have 2days plus 16hrs, but we need to subtract in both cases the lunch duration (1hr) so the final result will be 2 days 14hrs.\n\n" ]
[ 0, 0 ]
[]
[]
[ "excel", "excel_2016", "excel_dates", "excel_formula" ]
stackoverflow_0074654757_excel_excel_2016_excel_dates_excel_formula.txt
Q: react-select, AsyncSelect only able to select one option even i added isMulti after that it display no options I can select first option successfuly but after that it display No option,cant add second option,i even adde isMulti,need help ` import React from "react"; import AsyncSelect from "react-select/async"; import makeAnimated from "react-select/animated"; import { options } from "../colorOptions"; import chroma from "chroma-js"; const animatedComponents = makeAnimated(); export const SelectBox = () => { const loadOptions = (searchValue, callback) => { console.log(searchValue); setTimeout(() => { const filteredOptions = options.filter((option) => option.name.toLowerCase().includes(searchValue.toLowerCase()) ); console.log(filteredOptions); callback(filteredOptions); }, 1000); }; const colorStyles = { control: (styles) => ({ ...styles, backgroundColor: "white" }), option: (styles, { data, isDesable, isFocused, isSelected }) => { return { ...styles, color: data.colorCode }; }, multiValue: (styles, { data }) => { const color = chroma(data.colorCode); return { ...styles, backgroundColor: color.alpha(0.1).css(), color: data.colorCode }; }, multiValueLabel: (styles, { data }) => ({ ...styles, color: data.colorCode }) }; return ( <AsyncSelect key={options.length} loadOptions={loadOptions} option={options} closeMenuOnSelect={false} components={animatedComponents} isMulti defaultOptions styles={colorStyles} /> ); }; ` code sandbox link :https://codesandbox.io/s/dreamy-water-j2m55v?file=/src/components/SelectBox.jsx:0-1401 code sandbox link :https://codesandbox.io/s/dreamy-water-j2m55v?file=/src/components/SelectBox.jsx:0-1401 A: my mistake i should provide my collection of option in this format export const options = [ { id: 1, value: "Red", colorCode: "#FF0000", label: "Red" }, ]; when i change to this format the code works
react-select, AsyncSelect only able to select one option even i added isMulti after that it display no options
I can select first option successfuly but after that it display No option,cant add second option,i even adde isMulti,need help ` import React from "react"; import AsyncSelect from "react-select/async"; import makeAnimated from "react-select/animated"; import { options } from "../colorOptions"; import chroma from "chroma-js"; const animatedComponents = makeAnimated(); export const SelectBox = () => { const loadOptions = (searchValue, callback) => { console.log(searchValue); setTimeout(() => { const filteredOptions = options.filter((option) => option.name.toLowerCase().includes(searchValue.toLowerCase()) ); console.log(filteredOptions); callback(filteredOptions); }, 1000); }; const colorStyles = { control: (styles) => ({ ...styles, backgroundColor: "white" }), option: (styles, { data, isDesable, isFocused, isSelected }) => { return { ...styles, color: data.colorCode }; }, multiValue: (styles, { data }) => { const color = chroma(data.colorCode); return { ...styles, backgroundColor: color.alpha(0.1).css(), color: data.colorCode }; }, multiValueLabel: (styles, { data }) => ({ ...styles, color: data.colorCode }) }; return ( <AsyncSelect key={options.length} loadOptions={loadOptions} option={options} closeMenuOnSelect={false} components={animatedComponents} isMulti defaultOptions styles={colorStyles} /> ); }; ` code sandbox link :https://codesandbox.io/s/dreamy-water-j2m55v?file=/src/components/SelectBox.jsx:0-1401 code sandbox link :https://codesandbox.io/s/dreamy-water-j2m55v?file=/src/components/SelectBox.jsx:0-1401
[ "my mistake\ni should provide my collection of option in this format\nexport const options = [ { id: 1, value: \"Red\", colorCode: \"#FF0000\", label: \"Red\" }, ];\nwhen i change to this format the code works\n" ]
[ 0 ]
[]
[]
[ "dropdown", "react_select", "react_select_search", "reactjs" ]
stackoverflow_0074654133_dropdown_react_select_react_select_search_reactjs.txt
Q: Randomized Quick sort In randomized Quicksort, should I randomize the input data first and then use the first element as the pivot, or should I not change the input data but choose a random pivot? I am a bit confused about what needs to be randomized. A: If your array is not randomly distributed already, then just select a random pivot on the array, that is what randomised quicksort is for. If your array is previously randomised, then use a normal quicksort
Randomized Quick sort
In randomized Quicksort, should I randomize the input data first and then use the first element as the pivot, or should I not change the input data but choose a random pivot? I am a bit confused about what needs to be randomized.
[ "If your array is not randomly distributed already, then just select a random pivot on the array, that is what randomised quicksort is for.\nIf your array is previously randomised, then use a normal quicksort\n" ]
[ -1 ]
[ "An easy way to do this is:\nSimply take the array input as it is. Choose a random index in the array everytime, and replace it with the last element. And then take the last element as the pivot, as you would in a normal quick sort.\nHope it helps.\n" ]
[ -1 ]
[ "algorithm", "quicksort" ]
stackoverflow_0019888587_algorithm_quicksort.txt
Q: What is happening inside of my printFun function that is causing this behaviour I am trying to figure out recursion and how it operates and I cant seem to figure out what is happening in this code. def printFun(test): if (test < 1): return else: print(test, end="a ") printFun(test-1) # statement 2 print(test, end="n ") return # Driver Code test = 3 printFun(test) This outputs 3a 2a 1a 1n 2n 3n I can make sense of the first 4 outputs. test = 3, which not less than 1, so print test(1a), then re-call the printFun function with test-1 being 2, which is not less than 1, so print test (2a), then (1a) then 0, which IS less than 1 so return. I assume this brings you back to the print(test, end='n') line? which now prints 1n. This is where I am left perplexed... what is happening beyond this??? How does it start ascending and then stop again at 3? What is the flow and logic of this? Sorry if this is a ridiculous question and I am overlooking something blatantly obvious. But I cannot wrap my mind around this... Anyone? Thanks! A: Its because the stack unwinds depth first. In pseudocode, with each indentation being a new call to the function, you get call printFun(3) print 3a call printFun(2) print 2a call printFun(1) print 1a call printFun(0) print nothing return (test still = 1 in this frame) print 1n return (test still = 2 in this frame) print 2n return (test still = 3 in this frame) print 3n return When you return from the most recently called printFun, you get back to an older set of local variables holding the older value. A: You call printFun three times and each of it prints twice, so we should have 6 prints, isn't it? Sometimes it's hard to unsolve recursion but it doesn't differ as calling another function: def foo(): print("before") other_foo() print("after") Do you agree everything that is printed by other_foo will be between "before" and "after"? It's the same case, you could write it that way: def printFun1(): print("1a") print("1n") def printFun2(): print("2a") printFun1() # it prints "1a" and "1n" between "2a" and "2n" print("2n") def printFun3(): print("3a") printFun2() print("3n") printFun3()
What is happening inside of my printFun function that is causing this behaviour
I am trying to figure out recursion and how it operates and I cant seem to figure out what is happening in this code. def printFun(test): if (test < 1): return else: print(test, end="a ") printFun(test-1) # statement 2 print(test, end="n ") return # Driver Code test = 3 printFun(test) This outputs 3a 2a 1a 1n 2n 3n I can make sense of the first 4 outputs. test = 3, which not less than 1, so print test(1a), then re-call the printFun function with test-1 being 2, which is not less than 1, so print test (2a), then (1a) then 0, which IS less than 1 so return. I assume this brings you back to the print(test, end='n') line? which now prints 1n. This is where I am left perplexed... what is happening beyond this??? How does it start ascending and then stop again at 3? What is the flow and logic of this? Sorry if this is a ridiculous question and I am overlooking something blatantly obvious. But I cannot wrap my mind around this... Anyone? Thanks!
[ "Its because the stack unwinds depth first. In pseudocode, with each indentation being a new call to the function, you get\ncall printFun(3)\n print 3a\n call printFun(2)\n print 2a\n call printFun(1)\n print 1a\n call printFun(0)\n print nothing\n return\n (test still = 1 in this frame)\n print 1n\n return\n (test still = 2 in this frame)\n print 2n\n return\n (test still = 3 in this frame)\n print 3n\n return\n\nWhen you return from the most recently called printFun, you get back to an older set of local variables holding the older value.\n", "You call printFun three times and each of it prints twice, so we should have 6 prints, isn't it?\nSometimes it's hard to unsolve recursion but it doesn't differ as calling another function:\ndef foo():\n print(\"before\")\n other_foo()\n print(\"after\")\n\nDo you agree everything that is printed by other_foo will be between \"before\" and \"after\"? It's the same case, you could write it that way:\ndef printFun1():\n print(\"1a\")\n print(\"1n\")\n\n\ndef printFun2():\n print(\"2a\")\n printFun1() # it prints \"1a\" and \"1n\" between \"2a\" and \"2n\"\n print(\"2n\")\n\n\ndef printFun3():\n print(\"3a\")\n printFun2()\n print(\"3n\")\n\nprintFun3()\n\n" ]
[ 2, 0 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0074663859_python_recursion.txt
Q: Python: cv2 can't open USB camera. "error: (-215:Assertion failed)" I'd like to use cv2 with a Desktop PC that I build myself. I've bought a USB webcamera and successufuly installed it since it works smoothly when I access it. My probem is that it seems that cv2 is not able to open my camera. This is the error I'm getting: rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) cv2.error: OpenCV(4.6.0) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor So I've tried using various index (from -1 to 5) in this line of code: cap = cv2.VideoCapture(0) But nothing changed, I've also tried to use: cd /dev ls video But this is the error I'm getting: ls: cannot access 'video': No such file or directory Is there a way to fix this problem? A: rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) Before this line of code, did you also write something like cv2.imread(...)? I experienced the error exactly the same with yours when I mistakenly put a wrong image address in the cv2.imread(), so my advice is to double check if you pass a correct image address if there is any. Best:)
Python: cv2 can't open USB camera. "error: (-215:Assertion failed)"
I'd like to use cv2 with a Desktop PC that I build myself. I've bought a USB webcamera and successufuly installed it since it works smoothly when I access it. My probem is that it seems that cv2 is not able to open my camera. This is the error I'm getting: rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) cv2.error: OpenCV(4.6.0) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor So I've tried using various index (from -1 to 5) in this line of code: cap = cv2.VideoCapture(0) But nothing changed, I've also tried to use: cd /dev ls video But this is the error I'm getting: ls: cannot access 'video': No such file or directory Is there a way to fix this problem?
[ "rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n\nBefore this line of code, did you also write something like cv2.imread(...)? I experienced the error exactly the same with yours when I mistakenly put a wrong image address in the cv2.imread(), so my advice is to double check if you pass a correct image address if there is any. Best:)\n" ]
[ 0 ]
[]
[]
[ "opencv", "python" ]
stackoverflow_0074358640_opencv_python.txt
Q: SUM(col 1 + col 2) IF col 1 contain null Input: Boxes table: +--------+----------+-------------+--------------+ | box_id | chest_id | apple_count | orange_count | +--------+----------+-------------+--------------+ | 2 | null | 6 | 15 | | 18 | 14 | 4 | 15 | | 19 | 3 | 8 | 4 | | 12 | 2 | 19 | 20 | | 20 | 6 | 12 | 9 | | 8 | 6 | 9 | 9 | | 3 | 14 | 16 | 7 | +--------+----------+-------------+--------------+ Chests table: +----------+-------------+--------------+ | chest_id | apple_count | orange_count | +----------+-------------+--------------+ | 6 | 5 | 6 | | 14 | 20 | 10 | | 2 | 8 | 8 | | 3 | 19 | 4 | | 16 | 19 | 19 | +----------+-------------+--------------+ Output: +-------------+--------------+ | apple_count | orange_count | +-------------+--------------+ | 151 | 123 | +-------------+--------------+ Explanation: box 2 has 6 apples and 15 oranges. box 18 has 4 + 20 (from the chest) = 24 apples and 15 + 10 (from the chest) = 25 oranges. box 19 has 8 + 19 (from the chest) = 27 apples and 4 + 4 (from the chest) = 8 oranges. box 12 has 19 + 8 (from the chest) = 27 apples and 20 + 8 (from the chest) = 28 oranges. box 20 has 12 + 5 (from the chest) = 17 apples and 9 + 6 (from the chest) = 15 oranges. box 8 has 9 + 5 (from the chest) = 14 apples and 9 + 6 (from the chest) = 15 oranges. box 3 has 16 + 20 (from the chest) = 36 apples and 7 + 10 (from the chest) = 17 oranges. Total number of apples = 6 + 24 + 27 + 27 + 17 + 14 + 36 = 151 Total number of oranges = 15 + 25 + 8 + 28 + 15 + 15 + 17 = 123 My answer: SELECT SUM(b.apple_count +c.apple_count,0) AS apple_count, # IFNULL SUM(b.orange_count+c.orange_count,0) AS orange_count FROM Boxes b LEFT JOIN Chests c ON b.chest_id = c.chest_id The expected answer: SELECT SUM(b.apple_count +COALESCE(c.apple_count,0)) AS apple_count, # IFNULL SUM(b.orange_count+COALESCE(c.orange_count,0)) AS orange_count FROM Boxes b LEFT JOIN Chests c ON b.chest_id = c.chest_id My question is, why do we have to use COALESCE() OR IFNULL() for this question? What is the difference between 0 and null when using SUM()? I thought SUM() is supposed to ignore null values in MySQL and add 6 to apple and 15 to orange even with the null in the chest table? A: 1 + 0 = 1 1 + null = null This is the difference.
SUM(col 1 + col 2) IF col 1 contain null
Input: Boxes table: +--------+----------+-------------+--------------+ | box_id | chest_id | apple_count | orange_count | +--------+----------+-------------+--------------+ | 2 | null | 6 | 15 | | 18 | 14 | 4 | 15 | | 19 | 3 | 8 | 4 | | 12 | 2 | 19 | 20 | | 20 | 6 | 12 | 9 | | 8 | 6 | 9 | 9 | | 3 | 14 | 16 | 7 | +--------+----------+-------------+--------------+ Chests table: +----------+-------------+--------------+ | chest_id | apple_count | orange_count | +----------+-------------+--------------+ | 6 | 5 | 6 | | 14 | 20 | 10 | | 2 | 8 | 8 | | 3 | 19 | 4 | | 16 | 19 | 19 | +----------+-------------+--------------+ Output: +-------------+--------------+ | apple_count | orange_count | +-------------+--------------+ | 151 | 123 | +-------------+--------------+ Explanation: box 2 has 6 apples and 15 oranges. box 18 has 4 + 20 (from the chest) = 24 apples and 15 + 10 (from the chest) = 25 oranges. box 19 has 8 + 19 (from the chest) = 27 apples and 4 + 4 (from the chest) = 8 oranges. box 12 has 19 + 8 (from the chest) = 27 apples and 20 + 8 (from the chest) = 28 oranges. box 20 has 12 + 5 (from the chest) = 17 apples and 9 + 6 (from the chest) = 15 oranges. box 8 has 9 + 5 (from the chest) = 14 apples and 9 + 6 (from the chest) = 15 oranges. box 3 has 16 + 20 (from the chest) = 36 apples and 7 + 10 (from the chest) = 17 oranges. Total number of apples = 6 + 24 + 27 + 27 + 17 + 14 + 36 = 151 Total number of oranges = 15 + 25 + 8 + 28 + 15 + 15 + 17 = 123 My answer: SELECT SUM(b.apple_count +c.apple_count,0) AS apple_count, # IFNULL SUM(b.orange_count+c.orange_count,0) AS orange_count FROM Boxes b LEFT JOIN Chests c ON b.chest_id = c.chest_id The expected answer: SELECT SUM(b.apple_count +COALESCE(c.apple_count,0)) AS apple_count, # IFNULL SUM(b.orange_count+COALESCE(c.orange_count,0)) AS orange_count FROM Boxes b LEFT JOIN Chests c ON b.chest_id = c.chest_id My question is, why do we have to use COALESCE() OR IFNULL() for this question? What is the difference between 0 and null when using SUM()? I thought SUM() is supposed to ignore null values in MySQL and add 6 to apple and 15 to orange even with the null in the chest table?
[ "1 + 0 = 1\n1 + null = null\nThis is the difference.\n" ]
[ 0 ]
[]
[]
[ "database", "join", "mysql", "sql", "sum" ]
stackoverflow_0074660480_database_join_mysql_sql_sum.txt
Q: How do I upgrade an existing Flutter app? I have an existing Flutter app that I built half a year ago. I checked on pubspec.lock, it has this line: sdks: dart: ">=2.10.0-110 <2.11.0" flutter: ">=1.16.0 <2.0.0" So I assume the app was built for Flutter v1.16. How do I upgrade this app to use the latest Flutter's version? Running "flutter doctor" gives me [√] Flutter (Channel stable, 1.22.3, on Microsoft Windows [Version 10.0.19041.630], locale en-US), so my SDK is already updated to the latest version. Interestingly, when I create a new app from scratch, the pubspec.lock does not have any information about the Flutter's version. The same section now contains only this: sdks: dart: ">=2.10.0-110 <2.11.0". In the future, how would I know which version was this app running? I have tried running "flutter upgrade" within my app, but that was to upgrade the SDK, not the Flutter version of the app. So how do I upgrade my app to use the latest Flutter version? Or is it always built using the latest version of the SDK? Can't I target my app to build with specific version of Flutter? A: To update the project to null safety follow these steps: Side note: change the flutter version in pubsec.yaml, make new project and copy the following line: sdk: ">=2.12.0 <3.0.0" Then follow the steps: Run flutter upgrade in the terminal to upgrade Flutter Run dart migrate to run the dart migration tool. Solve all errors which the migration tool shows. Run flutter pub outdated --mode=null-safety to print all outdated packages. Run flutter pub upgrade --null-safety to upgrade all packages automatically. Check the code for errors and solve them (Very important). Run dart migrate again and it should now be successful. Follow the link to checkout the proposed changes. Press the "Apply Migration" button. Check the code for errors again and fix them. Your project should be updated now. Referenced from this website. A: Go ro the root directory of your flutter project and run flutter upgrade. This will upgrade both your existing flutter project and flutter SDK to latest version. Run the command: flutter upgrade Additional for upgrading to latest stable version only If you want to upgrade to latest version only then please first check your current flutter channel Step 1: Check for Stable channel flutter channel You will get output like this: beta dev master * stable If output was not like this then please proceed to Step 2 or directly proceed to Step 3 Step 2: Switch to flutter stable channel flutter channel stable Now you will get output like this: beta dev master * stable Step 3: Run the below command to upgrade to latest stable version of flutter flutter upgrade A: Inside your project root, run below command flutter upgrade This command will update the Flutter SDK locally installed on your workstation, wondering how does that make sense? After you run, above command flutter upgrade the SDK is updated locally and whenever you build or run your flutter app now, it should always pick up the latest stable version (stable channel) installed locally. to check run, flutter channel you should get something like below based on what version is installed locally on your workstation. Flutter is already up to date on channel stable Flutter 2.0.3 • channel stable • https://github.com/flutter/flutter.git Framework • revision 4d7946a68d (3 days ago) • 2021-03-18 17:24:33 -0700 Engine • revision 3459eb2436 Tools • Dart 2.12.2 You can always switch to a different channel with below command, flutter channel dev flutter upgrade Answer to - the Flutter SDK locally installed on your workstation, wondering how does that make sense? Open your pubspec.yml file and see below: version: 1.0.0+1 environment: sdk: ">=2.1.0 <3.0.0" dependencies: flutter: sdk: flutter Where version: 1.0.0+1 is your flutter app version When you run command flutter run your app should pick up the environment as defined which is sdk: ">=2.1.0 <3.0.0" With all dependencies as defined under, dependencies: flutter: sdk: flutter where sdk: flutter states that the SDK should be pulled from your locally installed SDK version. Recall, how you had installed the Flutter SDK first time, on your local workstation, as below MAC example, See all SDK releases cd ~/development unzip ~/Downloads/flutter_macos_2.0.3-stable.zip later, Update your path, and run flutter doctor. OR git clone https://github.com/flutter/flutter.git -b stable later, Update your path, and run flutter doctor. Note: You may check your pubspec.lock file that may look like below, sdks: dart: ">=2.12.0-0.0 <3.0.0" flutter: ">=1.16.0" <---- Use SDK greater than this installed locally A: I will show you an easy way to migrate old code projects. My recommendation is not to work on the existing old project. Instead, create a new project where you can turn your existing project code into new clean, tidy code at a time. Now put a line of code on the existing old code project terminal as below. $ flutter create -t <project-type> <new-project-path> For example, your terminal code like, PS C:\Users\habib\VScodeProject\git_ripository\simple-weather-old> flutter create -t app C:\Users\habib\VScodeProject\git_ripository\simple-weather-new Done. After that, Your new project will no more show any system problems, like gradle problem, android manifesto problem i.e. If you want to see more about flutter migrating: [See this flutter doc] A: if you upgrade your project, but still have problem. then please check your path spellin is ok or not!? I also face this problem. after upgrading project it won't work for me. then i look to my code, there was miss path.
How do I upgrade an existing Flutter app?
I have an existing Flutter app that I built half a year ago. I checked on pubspec.lock, it has this line: sdks: dart: ">=2.10.0-110 <2.11.0" flutter: ">=1.16.0 <2.0.0" So I assume the app was built for Flutter v1.16. How do I upgrade this app to use the latest Flutter's version? Running "flutter doctor" gives me [√] Flutter (Channel stable, 1.22.3, on Microsoft Windows [Version 10.0.19041.630], locale en-US), so my SDK is already updated to the latest version. Interestingly, when I create a new app from scratch, the pubspec.lock does not have any information about the Flutter's version. The same section now contains only this: sdks: dart: ">=2.10.0-110 <2.11.0". In the future, how would I know which version was this app running? I have tried running "flutter upgrade" within my app, but that was to upgrade the SDK, not the Flutter version of the app. So how do I upgrade my app to use the latest Flutter version? Or is it always built using the latest version of the SDK? Can't I target my app to build with specific version of Flutter?
[ "To update the project to null safety follow these steps:\nSide note: change the flutter version in pubsec.yaml, make new project and copy the following line:\nsdk: \">=2.12.0 <3.0.0\"\n\nThen follow the steps:\n\nRun flutter upgrade in the terminal to upgrade Flutter\nRun dart migrate to run the dart migration tool.\nSolve all errors which the migration tool shows.\nRun flutter pub outdated --mode=null-safety to print all outdated packages.\nRun flutter pub upgrade --null-safety to upgrade all packages automatically.\nCheck the code for errors and solve them (Very important).\nRun dart migrate again and it should now be successful. Follow the link to checkout the proposed changes.\nPress the \"Apply Migration\" button.\nCheck the code for errors again and fix them.\n\nYour project should be updated now.\nReferenced from this website.\n", "Go ro the root directory of your flutter project and run flutter upgrade. This will upgrade both your existing flutter project and flutter SDK to latest version.\nRun the command:\nflutter upgrade\n\nAdditional for upgrading to latest stable version only\nIf you want to upgrade to latest version only then please first check your current flutter channel\nStep 1:\nCheck for Stable channel\nflutter channel\n\nYou will get output like this:\n beta\n dev\n master\n* stable\n\nIf output was not like this then please proceed to Step 2 or directly proceed to Step 3\nStep 2:\nSwitch to flutter stable channel\nflutter channel stable\n\nNow you will get output like this:\n beta\n dev\n master\n* stable\n\nStep 3:\nRun the below command to upgrade to latest stable version of flutter\nflutter upgrade\n\n", "Inside your project root, run below command\nflutter upgrade\n\nThis command will update the Flutter SDK locally installed on your workstation, wondering how does that make sense?\nAfter you run, above command flutter upgrade the SDK is updated locally and whenever you build or run your flutter app now, it should always pick up the latest stable version (stable channel) installed locally.\nto check run,\nflutter channel\n\nyou should get something like below based on what version is installed locally on your workstation.\nFlutter is already up to date on channel stable\nFlutter 2.0.3 • channel stable • https://github.com/flutter/flutter.git\nFramework • revision 4d7946a68d (3 days ago) • 2021-03-18 17:24:33 -0700\nEngine • revision 3459eb2436\nTools • Dart 2.12.2\n\nYou can always switch to a different channel with below command,\nflutter channel dev\nflutter upgrade\n\nAnswer to - the Flutter SDK locally installed on your workstation, wondering how does that make sense?\nOpen your pubspec.yml file and see below:\nversion: 1.0.0+1\n\nenvironment:\n sdk: \">=2.1.0 <3.0.0\"\n\ndependencies:\n flutter:\n sdk: flutter\n\n\nWhere version: 1.0.0+1 is your flutter app version\nWhen you run command flutter run your app should pick up the environment as defined which is sdk: \">=2.1.0 <3.0.0\"\nWith all dependencies as defined under,\n\ndependencies:\n flutter:\n sdk: flutter\n\nwhere sdk: flutter states that the SDK should be pulled from your locally installed SDK version.\nRecall, how you had installed the Flutter SDK first time, on your local workstation, as below MAC example, See all SDK releases\ncd ~/development\nunzip ~/Downloads/flutter_macos_2.0.3-stable.zip\n\nlater, Update your path, and run flutter doctor.\nOR\ngit clone https://github.com/flutter/flutter.git -b stable\n\nlater, Update your path, and run flutter doctor.\nNote: You may check your pubspec.lock file that may look like below,\nsdks:\n dart: \">=2.12.0-0.0 <3.0.0\"\n flutter: \">=1.16.0\" <---- Use SDK greater than this installed locally\n\n", "I will show you an easy way to migrate old code projects.\nMy recommendation is not to work on the existing old project. Instead, create a new project where you can turn your existing project code into new clean, tidy code at a time.\nNow put a line of code on the existing old code project terminal as below.\n$ flutter create -t <project-type> <new-project-path>\n\nFor example, your terminal code like,\nPS C:\\Users\\habib\\VScodeProject\\git_ripository\\simple-weather-old> flutter create -t app C:\\Users\\habib\\VScodeProject\\git_ripository\\simple-weather-new\n\nDone.\nAfter that, Your new project will no more show any system problems, like gradle problem, android manifesto problem i.e.\nIf you want to see more about flutter migrating: [See this flutter doc]\n", "if you upgrade your project, but still have problem. then please check your path spellin is ok or not!?\nI also face this problem. after upgrading project it won't work for me. then i look to my code, there was miss path.\n" ]
[ 38, 8, 3, 0, 0 ]
[]
[]
[ "flutter" ]
stackoverflow_0064797607_flutter.txt
Q: How to merge csv file with xlsx file and save it into a new combined file The files of both csv and xlsx contain same context, with same header and all. But would like to combine all under one file and then having another column to identify which is csv, which is xlsx. How do I go about doing so? extension = 'csv' all_filenames = [i for i in glob.glob('*.{}.format(extension))] combined)csv = pd.concat([pd.read_csv(f) for f in all_filenames]) combined)csv.to_csv("combined_csv.csv", index= False, encoding= 'utf-8-sig') A: To merge CSV and XLSX files and save them into a new combined file using the code you provided, you can use the pandas library in Python to read the CSV and XLSX files, concatenate them into a single DataFrame, and then write the resulting DataFrame to a new CSV file. Here is an example of how you could modify your code to do this: import glob import pandas as pd # Set the file extension extension = 'csv' # Get the list of filenames with the specified extension all_filenames = [i for i in glob.glob('*.{}'.format(extension))] # Read the CSV and XLSX files using pandas combined_csv = pd.concat([pd.read_csv(f) for f in all_filenames]) combined_xlsx = pd.read_excel('combined_xlsx.xlsx') # Concatenate the CSV and XLSX data into a single DataFrame combined = pd.concat([combined_csv, combined_xlsx]) # Write the combined DataFrame to a new CSV file combined.to_csv("combined_csv.csv", index=False, encoding='utf-8-sig') In this example, the code uses the pandas library to read the CSV and XLSX files and concatenate them into a single DataFrame. It then writes the resulting DataFrame to a new CSV file using the to_csv() method. This will create a new CSV file that contains the combined data from the original CSV and XLSX files. A: In addition to the answer by aHelpfucoder, Use the below queries just before you concatenate the combined_csv & combined_xlsx dataframes to create a new column that can tell you whether a row from a csv file or from an xlsx file. combined_csv['file_type'] = 'CSV' combined_xlsx['file_type] = 'XLSX' Next you can concatenate these dataframes, combined = pd.concat([combined_csv, combined_xlsx])
How to merge csv file with xlsx file and save it into a new combined file
The files of both csv and xlsx contain same context, with same header and all. But would like to combine all under one file and then having another column to identify which is csv, which is xlsx. How do I go about doing so? extension = 'csv' all_filenames = [i for i in glob.glob('*.{}.format(extension))] combined)csv = pd.concat([pd.read_csv(f) for f in all_filenames]) combined)csv.to_csv("combined_csv.csv", index= False, encoding= 'utf-8-sig')
[ "To merge CSV and XLSX files and save them into a new combined file using the code you provided, you can use the pandas library in Python to read the CSV and XLSX files, concatenate them into a single DataFrame, and then write the resulting DataFrame to a new CSV file. Here is an example of how you could modify your code to do this:\nimport glob\nimport pandas as pd\n\n# Set the file extension\nextension = 'csv'\n\n# Get the list of filenames with the specified extension\nall_filenames = [i for i in glob.glob('*.{}'.format(extension))]\n\n# Read the CSV and XLSX files using pandas\ncombined_csv = pd.concat([pd.read_csv(f) for f in all_filenames])\ncombined_xlsx = pd.read_excel('combined_xlsx.xlsx')\n\n# Concatenate the CSV and XLSX data into a single DataFrame\ncombined = pd.concat([combined_csv, combined_xlsx])\n\n# Write the combined DataFrame to a new CSV file\ncombined.to_csv(\"combined_csv.csv\", index=False, encoding='utf-8-sig')\n\nIn this example, the code uses the pandas library to read the CSV and XLSX files and concatenate them into a single DataFrame. It then writes the resulting DataFrame to a new CSV file using the to_csv() method. This will create a new CSV file that contains the combined data from the original CSV and XLSX files.\n", "In addition to the answer by aHelpfucoder,\nUse the below queries just before you concatenate the combined_csv & combined_xlsx dataframes to create a new column that can tell you whether a row from a csv file or from an xlsx file.\ncombined_csv['file_type'] = 'CSV'\ncombined_xlsx['file_type] = 'XLSX'\n\nNext you can concatenate these dataframes,\ncombined = pd.concat([combined_csv, combined_xlsx])\n\n" ]
[ 1, 1 ]
[]
[]
[ "csv", "python", "xlsx" ]
stackoverflow_0074663750_csv_python_xlsx.txt
Q: Go; Reference List Literal in an "if" statement So I have this pointer list of strings, and I want to check if the list is a specific list. This is my setup: someList := &[]string{"foo"} if someList == &[]string{"foo"} { fmt.Println("This works!") } Now, I would expect the outcome of this program to be > This works! but it doesn't work. Does anyone have any insight why not? A: The composite literal expressions create a unique slice values with different backing arrays. Those slice values have different addresses. The following might help explain: someList := &[]string{"foo"} anotherList := &[]string{"foo"} The following compares the addresses of the two slice values. The statement prints false because the slice values have different addresses. fmt.Println(someList == anotherList) Modify one of the slices. (*anotherList)[0] = "bar" The following statement prints [foo] [bar]. This demonstrates the slices have different backing arrays. fmt.Println(*someList, *anotherList) https://go.dev/play/p/07HHJZs00D3
Go; Reference List Literal in an "if" statement
So I have this pointer list of strings, and I want to check if the list is a specific list. This is my setup: someList := &[]string{"foo"} if someList == &[]string{"foo"} { fmt.Println("This works!") } Now, I would expect the outcome of this program to be > This works! but it doesn't work. Does anyone have any insight why not?
[ "The composite literal expressions create a unique slice values with different backing arrays. Those slice values have different addresses.\nThe following might help explain:\nsomeList := &[]string{\"foo\"}\nanotherList := &[]string{\"foo\"}\n\nThe following compares the addresses of the two slice values.\nThe statement prints false because the slice values have different addresses.\nfmt.Println(someList == anotherList) \n\nModify one of the slices.\n(*anotherList)[0] = \"bar\"\n\nThe following statement prints [foo] [bar]. This\ndemonstrates the slices have different backing arrays.\nfmt.Println(*someList, *anotherList)\n\nhttps://go.dev/play/p/07HHJZs00D3\n" ]
[ 1 ]
[]
[]
[ "go", "if_statement", "list_literal", "pointers", "reference" ]
stackoverflow_0074663872_go_if_statement_list_literal_pointers_reference.txt
Q: Creating a scipy-dev environment I am following steps in the contributor guide to create a development environment. I am up to step 2. The Python-level dependencies for building SciPy will be installed as part of the conda environment creation - see environment.yml Note that we’re installing SciPy’s build dependencies and some other software, but not (yet) SciPy itself. Also note that you’ll need to have this virtual environment active whenever you want to work with the development version of SciPy. To create the environment with all dependencies and compilers, from the root of the SciPy folder, do conda env create -f environment.yml However this gives an error that the environment file does not exist. https://github.com/scipy/scipy/blob/main/environment.yml <-- environment.yml should look like this, so I have copied and put an environment.yml file in the envs folder. I am unsure whether I should put this file in the envs folder or if I need to go to the root of the scipy version that already exist in my pkgs folder. C:\\Users\\micha\\anaconda3\\envs\>conda env create -f environment.yml EnvironmentFileNotFound: 'C:\\Users\\micha\\anaconda3\\envs\\environment.yml' file not found After inserting the environment.yml file: C:\\Users\\micha\\anaconda3\\envs\>conda env create -f environment.yml Collecting package metadata (repodata.json): done Solving environment: / I am still awaiting the reults, however not sure if I have done the correct thing with the directory. A: It doesn't matter where the environment file is, one just needs to ensure the path they provide exists. In fact, Conda can even create it from a URL: conda env create -f https://github.com/scipy/scipy/raw/main/environment.yml Note that most users find it useful to name their environments by passing an --name,-n argument (see conda env create --help). This is arbitrary, so pick something semantic/easy to remember. A: The instruction is to run that command from the root of the SciPy folder. The "SciPy folder" is what you just checked out, and the root is the top-level folder of that checkout. Doing this all from the command-line would look something like: C:\Users\User> git clone https://github.com/scipy/scipy.git [git output omitted] C:\Users\User> cd scipy C:\Users\User\scipy> conda env create -f environment.yml That root folder is also where you'll run the "dev.py" script from.
Creating a scipy-dev environment
I am following steps in the contributor guide to create a development environment. I am up to step 2. The Python-level dependencies for building SciPy will be installed as part of the conda environment creation - see environment.yml Note that we’re installing SciPy’s build dependencies and some other software, but not (yet) SciPy itself. Also note that you’ll need to have this virtual environment active whenever you want to work with the development version of SciPy. To create the environment with all dependencies and compilers, from the root of the SciPy folder, do conda env create -f environment.yml However this gives an error that the environment file does not exist. https://github.com/scipy/scipy/blob/main/environment.yml <-- environment.yml should look like this, so I have copied and put an environment.yml file in the envs folder. I am unsure whether I should put this file in the envs folder or if I need to go to the root of the scipy version that already exist in my pkgs folder. C:\\Users\\micha\\anaconda3\\envs\>conda env create -f environment.yml EnvironmentFileNotFound: 'C:\\Users\\micha\\anaconda3\\envs\\environment.yml' file not found After inserting the environment.yml file: C:\\Users\\micha\\anaconda3\\envs\>conda env create -f environment.yml Collecting package metadata (repodata.json): done Solving environment: / I am still awaiting the reults, however not sure if I have done the correct thing with the directory.
[ "It doesn't matter where the environment file is, one just needs to ensure the path they provide exists. In fact, Conda can even create it from a URL:\nconda env create -f https://github.com/scipy/scipy/raw/main/environment.yml\n\nNote that most users find it useful to name their environments by passing an --name,-n argument (see conda env create --help). This is arbitrary, so pick something semantic/easy to remember.\n", "The instruction is to run that command from the root of the SciPy folder. The \"SciPy folder\" is what you just checked out, and the root is the top-level folder of that checkout. Doing this all from the command-line would look something like:\nC:\\Users\\User> git clone https://github.com/scipy/scipy.git\n[git output omitted]\nC:\\Users\\User> cd scipy\nC:\\Users\\User\\scipy> conda env create -f environment.yml\n\nThat root folder is also where you'll run the \"dev.py\" script from.\n" ]
[ 0, 0 ]
[]
[]
[ "conda", "python", "scipy" ]
stackoverflow_0074621983_conda_python_scipy.txt
Q: Optimize bioreactor for ethanol production using gekko Continuing my efforts on optimizing the Ethanol Bioreactor, I started planning and decided on the values to use to help me maximize the ethanol concentration at the end of a batch circle. Those are: S0, which is the initial substrate concentration in the loaded bioreactor Sin, which is the substrate concentration in bioreactor feed and it may change over time Qin, which is the volumetric inflowrate and ideally I would like to be a step function, to create a feeding policy Fc, which is the coolant inlet volumetric flowrate and it may change over time to help maintain the bioreactor's temperature within limits, to avoid inhibition due to high/low working temperature. Basically it is used instead of a temperature PID controller. Of course the batch time is also very important to optimize my problem, but is already complex enough and I leave it out for the time being, giving it a fixed value (40 hours). Just in case, I was wondering if gekko can decide the simulation time. So, I used 2 key performance indicators (KPIs) in order to have an efficient operation: Bioreactor productivity, the higher, the better Substrate loss during operation, should be as close to zero as possible With all that in mind, I altered the fixed code below (many thanks to professor Hedengren) but I think that gekko is having trouble finding a solution because of the stiffness of the problem. Any suggestions on what else to try? # Optimization logic: # Goal is to maximize ethanol concentration by the end of the batch time, keeping certain KPIs within limits. # Start with loose boundaries on: Prod, Gloss, T and slowly narrow them down. # Ideal case: Prod>=4, Gloss = 0 and T = 30-32oC throughout the time horizon, for that a PID controller might later be added. # Manipulated variables to achieve goal are: Qin, Sin, S0, Fc (Vl0 and batch time might as well be added). # Qin to be a step function, Sin can change to have substrate concentration at different levels in feed, S0 is fixed (concentration of substrate in loaded BR) # and Fc should be time dependant to ensure T is within boundaries. # Constraint due to problem definition on bioreactor working volume: Vl=<0.8V from gekko import GEKKO import numpy as np import matplotlib.pyplot as plt m = GEKKO(remote=False) # Create time vector [hours] tm = np.linspace(0,40,401) # Insert smaller time steps at the beginning tm = np.insert(tm,1,[0.001,0.005,0.01,0.05]) m.time = tm nt = len(tm) # Define constants and parameters ################################# # Kinetic Parameters a1 = m.Const(value=0.05, name='a1') # Ratkowsky parameter [oC-1 h-0.5] aP = m.Const(value=4.50, name='aP') # Growth-associated parameter for EtOh production [-] AP1 = m.Const(value=6.0, name='AP1') # Activation energy parameter for EtOh production [oC] AP2 = m.Const(value=20.3, name='AP2') # Activation energy parameter for EtOh production [oC] b1 = m.Const(value=0.035, name='b1') # Parameter in the exponential expression of the maximum specific growth rate expression [oC-1] b2 = m.Const(value=0.15, name='b2') # Parameter in the exponential expression of the maximum specific growth rate expression [oC-1] b3 = m.Const(value=0.40, name='b3') # Parameter in the exponential expression of the specific death rate expression [oC-1] c1 = m.Const(value=0.38, name='c1') # Constant decoupling factor for EtOh [kgP kgX-1 h-1] c2 = m.Const(value=0.29, name='c2') # Constant decoupling factor for EtOh [kgP kgX-1 h-1] k1 = m.Const(value=3, name='k1') # Parameter in the maximum specific growth rate expression [oC] k2 = m.Const(value=55, name='k2') # Parameter in the maximum specific growth rate expression [oC] k3 = m.Const(value=60, name='k3') # Parameter in the growth-inhibitory EtOH concentration expression [oC] k4 = m.Const(value=50, name='k4') # Temperature at the inflection point of the specific death rate sigmoid curve [oC] Pmaxb = m.Const(value=90, name='Pmaxb') # Temperature-independent product inhibition constant [kg m-3] PmaxT = m.Const(value=90, name='PmaxT') # Maximum value of product inhibition constant due to temperature [kg m-3] Kdb = m.Const(value=0.025, name='Kdb') # Basal specific cellular biomass death rate [h-1] KdT = m.Const(value=30, name='KdT') # Maximum value of specific cellular biomass death rate due to temperature [h-1] KSX = m.Const(value=5, name='KSX') # Glucose saturation constant for the specific growth rate [kg m-3] KOX = m.Const(value=0.0005, name='KOX') # Oxygen saturation constant for the specific growth rate [kg m-3] qOmax = m.Const(value=0.05, name='qOmax') # Maximum specific oxygen consumption rate [h-1] # Metabolic Parameters YPS = m.Const(value=0.51, name='YPS') # Theoretical yield of EtOH on glucose [kgP kgS-1] YXO = m.Const(value=0.97, name='YXO') # Theoretical yield of biomass on oxygen [kgX kgO-1] YXS = m.Const(value=0.53, name='YXS') # Theoretical yield of biomass on glucose [kgX kgS-1] # Physicochemical and thermodynamic parameters Chbr = m.Const(value=4.18, name='Chbr') # Heat capacity of the mass of reaction [kJ kg-1 oC-1] Chc = m.Const(value=4.18, name='Chc') # Heat capacity of cooling agent [kJ kg-1 oC-1] deltaH = m.Const(value=518.e3, name='deltaH') # Heat of reaction of fermentation [kJ kmol-1 O2] Tref = m.Const(value=25, name='Tref') # Reference temperature [oC] KH = m.Const(value=200, name='KH') # Henry's constant for oxygen in the fermentation broth [atm m3 kmol-1] z = m.Const(value=0.792, name='z') # Oxygen compressibility factor [-] R = m.Const(value=0.082, name='R') # Ideal gas constant [m3 atm kmol-1 oC-1] kla0 = m.Const(value=100, name='kla0') # Temperature-independent volumetric oxygen transfer coefficient [-h] KT = m.Const(value=360, name='KT') # Heat transfer coefficient [kJ h-1 m-2 oC-1] rho = m.Const(value=1080, name='rho') # Density of the fermentation broth [kg m-3] rhoc = m.Const(value=1000, name='rhoc') # Density of the cooling agent [kg m-3] MO = m.Const(value=31.998, name='MO') # Molecular weight of oxygen [kg kmol-1] # Bioreactor design data AT = m.Const(value=100, name='AT') # Bioreactor heat transfer area [m2] V = m.Const(value=2900, name='V') # Bioreactor working volume [m3] Vcj = m.Const(value=250, name='Vcj') # Cooling jacket volume [m3] Ogasin = m.Const(value=0.305, name='Ogasin') # Oxygen concentration in airflow inlet [kg m-3] # Define variables ################## # Manipulated Variables S0 = m.FV(value=50, lb=+0.0, ub=10000, name='S0') # Initial substrate concentration in loaded bioreactor [kg m-3] S0.STATUS = 1 Sin = m.MV(value=400, lb=0, ub=1500) # Substrate/Glucose concentration in bioreactor feed [kg m-3] Sin.STATUS = 1 Sin.DCOST = 0.0 Qin = m.MV(value=0, name='Qin') # Ideally Qin to be a step function Qin.STATUS = 1 Qin.DCOST = 0.0 Fc = m.FV(value=40, name='Fc') # Coolant inlet volumetric flow rate [m3 h-1] Fc.STATUS = 1 # Variables mi = m.Var(name='mi', lb=0) # Specific growth rate [kgP kgX-1 h-1] bP = m.Var(name='bP', lb=0) # Non-growth associated term [kgP kgX-1 h-1] # KPIs variables XXt = m.Var(name='XXt') # Biomass yield of glucose fermentation XP = m.Var(name='XP') # Ethanol yield of glucose fermentation Prod = m.Var(name='Prod', lb=1) # Bioreactor productivity in ethanol Gloss = m.Var(name='Gloss', ub=10000) # Substrate loss during fed-batch operation # Fixed variables, they are constant throughout the time horizon Xtin = m.FV(value=0, name='Xtin') # Total cellular biomass concentration in the bioreactor feed [kg/m3] Xvin = m.FV(value=0, name='Xvin') # Viable cellular biomass concentration in the bioreactor feed [kg/m3] Qe = m.FV(value=0, name='Qe') # Output flow rate [m3/h] Pin = m.FV(value=0, name='Pin') # Ethanol concentration in the bioreactor feed [kg/m3] Fair = m.FV(value=60000, name='Fair') # Air flow volumetric rate [m3/h] Tin = m.FV(value=30, name='Tin') # Temperature of bioreactor feed [oC] Tcin = m.FV(value=15, name='Tcin') # Temperature of coolant inlet [oC] # Differential equations variables Vl = m.Var(value=1000, ub=0.8*V, name='Vl') # [m3] Xt = m.Var(value=0.1, name='Xt') # [kg m-3] Xv = m.Var(value=0.1, name='Xv') # [kg m-3] S = m.Var(value=S0, name='S') # [kg m-3] P = m.Var(value=0, name='P') # [kg m-3] Ol = m.Var(value=0.0065, name= 'Ol') # [kg m-3] Og = m.Var(value=0.305, name='Og') # [kg m-3] T = m.Var(value=30, lb=20, ub=40, name='T') # [oC] Tc = m.Var(value=20, name='Tc') # [oC] Sf_cum = m.Var(value=0, name='Sf_cum') # [kg] t = m.Var(value=0, name='Time') # [h] # Define algebraic equations ############################ # Specific growth rate of cell mass mimax = m.Intermediate(((a1*(T-k1))*(1-m.exp(b1*(T-k2)))) ** 2) Pmax = m.Intermediate(Pmaxb + PmaxT/(1-m.exp(-b2*(T-k3)))) m.Equation(mi == mimax * S/(KSX+S) * Ol/(KOX + Ol) * (1 - P/Pmax) * 1 / (1+m.exp(-(100-S)/1))) # Specific production rate of EtOH m.Equation(bP == c1*m.exp(-AP1/T) - c2*m.exp(-AP2/T)) qP = m.Intermediate(aP*mi + bP) # Specific consumption rate of glucose qS = m.Intermediate(mi/YXS + qP/YPS) # Specific consumption rate of oxygen qO = m.Intermediate(qOmax*Ol/YXO/(KOX+Ol)) # Specific biological deactivation rate of cell mass Kd = m.Intermediate(Kdb + KdT/(1+m.exp(-b3*(T-k4)))) # Saturation concentration of oxygen in culture media Ostar = m.Intermediate(z*Og*R*T/KH) # Oxygen mass transfer coefficient kla = m.Intermediate(kla0*1.2**(T-20)) # Bioreactor phases equation Vg = m.Intermediate(V - Vl) # Define differential equations ############################### m.Equation(Vl.dt() == Qin - Qe) m.Equation(Vl*Xt.dt() == Qin*(Xtin-Xt) + mi*Vl*Xv) m.Equation(Vl*Xv.dt() == Qin*(Xvin-Xv) + Xv*Vl*(mi-Kd)) m.Equation(Vl*S.dt() == Qin*(Sin-S) - qS*Vl*Xv) m.Equation(Vl*P.dt() == Qin*(Pin-P) + qP*Vl*Xv) m.Equation(Vl*Ol.dt() == Qin*(Ostar-Ol) + Vl*kla*(Ostar-Ol) - qO*Vl*Xv) m.Equation(Vg*Og.dt() == Fair*(Ogasin-Og) - Vl*kla*(Ostar-Ol) + Og*(Qin-Qe)) m.Equation(Vl*T.dt() == Qin*(Tin-T) - Tref*(Qin-Qe) + Vl*qO*Xv*deltaH/MO/rho/Chbr - KT*AT*(T-Tc)/rho/Chbr) m.Equation(Vcj*Tc.dt() == Fc*(Tcin - Tc) + KT*AT*(T-Tc)/rhoc/Chc) m.Equation(Sf_cum.dt() == Qin*Sin) m.Equation(t.dt() == 1) # Yields and Productivity ######################### m.Equation(XXt == (Xt*Vl - Xt.value*Vl.value)/(S.value*Vl.value + Sf_cum)) m.Equation(XP == (P*Vl - P.value*Vl.value)/(S.value*Vl.value + Sf_cum)) m.Equation(Prod == (P-P.value)/t) m.Equation(Gloss == Vl*S) # solve DAE m.options.SOLVER= 1 m.options.IMODE = 7 m.options.NODES = 3 m.options.MAX_ITER = 3000 # m.open_folder() m.solve() # Objective function f = np.zeros(nt) f[-1] = 1.0 final = m.Param(value=f) m.Obj(-final*P) # Solve optimization problem m.options.IMODE=6 m.solve() print('Total loss of substrate: G=' + str(Gloss.value[-1]) + '[kg]') print('Biomass: Xt=' + str(Xt.value[-1]) + '[kg/m3]') print('Ethanol: P=' + str(P.value[-1]) + '[kg/m3]') print('Bioreactor productivity: Prod=' + str(Prod.value[-1]) + '[kg/m3/h]') print('Bioreactor operating volume: Vl='+ str(Vl.value[-1]) + '[m3]') # Plot results plt.figure(0) plt.title('Feeding Policy') plt.plot(m.time, Qin.value, label='Qin') plt.ylabel('Qin [m3/h]') plt.xlabel('Time [h]') plt.legend(); plt.grid(); plt.minorticks_on() plt.ylim(0); plt.xlim(m.time[0],m.time[-1]) plt.tight_layout() plt.figure(1) plt.title('Total & Viable Cellular Biomass') plt.plot(m.time, Xv.value, label='Xv') plt.plot(m.time, Xt.value, label='Xt') plt.ylabel('Biomass concentration [kg/m3]') plt.xlabel('Time [h]') plt.legend(); plt.grid(); plt.minorticks_on() plt.ylim(0); plt.xlim(m.time[0],m.time[-1]) plt.tight_layout() plt.figure(2) plt.title('Substrate (S) & Product (P) concentration') plt.plot(m.time, S.value, label='S') plt.plot(m.time, P.value, label='P') plt.ylabel('Concentration [kg/m3]') plt.xlabel('Time [h]') plt.legend(); plt.grid(); plt.minorticks_on() plt.ylim(0); plt.xlim(m.time[0],m.time[-1]) plt.tight_layout() fig3, ax = plt.subplots() ax.title.set_text('Dissolved & Gaseous Oxygen concentration') lns1 = ax.plot(m.time, Ol.value, label='[Oliq]', color='c') ax.set_xlabel('Time [h]') ax.set_ylabel('Oliq [kg/m3]', color='c') ax.minorticks_on() ax2 = ax.twinx() lns2 = ax2.plot(m.time, Og.value, label='[Ogas]', color='y') ax2.set_ylabel('Ogas [kg/m3]', color='y') ax2.minorticks_on() lns = lns1 + lns2 labs = [l.get_label() for l in lns] ax.legend(lns, labs, loc='best') ax.grid() ax.set_xlim(m.time[0],m.time[-1]) fig3.tight_layout() plt.figure(3) plt.figure(4) plt.title('Bioreactor & Cooling jacket temperature') plt.plot(m.time, T.value, label='T') plt.plot(m.time, Tc.value, label='Tc') plt.ylabel('Temperature [oC]') plt.xlabel('Time [h]') plt.legend(); plt.grid(); plt.minorticks_on() plt.ylim(0); plt.xlim(m.time[0],m.time[-1]) plt.tight_layout() fig5, ax = plt.subplots() ax.title.set_text('Specific rates & bP') lns1 = ax.plot(tm,Kd.value,label='Kd') lns2 = ax.plot(tm,mimax.value,label='mimax') lns3 = ax.plot(tm,mi.value,label='mi') ax.set_xlabel('Time [h]') ax.set_ylabel('Specific growth and death rate') ax.minorticks_on() ax2 = ax.twinx() lns4 = ax.plot(tm,bP.value,label='bP', color='magenta') ax2.set_ylabel('bP [1/h]', color='magenta') ax2.minorticks_on() lns = lns1 + lns2 + lns3 + lns4 labs = [l.get_label() for l in lns] ax.legend(lns, labs, loc='best'); ax.grid() ax.set_ylim(0); ax.set_xlim(m.time[0],m.time[-1]) fig5.tight_layout() plt.figure(5) fig6, ax = plt.subplots() ax.title.set_text('Ethanol yield & Productivity') lns1 = ax.plot(m.time, XP.value, label='xP', color='c') ax.set_xlabel('Time [h]') ax.set_ylabel('Ethanol yield on glucose', color='c') ax.minorticks_on() ax2 = ax.twinx() lns2 = ax2.plot(m.time, Prod.value, label='Prod', color='y') ax2.set_ylabel('Prod [kg/m3/h]', color='y') ax2.minorticks_on() lns = lns1 + lns2 labs = [l.get_label() for l in lns] ax.legend(lns, labs, loc='best') ax.grid() ax.set_ylim(0); ax.set_xlim(m.time[0],m.time[-1]) fig6.tight_layout() plt.figure(6) fig7, ax = plt.subplots() ax.title.set_text('Culture Volume & Total Substrate fed to the Bioreactor') lns1 = ax.plot(m.time, Vl.value, label='Vl', color='r') ax.set_xlabel('Time [h]') ax.set_ylabel('Vl [m3]', color='r') ax.minorticks_on() ax2 = ax.twinx() lns2 = ax2.plot(m.time, Sf_cum.value, label='Sf_cum', color='g') ax2.set_ylabel('Sf_cum [kg]', color='g') ax2.minorticks_on() lns = lns1 + lns2 labs = [l.get_label() for l in lns] ax.legend(lns, labs, loc='best') ax.grid() ax.set_ylim(900); ax2.set_ylim(0); ax.set_xlim(m.time[0],m.time[-1]) fig7.tight_layout() plt.figure(7) plt.show() A: Here are a few suggestions: Rearrange equations to avoid divide-by-zero KPI equations do not influence other variables and can be converted to Intermediates or calculated after the solve Use COLDSTART with 2..1..0 to initialize the model with separate solves Add constraints after the simulation initialization (COLDSTART=2,1). The constraints make the simulation infeasible. Add upper and lower bounds to the decision variables such as Qin. Use m.free_initial(S) to calculate the initial condition S0. I left this out for now, but you could add it back. Use MV_STEP_HOR=100 to reduce the number of changes for Qin or Sin to 4 times per batch to reduce operator actions. (Optional) Consider fixing the temperature to just optimize yield and assume that there is excellent temperature control from a lower level controller. This would remove the energy balance equations that could be added later. It would also help with the solution speed and remove some of the rate equation exponential terms in the model that are challenging to solve. (Optional) Switch to the public server (remote=True) to see the iteration summary and monitor the progress of the solver. The local mode doesn't have that capability currently. Below is code that almost solves successfully after 30 iterations. It may need some additional adjustments such as constraints with COLDSTART=0 to get a solution and the results that you expect. # Optimization logic: # Goal is to maximize ethanol concentration by the end of the batch time, keeping certain KPIs within limits. # Start with loose boundaries on: Prod, Gloss, T and slowly narrow them down. # Ideal case: Prod>=4, Gloss = 0 and T = 30-32oC throughout the time horizon, for that a PID controller might later be added. # Manipulated variables to achieve goal are: Qin, Sin, S0, Fc (Vl0 and batch time might as well be added). # Qin to be a step function, Sin can change to have substrate concentration at different levels in feed, S0 is fixed (concentration of substrate in loaded BR) # and Fc should be time dependant to ensure T is within boundaries. # Constraint due to problem definition on bioreactor working volume: Vl=<0.8V from gekko import GEKKO import numpy as np import matplotlib.pyplot as plt m = GEKKO(remote=True) # Create time vector [hours] tm = np.linspace(0,40,401) # Insert smaller time steps at the beginning tm = np.insert(tm,1,[0.001,0.005,0.01,0.05]) m.time = tm nt = len(tm) # Define constants and parameters ################################# # Kinetic Parameters a1 = m.Const(value=0.05, name='a1') # Ratkowsky parameter [oC-1 h-0.5] aP = m.Const(value=4.50, name='aP') # Growth-associated parameter for EtOh production [-] AP1 = m.Const(value=6.0, name='AP1') # Activation energy parameter for EtOh production [oC] AP2 = m.Const(value=20.3, name='AP2') # Activation energy parameter for EtOh production [oC] b1 = m.Const(value=0.035, name='b1') # Parameter in the exponential expression of the maximum specific growth rate expression [oC-1] b2 = m.Const(value=0.15, name='b2') # Parameter in the exponential expression of the maximum specific growth rate expression [oC-1] b3 = m.Const(value=0.40, name='b3') # Parameter in the exponential expression of the specific death rate expression [oC-1] c1 = m.Const(value=0.38, name='c1') # Constant decoupling factor for EtOh [kgP kgX-1 h-1] c2 = m.Const(value=0.29, name='c2') # Constant decoupling factor for EtOh [kgP kgX-1 h-1] k1 = m.Const(value=3, name='k1') # Parameter in the maximum specific growth rate expression [oC] k2 = m.Const(value=55, name='k2') # Parameter in the maximum specific growth rate expression [oC] k3 = m.Const(value=60, name='k3') # Parameter in the growth-inhibitory EtOH concentration expression [oC] k4 = m.Const(value=50, name='k4') # Temperature at the inflection point of the specific death rate sigmoid curve [oC] Pmaxb = m.Const(value=90, name='Pmaxb') # Temperature-independent product inhibition constant [kg m-3] PmaxT = m.Const(value=90, name='PmaxT') # Maximum value of product inhibition constant due to temperature [kg m-3] Kdb = m.Const(value=0.025, name='Kdb') # Basal specific cellular biomass death rate [h-1] KdT = m.Const(value=30, name='KdT') # Maximum value of specific cellular biomass death rate due to temperature [h-1] KSX = m.Const(value=5, name='KSX') # Glucose saturation constant for the specific growth rate [kg m-3] KOX = m.Const(value=0.0005, name='KOX') # Oxygen saturation constant for the specific growth rate [kg m-3] qOmax = m.Const(value=0.05, name='qOmax') # Maximum specific oxygen consumption rate [h-1] # Metabolic Parameters YPS = m.Const(value=0.51, name='YPS') # Theoretical yield of EtOH on glucose [kgP kgS-1] YXO = m.Const(value=0.97, name='YXO') # Theoretical yield of biomass on oxygen [kgX kgO-1] YXS = m.Const(value=0.53, name='YXS') # Theoretical yield of biomass on glucose [kgX kgS-1] # Physicochemical and thermodynamic parameters Chbr = m.Const(value=4.18, name='Chbr') # Heat capacity of the mass of reaction [kJ kg-1 oC-1] Chc = m.Const(value=4.18, name='Chc') # Heat capacity of cooling agent [kJ kg-1 oC-1] deltaH = m.Const(value=518.e3, name='deltaH') # Heat of reaction of fermentation [kJ kmol-1 O2] Tref = m.Const(value=25, name='Tref') # Reference temperature [oC] KH = m.Const(value=200, name='KH') # Henry's constant for oxygen in the fermentation broth [atm m3 kmol-1] z = m.Const(value=0.792, name='z') # Oxygen compressibility factor [-] R = m.Const(value=0.082, name='R') # Ideal gas constant [m3 atm kmol-1 oC-1] kla0 = m.Const(value=100, name='kla0') # Temperature-independent volumetric oxygen transfer coefficient [-h] KT = m.Const(value=360, name='KT') # Heat transfer coefficient [kJ h-1 m-2 oC-1] rho = m.Const(value=1080, name='rho') # Density of the fermentation broth [kg m-3] rhoc = m.Const(value=1000, name='rhoc') # Density of the cooling agent [kg m-3] MO = m.Const(value=31.998, name='MO') # Molecular weight of oxygen [kg kmol-1] # Bioreactor design data AT = m.Const(value=100, name='AT') # Bioreactor heat transfer area [m2] V = m.Const(value=2900, name='V') # Bioreactor working volume [m3] Vcj = m.Const(value=250, name='Vcj') # Cooling jacket volume [m3] Ogasin = m.Const(value=0.305, name='Ogasin') # Oxygen concentration in airflow inlet [kg m-3] # Define variables ################## # Manipulated Variables #S0 = m.FV(value=50, lb=+0.0, ub=10000, name='S0') # Initial substrate concentration in loaded bioreactor [kg m-3] #S0.STATUS = 1 # use m.free_initial(S) after initialization Sin = m.MV(value=400, lb=0, ub=1500) # Substrate/Glucose concentration in bioreactor feed [kg m-3] Sin.STATUS = 1 Sin.DCOST = 0.0 Sin.MV_STEP_HOR = 100 Qin = m.MV(value=0.1, lb=0.1, ub=100, name='Qin') # Ideally Qin to be a step function Qin.STATUS = 1 Qin.DCOST = 0.0 Qin.MV_STEP_HOR = 100 Fc = m.FV(value=40, lb=0, ub=1e4, name='Fc') # Coolant inlet volumetric flow rate [m3 h-1] Fc.STATUS = 1 # Variables mi = m.Var(name='mi') # Specific growth rate [kgP kgX-1 h-1] bP = m.Var(name='bP') # Non-growth associated term [kgP kgX-1 h-1] # Fixed variables, they are constant throughout the time horizon Xtin = m.FV(value=0, name='Xtin') # Total cellular biomass concentration in the bioreactor feed [kg/m3] Xvin = m.FV(value=0, name='Xvin') # Viable cellular biomass concentration in the bioreactor feed [kg/m3] Qe = m.FV(value=0, name='Qe') # Output flow rate [m3/h] Pin = m.FV(value=0, name='Pin') # Ethanol concentration in the bioreactor feed [kg/m3] Fair = m.FV(value=60000, name='Fair') # Air flow volumetric rate [m3/h] Tin = m.FV(value=30, name='Tin') # Temperature of bioreactor feed [oC] Tcin = m.FV(value=15, name='Tcin') # Temperature of coolant inlet [oC] # Differential equations variables Vl0 = 1000; Xt0 = 0.1; P0 = 0; S0 = 50 Vl = m.Var(value=Vl0, name='Vl') # [m3] Xt = m.Var(value=Xt0, name='Xt') # [kg m-3] Xv = m.Var(value=0.1, name='Xv') # [kg m-3] S = m.Var(value=S0, name='S') # [kg m-3] P = m.Var(value=P0, name='P') # [kg m-3] Ol = m.Var(value=0.0065, name= 'Ol') # [kg m-3] Og = m.Var(value=0.305, name='Og') # [kg m-3] T = m.Var(value=30,name='T') # [oC] Tc = m.Var(value=20, name='Tc') # [oC] Sf_cum = m.Var(value=0, name='Sf_cum') # [kg] # Define algebraic equations ############################ # Specific growth rate of cell mass mimax = m.Intermediate(((a1*(T-k1))*(1-m.exp(b1*(T-k2)))) ** 2) Pmax = m.Intermediate(Pmaxb + PmaxT/(1-m.exp(-b2*(T-k3)))) m.Equation(mi == mimax * S/(KSX+S) * Ol/(KOX + Ol) * (1 - P/Pmax) * 1 / (1+m.exp(-(100-S)/1))) # Specific production rate of EtOH bPe = m.Intermediate(c1*m.exp(-AP1/T) - c2*m.exp(-AP2/T)) m.Equation(bP == bPe) qP = m.Intermediate(aP*mi + bP) # Specific consumption rate of glucose qS = m.Intermediate(mi/YXS + qP/YPS) # Specific consumption rate of oxygen qO = m.Intermediate(qOmax*Ol/YXO/(KOX+Ol)) # Specific biological deactivation rate of cell mass Kd = m.Intermediate(Kdb + KdT/(1+m.exp(-b3*(T-k4)))) # Saturation concentration of oxygen in culture media Ostar = m.Intermediate(z*Og*R*T/KH) # Oxygen mass transfer coefficient kla = m.Intermediate(kla0*1.2**(T-20)) # Bioreactor phases equation Vg = m.Intermediate(V - Vl) # Define differential equations ############################### m.Equation(Vl.dt() == Qin - Qe) m.Equation(Vl*Xt.dt() == Qin*(Xtin-Xt) + mi*Vl*Xv) m.Equation(Vl*Xv.dt() == Qin*(Xvin-Xv) + Xv*Vl*(mi-Kd)) m.Equation(Vl*S.dt() == Qin*(Sin-S) - qS*Vl*Xv) m.Equation(Vl*P.dt() == Qin*(Pin-P) + qP*Vl*Xv) m.Equation(Vl*Ol.dt() == Qin*(Ostar-Ol) + Vl*kla*(Ostar-Ol) - qO*Vl*Xv) m.Equation(Vg*Og.dt() == Fair*(Ogasin-Og) - Vl*kla*(Ostar-Ol) + Og*(Qin-Qe)) m.Equation(Vl*T.dt() == Qin*(Tin-T) - Tref*(Qin-Qe) + Vl*qO*Xv*deltaH/MO/rho/Chbr - KT*AT*(T-Tc)/rho/Chbr) m.Equation(Vcj*Tc.dt() == Fc*(Tcin - Tc) + KT*AT*(T-Tc)/rhoc/Chc) m.Equation(Sf_cum.dt() == Qin*Sin) # KPIs as Intermediates or Var/Equations kpi_interm = True if kpi_interm: t = m.Param(m.time) XXt = m.Intermediate((Xt*Vl - Xt0*Vl0)/(S0*Vl0 + Sf_cum)) XP = m.Intermediate((P*Vl - P0*Vl0)/(S0*Vl0 + Sf_cum)) Prod = m.Intermediate((P-P0)/t) Gloss = m.Intermediate(Vl*S) else: # include KPIs as equations # KPIs variables t = m.Var(value=0, name='Time') # [h] XXt = m.Var(name='XXt') # Biomass yield of glucose fermentation XP = m.Var(name='XP') # Ethanol yield of glucose fermentation Prod = m.Var(name='Prod') #, lb=1) # Bioreactor productivity in ethanol Gloss = m.Var(name='Gloss') # Substrate loss during fed-batch operation # Yields and Productivity ######################### m.Equation(t.dt() == 1) m.Equation(XXt*(S0*Vl0 + Sf_cum) == (Xt*Vl - Xt0*Vl0)) m.Equation(XP *(S0*Vl0 + Sf_cum) == (P*Vl - P0*Vl0)) m.Equation(Prod * t == (P-P0)) m.Equation(Gloss == Vl*S) mi.LOWER = 0 bP.LOWER = 0 T.LOWER=0 # solve DAE m.options.SOLVER= 1 m.options.REDUCE = 3 m.options.NODES = 2 m.options.IMODE = 6 m.options.COLDSTART = 2 m.options.MAX_ITER = 3000 # m.open_folder() print('Start Coldstart Simulation') m.solve() print('End Coldstart Simulation') # Objective function f = np.zeros(nt) f[-1] = 1.0 final = m.Param(value=f) m.Maximize(final*P) # Solve optimization problem #m.options.SOLVER = 3 m.options.TIME_SHIFT = 0 m.options.COLDSTART=1 m.options.NODES=3 m.options.IMODE=6 print('Start Optimization Coldstart') m.solve(disp=True) print('End Optimization Coldstart') # Add some variable bounds back after simulation T.UPPER=40 P.LOWER = 0 Gloss.UPPER=10000 Vl.UPPER=0.8*V # Calculate S0 m.free_initial(S) m.options.TIME_SHIFT=0 m.options.COLDSTART=0 m.options.NODES=3 m.options.IMODE=6 m.options.SOLVER= 1 print('Start Optimization') m.solve(disp=True) print('End Optimization') print('Total loss of substrate: G=' + str(Gloss.value[-1]) + '[kg]') print('Biomass: Xt=' + str(Xt.value[-1]) + '[kg/m3]') print('Ethanol: P=' + str(P.value[-1]) + '[kg/m3]') print('Bioreactor productivity: Prod=' + str(Prod.value[-1]) + '[kg/m3/h]') print('Bioreactor operating volume: Vl='+ str(Vl.value[-1]) + '[m3]') # Plot results plt.figure(0) plt.title('Feeding Policy') plt.plot(m.time, Qin.value, label='Qin') plt.ylabel('Qin [m3/h]') plt.xlabel('Time [h]') plt.legend(); plt.grid(); plt.minorticks_on() plt.ylim(0); plt.xlim(m.time[0],m.time[-1]) plt.tight_layout() plt.figure(1) plt.title('Total & Viable Cellular Biomass') plt.plot(m.time, Xv.value, label='Xv') plt.plot(m.time, Xt.value, label='Xt') plt.ylabel('Biomass concentration [kg/m3]') plt.xlabel('Time [h]') plt.legend(); plt.grid(); plt.minorticks_on() plt.ylim(0); plt.xlim(m.time[0],m.time[-1]) plt.tight_layout() plt.figure(2) plt.title('Substrate (S) & Product (P) concentration') plt.plot(m.time, S.value, label='S') plt.plot(m.time, P.value, label='P') plt.ylabel('Concentration [kg/m3]') plt.xlabel('Time [h]') plt.legend(); plt.grid(); plt.minorticks_on() plt.ylim(0); plt.xlim(m.time[0],m.time[-1]) plt.tight_layout() fig3, ax = plt.subplots() ax.title.set_text('Dissolved & Gaseous Oxygen concentration') lns1 = ax.plot(m.time, Ol.value, label='[Oliq]', color='c') ax.set_xlabel('Time [h]') ax.set_ylabel('Oliq [kg/m3]', color='c') ax.minorticks_on() ax2 = ax.twinx() lns2 = ax2.plot(m.time, Og.value, label='[Ogas]', color='y') ax2.set_ylabel('Ogas [kg/m3]', color='y') ax2.minorticks_on() lns = lns1 + lns2 labs = [l.get_label() for l in lns] ax.legend(lns, labs, loc='best') ax.grid() ax.set_xlim(m.time[0],m.time[-1]) fig3.tight_layout() plt.figure(3) plt.figure(4) plt.title('Bioreactor & Cooling jacket temperature') plt.plot(m.time, T.value, label='T') plt.plot(m.time, Tc.value, label='Tc') plt.ylabel('Temperature [oC]') plt.xlabel('Time [h]') plt.legend(); plt.grid(); plt.minorticks_on() plt.ylim(0); plt.xlim(m.time[0],m.time[-1]) plt.tight_layout() fig5, ax = plt.subplots() ax.title.set_text('Specific rates & bP') lns1 = ax.plot(tm,Kd.value,label='Kd') lns2 = ax.plot(tm,mimax.value,label='mimax') lns3 = ax.plot(tm,mi.value,label='mi') ax.set_xlabel('Time [h]') ax.set_ylabel('Specific growth and death rate') ax.minorticks_on() ax2 = ax.twinx() lns4 = ax.plot(tm,bP.value,label='bP', color='magenta') ax2.set_ylabel('bP [1/h]', color='magenta') ax2.minorticks_on() lns = lns1 + lns2 + lns3 + lns4 labs = [l.get_label() for l in lns] ax.legend(lns, labs, loc='best'); ax.grid() ax.set_ylim(0); ax.set_xlim(m.time[0],m.time[-1]) fig5.tight_layout() plt.figure(5) fig6, ax = plt.subplots() ax.title.set_text('Ethanol yield & Productivity') lns1 = ax.plot(m.time, XP.value, label='xP', color='c') ax.set_xlabel('Time [h]') ax.set_ylabel('Ethanol yield on glucose', color='c') ax.minorticks_on() ax2 = ax.twinx() lns2 = ax2.plot(m.time, Prod.value, label='Prod', color='y') ax2.set_ylabel('Prod [kg/m3/h]', color='y') ax2.minorticks_on() lns = lns1 + lns2 labs = [l.get_label() for l in lns] ax.legend(lns, labs, loc='best') ax.grid() ax.set_ylim(0); ax.set_xlim(m.time[0],m.time[-1]) fig6.tight_layout() plt.figure(6) fig7, ax = plt.subplots() ax.title.set_text('Culture Volume & Total Substrate fed to the Bioreactor') lns1 = ax.plot(m.time, Vl.value, label='Vl', color='r') ax.set_xlabel('Time [h]') ax.set_ylabel('Vl [m3]', color='r') ax.minorticks_on() ax2 = ax.twinx() lns2 = ax2.plot(m.time, Sf_cum.value, label='Sf_cum', color='g') ax2.set_ylabel('Sf_cum [kg]', color='g') ax2.minorticks_on() lns = lns1 + lns2 labs = [l.get_label() for l in lns] ax.legend(lns, labs, loc='best') ax.grid() ax.set_ylim(900); ax2.set_ylim(0); ax.set_xlim(m.time[0],m.time[-1]) fig7.tight_layout() plt.figure(7) plt.show() It is also possible to optimize the total batch time. See the Jennings problem for an example.
Optimize bioreactor for ethanol production using gekko
Continuing my efforts on optimizing the Ethanol Bioreactor, I started planning and decided on the values to use to help me maximize the ethanol concentration at the end of a batch circle. Those are: S0, which is the initial substrate concentration in the loaded bioreactor Sin, which is the substrate concentration in bioreactor feed and it may change over time Qin, which is the volumetric inflowrate and ideally I would like to be a step function, to create a feeding policy Fc, which is the coolant inlet volumetric flowrate and it may change over time to help maintain the bioreactor's temperature within limits, to avoid inhibition due to high/low working temperature. Basically it is used instead of a temperature PID controller. Of course the batch time is also very important to optimize my problem, but is already complex enough and I leave it out for the time being, giving it a fixed value (40 hours). Just in case, I was wondering if gekko can decide the simulation time. So, I used 2 key performance indicators (KPIs) in order to have an efficient operation: Bioreactor productivity, the higher, the better Substrate loss during operation, should be as close to zero as possible With all that in mind, I altered the fixed code below (many thanks to professor Hedengren) but I think that gekko is having trouble finding a solution because of the stiffness of the problem. Any suggestions on what else to try? # Optimization logic: # Goal is to maximize ethanol concentration by the end of the batch time, keeping certain KPIs within limits. # Start with loose boundaries on: Prod, Gloss, T and slowly narrow them down. # Ideal case: Prod>=4, Gloss = 0 and T = 30-32oC throughout the time horizon, for that a PID controller might later be added. # Manipulated variables to achieve goal are: Qin, Sin, S0, Fc (Vl0 and batch time might as well be added). # Qin to be a step function, Sin can change to have substrate concentration at different levels in feed, S0 is fixed (concentration of substrate in loaded BR) # and Fc should be time dependant to ensure T is within boundaries. # Constraint due to problem definition on bioreactor working volume: Vl=<0.8V from gekko import GEKKO import numpy as np import matplotlib.pyplot as plt m = GEKKO(remote=False) # Create time vector [hours] tm = np.linspace(0,40,401) # Insert smaller time steps at the beginning tm = np.insert(tm,1,[0.001,0.005,0.01,0.05]) m.time = tm nt = len(tm) # Define constants and parameters ################################# # Kinetic Parameters a1 = m.Const(value=0.05, name='a1') # Ratkowsky parameter [oC-1 h-0.5] aP = m.Const(value=4.50, name='aP') # Growth-associated parameter for EtOh production [-] AP1 = m.Const(value=6.0, name='AP1') # Activation energy parameter for EtOh production [oC] AP2 = m.Const(value=20.3, name='AP2') # Activation energy parameter for EtOh production [oC] b1 = m.Const(value=0.035, name='b1') # Parameter in the exponential expression of the maximum specific growth rate expression [oC-1] b2 = m.Const(value=0.15, name='b2') # Parameter in the exponential expression of the maximum specific growth rate expression [oC-1] b3 = m.Const(value=0.40, name='b3') # Parameter in the exponential expression of the specific death rate expression [oC-1] c1 = m.Const(value=0.38, name='c1') # Constant decoupling factor for EtOh [kgP kgX-1 h-1] c2 = m.Const(value=0.29, name='c2') # Constant decoupling factor for EtOh [kgP kgX-1 h-1] k1 = m.Const(value=3, name='k1') # Parameter in the maximum specific growth rate expression [oC] k2 = m.Const(value=55, name='k2') # Parameter in the maximum specific growth rate expression [oC] k3 = m.Const(value=60, name='k3') # Parameter in the growth-inhibitory EtOH concentration expression [oC] k4 = m.Const(value=50, name='k4') # Temperature at the inflection point of the specific death rate sigmoid curve [oC] Pmaxb = m.Const(value=90, name='Pmaxb') # Temperature-independent product inhibition constant [kg m-3] PmaxT = m.Const(value=90, name='PmaxT') # Maximum value of product inhibition constant due to temperature [kg m-3] Kdb = m.Const(value=0.025, name='Kdb') # Basal specific cellular biomass death rate [h-1] KdT = m.Const(value=30, name='KdT') # Maximum value of specific cellular biomass death rate due to temperature [h-1] KSX = m.Const(value=5, name='KSX') # Glucose saturation constant for the specific growth rate [kg m-3] KOX = m.Const(value=0.0005, name='KOX') # Oxygen saturation constant for the specific growth rate [kg m-3] qOmax = m.Const(value=0.05, name='qOmax') # Maximum specific oxygen consumption rate [h-1] # Metabolic Parameters YPS = m.Const(value=0.51, name='YPS') # Theoretical yield of EtOH on glucose [kgP kgS-1] YXO = m.Const(value=0.97, name='YXO') # Theoretical yield of biomass on oxygen [kgX kgO-1] YXS = m.Const(value=0.53, name='YXS') # Theoretical yield of biomass on glucose [kgX kgS-1] # Physicochemical and thermodynamic parameters Chbr = m.Const(value=4.18, name='Chbr') # Heat capacity of the mass of reaction [kJ kg-1 oC-1] Chc = m.Const(value=4.18, name='Chc') # Heat capacity of cooling agent [kJ kg-1 oC-1] deltaH = m.Const(value=518.e3, name='deltaH') # Heat of reaction of fermentation [kJ kmol-1 O2] Tref = m.Const(value=25, name='Tref') # Reference temperature [oC] KH = m.Const(value=200, name='KH') # Henry's constant for oxygen in the fermentation broth [atm m3 kmol-1] z = m.Const(value=0.792, name='z') # Oxygen compressibility factor [-] R = m.Const(value=0.082, name='R') # Ideal gas constant [m3 atm kmol-1 oC-1] kla0 = m.Const(value=100, name='kla0') # Temperature-independent volumetric oxygen transfer coefficient [-h] KT = m.Const(value=360, name='KT') # Heat transfer coefficient [kJ h-1 m-2 oC-1] rho = m.Const(value=1080, name='rho') # Density of the fermentation broth [kg m-3] rhoc = m.Const(value=1000, name='rhoc') # Density of the cooling agent [kg m-3] MO = m.Const(value=31.998, name='MO') # Molecular weight of oxygen [kg kmol-1] # Bioreactor design data AT = m.Const(value=100, name='AT') # Bioreactor heat transfer area [m2] V = m.Const(value=2900, name='V') # Bioreactor working volume [m3] Vcj = m.Const(value=250, name='Vcj') # Cooling jacket volume [m3] Ogasin = m.Const(value=0.305, name='Ogasin') # Oxygen concentration in airflow inlet [kg m-3] # Define variables ################## # Manipulated Variables S0 = m.FV(value=50, lb=+0.0, ub=10000, name='S0') # Initial substrate concentration in loaded bioreactor [kg m-3] S0.STATUS = 1 Sin = m.MV(value=400, lb=0, ub=1500) # Substrate/Glucose concentration in bioreactor feed [kg m-3] Sin.STATUS = 1 Sin.DCOST = 0.0 Qin = m.MV(value=0, name='Qin') # Ideally Qin to be a step function Qin.STATUS = 1 Qin.DCOST = 0.0 Fc = m.FV(value=40, name='Fc') # Coolant inlet volumetric flow rate [m3 h-1] Fc.STATUS = 1 # Variables mi = m.Var(name='mi', lb=0) # Specific growth rate [kgP kgX-1 h-1] bP = m.Var(name='bP', lb=0) # Non-growth associated term [kgP kgX-1 h-1] # KPIs variables XXt = m.Var(name='XXt') # Biomass yield of glucose fermentation XP = m.Var(name='XP') # Ethanol yield of glucose fermentation Prod = m.Var(name='Prod', lb=1) # Bioreactor productivity in ethanol Gloss = m.Var(name='Gloss', ub=10000) # Substrate loss during fed-batch operation # Fixed variables, they are constant throughout the time horizon Xtin = m.FV(value=0, name='Xtin') # Total cellular biomass concentration in the bioreactor feed [kg/m3] Xvin = m.FV(value=0, name='Xvin') # Viable cellular biomass concentration in the bioreactor feed [kg/m3] Qe = m.FV(value=0, name='Qe') # Output flow rate [m3/h] Pin = m.FV(value=0, name='Pin') # Ethanol concentration in the bioreactor feed [kg/m3] Fair = m.FV(value=60000, name='Fair') # Air flow volumetric rate [m3/h] Tin = m.FV(value=30, name='Tin') # Temperature of bioreactor feed [oC] Tcin = m.FV(value=15, name='Tcin') # Temperature of coolant inlet [oC] # Differential equations variables Vl = m.Var(value=1000, ub=0.8*V, name='Vl') # [m3] Xt = m.Var(value=0.1, name='Xt') # [kg m-3] Xv = m.Var(value=0.1, name='Xv') # [kg m-3] S = m.Var(value=S0, name='S') # [kg m-3] P = m.Var(value=0, name='P') # [kg m-3] Ol = m.Var(value=0.0065, name= 'Ol') # [kg m-3] Og = m.Var(value=0.305, name='Og') # [kg m-3] T = m.Var(value=30, lb=20, ub=40, name='T') # [oC] Tc = m.Var(value=20, name='Tc') # [oC] Sf_cum = m.Var(value=0, name='Sf_cum') # [kg] t = m.Var(value=0, name='Time') # [h] # Define algebraic equations ############################ # Specific growth rate of cell mass mimax = m.Intermediate(((a1*(T-k1))*(1-m.exp(b1*(T-k2)))) ** 2) Pmax = m.Intermediate(Pmaxb + PmaxT/(1-m.exp(-b2*(T-k3)))) m.Equation(mi == mimax * S/(KSX+S) * Ol/(KOX + Ol) * (1 - P/Pmax) * 1 / (1+m.exp(-(100-S)/1))) # Specific production rate of EtOH m.Equation(bP == c1*m.exp(-AP1/T) - c2*m.exp(-AP2/T)) qP = m.Intermediate(aP*mi + bP) # Specific consumption rate of glucose qS = m.Intermediate(mi/YXS + qP/YPS) # Specific consumption rate of oxygen qO = m.Intermediate(qOmax*Ol/YXO/(KOX+Ol)) # Specific biological deactivation rate of cell mass Kd = m.Intermediate(Kdb + KdT/(1+m.exp(-b3*(T-k4)))) # Saturation concentration of oxygen in culture media Ostar = m.Intermediate(z*Og*R*T/KH) # Oxygen mass transfer coefficient kla = m.Intermediate(kla0*1.2**(T-20)) # Bioreactor phases equation Vg = m.Intermediate(V - Vl) # Define differential equations ############################### m.Equation(Vl.dt() == Qin - Qe) m.Equation(Vl*Xt.dt() == Qin*(Xtin-Xt) + mi*Vl*Xv) m.Equation(Vl*Xv.dt() == Qin*(Xvin-Xv) + Xv*Vl*(mi-Kd)) m.Equation(Vl*S.dt() == Qin*(Sin-S) - qS*Vl*Xv) m.Equation(Vl*P.dt() == Qin*(Pin-P) + qP*Vl*Xv) m.Equation(Vl*Ol.dt() == Qin*(Ostar-Ol) + Vl*kla*(Ostar-Ol) - qO*Vl*Xv) m.Equation(Vg*Og.dt() == Fair*(Ogasin-Og) - Vl*kla*(Ostar-Ol) + Og*(Qin-Qe)) m.Equation(Vl*T.dt() == Qin*(Tin-T) - Tref*(Qin-Qe) + Vl*qO*Xv*deltaH/MO/rho/Chbr - KT*AT*(T-Tc)/rho/Chbr) m.Equation(Vcj*Tc.dt() == Fc*(Tcin - Tc) + KT*AT*(T-Tc)/rhoc/Chc) m.Equation(Sf_cum.dt() == Qin*Sin) m.Equation(t.dt() == 1) # Yields and Productivity ######################### m.Equation(XXt == (Xt*Vl - Xt.value*Vl.value)/(S.value*Vl.value + Sf_cum)) m.Equation(XP == (P*Vl - P.value*Vl.value)/(S.value*Vl.value + Sf_cum)) m.Equation(Prod == (P-P.value)/t) m.Equation(Gloss == Vl*S) # solve DAE m.options.SOLVER= 1 m.options.IMODE = 7 m.options.NODES = 3 m.options.MAX_ITER = 3000 # m.open_folder() m.solve() # Objective function f = np.zeros(nt) f[-1] = 1.0 final = m.Param(value=f) m.Obj(-final*P) # Solve optimization problem m.options.IMODE=6 m.solve() print('Total loss of substrate: G=' + str(Gloss.value[-1]) + '[kg]') print('Biomass: Xt=' + str(Xt.value[-1]) + '[kg/m3]') print('Ethanol: P=' + str(P.value[-1]) + '[kg/m3]') print('Bioreactor productivity: Prod=' + str(Prod.value[-1]) + '[kg/m3/h]') print('Bioreactor operating volume: Vl='+ str(Vl.value[-1]) + '[m3]') # Plot results plt.figure(0) plt.title('Feeding Policy') plt.plot(m.time, Qin.value, label='Qin') plt.ylabel('Qin [m3/h]') plt.xlabel('Time [h]') plt.legend(); plt.grid(); plt.minorticks_on() plt.ylim(0); plt.xlim(m.time[0],m.time[-1]) plt.tight_layout() plt.figure(1) plt.title('Total & Viable Cellular Biomass') plt.plot(m.time, Xv.value, label='Xv') plt.plot(m.time, Xt.value, label='Xt') plt.ylabel('Biomass concentration [kg/m3]') plt.xlabel('Time [h]') plt.legend(); plt.grid(); plt.minorticks_on() plt.ylim(0); plt.xlim(m.time[0],m.time[-1]) plt.tight_layout() plt.figure(2) plt.title('Substrate (S) & Product (P) concentration') plt.plot(m.time, S.value, label='S') plt.plot(m.time, P.value, label='P') plt.ylabel('Concentration [kg/m3]') plt.xlabel('Time [h]') plt.legend(); plt.grid(); plt.minorticks_on() plt.ylim(0); plt.xlim(m.time[0],m.time[-1]) plt.tight_layout() fig3, ax = plt.subplots() ax.title.set_text('Dissolved & Gaseous Oxygen concentration') lns1 = ax.plot(m.time, Ol.value, label='[Oliq]', color='c') ax.set_xlabel('Time [h]') ax.set_ylabel('Oliq [kg/m3]', color='c') ax.minorticks_on() ax2 = ax.twinx() lns2 = ax2.plot(m.time, Og.value, label='[Ogas]', color='y') ax2.set_ylabel('Ogas [kg/m3]', color='y') ax2.minorticks_on() lns = lns1 + lns2 labs = [l.get_label() for l in lns] ax.legend(lns, labs, loc='best') ax.grid() ax.set_xlim(m.time[0],m.time[-1]) fig3.tight_layout() plt.figure(3) plt.figure(4) plt.title('Bioreactor & Cooling jacket temperature') plt.plot(m.time, T.value, label='T') plt.plot(m.time, Tc.value, label='Tc') plt.ylabel('Temperature [oC]') plt.xlabel('Time [h]') plt.legend(); plt.grid(); plt.minorticks_on() plt.ylim(0); plt.xlim(m.time[0],m.time[-1]) plt.tight_layout() fig5, ax = plt.subplots() ax.title.set_text('Specific rates & bP') lns1 = ax.plot(tm,Kd.value,label='Kd') lns2 = ax.plot(tm,mimax.value,label='mimax') lns3 = ax.plot(tm,mi.value,label='mi') ax.set_xlabel('Time [h]') ax.set_ylabel('Specific growth and death rate') ax.minorticks_on() ax2 = ax.twinx() lns4 = ax.plot(tm,bP.value,label='bP', color='magenta') ax2.set_ylabel('bP [1/h]', color='magenta') ax2.minorticks_on() lns = lns1 + lns2 + lns3 + lns4 labs = [l.get_label() for l in lns] ax.legend(lns, labs, loc='best'); ax.grid() ax.set_ylim(0); ax.set_xlim(m.time[0],m.time[-1]) fig5.tight_layout() plt.figure(5) fig6, ax = plt.subplots() ax.title.set_text('Ethanol yield & Productivity') lns1 = ax.plot(m.time, XP.value, label='xP', color='c') ax.set_xlabel('Time [h]') ax.set_ylabel('Ethanol yield on glucose', color='c') ax.minorticks_on() ax2 = ax.twinx() lns2 = ax2.plot(m.time, Prod.value, label='Prod', color='y') ax2.set_ylabel('Prod [kg/m3/h]', color='y') ax2.minorticks_on() lns = lns1 + lns2 labs = [l.get_label() for l in lns] ax.legend(lns, labs, loc='best') ax.grid() ax.set_ylim(0); ax.set_xlim(m.time[0],m.time[-1]) fig6.tight_layout() plt.figure(6) fig7, ax = plt.subplots() ax.title.set_text('Culture Volume & Total Substrate fed to the Bioreactor') lns1 = ax.plot(m.time, Vl.value, label='Vl', color='r') ax.set_xlabel('Time [h]') ax.set_ylabel('Vl [m3]', color='r') ax.minorticks_on() ax2 = ax.twinx() lns2 = ax2.plot(m.time, Sf_cum.value, label='Sf_cum', color='g') ax2.set_ylabel('Sf_cum [kg]', color='g') ax2.minorticks_on() lns = lns1 + lns2 labs = [l.get_label() for l in lns] ax.legend(lns, labs, loc='best') ax.grid() ax.set_ylim(900); ax2.set_ylim(0); ax.set_xlim(m.time[0],m.time[-1]) fig7.tight_layout() plt.figure(7) plt.show()
[ "Here are a few suggestions:\n\nRearrange equations to avoid divide-by-zero\nKPI equations do not influence other variables and can be converted to Intermediates or calculated after the solve\nUse COLDSTART with 2..1..0 to initialize the model with separate solves\nAdd constraints after the simulation initialization (COLDSTART=2,1). The constraints make the simulation infeasible.\nAdd upper and lower bounds to the decision variables such as Qin.\nUse m.free_initial(S) to calculate the initial condition S0. I left this out for now, but you could add it back.\nUse MV_STEP_HOR=100 to reduce the number of changes for Qin or Sin to 4 times per batch to reduce operator actions.\n(Optional) Consider fixing the temperature to just optimize yield and assume that there is excellent temperature control from a lower level controller. This would remove the energy balance equations that could be added later. It would also help with the solution speed and remove some of the rate equation exponential terms in the model that are challenging to solve.\n(Optional) Switch to the public server (remote=True) to see the iteration summary and monitor the progress of the solver. The local mode doesn't have that capability currently.\n\nBelow is code that almost solves successfully after 30 iterations. It may need some additional adjustments such as constraints with COLDSTART=0 to get a solution and the results that you expect.\n\n# Optimization logic:\n# Goal is to maximize ethanol concentration by the end of the batch time, keeping certain KPIs within limits.\n# Start with loose boundaries on: Prod, Gloss, T and slowly narrow them down.\n# Ideal case: Prod>=4, Gloss = 0 and T = 30-32oC throughout the time horizon, for that a PID controller might later be added.\n# Manipulated variables to achieve goal are: Qin, Sin, S0, Fc (Vl0 and batch time might as well be added).\n# Qin to be a step function, Sin can change to have substrate concentration at different levels in feed, S0 is fixed (concentration of substrate in loaded BR)\n# and Fc should be time dependant to ensure T is within boundaries.\n# Constraint due to problem definition on bioreactor working volume: Vl=<0.8V\n\nfrom gekko import GEKKO\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nm = GEKKO(remote=True)\n# Create time vector [hours]\ntm = np.linspace(0,40,401)\n# Insert smaller time steps at the beginning\ntm = np.insert(tm,1,[0.001,0.005,0.01,0.05])\nm.time = tm\nnt = len(tm)\n\n# Define constants and parameters\n#################################\n# Kinetic Parameters\na1 = m.Const(value=0.05, name='a1') # Ratkowsky parameter [oC-1 h-0.5]\naP = m.Const(value=4.50, name='aP') # Growth-associated parameter for EtOh production [-]\nAP1 = m.Const(value=6.0, name='AP1') # Activation energy parameter for EtOh production [oC]\nAP2 = m.Const(value=20.3, name='AP2') # Activation energy parameter for EtOh production [oC]\nb1 = m.Const(value=0.035, name='b1') # Parameter in the exponential expression of the maximum specific growth rate expression [oC-1]\nb2 = m.Const(value=0.15, name='b2') # Parameter in the exponential expression of the maximum specific growth rate expression [oC-1]\nb3 = m.Const(value=0.40, name='b3') # Parameter in the exponential expression of the specific death rate expression [oC-1]\nc1 = m.Const(value=0.38, name='c1') # Constant decoupling factor for EtOh [kgP kgX-1 h-1]\nc2 = m.Const(value=0.29, name='c2') # Constant decoupling factor for EtOh [kgP kgX-1 h-1]\nk1 = m.Const(value=3, name='k1') # Parameter in the maximum specific growth rate expression [oC]\nk2 = m.Const(value=55, name='k2') # Parameter in the maximum specific growth rate expression [oC]\nk3 = m.Const(value=60, name='k3') # Parameter in the growth-inhibitory EtOH concentration expression [oC]\nk4 = m.Const(value=50, name='k4') # Temperature at the inflection point of the specific death rate sigmoid curve [oC]\nPmaxb = m.Const(value=90, name='Pmaxb') # Temperature-independent product inhibition constant [kg m-3]\nPmaxT = m.Const(value=90, name='PmaxT') # Maximum value of product inhibition constant due to temperature [kg m-3]\nKdb = m.Const(value=0.025, name='Kdb') # Basal specific cellular biomass death rate [h-1]\nKdT = m.Const(value=30, name='KdT') # Maximum value of specific cellular biomass death rate due to temperature [h-1]\nKSX = m.Const(value=5, name='KSX') # Glucose saturation constant for the specific growth rate [kg m-3]\nKOX = m.Const(value=0.0005, name='KOX') # Oxygen saturation constant for the specific growth rate [kg m-3]\nqOmax = m.Const(value=0.05, name='qOmax') # Maximum specific oxygen consumption rate [h-1]\n\n# Metabolic Parameters\nYPS = m.Const(value=0.51, name='YPS') # Theoretical yield of EtOH on glucose [kgP kgS-1]\nYXO = m.Const(value=0.97, name='YXO') # Theoretical yield of biomass on oxygen [kgX kgO-1]\nYXS = m.Const(value=0.53, name='YXS') # Theoretical yield of biomass on glucose [kgX kgS-1]\n\n# Physicochemical and thermodynamic parameters\nChbr = m.Const(value=4.18, name='Chbr') # Heat capacity of the mass of reaction [kJ kg-1 oC-1]\nChc = m.Const(value=4.18, name='Chc') # Heat capacity of cooling agent [kJ kg-1 oC-1]\ndeltaH = m.Const(value=518.e3, name='deltaH') # Heat of reaction of fermentation [kJ kmol-1 O2]\nTref = m.Const(value=25, name='Tref') # Reference temperature [oC]\nKH = m.Const(value=200, name='KH') # Henry's constant for oxygen in the fermentation broth [atm m3 kmol-1]\nz = m.Const(value=0.792, name='z') # Oxygen compressibility factor [-]\nR = m.Const(value=0.082, name='R') # Ideal gas constant [m3 atm kmol-1 oC-1]\nkla0 = m.Const(value=100, name='kla0') # Temperature-independent volumetric oxygen transfer coefficient [-h]\nKT = m.Const(value=360, name='KT') # Heat transfer coefficient [kJ h-1 m-2 oC-1]\nrho = m.Const(value=1080, name='rho') # Density of the fermentation broth [kg m-3]\nrhoc = m.Const(value=1000, name='rhoc') # Density of the cooling agent [kg m-3]\nMO = m.Const(value=31.998, name='MO') # Molecular weight of oxygen [kg kmol-1]\n\n# Bioreactor design data\nAT = m.Const(value=100, name='AT') # Bioreactor heat transfer area [m2]\nV = m.Const(value=2900, name='V') # Bioreactor working volume [m3]\nVcj = m.Const(value=250, name='Vcj') # Cooling jacket volume [m3]\nOgasin = m.Const(value=0.305, name='Ogasin') # Oxygen concentration in airflow inlet [kg m-3]\n\n# Define variables\n##################\n# Manipulated Variables\n#S0 = m.FV(value=50, lb=+0.0, ub=10000, name='S0') # Initial substrate concentration in loaded bioreactor [kg m-3]\n#S0.STATUS = 1\n# use m.free_initial(S) after initialization\n\nSin = m.MV(value=400, lb=0, ub=1500) # Substrate/Glucose concentration in bioreactor feed [kg m-3]\nSin.STATUS = 1\nSin.DCOST = 0.0\nSin.MV_STEP_HOR = 100\n\nQin = m.MV(value=0.1, lb=0.1, ub=100, name='Qin') # Ideally Qin to be a step function\nQin.STATUS = 1\nQin.DCOST = 0.0\nQin.MV_STEP_HOR = 100\n\nFc = m.FV(value=40, lb=0, ub=1e4, name='Fc') # Coolant inlet volumetric flow rate [m3 h-1]\nFc.STATUS = 1\n\n# Variables\nmi = m.Var(name='mi') # Specific growth rate [kgP kgX-1 h-1]\nbP = m.Var(name='bP') # Non-growth associated term [kgP kgX-1 h-1]\n\n# Fixed variables, they are constant throughout the time horizon\nXtin = m.FV(value=0, name='Xtin') # Total cellular biomass concentration in the bioreactor feed [kg/m3]\nXvin = m.FV(value=0, name='Xvin') # Viable cellular biomass concentration in the bioreactor feed [kg/m3]\nQe = m.FV(value=0, name='Qe') # Output flow rate [m3/h]\nPin = m.FV(value=0, name='Pin') # Ethanol concentration in the bioreactor feed [kg/m3]\nFair = m.FV(value=60000, name='Fair') # Air flow volumetric rate [m3/h]\nTin = m.FV(value=30, name='Tin') # Temperature of bioreactor feed [oC]\nTcin = m.FV(value=15, name='Tcin') # Temperature of coolant inlet [oC]\n\n# Differential equations variables\nVl0 = 1000; Xt0 = 0.1; P0 = 0; S0 = 50\nVl = m.Var(value=Vl0, name='Vl') # [m3]\nXt = m.Var(value=Xt0, name='Xt') # [kg m-3]\nXv = m.Var(value=0.1, name='Xv') # [kg m-3]\nS = m.Var(value=S0, name='S') # [kg m-3]\nP = m.Var(value=P0, name='P') # [kg m-3]\nOl = m.Var(value=0.0065, name= 'Ol') # [kg m-3]\nOg = m.Var(value=0.305, name='Og') # [kg m-3]\nT = m.Var(value=30,name='T') # [oC]\nTc = m.Var(value=20, name='Tc') # [oC]\nSf_cum = m.Var(value=0, name='Sf_cum') # [kg]\n\n# Define algebraic equations\n############################\n# Specific growth rate of cell mass\nmimax = m.Intermediate(((a1*(T-k1))*(1-m.exp(b1*(T-k2)))) ** 2)\nPmax = m.Intermediate(Pmaxb + PmaxT/(1-m.exp(-b2*(T-k3))))\nm.Equation(mi == mimax * S/(KSX+S) * Ol/(KOX + Ol) * (1 - P/Pmax) * 1 / (1+m.exp(-(100-S)/1)))\n# Specific production rate of EtOH\nbPe = m.Intermediate(c1*m.exp(-AP1/T) - c2*m.exp(-AP2/T))\nm.Equation(bP == bPe)\nqP = m.Intermediate(aP*mi + bP)\n# Specific consumption rate of glucose\nqS = m.Intermediate(mi/YXS + qP/YPS)\n# Specific consumption rate of oxygen\nqO = m.Intermediate(qOmax*Ol/YXO/(KOX+Ol))\n# Specific biological deactivation rate of cell mass\nKd = m.Intermediate(Kdb + KdT/(1+m.exp(-b3*(T-k4))))\n# Saturation concentration of oxygen in culture media\nOstar = m.Intermediate(z*Og*R*T/KH)\n# Oxygen mass transfer coefficient\nkla = m.Intermediate(kla0*1.2**(T-20))\n# Bioreactor phases equation\nVg = m.Intermediate(V - Vl)\n\n# Define differential equations\n###############################\nm.Equation(Vl.dt() == Qin - Qe)\nm.Equation(Vl*Xt.dt() == Qin*(Xtin-Xt) + mi*Vl*Xv)\nm.Equation(Vl*Xv.dt() == Qin*(Xvin-Xv) + Xv*Vl*(mi-Kd))\nm.Equation(Vl*S.dt() == Qin*(Sin-S) - qS*Vl*Xv)\nm.Equation(Vl*P.dt() == Qin*(Pin-P) + qP*Vl*Xv)\nm.Equation(Vl*Ol.dt() == Qin*(Ostar-Ol) + Vl*kla*(Ostar-Ol) - qO*Vl*Xv)\nm.Equation(Vg*Og.dt() == Fair*(Ogasin-Og) - Vl*kla*(Ostar-Ol) + Og*(Qin-Qe))\nm.Equation(Vl*T.dt() == Qin*(Tin-T) - Tref*(Qin-Qe) + Vl*qO*Xv*deltaH/MO/rho/Chbr - KT*AT*(T-Tc)/rho/Chbr)\nm.Equation(Vcj*Tc.dt() == Fc*(Tcin - Tc) + KT*AT*(T-Tc)/rhoc/Chc)\nm.Equation(Sf_cum.dt() == Qin*Sin)\n\n# KPIs as Intermediates or Var/Equations\nkpi_interm = True\nif kpi_interm:\n t = m.Param(m.time)\n XXt = m.Intermediate((Xt*Vl - Xt0*Vl0)/(S0*Vl0 + Sf_cum))\n XP = m.Intermediate((P*Vl - P0*Vl0)/(S0*Vl0 + Sf_cum))\n Prod = m.Intermediate((P-P0)/t)\n Gloss = m.Intermediate(Vl*S)\nelse:\n # include KPIs as equations\n # KPIs variables\n t = m.Var(value=0, name='Time') # [h]\n XXt = m.Var(name='XXt') # Biomass yield of glucose fermentation\n XP = m.Var(name='XP') # Ethanol yield of glucose fermentation\n Prod = m.Var(name='Prod') #, lb=1) # Bioreactor productivity in ethanol\n Gloss = m.Var(name='Gloss') # Substrate loss during fed-batch operation\n\n # Yields and Productivity\n #########################\n m.Equation(t.dt() == 1)\n m.Equation(XXt*(S0*Vl0 + Sf_cum) == (Xt*Vl - Xt0*Vl0))\n m.Equation(XP *(S0*Vl0 + Sf_cum) == (P*Vl - P0*Vl0))\n m.Equation(Prod * t == (P-P0))\n m.Equation(Gloss == Vl*S)\n\nmi.LOWER = 0\nbP.LOWER = 0\nT.LOWER=0\n\n# solve DAE\nm.options.SOLVER= 1\nm.options.REDUCE = 3\nm.options.NODES = 2\nm.options.IMODE = 6\nm.options.COLDSTART = 2\nm.options.MAX_ITER = 3000\n# m.open_folder()\nprint('Start Coldstart Simulation')\nm.solve()\nprint('End Coldstart Simulation')\n\n# Objective function\nf = np.zeros(nt)\nf[-1] = 1.0\nfinal = m.Param(value=f)\nm.Maximize(final*P)\n\n# Solve optimization problem\n#m.options.SOLVER = 3\nm.options.TIME_SHIFT = 0\nm.options.COLDSTART=1\nm.options.NODES=3\nm.options.IMODE=6\nprint('Start Optimization Coldstart')\nm.solve(disp=True)\nprint('End Optimization Coldstart')\n\n# Add some variable bounds back after simulation\nT.UPPER=40\nP.LOWER = 0\nGloss.UPPER=10000\nVl.UPPER=0.8*V \n\n# Calculate S0\nm.free_initial(S)\n\nm.options.TIME_SHIFT=0\nm.options.COLDSTART=0\nm.options.NODES=3\nm.options.IMODE=6\nm.options.SOLVER= 1\nprint('Start Optimization')\nm.solve(disp=True)\nprint('End Optimization')\n\nprint('Total loss of substrate: G=' + str(Gloss.value[-1]) + '[kg]')\nprint('Biomass: Xt=' + str(Xt.value[-1]) + '[kg/m3]')\nprint('Ethanol: P=' + str(P.value[-1]) + '[kg/m3]')\nprint('Bioreactor productivity: Prod=' + str(Prod.value[-1]) + '[kg/m3/h]')\nprint('Bioreactor operating volume: Vl='+ str(Vl.value[-1]) + '[m3]')\n\n# Plot results\nplt.figure(0)\nplt.title('Feeding Policy')\nplt.plot(m.time, Qin.value, label='Qin')\nplt.ylabel('Qin [m3/h]')\nplt.xlabel('Time [h]')\nplt.legend(); plt.grid(); plt.minorticks_on()\nplt.ylim(0); plt.xlim(m.time[0],m.time[-1])\nplt.tight_layout()\n\nplt.figure(1)\nplt.title('Total & Viable Cellular Biomass')\nplt.plot(m.time, Xv.value, label='Xv')\nplt.plot(m.time, Xt.value, label='Xt')\nplt.ylabel('Biomass concentration [kg/m3]')\nplt.xlabel('Time [h]')\nplt.legend(); plt.grid(); plt.minorticks_on()\nplt.ylim(0); plt.xlim(m.time[0],m.time[-1])\nplt.tight_layout()\n\nplt.figure(2)\nplt.title('Substrate (S) & Product (P) concentration')\nplt.plot(m.time, S.value, label='S')\nplt.plot(m.time, P.value, label='P')\nplt.ylabel('Concentration [kg/m3]')\nplt.xlabel('Time [h]')\nplt.legend(); plt.grid(); plt.minorticks_on()\nplt.ylim(0); plt.xlim(m.time[0],m.time[-1])\nplt.tight_layout()\n\nfig3, ax = plt.subplots()\nax.title.set_text('Dissolved & Gaseous Oxygen concentration')\nlns1 = ax.plot(m.time, Ol.value, label='[Oliq]', color='c')\nax.set_xlabel('Time [h]')\nax.set_ylabel('Oliq [kg/m3]', color='c')\nax.minorticks_on()\nax2 = ax.twinx()\nlns2 = ax2.plot(m.time, Og.value, label='[Ogas]', color='y')\nax2.set_ylabel('Ogas [kg/m3]', color='y')\nax2.minorticks_on()\nlns = lns1 + lns2\nlabs = [l.get_label() for l in lns]\nax.legend(lns, labs, loc='best')\nax.grid()\nax.set_xlim(m.time[0],m.time[-1])\nfig3.tight_layout()\nplt.figure(3)\n\nplt.figure(4)\nplt.title('Bioreactor & Cooling jacket temperature')\nplt.plot(m.time, T.value, label='T')\nplt.plot(m.time, Tc.value, label='Tc')\nplt.ylabel('Temperature [oC]')\nplt.xlabel('Time [h]')\nplt.legend(); plt.grid(); plt.minorticks_on()\nplt.ylim(0); plt.xlim(m.time[0],m.time[-1])\nplt.tight_layout()\n\nfig5, ax = plt.subplots()\nax.title.set_text('Specific rates & bP')\nlns1 = ax.plot(tm,Kd.value,label='Kd')\nlns2 = ax.plot(tm,mimax.value,label='mimax')\nlns3 = ax.plot(tm,mi.value,label='mi')\nax.set_xlabel('Time [h]')\nax.set_ylabel('Specific growth and death rate')\nax.minorticks_on()\nax2 = ax.twinx()\nlns4 = ax.plot(tm,bP.value,label='bP', color='magenta')\nax2.set_ylabel('bP [1/h]', color='magenta')\nax2.minorticks_on()\nlns = lns1 + lns2 + lns3 + lns4\nlabs = [l.get_label() for l in lns]\nax.legend(lns, labs, loc='best'); ax.grid()\nax.set_ylim(0); ax.set_xlim(m.time[0],m.time[-1])\nfig5.tight_layout()\nplt.figure(5)\n\nfig6, ax = plt.subplots()\nax.title.set_text('Ethanol yield & Productivity')\nlns1 = ax.plot(m.time, XP.value, label='xP', color='c')\nax.set_xlabel('Time [h]')\nax.set_ylabel('Ethanol yield on glucose', color='c')\nax.minorticks_on()\nax2 = ax.twinx()\nlns2 = ax2.plot(m.time, Prod.value, label='Prod', color='y')\nax2.set_ylabel('Prod [kg/m3/h]', color='y')\nax2.minorticks_on()\nlns = lns1 + lns2\nlabs = [l.get_label() for l in lns]\nax.legend(lns, labs, loc='best')\nax.grid()\nax.set_ylim(0); ax.set_xlim(m.time[0],m.time[-1])\nfig6.tight_layout()\nplt.figure(6)\n\nfig7, ax = plt.subplots()\nax.title.set_text('Culture Volume & Total Substrate fed to the Bioreactor')\nlns1 = ax.plot(m.time, Vl.value, label='Vl', color='r')\nax.set_xlabel('Time [h]')\nax.set_ylabel('Vl [m3]', color='r')\nax.minorticks_on()\nax2 = ax.twinx()\nlns2 = ax2.plot(m.time, Sf_cum.value, label='Sf_cum', color='g')\nax2.set_ylabel('Sf_cum [kg]', color='g')\nax2.minorticks_on()\nlns = lns1 + lns2\nlabs = [l.get_label() for l in lns]\nax.legend(lns, labs, loc='best')\nax.grid()\nax.set_ylim(900); ax2.set_ylim(0); ax.set_xlim(m.time[0],m.time[-1])\nfig7.tight_layout()\nplt.figure(7)\n\nplt.show()\n\nIt is also possible to optimize the total batch time. See the Jennings problem for an example.\n" ]
[ 0 ]
[]
[]
[ "gekko" ]
stackoverflow_0074576388_gekko.txt
Q: DiscordJSv14 Recording / Receiving Voice Audio So I'm working on a Discord bot using JS and DiscordJSv14, and want the bot to use audio from a voice chat to send to another bot, some type of listen and snitch bot. So far I got the Bot's connecting to the voice call but can't get any of the packets to send to the other bot. Here's some code I've got so far: const connection = joinVoiceChannel({ channelId: C.id, guildId: guild.id, adapterCreator: guild.voiceAdapterCreator, selfDeaf: false, selfMute: false, group: this.client.user.id, }); if (isListener) { console.log("Listener Is Joining Voice And Listening..."); const encoder = new OpusEncoder(48000, 2); let subscription = connection.receiver.subscribe(ID); // ID = Bot's ID // Basically client.user.id subscription.on("data", (chunk) => { console.log(encoder.decode(chunk)); }); } Console won't log anything about the chunk Using DiscordJSv14 + @discordjs/opus A: Everything worked fine I just needed to add the following code below. this.client = new Client({ intents: [GatewayIntentBits.GuildVoiceStates, GatewayIntentBits.GuildMessages, GatewayIntentBits.Guilds], });
DiscordJSv14 Recording / Receiving Voice Audio
So I'm working on a Discord bot using JS and DiscordJSv14, and want the bot to use audio from a voice chat to send to another bot, some type of listen and snitch bot. So far I got the Bot's connecting to the voice call but can't get any of the packets to send to the other bot. Here's some code I've got so far: const connection = joinVoiceChannel({ channelId: C.id, guildId: guild.id, adapterCreator: guild.voiceAdapterCreator, selfDeaf: false, selfMute: false, group: this.client.user.id, }); if (isListener) { console.log("Listener Is Joining Voice And Listening..."); const encoder = new OpusEncoder(48000, 2); let subscription = connection.receiver.subscribe(ID); // ID = Bot's ID // Basically client.user.id subscription.on("data", (chunk) => { console.log(encoder.decode(chunk)); }); } Console won't log anything about the chunk Using DiscordJSv14 + @discordjs/opus
[ "Everything worked fine I just needed to add the following code below.\nthis.client = new Client({\n intents: [GatewayIntentBits.GuildVoiceStates, GatewayIntentBits.GuildMessages, GatewayIntentBits.Guilds],\n});\n\n" ]
[ 0 ]
[]
[]
[ "discord", "discord.js", "javascript", "node.js" ]
stackoverflow_0074651993_discord_discord.js_javascript_node.js.txt
Q: How do I make external links pass through an affiliate link first using .htaccess or Javascript? I have a significant amount of external links on my website in this format: website.com/product/[variable] I need these links to somehow pass through “myaffiliatelink.com” before being redirected to website.com/product/[variable]. Is this possible using .htaccess or Javascript? I looked into using .htaccess, but seems I would need to do this individually. Is there a way to set a rule such that any external link using "website.com/product/[variable]" should pass through "myaffiliatelink.com" first? A: // catch every click on the page document.addEventListener("click", e => { const target = e.target; if (target.tagName === 'A' && target.href.indexOf("website.com") !== -1) { // prevent the <a> tag from navigating e.preventDefault(); const lastSlash = target.href.lastIndexOf('/'); if (lastSlash > 0) { const variable = target.href.substring(lastSlash + 1); // use the commented code below, or a window.open //location.href = "https://myaffiliatelink.com/"+variable; // for demonstration console.log("https://myaffiliatelink.com/" + variable); } } }) <a href="https://website.com/product/[variable]">Product</a> <p>should pass through "myaffiliatelink.com"</p>
How do I make external links pass through an affiliate link first using .htaccess or Javascript?
I have a significant amount of external links on my website in this format: website.com/product/[variable] I need these links to somehow pass through “myaffiliatelink.com” before being redirected to website.com/product/[variable]. Is this possible using .htaccess or Javascript? I looked into using .htaccess, but seems I would need to do this individually. Is there a way to set a rule such that any external link using "website.com/product/[variable]" should pass through "myaffiliatelink.com" first?
[ "\n\n// catch every click on the page\ndocument.addEventListener(\"click\", e => {\n const target = e.target;\n if (target.tagName === 'A' && target.href.indexOf(\"website.com\") !== -1) {\n // prevent the <a> tag from navigating\n e.preventDefault();\n const lastSlash = target.href.lastIndexOf('/');\n if (lastSlash > 0) {\n const variable = target.href.substring(lastSlash + 1);\n // use the commented code below, or a window.open\n //location.href = \"https://myaffiliatelink.com/\"+variable;\n // for demonstration\n console.log(\"https://myaffiliatelink.com/\" + variable);\n }\n }\n})\n<a href=\"https://website.com/product/[variable]\">Product</a>\n<p>should pass through \"myaffiliatelink.com\"</p>\n\n\n\n" ]
[ 0 ]
[]
[]
[ ".htaccess", "affiliate", "hyperlink", "javascript", "php" ]
stackoverflow_0074663916_.htaccess_affiliate_hyperlink_javascript_php.txt
Q: Kivy: laptop touch pad - mouse cursor move My problem is simple and certainly isn't any news: I can manage my Kivy desktop app with a mouse pretty reasonably. Unfortunately, touch pad is a different story: a single finger move is interpreted as a swipe so there's no way to just move the mouse cursor where it's needed. Google isn't very cooperative; maybe I don't know the keywords? The desktop is KDE on Linux. Is there a way to make a Kivy desktop app respond to the touch pad the way ordinary desktop apps do? Input management looks close, but low level. I'm sorry, I'm new to Kivy. A: A solution: comment out probesysfs line in ~/.kivy/config.ini. ... [input] mouse = mouse #%(name)s = probesysfs ...
Kivy: laptop touch pad - mouse cursor move
My problem is simple and certainly isn't any news: I can manage my Kivy desktop app with a mouse pretty reasonably. Unfortunately, touch pad is a different story: a single finger move is interpreted as a swipe so there's no way to just move the mouse cursor where it's needed. Google isn't very cooperative; maybe I don't know the keywords? The desktop is KDE on Linux. Is there a way to make a Kivy desktop app respond to the touch pad the way ordinary desktop apps do? Input management looks close, but low level. I'm sorry, I'm new to Kivy.
[ "A solution: comment out probesysfs line in ~/.kivy/config.ini.\n...\n[input]\nmouse = mouse\n#%(name)s = probesysfs\n...\n\n" ]
[ 1 ]
[]
[]
[ "desktop_application", "gesture", "kivy", "python", "touchpad" ]
stackoverflow_0074646535_desktop_application_gesture_kivy_python_touchpad.txt
Q: Regex only works if the input is split line by line first The following pattern only matches when splitting the input line by line first: (?<=^\p{Z}*)\?.*\(.*\)$ When I do this I get zero matches: var matches = Regex.Matches(input, @"(?<=^\p{Z}*)\?.*\(.*\)$", RegexOptions.Multiline); When I do split the input line by line first it does work: using (var reader = new StringReader(input)) { while (reader.ReadLine() is { } line) { if (string.IsNullOrWhiteSpace(line)) { continue; } var match = Regex.Match(line, @"(?<=^\p{Z}*)\?.*\(.*\)$"); if (match.Success) { Console.WriteLine($"Result: {match}"); } } } However, online, it just works. Question: How to get this regex to match without having to split the input into lines first? A: Finally found the cause, this special behavior is explained in the documentation: To match the CR/LF character combination, include \r?$ in the regular expression pattern. So we end up with the following pattern that works on a multi-line string: (?<=^\p{Z}*)\?.*\(.*\)\r?$
Regex only works if the input is split line by line first
The following pattern only matches when splitting the input line by line first: (?<=^\p{Z}*)\?.*\(.*\)$ When I do this I get zero matches: var matches = Regex.Matches(input, @"(?<=^\p{Z}*)\?.*\(.*\)$", RegexOptions.Multiline); When I do split the input line by line first it does work: using (var reader = new StringReader(input)) { while (reader.ReadLine() is { } line) { if (string.IsNullOrWhiteSpace(line)) { continue; } var match = Regex.Match(line, @"(?<=^\p{Z}*)\?.*\(.*\)$"); if (match.Success) { Console.WriteLine($"Result: {match}"); } } } However, online, it just works. Question: How to get this regex to match without having to split the input into lines first?
[ "Finally found the cause, this special behavior is explained in the documentation:\n\nTo match the CR/LF character combination, include \\r?$ in the regular expression pattern.\n\nSo we end up with the following pattern that works on a multi-line string:\n(?<=^\\p{Z}*)\\?.*\\(.*\\)\\r?$\n\n" ]
[ 0 ]
[]
[]
[ ".net", "regex" ]
stackoverflow_0074663614_.net_regex.txt
Q: list check logic in typescript I have a list like below. empList = ['one','two','finish','one','three'] I need to check condition from empList scenario 1: if list order 'two' is coming before 'finish' I have to make this.beforeCheckFlag = true scenario 2: if list order 'two' is coming after 'finish' I have to make this.afterCheckFlag = true A: You can use here Map to store the emp as key and index as value as: const empList = ['one', 'two', 'finish', 'one', 'three']; const map = new Map(empList.map((emp, index) => [emp, index])); // If 'two' comes before 'finish' then its index will be lesser const beforeCheckFlag = map.get('two') < map.get('finish'); console.log(beforeCheckFlag); // If 'two' comes before 'finish' then its index will be greater const afterCheckFlag = map.get('two') > map.get('finish'); console.log(afterCheckFlag);
list check logic in typescript
I have a list like below. empList = ['one','two','finish','one','three'] I need to check condition from empList scenario 1: if list order 'two' is coming before 'finish' I have to make this.beforeCheckFlag = true scenario 2: if list order 'two' is coming after 'finish' I have to make this.afterCheckFlag = true
[ "You can use here Map to store the emp as key and index as value as:\n\n\nconst empList = ['one', 'two', 'finish', 'one', 'three'];\nconst map = new Map(empList.map((emp, index) => [emp, index]));\n\n// If 'two' comes before 'finish' then its index will be lesser\nconst beforeCheckFlag = map.get('two') < map.get('finish');\nconsole.log(beforeCheckFlag);\n\n// If 'two' comes before 'finish' then its index will be greater\nconst afterCheckFlag = map.get('two') > map.get('finish');\nconsole.log(afterCheckFlag);\n\n\n\n" ]
[ 0 ]
[]
[]
[ "angular", "typescript" ]
stackoverflow_0074663630_angular_typescript.txt
Q: Python: How to ffill and bfill a column with nan? How might I ffill and bfill a column that contains nans? Consider this example: # data df = pd.DataFrame([ [np.nan, '2019-01-01', 'P', 'O', 'A'], [np.nan, '2019-01-02', 'O', 'O', 'A'], ['A', '2019-01-03', 'O', 'O', 'A'], ['A', '2019-01-04', 'O', 'P', 'A'], [np.nan, '2019-01-05', 'O', 'P', 'A'], [np.nan, '2019-01-01', 'P', 'O', 'B'], ['B', '2019-01-02', 'O', 'O', 'B'], ['B', '2019-01-03', 'O', 'O', 'B'], ['B', '2019-01-04', 'O', 'P', 'B'], [np.nan, '2019-01-05', 'O', 'P', 'B'], ], columns=['ID', 'Time', 'FromState', 'ToState', 'Expected']) # updated try df['ID'] = df['ID'].transform(lambda x: x.ffill().bfill() ) A: The following works for me: df['ID'] = df['ID'].ffill(limit=1).bfill(limit=2)
Python: How to ffill and bfill a column with nan?
How might I ffill and bfill a column that contains nans? Consider this example: # data df = pd.DataFrame([ [np.nan, '2019-01-01', 'P', 'O', 'A'], [np.nan, '2019-01-02', 'O', 'O', 'A'], ['A', '2019-01-03', 'O', 'O', 'A'], ['A', '2019-01-04', 'O', 'P', 'A'], [np.nan, '2019-01-05', 'O', 'P', 'A'], [np.nan, '2019-01-01', 'P', 'O', 'B'], ['B', '2019-01-02', 'O', 'O', 'B'], ['B', '2019-01-03', 'O', 'O', 'B'], ['B', '2019-01-04', 'O', 'P', 'B'], [np.nan, '2019-01-05', 'O', 'P', 'B'], ], columns=['ID', 'Time', 'FromState', 'ToState', 'Expected']) # updated try df['ID'] = df['ID'].transform(lambda x: x.ffill().bfill() )
[ "The following works for me:\ndf['ID'] = df['ID'].ffill(limit=1).bfill(limit=2)\n\n" ]
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074663824_pandas_python.txt
Q: Error with while (cap.isopened()): in python using cv2 There are a lot of examples using while (cap.isopened()): to loop through a video, but I've found that it always errors out on the last frame. I'm currently using this instead while (cap.get(1) < cap.get(7)): but is there something I need to do to get the first method to work and not error out? I'm just doing normal things within the while loop; an example is below: while (cap.get(1) < cap.get(7)): #(cap.isOpened()): ret, frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cv2.imshow('frame',gray) if cv2.waitKey(1) & 0xFF == ord('q'): break A: The first method is most likely failing because you're reading a frame after the video is over (and thus getting a blank frame), and then trying to do things to that blank frame which aren't allowed. You can add a check to see if the frame you got was blank: while(cap.isOpened()): ret, frame = cap.read() if frame is None: break I believe this should fix the issue. A: while cap.isOpened(): # reading frames success, img = cap.read() # success will be true if the images are read successfully. if success: # Do your work here else: print("Did not read the frame")
Error with while (cap.isopened()): in python using cv2
There are a lot of examples using while (cap.isopened()): to loop through a video, but I've found that it always errors out on the last frame. I'm currently using this instead while (cap.get(1) < cap.get(7)): but is there something I need to do to get the first method to work and not error out? I'm just doing normal things within the while loop; an example is below: while (cap.get(1) < cap.get(7)): #(cap.isOpened()): ret, frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cv2.imshow('frame',gray) if cv2.waitKey(1) & 0xFF == ord('q'): break
[ "The first method is most likely failing because you're reading a frame after the video is over (and thus getting a blank frame), and then trying to do things to that blank frame which aren't allowed. You can add a check to see if the frame you got was blank:\n while(cap.isOpened()):\n ret, frame = cap.read()\n if frame is None:\n break\n\nI believe this should fix the issue.\n", "while cap.isOpened():\n# reading frames\nsuccess, img = cap.read()\n# success will be true if the images are read successfully.\nif success:\n # Do your work here\nelse:\n print(\"Did not read the frame\")\n\n" ]
[ 4, 0 ]
[]
[]
[ "opencv", "python" ]
stackoverflow_0027148047_opencv_python.txt
Q: VSCode jumpiness when editing markdown and preview pane is open This problem comes and goes, but it's been getting unbearable as times goes on. The environment: I am using the latest version of VSCode (1.45.1) on a mac running OSX 10.15.4. with a minimal set of extensions (I have disabled everything I can), namely: Markdown All in One 2.8.0 Markdown Preview Mermaid Markdownlint 0.35.1 The problem: When I am editing a Markdown document with preview alongside it, the text window jumps with the cursor location moving up the window to the point of disappearing at the top. I am not sure exactly what triggers this behavior, but I suspect it has to do with using any sort of graphic rendering, be it MathJax, Mermaid, or a simple figure. Online searches show similar behavior reported, and supposedly corrected, several years ago. But nothing recent which surprises me as it is maddening. The question Anyone has seen this behavior? Any idea what could be triggering it? Update: After more than a week trying to fix this, a couple hours after posting this question (and with no changes that I can think of on my part, it seems to have fixed itself). I am just waiting for the problem to come back. This is infuriating. Of course, a mere few hours afterwards the same problem came back. It seems to be some specific property of the markdown file as two different computers with different screen and window sizes started and stopped behaving exactly the same way with the same files. At the suggestion of @user8682688, who found the settings for the scroll synchronization in VSCode, I turned off synchronization from the preview window back into the editor ("markdown.preview.scrollEditorWithPreview": false) this at least removed the jumping from the the editor window making it usable again, but the preview window is still jumping all over the place which is the actual bug. Of course, I could disable the updating altogether with markdown.preview.scrollPreviewWithEditor, but that's just a work-around that removes useful functionality. A: VSCode automatically synchronizes the Markdown editor and the preview panes. Have you tried to disable the markdown.preview.scrollPreviewWithEditor and markdown.preview.scrollEditorWithPreview settings? ref: https://code.visualstudio.com/docs/languages/markdown#_editor-and-preview-synchronization A: For posterity, whenever getting a weird issue like this comment out all the settings in Vscode JSON settings and then try again. I had a weird markdown file issue similar to what you are describing and I just commented out all my settings and then it worked as expected.
VSCode jumpiness when editing markdown and preview pane is open
This problem comes and goes, but it's been getting unbearable as times goes on. The environment: I am using the latest version of VSCode (1.45.1) on a mac running OSX 10.15.4. with a minimal set of extensions (I have disabled everything I can), namely: Markdown All in One 2.8.0 Markdown Preview Mermaid Markdownlint 0.35.1 The problem: When I am editing a Markdown document with preview alongside it, the text window jumps with the cursor location moving up the window to the point of disappearing at the top. I am not sure exactly what triggers this behavior, but I suspect it has to do with using any sort of graphic rendering, be it MathJax, Mermaid, or a simple figure. Online searches show similar behavior reported, and supposedly corrected, several years ago. But nothing recent which surprises me as it is maddening. The question Anyone has seen this behavior? Any idea what could be triggering it? Update: After more than a week trying to fix this, a couple hours after posting this question (and with no changes that I can think of on my part, it seems to have fixed itself). I am just waiting for the problem to come back. This is infuriating. Of course, a mere few hours afterwards the same problem came back. It seems to be some specific property of the markdown file as two different computers with different screen and window sizes started and stopped behaving exactly the same way with the same files. At the suggestion of @user8682688, who found the settings for the scroll synchronization in VSCode, I turned off synchronization from the preview window back into the editor ("markdown.preview.scrollEditorWithPreview": false) this at least removed the jumping from the the editor window making it usable again, but the preview window is still jumping all over the place which is the actual bug. Of course, I could disable the updating altogether with markdown.preview.scrollPreviewWithEditor, but that's just a work-around that removes useful functionality.
[ "VSCode automatically synchronizes the Markdown editor and the preview panes. Have you tried to disable the markdown.preview.scrollPreviewWithEditor and markdown.preview.scrollEditorWithPreview settings?\nref: https://code.visualstudio.com/docs/languages/markdown#_editor-and-preview-synchronization\n", "For posterity, whenever getting a weird issue like this comment out all the settings in Vscode JSON settings and then try again. I had a weird markdown file issue similar to what you are describing and I just commented out all my settings and then it worked as expected.\n" ]
[ 11, 0 ]
[]
[]
[ "markdown", "mathjax", "mermaid", "visual_studio_code" ]
stackoverflow_0061831197_markdown_mathjax_mermaid_visual_studio_code.txt
Q: Python TypeError: Unhashable type when inheriting from subclass with __hash__ I have a base class and a subclass, such as: class Base: def __init__(self, x): self.x = x def __eq__(self, other): return self.x == other.x def __hash__(self): return hash(self.x) class Subclass(Base): def __init__(self, x, y): super().__init__(x) self.y = y def __eq__(self, other): return self.x == other.x and self.y == other.y Since the parent class implements __hash__, it should be hashable. However, when I try to put two copies in a set, such as {Subclass(1, 2), Subclass(1, 3)}, I get this error: TypeError: unhashable type: 'Subclass' I know if an object implements __eq__ but not __hash__ then it throws the TypeError, but there is a clearly implemented hash function. What's going on? A: The __eq__ rule applies both to classes without any subclasses implementing __hash__ and to classes that have a parent class with a hash function. If a class overrides __eq__, it must override __hash__ alongside it. To fix your sample: class Base: def __init__(self, x): self.x = x def __eq__(self, other): return self.x == other.x def __hash__(self): return hash(self.x) class Subclass(Base): def __init__(self, x, y): super().__init__(x) self.y = y def __eq__(self, other): return self.x == other.x and self.y == other.y def __hash__(self): return hash((self.x, self.y))
Python TypeError: Unhashable type when inheriting from subclass with __hash__
I have a base class and a subclass, such as: class Base: def __init__(self, x): self.x = x def __eq__(self, other): return self.x == other.x def __hash__(self): return hash(self.x) class Subclass(Base): def __init__(self, x, y): super().__init__(x) self.y = y def __eq__(self, other): return self.x == other.x and self.y == other.y Since the parent class implements __hash__, it should be hashable. However, when I try to put two copies in a set, such as {Subclass(1, 2), Subclass(1, 3)}, I get this error: TypeError: unhashable type: 'Subclass' I know if an object implements __eq__ but not __hash__ then it throws the TypeError, but there is a clearly implemented hash function. What's going on?
[ "The __eq__ rule applies both to classes without any subclasses implementing __hash__ and to classes that have a parent class with a hash function. If a class overrides __eq__, it must override __hash__ alongside it.\nTo fix your sample:\nclass Base:\n def __init__(self, x):\n self.x = x\n def __eq__(self, other):\n return self.x == other.x\n def __hash__(self):\n return hash(self.x)\n\nclass Subclass(Base):\n def __init__(self, x, y):\n super().__init__(x)\n self.y = y\n def __eq__(self, other):\n return self.x == other.x and self.y == other.y\n def __hash__(self):\n return hash((self.x, self.y))\n\n" ]
[ 2 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074664008_python_python_3.x.txt
Q: How do I write all my BeautifulSoup data from a website to a text file? Python I am trying to read data from open insider and put it into an easy to read text file. Here is my code so far: from bs4 import BeautifulSoup import requests page = requests.get("http://openinsider.com/top-insider-purchases-of-the-month") '''print(page.status_code) checks to see if the page was downloaded successfully''' soup = BeautifulSoup(page.content,'html.parser') # Find the table with the insider purchase data table = soup.find(class_="tinytable") # Find all rows of the table rows = table.find_all('tr') # Loop through each row for row in rows: # Extract the company name, insider name, and trade type from the row data = row.find_all("td") ticker = data[3].get_text() if len(data) > 3 else "Ticker representing the company" company = data[4].get_text() if len(data) > 4 else "Name" insider = data[6].get_text() if len(data) > 6 else "Position of trader" trade_type = data[7].get_text() if len(data) > 7 else "Buy or sell" value = data[12].get_text() if len(data) > 12 else "Monetary value" # Print the extracted data print(f'Ticker : {ticker} | Company: {company} | Title: {insider} | Trade Type: {trade_type} | Value: {value}') with open('TopInsiderMonth.txt', 'w') as f: f.write(f'Ticker : {ticker} | Company: {company} | Title: {insider} | Trade Type: {trade_type} | Value: {value}') My print function is giving me the results I want but when I try to write it I only write one line of the information instead of the 100 lines I am looking for. Any ideas? A: Open file then the for loop and added \n for new line: from bs4 import BeautifulSoup import requests page = requests.get("http://openinsider.com/top-insider-purchases-of-the-month") '''print(page.status_code) checks to see if the page was downloaded successfully''' soup = BeautifulSoup(page.content,'html.parser') # Find the table with the insider purchase data table = soup.find(class_="tinytable") # Find all rows of the table rows = table.find_all('tr') with open('TopInsiderMonth.txt', 'w') as f: # Loop through each row for row in rows: # Extract the company name, insider name, and trade type from the row data = row.find_all("td") ticker = data[3].get_text() if len(data) > 3 else "Ticker representing the company" company = data[4].get_text() if len(data) > 4 else "Name" insider = data[6].get_text() if len(data) > 6 else "Position of trader" trade_type = data[7].get_text() if len(data) > 7 else "Buy or sell" value = data[12].get_text() if len(data) > 12 else "Monetary value" # Print the extracted data print(f'Ticker : {ticker} | Company: {company} | Title: {insider} | Trade Type: {trade_type} | Value: {value}') f.write( f'Ticker : {ticker} | Company: {company} | Title: {insider} | Trade Type: {trade_type} | Value: {value}\n')
How do I write all my BeautifulSoup data from a website to a text file? Python
I am trying to read data from open insider and put it into an easy to read text file. Here is my code so far: from bs4 import BeautifulSoup import requests page = requests.get("http://openinsider.com/top-insider-purchases-of-the-month") '''print(page.status_code) checks to see if the page was downloaded successfully''' soup = BeautifulSoup(page.content,'html.parser') # Find the table with the insider purchase data table = soup.find(class_="tinytable") # Find all rows of the table rows = table.find_all('tr') # Loop through each row for row in rows: # Extract the company name, insider name, and trade type from the row data = row.find_all("td") ticker = data[3].get_text() if len(data) > 3 else "Ticker representing the company" company = data[4].get_text() if len(data) > 4 else "Name" insider = data[6].get_text() if len(data) > 6 else "Position of trader" trade_type = data[7].get_text() if len(data) > 7 else "Buy or sell" value = data[12].get_text() if len(data) > 12 else "Monetary value" # Print the extracted data print(f'Ticker : {ticker} | Company: {company} | Title: {insider} | Trade Type: {trade_type} | Value: {value}') with open('TopInsiderMonth.txt', 'w') as f: f.write(f'Ticker : {ticker} | Company: {company} | Title: {insider} | Trade Type: {trade_type} | Value: {value}') My print function is giving me the results I want but when I try to write it I only write one line of the information instead of the 100 lines I am looking for. Any ideas?
[ "Open file then the for loop and added \\n for new line:\nfrom bs4 import BeautifulSoup\nimport requests\n\npage = requests.get(\"http://openinsider.com/top-insider-purchases-of-the-month\")\n\n'''print(page.status_code)\nchecks to see if the page was downloaded successfully'''\n\nsoup = BeautifulSoup(page.content,'html.parser')\n\n# Find the table with the insider purchase data\ntable = soup.find(class_=\"tinytable\")\n\n# Find all rows of the table\nrows = table.find_all('tr')\n\nwith open('TopInsiderMonth.txt', 'w') as f:\n \n # Loop through each row\n for row in rows:\n # Extract the company name, insider name, and trade type from the row\n data = row.find_all(\"td\")\n ticker = data[3].get_text() if len(data) > 3 else \"Ticker representing the company\"\n company = data[4].get_text() if len(data) > 4 else \"Name\"\n insider = data[6].get_text() if len(data) > 6 else \"Position of trader\"\n trade_type = data[7].get_text() if len(data) > 7 else \"Buy or sell\"\n value = data[12].get_text() if len(data) > 12 else \"Monetary value\"\n # Print the extracted data\n print(f'Ticker : {ticker} | Company: {company} | Title: {insider} | Trade Type: {trade_type} | Value: {value}')\n\n f.write(\n f'Ticker : {ticker} | Company: {company} | Title: {insider} | Trade Type: {trade_type} | Value: {value}\\n')\n\n" ]
[ 1 ]
[]
[]
[ "beautifulsoup", "python", "txt" ]
stackoverflow_0074663991_beautifulsoup_python_txt.txt
Q: Java - read structured binary file I'm new to Java and a I need to read a binary file and display its contents converted as integers. The file has this structure: {client#, position 1, size 32 | category, position 33, size 10 | type, position 43, size 10 | creditlimit, position 53, size 20} I need just a guide on what classes to use and a convertion example, a little snipet will be appreciated. A: I assume that position 1 actually is 0; the first byte. Also it seems the file format is of fixed size records, probably with ASCII in the bytes. To check the data, I start with taking the fields in Strings. Converting them to long/int could loose information on the actual content. The following uses a sequential binary file. Faster would be a memory mapped file, but this is acceptable and short. Hold the client data: class Client { String clientno; String category; String type; String position; String creditlimit; @Override public String toString() { return String.format("Client# %s, categ %s, type %s, pos %s, creditlimit %s%n", clientno, category, type, position, creditlimit); } } Read the file: // Field sizes: final int CLIENT_NO = 32; final int CATEGORY = 10; final int TYPE = 10; final int CREDIT_LIMIT = 20; final int RECORD_SIZE = CLIENT_NO + CATEGORY + TYPE + CREDIT_LIMIT; byte[] record = new byte[RECORD_SIZE]; try (BufferedInputStream in = new BufferedInputStream( new FileInputStream(file))) { for (;;) { int nread = in.read(record); if (nread < RECORD_SIZE) { break; } Client client = new Client(); int offset = 0; int offset2 = offset + CLIENT_NO; client.clientno = recordField(record, offset, offset2 - offset); offset = offset2; int offset2 = offset + CATEGORY; client.category = recordField(record, offset, offset2 - offset); offset = offset2; int offset2 = offset + TYPE; client.type = recordField(record, offset, offset2 - offset); offset = offset2; int offset2 = offset + CREDITLIMIT; client.creditlimit = recordField(record, offset, offset2 - offset); System.out.println(client); } } // Closes in. with a field extraction: private static String recordField(byte[] record, int offset, int length) { String field = new String(record, offset, length, StandardCharsets.ISO_8859_1); // Use ASCII NUL as string terminator: int pos = field.indexOf('\u0000'); if (pos != -1) { field = field.substring(0, pos); } return field.trim(); // Trim also spaces for fixed fields. } A: If i understand your question correct, you should use the NIO Package. With the asIntBuffer() from the byteBuffer class, you can get an IntBuffer view of a ByteBuffer. And by calling get(int[] dst) you could convert it to integers. The initial ByteBuffer is available by using file channels. A: If you work with binary data, may be JBBP will be comfortable way for you, to parse and print the data structure with the framework is very easy (if I understood the task correctly and you work with byte fields), the example parsing whole input stream and then print parsed data to console @Bin class Record {byte [] client; byte [] category; byte [] type; byte [] creditlimit;}; @Bin class Records {Record [] records;}; Records parsed = JBBPParser.prepare("records [_] {byte [32] client; byte [10] category; byte [10] type; byte [20] creditlimit;}").parse(THE_INPUT_STREAM).mapTo(Records.class); System.out.println(new JBBPTextWriter().Bin(parsed).toString());
Java - read structured binary file
I'm new to Java and a I need to read a binary file and display its contents converted as integers. The file has this structure: {client#, position 1, size 32 | category, position 33, size 10 | type, position 43, size 10 | creditlimit, position 53, size 20} I need just a guide on what classes to use and a convertion example, a little snipet will be appreciated.
[ "I assume that position 1 actually is 0; the first byte.\nAlso it seems the file format is of fixed size records, probably with ASCII in the bytes.\nTo check the data, I start with taking the fields in Strings. Converting them to long/int could loose information on the actual content.\nThe following uses a sequential binary file. Faster would be a memory mapped file, but this is acceptable and short.\nHold the client data:\nclass Client {\n String clientno;\n String category; \n String type;\n String position;\n String creditlimit;\n\n @Override\n public String toString() {\n return String.format(\"Client# %s, categ %s, type %s, pos %s, creditlimit %s%n\",\n clientno, category, type, position, creditlimit);\n }\n}\n\nRead the file:\n// Field sizes:\nfinal int CLIENT_NO = 32;\nfinal int CATEGORY = 10;\nfinal int TYPE = 10;\nfinal int CREDIT_LIMIT = 20;\nfinal int RECORD_SIZE = CLIENT_NO + CATEGORY + TYPE + CREDIT_LIMIT;\n\nbyte[] record = new byte[RECORD_SIZE];\ntry (BufferedInputStream in = new BufferedInputStream(\n new FileInputStream(file))) {\n\n for (;;) {\n int nread = in.read(record);\n if (nread < RECORD_SIZE) {\n break;\n }\n Client client = new Client();\n int offset = 0;\n int offset2 = offset + CLIENT_NO;\n client.clientno = recordField(record, offset, offset2 - offset);\n offset = offset2;\n int offset2 = offset + CATEGORY;\n client.category = recordField(record, offset, offset2 - offset);\n offset = offset2;\n int offset2 = offset + TYPE;\n client.type = recordField(record, offset, offset2 - offset);\n offset = offset2;\n int offset2 = offset + CREDITLIMIT;\n client.creditlimit = recordField(record, offset, offset2 - offset);\n\n System.out.println(client);\n }\n\n} // Closes in.\n\nwith a field extraction:\nprivate static String recordField(byte[] record, int offset, int length) {\n String field = new String(record, offset, length, StandardCharsets.ISO_8859_1);\n\n // Use ASCII NUL as string terminator:\n int pos = field.indexOf('\\u0000');\n if (pos != -1) {\n field = field.substring(0, pos);\n }\n\n return field.trim(); // Trim also spaces for fixed fields.\n}\n\n", "If i understand your question correct, you should use the NIO Package.\nWith the asIntBuffer() from the byteBuffer class, you can get an IntBuffer view of a ByteBuffer. And by calling get(int[] dst) you could convert it to integers. \nThe initial ByteBuffer is available by using file channels.\n", "If you work with binary data, may be JBBP will be comfortable way for you, to parse and print the data structure with the framework is very easy (if I understood the task correctly and you work with byte fields), the example parsing whole input stream and then print parsed data to console\n@Bin class Record {byte [] client; byte [] category; byte [] type; byte [] creditlimit;};\n@Bin class Records {Record [] records;};\nRecords parsed = JBBPParser.prepare(\"records [_] {byte [32] client; byte [10] category; byte [10] type; byte [20] creditlimit;}\").parse(THE_INPUT_STREAM).mapTo(Records.class);\nSystem.out.println(new JBBPTextWriter().Bin(parsed).toString());\n\n" ]
[ 2, 1, 1 ]
[ "Recommend you a java tool(FastProto) to parse binary quickly.\nimport org.indunet.fastproto.annotation.*;\n\npublic class File {\n @StringType(offset = 1, length = 32)\n String client;\n \n @Int32Type(offset = 33, length = 10)\n String category;\n\n @StringType(offset = 43, length = 10)\n String type;\n\n @StringType(offset = 53, length = 20)\n String creditLimit;\n}\n\n\nbyte[] bytes = ... // the binary file\nFile file = FastProto.parse(bytes, File.class);\n\n\nIf the project can solve your problem, please give a star, thanks.\nGitHub Repo: https://github.com/indunet/fastproto\n" ]
[ -1 ]
[ "java" ]
stackoverflow_0027041141_java.txt
Q: Is there a way to transform a list of tuples into a dictionary in python? I am doing an assignment in which I need to open a raw mailing list, saved in a CSV file, filter the users that have been unsubscribed, and print back the resulting mailing list to another CSV file. To do so, I first need to create tuples with each row in the original list, and then transform the tuples into a dictionary. Can I have some help filling out the blank parts of this code? mailing_list.csv: uuid,username,email,subscribe_status 307919e9-d6f0-4ecf-9bef-c1320db8941a,afarrimond0,[email protected],opt-out 8743d75d-c62a-4bae-8990-3390fefbe5c7,tdelicate1,[email protected],opt-out 68a32cae-847a-47c5-a77c-0d14ccf11e70,edelahuntyk,[email protected],OPT-OUT a50bd76f-bc4d-4141-9b5d-3bfb9cb4c65d,tdelicate10,[email protected],active 26edd0b3-0040-4ba9-8c19-9b69d565df36,ogelder2,[email protected],unsubscribed 5c96189f-95fe-4638-9753-081a6e1a82e8,bnornable3,[email protected],opt-out 480fb04a-d7cd-47c5-8079-b580cb14b4d9,csheraton4,[email protected],active d08649ee-62ae-4d1a-b578-fdde309bb721,tstodart5,[email protected],active 5772c293-c2a9-41ff-a8d3-6c666fc19d9a,mbaudino6,[email protected],unsubscribed 9e8fb253-d80d-47b5-8e1d-9a89b5bcc41b,paspling7,[email protected],active 055dff79-7d09-4194-95f2-48dd586b8bd7,mknapton8,[email protected],active 5216dc65-05bb-4aba-a516-3c1317091471,ajelf9,[email protected],unsubscribed 41c30786-aa84-4d60-9879-0c53f8fad970,cgoodleyh,[email protected],active 3fd55224-dbff-4c89-baec-629a3442d8f7,smcgonnelli,[email protected],opt-out 2ac17a63-a64b-42fc-8780-02c5549f23a7,mmayoralj,[email protected],unsubscribed import csv base_url = '../dataset/' def read_mailing_list_file(): with open('mailing_list.csv', 'r') as csv_file: hdr = csv.Sniffer().has_header(csv_file.read()) csv_file.seek(0) file_reader = csv.reader(csv_file) line_count = 0 mailing_list = [] if hdr: next(file_reader) for row in file_reader: mailing_list.append(row) line_count += 1 mailing_list_buffer = # Create another list variable that will be used as a temporary buffer to transform # our previous list into a dictionary, which is the data structure expected from the `update_mailing_list_extended` # function # Looping through the mailing list object for item in mailing_list: # Creating tuples with each row in the original list mailing_dict = # Transforming the list of tuples into a python dictionary I am trying to transform a list of tuples into a dictionary. A: This seems like an XY problem - you are trying to solve problem X (filter csv) with solution Y (a dictionary) when there is a better way to solve X. Going from the description of your problem, there is no need for a dictionary. You can filter the CSV row by row and write directly to the new file. with open("mailing_list.csv") as infile: with open("mailing_list_filtered.csv", "w") as outfile: csv.writer(outfile).writerows(row for row in csv.reader(infile) if row[0] != "unsubscribed")
Is there a way to transform a list of tuples into a dictionary in python?
I am doing an assignment in which I need to open a raw mailing list, saved in a CSV file, filter the users that have been unsubscribed, and print back the resulting mailing list to another CSV file. To do so, I first need to create tuples with each row in the original list, and then transform the tuples into a dictionary. Can I have some help filling out the blank parts of this code? mailing_list.csv: uuid,username,email,subscribe_status 307919e9-d6f0-4ecf-9bef-c1320db8941a,afarrimond0,[email protected],opt-out 8743d75d-c62a-4bae-8990-3390fefbe5c7,tdelicate1,[email protected],opt-out 68a32cae-847a-47c5-a77c-0d14ccf11e70,edelahuntyk,[email protected],OPT-OUT a50bd76f-bc4d-4141-9b5d-3bfb9cb4c65d,tdelicate10,[email protected],active 26edd0b3-0040-4ba9-8c19-9b69d565df36,ogelder2,[email protected],unsubscribed 5c96189f-95fe-4638-9753-081a6e1a82e8,bnornable3,[email protected],opt-out 480fb04a-d7cd-47c5-8079-b580cb14b4d9,csheraton4,[email protected],active d08649ee-62ae-4d1a-b578-fdde309bb721,tstodart5,[email protected],active 5772c293-c2a9-41ff-a8d3-6c666fc19d9a,mbaudino6,[email protected],unsubscribed 9e8fb253-d80d-47b5-8e1d-9a89b5bcc41b,paspling7,[email protected],active 055dff79-7d09-4194-95f2-48dd586b8bd7,mknapton8,[email protected],active 5216dc65-05bb-4aba-a516-3c1317091471,ajelf9,[email protected],unsubscribed 41c30786-aa84-4d60-9879-0c53f8fad970,cgoodleyh,[email protected],active 3fd55224-dbff-4c89-baec-629a3442d8f7,smcgonnelli,[email protected],opt-out 2ac17a63-a64b-42fc-8780-02c5549f23a7,mmayoralj,[email protected],unsubscribed import csv base_url = '../dataset/' def read_mailing_list_file(): with open('mailing_list.csv', 'r') as csv_file: hdr = csv.Sniffer().has_header(csv_file.read()) csv_file.seek(0) file_reader = csv.reader(csv_file) line_count = 0 mailing_list = [] if hdr: next(file_reader) for row in file_reader: mailing_list.append(row) line_count += 1 mailing_list_buffer = # Create another list variable that will be used as a temporary buffer to transform # our previous list into a dictionary, which is the data structure expected from the `update_mailing_list_extended` # function # Looping through the mailing list object for item in mailing_list: # Creating tuples with each row in the original list mailing_dict = # Transforming the list of tuples into a python dictionary I am trying to transform a list of tuples into a dictionary.
[ "This seems like an XY problem - you are trying to solve problem X (filter csv) with solution Y (a dictionary) when there is a better way to solve X.\nGoing from the description of your problem, there is no need for a dictionary. You can filter the CSV row by row and write directly to the new file.\nwith open(\"mailing_list.csv\") as infile:\n with open(\"mailing_list_filtered.csv\", \"w\") as outfile:\n csv.writer(outfile).writerows(row for row in csv.reader(infile)\n if row[0] != \"unsubscribed\")\n\n" ]
[ 0 ]
[ "you can try to use dict class , such as my_dict = dict(tuple_list)\n" ]
[ -1 ]
[ "csv", "dictionary", "python", "tuples" ]
stackoverflow_0074663927_csv_dictionary_python_tuples.txt
Q: How can I get N distinct spectrum-like colors in Qt with starting color RED and ending color BLUE Initially, I thought it can be easily implemented using a single for-loop with pre-calculated step size. // blue = (240, 255, 255) // red = (0, 255, 255) const int step = (240 - 0) / (N - 1); QColor color; for (int i = 0; i < N; ++i) { color.setHsv(i * step, 255, 255); } But as N grows larger, the ending color may not be what I expected. For example (N == 82), ending color is hsv(162, 255, 255) instead of hsv(240, 255, 255). My intention is to 1) generate N distinct color, 2) spectrum-like, 3) starts in RED and ends in BLUE. Should I take S, V into consideration for my requirement as well? A: Right now, you're choosing an integer step, and adding it to get from the smallest to the largest value. This has the advantage of spacing the hues evenly. But as you've observed, it has the disadvantage of getting the range wrong (possibly quite badly wrong) at times. If you're willing to sacrifice a little in the way of the spacing of hues being perfectly even to get closer to filling the specified range, you can compute the step as a floating point number, do floating point multiplication, and round (or truncate) afterwards. std::vector<int> interpolate_range(int lower, int upper, int step_count) { double step = (upper - lower) / (step_count - 1.0); std::vector<int> ret; for (int i=0; i<step_count; i++) { // step is a double, so `double * i` is done in floating // point, then the result is truncated to be pushed into // ret. ret.push_back(step * i); } return ret; } Skipping the other color components, and just printing out these values, we get this: 0 2 5 8 11 14 17 20 23 26 29 32 35 38 41 44 47 50 53 56 59 62 65 68 71 74 77 80 82 85 88 91 94 97 100 103 106 109 112 115 118 121 124 127 130 133 136 139 142 145 148 151 154 157 160 162 165 168 171 174 177 180 183 186 189 192 195 198 201 204 207 210 213 216 219 222 225 228 231 234 237 240 As you can see, we usually get a separation of 3, but a few times (0 to 2, 80 to 82 and 160 to 162) only 2, allowing us to fill the entire range.
How can I get N distinct spectrum-like colors in Qt with starting color RED and ending color BLUE
Initially, I thought it can be easily implemented using a single for-loop with pre-calculated step size. // blue = (240, 255, 255) // red = (0, 255, 255) const int step = (240 - 0) / (N - 1); QColor color; for (int i = 0; i < N; ++i) { color.setHsv(i * step, 255, 255); } But as N grows larger, the ending color may not be what I expected. For example (N == 82), ending color is hsv(162, 255, 255) instead of hsv(240, 255, 255). My intention is to 1) generate N distinct color, 2) spectrum-like, 3) starts in RED and ends in BLUE. Should I take S, V into consideration for my requirement as well?
[ "Right now, you're choosing an integer step, and adding it to get from the smallest to the largest value. This has the advantage of spacing the hues evenly. But as you've observed, it has the disadvantage of getting the range wrong (possibly quite badly wrong) at times.\nIf you're willing to sacrifice a little in the way of the spacing of hues being perfectly even to get closer to filling the specified range, you can compute the step as a floating point number, do floating point multiplication, and round (or truncate) afterwards.\nstd::vector<int> interpolate_range(int lower, int upper, int step_count) { \n double step = (upper - lower) / (step_count - 1.0);\n\n std::vector<int> ret;\n for (int i=0; i<step_count; i++) {\n // step is a double, so `double * i` is done in floating\n // point, then the result is truncated to be pushed into\n // ret.\n ret.push_back(step * i);\n }\n return ret;\n}\n\nSkipping the other color components, and just printing out these values, we get this:\n0 2 5 8 11 14 17 20 23 26 \n\n29 32 35 38 41 44 47 50 53 56 \n\n59 62 65 68 71 74 77 80 82 85 \n\n88 91 94 97 100 103 106 109 112 115 \n\n118 121 124 127 130 133 136 139 142 145 \n\n148 151 154 157 160 162 165 168 171 174 \n\n177 180 183 186 189 192 195 198 201 204 \n\n207 210 213 216 219 222 225 228 231 234 \n\n237 240 \n\n\nAs you can see, we usually get a separation of 3, but a few times (0 to 2, 80 to 82 and 160 to 162) only 2, allowing us to fill the entire range.\n" ]
[ 0 ]
[]
[]
[ "c++", "colors", "gradient", "qt", "spectrum" ]
stackoverflow_0074663888_c++_colors_gradient_qt_spectrum.txt
Q: how to get notified about changes in firestore using firebase admin sdk i am makin a chating app and the user needs to be notified wheneer new notification comes. so i am using firebase admin sdk onSnapshot function. but the problem is how can i listen to changes deep inside the multiple collection and documents. i wanted to do this const admin = require("firebase-admin"); const firebaseAdminKey = require("./firebase-admin-key.json"); admin.initializeApp({ credential: admin.credential.cert(firebaseAdminKey), databaseURL: `https://${firebaseAdminKey.project_id}.firebaseio.com`, }); let firestore = admin.firestore(); let messeging = admin.messaging(); let storage = admin.storage(); console.log("Firebase Admin Initialized"); firestore .collection("users") .doc("{userID}") .collection("chats") .doc("{senderID}") .collection("messages") .onSnapshot((snapshot) => { console.log("New Message ", snapshot.docs); snapshot.docChanges().forEach((change) => { console.log("New message: ", change.doc.data()); }); }); But i doesn't work in admin sdk NOTE:- I AMM NOT DEPLOYING THIS API TO FIREBASE CLOUD SO I CAN NOT USE FIREBASE FUNCTIONS this is what i was expecting but it works just between one user and sender. const admin = require("firebase-admin"); const firebaseAdminKey = require("./firebase-admin-key.json"); admin.initializeApp({ credential: admin.credential.cert(firebaseAdminKey), databaseURL: `https://${firebaseAdminKey.project_id}.firebaseio.com`, }); let firestore = admin.firestore(); let messeging = admin.messaging(); let storage = admin.storage(); console.log("Firebase Admin Initialized"); firestore .collection("users") .doc("Zcpq0NHMODTGMT2Qry53ylksmvp2") .collection("chats") .doc("m79kGeXHKPNEgteCqxn2RG4eytL2") .collection("messages") .onSnapshot((snapshot) => { console.log("New Message ", snapshot.docs); snapshot.docChanges().forEach((change) => { console.log("New message: ", change.doc.data()); }); }); every user hase multiple friends i.e sender so how can i do it theres one way ican think of i.e itrating over every user and sender but it will be very costly for my api as it could have time complexity of O(nk) where k is average number of friends of each user. A: With the SDKs for Firestore there's only two ways to listen to a collection or query: To a single collection with firestore.collection('exact/path/to/the/collection').onSnapshot. To a collection group, which listens to all collections with a certain name, with firestore.collectionGroup('collectionName').onSnapshot. In both cases you can then use a query to limit the results, and in the case of collection group queries you can tweak this to listen to a specific path, as shown in this answer to: CollectionGroupQuery but limit search to subcollections under a particular document Beyond that there is no way to listen to a path structure similar to what Cloud Functions allows.
how to get notified about changes in firestore using firebase admin sdk
i am makin a chating app and the user needs to be notified wheneer new notification comes. so i am using firebase admin sdk onSnapshot function. but the problem is how can i listen to changes deep inside the multiple collection and documents. i wanted to do this const admin = require("firebase-admin"); const firebaseAdminKey = require("./firebase-admin-key.json"); admin.initializeApp({ credential: admin.credential.cert(firebaseAdminKey), databaseURL: `https://${firebaseAdminKey.project_id}.firebaseio.com`, }); let firestore = admin.firestore(); let messeging = admin.messaging(); let storage = admin.storage(); console.log("Firebase Admin Initialized"); firestore .collection("users") .doc("{userID}") .collection("chats") .doc("{senderID}") .collection("messages") .onSnapshot((snapshot) => { console.log("New Message ", snapshot.docs); snapshot.docChanges().forEach((change) => { console.log("New message: ", change.doc.data()); }); }); But i doesn't work in admin sdk NOTE:- I AMM NOT DEPLOYING THIS API TO FIREBASE CLOUD SO I CAN NOT USE FIREBASE FUNCTIONS this is what i was expecting but it works just between one user and sender. const admin = require("firebase-admin"); const firebaseAdminKey = require("./firebase-admin-key.json"); admin.initializeApp({ credential: admin.credential.cert(firebaseAdminKey), databaseURL: `https://${firebaseAdminKey.project_id}.firebaseio.com`, }); let firestore = admin.firestore(); let messeging = admin.messaging(); let storage = admin.storage(); console.log("Firebase Admin Initialized"); firestore .collection("users") .doc("Zcpq0NHMODTGMT2Qry53ylksmvp2") .collection("chats") .doc("m79kGeXHKPNEgteCqxn2RG4eytL2") .collection("messages") .onSnapshot((snapshot) => { console.log("New Message ", snapshot.docs); snapshot.docChanges().forEach((change) => { console.log("New message: ", change.doc.data()); }); }); every user hase multiple friends i.e sender so how can i do it theres one way ican think of i.e itrating over every user and sender but it will be very costly for my api as it could have time complexity of O(nk) where k is average number of friends of each user.
[ "With the SDKs for Firestore there's only two ways to listen to a collection or query:\n\nTo a single collection with firestore.collection('exact/path/to/the/collection').onSnapshot.\nTo a collection group, which listens to all collections with a certain name, with firestore.collectionGroup('collectionName').onSnapshot.\n\nIn both cases you can then use a query to limit the results, and in the case of collection group queries you can tweak this to listen to a specific path, as shown in this answer to: CollectionGroupQuery but limit search to subcollections under a particular document\nBeyond that there is no way to listen to a path structure similar to what Cloud Functions allows.\n" ]
[ 0 ]
[]
[]
[ "firebase", "firebase_admin", "google_cloud_firestore", "javascript" ]
stackoverflow_0074663876_firebase_firebase_admin_google_cloud_firestore_javascript.txt
Q: How stop multiple projects in vscode with the launch.json I have in my launch.JSON a configuration that allows me to start two different API projects at the same time (Web API One and Web API Two), both are components of the same project, everything works fine on start, but if I need to stop the APIs I need to stop each of them individually, theirs a way to create a config file to stop both projects at the same time? Observation: I use only two projects in this code example, but in reality, I have six APIs and other projects like services and front-end projects. Most C# projects, Windows Services and Web APIs, but I want to include JavaScript front-end projects in the future. My launch.JSON: // Components for start menu in vscode debug mode { "version": "0.2.0", "compounds": [ { "name": "Web API", "configurations": [ "Web API One", "Web API Two" ] } ], // Configuration of each project "configurations": [ { "name": "Web API One", "type": "coreclr", "request": "launch", "preLaunchTask": "buildWEBAPI", "program": "${workspaceFolder}/WEBAPI/PATH", "args": [ "--force" ], "cwd": "${workspaceFolder}/01.Application/WEBAPI", "stopAtEntry": false, "env": { "ASPNETCORE_ENVIRONMENT": "Development" } }, { "name": "Web API Two", "type": "coreclr", "request": "launch", "preLaunchTask": "buildWEBAPI", "program": "${workspaceFolder}/WEBAPI/PATH", "args": [ "--force" ], "cwd": "${workspaceFolder}/01.Application//WEBAPI/", "stopAtEntry": false, "env": { "ASPNETCORE_ENVIRONMENT": "Development" } } ] } A: I will answer my own question because I found a solution. Based on my search, this approach using .json config file is not possible, but an alternative is to click "shift + F5" on a call stack tab in vscode when the project is running and held until all projects has been stopped
How stop multiple projects in vscode with the launch.json
I have in my launch.JSON a configuration that allows me to start two different API projects at the same time (Web API One and Web API Two), both are components of the same project, everything works fine on start, but if I need to stop the APIs I need to stop each of them individually, theirs a way to create a config file to stop both projects at the same time? Observation: I use only two projects in this code example, but in reality, I have six APIs and other projects like services and front-end projects. Most C# projects, Windows Services and Web APIs, but I want to include JavaScript front-end projects in the future. My launch.JSON: // Components for start menu in vscode debug mode { "version": "0.2.0", "compounds": [ { "name": "Web API", "configurations": [ "Web API One", "Web API Two" ] } ], // Configuration of each project "configurations": [ { "name": "Web API One", "type": "coreclr", "request": "launch", "preLaunchTask": "buildWEBAPI", "program": "${workspaceFolder}/WEBAPI/PATH", "args": [ "--force" ], "cwd": "${workspaceFolder}/01.Application/WEBAPI", "stopAtEntry": false, "env": { "ASPNETCORE_ENVIRONMENT": "Development" } }, { "name": "Web API Two", "type": "coreclr", "request": "launch", "preLaunchTask": "buildWEBAPI", "program": "${workspaceFolder}/WEBAPI/PATH", "args": [ "--force" ], "cwd": "${workspaceFolder}/01.Application//WEBAPI/", "stopAtEntry": false, "env": { "ASPNETCORE_ENVIRONMENT": "Development" } } ] }
[ "I will answer my own question because I found a solution. Based on my search, this approach using .json config file is not possible, but an alternative is to click \"shift + F5\" on a call stack tab in vscode when the project is running and held until all projects has been stopped\n" ]
[ 0 ]
[]
[]
[ "c#", "configuration_files", "javascript", "json", "visual_studio_code" ]
stackoverflow_0071670048_c#_configuration_files_javascript_json_visual_studio_code.txt
Q: rich.table prints unicode when I want ascii I am trying to print MAC address using python rich library. Below is code. The ":cd" in the MAC address get converted to an actual CD disk emoji. How to prevent that from happening? from rich.console import Console from rich.table import Table table = Table(safe_box=True) table.add_column("MAC address") table.add_row("08:00:27:cd:af:88") console = Console() console.print(table) Output: ┏━━━━━━━━━━━━━━━━━┓ ┃ MAC address ┃ ┡━━━━━━━━━━━━━━━━━┩ │ 08:00:27af:88 │ └─────────────────┘ I tried using safe_box=True option to not print Unicode but that did not work. I want the final output to look like ┏━━━━━━━━━━━━━--━━━━┓ ┃ MAC address ┃ ┡━━━━━━━━━━━━━━━--━━┩ │ 08:00:27:cd:af:88 │ └───────────--──────┘ A: The documentation describes this. You use backslash to escape characters that would otherwise be recognized. table.add_row("08:00:27\\:cd:af:88") If you have a string, do s = s.replace(':cd','\\:cd') https://rich.readthedocs.io/en/stable/markup.html FOLLOWUP I looked at the full emoji list in the source code. There are two possible paths. First, they look for the Unicode "zero-width joiner" as a way to interrupt the emoji search. So, you could do: s = s.replace(':cd',':\u200dcd') Second, "cd" is, in fact, the only two-letter emoji code in their list that is also a hex number. So, you can add this at the top, and this also works: from rich._emoji_codes import EMOJI del EMOJI["cd"] I've tested both of these. What a very strange problem.
rich.table prints unicode when I want ascii
I am trying to print MAC address using python rich library. Below is code. The ":cd" in the MAC address get converted to an actual CD disk emoji. How to prevent that from happening? from rich.console import Console from rich.table import Table table = Table(safe_box=True) table.add_column("MAC address") table.add_row("08:00:27:cd:af:88") console = Console() console.print(table) Output: ┏━━━━━━━━━━━━━━━━━┓ ┃ MAC address ┃ ┡━━━━━━━━━━━━━━━━━┩ │ 08:00:27af:88 │ └─────────────────┘ I tried using safe_box=True option to not print Unicode but that did not work. I want the final output to look like ┏━━━━━━━━━━━━━--━━━━┓ ┃ MAC address ┃ ┡━━━━━━━━━━━━━━━--━━┩ │ 08:00:27:cd:af:88 │ └───────────--──────┘
[ "The documentation describes this. You use backslash to escape characters that would otherwise be recognized.\ntable.add_row(\"08:00:27\\\\:cd:af:88\")\n\nIf you have a string, do\ns = s.replace(':cd','\\\\:cd')\n\nhttps://rich.readthedocs.io/en/stable/markup.html\nFOLLOWUP\nI looked at the full emoji list in the source code. There are two possible paths.\nFirst, they look for the Unicode \"zero-width joiner\" as a way to interrupt the emoji search. So, you could do:\ns = s.replace(':cd',':\\u200dcd')\n\nSecond, \"cd\" is, in fact, the only two-letter emoji code in their list that is also a hex number. So, you can add this at the top, and this also works:\nfrom rich._emoji_codes import EMOJI\ndel EMOJI[\"cd\"]\n\nI've tested both of these. What a very strange problem.\n" ]
[ 0 ]
[]
[]
[ "python", "rich" ]
stackoverflow_0074663714_python_rich.txt
Q: How to get rid of python in VS Code's sidebar? I tried python and didn't like it, but under the "Explorer" sidebar in VS Code, it still has a python section. I tried deleting the python extensions, reloading VS Code and looking in settings. It's possible I missed it in settings.
How to get rid of python in VS Code's sidebar?
I tried python and didn't like it, but under the "Explorer" sidebar in VS Code, it still has a python section. I tried deleting the python extensions, reloading VS Code and looking in settings. It's possible I missed it in settings.
[]
[]
[ "Holy Sh*t i am stupid. My folder containing the code was Named \"Python.\" sorry y'all\n" ]
[ -2 ]
[ "c#", "python", "visual_studio_code" ]
stackoverflow_0074664012_c#_python_visual_studio_code.txt
Q: Kafka Connectors would not spin up using docker alpine_container and Kafka S3 version 10.3.0 I tried to update my Docker container file using Alpine_container from alpine itself. However when I tried this technique none of my Kafka connectors were starting. The error message said that it failed to connect and find port 8083. I also tried to update my S3 Bucket version to 10.3.0 as the latest version based on the Kafka documentation however that also failed to connect to port 8083. My secrets and bootstrap servers+schema registry is working and the pod is working but failed to connect to port 8083 to start the connectors. Here is my docker file. Any clue or suggestion why using alpine_container and version 10.3.0 failed FROM alpine AS alpine_container WORKDIR / EXPOSE 9999 RUN apk add bash curl unzip \ # Download Kafka Connect && mkdir /kafka_connect \ && curl https://archive.apache.org/dist/kafka/3.1.1/kafka_2.13-3.1.1.tgz \ | tar xz --strip-components=1 -C /kafka_connect \ # Download the Confluent Kafka Connect JDBC Connector, a plugin for Kafka Connect && mkdir /kafka_jdbc_connector \ && curl https://d1i4a15mxbxib1.cloudfront.net/api/plugins/confluentinc/kafka-connect-jdbc/versions/10.6.0/confluentinc-kafka-connect-jdbc-10.6.0.zip -o kafka_connect_jdbc_connector.zip \ && unzip kafka_connect_jdbc_connector.zip -d /kafka_connect_jdbc_connector \ # Download the Confluent Kafka Connect Avro Converter, a plugin for Kafka Connect && mkdir /kafka_avro_converter \ && curl https://d1i4a15mxbxib1.cloudfront.net/api/plugins/confluentinc/kafka-connect-avro-converter/versions/7.1.4/confluentinc-kafka-connect-avro-converter-7.1.4.zip -o kafka_connect_avro_converter.zip \ && unzip kafka_connect_avro_converter.zip -d /kafka_connect_avro_converter \ && mkdir /kafka_connect_s3 \ && curl https://d1i4a15mxbxib1.cloudfront.net/api/plugins/confluentinc/kafka-connect-s3/versions/10.3.0/confluentinc-kafka-connect-s3-10.3.0.zip -o kafka_connect_s3.zip \ && unzip kafka_connect_s3.zip -d /kafka_connect_s3 FROM openjdk:11-slim RUN apt-get update \ && apt-get install -y \ procps \ dnsutils \ curl \ jq \ netcat \ net-tools \ && apt-get clean COPY --from=alpine_container /kafka_connect /kafka_connect COPY --from=alpine_container /kafka_connect_jdbc_connector/* /kafka_connect_jdbc_connector COPY --from=alpine_container /kafka_connect_avro_converter/* /kafka_connect_avro_converter COPY --from=alpine_container /kafka_connect_s3/* /kafka_connect_s3 COPY ./kafka_connect/. /kafka_connect/ COPY ./s3-connector.sh /kafka_connect/ ENV CLASSPATH /kafka_connect_jdbc_connector/lib/*:/kafka_connect_avro_converter/lib/*:/kafka_connect_s3/lib/* WORKDIR /kafka_connect A: Version doesn't matter. You're starting from plain Java image. That doesn't automatically run any server. I suggest you start FROM confluentinc/cp-kafka-connect-base. Otherwise, you must add CMD /kafka_connect/bin/connect-distributed.sh /kafka_connect/config/connect-distributed.properties. Note, your base folder here is all Kafka not only "kafka connect", so naming should probably be fixed There's also no reason I see for using Alpine. You can install confluent-hub CLI and use that instead of curl and unzip and needing to COPY and set CLASSPATH... Example https://github.com/OneCricketeer/apache-kafka-connect-docker/blob/schema-registry/Dockerfile.schema-registry#L5
Kafka Connectors would not spin up using docker alpine_container and Kafka S3 version 10.3.0
I tried to update my Docker container file using Alpine_container from alpine itself. However when I tried this technique none of my Kafka connectors were starting. The error message said that it failed to connect and find port 8083. I also tried to update my S3 Bucket version to 10.3.0 as the latest version based on the Kafka documentation however that also failed to connect to port 8083. My secrets and bootstrap servers+schema registry is working and the pod is working but failed to connect to port 8083 to start the connectors. Here is my docker file. Any clue or suggestion why using alpine_container and version 10.3.0 failed FROM alpine AS alpine_container WORKDIR / EXPOSE 9999 RUN apk add bash curl unzip \ # Download Kafka Connect && mkdir /kafka_connect \ && curl https://archive.apache.org/dist/kafka/3.1.1/kafka_2.13-3.1.1.tgz \ | tar xz --strip-components=1 -C /kafka_connect \ # Download the Confluent Kafka Connect JDBC Connector, a plugin for Kafka Connect && mkdir /kafka_jdbc_connector \ && curl https://d1i4a15mxbxib1.cloudfront.net/api/plugins/confluentinc/kafka-connect-jdbc/versions/10.6.0/confluentinc-kafka-connect-jdbc-10.6.0.zip -o kafka_connect_jdbc_connector.zip \ && unzip kafka_connect_jdbc_connector.zip -d /kafka_connect_jdbc_connector \ # Download the Confluent Kafka Connect Avro Converter, a plugin for Kafka Connect && mkdir /kafka_avro_converter \ && curl https://d1i4a15mxbxib1.cloudfront.net/api/plugins/confluentinc/kafka-connect-avro-converter/versions/7.1.4/confluentinc-kafka-connect-avro-converter-7.1.4.zip -o kafka_connect_avro_converter.zip \ && unzip kafka_connect_avro_converter.zip -d /kafka_connect_avro_converter \ && mkdir /kafka_connect_s3 \ && curl https://d1i4a15mxbxib1.cloudfront.net/api/plugins/confluentinc/kafka-connect-s3/versions/10.3.0/confluentinc-kafka-connect-s3-10.3.0.zip -o kafka_connect_s3.zip \ && unzip kafka_connect_s3.zip -d /kafka_connect_s3 FROM openjdk:11-slim RUN apt-get update \ && apt-get install -y \ procps \ dnsutils \ curl \ jq \ netcat \ net-tools \ && apt-get clean COPY --from=alpine_container /kafka_connect /kafka_connect COPY --from=alpine_container /kafka_connect_jdbc_connector/* /kafka_connect_jdbc_connector COPY --from=alpine_container /kafka_connect_avro_converter/* /kafka_connect_avro_converter COPY --from=alpine_container /kafka_connect_s3/* /kafka_connect_s3 COPY ./kafka_connect/. /kafka_connect/ COPY ./s3-connector.sh /kafka_connect/ ENV CLASSPATH /kafka_connect_jdbc_connector/lib/*:/kafka_connect_avro_converter/lib/*:/kafka_connect_s3/lib/* WORKDIR /kafka_connect
[ "Version doesn't matter.\nYou're starting from plain Java image. That doesn't automatically run any server.\nI suggest you start FROM confluentinc/cp-kafka-connect-base. Otherwise, you must add CMD /kafka_connect/bin/connect-distributed.sh /kafka_connect/config/connect-distributed.properties. Note, your base folder here is all Kafka not only \"kafka connect\", so naming should probably be fixed\nThere's also no reason I see for using Alpine. You can install confluent-hub CLI and use that instead of curl and unzip and needing to COPY and set CLASSPATH...\nExample https://github.com/OneCricketeer/apache-kafka-connect-docker/blob/schema-registry/Dockerfile.schema-registry#L5\n" ]
[ 0 ]
[]
[]
[ "apache_kafka", "apache_kafka_connect", "docker" ]
stackoverflow_0074663326_apache_kafka_apache_kafka_connect_docker.txt
Q: I am having an error on php has there been a change in the way syntax is done? I have the following code on my php website from a theme i made a long time ago but it gives warnings on 7.4 and errors on 8.0 add_action('widgets_init', create_function('', 'return register_widget("Banners125");')); Any suggestion on how i can fix this code in my wordpress theme for php 8.0? I would like it to work on php 8.0 A: The function create_function was deprecated in 7.2 and removed in 8.0. Your code can be rewritten in several ways, one of which is: add_action( 'widgets_init', function() { return register_widget("Banners125"); } );
I am having an error on php has there been a change in the way syntax is done?
I have the following code on my php website from a theme i made a long time ago but it gives warnings on 7.4 and errors on 8.0 add_action('widgets_init', create_function('', 'return register_widget("Banners125");')); Any suggestion on how i can fix this code in my wordpress theme for php 8.0? I would like it to work on php 8.0
[ "The function create_function was deprecated in 7.2 and removed in 8.0. Your code can be rewritten in several ways, one of which is:\nadd_action(\n 'widgets_init',\n function() {\n return register_widget(\"Banners125\");\n }\n);\n\n" ]
[ 0 ]
[]
[]
[ "php", "wordpress" ]
stackoverflow_0074663825_php_wordpress.txt
Q: Javascript - Save typed array as blob and read back in as binary data I have a typed array full of binary data that is being generated from an ArrayBuffer var myArr = new Uint8Array(myBuffer); I am presenting this to the user with var blob = new Blob(myArr, {type: "octet/stream"}; var blobURL = URL.createObjectURL(blob); and inserting a link that is "<a href=" + blobUrl + " download=" + filename "/a>" Later, I am letting the user select the file from disk, and using a file reader to do with var reader = new FileReader(); reader.onload = function () { console.log(reader.result); }; reader.readAsArrayBuffer(sourceFile); The problem is, it seems like no matter what I do, I get a "string" of the file's contents. In fact, when I save the file, I can open it, and it is plainly human readable. I.E. if my Uint8Array was {"0" : "51", "1" : "52", "2" : "53" } I can open the downloaded blob in a text editor and I just see "515253" which I don't think is what should be happening. How can I make a link to a file download for my file that is formatted properly so I can read it back in an dget the right values? A: As it turns out, the problem was that I had a syntax error in the creation of the Blob. The corrected code looked like: var blob = new Blob([myArr], {type: "octet/stream"}); I'm not really sure why if I am already passing an ArrayBuffer argument. Why I need bracket notation? Seems redundant? A: According to Mozilla https://developer.mozilla.org/en-US/docs/Web/API/Blob#Example_for_creating_a_URL_to_a_typed_array_using_a_blob var blob = new Blob([typedArray.buffer], {type: 'application/octet-stream'}); A: const download = function (data) { const blob = new Blob(data, { type: "octet/stream"}); const url = window.URL.createObjectURL(blob) const a = document.createElement('a') a.setAttribute('href', url) a.setAttribute('download', app.lastSub+"_"+new Date().toISOString()+'.py'); a.click() } const get = async function () { download(app.psspyList); }
Javascript - Save typed array as blob and read back in as binary data
I have a typed array full of binary data that is being generated from an ArrayBuffer var myArr = new Uint8Array(myBuffer); I am presenting this to the user with var blob = new Blob(myArr, {type: "octet/stream"}; var blobURL = URL.createObjectURL(blob); and inserting a link that is "<a href=" + blobUrl + " download=" + filename "/a>" Later, I am letting the user select the file from disk, and using a file reader to do with var reader = new FileReader(); reader.onload = function () { console.log(reader.result); }; reader.readAsArrayBuffer(sourceFile); The problem is, it seems like no matter what I do, I get a "string" of the file's contents. In fact, when I save the file, I can open it, and it is plainly human readable. I.E. if my Uint8Array was {"0" : "51", "1" : "52", "2" : "53" } I can open the downloaded blob in a text editor and I just see "515253" which I don't think is what should be happening. How can I make a link to a file download for my file that is formatted properly so I can read it back in an dget the right values?
[ "As it turns out, the problem was that I had a syntax error in the creation of the Blob.\nThe corrected code looked like:\nvar blob = new Blob([myArr], {type: \"octet/stream\"});\nI'm not really sure why if I am already passing an ArrayBuffer argument. Why I need bracket notation? Seems redundant?\n", "According to Mozilla\nhttps://developer.mozilla.org/en-US/docs/Web/API/Blob#Example_for_creating_a_URL_to_a_typed_array_using_a_blob\nvar blob = new Blob([typedArray.buffer], {type: 'application/octet-stream'});\n\n", "const download = function (data) \n{\n const blob = new Blob(data, { type: \"octet/stream\"});\n const url = window.URL.createObjectURL(blob)\n const a = document.createElement('a')\n a.setAttribute('href', url)\n a.setAttribute('download', app.lastSub+\"_\"+new Date().toISOString()+'.py');\n a.click()\n}\n\nconst get = async function () {\n download(app.psspyList);\n}\n\n" ]
[ 17, 6, 0 ]
[]
[]
[ "arrays", "filereader", "javascript", "typed_arrays" ]
stackoverflow_0036985406_arrays_filereader_javascript_typed_arrays.txt
Q: still keeping some vertical space while list-style: none still keeping some vertical space while list-style: none is defined. https://product-landing-page.freecodecamp.rocks/#how-it-works If you check this project and scroll to pricing labels there is defined exactly like mine and it behave differently. My price label: Project's label MY CSS: /* ========== PRICE ======= */ #cost { display: flex; flex-direction: row; justify-content: center; } .price-box { display: flex; flex-direction: column; align-items: center; text-align: center; width: calc(100% / 3); margin: 10px; border: 1px solid #000; border-radius: 3px; } .lvl { background-color: #dddddd; text-align: center; font-size: 1.4em; color: rgb(65, 65, 65); padding: 5px; width: 100%; } #cost ol li { padding: 5px 0; margin: 0; } li { list-style: none; } Project's CSS: #pricing { margin-top: 60px; display: flex; flex-direction: row; justify-content: center; } .product { display: flex; flex-direction: column; align-items: center; text-align: center; width: calc(100% / 3); margin: 10px; border: 1px solid #000; border-radius: 3px; } .product > .level { background-color: #ddd; color: black; padding: 15px 0; width: 100%; text-transform: uppercase; font-weight: 700; } .product > h2 { margin-top: 15px; } .product > ol { margin: 15px 0; } .product > ol > li { padding: 5px 0; } Maybe someone can explain it to me so i can understand what is happening here A: Just add padding: 0 ul, ol { list-style:none; padding:0; } A: If you look at all the CSS that is being applied to that ol element you'll notice that there is a setting of everything (*) which includes padding: 0; This overrides the browser's default settings for padding related to ol elements. You may or may not want to set padding: 0 for everything at the start. It depends on your precise use case. As in the case of the site you reference, something like this can be seen at the top of some stylesheets - meaning the author will add any padding and margin settings themselves rather than relying on default browser settings. * { margin: 0; padding: 0; box-sizing: border-box; } [The box-sizing setting means e.g. padding and border dimensions are included in the dimensions of the element]. If you don't want such a global approach to unsetting padding then put the padding: 0 in the style setting for the ol element itself. For example: [I can't tell exactly what this should be as I don't know your HTML stucture] #cost ol { padding: 0; }
still keeping some vertical space while list-style: none
still keeping some vertical space while list-style: none is defined. https://product-landing-page.freecodecamp.rocks/#how-it-works If you check this project and scroll to pricing labels there is defined exactly like mine and it behave differently. My price label: Project's label MY CSS: /* ========== PRICE ======= */ #cost { display: flex; flex-direction: row; justify-content: center; } .price-box { display: flex; flex-direction: column; align-items: center; text-align: center; width: calc(100% / 3); margin: 10px; border: 1px solid #000; border-radius: 3px; } .lvl { background-color: #dddddd; text-align: center; font-size: 1.4em; color: rgb(65, 65, 65); padding: 5px; width: 100%; } #cost ol li { padding: 5px 0; margin: 0; } li { list-style: none; } Project's CSS: #pricing { margin-top: 60px; display: flex; flex-direction: row; justify-content: center; } .product { display: flex; flex-direction: column; align-items: center; text-align: center; width: calc(100% / 3); margin: 10px; border: 1px solid #000; border-radius: 3px; } .product > .level { background-color: #ddd; color: black; padding: 15px 0; width: 100%; text-transform: uppercase; font-weight: 700; } .product > h2 { margin-top: 15px; } .product > ol { margin: 15px 0; } .product > ol > li { padding: 5px 0; } Maybe someone can explain it to me so i can understand what is happening here
[ "Just add padding: 0\n\n\nul, ol {\nlist-style:none;\npadding:0;\n}\n\n\n\n", "If you look at all the CSS that is being applied to that ol element you'll notice that there is a setting of everything (*) which includes padding: 0;\nThis overrides the browser's default settings for padding related to ol elements.\nYou may or may not want to set padding: 0 for everything at the start. It depends on your precise use case.\nAs in the case of the site you reference, something like this can be seen at the top of some stylesheets - meaning the author will add any padding and margin settings themselves rather than relying on default browser settings.\n* {\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n}\n\n[The box-sizing setting means e.g. padding and border dimensions are included in the dimensions of the element].\nIf you don't want such a global approach to unsetting padding then put the padding: 0 in the style setting for the ol element itself. For example: [I can't tell exactly what this should be as I don't know your HTML stucture]\n#cost ol {\n padding: 0;\n}\n\n" ]
[ 0, 0 ]
[]
[]
[ "css", "html" ]
stackoverflow_0074662947_css_html.txt
Q: Resolve and Register services using Scrutor in Asp.net core i have an interface(IDomainService) and a (lot) like it in my app which i mark more interfaces with it(IProductionLineTitleDuplicationChecker ) like what u will see in the rest: public interface IDomainService { } public interface IProductionLineTitleDuplicationChecker : IDomainService { /// } and the implementation like this: public class ProductionLineTitleDuplicationChecker : IProductionLineTitleDuplicationChecker { private readonly IProductionLineRepository _productionLineRepository; public ProductionLineTitleDuplicationChecker(IProductionLineRepository productionLineRepository) { _productionLineRepository = productionLineRepository; } public bool IsDuplicated(string productionLineTitle) { /// } } right now im using the built-in DI-container to resolve and register the services but i want to change it and use scrutor instead how can i resolve and register my Services using scrutor? A: You could just leverage the Scrutor extension methods for Microsoft.Extensions.DependencyInjection.IServiceCollection. In your Startup.cs: public void ConfigureServices(IServiceCollection serviceCollection) { serviceCollection .Scan(x => x.FromAssemblyOf<ProductionLineTitleDuplicationChecker>() .AddClasses() .AsImplementedInterfaces() .WithTransientLifetime()); } A: I think your situation is consistent with this post, please try to use the way inside: services.Scan(scan => scan .FromAssemblyOf<IProductionLineTitleDuplicationChecker>() .AddClasses(classes => classes .AssignableTo<IProductionLineTitleDuplicationChecker>()) .AsImplementedInterfaces() .WithScopedLifetime()); A: I think this should work public void ConfigureServices(IServiceCollection serviceCollection) { services.Scan(scan => scan .FromAssemblyOf<IProductionLineTitleDuplicationChecker>() .AddClasses(classes => classes.AssignableTo<IDomainService>()) .AsImplementedInterfaces() .WithScopedLifetime()); } A: Here is the solution: protected IServiceCollection _serviceCollection; public virtual void Register(IServiceCollection serviceCollection, ) { _serviceCollection = serviceCollection; RegisterTransient<IDomainService>(); } private void RegisterTransient<TRegisterBase>() { _serviceCollection.Scan(s => s.FromApplicationDependencies() .AddClasses(c => c.AssignableTo<TRegisterBase>()) .UsingRegistrationStrategy(RegistrationStrategy.Throw) .AsMatchingInterface() .WithTransientLifetime()); }
Resolve and Register services using Scrutor in Asp.net core
i have an interface(IDomainService) and a (lot) like it in my app which i mark more interfaces with it(IProductionLineTitleDuplicationChecker ) like what u will see in the rest: public interface IDomainService { } public interface IProductionLineTitleDuplicationChecker : IDomainService { /// } and the implementation like this: public class ProductionLineTitleDuplicationChecker : IProductionLineTitleDuplicationChecker { private readonly IProductionLineRepository _productionLineRepository; public ProductionLineTitleDuplicationChecker(IProductionLineRepository productionLineRepository) { _productionLineRepository = productionLineRepository; } public bool IsDuplicated(string productionLineTitle) { /// } } right now im using the built-in DI-container to resolve and register the services but i want to change it and use scrutor instead how can i resolve and register my Services using scrutor?
[ "You could just leverage the Scrutor extension methods for Microsoft.Extensions.DependencyInjection.IServiceCollection. In your Startup.cs:\npublic void ConfigureServices(IServiceCollection serviceCollection)\n{\n serviceCollection\n .Scan(x => x.FromAssemblyOf<ProductionLineTitleDuplicationChecker>()\n .AddClasses()\n .AsImplementedInterfaces()\n .WithTransientLifetime());\n}\n\n", "I think your situation is consistent with this post, please try to use the way inside:\nservices.Scan(scan => scan\n .FromAssemblyOf<IProductionLineTitleDuplicationChecker>()\n .AddClasses(classes => classes\n .AssignableTo<IProductionLineTitleDuplicationChecker>())\n.AsImplementedInterfaces()\n.WithScopedLifetime());\n\n", "I think this should work\npublic void ConfigureServices(IServiceCollection serviceCollection)\n{\n services.Scan(scan => scan\n .FromAssemblyOf<IProductionLineTitleDuplicationChecker>()\n .AddClasses(classes => classes.AssignableTo<IDomainService>())\n .AsImplementedInterfaces()\n .WithScopedLifetime());\n}\n\n", "Here is the solution:\n protected IServiceCollection _serviceCollection;\n public virtual void Register(IServiceCollection serviceCollection, )\n {\n _serviceCollection = serviceCollection;\n RegisterTransient<IDomainService>();\n }\n\n private void RegisterTransient<TRegisterBase>()\n {\n _serviceCollection.Scan(s =>\n s.FromApplicationDependencies()\n .AddClasses(c => c.AssignableTo<TRegisterBase>())\n .UsingRegistrationStrategy(RegistrationStrategy.Throw)\n .AsMatchingInterface()\n .WithTransientLifetime());\n }\n\n" ]
[ 0, 0, 0, 0 ]
[]
[]
[ "asp.net_core", "c#", "scrutor" ]
stackoverflow_0074502598_asp.net_core_c#_scrutor.txt
Q: Downloading gz json file from url in R lien_du_cadastre<-str_replace_all(paste("https://france-cadastre.fr/cadastre/",Nom_ville), " ","") lien_du_cadastre serveur_objet$navigate(lien_du_cadastre) url2=serveur_objet$findElement(using = 'xpath','/html/body/div[4]/div[3]/div[1]/div[4]/div/div[3]/div[2]/div/a[1]')$getElementAttribute("href")[[1]] #donne l'url de téléchargement du plan cadastre url2 (the url inside is : https://france-cadastre.fr/downloadcenter.php?format=json&echelle=commune&insee=02408&type=parcelles) file_path <- tempfile(pattern = "", fileext = ".json") file_path download.file(url2, file_path, quiet = TRUE, mode = "wb") Hi, I'm trying to download a file from this website after got the url but the file which is downloaded is corrupted because when i tried to open it i see binary and character not the json file content. I tried to download it manually and by this way the real content is displayed. I don't know my using of download.file function is bad i didn't succeed to fixe it since. A: The jsonlite package has the parse_gzjson_raw() function to read gzip compressed data. First you need to read the data into R as a raw vector. library(jsonlite) url <- "https://france-cadastre.fr/downloadcenter.php?format=json&echelle=commune&insee=02408&type=parcelles" dat <- readBin(url, "raw", 1e07) # Or readr::read_file_raw(url) res <- parse_gzjson_raw(dat) Check the data: str(res) List of 2 $ type : chr "FeatureCollection" $ features:'data.frame': 12405 obs. of 4 variables: ..$ type : chr [1:12405] "Feature" "Feature" "Feature" "Feature" ... ..$ id : chr [1:12405] "02408000AB0133" "02408000AB0132" "02408000AB0131" "02408000AB0129" ... ..$ geometry :'data.frame': 12405 obs. of 2 variables: .. ..$ type : chr [1:12405] "Polygon" "Polygon" "Polygon" "Polygon" ... .. ..$ coordinates:List of 12405 .. .. ..$ : num [1, 1:12, 1:2] 3.63 3.63 3.63 3.62 3.63 ... .. .. ..$ : num [1, 1:9, 1:2] 3.63 3.62 3.62 3.62 3.62 ... .. .. ..$ : num [1, 1:17, 1:2] 3.62 3.62 3.62 3.62 3.62 ... ...
Downloading gz json file from url in R
lien_du_cadastre<-str_replace_all(paste("https://france-cadastre.fr/cadastre/",Nom_ville), " ","") lien_du_cadastre serveur_objet$navigate(lien_du_cadastre) url2=serveur_objet$findElement(using = 'xpath','/html/body/div[4]/div[3]/div[1]/div[4]/div/div[3]/div[2]/div/a[1]')$getElementAttribute("href")[[1]] #donne l'url de téléchargement du plan cadastre url2 (the url inside is : https://france-cadastre.fr/downloadcenter.php?format=json&echelle=commune&insee=02408&type=parcelles) file_path <- tempfile(pattern = "", fileext = ".json") file_path download.file(url2, file_path, quiet = TRUE, mode = "wb") Hi, I'm trying to download a file from this website after got the url but the file which is downloaded is corrupted because when i tried to open it i see binary and character not the json file content. I tried to download it manually and by this way the real content is displayed. I don't know my using of download.file function is bad i didn't succeed to fixe it since.
[ "The jsonlite package has the parse_gzjson_raw() function to read gzip compressed data. First you need to read the data into R as a raw vector.\nlibrary(jsonlite)\n\nurl <- \"https://france-cadastre.fr/downloadcenter.php?format=json&echelle=commune&insee=02408&type=parcelles\"\n\ndat <- readBin(url, \"raw\", 1e07) # Or readr::read_file_raw(url)\nres <- parse_gzjson_raw(dat)\n\nCheck the data:\nstr(res)\n\nList of 2\n $ type : chr \"FeatureCollection\"\n $ features:'data.frame': 12405 obs. of 4 variables:\n ..$ type : chr [1:12405] \"Feature\" \"Feature\" \"Feature\" \"Feature\" ...\n ..$ id : chr [1:12405] \"02408000AB0133\" \"02408000AB0132\" \"02408000AB0131\" \"02408000AB0129\" ...\n ..$ geometry :'data.frame': 12405 obs. of 2 variables:\n .. ..$ type : chr [1:12405] \"Polygon\" \"Polygon\" \"Polygon\" \"Polygon\" ...\n .. ..$ coordinates:List of 12405\n .. .. ..$ : num [1, 1:12, 1:2] 3.63 3.63 3.63 3.62 3.63 ...\n .. .. ..$ : num [1, 1:9, 1:2] 3.63 3.62 3.62 3.62 3.62 ...\n .. .. ..$ : num [1, 1:17, 1:2] 3.62 3.62 3.62 3.62 3.62 ...\n...\n\n" ]
[ 0 ]
[]
[]
[ "r" ]
stackoverflow_0074663899_r.txt
Q: sublime text 3 complete vim support I installed Vintageous in sublime text 3 so i can use some of vim commands and interactions. But I am using it for a long time, and there is a lot of features missing, like the 'ctrl+x' and 'ctrl+a" to decrease and increase a number, the 'ctrl+r' to redo, the 'ctrl+v' to select vertical blocks, 'ctrl+c' to quit insertion mode ... etc. I really like sublime text 3, but in the other hand, i'm really missing this commands, it's all of theses commands which makes vim so powerful. So how can I get a complete vim mode in sublime text 3. It would be just perfect if i can do that (because I really miss vim complete features). PS : I'm using Ubuntu 15.10 with Linux version > 4. A: Vintageous has the setting vintageous_use_ctrl_keys, which should solve most of your issues.In contrast to other packages Vintageous uses the User preferences. Hence you can just add the entry "vintageous_use_ctrl_keys": false to "Preferences >> Settings - User". However for this settings there is an entry in the control palette. Press ctrl+shift+p and write Vintageous: Toggle Vim Ctrl Keys. You can see the other settings here and just change them in the user preferences. If you are still missing some keys I would recommend to look at the default keymap and search for other packages, which provide this behavior and change the keybinding as you want them. A: Now there is a new player, ActualVim plugin. Everything you like about using Sublime Text 3, and everything you like about typing in vim. Actual uses an embedded Neovim instance to accurately manipulate each Sublime Text buffer as though you were editing the text directly in vim, without breaking any Sublime Text features (aside from multiple selection for now). It’s way better than Vintage mode or Vintageous. You can use your own .vimrc, plugins, real vim motions and commands. A: To get vim shortcuts in Sublime Text Install neovim (the actual program which is unrelated to sublime text - it's necessary for this approach to work). Example brew install neovim. In sublime, press command + shift + p, type "install package" and click on the top result. Now search for 'ActualVim', and click on it, it should install. Close and reopen sublime. Vim shortcuts now work!
sublime text 3 complete vim support
I installed Vintageous in sublime text 3 so i can use some of vim commands and interactions. But I am using it for a long time, and there is a lot of features missing, like the 'ctrl+x' and 'ctrl+a" to decrease and increase a number, the 'ctrl+r' to redo, the 'ctrl+v' to select vertical blocks, 'ctrl+c' to quit insertion mode ... etc. I really like sublime text 3, but in the other hand, i'm really missing this commands, it's all of theses commands which makes vim so powerful. So how can I get a complete vim mode in sublime text 3. It would be just perfect if i can do that (because I really miss vim complete features). PS : I'm using Ubuntu 15.10 with Linux version > 4.
[ "Vintageous has the setting vintageous_use_ctrl_keys, which should solve most of your issues.In contrast to other packages Vintageous uses the User preferences. Hence you can just add the entry \"vintageous_use_ctrl_keys\": false to \"Preferences >> Settings - User\". However for this settings there is an entry in the control palette. Press ctrl+shift+p and write Vintageous: Toggle Vim Ctrl Keys. You can see the other settings here and just change them in the user preferences.\nIf you are still missing some keys I would recommend to look at the default keymap and search for other packages, which provide this behavior and change the keybinding as you want them.\n", "Now there is a new player, ActualVim plugin.\n\nEverything you like about using Sublime Text 3, and everything you\n like about typing in vim.\nActual uses an embedded Neovim instance to accurately manipulate each\n Sublime Text buffer as though you were editing the text directly in\n vim, without breaking any Sublime Text features (aside from multiple\n selection for now).\n\nIt’s way better than Vintage mode or Vintageous. You can use your own .vimrc, plugins, real vim motions and commands.\n", "To get vim shortcuts in Sublime Text\n\nInstall neovim (the actual program which is unrelated to sublime text - it's necessary for this approach to work). Example brew install neovim.\n\nIn sublime, press command + shift + p, type \"install package\" and click on the top result.\n\nNow search for 'ActualVim', and click on it, it should install.\n\nClose and reopen sublime.\n\nVim shortcuts now work!\n\n\n" ]
[ 6, 5, 0 ]
[]
[]
[ "linux", "sublimetext3", "vim" ]
stackoverflow_0035872530_linux_sublimetext3_vim.txt
Q: How can I vertically center a div element for all browsers using CSS? I want to center a div vertically with CSS. I don't want tables or JavaScript, but only pure CSS. I found some solutions, but all of them are missing Internet Explorer 6 support. <body> <div>Div to be aligned vertically</div> </body> How can I center a div vertically in all major browsers, including Internet Explorer 6? A: Below is the best all-around solution I could build to vertically and horizontally center a fixed-width, flexible height content box. It was tested and worked for recent versions of Firefox, Opera, Chrome, and Safari. .outer { display: table; position: absolute; top: 0; left: 0; height: 100%; width: 100%; } .middle { display: table-cell; vertical-align: middle; } .inner { margin-left: auto; margin-right: auto; width: 400px; /* Whatever width you want */ } <div class="outer"> <div class="middle"> <div class="inner"> <h1>The Content</h1> <p>Once upon a midnight dreary...</p> </div> </div> </div> View A Working Example With Dynamic Content I built in some dynamic content to test the flexibility and would love to know if anyone sees any problems with it. It should work well for centered overlays also -- lightbox, pop-up, etc. A: The simplest way would be the following three lines of CSS: 1) position: relative; 2) top: 50%; 3) transform: translateY(-50%); Following is an example: div.outer-div { height: 170px; width: 300px; background-color: lightgray; } div.middle-div { position: relative; top: 50%; -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); transform: translateY(-50%); } <div class='outer-div'> <div class='middle-div'> Test text </div> </div> A: One more I can't see on the list: .Center-Container { position: relative; height: 100%; } .Absolute-Center { width: 50%; height: 50%; overflow: auto; margin: auto; position: absolute; top: 0; left: 0; bottom: 0; right: 0; border: solid black; } Cross-browser (including Internet Explorer 8 - Internet Explorer 10 without hacks!) Responsive with percentages and min-/max- Centered regardless of padding (without box-sizing!) height must be declared (see Variable Height) Recommended setting overflow: auto to prevent content spillover (see Overflow) Source: Absolute Horizontal And Vertical Centering In CSS A: Now the Flexbox solution is a very easy way for modern browsers, so I recommend this for you: .container { display: flex; align-items: center; justify-content: center; height: 100%; background: green; } body, html { height: 100%; } <div class="container"> <div>Div to be aligned vertically</div> </div> A: Actually, you need two div's for vertical centering. The div containing the content must have a width and height. #container { position: absolute; top: 50%; margin-top: -200px; /* Half of #content height */ left: 0; width: 100%; } #content { width: 624px; margin-left: auto; margin-right: auto; height: 395px; border: 1px solid #000000; } <div id="container"> <div id="content"> <h1>Centered div</h1> </div> </div> Here is the result. A: Edit 2020: only use this if you need to support old browsers like Internet Explorer 8 (which you should refuse to do ). If not, use Flexbox. This is the simplest method I found and I use it all the time (jsFiddle demo here). Thank Chris Coyier from CSS Tricks for this article. html, body{ height: 100%; margin: 0; } .v-wrap{ height: 100%; white-space: nowrap; text-align: center; } .v-wrap:before{ content: ""; display: inline-block; vertical-align: middle; width: 0; /* adjust for white space between pseudo element and next sibling */ margin-right: -.25em; /* stretch line height */ height: 100%; } .v-box{ display: inline-block; vertical-align: middle; white-space: normal; } <div class="v-wrap"> <article class="v-box"> <p>This is how I've been doing it for some time</p> </article> </div> Support starts with Internet Explorer 8. A: After a lot of research I finally found the ultimate solution. It works even for floated elements. View Source .element { position: relative; top: 50%; transform: translateY(-50%); /* or try 50% */ } A: Use the CSS Flexbox align-items property to achieve this. html, body { height: 100%; } body { display: flex; align-items: center; } <div>This is centered vertically</div> A: To center the div on a page, check the fiddle link. #vh { margin: auto; position: absolute; top: 0; left: 0; bottom: 0; right: 0; } .box{ border-radius: 15px; box-shadow: 0 0 8px rgba(0, 0, 0, 0.4); padding: 25px; width: 100px; height: 100px; background: white; } <div id="vh" class="box">Div to be aligned vertically</div> Another option is to use flex box, check the fiddle link. .vh { background-color: #ddd; height: 400px; align-items: center; display: flex; } .vh > div { width: 100%; text-align: center; vertical-align: middle; } <div class="vh"> <div>Div to be aligned vertically</div> </div> Another option is to use a CSS 3 transform: #vh { position: absolute; top: 50%; left: 50%; /*transform: translateX(-50%) translateY(-50%);*/ transform: translate(-50%, -50%); } .box{ border-radius: 15px; box-shadow: 0 0 8px rgba(0, 0, 0, 0.4); padding: 25px; width: 100px; height: 100px; background: white; } <div id="vh" class="box">Div to be aligned vertically</div> A: The easiest solution is below: .outer-div{ width: 100%; height: 200px; display: flex; border:1px solid #000; } .inner-div{ margin: auto; text-align: center; border: 1px solid red; } <div class="outer-div"> <div class="inner-div"> Hey there! </div> </div> A: There are multiple ways to achieve this. Using flex property of CSS. Solution #1 .parent { width: 400px; height:200px; background: blue; display: flex; align-items: center; justify-content:center; } .child { width: 75px; height: 75px; background: yellow; } <div class="parent"> <div class="child"></div> </div> or by using display: flex; and margin: auto; Solution #2 .parent { width: 400px; height:200px; background: blue; display: flex; } .child { width: 75px; height: 75px; background: yellow; margin:auto; } <div class="parent"> <div class="child"></div> </div> show text center Solution #3 .parent { width: 400px; height: 200px; background: yellow; display: flex; align-items: center; justify-content:center; } <div class="parent">Center</div> Using percentage(%) height and width. Solution #4 .parent { position: absolute; height:100%; width:100%; background: blue; display: flex; align-items: center; justify-content:center; } .child { width: 75px; height: 75px; background: yellow; } <div class="parent"> <div class="child"></div> </div> A: Unfortunately — but not surprisingly — the solution is more complicated than one would wish it to be. Also unfortunately, you'll need to use additional divs around the div you want vertically centered. For standards-compliant browsers like Mozilla, Opera, Safari, etc. you need to set the outer div to be displayed as a table and the inner div to be displayed as a table-cell — which can then be vertically centered. For Internet Explorer, you need to position the inner div absolutely within the outer div and then specify the top as 50%. The following pages explain this technique well and provide some code samples too: Vertical Centering in CSS Vertical Centering in CSS with Unknown Height (Internet Explorer 7 compatible) (Archived article courtesy of the Wayback Machine) There is also a technique to do the vertical centering using JavaScript. Vertical alignment of content with JavaScript & CSS demonstrates it. A: If someone cares for Internet Explorer 10 (and later) only, use Flexbox: .parent { width: 500px; height: 500px; background: yellow; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-justify-content: center; -ms-flex-pack: center; justify-content: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .centered { width: 100px; height: 100px; background: blue; } <div class="parent"> <div class="centered"></div> </div> Flexbox support: http://caniuse.com/flexbox A: A modern way to center an element vertically would be to use flexbox. You need a parent to decide the height and a child to center. The example below will center a div to the center within your browser. What's important (in my example) is to set height: 100% to body and html and then min-height: 100% to your container. body, html { background: #F5F5F5; box-sizing: border-box; height: 100%; margin: 0; } #center_container { align-items: center; display: flex; min-height: 100%; } #center { background: white; margin: 0 auto; padding: 10px; text-align: center; width: 200px; } <div id='center_container'> <div id='center'>I am center.</div> </div> A: Centering only vertically If you don't care about Internet Explorer 6 and 7, you can use a technique that involves two containers. The outer container: should have display: table; The inner container: should have display: table-cell; should have vertical-align: middle; The content box: should have display: inline-block; You can add any content you want to the content box without caring about its width or height! Demo: body { margin: 0; } .outer-container { position: absolute; display: table; width: 100%; /* This could be ANY width */ height: 100%; /* This could be ANY height */ background: #ccc; } .inner-container { display: table-cell; vertical-align: middle; } .centered-content { display: inline-block; background: #fff; padding: 20px; border: 1px solid #000; } <div class="outer-container"> <div class="inner-container"> <div class="centered-content"> Malcolm in the Middle </div> </div> </div> See also this Fiddle! Centering horizontally and vertically If you want to center both horizontally and vertically, you also need the following. The inner container: should have text-align: center; The content box: should re-adjust the horizontal text-alignment to for example text-align: left; or text-align: right;, unless you want text to be centered Demo: body { margin: 0; } .outer-container { position: absolute; display: table; width: 100%; /* This could be ANY width */ height: 100%; /* This could be ANY height */ background: #ccc; } .inner-container { display: table-cell; vertical-align: middle; text-align: center; } .centered-content { display: inline-block; text-align: left; background: #fff; padding: 20px; border: 1px solid #000; } <div class="outer-container"> <div class="inner-container"> <div class="centered-content"> Malcolm in the Middle </div> </div> </div> See also this Fiddle! A: .center { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); /* (x, y) => position */ -ms-transform: translate(-50%, -50%); /* IE 9 */ -webkit-transform: translate(-50%, -50%); /* Chrome, Safari, Opera */ } .vertical { position: absolute; top: 50%; //left: 0; transform: translate(0, -50%); /* (x, y) => position */ } .horizontal { position: absolute; //top: 0; left: 50%; transform: translate(-50%, 0); /* (x, y) => position */ } div { padding: 1em; background-color: grey; color: white; } <body> <div class="vertical">Vertically left</div> <div class="horizontal">Horizontal top</div> <div class="center">Vertically Horizontal</div> </body> Related: Center a Image A: It can be done in two ways body{ left: 50%; top:50%; transform: translate(-50%, -50%); height: 100%; width: 100%; } OR Using flex body { height:100% width:100% display: flex; justify-content: center; align-items: center; } align-items:center; makes the content vertically center justify-content: center;makes the content horizontally center A: This is always where I go when I have to come back to this issue. For those who don't want to make the jump: Specify the parent container as position:relative or position:absolute. Specify a fixed height on the child container. Set position:absolute and top:50% on the child container to move the top down to the middle of the parent. Set margin-top:-yy where yy is half the height of the child container to offset the item up. An example of this in code: <style type="text/css"> #myoutercontainer {position:relative} #myinnercontainer {position:absolute; top:50%; height:10em; margin-top:-5em} </style> ... <div id="myoutercontainer"> <div id="myinnercontainer"> <p>Hey look! I'm vertically centered!</p> <p>How sweet is this?!</p> </div> </div> A: I just wrote this CSS and to know more, please go through: This article with vertical align anything with just 3 lines of CSS. .element { position: relative; top: 50%; transform: perspective(1px) translateY(-50%); } A: For newcomers, please try: display: flex; align-items: center; justify-content: center; A: The three lines of code using transform works practically on modern browsers and Internet Explorer: .element{ position: relative; top: 50%; transform: translateY(-50%); -moz-transform: translateY(-50%); -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); } I am adding this answer since I found some incompleteness in the previous version of this answer (and Stack Overflow won't allow me to simply comment). 'position' relative messes up the styling if the current div is in the body and has no container div. However 'fixed' seems to work, but it obviously fixes the content in the center of the viewport Also I used this styling for centering some overlay divs and found that in Mozilla all elements inside this transformed div had lost their bottom borders. Possibly a rendering issue. But adding just the minimal padding to some of them rendered it correctly. Chrome and Internet Explorer (surprisingly) rendered the boxes without any need for padding A: CSS Grid body, html { margin: 0; } body { display: grid; min-height: 100vh; align-items: center; } <div>Div to be aligned vertically</div> A: .center{ display: grid; place-items: center; } A: I did it with this (change width, height, margin-top and margin-left accordingly): .wrapper { width: 960px; height: 590px; position: absolute; top: 50%; left: 50%; margin-top: -295px; margin-left: -480px; } <div class="wrapper"> -- Content -- </div> A: The answer from Billbad only works with a fixed width of the .inner div. This solution works for a dynamic width by adding the attribute text-align: center to the .outer div. .outer { position: absolute; display: table; width: 100%; height: 100%; text-align: center; } .middle { display: table-cell; vertical-align: middle; } .inner { text-align: center; display: inline-block; width: auto; } <div class="outer"> <div class="middle"> <div class="inner"> Content </div> </div> </div> A: Just do it: Add the class at your div: .modal { margin: auto; position: absolute; top: 0; right: 0; left: 0; bottom: 0; height: 240px; } And read this article for an explanation. Note: Height is necessary. A: Not answering for browser compatibility but to also mention the new Grid and the not so new Flexbox feature. Grid From: Mozilla - Grid Documentation - Align Div Vertically Browser Support: Grid Browser Support CSS: .wrapper { display: grid; grid-template-columns: repeat(4, 1fr); grid-gap: 10px; grid-auto-rows: 200px; grid-template-areas: ". a a ." ". a a ."; } .item1 { grid-area: a; align-self: center; justify-self: center; } HTML: <div class="wrapper"> <div class="item1">Item 1</div> </div> Flexbox Browser Support: Flexbox Browser Support CSS: display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -webkit-flex; display: flex; align-items: center; justify-content: center; A: I think a solid solution for all browsers without using Flexbox - "align-items: center;" is a combination of display: table and vertical-align: middle;. CSS .vertically-center { display: table; width: 100%; /* Optional */ height: 100%; /* Optional */ } .vertically-center > div { display: table-cell; vertical-align: middle; } HTML <div class="vertically-center"> <div> <div style="border: 1px solid black;">some text</div> </div> </div> ‣Demo: https://jsfiddle.net/6m640rpp/ A: Especially for parent divs with relative (unknown) height, the centering in the unknown solution works great for me. There are some really nice code examples in the article. It was tested in Chrome, Firefox, Opera, and Internet Explorer. /* This parent can be any width and height */ .block { text-align: center; } /* The ghost, nudged to maintain perfect centering */ .block:before { content: ''; display: inline-block; height: 100%; vertical-align: middle; margin-right: -0.25em; /* Adjusts for spacing */ } /* The element to be centered, can also be of any width and height */ .centered { display: inline-block; vertical-align: middle; width: 300px; } <div style="width: 400px; height: 200px;"> <div class="block" style="height: 90%; width: 100%"> <div class="centered"> <h1>Some text</h1> <p>Any other text..."</p> </div> </div> </div> A: The contents can be easily centered by using Flexbox. The following code shows the CSS for the container inside which the contents needs to be centered: .absolute-center { display: -ms-flexbox; display: -webkit-flex; display: flex; -ms-flex-align: center; -webkit-align-items: center; -webkit-box-align: center; align-items: center; } A: There is a trick I found out recently: You need to use top 50%, and then you do a translateY(-50%). .outer-div { position: relative; height: 150px; width: 150px; background-color: red; } .centered-div { position: absolute; top: 50%; -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); transform: translateY(-50%); background-color: white; } <div class='outer-div'> <div class='centered-div'> Test text </div> </div> A: I find this one most useful... It gives the most accurate 'H' layout and is very simple to understand. The benefit of this markup is that you define your content size in a single place -> "PageContent". The Colors of the page background and its horizontal margins are defined in their corresponding divs. <div id="PageLayoutConfiguration" style="display: table; position:absolute; top: 0px; right: 0px; bottom: 0px; left: 0px; width: 100%; height: 100%;"> <div id="PageBackground" style="display: table-cell; vertical-align: middle; background-color: purple;"> <div id="PageHorizontalMargins" style="width: 100%; background-color: seashell;"> <div id="PageContent" style="width: 1200px; height: 620px; margin: 0 auto; background-color: grey;"> My content goes here... </div> </div> </div> </div> And here with CSS separated: <div id="PageLayoutConfiguration"> <div id="PageBackground"> <div id="PageHorizontalMargins"> <div id="PageContent"> my content goes here... </div> </div> </div> </div> #PageLayoutConfiguration{ display: table; width: 100%; height: 100%; position: absolute; top: 0px; right: 0px; bottom: 0px; left: 0px; } #PageBackground{ display: table-cell; vertical-align: middle; background-color: purple; } #PageHorizontalMargins{ style="width: 100%; background-color: seashell; } #PageContent{ width: 1200px; height: 620px; margin: 0 auto; background-color: grey; } A: I use this. It works in Internet Explorer 8 and later: height:268px - for display:table acts like min-height. CSS: * { padding: 0; margin: 0; } body { background: #cc9999; } p { background: #f0ad4e; } #all { margin: 200px auto; } .ff-valign-wrap { display: table; width: 100%; height: 268px; background: #ff00ff; } .ff-valign { display: table-cell; height: 100%; vertical-align: middle; text-align: center; background: #ffff00; } HTML: <body> <div id="all"> <div class="ff-valign-wrap"> <div class="ff-valign"> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet, animi autem doloribus earum expedita, ipsum laboriosam nostrum nulla officiis optio quam quis quod sunt tempora tenetur veritatis vero voluptatem voluptates?</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet, animi autem doloribus earum expedita, ipsum laboriosam nostrum nulla officiis optio quam quis quod sunt tempora tenetur veritatis vero voluptatem voluptates?</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet, animi autem doloribus earum expedita, ipsum laboriosam nostrum nulla officiis optio quam quis quod sunt tempora tenetur veritatis vero voluptatem voluptates?</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet, animi autem doloribus earum expedita, ipsum laboriosam nostrum nulla officiis optio quam quis quod sunt tempora tenetur veritatis vero voluptatem voluptates?</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet, animi autem doloribus earum expedita, ipsum laboriosam nostrum nulla officiis optio quam quis quod sunt tempora tenetur veritatis vero voluptatem voluptates?</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet, animi autem doloribus earum expedita, ipsum laboriosam nostrum nulla officiis optio quam quis quod sunt tempora tenetur veritatis vero voluptatem voluptates?</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet, animi autem doloribus earum expedita, ipsum laboriosam nostrum nulla officiis optio quam quis quod sunt tempora tenetur veritatis vero voluptatem voluptates?</p> </div> </div> </div> </body> A: The following is working in my case and was tested in Firefox. #element { display: block; transform: translateY(50%); -moz-transform: translateY(50%); -webkit-transform: translateY(50%); -ms-transform: translateY(50%); } The div's height and parent's height are dynamic. I use it when there are other elements on the same parent which is higher than the target element, where both are positioned horizontally inline. A: This solution worked for me for a block element (e.g., <div>). I used the colors to make the solution clearer. HTML: <main class="skin_orange"> <p>As you can the the element/box is vertically centered</p> <div class="bigBox skin_blue">Blue Box</div> </main> CSS: main { position: relative; width: 400px; height: 400px; } .skin_orange { outline: thin dotted red; background: orange; } .bigBox { width: 150px; height: 150px; position: absolute; top: 50%; transform: translateY(-50%); } .skin_blue { background-color: blue; } JSFiddle Code Demo A: I just found another way which worked for me: <div class="container"> <div class="vertical"> <h1>Welcome</h1> <h2>Aligned Vertically</h2> <a href="#">Click ME</a> </div> </div> CSS .vertical{ top: 50%; -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); transform: translateY(-50%); } More information A: Vertical & Horizontal CENTER HTML <div id="dialog">Centered Dialog</div> CSS #dialog { position:fixed; top:50%; left:50%; z-index:99991; width:300px; height:60px; margin-top:-150px; /* half of the width */ margin-left:-30px; /* half of the height */} Enjoy! A: By using the transform property we can do a vertically centered div easily. .main-div { background: none repeat scroll 0 0 #999; font-size: 18px; height: 450px; max-width: 850px; padding: 15px; } .vertical-center { background: none repeat scroll 0 0 #1FA67A; color: #FFFFFF; padding: 15px; position: relative; top: 50%; transform: translateY(-50%); -moz-transform: translateY(-50%); -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); -o-transform: translateY(-50%); } <div class="main-div"> <div class="vertical-center"> <span>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</span> </div> </div> See here for full article A: The best thing to do would be: #vertalign{ height: 300px; width: 300px; position: absolute; top: calc(50vh - 150px); } 150 pixels because that's half of the div's height in this case. A: Declare this Mixin: @mixin vertical-align($position: relative) { position: $position; top: 50%; -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); transform: translateY(-50%); } Then include it in your element: .element{ @include vertical-align(); } A: This is by far the easiest approach and works on non-blocking elements as well. The only downside is it's Flexbox, thus, older browsers will not support this. <div class="sweet-overlay"> <img class="centered" src="http://jimpunk.com/Loading/loading83.gif" /> </div> Link to CodePen: http://codepen.io/damianocel/pen/LNOdRp The important point here is, for vertical centering, we need to define a parent element (container) and the img must have a smaller height than the parent element. A: This method doesn't use any transform. So it doesn't have a problem with the output becoming blurry. position: absolute; width: 100vw; top: 25%; bottom: 25%; text-align: center; A: Since each time I need to center div vertically I google for it over and over again and this answer always comes first I'll leave this for future me (since none of the provided solutions fit my need well): So if one is already using bootstrap this can be done as below: <div style="min-height: 100vh;" class="align-items-center row"> <div class="col" style="margin: auto; max-width: 750px;"> //optional style to center horizontally as well //content goes here </div> </div> A: Centering things is one of the most difficult aspects of CSS. The methods themselves usually aren't difficult to understand. Instead, it's more due to the fact that there are so many ways to center things. The method you use can vary depending on the HTML element you're trying to center, or whether you're centering it horizontally or vertically. Center Horizontally Centering elements horizontally is generally easier than centering them vertically. Here are some common elements you may want to center horizontally and different ways to do it. Center Text with the CSS Text-Align Center Property To center text or links horizontally, just use the text-align property with the value center: HTML <div class="container"> <p>Hello, (centered) World!</p> </div> CSS .container { font-family: arial; font-size: 24px; margin: 25px; width: 350px; height: 200px; outline: dashed 1px black; } p { /* Center horizontally*/ text-align: center; } Center a Div with CSS Margin Auto Use the shorthand margin property with the value 0 auto to center block-level elements like a div horizontally: HTML <div class="container"> <div class="child"></div> </div> CSS .container { font-family: arial; font-size: 24px; margin: 25px; width: 350px; height: 200px; outline: dashed 1px black; } .child { width: 50px; height: 50px; background-color: red; /* Center horizontally*/ margin: 0 auto; } Center a Div Horizontally with Flexbox Flexbox is the most modern way to center things on the page, and makes designing responsive layouts much easier than it used to be. However, it's not fully supported in some legacy browsers like Internet Explorer. To center an element horizontally with Flexbox, just apply display: flex and justify-content: center to the parent element: HTML <div class="container"> <div class="child"></div> </div> CSS .container { font-family: arial; font-size: 24px; margin: 25px; width: 350px; height: 200px; outline: dashed 1px black; /* Center child horizontally*/ display: flex; justify-content: center; } .child { width: 50px; height: 50px; background-color: red; } Center Vertically Centering elements vertically without modern methods like Flexbox can be a real chore. Here we'll go over some of the older methods to center things vertically first, then show you how to do it with Flexbox. How to Center a Div Vertically with CSS Absolute Positioning and Negative Margins For a long time, this was the go-to way to center things vertically. For this method, you must know the height of the element you want to center. First, set the position property of the parent element to relative. Then for the child element, set the position property to absolute and top to 50%: HTML <div class="container"> <div class="child"></div> </div> CSS .container { font-family: arial; font-size: 24px; margin: 25px; width: 350px; height: 200px; outline: dashed 1px black; /* Setup */ position: relative; } .child { width: 50px; height: 50px; background-color: red; /* Center vertically */ position: absolute; top: 50%; } But that really just vertically centers the top edge of the child element. To truly center the child element, set the margin-top property to -(half the child element's height): .container { font-family: arial; font-size: 24px; margin: 25px; width: 350px; height: 200px; outline: dashed 1px black; /* Setup */ position: relative; } .child { width: 50px; height: 50px; background-color: red; /* Center vertically */ position: absolute; top: 50%; margin-top: -25px; /* Half this element's height */ } Center a Div Vertically with Transform and Translate If you don't know the height of the element you want to center (or even if you do), this method is a nifty trick. This method is very similar to the negative margins method above. Set the position property of the parent element to relative. For the child element, set the position property to absolute and set top to 50%. Now instead of using a negative margin to truly center the child element, just use transform: translate(0, -50%): HTML <div class="container"> <div class="child"></div> </div> CSS .container { font-family: arial; font-size: 24px; margin: 25px; width: 350px; height: 200px; outline: dashed 1px black; /* Setup */ position: relative; } .child { width: 50px; height: 50px; background-color: red; /* Center vertically */ position: absolute; top: 50%; transform: translate(0, -50%); } Note that translate(0, -50%) is shorthand for translateX(0) and translateY(-50%). You could also write transform: translateY(-50%) to center the child element vertically. Center Both Vertically and Horizontally Center a Div Vertically and Horizontally with CSS Absolute Positioning and Negative Margins This is very similar to the method above to center an element vertically. Like last time, you must know the width and height of the element you want to center. Set the position property of the parent element to relative. Then set the child's position property to absolute, top to 50%, and left to 50%. This just centers the top left corner of the child element vertically and horizontally. To truly center the child element, apply a negative top margin set to half the child element's height, and a negative left margin set to half the child element's width: HTML <div class="container"> <div class="child"></div> </div> CSS .container { font-family: arial; font-size: 24px; margin: 25px; width: 350px; height: 200px; outline: dashed 1px black; /* Setup */ position: relative; } .child { width: 50px; height: 50px; background-color: red; /* Center vertically and horizontally */ position: absolute; top: 50%; left: 50%; margin: -25px 0 0 -25px; /* Apply negative top and left margins to truly center the element */ }
How can I vertically center a div element for all browsers using CSS?
I want to center a div vertically with CSS. I don't want tables or JavaScript, but only pure CSS. I found some solutions, but all of them are missing Internet Explorer 6 support. <body> <div>Div to be aligned vertically</div> </body> How can I center a div vertically in all major browsers, including Internet Explorer 6?
[ "Below is the best all-around solution I could build to vertically and horizontally center a fixed-width, flexible height content box. It was tested and worked for recent versions of Firefox, Opera, Chrome, and Safari.\n\n\n.outer {\n display: table;\n position: absolute;\n top: 0;\n left: 0;\n height: 100%;\n width: 100%;\n}\n\n.middle {\n display: table-cell;\n vertical-align: middle;\n}\n\n.inner {\n margin-left: auto;\n margin-right: auto;\n width: 400px;\n /* Whatever width you want */\n}\n<div class=\"outer\">\n <div class=\"middle\">\n <div class=\"inner\">\n <h1>The Content</h1>\n <p>Once upon a midnight dreary...</p>\n </div>\n </div>\n</div>\n\n\n\nView A Working Example With Dynamic Content\nI built in some dynamic content to test the flexibility and would love to know if anyone sees any problems with it. It should work well for centered overlays also -- lightbox, pop-up, etc.\n", "The simplest way would be the following three lines of CSS:\n1) position: relative;\n2) top: 50%;\n3) transform: translateY(-50%);\nFollowing is an example:\n\n\ndiv.outer-div {\n height: 170px;\n width: 300px;\n background-color: lightgray;\n}\n\ndiv.middle-div {\n position: relative;\n top: 50%;\n -webkit-transform: translateY(-50%);\n -ms-transform: translateY(-50%);\n transform: translateY(-50%);\n}\n<div class='outer-div'>\n <div class='middle-div'>\n Test text\n </div>\n</div>\n\n\n\n", "One more I can't see on the list:\n.Center-Container {\n position: relative;\n height: 100%;\n}\n\n.Absolute-Center {\n width: 50%;\n height: 50%;\n overflow: auto;\n margin: auto;\n position: absolute;\n top: 0; left: 0; bottom: 0; right: 0;\n border: solid black;\n}\n\n\nCross-browser (including Internet Explorer 8 - Internet Explorer 10 without hacks!)\nResponsive with percentages and min-/max-\nCentered regardless of padding (without box-sizing!)\nheight must be declared (see Variable Height)\nRecommended setting overflow: auto to prevent content spillover (see Overflow)\n\nSource: Absolute Horizontal And Vertical Centering In CSS\n", "Now the Flexbox solution is a very easy way for modern browsers, so I recommend this for you:\n\n\n.container {\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100%;\n background: green;\n}\n\nbody,\nhtml {\n height: 100%;\n}\n<div class=\"container\">\n <div>Div to be aligned vertically</div>\n</div>\n\n\n\n", "Actually, you need two div's for vertical centering. The div containing the content must have a width and height.\n\n\n#container {\n position: absolute;\n top: 50%;\n margin-top: -200px;\n /* Half of #content height */\n left: 0;\n width: 100%;\n}\n\n#content {\n width: 624px;\n margin-left: auto;\n margin-right: auto;\n height: 395px;\n border: 1px solid #000000;\n}\n<div id=\"container\">\n <div id=\"content\">\n <h1>Centered div</h1>\n </div>\n</div>\n\n\n\nHere is the result.\n", "Edit 2020: only use this if you need to support old browsers like Internet Explorer 8 (which you should refuse to do ). If not, use Flexbox.\n\nThis is the simplest method I found and I use it all the time\n(jsFiddle demo here).\nThank Chris Coyier from CSS Tricks for this article.\n\n\nhtml, body{\n height: 100%;\n margin: 0;\n}\n.v-wrap{\n height: 100%;\n white-space: nowrap;\n text-align: center;\n}\n.v-wrap:before{\n content: \"\";\n display: inline-block;\n vertical-align: middle;\n width: 0;\n /* adjust for white space between pseudo element and next sibling */\n margin-right: -.25em;\n /* stretch line height */\n height: 100%;\n}\n.v-box{\n display: inline-block;\n vertical-align: middle;\n white-space: normal;\n}\n<div class=\"v-wrap\">\n <article class=\"v-box\">\n <p>This is how I've been doing it for some time</p>\n </article>\n</div>\n\n\n\nSupport starts with Internet Explorer 8.\n", "After a lot of research I finally found the ultimate solution. It works even for floated elements. View Source \n.element {\n position: relative;\n top: 50%;\n transform: translateY(-50%); /* or try 50% */\n}\n\n", "Use the CSS Flexbox align-items property to achieve this.\n\n\nhtml, body {\n height: 100%;\n}\n\nbody {\n display: flex;\n align-items: center;\n}\n<div>This is centered vertically</div>\n\n\n\n", "To center the div on a page, check the fiddle link.\n\n\n#vh {\r\n margin: auto;\r\n position: absolute;\r\n top: 0;\r\n left: 0;\r\n bottom: 0;\r\n right: 0;\r\n}\r\n.box{\r\n border-radius: 15px;\r\n box-shadow: 0 0 8px rgba(0, 0, 0, 0.4);\r\n padding: 25px;\r\n width: 100px;\r\n height: 100px;\r\n background: white;\r\n}\n<div id=\"vh\" class=\"box\">Div to be aligned vertically</div>\n\n\n\nAnother option is to use flex box, check the fiddle link.\n\n\n.vh {\r\n background-color: #ddd;\r\n height: 400px;\r\n align-items: center;\r\n display: flex;\r\n}\r\n.vh > div {\r\n width: 100%;\r\n text-align: center;\r\n vertical-align: middle;\r\n}\n<div class=\"vh\">\r\n <div>Div to be aligned vertically</div>\r\n</div>\n\n\n\nAnother option is to use a CSS 3 transform:\n\n\n#vh {\r\n position: absolute;\r\n top: 50%;\r\n left: 50%;\r\n /*transform: translateX(-50%) translateY(-50%);*/\r\n transform: translate(-50%, -50%);\r\n}\r\n.box{\r\n border-radius: 15px;\r\n box-shadow: 0 0 8px rgba(0, 0, 0, 0.4);\r\n padding: 25px;\r\n width: 100px;\r\n height: 100px;\r\n background: white;\r\n}\n<div id=\"vh\" class=\"box\">Div to be aligned vertically</div>\n\n\n\n", "The easiest solution is below:\n\n\n.outer-div{\n width: 100%;\n height: 200px;\n display: flex;\n border:1px solid #000;\n}\n.inner-div{\n margin: auto;\n text-align: center;\n border: 1px solid red;\n}\n<div class=\"outer-div\">\n <div class=\"inner-div\">\n Hey there!\n </div>\n</div>\n\n\n\n", "There are multiple ways to achieve this.\nUsing flex property of CSS.\nSolution #1\n\n\n.parent {\n width: 400px;\n height:200px;\n background: blue;\n display: flex;\n align-items: center;\n justify-content:center;\n}\n\n.child {\n width: 75px;\n height: 75px;\n background: yellow;\n}\n<div class=\"parent\">\n <div class=\"child\"></div>\n</div>\n\n\n\nor by using display: flex; and margin: auto;\nSolution #2\n\n\n.parent {\n width: 400px;\n height:200px;\n background: blue;\n display: flex;\n}\n\n.child {\n width: 75px;\n height: 75px;\n background: yellow;\n margin:auto;\n}\n<div class=\"parent\">\n <div class=\"child\"></div>\n</div>\n\n\n\nshow text center\nSolution #3\n\n\n.parent {\n width: 400px;\n height: 200px;\n background: yellow;\n display: flex;\n align-items: center;\n justify-content:center;\n}\n<div class=\"parent\">Center</div>\n\n\n\nUsing percentage(%) height and width.\nSolution #4\n\n\n.parent {\n position: absolute;\n height:100%;\n width:100%;\n background: blue;\n display: flex;\n align-items: center;\n justify-content:center;\n}\n\n.child {\n width: 75px;\n height: 75px;\n background: yellow;\n}\n<div class=\"parent\">\n <div class=\"child\"></div>\n</div> \n\n\n\n", "Unfortunately — but not surprisingly — the solution is more complicated than one would wish it to be. Also unfortunately, you'll need to use additional divs around the div you want vertically centered.\nFor standards-compliant browsers like Mozilla, Opera, Safari, etc. you need to set the outer div to be displayed as a table and the inner div to be displayed as a table-cell — which can then be vertically centered. For Internet Explorer, you need to position the inner div absolutely within the outer div and then specify the top as 50%. The following pages explain this technique well and provide some code samples too:\n\nVertical Centering in CSS\nVertical Centering in CSS with Unknown Height (Internet Explorer 7 compatible) (Archived article courtesy of the Wayback Machine)\n\nThere is also a technique to do the vertical centering using JavaScript. Vertical alignment of content with JavaScript & CSS demonstrates it.\n", "If someone cares for Internet Explorer 10 (and later) only, use Flexbox:\n\n\n.parent {\n width: 500px;\n height: 500px;\n background: yellow;\n\n display: -webkit-flex;\n display: -ms-flexbox;\n display: flex;\n\n -webkit-justify-content: center;\n -ms-flex-pack: center;\n justify-content: center;\n\n -webkit-align-items: center;\n -ms-flex-align: center;\n align-items: center;\n}\n\n.centered {\n width: 100px;\n height: 100px;\n background: blue;\n}\n<div class=\"parent\">\n <div class=\"centered\"></div>\n</div>\n\n\n\nFlexbox support: http://caniuse.com/flexbox\n", "A modern way to center an element vertically would be to use flexbox.\nYou need a parent to decide the height and a child to center.\nThe example below will center a div to the center within your browser. What's important (in my example) is to set height: 100% to body and html and then min-height: 100% to your container.\n\n\nbody, html {\n background: #F5F5F5;\n box-sizing: border-box;\n height: 100%;\n margin: 0;\n}\n\n#center_container {\n align-items: center;\n display: flex;\n min-height: 100%;\n}\n\n#center {\n background: white;\n margin: 0 auto;\n padding: 10px;\n text-align: center;\n width: 200px;\n}\n<div id='center_container'>\n <div id='center'>I am center.</div>\n</div>\n\n\n\n", "Centering only vertically\nIf you don't care about Internet Explorer 6 and 7, you can use a technique that involves two containers.\nThe outer container:\n\nshould have display: table;\n\nThe inner container:\n\nshould have display: table-cell;\nshould have vertical-align: middle;\n\nThe content box:\n\nshould have display: inline-block;\n\nYou can add any content you want to the content box without caring about its width or height!\nDemo:\n\n\nbody {\n margin: 0;\n}\n\n.outer-container {\n position: absolute;\n display: table;\n width: 100%; /* This could be ANY width */\n height: 100%; /* This could be ANY height */\n background: #ccc;\n}\n\n.inner-container {\n display: table-cell;\n vertical-align: middle;\n}\n\n.centered-content {\n display: inline-block;\n background: #fff;\n padding: 20px;\n border: 1px solid #000;\n}\n<div class=\"outer-container\">\n <div class=\"inner-container\">\n <div class=\"centered-content\">\n Malcolm in the Middle\n </div>\n </div>\n</div>\n\n\n\nSee also this Fiddle!\n\nCentering horizontally and vertically\nIf you want to center both horizontally and vertically, you also need the following.\nThe inner container:\n\nshould have text-align: center;\n\nThe content box:\n\nshould re-adjust the horizontal text-alignment to for example text-align: left; or text-align: right;, unless you want text to be centered\n\nDemo:\n\n\nbody {\n margin: 0;\n}\n\n.outer-container {\n position: absolute;\n display: table;\n width: 100%; /* This could be ANY width */\n height: 100%; /* This could be ANY height */\n background: #ccc;\n}\n\n.inner-container {\n display: table-cell;\n vertical-align: middle;\n text-align: center;\n}\n\n.centered-content {\n display: inline-block;\n text-align: left;\n background: #fff;\n padding: 20px;\n border: 1px solid #000;\n}\n<div class=\"outer-container\">\n <div class=\"inner-container\">\n <div class=\"centered-content\">\n Malcolm in the Middle\n </div>\n </div>\n</div>\n\n\n\nSee also this Fiddle!\n", "\n\n.center {\r\n position: absolute;\r\n top: 50%;\r\n left: 50%;\r\n transform: translate(-50%, -50%); /* (x, y) => position */\r\n -ms-transform: translate(-50%, -50%); /* IE 9 */\r\n -webkit-transform: translate(-50%, -50%); /* Chrome, Safari, Opera */ \r\n}\r\n\r\n.vertical {\r\n position: absolute;\r\n top: 50%;\r\n //left: 0;\r\n transform: translate(0, -50%); /* (x, y) => position */\r\n}\r\n\r\n.horizontal {\r\n position: absolute;\r\n //top: 0;\r\n left: 50%;\r\n transform: translate(-50%, 0); /* (x, y) => position */\r\n}\r\n\r\ndiv {\r\n padding: 1em;\r\n background-color: grey; \r\n color: white;\r\n} \n<body>\r\n <div class=\"vertical\">Vertically left</div>\r\n <div class=\"horizontal\">Horizontal top</div>\r\n <div class=\"center\">Vertically Horizontal</div> \r\n</body>\n\n\n\nRelated: Center a Image\n", "It can be done in two ways\nbody{\nleft: 50%; \ntop:50%; \ntransform: translate(-50%, -50%); \nheight: 100%; \nwidth: 100%; \n}\n\n\nOR\nUsing flex\nbody {\n height:100%\n width:100%\n display: flex;\n justify-content: center;\n align-items: center;\n}\n\nalign-items:center; makes the content vertically center\njustify-content: center;makes the content horizontally center\n", "This is always where I go when I have to come back to this issue.\nFor those who don't want to make the jump:\n\nSpecify the parent container as position:relative or position:absolute.\nSpecify a fixed height on the child container.\nSet position:absolute and top:50% on the child container to move the top down to the middle of the parent.\nSet margin-top:-yy where yy is half the height of the child container to offset the item up. \n\nAn example of this in code:\n<style type=\"text/css\">\n #myoutercontainer {position:relative}\n #myinnercontainer {position:absolute; top:50%; height:10em; margin-top:-5em}\n</style>\n...\n<div id=\"myoutercontainer\">\n <div id=\"myinnercontainer\">\n <p>Hey look! I'm vertically centered!</p>\n <p>How sweet is this?!</p>\n </div>\n</div>\n\n", "I just wrote this CSS and to know more, please go through: This article with vertical align anything with just 3 lines of CSS.\n.element {\n position: relative;\n top: 50%;\n transform: perspective(1px) translateY(-50%);\n}\n\n", "For newcomers, please try:\ndisplay: flex;\nalign-items: center;\njustify-content: center;\n\n", "The three lines of code using transform works practically on modern browsers and Internet Explorer:\n.element{\n position: relative;\n top: 50%;\n transform: translateY(-50%);\n -moz-transform: translateY(-50%);\n -webkit-transform: translateY(-50%);\n -ms-transform: translateY(-50%);\n}\n\nI am adding this answer since I found some incompleteness in the previous version of this answer (and Stack Overflow won't allow me to simply comment).\n\n'position' relative messes up the styling if the current div is in the body and has no container div. However 'fixed' seems to work, but it obviously fixes the content in the center of the viewport\n\nAlso I used this styling for centering some overlay divs and found that in Mozilla all elements inside this transformed div had lost their bottom borders. Possibly a rendering issue. But adding just the minimal padding to some of them rendered it correctly. Chrome and Internet Explorer (surprisingly) rendered the boxes without any need for padding\n\n\n\n", "CSS Grid\n\n\nbody, html { margin: 0; }\r\n\r\nbody {\r\n display: grid;\r\n min-height: 100vh;\r\n align-items: center;\r\n}\n<div>Div to be aligned vertically</div>\n\n\n\n", ".center{\n display: grid;\n place-items: center;\n}\n\n", "I did it with this (change width, height, margin-top and margin-left accordingly):\n.wrapper {\n width: 960px;\n height: 590px;\n position: absolute;\n top: 50%;\n left: 50%;\n margin-top: -295px;\n margin-left: -480px;\n}\n\n<div class=\"wrapper\"> -- Content -- </div>\n\n", "The answer from Billbad only works with a fixed width of the .inner div.\nThis solution works for a dynamic width by adding the attribute text-align: center to the .outer div.\n\n\n.outer {\r\n position: absolute;\r\n display: table;\r\n width: 100%;\r\n height: 100%;\r\n text-align: center;\r\n}\r\n.middle {\r\n display: table-cell;\r\n vertical-align: middle;\r\n}\r\n.inner {\r\n text-align: center;\r\n display: inline-block;\r\n width: auto;\r\n}\n<div class=\"outer\">\r\n <div class=\"middle\">\r\n <div class=\"inner\">\r\n Content\r\n </div>\r\n </div>\r\n</div>\n\n\n\n", "Just do it: Add the class at your div:\n.modal {\n margin: auto;\n position: absolute;\n top: 0;\n right: 0;\n left: 0;\n bottom: 0;\n height: 240px;\n}\n\nAnd read this article for an explanation. Note: Height is necessary.\n", "Not answering for browser compatibility but to also mention the new Grid and the not so new Flexbox feature.\nGrid\nFrom: Mozilla - Grid Documentation - Align Div Vertically\nBrowser Support: Grid Browser Support\nCSS:\n.wrapper {\n display: grid;\n grid-template-columns: repeat(4, 1fr);\n grid-gap: 10px;\n grid-auto-rows: 200px;\n grid-template-areas: \n \". a a .\"\n \". a a .\";\n}\n.item1 {\n grid-area: a;\n align-self: center;\n justify-self: center;\n}\n\nHTML:\n<div class=\"wrapper\">\n <div class=\"item1\">Item 1</div>\n</div>\n\nFlexbox\nBrowser Support: Flexbox Browser Support\nCSS:\ndisplay: -webkit-box;\ndisplay: -moz-box;\ndisplay: -ms-flexbox;\ndisplay: -webkit-flex;\ndisplay: flex;\nalign-items: center;\njustify-content: center;\n\n", "I think a solid solution for all browsers without using Flexbox - \"align-items: center;\" is a combination of display: table and vertical-align: middle;.\nCSS\n.vertically-center\n{\n display: table;\n\n width: 100%; /* Optional */\n height: 100%; /* Optional */\n}\n\n.vertically-center > div\n{\n display: table-cell;\n vertical-align: middle;\n}\n\nHTML\n<div class=\"vertically-center\">\n <div>\n <div style=\"border: 1px solid black;\">some text</div>\n </div>\n</div>\n\n‣Demo: https://jsfiddle.net/6m640rpp/\n", "Especially for parent divs with relative (unknown) height, the centering in the unknown solution works great for me. There are some really nice code examples in the article.\nIt was tested in Chrome, Firefox, Opera, and Internet Explorer.\n\n\n/* This parent can be any width and height */\r\n.block {\r\n text-align: center;\r\n}\r\n\r\n/* The ghost, nudged to maintain perfect centering */\r\n.block:before {\r\n content: '';\r\n display: inline-block;\r\n height: 100%;\r\n vertical-align: middle;\r\n margin-right: -0.25em; /* Adjusts for spacing */\r\n}\r\n\r\n/* The element to be centered, can\r\n also be of any width and height */ \r\n.centered {\r\n display: inline-block;\r\n vertical-align: middle;\r\n width: 300px;\r\n}\n<div style=\"width: 400px; height: 200px;\">\r\n <div class=\"block\" style=\"height: 90%; width: 100%\">\r\n <div class=\"centered\">\r\n <h1>Some text</h1>\r\n <p>Any other text...\"</p>\r\n </div> \r\n </div>\r\n</div>\n\n\n\n", "The contents can be easily centered by using Flexbox. The following code shows the CSS for the container inside which the contents needs to be centered:\n.absolute-center {\n display: -ms-flexbox;\n display: -webkit-flex;\n display: flex;\n\n -ms-flex-align: center;\n -webkit-align-items: center;\n -webkit-box-align: center;\n\n align-items: center;\n}\n\n", "There is a trick I found out recently: You need to use top 50%, and then you do a translateY(-50%).\n\n\n.outer-div {\n position: relative;\n height: 150px;\n width: 150px;\n background-color: red;\n}\n\n.centered-div {\n position: absolute;\n top: 50%;\n -webkit-transform: translateY(-50%);\n -ms-transform: translateY(-50%);\n transform: translateY(-50%);\n background-color: white;\n}\n<div class='outer-div'>\n <div class='centered-div'>\n Test text\n </div>\n</div>\n\n\n\n", "I find this one most useful... It gives the most accurate 'H' layout and is very simple to understand.\nThe benefit of this markup is that you define your content size in a single place -> \"PageContent\".\nThe Colors of the page background and its horizontal margins are defined in their corresponding divs.\n<div id=\"PageLayoutConfiguration\"\n style=\"display: table;\n position:absolute; top: 0px; right: 0px; bottom: 0px; left: 0px;\n width: 100%; height: 100%;\">\n\n <div id=\"PageBackground\"\n style=\"display: table-cell; vertical-align: middle;\n background-color: purple;\">\n\n <div id=\"PageHorizontalMargins\"\n style=\"width: 100%;\n background-color: seashell;\">\n\n <div id=\"PageContent\"\n style=\"width: 1200px; height: 620px; margin: 0 auto;\n background-color: grey;\">\n\n My content goes here...\n\n </div>\n </div>\n </div>\n</div>\n\nAnd here with CSS separated:\n<div id=\"PageLayoutConfiguration\">\n <div id=\"PageBackground\">\n <div id=\"PageHorizontalMargins\">\n <div id=\"PageContent\">\n my content goes here...\n </div>\n </div>\n </div>\n</div>\n\n#PageLayoutConfiguration{\n display: table;\n width: 100%;\n height: 100%;\n position: absolute;\n top: 0px;\n right: 0px;\n bottom: 0px;\n left: 0px;\n}\n\n#PageBackground{\n display: table-cell;\n vertical-align: middle;\n background-color: purple;\n}\n\n#PageHorizontalMargins{\n style=\"width: 100%;\n background-color: seashell;\n}\n#PageContent{\n width: 1200px;\n height: 620px;\n margin: 0 auto;\n background-color: grey;\n}\n\n", "I use this. It works in Internet Explorer 8 and later:\nheight:268px - for display:table acts like min-height.\nCSS:\n* {\n padding: 0;\n margin: 0;\n}\nbody {\n background: #cc9999;\n}\np {\n background: #f0ad4e;\n}\n#all {\n margin: 200px auto;\n}\n.ff-valign-wrap {\n display: table;\n width: 100%;\n height: 268px;\n background: #ff00ff;\n}\n.ff-valign {\n display: table-cell;\n height: 100%;\n vertical-align: middle;\n text-align: center;\n background: #ffff00;\n}\n\nHTML:\n<body>\n\n <div id=\"all\">\n <div class=\"ff-valign-wrap\">\n <div class=\"ff-valign\">\n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet, animi autem doloribus earum expedita, ipsum laboriosam nostrum nulla officiis optio quam quis quod sunt tempora tenetur veritatis vero voluptatem voluptates?</p>\n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet, animi autem doloribus earum expedita, ipsum laboriosam nostrum nulla officiis optio quam quis quod sunt tempora tenetur veritatis vero voluptatem voluptates?</p>\n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet, animi autem doloribus earum expedita, ipsum laboriosam nostrum nulla officiis optio quam quis quod sunt tempora tenetur veritatis vero voluptatem voluptates?</p>\n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet, animi autem doloribus earum expedita, ipsum laboriosam nostrum nulla officiis optio quam quis quod sunt tempora tenetur veritatis vero voluptatem voluptates?</p>\n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet, animi autem doloribus earum expedita, ipsum laboriosam nostrum nulla officiis optio quam quis quod sunt tempora tenetur veritatis vero voluptatem voluptates?</p>\n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet, animi autem doloribus earum expedita, ipsum laboriosam nostrum nulla officiis optio quam quis quod sunt tempora tenetur veritatis vero voluptatem voluptates?</p>\n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet, animi autem doloribus earum expedita, ipsum laboriosam nostrum nulla officiis optio quam quis quod sunt tempora tenetur veritatis vero voluptatem voluptates?</p>\n </div>\n </div>\n </div>\n\n</body>\n\n", "The following is working in my case and was tested in Firefox.\n#element {\n display: block;\n transform: translateY(50%);\n -moz-transform: translateY(50%);\n -webkit-transform: translateY(50%);\n -ms-transform: translateY(50%);\n}\n\nThe div's height and parent's height are dynamic. I use it when there are other elements on the same parent which is higher than the target element, where both are positioned horizontally inline.\n", "This solution worked for me for a block element (e.g., <div>). I used the colors to make the solution clearer.\nHTML:\n<main class=\"skin_orange\">\n <p>As you can the the element/box is vertically centered</p>\n <div class=\"bigBox skin_blue\">Blue Box</div>\n</main>\n\nCSS:\nmain {\n position: relative;\n width: 400px;\n height: 400px;\n}\n\n.skin_orange {\n outline: thin dotted red;\n background: orange;\n}\n\n.bigBox {\n width: 150px;\n height: 150px;\n position: absolute;\n top: 50%;\n transform: translateY(-50%);\n}\n\n.skin_blue {\n background-color: blue;\n}\n\nJSFiddle Code Demo\n", "I just found another way which worked for me:\n<div class=\"container\">\n <div class=\"vertical\">\n <h1>Welcome</h1>\n <h2>Aligned Vertically</h2>\n <a href=\"#\">Click ME</a>\n </div>\n</div>\n\nCSS\n.vertical{\n top: 50%;\n -webkit-transform: translateY(-50%);\n -ms-transform: translateY(-50%);\n transform: translateY(-50%);\n}\n\nMore information\n", "Vertical & Horizontal CENTER\nHTML\n<div id=\"dialog\">Centered Dialog</div>\n\nCSS\n#dialog {\n position:fixed; top:50%; left:50%; z-index:99991;\n width:300px; height:60px;\n margin-top:-150px; /* half of the width */\n margin-left:-30px; /* half of the height */}\n\nEnjoy!\n", "By using the transform property we can do a vertically centered div easily.\n\n\n.main-div {\r\n background: none repeat scroll 0 0 #999;\r\n font-size: 18px;\r\n height: 450px;\r\n max-width: 850px;\r\n padding: 15px;\r\n}\r\n\r\n.vertical-center {\r\n background: none repeat scroll 0 0 #1FA67A;\r\n color: #FFFFFF;\r\n padding: 15px;\r\n position: relative;\r\n top: 50%;\r\n transform: translateY(-50%);\r\n -moz-transform: translateY(-50%);\r\n -webkit-transform: translateY(-50%);\r\n -ms-transform: translateY(-50%);\r\n -o-transform: translateY(-50%);\r\n}\n<div class=\"main-div\">\r\n <div class=\"vertical-center\">\r\n <span>\"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\"</span>\r\n </div>\r\n</div>\n\n\n\nSee here for full article\n", "The best thing to do would be:\n#vertalign{\n height: 300px;\n width: 300px;\n position: absolute;\n top: calc(50vh - 150px); \n}\n\n150 pixels because that's half of the div's height in this case.\n", "Declare this Mixin:\n@mixin vertical-align($position: relative) {\n position: $position;\n top: 50%;\n -webkit-transform: translateY(-50%);\n -ms-transform: translateY(-50%);\n transform: translateY(-50%);\n}\n\nThen include it in your element:\n.element{\n @include vertical-align();\n}\n\n", "This is by far the easiest approach and works on non-blocking elements as well. The only downside is it's Flexbox, thus, older browsers will not support this.\n<div class=\"sweet-overlay\">\n <img class=\"centered\" src=\"http://jimpunk.com/Loading/loading83.gif\" />\n</div>\n\nLink to CodePen:\nhttp://codepen.io/damianocel/pen/LNOdRp\nThe important point here is, for vertical centering, we need to define a parent element (container) and the img must have a smaller height than the parent element.\n", "This method doesn't use any transform. So it doesn't have a problem with the output becoming blurry.\nposition: absolute;\nwidth: 100vw;\ntop: 25%;\nbottom: 25%;\ntext-align: center;\n\n", "Since each time I need to center div vertically I google for it over and over again and this answer always comes first I'll leave this for future me (since none of the provided solutions fit my need well):\nSo if one is already using bootstrap this can be done as below:\n<div style=\"min-height: 100vh;\" class=\"align-items-center row\">\n <div class=\"col\" style=\"margin: auto; max-width: 750px;\"> //optional style to center horizontally as well\n\n //content goes here\n\n </div>\n</div>\n\n", "Centering things is one of the most difficult aspects of CSS.\nThe methods themselves usually aren't difficult to understand. Instead, it's more due to the fact that there are so many ways to center things.\nThe method you use can vary depending on the HTML element you're trying to center, or whether you're centering it horizontally or vertically.\nCenter Horizontally\nCentering elements horizontally is generally easier than centering them vertically. Here are some common elements you may want to center horizontally and different ways to do it.\n\nCenter Text with the CSS Text-Align Center Property\n\nTo center text or links horizontally, just use the text-align property with the value center:\nHTML\n<div class=\"container\">\n <p>Hello, (centered) World!</p>\n</div>\n\nCSS\n.container {\n font-family: arial;\n font-size: 24px;\n margin: 25px;\n width: 350px;\n height: 200px;\n outline: dashed 1px black;\n}\n\np {\n /* Center horizontally*/\n text-align: center;\n}\n\nCenter a Div with CSS Margin Auto\nUse the shorthand margin property with the value 0 auto to center block-level elements like a div horizontally:\nHTML\n<div class=\"container\">\n <div class=\"child\"></div>\n</div>\n\nCSS\n.container {\n font-family: arial;\n font-size: 24px;\n margin: 25px;\n width: 350px;\n height: 200px;\n outline: dashed 1px black;\n}\n\n.child {\n width: 50px;\n height: 50px;\n background-color: red;\n /* Center horizontally*/\n margin: 0 auto;\n}\n\n\nCenter a Div Horizontally with Flexbox\n\nFlexbox is the most modern way to center things on the page, and makes designing responsive layouts much easier than it used to be. However, it's not fully supported in some legacy browsers like Internet Explorer.\nTo center an element horizontally with Flexbox, just apply display: flex and justify-content: center to the parent element:\nHTML\n<div class=\"container\">\n <div class=\"child\"></div>\n</div>\n\nCSS\n.container {\n font-family: arial;\n font-size: 24px;\n margin: 25px;\n width: 350px;\n height: 200px;\n outline: dashed 1px black;\n /* Center child horizontally*/\n display: flex;\n justify-content: center;\n}\n\n.child {\n width: 50px;\n height: 50px;\n background-color: red;\n}\n\nCenter Vertically\nCentering elements vertically without modern methods like Flexbox can be a real chore. Here we'll go over some of the older methods to center things vertically first, then show you how to do it with Flexbox.\n\nHow to Center a Div Vertically with CSS Absolute Positioning and Negative Margins\n\nFor a long time, this was the go-to way to center things vertically. For this method, you must know the height of the element you want to center.\nFirst, set the position property of the parent element to relative.\nThen for the child element, set the position property to absolute and top to 50%:\nHTML\n<div class=\"container\">\n <div class=\"child\"></div>\n</div>\n\nCSS\n.container {\n font-family: arial;\n font-size: 24px;\n margin: 25px;\n width: 350px;\n height: 200px;\n outline: dashed 1px black;\n /* Setup */\n position: relative;\n}\n\n.child {\n width: 50px;\n height: 50px;\n background-color: red;\n /* Center vertically */\n position: absolute;\n top: 50%;\n}\n\nBut that really just vertically centers the top edge of the child element.\nTo truly center the child element, set the margin-top property to -(half the child element's height):\n.container {\n font-family: arial;\n font-size: 24px;\n margin: 25px;\n width: 350px;\n height: 200px;\n outline: dashed 1px black;\n /* Setup */\n position: relative;\n}\n\n.child {\n width: 50px;\n height: 50px;\n background-color: red;\n /* Center vertically */\n position: absolute;\n top: 50%;\n margin-top: -25px; /* Half this element's height */\n}\n\n\nCenter a Div Vertically with Transform and Translate\n\nIf you don't know the height of the element you want to center (or even if you do), this method is a nifty trick.\nThis method is very similar to the negative margins method above. Set the position property of the parent element to relative.\nFor the child element, set the position property to absolute and set top to 50%. Now instead of using a negative margin to truly center the child element, just use transform: translate(0, -50%):\nHTML\n<div class=\"container\">\n <div class=\"child\"></div>\n</div>\n\nCSS\n.container {\n font-family: arial;\n font-size: 24px;\n margin: 25px;\n width: 350px;\n height: 200px;\n outline: dashed 1px black;\n /* Setup */\n position: relative;\n}\n\n.child {\n width: 50px;\n height: 50px;\n background-color: red;\n /* Center vertically */\n position: absolute;\n top: 50%;\n transform: translate(0, -50%);\n}\n\nNote that translate(0, -50%) is shorthand for translateX(0) and translateY(-50%). You could also write transform: translateY(-50%) to center the child element vertically.\nCenter Both Vertically and Horizontally\n\nCenter a Div Vertically and Horizontally with CSS Absolute Positioning and Negative Margins\n\nThis is very similar to the method above to center an element vertically. Like last time, you must know the width and height of the element you want to center.\nSet the position property of the parent element to relative.\nThen set the child's position property to absolute, top to 50%, and left to 50%. This just centers the top left corner of the child element vertically and horizontally.\nTo truly center the child element, apply a negative top margin set to half the child element's height, and a negative left margin set to half the child element's width:\nHTML\n<div class=\"container\">\n <div class=\"child\"></div>\n</div>\n\nCSS\n.container {\n font-family: arial;\n font-size: 24px;\n margin: 25px;\n width: 350px;\n height: 200px;\n outline: dashed 1px black;\n /* Setup */\n position: relative;\n}\n\n.child {\n width: 50px;\n height: 50px;\n background-color: red;\n /* Center vertically and horizontally */\n position: absolute;\n top: 50%;\n left: 50%;\n margin: -25px 0 0 -25px; /* Apply negative top and left margins to truly center the element */\n}\n\n" ]
[ 1535, 353, 310, 214, 144, 83, 80, 62, 39, 27, 24, 23, 21, 20, 15, 15, 12, 11, 9, 8, 7, 6, 5, 4, 4, 4, 3, 3, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ "To vertical-align a box in web page, including Internet Explorer 6, you may use:\n\nConditional comments\nThe haslayout property\ndisplay: table-value for others (and now flex)\n\nFiddle\n\n\n/* Internet Explorer 8 and others */\r\n.main {\r\n width: 500px;\r\n margin: auto;\r\n border: solid;\r\n}\r\nhtml {\r\n height: 100%;\r\n width: 100%;\r\n display: table;\r\n}\r\nbody {\r\n display: table-cell;\r\n vertical-align: middle;\r\n}\n<!-- [if lte IE 7]>\r\n<style> /* Should be in the <head> */\r\n html, body , .ie {\r\n height: 100%;\r\n text-align: center;\r\n white-space: nowrap;\r\n }\r\n .ie , .main{\r\n display: inline; /* Used with zoom in case you take a block element instead an inline element */\r\n zoom: 1;\r\n vertical-align: middle;\r\n text-align: left;\r\n white-space: normal;\r\n }\r\n</style>\r\n<b class=\"ie\"></b>\r\n<!--[endif]-->\r\n<div class=\"main\">\r\n <p>Fill it up with your content </p>\r\n <p><a href=\"https://jsfiddle.net/h8z24s5v/embedded/result/\">JsFiddle versie</a></p>\r\n</div>\n\n\n\nActually, Internet Explorer 7 would bring some trouble here being the only which will strictly apply height: 100% on HTML/body elements.\n\nBut, this is past and today and who still minds old versions of Internet Explorer, table/table-cell is just fine, display: flex is promising, and display: grid will show up some day.\n\nAnother nowdays example via flex \n\n\nhtml {\r\n display: flex;\r\n min-height: 100vh;/* or height */\r\n}\r\n\r\nbody {\r\n margin: auto;\r\n}\n<div>Div to be aligned vertically</div>\n\n\n\n", "I shared short version for who is want.\n\n\n.firstDivision {\n display: table;\n position: absolute;\n top: 0;\n left: 0;\n height: 100%;\n width: 100%;\n}\n\n.firstDivision .verticalCenter {\n text-align: center;\n display: table-cell;\n vertical-align: middle;\n}\n<div class=\"firstDivision\">\n <div class=\"verticalCenter\">\n Text was centered for Vertical.\n </div>\n</div>\n\n\n\n", "Here is a simple way, with almost no code:\nCSS code:\n.main{\n height: 100%;\n}\n\n.center{\n top: 50%;\n margin-top: 50%;\n}\n\nHTML code:\n<div class=\"main\">\n <div class=\"center\">\n Hi, I am centered!\n </div>\n</div>\n\nYour text will be in the middle of the page!\n", "This worked in my case (only tested in modern browsers):\n.textthatneedstobecentered {\n margin: auto;\n top: 0; bottom: 0;\n}\n\n" ]
[ -1, -1, -3, -4 ]
[ "alignment", "centering", "css", "html", "vertical_alignment" ]
stackoverflow_0000396145_alignment_centering_css_html_vertical_alignment.txt
Q: Plotting previous day high/low/close using pine script I have a pine script to draw previous day high/open/low as shown below: //@version=4 strategy("Plot Lines", overlay=true) PDH = security(syminfo.tickerid,"D",high) PDO = security(syminfo.tickerid,"D",open) PDL = security(syminfo.tickerid,"D",low) plot(PDH, title="High",color=color.red,linewidth=2,trackprice=true) plot(PDO, title="Open",color=color.yellow,linewidth=2,trackprice=true) plot(PDL, title="Low",color=color.green,linewidth=2,trackprice=true) The script work well but I only want previous day to be shown and ignore the others day before previous day so that the chart will not be that messy. This is what I get from the script above: As you can see, it plot the PDH/PDO/PDL for every previous day, but I just want previous day (one day) only. Any help or advice will be greatly appreciated! New Edited Result after apply the script A: Great answer by @vitruvius, but I wanted to add a little something. There's no need to draw lines and remove the old ones. You can just define them once, and move them on the last bar. Also, the values can be requested in one single security() call. //@version=5 indicator("Plot Lines", overlay=true) f_newLine(_color) => line.new(na, na, na, na, xloc.bar_time, extend.right, _color) f_moveLine(_line, _x, _y) => line.set_xy1(_line, _x, _y) line.set_xy2(_line, _x+1, _y) var line line_open = f_newLine(color.yellow) var line line_high = f_newLine(color.red) var line line_low = f_newLine(color.green) [pdo,pdh,pdl] = request.security(syminfo.tickerid,"D", [open,high,low]) if barstate.islast f_moveLine(line_open, time, pdo) f_moveLine(line_high, time, pdh) f_moveLine(line_low , time, pdl) Edit 1 //@version=5 indicator("Plot Lines", overlay=true) f_newLine(_color) => line.new(na, na, na, na, xloc.bar_time, extend.right, _color) f_moveLine(_line, _x, _y) => line.set_xy1(_line, _x, _y) line.set_xy2(_line, _x+1, _y) var line line_open = f_newLine(color.yellow) var line line_high = f_newLine(color.red) var line line_low = f_newLine(color.green) [pdo,pdh,pdl,pdt] = request.security(syminfo.tickerid,"D", [open[1],high[1],low[1],time[1]]) if barstate.islast f_moveLine(line_open, pdt, pdo) f_moveLine(line_high, pdt, pdh) f_moveLine(line_low , pdt, pdl) A: You can use the line() function instead of plot(). Draw the lines if it is the last bar, and delete the previous ones along the way. //@version=4 study("Plot Lines", overlay=true) PDH = security(syminfo.tickerid,"D",high) PDO = security(syminfo.tickerid,"D",open) PDL = security(syminfo.tickerid,"D",low) var line l_pdh = na, var line l_pdo = na, var line l_pdl = na if barstate.islast l_pdh := line.new(bar_index-1, PDH, bar_index, PDH, extend=extend.both, color=color.green) l_pdo := line.new(bar_index-1, PDO, bar_index, PDO, extend=extend.both, color=color.blue) l_pdl := line.new(bar_index-1, PDL, bar_index, PDL, extend=extend.both, color=color.red) line.delete(l_pdh[1]) line.delete(l_pdo[1]) line.delete(l_pdl[1]) A: Not exactly what you asked, but it could lead you in the right direction: //@version=5 indicator("My script", overlay = true) resolution = 'D' var float highSecurityValue = na var float lowSecurityValue = na var float closeSecurityValue = na fNoRepainting(timeframe, expression) => request.security(symbol = syminfo.tickerid, timeframe = timeframe, expression = expression[barstate.isrealtime ? 1 : 0], gaps = barmerge.gaps_off)[barstate.isrealtime ? 0 : 1] // PineCoders best practice. trimLineAtRange = '0000-0001' trimLinePlot = time('1', trimLineAtRange) plottingCondition = not trimLinePlot highRequest = fNoRepainting(resolution, high) lowRequest = fNoRepainting(resolution, low) closeRequest = fNoRepainting(resolution, close) if trimLinePlot[1] highSecurityValue := highRequest lowSecurityValue := lowRequest closeSecurityValue := closeRequest plot(plottingCondition ? highSecurityValue : na, title = 'H', style = plot.style_linebr, linewidth = 1, color = color.new(color.red, 0)) plot(plottingCondition ? lowSecurityValue : na, title = 'L', style = plot.style_linebr, linewidth = 1, color = color.new(color.lime, 0)) plot(plottingCondition ? closeSecurityValue : na, title = 'C', style = plot.style_linebr, linewidth = 1, color = color.new(color.orange, 0)) The result is (maybe a little more than your asked): I placed the vertical lines just to enhance the division of days. Notice that the horizontal line of each day, belongs to the value of the previous day. Green is lowest, red is highest, and orange is close (you can change it for open, but I do recommend you to use the closing value).
Plotting previous day high/low/close using pine script
I have a pine script to draw previous day high/open/low as shown below: //@version=4 strategy("Plot Lines", overlay=true) PDH = security(syminfo.tickerid,"D",high) PDO = security(syminfo.tickerid,"D",open) PDL = security(syminfo.tickerid,"D",low) plot(PDH, title="High",color=color.red,linewidth=2,trackprice=true) plot(PDO, title="Open",color=color.yellow,linewidth=2,trackprice=true) plot(PDL, title="Low",color=color.green,linewidth=2,trackprice=true) The script work well but I only want previous day to be shown and ignore the others day before previous day so that the chart will not be that messy. This is what I get from the script above: As you can see, it plot the PDH/PDO/PDL for every previous day, but I just want previous day (one day) only. Any help or advice will be greatly appreciated! New Edited Result after apply the script
[ "Great answer by @vitruvius, but I wanted to add a little something.\nThere's no need to draw lines and remove the old ones. You can just define them once, and move them on the last bar. Also, the values can be requested in one single security() call.\n//@version=5\nindicator(\"Plot Lines\", overlay=true)\n\nf_newLine(_color) => line.new(na, na, na, na, xloc.bar_time, extend.right, _color)\n\nf_moveLine(_line, _x, _y) =>\n line.set_xy1(_line, _x, _y)\n line.set_xy2(_line, _x+1, _y)\n\nvar line line_open = f_newLine(color.yellow)\nvar line line_high = f_newLine(color.red)\nvar line line_low = f_newLine(color.green)\n\n[pdo,pdh,pdl] = request.security(syminfo.tickerid,\"D\", [open,high,low])\n\nif barstate.islast\n f_moveLine(line_open, time, pdo)\n f_moveLine(line_high, time, pdh)\n f_moveLine(line_low , time, pdl)\n\nEdit 1\n//@version=5\nindicator(\"Plot Lines\", overlay=true)\n\nf_newLine(_color) => line.new(na, na, na, na, xloc.bar_time, extend.right, _color)\n\nf_moveLine(_line, _x, _y) =>\n line.set_xy1(_line, _x, _y)\n line.set_xy2(_line, _x+1, _y)\n\nvar line line_open = f_newLine(color.yellow)\nvar line line_high = f_newLine(color.red)\nvar line line_low = f_newLine(color.green)\n\n[pdo,pdh,pdl,pdt] = request.security(syminfo.tickerid,\"D\", [open[1],high[1],low[1],time[1]])\n\nif barstate.islast\n f_moveLine(line_open, pdt, pdo)\n f_moveLine(line_high, pdt, pdh)\n f_moveLine(line_low , pdt, pdl)\n\n", "You can use the line() function instead of plot().\nDraw the lines if it is the last bar, and delete the previous ones along the way.\n//@version=4\nstudy(\"Plot Lines\", overlay=true)\n\nPDH = security(syminfo.tickerid,\"D\",high)\nPDO = security(syminfo.tickerid,\"D\",open)\nPDL = security(syminfo.tickerid,\"D\",low)\n\nvar line l_pdh = na, var line l_pdo = na, var line l_pdl = na\n\nif barstate.islast\n l_pdh := line.new(bar_index-1, PDH, bar_index, PDH, extend=extend.both, color=color.green)\n l_pdo := line.new(bar_index-1, PDO, bar_index, PDO, extend=extend.both, color=color.blue)\n l_pdl := line.new(bar_index-1, PDL, bar_index, PDL, extend=extend.both, color=color.red)\n\nline.delete(l_pdh[1])\nline.delete(l_pdo[1])\nline.delete(l_pdl[1])\n\n\n", "Not exactly what you asked, but it could lead you in the right direction:\n//@version=5\nindicator(\"My script\", overlay = true)\n\nresolution = 'D'\nvar float highSecurityValue = na\nvar float lowSecurityValue = na\nvar float closeSecurityValue = na\n\nfNoRepainting(timeframe, expression) =>\n request.security(symbol = syminfo.tickerid, timeframe = timeframe, expression = expression[barstate.isrealtime ? 1 : 0], gaps = barmerge.gaps_off)[barstate.isrealtime ? 0 : 1] // PineCoders best practice.\n\ntrimLineAtRange = '0000-0001'\ntrimLinePlot = time('1', trimLineAtRange)\nplottingCondition = not trimLinePlot\n\n\nhighRequest = fNoRepainting(resolution, high)\nlowRequest = fNoRepainting(resolution, low)\ncloseRequest = fNoRepainting(resolution, close)\nif trimLinePlot[1]\n highSecurityValue := highRequest\n lowSecurityValue := lowRequest\n closeSecurityValue := closeRequest\n\nplot(plottingCondition ? highSecurityValue : na, title = 'H', style = plot.style_linebr, linewidth = 1, color = color.new(color.red, 0))\nplot(plottingCondition ? lowSecurityValue : na, title = 'L', style = plot.style_linebr, linewidth = 1, color = color.new(color.lime, 0))\nplot(plottingCondition ? closeSecurityValue : na, title = 'C', style = plot.style_linebr, linewidth = 1, color = color.new(color.orange, 0))\n\nThe result is (maybe a little more than your asked):\n\nI placed the vertical lines just to enhance the division of days.\nNotice that the horizontal line of each day, belongs to the value of the previous day. Green is lowest, red is highest, and orange is close (you can change it for open, but I do recommend you to use the closing value).\n" ]
[ 4, 2, 0 ]
[]
[]
[ "pine_script" ]
stackoverflow_0070843193_pine_script.txt
Q: Can you open a Python shell in Atom editor? You can open multiple tabs in the Atom editor, and have a multiple column layout as well. However, I am not being able to find out how to open a Python shell inside Atom so that I can load a Python script in the Python interactive shell. Does anyone know the steps to achieve this? A: The script package is likely what you want, it allows you to test your code by running part or all of it at a time: You can install it by opening the settings view with Ctrl-, switching to the Install panel and searching for script. You can also install from the command line by running: apm install script Technically what you are asking for is closer to the Terminal Plus package, as opens up a terminal pane from which you can load the python interactive environment by entering python. A: Good day. Type Python in the editor command line to use the interactive shell, exit() to leave interactive mode. It is that easy.
Can you open a Python shell in Atom editor?
You can open multiple tabs in the Atom editor, and have a multiple column layout as well. However, I am not being able to find out how to open a Python shell inside Atom so that I can load a Python script in the Python interactive shell. Does anyone know the steps to achieve this?
[ "The script package is likely what you want, it allows you to test your code by running part or all of it at a time:\n\nYou can install it by opening the settings view with Ctrl-, switching to the Install panel and searching for script. You can also install from the command line by running:\napm install script\n\nTechnically what you are asking for is closer to the Terminal Plus package, as opens up a terminal pane from which you can load the python interactive environment by entering python.\n\n", "Good day. Type Python in the editor command line to use the interactive shell, exit() to leave interactive mode. It is that easy.\n" ]
[ 31, 0 ]
[ "You need to go into: Packages --> Settings view --> Install packages and themes and then type \"terminal\" and install the one that starts with \"platformio\":\n\nInstall it and then you will have the + button down there.\n" ]
[ -1 ]
[ "atom_editor", "python" ]
stackoverflow_0033708758_atom_editor_python.txt
Q: Real use(problem) of Encrypting Environment Files with Laravel I was reading this article Encrypting Environment Files to encrypt and decrypt the .env content. as per the documentation, after running php artisan env:encrypt command, it generates a new .env.encrypted file, and also the output of the command is returning a Key. To decrypt the content, the command is looking for LARAVEL_ENV_ENCRYPTION_KEY which always changes as soon as I encrypt the content. So I don't understand the best use of this feature. Real Use case. Let's suppose, I have added a new variable in the .env file and encrypted the file. Now I shared this file with other team members, now I have to share the key as well to decrypt it. after decrypting, another team member adds a new variable and he has to follow the same routine. encrypt, and share the key. for decryption, you have to remove the .env file, and obviously LARAVEL_ENV_ENCRYPTION_KEY will never be found(or which might be changed because of the latest encryption), so you have to pass the --key option while decrypting the content. A: 'To decrypt the content, the command is looking for LARAVEL_ENV_ENCRYPTION_KEY which always changes as soon as I encrypt the content. So I don't understand the best use of this feature.' You can always provide your own encryption key while decrypting using: php artisan env:decrypt --force --key=3UVsEgGVK36XN82KKeyLFMhvosbZN1aF In addition, you can encrypt by provide the same encryption key using: php artisan env:encrypt --force --key=3UVsEgGVK36XN82KKeyLFMhvosbZN1aF The team members don't need to share a new encryption key every time they add a new environment variable to the .env file since they will always be using the same key to encrypt the edited .env file before adding/committing the regenerated .env.encrypted file to source control.
Real use(problem) of Encrypting Environment Files with Laravel
I was reading this article Encrypting Environment Files to encrypt and decrypt the .env content. as per the documentation, after running php artisan env:encrypt command, it generates a new .env.encrypted file, and also the output of the command is returning a Key. To decrypt the content, the command is looking for LARAVEL_ENV_ENCRYPTION_KEY which always changes as soon as I encrypt the content. So I don't understand the best use of this feature. Real Use case. Let's suppose, I have added a new variable in the .env file and encrypted the file. Now I shared this file with other team members, now I have to share the key as well to decrypt it. after decrypting, another team member adds a new variable and he has to follow the same routine. encrypt, and share the key. for decryption, you have to remove the .env file, and obviously LARAVEL_ENV_ENCRYPTION_KEY will never be found(or which might be changed because of the latest encryption), so you have to pass the --key option while decrypting the content.
[ "\n'To decrypt the content, the command is looking for LARAVEL_ENV_ENCRYPTION_KEY which always changes as soon as I encrypt\nthe content. So I don't understand the best use of this feature.'\n\nYou can always provide your own encryption key while decrypting using:\nphp artisan env:decrypt --force --key=3UVsEgGVK36XN82KKeyLFMhvosbZN1aF\nIn addition, you can encrypt by provide the same encryption key using:\nphp artisan env:encrypt --force --key=3UVsEgGVK36XN82KKeyLFMhvosbZN1aF\n\nThe team members don't need to share a new encryption key every time they add a new environment variable to the .env file since they will always be using the same key to encrypt the edited .env file before adding/committing the regenerated .env.encrypted file to source control.\n" ]
[ 0 ]
[]
[]
[ "encryption", "environment_variables", "laravel" ]
stackoverflow_0074663703_encryption_environment_variables_laravel.txt
Q: How to do fast memory copy from YUV_420_888 to NV21 Refer to this post, I want to write a method converting android YUV_420_888 to nv21. A more general implementation is needed although image from camera2 API is default NV21 in disguise. It is as follows: class NV21Image{ public byte[] y; public byte[] uv; } public static void cvtYUV420ToNV21(Image image, NV21Image nv21) { int width = image.getWidth(); int height = image.getHeight(); int ySize = width*height; ByteBuffer yBuffer = image.getPlanes()[0].getBuffer(); // Y ByteBuffer uBuffer = image.getPlanes()[1].getBuffer(); // U ByteBuffer vBuffer = image.getPlanes()[2].getBuffer(); // V int yRowStride = image.getPlanes()[0].getRowStride(); int vRowStride = image.getPlanes()[2].getRowStride(); int pixelStride = image.getPlanes()[2].getPixelStride(); assert(image.getPlanes()[0].getPixelStride() == 1); assert(image.getPlanes()[2].getRowStride() == image.getPlanes()[1].getRowStride()); assert(image.getPlanes()[2].getPixelStride() == image.getPlanes()[1].getPixelStride()); int pos = 0; int yBufferPos = -yRowStride; // not an actual position for (; pos<ySize; pos+=width) { yBufferPos += yRowStride; yBuffer.position(yBufferPos); yBuffer.get(nv21.y, pos, width); } pos = 0; for (int row=0; row<height/2; row++) { for (int col=0; col<vRowStride / pixelStride; col++) { int vuPos = col*pixelStride + row * vRowStride; nv21.uv[pos++] = vBuffer.get(vuPos); nv21.uv[pos++] = uBuffer.get(vuPos); } } } Above codes work as expected while very time-consuming for my live camera preview app(about 12ms per frame of 720p in Snapdragon 865 CPU), So I tried to accelerate it with JNI implementation to take profit from the byte-access and performance advantages: JNIEXPORT void JNICALL Java_com_example_Utils_nFillYUVArray(JNIEnv *env, jclass clazz, jbyteArray yArr, jbyteArray uvArr, jobject yBuf, jobject uBuf, jobject vBuf, jint yRowStride, jint vRowStride, jint vPixelStride, jint w, jint h) { auto ySrcPtr = (jbyte const*)env->GetDirectBufferAddress(yBuf); auto uSrcPtr = (jbyte const*)env->GetDirectBufferAddress(uBuf); auto vSrcPtr = (jbyte const*)env->GetDirectBufferAddress(vBuf); for(int row = 0; row < h; row++){ env->SetByteArrayRegion(yArr, row * w, w, ySrcPtr + row * yRowStride); } int pos = 0; for (int row=0; row<h/2; row++) { for (int col=0; col<w/2; col++) { int vuPos = col * vPixelStride + row * vRowStride; env->SetByteArrayRegion(uvArr, pos++, 1, vSrcPtr + vuPos); env->SetByteArrayRegion(uvArr, pos++, 1, uSrcPtr + vuPos); } } } However, it get worse than I expected(about 107ms per frame). And the most time-consuming part is interlaced memory copying for UV buffer So my problem is Whether any ways to accelerate and how to work it out? Update I accelerated it successfully(check my answer) when pixelStrides of U,V plane are both 1 or 2, I believe it is what happening in most cases. A: As @snachmsm said libyuv might help. I found an available API I420ToNV21, But it cannot receive pixelStride parameter, for YUV_420_888 does not guarantee no gaps exist between adjacent pixels in U,V planes. I accelerated it successfully with arm intrinsics when the pixelStride is 2(reduce to 2.7ms per frame): JNIEXPORT void JNICALL Java_com_example_Utils_nFillYUVArray(JNIEnv *env, jclass clazz, jbyteArray yArr, jbyteArray uvArr, jobject yBuf, jobject uBuf, jobject vBuf, jint yRowStride, jint vRowStride, jint uRowStride, jint pixelStride, jint width, jint height) { ///TODO: too time-consuming auto ySrcPtr = (jbyte const*)env->GetDirectBufferAddress(yBuf); auto uSrcPtr = (jbyte const*)env->GetDirectBufferAddress(uBuf); auto vSrcPtr = (jbyte const*)env->GetDirectBufferAddress(vBuf); for(int row = 0; row < height; row++){ env->SetByteArrayRegion(yArr, row * width, width, ySrcPtr + row * yRowStride); } constexpr int kStride = 8; const size_t nGroups = width / kStride; if(pixelStride == 2){ int8_t *line = (int8_t*)alignedAlloc(width, 64); int8_t *mask = (int8_t*)alignedAlloc(kStride, 64); memset(mask, 0, kStride); for(int i=0; i < kStride / 2; i++) { mask[i * 2] = -1; } int8x8_t vm = vld1_s8(mask); for(int row = 0; row < height / 2; row ++){ size_t vrowOff = row * vRowStride; size_t urowOff = row * uRowStride; for(int g = 0; g < nGroups; g++) { size_t colOff = g * kStride; int8x8_t v0 = vld1_s8(vSrcPtr + vrowOff + colOff); int8x8_t v1 = vld1_s8(uSrcPtr + urowOff + colOff); int8x8_t a0 = vand_s8(v0, vm); int16x4_t b1 = vreinterpret_s16_s8(vand_s8(v1, vm)); int8x8_t a1 = vreinterpret_s8_s16(vshl_n_s16(b1, 8)); int8x8_t r = vorr_s8(a0, a1); vst1_s8(line + colOff, r); } env->SetByteArrayRegion(uvArr, row * width, width, line); } free(mask); free(line); }else if(pixelStride == 1){ int8_t *line = (int8_t*)alignedAlloc(width, 64); for(int row = 0; row < height / 2; row ++) { size_t vrowOff = row * vRowStride; size_t urowOff = row * uRowStride; for(int g = 0; g < nGroups / 2; g++){ size_t colOff = g * kStride; int8x8_t a0 = vld1_s8(vSrcPtr + vrowOff + colOff); int8x16_t b0 = vreinterpretq_s8_s16(vmovl_s8(a0)); int8x8_t b01 = vget_high_s8(b0); int8x8_t b00 = vget_low_s8(b0); int8x8_t a1 = vld1_s8(uSrcPtr + urowOff + colOff); int16x8_t c1 = vmovl_s8(a1); int16x4_t c11 = vget_high_s16(c1); int16x4_t c10 = vget_low_s16(c1); int8x8_t b11 = vreinterpret_s8_s16(vshl_n_s16(c11, 8)); int8x8_t b10 = vreinterpret_s8_s16(vshl_n_s16(c10, 8)); a1 = vorr_s8(b11, b01); a0 = vorr_s8(b10, b00); vst1_s8(line + colOff, a0); vst1_s8(line + colOff + kStride, a1); } env->SetByteArrayRegion(uvArr, row * width, width, line); } free(line); } } Case of pixelStride == 1 is not tested sufficiently, but I believe it will work as expected.
How to do fast memory copy from YUV_420_888 to NV21
Refer to this post, I want to write a method converting android YUV_420_888 to nv21. A more general implementation is needed although image from camera2 API is default NV21 in disguise. It is as follows: class NV21Image{ public byte[] y; public byte[] uv; } public static void cvtYUV420ToNV21(Image image, NV21Image nv21) { int width = image.getWidth(); int height = image.getHeight(); int ySize = width*height; ByteBuffer yBuffer = image.getPlanes()[0].getBuffer(); // Y ByteBuffer uBuffer = image.getPlanes()[1].getBuffer(); // U ByteBuffer vBuffer = image.getPlanes()[2].getBuffer(); // V int yRowStride = image.getPlanes()[0].getRowStride(); int vRowStride = image.getPlanes()[2].getRowStride(); int pixelStride = image.getPlanes()[2].getPixelStride(); assert(image.getPlanes()[0].getPixelStride() == 1); assert(image.getPlanes()[2].getRowStride() == image.getPlanes()[1].getRowStride()); assert(image.getPlanes()[2].getPixelStride() == image.getPlanes()[1].getPixelStride()); int pos = 0; int yBufferPos = -yRowStride; // not an actual position for (; pos<ySize; pos+=width) { yBufferPos += yRowStride; yBuffer.position(yBufferPos); yBuffer.get(nv21.y, pos, width); } pos = 0; for (int row=0; row<height/2; row++) { for (int col=0; col<vRowStride / pixelStride; col++) { int vuPos = col*pixelStride + row * vRowStride; nv21.uv[pos++] = vBuffer.get(vuPos); nv21.uv[pos++] = uBuffer.get(vuPos); } } } Above codes work as expected while very time-consuming for my live camera preview app(about 12ms per frame of 720p in Snapdragon 865 CPU), So I tried to accelerate it with JNI implementation to take profit from the byte-access and performance advantages: JNIEXPORT void JNICALL Java_com_example_Utils_nFillYUVArray(JNIEnv *env, jclass clazz, jbyteArray yArr, jbyteArray uvArr, jobject yBuf, jobject uBuf, jobject vBuf, jint yRowStride, jint vRowStride, jint vPixelStride, jint w, jint h) { auto ySrcPtr = (jbyte const*)env->GetDirectBufferAddress(yBuf); auto uSrcPtr = (jbyte const*)env->GetDirectBufferAddress(uBuf); auto vSrcPtr = (jbyte const*)env->GetDirectBufferAddress(vBuf); for(int row = 0; row < h; row++){ env->SetByteArrayRegion(yArr, row * w, w, ySrcPtr + row * yRowStride); } int pos = 0; for (int row=0; row<h/2; row++) { for (int col=0; col<w/2; col++) { int vuPos = col * vPixelStride + row * vRowStride; env->SetByteArrayRegion(uvArr, pos++, 1, vSrcPtr + vuPos); env->SetByteArrayRegion(uvArr, pos++, 1, uSrcPtr + vuPos); } } } However, it get worse than I expected(about 107ms per frame). And the most time-consuming part is interlaced memory copying for UV buffer So my problem is Whether any ways to accelerate and how to work it out? Update I accelerated it successfully(check my answer) when pixelStrides of U,V plane are both 1 or 2, I believe it is what happening in most cases.
[ "As @snachmsm said libyuv might help. I found an available API I420ToNV21, But it cannot receive pixelStride parameter, for YUV_420_888 does not guarantee no gaps exist between adjacent pixels in U,V planes.\nI accelerated it successfully with arm intrinsics when the pixelStride is 2(reduce to 2.7ms per frame):\nJNIEXPORT void JNICALL\nJava_com_example_Utils_nFillYUVArray(JNIEnv *env, jclass clazz, jbyteArray yArr, jbyteArray uvArr,\n jobject yBuf, jobject uBuf, jobject vBuf,\n jint yRowStride, jint vRowStride, jint uRowStride, jint pixelStride,\n jint width, jint height) {\n ///TODO: too time-consuming\n auto ySrcPtr = (jbyte const*)env->GetDirectBufferAddress(yBuf);\n auto uSrcPtr = (jbyte const*)env->GetDirectBufferAddress(uBuf);\n auto vSrcPtr = (jbyte const*)env->GetDirectBufferAddress(vBuf);\n\n for(int row = 0; row < height; row++){\n env->SetByteArrayRegion(yArr, row * width, width, ySrcPtr + row * yRowStride);\n }\n\n constexpr int kStride = 8;\n const size_t nGroups = width / kStride;\n if(pixelStride == 2){\n int8_t *line = (int8_t*)alignedAlloc(width, 64);\n int8_t *mask = (int8_t*)alignedAlloc(kStride, 64);\n memset(mask, 0, kStride);\n for(int i=0; i < kStride / 2; i++) {\n mask[i * 2] = -1;\n }\n int8x8_t vm = vld1_s8(mask);\n\n for(int row = 0; row < height / 2; row ++){\n size_t vrowOff = row * vRowStride;\n size_t urowOff = row * uRowStride;\n for(int g = 0; g < nGroups; g++) {\n size_t colOff = g * kStride;\n int8x8_t v0 = vld1_s8(vSrcPtr + vrowOff + colOff);\n int8x8_t v1 = vld1_s8(uSrcPtr + urowOff + colOff);\n int8x8_t a0 = vand_s8(v0, vm);\n int16x4_t b1 = vreinterpret_s16_s8(vand_s8(v1, vm));\n int8x8_t a1 = vreinterpret_s8_s16(vshl_n_s16(b1, 8));\n int8x8_t r = vorr_s8(a0, a1);\n vst1_s8(line + colOff, r);\n }\n env->SetByteArrayRegion(uvArr, row * width, width, line);\n }\n\n free(mask);\n free(line);\n }else if(pixelStride == 1){\n int8_t *line = (int8_t*)alignedAlloc(width, 64);\n for(int row = 0; row < height / 2; row ++) {\n size_t vrowOff = row * vRowStride;\n size_t urowOff = row * uRowStride;\n for(int g = 0; g < nGroups / 2; g++){\n size_t colOff = g * kStride;\n int8x8_t a0 = vld1_s8(vSrcPtr + vrowOff + colOff);\n int8x16_t b0 = vreinterpretq_s8_s16(vmovl_s8(a0));\n int8x8_t b01 = vget_high_s8(b0);\n int8x8_t b00 = vget_low_s8(b0);\n\n int8x8_t a1 = vld1_s8(uSrcPtr + urowOff + colOff);\n int16x8_t c1 = vmovl_s8(a1);\n int16x4_t c11 = vget_high_s16(c1);\n int16x4_t c10 = vget_low_s16(c1);\n int8x8_t b11 = vreinterpret_s8_s16(vshl_n_s16(c11, 8));\n int8x8_t b10 = vreinterpret_s8_s16(vshl_n_s16(c10, 8));\n\n a1 = vorr_s8(b11, b01);\n a0 = vorr_s8(b10, b00);\n\n vst1_s8(line + colOff, a0);\n vst1_s8(line + colOff + kStride, a1);\n }\n\n env->SetByteArrayRegion(uvArr, row * width, width, line);\n }\n free(line);\n }\n}\n\nCase of pixelStride == 1 is not tested sufficiently, but I believe it will work as expected.\n" ]
[ 0 ]
[]
[]
[ "android", "c++", "java", "nv12_nv21", "yuv" ]
stackoverflow_0074653288_android_c++_java_nv12_nv21_yuv.txt
Q: Popup Alert dialog in react-native Android app while app is not in foreground I have a react-native app doing a long-running operation (doing BLE transfer of file to another device) that takes roughly 40-50 seconds. When the operation is complete, I pop an Alert dialog notifying the user that it completed, like this: Alert.alert('File transfer complete'); This all works great when the user waits for the transfer to complete. But if the user switches applications so the app is not in the foreground when the transfer completes, then switches back to the application, the dialog is not displayed. I expect the behavior to be that when they switch back the dialog is on the screen, and they have to click 'OK' to dismiss it (which is how it behaves when running on iOS). A: You can use an AppState event listener to show the dialog only when the app is in the foreground. There's a good example of it in the docs.
Popup Alert dialog in react-native Android app while app is not in foreground
I have a react-native app doing a long-running operation (doing BLE transfer of file to another device) that takes roughly 40-50 seconds. When the operation is complete, I pop an Alert dialog notifying the user that it completed, like this: Alert.alert('File transfer complete'); This all works great when the user waits for the transfer to complete. But if the user switches applications so the app is not in the foreground when the transfer completes, then switches back to the application, the dialog is not displayed. I expect the behavior to be that when they switch back the dialog is on the screen, and they have to click 'OK' to dismiss it (which is how it behaves when running on iOS).
[ "You can use an AppState event listener to show the dialog only when the app is in the foreground. There's a good example of it in the docs.\n" ]
[ 0 ]
[]
[]
[ "android", "react_native", "user_interface" ]
stackoverflow_0074662876_android_react_native_user_interface.txt
Q: telegram bot location python How to get location from user using telegram bot? I tried this: location_keyboard = KeyboardButton(text="send_location", request_location=True) contact_keyboard = KeyboardButton(text ='Share contact', request_contact=True) custom_keyboard = [[ location_keyboard], [contact_keyboard ]] A: You need to do the following: Call sendMessage function with the following params: { chat_id : 1234, text: "your message", reply_markup: {keyboard: [ [{text: "Send Your Mobile", request_contact: true}], [{text: "Send Your Location", request_location: true}] ] } } A: It appears user7870818 is using the library python-telegram-bot. For documentation see here. Here is a minimal working example of how to request location and contact from a user: # -*- coding: utf-8 -*- from telegram import ( Update, KeyboardButton, ReplyKeyboardMarkup ) from telegram.ext import ( Updater, CommandHandler, MessageHandler, CallbackContext, ) def request_location(update: Update, context: CallbackContext) -> None: keyboard = [[ KeyboardButton(text="Send Your Mobile", request_contact=True), KeyboardButton(text="Send Your Location", request_location=True), ] ] reply_markup = ReplyKeyboardMarkup(keyboard, one_time_keyboard=True, resize_keyboard=True) update.message.reply_text(f'Hello {update.effective_user.first_name}', reply_markup=reply_markup) def receive_location(update: Update, context: CallbackContext) -> None: print(f"Location is: {update.message.location}") def main(): updater = Updater("BOT_TOKEN") updater.dispatcher.add_handler(CommandHandler('location', request_location)) updater.dispatcher.add_handler(MessageHandler(None, receive_location)) updater.start_polling() updater.idle() if __name__=="__main__": main()
telegram bot location python
How to get location from user using telegram bot? I tried this: location_keyboard = KeyboardButton(text="send_location", request_location=True) contact_keyboard = KeyboardButton(text ='Share contact', request_contact=True) custom_keyboard = [[ location_keyboard], [contact_keyboard ]]
[ "You need to do the following:\nCall sendMessage function with the following params:\n{\n chat_id : 1234,\n text: \"your message\",\n reply_markup: \n {keyboard: \n [\n [{text: \"Send Your Mobile\", request_contact: true}],\n [{text: \"Send Your Location\", request_location: true}]\n ]\n }\n}\n\n", "It appears user7870818 is using the library python-telegram-bot. For documentation see here.\nHere is a minimal working example of how to request location and contact from a user:\n# -*- coding: utf-8 -*-\nfrom telegram import (\n Update,\n KeyboardButton,\n ReplyKeyboardMarkup\n )\nfrom telegram.ext import (\n Updater,\n CommandHandler,\n MessageHandler,\n CallbackContext,\n )\n \ndef request_location(update: Update, context: CallbackContext) -> None: \n keyboard = [[\n KeyboardButton(text=\"Send Your Mobile\", request_contact=True),\n KeyboardButton(text=\"Send Your Location\", request_location=True),\n ]\n ]\n reply_markup = ReplyKeyboardMarkup(keyboard, one_time_keyboard=True, resize_keyboard=True)\n update.message.reply_text(f'Hello {update.effective_user.first_name}',\n reply_markup=reply_markup)\n \ndef receive_location(update: Update, context: CallbackContext) -> None: \n print(f\"Location is: {update.message.location}\") \n\ndef main():\n updater = Updater(\"BOT_TOKEN\")\n updater.dispatcher.add_handler(CommandHandler('location', request_location))\n updater.dispatcher.add_handler(MessageHandler(None, receive_location)) \n updater.start_polling()\n updater.idle()\n\nif __name__==\"__main__\":\n main()\n\n" ]
[ 1, 0 ]
[]
[]
[ "bots", "location", "python", "telegram" ]
stackoverflow_0043424621_bots_location_python_telegram.txt
Q: Get a file path from the explorer menu to a Powershell variable I need to make a API call where file upload operation is required how can I prompt user to select the file from explorer and use the path after storing in a variable. I found similar question but it only works for folder. A: On Windows, you can take advantage the OpenFileDialog Windows Forms component: function Select-File { param([string]$Directory = $PWD) $dialog = [System.Windows.Forms.OpenFileDialog]::new() $dialog.InitialDirectory = (Resolve-Path $Directory).Path $dialog.RestoreDirectory = $true $result = $dialog.ShowDialog() if($result -eq [System.Windows.Forms.DialogResult]::OK){ return $dialog.FileName } } Then use like so: $path = Select-File if(Test-Path $path){ Upload-File -Path $path } A: Mathias's answear is great, there's just one issue. You first need to load the System.Windows.Forms assembly, as this article states!
Get a file path from the explorer menu to a Powershell variable
I need to make a API call where file upload operation is required how can I prompt user to select the file from explorer and use the path after storing in a variable. I found similar question but it only works for folder.
[ "On Windows, you can take advantage the OpenFileDialog Windows Forms component:\nfunction Select-File {\n param([string]$Directory = $PWD)\n\n $dialog = [System.Windows.Forms.OpenFileDialog]::new()\n\n $dialog.InitialDirectory = (Resolve-Path $Directory).Path\n $dialog.RestoreDirectory = $true\n\n $result = $dialog.ShowDialog()\n\n if($result -eq [System.Windows.Forms.DialogResult]::OK){\n return $dialog.FileName\n }\n}\n\nThen use like so:\n$path = Select-File\nif(Test-Path $path){\n Upload-File -Path $path\n}\n\n", "Mathias's answear is great, there's just one issue.\nYou first need to load the System.Windows.Forms assembly, as this article states!\n" ]
[ 1, 0 ]
[]
[]
[ "powershell", "windows" ]
stackoverflow_0069629187_powershell_windows.txt
Q: Why doesn't a module partion indirectly import the module imported by it's primary module interface unit? Consider the example MA.cpp: export module MA; import MB; export int MyFunA() { return 0; } MB.cpp: export module MB; export int MyFuncB() { return 0; } MA-PA.cpp: module MA:PA; import MA; int x = MyFuncB(); // #1 main.cpp: import MA; int main() { return 0; } CMakeLists.txt: project(ModuleTestProject) cmake_minimum_required(VERSION 3.5) add_executable(the_executable MB.cpp MA.cpp MA-PA.cpp main.cpp) When compiling the example with GCC(v 12.2): g++ -std=c++20 -fmodules-ts, it reports the error: MA-PA.cpp:5:9: error: 'MyFuncB' was not declared in this scope 5 | int x = MyFuncB(); | ^~~~~~~ When compiling with Visual Studio 2022(v 17.4.1), it reports a similar error: C3861 'MyFuncB': identifier not found ModuleTestProject When I deleted #1, both the two compilers could complie successfully. In the module partion MA:PA, I tried to invoke the function MyFuncB declared in MB. According to the error reported by compiler, it seems that MA:PA doesn't import MB.The result really confused me .After looking for related contents in C++ standard, I found the §10.3/7 said: Additionally, when a module-import-declaration in a module unit of some module M imports another module unit U of M, it also imports all translation units imported by non-exported module-import-declarations in the module unit purview of U.These rules can in turn lead to the importation of yet more translation units. I am not able to understand why MA:PA doesn't import MB. According to my understanding, MA:PA shall indirectly import MB. Here are the reasons. On one hand, MA:PA imports MA and MA imports MB. On the other hand, both MA.cpp and MA-PA.cpp are translation units of module MA. I had found the related question before I asked this question. The related question's answer says a primary module interface unit could import the module imported by its module partion indirectly. This answer is absolutely right because the C++ standard §10.3/7 applies to it. But the behavior of the compiler shows that when a module partion imports it's primary module interface unit,it doesn't also import the module imported by it's primary module interface unit. In my view, §10.3/7 also applies to this situation.So my question is why doesn't a module partion indirectly import the module imported by it's primary module interface unit? Could you please tell your opinion and point out my mistake about this question? Thank you very much. English is not my native language so that sometimes I may not able to express my meanings exactly.Sorry for the inconvenience and thanks for your understanding. A: Given that both GCC and VS2022 work just fine if you make your implementation unit a non-partition unit, this is definitely some kind of weird glitch in the compilers. It's clear from this experiment that the result of compiling the primary interface unit does contain all of those imports, even if importing it from outside of the module doesn't let you see them. And through non-partition implementation units, it's clear that importing from within the module is able to reach these things. It just doesn't work when it happens in an implementation partition unit. There's nothing in the standard to account for this, so it seems like a bug. But it is weird that both compilers not only have the same bug manifesting in the same way, the bug goes away under the same conditions (using non-partition implementation units).
Why doesn't a module partion indirectly import the module imported by it's primary module interface unit?
Consider the example MA.cpp: export module MA; import MB; export int MyFunA() { return 0; } MB.cpp: export module MB; export int MyFuncB() { return 0; } MA-PA.cpp: module MA:PA; import MA; int x = MyFuncB(); // #1 main.cpp: import MA; int main() { return 0; } CMakeLists.txt: project(ModuleTestProject) cmake_minimum_required(VERSION 3.5) add_executable(the_executable MB.cpp MA.cpp MA-PA.cpp main.cpp) When compiling the example with GCC(v 12.2): g++ -std=c++20 -fmodules-ts, it reports the error: MA-PA.cpp:5:9: error: 'MyFuncB' was not declared in this scope 5 | int x = MyFuncB(); | ^~~~~~~ When compiling with Visual Studio 2022(v 17.4.1), it reports a similar error: C3861 'MyFuncB': identifier not found ModuleTestProject When I deleted #1, both the two compilers could complie successfully. In the module partion MA:PA, I tried to invoke the function MyFuncB declared in MB. According to the error reported by compiler, it seems that MA:PA doesn't import MB.The result really confused me .After looking for related contents in C++ standard, I found the §10.3/7 said: Additionally, when a module-import-declaration in a module unit of some module M imports another module unit U of M, it also imports all translation units imported by non-exported module-import-declarations in the module unit purview of U.These rules can in turn lead to the importation of yet more translation units. I am not able to understand why MA:PA doesn't import MB. According to my understanding, MA:PA shall indirectly import MB. Here are the reasons. On one hand, MA:PA imports MA and MA imports MB. On the other hand, both MA.cpp and MA-PA.cpp are translation units of module MA. I had found the related question before I asked this question. The related question's answer says a primary module interface unit could import the module imported by its module partion indirectly. This answer is absolutely right because the C++ standard §10.3/7 applies to it. But the behavior of the compiler shows that when a module partion imports it's primary module interface unit,it doesn't also import the module imported by it's primary module interface unit. In my view, §10.3/7 also applies to this situation.So my question is why doesn't a module partion indirectly import the module imported by it's primary module interface unit? Could you please tell your opinion and point out my mistake about this question? Thank you very much. English is not my native language so that sometimes I may not able to express my meanings exactly.Sorry for the inconvenience and thanks for your understanding.
[ "Given that both GCC and VS2022 work just fine if you make your implementation unit a non-partition unit, this is definitely some kind of weird glitch in the compilers. It's clear from this experiment that the result of compiling the primary interface unit does contain all of those imports, even if importing it from outside of the module doesn't let you see them. And through non-partition implementation units, it's clear that importing from within the module is able to reach these things.\nIt just doesn't work when it happens in an implementation partition unit. There's nothing in the standard to account for this, so it seems like a bug.\nBut it is weird that both compilers not only have the same bug manifesting in the same way, the bug goes away under the same conditions (using non-partition implementation units).\n" ]
[ 0 ]
[]
[]
[ "c++", "c++20", "c++_modules", "language_lawyer", "visual_studio" ]
stackoverflow_0074608978_c++_c++20_c++_modules_language_lawyer_visual_studio.txt