qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,664,212
<p>As you know looping through each pixels and accessing their values with opencv takes too long. As a beginner I'm trying to learn opencv myself when I tried this approach it took me around 7-10 seconds of time to loop through image and perform operations.</p> <p>code is as below</p> <pre><code>original_image = cv2.imread(img_f) image = np.array(original_image) for y in range(image.shape[0]): for x in range(image.shape[1]): # remove grey background if 150 &lt;= image[y, x, 0] &lt;= 180 and \ 150 &lt;= image[y, x, 1] &lt;= 180 and \ 150 &lt;= image[y, x, 2] &lt;= 180: image[y, x, 0] = 0 image[y, x, 1] = 0 image[y, x, 2] = 0 # remove green dashes if image[y, x, 0] == 0 and \ image[y, x, 1] == 169 and \ image[y, x, 2] == 0: image[y, x, 0] = 0 image[y, x, 1] = 0 image[y, x, 2] = 0 </code></pre> <p>in above code i'm just trying to remove grey and green pixel colors.</p> <p>I found similar question asked <a href="https://stackoverflow.com/questions/63924991/opencv-python-pixel-by-pixel-loop-is-slow">here</a> but im not able to understand how to use numpy in my usecase as i'm beginner in python and numpy.</p> <p>Any help or suggestion for solving this will be appreciated thanks</p>
[ { "answer_id": 74664281, "author": "Phinnik", "author_id": 13980141, "author_profile": "https://Stackoverflow.com/users/13980141", "pm_score": 0, "selected": false, "text": "mask_gray = (\n (150 <= image[:, :, 0]) & (image[:, :, 0] <= 180) & \n (150 <= image[:, :, 1]) & (image[:, :, 1] <= 180) & \n (150 <= image[:, :, 2]) & (image[:, :, 2] <= 180)\n)\n\nimage[mask_gray] = 0\n\nmask_green = (\n (image[:, :, 0] == 0) &\n (image[:, :, 1] == 169) &\n (image[:, :, 2] == 0)\n)\n\nimage[mask_green] = 0\n mask_gray mask_green" }, { "answer_id": 74664369, "author": "kmkurn", "author_id": 20671531, "author_profile": "https://Stackoverflow.com/users/20671531", "pm_score": 3, "selected": true, "text": "# Remove grey background\nis_grey = ((150 <= image) & (image <= 180)).all(axis=2, keepdims=True)\nimage = np.where(is_grey, 0, image)\n\n# Remove green dashes\nis_green_dash = (image[..., 0] == 0) & (image[..., 1] == 169) & (image[..., 2] == 0)\nis_green_dash = is_green_dash[..., np.newaxis] # append a new dim at the end\nimage = np.where(is_green_dash, 0, image)\n np.where" }, { "answer_id": 74664521, "author": "chivalrous-nerd", "author_id": 7347835, "author_profile": "https://Stackoverflow.com/users/7347835", "pm_score": 1, "selected": false, "text": "cv2.inRange() cv2.bitwise_and() import cv2\nimport numpy as np\n\n# Read the image\noriginal_image = cv2.imread('image.jpg')\n\n# Define the colors to be removed as ranges of BGR values\ngrey_min = np.array([150, 150, 150], np.uint8)\ngrey_max = np.array([180, 180, 180], np.uint8)\ngreen_min = np.array([0, 0, 0], np.uint8)\ngreen_max = np.array([0, 169, 0], np.uint8)\n\n# Use inRange() to find pixels with the desired colors\ngrey_mask = cv2.inRange(original_image, grey_min, grey_max)\ngreen_mask = cv2.inRange(original_image, green_min, green_max)\n\n# Use bitwise_and() to remove the pixels with\n" }, { "answer_id": 74671453, "author": "Christoph Rackwitz", "author_id": 2602877, "author_profile": "https://Stackoverflow.com/users/2602877", "pm_score": 0, "selected": false, "text": "numba from numba import njit\n\n@njit\ndef your_function(input):\n ...\n return output\n\ninput = cv.imread(...) # yes this will shadow the builtin of the same name\noutput = your_function(input)\n your_function" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19669574/" ]
74,664,215
<p>I'm using the following function to determine if a winner has been crowned in connect four. Piece is whether they are green or red, last is the last played move (by piece), and name is the discord name of the person playing the game, as it is a file based connect four game. Board is a 2d array being made of all empty and filled squares. Due to the game being based in python, is this a effecient way to check?</p> <p>Examples: Piece: :green_circle:</p> <p>Board: [[':white_large_square:', ':white_large_square:', ':white_large_square:', ':white_large_square:', ':white_large_square:', ':white_large_square:', ':white_large_square:'], [':white_large_square:', ':white_large_square:', ':white_large_square:', ':white_large_square:', ':white_large_square:', ':white_large_square:', ':white_large_square:'], [':white_large_square:', ':white_large_square:', ':white_large_square:', ':white_large_square:', ':white_large_square:', ':white_large_square:', ':white_large_square:'], [':white_large_square:', ':white_large_square:', ':white_large_square:', ':white_large_square:', ':white_large_square:', ':white_large_square:', ':white_large_square:'], [':white_large_square:', ':white_large_square:', ':white_large_square:', ':white_large_square:', ':white_large_square:', ':white_large_square:', ':white_large_square:'], [':white_large_square:', ':green_circle:', ':white_large_square:', ':white_large_square:', ':white_large_square:', ':white_large_square:', ':white_large_square:']]</p> <p>Last: 5,1</p> <p>Discord View: <a href="https://i.stack.imgur.com/tpRd1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tpRd1.png" alt="enter image description here" /></a></p> <pre><code>def checks(piece, last, name): board = [] open_file = open(name, &quot;r&quot;) thing = open_file.readline() for x in range(6): value = open_file.readline() board.append(value.strip(&quot;\n&quot;).split(&quot;,&quot;)) open_file.close() cords = last.split(',') i = int(cords[0]) # row/x j = int(cords[1]) # column/y # checks for 000_ if j &gt; 2: if board[i][j - 1] == piece and board[i][j - 2] == piece and board[i][ j - 3] == piece: return piece + &quot; won&quot; # checks for _000 if j &lt; 4: if board[i][j + 1] == piece and board[i][j + 2] == piece and board[i][ j + 3] == piece: return piece + &quot; won&quot; # checks for downs if i &lt; 3: if board[i + 1][j] == piece and board[i + 2][j] == piece and board[ i + 3][j] == piece: return piece + &quot; won&quot; #check if you place in a 00_0 if not j in [0, 1, 6]: if board[i][j + 1] == piece and board[i][j - 1] == piece and board[i][ j - 2] == piece: return piece + &quot; won&quot; #check for 0_00 if not j in [0, 5, 6]: if board[i][j + 1] == piece and board[i][j + 2] == piece and board[i][ j - 1] == piece: return piece + &quot; won&quot; # check for top piece of a down-right diagonal if i &lt; 3 and j &lt; 4: if board[i + 1][j + 1] == piece and board[i + 2][j + 2] == piece and board[ i + 3][j + 3] == piece: return piece + &quot; won&quot; # check for bottom piece of a down-right diagonal if i &gt; 2 and j &gt; 2: if board[i - 1][j - 1] == piece and board[i - 2][j - 2] == piece and board[ i - 3][j - 3] == piece: return piece + &quot; won&quot; # check for top piece of down-left diagonal if i &lt; 3 and j &gt; 2: if board[i + 1][j - 1] == piece and board[i + 2][j - 2] == piece and board[ i + 3][j - 3] == piece: return piece + &quot; won&quot; # check for bottom piece of down-left diagonal if i &gt; 2 and j &lt; 4: if board[i - 1][j + 1] == piece and board[i - 2][j + 2] == piece and board[ i - 3][j + 3] == piece: return piece + &quot; won&quot; # check for 2nd top piece of down-right diagonal if i in [1,2,3] and j in [1,2,3,4]: if board[i - 1][j - 1] == piece and board[i +1 ][j + 1] == piece and board[i +2][j +2] == piece: return piece + &quot; won&quot; # check for 3rd piece of down-right diagonal if i in [2,3,4] and j in [2,3,4,5]: if board[i - 1][j - 1] == piece and board[i -2 ][j -2] == piece and board[i +1][j +1] == piece: return piece + &quot; won&quot; # check for 2nd piece of down-left diagonal if i in [1,2,3] and j in [2,3,4,5]: if board[i - 1][j + 1] == piece and board[i +1 ][j -1] == piece and board[i +2][j -2] == piece: return piece + &quot; won&quot; # check for 3rd piece in down-left diagonal if i in [2,3,4] and j in [1,2,3,4]: if board[i - 1][j + 1] == piece and board[i +1 ][j -1] == piece and board[i -2][j +2] == piece: return piece + &quot; won&quot; </code></pre>
[ { "answer_id": 74664281, "author": "Phinnik", "author_id": 13980141, "author_profile": "https://Stackoverflow.com/users/13980141", "pm_score": 0, "selected": false, "text": "mask_gray = (\n (150 <= image[:, :, 0]) & (image[:, :, 0] <= 180) & \n (150 <= image[:, :, 1]) & (image[:, :, 1] <= 180) & \n (150 <= image[:, :, 2]) & (image[:, :, 2] <= 180)\n)\n\nimage[mask_gray] = 0\n\nmask_green = (\n (image[:, :, 0] == 0) &\n (image[:, :, 1] == 169) &\n (image[:, :, 2] == 0)\n)\n\nimage[mask_green] = 0\n mask_gray mask_green" }, { "answer_id": 74664369, "author": "kmkurn", "author_id": 20671531, "author_profile": "https://Stackoverflow.com/users/20671531", "pm_score": 3, "selected": true, "text": "# Remove grey background\nis_grey = ((150 <= image) & (image <= 180)).all(axis=2, keepdims=True)\nimage = np.where(is_grey, 0, image)\n\n# Remove green dashes\nis_green_dash = (image[..., 0] == 0) & (image[..., 1] == 169) & (image[..., 2] == 0)\nis_green_dash = is_green_dash[..., np.newaxis] # append a new dim at the end\nimage = np.where(is_green_dash, 0, image)\n np.where" }, { "answer_id": 74664521, "author": "chivalrous-nerd", "author_id": 7347835, "author_profile": "https://Stackoverflow.com/users/7347835", "pm_score": 1, "selected": false, "text": "cv2.inRange() cv2.bitwise_and() import cv2\nimport numpy as np\n\n# Read the image\noriginal_image = cv2.imread('image.jpg')\n\n# Define the colors to be removed as ranges of BGR values\ngrey_min = np.array([150, 150, 150], np.uint8)\ngrey_max = np.array([180, 180, 180], np.uint8)\ngreen_min = np.array([0, 0, 0], np.uint8)\ngreen_max = np.array([0, 169, 0], np.uint8)\n\n# Use inRange() to find pixels with the desired colors\ngrey_mask = cv2.inRange(original_image, grey_min, grey_max)\ngreen_mask = cv2.inRange(original_image, green_min, green_max)\n\n# Use bitwise_and() to remove the pixels with\n" }, { "answer_id": 74671453, "author": "Christoph Rackwitz", "author_id": 2602877, "author_profile": "https://Stackoverflow.com/users/2602877", "pm_score": 0, "selected": false, "text": "numba from numba import njit\n\n@njit\ndef your_function(input):\n ...\n return output\n\ninput = cv.imread(...) # yes this will shadow the builtin of the same name\noutput = your_function(input)\n your_function" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20419122/" ]
74,664,244
<p>Editing my sister's tic-tac-toe code and she (also I) hit a snag. If Player one was to type a number greater than 9 or type a number that at was already used it will crash. Is there and recommended solution to problem.</p> <pre><code>printGameBoard(gameBoard); //User input requests while(true) { System.out.println(&quot;Enter your placement (1-9):&quot;); int playerPos = scan.nextInt(); while(playerPositions.contains(playerPos) || cpuPositions.contains(playerPositions) || cpuPositions.contains(playerPos)){ System.out.println(&quot;Position taken! Enter another position:&quot;); playerPos = scan.nextInt(); //Prevent user from printing on top of CPU while(playerPositions.contains(playerPos) || cpuPositions.contains(playerPos)){ System.out.println(&quot;Position taken! Enter another position:&quot;); playerPos= scan.nextInt(); } } placePiece(gameBoard, playerPos, &quot;player&quot;); String result = checkWinner(); if(result.length() &gt; 0) { System.out.println(result); break; } //CPU random positions (this what you are looking for) Random rand = new Random(); int cpuPos = rand.nextInt(9) + 1; while(playerPositions.contains(cpuPos) || cpuPositions.contains(cpuPos)){ cpuPos = rand.nextInt(9) + 1; } placePiece(gameBoard, cpuPos, &quot;cpu&quot;); printGameBoard(gameBoard); result = checkWinner(); if(result.length() &gt; 0){ System.out.println(result); break; } } } public static void placePiece(char[][] gameBoard, int pos, String user){ char symbol = ' '; if(user.equals(&quot;player&quot;)){ symbol = 'X'; playerPositions.add(pos); } else if(user.equals(&quot;cpu&quot;)){ symbol = 'O'; cpuPositions.add(pos); } switch(pos){ case 1: gameBoard[0][0] = symbol; break; case 2: gameBoard[0][2] = symbol; break; case 3: gameBoard[0][4] = symbol; break; case 4: gameBoard[2][0] = symbol; break; case 5: gameBoard[2][2] = symbol; break; case 6: gameBoard[2][4] = symbol; break; case 7: gameBoard[4][0] = symbol; break; case 8: gameBoard[4][2] = symbol; break; case 9: gameBoard[4][4] = symbol; break; default: break; } } public static String checkWinner(){ // (This define what a winng move looks like) List topRow = Arrays.asList(1, 2, 3); List midRow = Arrays.asList(4, 5, 6); List botRow = Arrays.asList(7, 8, 9); List leftCol = Arrays.asList(1, 4, 7); List midCol = Arrays.asList(2, 5, 8); List rightCol = Arrays.asList(3, 6, 9); List cross1 = Arrays.asList(1, 5, 9); List cross2 = Arrays.asList(7, 5, 3); List&lt;List&gt; winning = new ArrayList&lt;List&gt;(); winning.add(topRow); winning.add(midRow); winning.add(botRow); winning.add(leftCol); winning.add(midCol); winning.add(rightCol); winning.add(cross1); winning.add(cross2); for(List l : winning){ if(playerPositions.containsAll(l)){ return &quot;Congraduations you won!&quot;; } else if(cpuPositions.containsAll(l)){ return &quot;CPU wins! Sorry!&quot;; } else if(playerPositions.size() + cpuPositions.size() == 9){ return &quot;We are tied!&quot;; } } return &quot;&quot;; } public static void printGameBoard (char [][] gameBoard){ for(char[] row : gameBoard) { for(char c : row) { System.out.print(c); } System.out.println(); } } } PLAYGAME CODE import java.util.*; public class PlayGame { private int incrementer; private char location[]=new char[10]; private char gamer; public static void main(String args[]) { String ch; PlayGame Toe=new PlayGame(); do{ Toe.beginBoard(); Toe.startplay(); System.out.println (&quot;Would you like to play again (Enter 'Y')? &quot;); Scanner in =new Scanner(System.in); ch=in.nextLine(); System.out.println(&quot;ch value is &quot;+ch); }while (ch.equals(&quot;Y&quot;)); } public void beginBoard() { char locationdef[] = {'0','1', '2', '3', '4', '5', '6', '7', '8', '9'}; int i; incrementer = 0; gamer = 'X'; for (i=1; i&lt;10; i++) location[i]=locationdef[i]; presentBoard(); } public String presentBoard() { System.out.println( &quot;\n\n&quot; ); System.out.println( &quot;\n\n&quot; ); System.out.println( &quot;\n\n\t\t&quot; + location [1] + &quot; | &quot; +location [2]+ &quot; | &quot; +location [3]); System.out.println( &quot; \t\t | | &quot; ); System.out.println( &quot; \t\t ___|____|___ &quot; ); System.out.println( &quot;\n\n\t\t&quot; +location [4]+ &quot; | &quot; +location [5]+ &quot; | &quot; +location [6]); System.out.println( &quot; \t\t | | &quot; ); System.out.println( &quot; \t\t ___|____|___ &quot; ); System.out.println( &quot;\n\n\t\t&quot; +location [7]+ &quot; | &quot; +location [8]+ &quot; | &quot; +location [9]); System.out.println( &quot; \t\t | | &quot; ); System.out.println( &quot; \t\t | | &quot; ); System.out.println( &quot;\n\n&quot; ); return &quot;presentBoard&quot;; } public void startplay() { int center; char blank = ' '; System.out.println( &quot;gamer &quot; + locategamer() +&quot; will go first and be the letter 'X'&quot; ); do { presentBoard(); System.out.println( &quot;\n\n gamer &quot; + locategamer() +&quot; choose a location.&quot; ); boolean currentlocation = true; while (currentlocation) { Scanner in =new Scanner (System.in); center=in.nextInt(); currentlocation = checklocation(center); if(currentlocation==false) location[center]=locategamer(); } System.out.println( &quot;Excellent move&quot; ); presentBoard(); latergamer(); }while ( getWinner() == blank ); } public char getWinner() { char Winner = ' '; if (location[1] == 'X' &amp;&amp; location[2] == 'X' &amp;&amp; location[3] == 'X') Winner = 'X'; if (location[4] == 'X' &amp;&amp; location[5] == 'X' &amp;&amp; location[6] == 'X') Winner = 'X'; if (location[7] == 'X' &amp;&amp; location[8] == 'X' &amp;&amp; location[9] == 'X') Winner = 'X'; if (location[1] == 'X' &amp;&amp; location[4] == 'X' &amp;&amp; location[7] == 'X') Winner = 'X'; if (location[2] == 'X' &amp;&amp; location[5] == 'X' &amp;&amp; location[8] == 'X') Winner = 'X'; if (location[3] == 'X' &amp;&amp; location[6] == 'X' &amp;&amp; location[9] == 'X') Winner = 'X'; if (location[1] == 'X' &amp;&amp; location[5] == 'X' &amp;&amp; location[9] == 'X') Winner = 'X'; if (location[3] == 'X' &amp;&amp; location[5] == 'X' &amp;&amp; location[7] == 'X') Winner = 'X'; if (Winner == 'X' ) {System.out.println(&quot;gamer1 wins the game.&quot; ); return Winner; } if (location[1] == 'O' &amp;&amp; location[2] == 'O' &amp;&amp; location[3] == 'O') Winner = 'O'; if (location[4] == 'O' &amp;&amp; location[5] == 'O' &amp;&amp; location[6] == 'O') Winner = 'O'; if (location[7] == 'O' &amp;&amp; location[8] == 'O' &amp;&amp; location[9] == 'O') Winner = 'O'; if (location[1] == 'O' &amp;&amp; location[4] == 'O' &amp;&amp; location[7] == 'O') Winner = 'O'; if (location[2] == 'O' &amp;&amp; location[5] == 'O' &amp;&amp; location[8] == 'O') Winner = 'O'; if (location[3] == 'O' &amp;&amp; location[6] == 'O' &amp;&amp; location[9] == 'O') Winner = 'O'; if (location[1] == 'O' &amp;&amp; location[5] == 'O' &amp;&amp; location[9] == 'O') Winner = 'O'; if (location[3] == 'O' &amp;&amp; location[5] == 'O' &amp;&amp; location[7] == 'O') Winner = 'O'; if (Winner == 'O' ) { System.out.println( &quot;gamer2 wins the game.&quot; ); return Winner; } for(int i=1;i&lt;10;i++) { if(location[i]=='X' || location[i]=='O') { if(i==9) { char Draw='D'; System.out.println(&quot; Game is draw &quot;); return Draw; } continue; } else break; } return Winner; } public boolean checklocation(int center) { if (location[center] == 'X' || location[center] == 'O') { System.out.println(&quot;That location is already occupied please choose another location&quot;); return true; } else { return false; } } public void latergamer() { if (gamer == 'X') gamer = 'O'; else gamer = 'X'; } public String locatename() { return &quot; Game Tic Tac Toe&quot; ; } public char locategamer() { return gamer; } } </code></pre> <p>i found code to fix redundant input, but not the crash when input is higher than 9</p>
[ { "answer_id": 74664281, "author": "Phinnik", "author_id": 13980141, "author_profile": "https://Stackoverflow.com/users/13980141", "pm_score": 0, "selected": false, "text": "mask_gray = (\n (150 <= image[:, :, 0]) & (image[:, :, 0] <= 180) & \n (150 <= image[:, :, 1]) & (image[:, :, 1] <= 180) & \n (150 <= image[:, :, 2]) & (image[:, :, 2] <= 180)\n)\n\nimage[mask_gray] = 0\n\nmask_green = (\n (image[:, :, 0] == 0) &\n (image[:, :, 1] == 169) &\n (image[:, :, 2] == 0)\n)\n\nimage[mask_green] = 0\n mask_gray mask_green" }, { "answer_id": 74664369, "author": "kmkurn", "author_id": 20671531, "author_profile": "https://Stackoverflow.com/users/20671531", "pm_score": 3, "selected": true, "text": "# Remove grey background\nis_grey = ((150 <= image) & (image <= 180)).all(axis=2, keepdims=True)\nimage = np.where(is_grey, 0, image)\n\n# Remove green dashes\nis_green_dash = (image[..., 0] == 0) & (image[..., 1] == 169) & (image[..., 2] == 0)\nis_green_dash = is_green_dash[..., np.newaxis] # append a new dim at the end\nimage = np.where(is_green_dash, 0, image)\n np.where" }, { "answer_id": 74664521, "author": "chivalrous-nerd", "author_id": 7347835, "author_profile": "https://Stackoverflow.com/users/7347835", "pm_score": 1, "selected": false, "text": "cv2.inRange() cv2.bitwise_and() import cv2\nimport numpy as np\n\n# Read the image\noriginal_image = cv2.imread('image.jpg')\n\n# Define the colors to be removed as ranges of BGR values\ngrey_min = np.array([150, 150, 150], np.uint8)\ngrey_max = np.array([180, 180, 180], np.uint8)\ngreen_min = np.array([0, 0, 0], np.uint8)\ngreen_max = np.array([0, 169, 0], np.uint8)\n\n# Use inRange() to find pixels with the desired colors\ngrey_mask = cv2.inRange(original_image, grey_min, grey_max)\ngreen_mask = cv2.inRange(original_image, green_min, green_max)\n\n# Use bitwise_and() to remove the pixels with\n" }, { "answer_id": 74671453, "author": "Christoph Rackwitz", "author_id": 2602877, "author_profile": "https://Stackoverflow.com/users/2602877", "pm_score": 0, "selected": false, "text": "numba from numba import njit\n\n@njit\ndef your_function(input):\n ...\n return output\n\ninput = cv.imread(...) # yes this will shadow the builtin of the same name\noutput = your_function(input)\n your_function" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20671989/" ]
74,664,246
<p>I have two data frames:</p> <p>df1:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Index</th> <th>Date</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>2016-03-21 20:10:00</td> </tr> <tr> <td>1</td> <td>2016-03-22 21:09:00</td> </tr> <tr> <td>2</td> <td>2016-05-03 17:05:00</td> </tr> </tbody> </table> </div> <p>df2:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Index</th> <th>Date</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>2016-03-21 20:10:00</td> </tr> <tr> <td>1</td> <td>2016-03-21 21:00:00</td> </tr> <tr> <td>2</td> <td>2016-03-22 21:09:00</td> </tr> <tr> <td>3</td> <td>2016-05-03 17:05:00</td> </tr> <tr> <td>4</td> <td>2017-06-01 16:10:00</td> </tr> </tbody> </table> </div> <p>There's probably a really simple way to do this but how would I count the number of values in the df1 Date column that are also in the df2 Date column? (These are not unique value counts)</p>
[ { "answer_id": 74664281, "author": "Phinnik", "author_id": 13980141, "author_profile": "https://Stackoverflow.com/users/13980141", "pm_score": 0, "selected": false, "text": "mask_gray = (\n (150 <= image[:, :, 0]) & (image[:, :, 0] <= 180) & \n (150 <= image[:, :, 1]) & (image[:, :, 1] <= 180) & \n (150 <= image[:, :, 2]) & (image[:, :, 2] <= 180)\n)\n\nimage[mask_gray] = 0\n\nmask_green = (\n (image[:, :, 0] == 0) &\n (image[:, :, 1] == 169) &\n (image[:, :, 2] == 0)\n)\n\nimage[mask_green] = 0\n mask_gray mask_green" }, { "answer_id": 74664369, "author": "kmkurn", "author_id": 20671531, "author_profile": "https://Stackoverflow.com/users/20671531", "pm_score": 3, "selected": true, "text": "# Remove grey background\nis_grey = ((150 <= image) & (image <= 180)).all(axis=2, keepdims=True)\nimage = np.where(is_grey, 0, image)\n\n# Remove green dashes\nis_green_dash = (image[..., 0] == 0) & (image[..., 1] == 169) & (image[..., 2] == 0)\nis_green_dash = is_green_dash[..., np.newaxis] # append a new dim at the end\nimage = np.where(is_green_dash, 0, image)\n np.where" }, { "answer_id": 74664521, "author": "chivalrous-nerd", "author_id": 7347835, "author_profile": "https://Stackoverflow.com/users/7347835", "pm_score": 1, "selected": false, "text": "cv2.inRange() cv2.bitwise_and() import cv2\nimport numpy as np\n\n# Read the image\noriginal_image = cv2.imread('image.jpg')\n\n# Define the colors to be removed as ranges of BGR values\ngrey_min = np.array([150, 150, 150], np.uint8)\ngrey_max = np.array([180, 180, 180], np.uint8)\ngreen_min = np.array([0, 0, 0], np.uint8)\ngreen_max = np.array([0, 169, 0], np.uint8)\n\n# Use inRange() to find pixels with the desired colors\ngrey_mask = cv2.inRange(original_image, grey_min, grey_max)\ngreen_mask = cv2.inRange(original_image, green_min, green_max)\n\n# Use bitwise_and() to remove the pixels with\n" }, { "answer_id": 74671453, "author": "Christoph Rackwitz", "author_id": 2602877, "author_profile": "https://Stackoverflow.com/users/2602877", "pm_score": 0, "selected": false, "text": "numba from numba import njit\n\n@njit\ndef your_function(input):\n ...\n return output\n\ninput = cv.imread(...) # yes this will shadow the builtin of the same name\noutput = your_function(input)\n your_function" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20543897/" ]
74,664,257
<p>Could you tell me the way to refresh data on RecycleView on Fragment. On DialogFragment, there are some TextInputEditText, and users could change the data. After users closed DialogFragment with dismiss(), RecycleView isn't changed.</p> <p>Tried to use Intetnt back to RecycleView, but I think it is not correct way. My environment is JAVA, Android Studio.</p>
[ { "answer_id": 74664281, "author": "Phinnik", "author_id": 13980141, "author_profile": "https://Stackoverflow.com/users/13980141", "pm_score": 0, "selected": false, "text": "mask_gray = (\n (150 <= image[:, :, 0]) & (image[:, :, 0] <= 180) & \n (150 <= image[:, :, 1]) & (image[:, :, 1] <= 180) & \n (150 <= image[:, :, 2]) & (image[:, :, 2] <= 180)\n)\n\nimage[mask_gray] = 0\n\nmask_green = (\n (image[:, :, 0] == 0) &\n (image[:, :, 1] == 169) &\n (image[:, :, 2] == 0)\n)\n\nimage[mask_green] = 0\n mask_gray mask_green" }, { "answer_id": 74664369, "author": "kmkurn", "author_id": 20671531, "author_profile": "https://Stackoverflow.com/users/20671531", "pm_score": 3, "selected": true, "text": "# Remove grey background\nis_grey = ((150 <= image) & (image <= 180)).all(axis=2, keepdims=True)\nimage = np.where(is_grey, 0, image)\n\n# Remove green dashes\nis_green_dash = (image[..., 0] == 0) & (image[..., 1] == 169) & (image[..., 2] == 0)\nis_green_dash = is_green_dash[..., np.newaxis] # append a new dim at the end\nimage = np.where(is_green_dash, 0, image)\n np.where" }, { "answer_id": 74664521, "author": "chivalrous-nerd", "author_id": 7347835, "author_profile": "https://Stackoverflow.com/users/7347835", "pm_score": 1, "selected": false, "text": "cv2.inRange() cv2.bitwise_and() import cv2\nimport numpy as np\n\n# Read the image\noriginal_image = cv2.imread('image.jpg')\n\n# Define the colors to be removed as ranges of BGR values\ngrey_min = np.array([150, 150, 150], np.uint8)\ngrey_max = np.array([180, 180, 180], np.uint8)\ngreen_min = np.array([0, 0, 0], np.uint8)\ngreen_max = np.array([0, 169, 0], np.uint8)\n\n# Use inRange() to find pixels with the desired colors\ngrey_mask = cv2.inRange(original_image, grey_min, grey_max)\ngreen_mask = cv2.inRange(original_image, green_min, green_max)\n\n# Use bitwise_and() to remove the pixels with\n" }, { "answer_id": 74671453, "author": "Christoph Rackwitz", "author_id": 2602877, "author_profile": "https://Stackoverflow.com/users/2602877", "pm_score": 0, "selected": false, "text": "numba from numba import njit\n\n@njit\ndef your_function(input):\n ...\n return output\n\ninput = cv.imread(...) # yes this will shadow the builtin of the same name\noutput = your_function(input)\n your_function" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20672071/" ]
74,664,279
<p>So if someone needs to disable a submit button unless the user input is filled, he needs to do this:</p> <pre><code> $(function () { $('#login').attr('disabled', true); $('#userinput').change(function () { if ($('#userinput').val() != '') { $('#login').attr('disabled', false); } else { $('#login').attr('disabled', true); } }); }); </code></pre> <p>And this is the html:</p> <pre><code>&lt;input type=&quot;text&quot; name=&quot;userinput&quot; class=&quot;form-control&quot; id=&quot;userinput&quot;&gt; &lt;button id=&quot;login&quot; class=&quot;button&quot; disabled=&quot;disabled&quot;&gt;Submit&lt;/button&gt; </code></pre> <p>And this will work fine but the only problem exists, is that, the user MUST leave the input field in order to run the <code>change</code> event of Javascript.</p> <p>However I need to run this when user is still active on the input.</p> <p>So how to do that in Javascript?</p>
[ { "answer_id": 74664281, "author": "Phinnik", "author_id": 13980141, "author_profile": "https://Stackoverflow.com/users/13980141", "pm_score": 0, "selected": false, "text": "mask_gray = (\n (150 <= image[:, :, 0]) & (image[:, :, 0] <= 180) & \n (150 <= image[:, :, 1]) & (image[:, :, 1] <= 180) & \n (150 <= image[:, :, 2]) & (image[:, :, 2] <= 180)\n)\n\nimage[mask_gray] = 0\n\nmask_green = (\n (image[:, :, 0] == 0) &\n (image[:, :, 1] == 169) &\n (image[:, :, 2] == 0)\n)\n\nimage[mask_green] = 0\n mask_gray mask_green" }, { "answer_id": 74664369, "author": "kmkurn", "author_id": 20671531, "author_profile": "https://Stackoverflow.com/users/20671531", "pm_score": 3, "selected": true, "text": "# Remove grey background\nis_grey = ((150 <= image) & (image <= 180)).all(axis=2, keepdims=True)\nimage = np.where(is_grey, 0, image)\n\n# Remove green dashes\nis_green_dash = (image[..., 0] == 0) & (image[..., 1] == 169) & (image[..., 2] == 0)\nis_green_dash = is_green_dash[..., np.newaxis] # append a new dim at the end\nimage = np.where(is_green_dash, 0, image)\n np.where" }, { "answer_id": 74664521, "author": "chivalrous-nerd", "author_id": 7347835, "author_profile": "https://Stackoverflow.com/users/7347835", "pm_score": 1, "selected": false, "text": "cv2.inRange() cv2.bitwise_and() import cv2\nimport numpy as np\n\n# Read the image\noriginal_image = cv2.imread('image.jpg')\n\n# Define the colors to be removed as ranges of BGR values\ngrey_min = np.array([150, 150, 150], np.uint8)\ngrey_max = np.array([180, 180, 180], np.uint8)\ngreen_min = np.array([0, 0, 0], np.uint8)\ngreen_max = np.array([0, 169, 0], np.uint8)\n\n# Use inRange() to find pixels with the desired colors\ngrey_mask = cv2.inRange(original_image, grey_min, grey_max)\ngreen_mask = cv2.inRange(original_image, green_min, green_max)\n\n# Use bitwise_and() to remove the pixels with\n" }, { "answer_id": 74671453, "author": "Christoph Rackwitz", "author_id": 2602877, "author_profile": "https://Stackoverflow.com/users/2602877", "pm_score": 0, "selected": false, "text": "numba from numba import njit\n\n@njit\ndef your_function(input):\n ...\n return output\n\ninput = cv.imread(...) # yes this will shadow the builtin of the same name\noutput = your_function(input)\n your_function" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17730693/" ]
74,664,288
<p>I was building a React project with Vite and it was going great. I needed to add some charts and found out about the recharts package and really liked it so downloaded it into my project with the command <code>npm i recharts</code>.</p> <p>I get the following message:</p> <p><a href="https://i.stack.imgur.com/An8KL.jpg" rel="nofollow noreferrer">high severity vulnerabilities</a></p> <p>I then ran <code>npm audit</code>, <code>npm audit fix</code> and <code>npm audit fix --force</code> and got this:</p> <p><a href="https://i.stack.imgur.com/0k9AO.jpg" rel="nofollow noreferrer">lots of warnings</a></p> <p>Now when I try to start up my project with <code>npm run dev</code> I get this error in the console:</p> <pre><code>Uncaught TypeError: import_events.default is not a constructor </code></pre> <p>It says it's coming from a file called Events.js but I do not have such a file in my project.</p> <p>I tried running <code>npm audit fix --force</code> multiple times like my terminal told me to but it did not work.</p>
[ { "answer_id": 74664281, "author": "Phinnik", "author_id": 13980141, "author_profile": "https://Stackoverflow.com/users/13980141", "pm_score": 0, "selected": false, "text": "mask_gray = (\n (150 <= image[:, :, 0]) & (image[:, :, 0] <= 180) & \n (150 <= image[:, :, 1]) & (image[:, :, 1] <= 180) & \n (150 <= image[:, :, 2]) & (image[:, :, 2] <= 180)\n)\n\nimage[mask_gray] = 0\n\nmask_green = (\n (image[:, :, 0] == 0) &\n (image[:, :, 1] == 169) &\n (image[:, :, 2] == 0)\n)\n\nimage[mask_green] = 0\n mask_gray mask_green" }, { "answer_id": 74664369, "author": "kmkurn", "author_id": 20671531, "author_profile": "https://Stackoverflow.com/users/20671531", "pm_score": 3, "selected": true, "text": "# Remove grey background\nis_grey = ((150 <= image) & (image <= 180)).all(axis=2, keepdims=True)\nimage = np.where(is_grey, 0, image)\n\n# Remove green dashes\nis_green_dash = (image[..., 0] == 0) & (image[..., 1] == 169) & (image[..., 2] == 0)\nis_green_dash = is_green_dash[..., np.newaxis] # append a new dim at the end\nimage = np.where(is_green_dash, 0, image)\n np.where" }, { "answer_id": 74664521, "author": "chivalrous-nerd", "author_id": 7347835, "author_profile": "https://Stackoverflow.com/users/7347835", "pm_score": 1, "selected": false, "text": "cv2.inRange() cv2.bitwise_and() import cv2\nimport numpy as np\n\n# Read the image\noriginal_image = cv2.imread('image.jpg')\n\n# Define the colors to be removed as ranges of BGR values\ngrey_min = np.array([150, 150, 150], np.uint8)\ngrey_max = np.array([180, 180, 180], np.uint8)\ngreen_min = np.array([0, 0, 0], np.uint8)\ngreen_max = np.array([0, 169, 0], np.uint8)\n\n# Use inRange() to find pixels with the desired colors\ngrey_mask = cv2.inRange(original_image, grey_min, grey_max)\ngreen_mask = cv2.inRange(original_image, green_min, green_max)\n\n# Use bitwise_and() to remove the pixels with\n" }, { "answer_id": 74671453, "author": "Christoph Rackwitz", "author_id": 2602877, "author_profile": "https://Stackoverflow.com/users/2602877", "pm_score": 0, "selected": false, "text": "numba from numba import njit\n\n@njit\ndef your_function(input):\n ...\n return output\n\ninput = cv.imread(...) # yes this will shadow the builtin of the same name\noutput = your_function(input)\n your_function" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8926559/" ]
74,664,338
<p>I am trying to exclude certain words from dictionary file.</p> <pre><code># cat en.txt test testing access/p batch batch/n batches cross # cat exclude.txt test batch # grep -vf exclude.txt en.txt access/p cross </code></pre> <p>The words like &quot;testing&quot; and &quot;batches&quot; should be included in the results.</p> <pre><code>expected result: testing access/p batches cross </code></pre> <p>Because the word &quot;batch&quot; may or may not be followed by a slash &quot;/&quot;. There can be one or more tags after slash (n in this case). But the word &quot;batches&quot; is a different word and should not match with &quot;batch&quot;.</p>
[ { "answer_id": 74664612, "author": "Daweo", "author_id": 10785975, "author_profile": "https://Stackoverflow.com/users/10785975", "pm_score": 2, "selected": false, "text": "AWK en.txt test\ntesting\naccess/p\nbatch\nbatch/n\nbatches\ncross\n exclude.txt test\nbatch\n awk 'BEGIN{FS=\"/\"}FNR==NR{arr[$1];next}!($1 in arr)' exclude.txt en.txt\n testing\naccess/p\nbatches\ncross\n AWK / FS FNR==NR arr next ! arr" }, { "answer_id": 74665212, "author": "zdim", "author_id": 4653379, "author_profile": "https://Stackoverflow.com/users/4653379", "pm_score": 0, "selected": false, "text": "use warnings;\nuse strict;\nuse feature 'say';\nuse Path::Tiny; # for convenient read of the file\n\nmy $excl_file = 'exclude.txt';\n\nmy $re_excl = join '|', split /\\n/, path($excl_file)->slurp;\n$re_excl = qr($re_excl);\n\nwhile (<>) { \n if ( m{^ $re_excl (?:/.)? $}x ) { \n # say \"Skip printing (so filter out): $_\";\n next;\n }\n say;\n}\n program.pl dictionary-filename / (?:/.)? / (?:/.+)? (?:/[np])? n p (?:[^xy]+)?" }, { "answer_id": 74666820, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 2, "selected": true, "text": "grep -wvf exclude.txt en.txt\n -w --word-regexp -v --invert-match -f -f FILE testing\naccess/p\nbatches\ncross\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/139150/" ]
74,664,355
<p>i have html css js web-site and i have a little problem. I make html and css for my search_form. I need to scroll the site page to a current product when user enters the product name in the search engine. I suggest that when i'm inputting product name with class .text_2_Rapid_Item_1 my page is scrolling before product .Rapid_Item_1 with product name .text_2_Rapid_Item_1. How can i do that?</p> <pre><code> </code></pre> <pre><code>// scroll to current product (it didn't work) $(function () { $(&quot;.text_2_Rapid_Item_1&quot;).on(&quot;input&quot;, function () { $(&quot;.Rapid_Item_1&quot;).get(0).scrollIntoView({ block: &quot;start&quot;, behavior: &quot;smooth&quot;, }); }); }); </code></pre> <pre><code> </code></pre>
[ { "answer_id": 74664612, "author": "Daweo", "author_id": 10785975, "author_profile": "https://Stackoverflow.com/users/10785975", "pm_score": 2, "selected": false, "text": "AWK en.txt test\ntesting\naccess/p\nbatch\nbatch/n\nbatches\ncross\n exclude.txt test\nbatch\n awk 'BEGIN{FS=\"/\"}FNR==NR{arr[$1];next}!($1 in arr)' exclude.txt en.txt\n testing\naccess/p\nbatches\ncross\n AWK / FS FNR==NR arr next ! arr" }, { "answer_id": 74665212, "author": "zdim", "author_id": 4653379, "author_profile": "https://Stackoverflow.com/users/4653379", "pm_score": 0, "selected": false, "text": "use warnings;\nuse strict;\nuse feature 'say';\nuse Path::Tiny; # for convenient read of the file\n\nmy $excl_file = 'exclude.txt';\n\nmy $re_excl = join '|', split /\\n/, path($excl_file)->slurp;\n$re_excl = qr($re_excl);\n\nwhile (<>) { \n if ( m{^ $re_excl (?:/.)? $}x ) { \n # say \"Skip printing (so filter out): $_\";\n next;\n }\n say;\n}\n program.pl dictionary-filename / (?:/.)? / (?:/.+)? (?:/[np])? n p (?:[^xy]+)?" }, { "answer_id": 74666820, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 2, "selected": true, "text": "grep -wvf exclude.txt en.txt\n -w --word-regexp -v --invert-match -f -f FILE testing\naccess/p\nbatches\ncross\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20672142/" ]
74,664,379
<p>What is the best approach to audit the database for:</p> <ol> <li>Make a copy of the deleted and updated records.</li> <li>Save the date and user ID of the ones who did the DML which is (the ID) was saved on a session in ASP.NET</li> </ol> <p>My manager told me to add 3 extra columns to each table one for the <code>ID</code> of whom updated the record, one for whom deleted the record and the third has a boolean value 0 for deleted and 1 for active (not deleted yet), but I think this is a work around and I'm pretty sure there is a better way to do it .</p> <p>I was thinking of creating history tables and write an <code>AFTER DELETE</code> trigger that saves all the DML.</p> <p>Is this it or is there a more plain forward way?</p>
[ { "answer_id": 74664612, "author": "Daweo", "author_id": 10785975, "author_profile": "https://Stackoverflow.com/users/10785975", "pm_score": 2, "selected": false, "text": "AWK en.txt test\ntesting\naccess/p\nbatch\nbatch/n\nbatches\ncross\n exclude.txt test\nbatch\n awk 'BEGIN{FS=\"/\"}FNR==NR{arr[$1];next}!($1 in arr)' exclude.txt en.txt\n testing\naccess/p\nbatches\ncross\n AWK / FS FNR==NR arr next ! arr" }, { "answer_id": 74665212, "author": "zdim", "author_id": 4653379, "author_profile": "https://Stackoverflow.com/users/4653379", "pm_score": 0, "selected": false, "text": "use warnings;\nuse strict;\nuse feature 'say';\nuse Path::Tiny; # for convenient read of the file\n\nmy $excl_file = 'exclude.txt';\n\nmy $re_excl = join '|', split /\\n/, path($excl_file)->slurp;\n$re_excl = qr($re_excl);\n\nwhile (<>) { \n if ( m{^ $re_excl (?:/.)? $}x ) { \n # say \"Skip printing (so filter out): $_\";\n next;\n }\n say;\n}\n program.pl dictionary-filename / (?:/.)? / (?:/.+)? (?:/[np])? n p (?:[^xy]+)?" }, { "answer_id": 74666820, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 2, "selected": true, "text": "grep -wvf exclude.txt en.txt\n -w --word-regexp -v --invert-match -f -f FILE testing\naccess/p\nbatches\ncross\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18598052/" ]
74,664,396
<p>Hello im trying to make a oop function but im currently stuck on how can i inherit the <code>__init__</code> arguments of my parent class to the child class, is there a method that can i use to adapt the variable from my main to use in child?</p> <pre><code>class a: def __init__(self, name): self.name = name class b(a): def __init__(self, age): super().__init__() self.age = age </code></pre> <p>When i trying to use the <code>name</code> from the parent it errors.</p> <pre><code>b('joe', 40) &gt; Traceback (most recent call last): File &quot;&lt;string&gt;&quot;, line 11, in &lt;module&gt; TypeError: __init__() takes 2 positional arguments but 3 were given&gt; </code></pre>
[ { "answer_id": 74664612, "author": "Daweo", "author_id": 10785975, "author_profile": "https://Stackoverflow.com/users/10785975", "pm_score": 2, "selected": false, "text": "AWK en.txt test\ntesting\naccess/p\nbatch\nbatch/n\nbatches\ncross\n exclude.txt test\nbatch\n awk 'BEGIN{FS=\"/\"}FNR==NR{arr[$1];next}!($1 in arr)' exclude.txt en.txt\n testing\naccess/p\nbatches\ncross\n AWK / FS FNR==NR arr next ! arr" }, { "answer_id": 74665212, "author": "zdim", "author_id": 4653379, "author_profile": "https://Stackoverflow.com/users/4653379", "pm_score": 0, "selected": false, "text": "use warnings;\nuse strict;\nuse feature 'say';\nuse Path::Tiny; # for convenient read of the file\n\nmy $excl_file = 'exclude.txt';\n\nmy $re_excl = join '|', split /\\n/, path($excl_file)->slurp;\n$re_excl = qr($re_excl);\n\nwhile (<>) { \n if ( m{^ $re_excl (?:/.)? $}x ) { \n # say \"Skip printing (so filter out): $_\";\n next;\n }\n say;\n}\n program.pl dictionary-filename / (?:/.)? / (?:/.+)? (?:/[np])? n p (?:[^xy]+)?" }, { "answer_id": 74666820, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 2, "selected": true, "text": "grep -wvf exclude.txt en.txt\n -w --word-regexp -v --invert-match -f -f FILE testing\naccess/p\nbatches\ncross\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14740052/" ]
74,664,399
<p>i tried to make a function for averaging all the array in an object of another array, but however i tried i can't call the parameter for the function i make</p> <blockquote> </blockquote> <pre><code>let students = [randy, riziq, rama]; let randy = { name: 'Randy', score: [75, 80, 90] }; let riziq = { name: 'Riziq', score: [50, 90, 90] }; let rama = { name: 'Rama', score: [80, 75, 90] }; function average(/*students*/) { let avgScore = /*students's score avg*/ return /*students's name + &quot;&quot; + student's average*/ }; console.log(average(/*students*/)); </code></pre> <p>is there any way to call that?</p> <p>i tried to make a for loop to each of the props inside the students array but still i can't call that. i tried to sum all the student's score with array.reduce() of the students array and divide them with array.length</p>
[ { "answer_id": 74664504, "author": "Asraf", "author_id": 20361860, "author_profile": "https://Stackoverflow.com/users/20361860", "pm_score": 2, "selected": false, "text": "let students = [randy, riziq, rama]; let randy = {\n name: 'Randy',\n score: [75, 80, 90]\n};\nlet riziq = {\n name: 'Riziq',\n score: [50, 90, 90]\n};\nlet rama = {\n name: 'Rama',\n score: [80, 75, 90]\n};\n\nlet students = [randy, riziq, rama];\n\nfunction average(students) {\n return students.map(({name, score}) => {\n const total = score.reduce((a, b) => a + b,0);\n return `${name} ${total/score.length}`;\n});\n}\n\nconsole.log(average(students)); .map() .reduce()" }, { "answer_id": 74664553, "author": "Vatsal Patel", "author_id": 10363373, "author_profile": "https://Stackoverflow.com/users/10363373", "pm_score": 0, "selected": false, "text": "let randy = {\n name: 'Randy',\n score: [75, 80, 90]\n };\nlet riziq = {\n name: 'Riziq',\n score: [50, 90, 90]\n };\nlet rama = {\n name: 'Rama',\n score: [80, 75, 90]\n };\n let students = [randy, riziq, rama];\n \nfunction average(students) {\n var data = { \"averages\" : {}};\n var i;\n for (i = 0; i < students.length; ++i) {\n var total = 0;\n for (var ti = 0; ti < students[i].score.length; ti++) {\n total += students[i].score[ti] << 0;\n }\n var avg = total/students[i].score.length;\n \n data.averages[i] = { \n \"name\":students[i].name, \n \"average\":avg.toFixed(2), \n }; \n }\n \n return data;\n};\n \nconsole.log(average(students));" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20672275/" ]
74,664,400
<p>this is my code for a dropdown, I am using tailwindCSS and pure html,</p> <pre><code>&lt;li class=&quot;relative&quot; x-data=&quot;{isOpen:false}&quot;&gt; &lt;button @click=&quot;isOpen=!isOpen&quot; class=&quot; block text-sm font-bold outline-none focus:outline-none text-blue-900 &quot; href=&quot;#&quot;&gt; SERVICES&lt;/button&gt; &lt;div class=&quot;right-0 p-2 mt-1 bg-white rounded-md shadow lg:absolute&quot; :class=&quot;{'hidden':!isOpen'flex flex-col':isOpen}&quot; @click.away=&quot;isOpen = false&quot;&gt; &lt;a href=&quot;#&quot; class=&quot;flex p-2 font-medium text-gray-600 rounded-md hover:bg-gray-100 hover:text-black&quot;&gt;Categories&lt;/a&gt; &lt;a href=&quot;#&quot; class=&quot;flex p-2 font-medium text-gray-600 rounded-md hover:bg-gray-100 hover:text-black&quot;&gt;Inventories&lt;/a&gt; &lt;a href=&quot;#&quot; class=&quot;flex p-2 font-medium text-gray-600 rounded-md hover:bg-gray-100 hover:text-black&quot;&gt;Brands&lt;/a&gt; &lt;/div&gt; &lt;/li&gt; </code></pre> <p>I want to hide my dropdown by default and is should only open when someone hovers on it or when someone clicks on it. but right now it is still visible even though I have tried hiding it. Please see image for reference. and let know what am I doing wrong.<a href="https://i.stack.imgur.com/fJqbJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fJqbJ.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74664436, "author": "Code28", "author_id": 17574707, "author_profile": "https://Stackoverflow.com/users/17574707", "pm_score": 1, "selected": false, "text": ".\n\ndrop-down{\ndisplay:none;\n}\n.drop-down-parent:hover .drop-down{\n\ndisplay:block;\n\n}\n" }, { "answer_id": 74664768, "author": "MAYUR SANCHETI", "author_id": 12238257, "author_profile": "https://Stackoverflow.com/users/12238257", "pm_score": 0, "selected": false, "text": ".dropdown:hover .dropdown-menu {\n display: block;\n} <link href=\"https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/1.0.4/tailwind.min.css\" rel=\"stylesheet\"/>\n<div class=\"p-10\">\n\n <div class=\"dropdown inline-block relative\">\n <button class=\"bg-gray-300 text-gray-700 font-semibold py-2 px-4 rounded inline-flex items-center\">\n <span class=\"mr-1\">Dropdown</span>\n <svg class=\"fill-current h-4 w-4\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 20 20\"><path d=\"M9.293 12.95l.707.707L15.657 8l-1.414-1.414L10 10.828 5.757 6.586 4.343 8z\"/> </svg>\n </button>\n <ul class=\"dropdown-menu absolute hidden text-gray-700 pt-1\">\n <li class=\"\"><a class=\"rounded-t bg-gray-200 hover:bg-gray-400 py-2 px-4 block whitespace-no-wrap\" href=\"#\">One</a></li>\n <li class=\"\"><a class=\"bg-gray-200 hover:bg-gray-400 py-2 px-4 block whitespace-no-wrap\" href=\"#\">Two</a></li>\n <li class=\"\"><a class=\"rounded-b bg-gray-200 hover:bg-gray-400 py-2 px-4 block whitespace-no-wrap\" href=\"#\">Three is the magic number</a></li>\n </ul>\n </div>\n\n</div>" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19336351/" ]
74,664,410
<p>I am using Stripe in my NextJs project and have tried to get customers list in my app but have not succeeded. If anyone knows how to get it, please instruct me on how to do that.</p> <p><strong>This is my code:</strong></p> <pre><code>import { loadStripe } from &quot;@stripe/stripe-js&quot;; async function getStripeCustomers(){ const stripe = await loadStripe( process.env.key ); if (stripe) { // there was a toturail for node.js like this. console.log(stripe.customers.list()) } } useEffect(() =&gt; { getStripeCustomers() }, []); </code></pre>
[ { "answer_id": 74664449, "author": "regex", "author_id": 9470979, "author_profile": "https://Stackoverflow.com/users/9470979", "pm_score": 0, "selected": false, "text": "stripe.customers.list() email created stripe.customers.list() import { loadStripe } from \"@stripe/stripe-js\";\n\nasync function getStripeCustomers(){\n const stripe = await loadStripe(process.env.key);\n if (stripe) {\n // retrieve all customers\n const customers = await stripe.customers.list();\n // log the list of customers to the console\n console.log(customers);\n }\n}\n\nuseEffect(() => {\n getStripeCustomers();\n}, []);\n import { loadStripe } from \"@stripe/stripe-js\";\n\nasync function getStripeCustomers(){\n const stripe = await loadStripe(process.env.key);\n if (stripe) {\n // retrieve only customers with the email address \"customer@example.com\"\n const customers = await stripe.customers.list({email: \"customer@example.com\"});\n // log the list of customers to the console\n console.log(customers);\n }\n}\n\nuseEffect(() => {\n getStripeCustomers();\n}, []);\n" }, { "answer_id": 74664459, "author": "sidverma", "author_id": 7721497, "author_profile": "https://Stackoverflow.com/users/7721497", "pm_score": 0, "selected": false, "text": "loadStripe @stripe/stripe-js customers.list() import { useEffect } from 'react';\nimport { loadStripe } from '@stripe/stripe-js';\n\nasync function getStripeCustomers() {\n // Load Stripe with your secret key\n const stripe = await loadStripe(process.env.STRIPE_SECRET_KEY);\n\n if (stripe) {\n // Retrieve a list of customers\n const customers = await stripe.customers.list();\n\n // Use the `customers` variable here\n console.log(customers);\n }\n}\n\nfunction App() {\n useEffect(() => {\n // Fetch the Stripe customers when the component mounts\n getStripeCustomers();\n }, []);\n\n // ...\n}\n loadStripe()" }, { "answer_id": 74669051, "author": "Paiman Rasoli", "author_id": 17462012, "author_profile": "https://Stackoverflow.com/users/17462012", "pm_score": 2, "selected": true, "text": "// api/payment/get-all-customers.js\n\nimport Stripe from \"stripe\";\nexport default async function handler(req, res) {\nif (req.method === \"POST\") {\n const { token } = JSON.parse(req.body);\nif (!token) {\n return res.status(403).json({ msg: \"Forbidden\" });\n }\n const stripe = new Stripe(process.env.NEXT_PUBLIC_STRIPE_SECRET, {\n apiVersion: \"2020-08-27\",\n});\ntry {\n const customers = await stripe.customers.list(); // returns all customers sorted by createdDate\n res.status(200).json(customers);\n} catch (err) {\n console.log(err);\n res.status(500).json({ error: true });\n}\n }\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11283695/" ]
74,664,427
<p>I'm trying to do some sort of timeline design using CSS grid, with elements interweaved on both sides. But at least rows 1, 2 and the last have juste blanked unused space.</p> <p>The columns are declared, but the rows aren't. So I tried using <code>grid-auto-rows: min-content</code>, but it didn't change anything. Actually, whatever the value I put doesn't change anything. I tried putting hardcoded px value (which is not a option) for testing, and I can easily keep the integrity of the design without the dead space.</p> <p>Tested on Firefox and Brave</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>* { margin: 0; font-family: "Ubuntu", sans-serif; box-sizing: border-box; } :root { font-size: 1px; } body { font-size: 16rem; } /*******/ .wrapper { --border-width: 0.5em; --gap: 8rem; display: grid; grid-template-columns: 1fr auto 1fr; gap: var(--gap); padding: 0.5em; align-items: start; } h2 { grid-column: 1/2; grid-row: 1/2; font-size: 2em; } section { position: relative; text-align: justify; border-top: var(--border-width) solid var(--accent); border-bottom: var(--border-width) solid transparent; padding: 0 0.5em; max-width: 60ch; } section::after { content: ""; display: block; height: var(--border-width); width: calc(var(--border-width) + var(--gap)); background-color: var(--accent); position: absolute; top: calc(-1 * var(--border-width)); z-index: -1; } section:nth-of-type(odd) { grid-column: 3/4; border-right: var(--border-width) solid var(--accent); border-top-right-radius: 1em; } section:nth-of-type(odd)::after { left: 0; translate: -100%; } section:nth-of-type(even) { grid-column: 1/2; justify-self: end; border-left: var(--border-width) solid var(--accent); border-top-left-radius: 1em; } section:nth-of-type(even)::after { right: 0; translate: 100%; } .date { grid-column: 2/3; display: flex; flex-flow: column nowrap; align-items: center; font-size: 12rem; padding: 0.6em 0.3em; line-height: 0.7em; background-color: var(--accent); color: white; } .date:nth-of-type(odd) { border-radius: 1em 0 1em 0; } .date:nth-of-type(even) { border-radius: 0 1em 0 1em; } .date&gt;* { flex-basis: 100%; } .green { --accent: hsl(171, 67%, 28%); grid-row: 1/3; } .orange { --accent: hsl(22, 99%, 50%); grid-row: 2/4; } .orange.date { grid-row: 2/3; } .yellow { --accent: hsl(46, 100%, 47%); grid-row: 3/5; } .yellow.date { grid-row: 3/4; } .pink { --accent: hsl(343, 78%, 62%); grid-row: 4/6; } .pink.date { grid-row: 4/5; } .blue { --accent: hsl(192deg 80% 48%); grid-row: 5/7; } .blue.date { grid-row: 5/6; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="wrapper"&gt; &lt;h2&gt;Lorem Ipsum&lt;/h2&gt; &lt;section class="green"&gt; Lorem ipsum dolor sit amet consectetur adipisicing elit. Minus quidem qui, aliquid asperiores commodi officiis inventore laboriosam dignissimos dolor officia id itaque tempora provident exercitationem accusamus expedita ullam dolorum fuga. Officiis temporibus porro nesciunt libero, eum aliquid doloremque minima nisi sint minus id mollitia ea quisquam consequuntur laudantium autem. Aperiam. &lt;/section&gt; &lt;p class="green date"&gt;&lt;span&gt;03/2022&lt;/span&gt;-&lt;span&gt;04/2023&lt;/span&gt;&lt;/p&gt; &lt;section class="orange"&gt; Lorem ipsum dolor sit amet consectetur adipisicing elit. Eum, quisquam atque. Dolores beatae, nisi, laborum perspiciatis architecto non dolorem quae, doloribus aliquam quaerat rem? Esse hic illum sint mollitia quibusdam repellendus totam dolorum voluptatem ipsa, nobis sapiente. Quasi quo porro aperiam cumque nobis debitis praesentium dolorem omnis repellat saepe. Incidunt laudantium at similique nobis perferendis et illo dolor aliquid nisi voluptatum eaque ab accusamus maxime possimus, ut ratione soluta nam, natus quibusdam illum! Qui modi cum libero odit blanditiis distinctio eveniet illo facilis alias, aut neque perspiciatis et ipsam, hic natus? Explicabo consequuntur voluptatibus a ipsam voluptatem, deleniti at doloribus! &lt;/section&gt; &lt;p class="orange date"&gt;&lt;span&gt;12/2020&lt;/span&gt;-&lt;span&gt;02/2022&lt;/span&gt;&lt;/p&gt; &lt;section class="yellow"&gt; Lorem ipsum dolor sit amet consectetur adipisicing elit. Eius, aliquam blanditiis! Magnam dolorem nostrum molestias modi, ratione id quaerat adipisci dolore impedit quas voluptate recusandae nisi deleniti sed, doloremque ullam ducimus. Voluptatem aut praesentium magni iusto blanditiis? Doloremque, maxime necessitatibus eaque obcaecati voluptate cumque veritatis exercitationem, dolor ex beatae blanditiis. &lt;/section&gt; &lt;p class="yellow date"&gt;&lt;span&gt;11/2018&lt;/span&gt;-&lt;span&gt;10/2020&lt;/span&gt;&lt;/p&gt; &lt;section class="pink"&gt; Lorem ipsum dolor sit, amet consectetur adipisicing elit. Perferendis blanditiis repellat nulla iste illo quos, culpa sint nihil doloribus quae molestiae eaque perspiciatis reiciendis exercitationem eum minima molestias voluptatum consequatur quisquam asperiores obcaecati? Quas animi quis itaque molestias praesentium maiores minima. Consequuntur hic explicabo eos expedita quidem, dolorum maiores perferendis, illum quod, placeat magni! Exercitationem architecto iusto deserunt magni possimus. &lt;/section&gt; &lt;p class="pink date"&gt;&lt;span&gt;01/2018&lt;/span&gt;-&lt;span&gt;11/2018&lt;/span&gt;&lt;/p&gt; &lt;section class="blue"&gt; Lorem ipsum dolor sit amet consectetur adipisicing elit. Consequatur minima illum, accusamus recusandae eveniet blanditiis repellendus quaerat ullam inventore eaque? Doloremque delectus quibusdam rem hic! Modi ducimus iusto perspiciatis incidunt quidem cum, optio, soluta id voluptatum placeat nobis quasi maxime dolorem magni pariatur cumque illum odio dolor. Dolor libero sint ea iste, autem rerum cupiditate enim aliquam? Cumque voluptatum at dolore. Veritatis, assumenda autem. Culpa facilis dolorum molestias voluptatum, natus, fugit fuga amet veritatis, dicta similique suscipit temporibus porro tempora? &lt;/section&gt; &lt;p class="blue date"&gt;&lt;span&gt;07/2014&lt;/span&gt;-&lt;span&gt;07/2017&lt;/span&gt;&lt;/p&gt; &lt;/div</code></pre> </div> </div> </p>
[ { "answer_id": 74664449, "author": "regex", "author_id": 9470979, "author_profile": "https://Stackoverflow.com/users/9470979", "pm_score": 0, "selected": false, "text": "stripe.customers.list() email created stripe.customers.list() import { loadStripe } from \"@stripe/stripe-js\";\n\nasync function getStripeCustomers(){\n const stripe = await loadStripe(process.env.key);\n if (stripe) {\n // retrieve all customers\n const customers = await stripe.customers.list();\n // log the list of customers to the console\n console.log(customers);\n }\n}\n\nuseEffect(() => {\n getStripeCustomers();\n}, []);\n import { loadStripe } from \"@stripe/stripe-js\";\n\nasync function getStripeCustomers(){\n const stripe = await loadStripe(process.env.key);\n if (stripe) {\n // retrieve only customers with the email address \"customer@example.com\"\n const customers = await stripe.customers.list({email: \"customer@example.com\"});\n // log the list of customers to the console\n console.log(customers);\n }\n}\n\nuseEffect(() => {\n getStripeCustomers();\n}, []);\n" }, { "answer_id": 74664459, "author": "sidverma", "author_id": 7721497, "author_profile": "https://Stackoverflow.com/users/7721497", "pm_score": 0, "selected": false, "text": "loadStripe @stripe/stripe-js customers.list() import { useEffect } from 'react';\nimport { loadStripe } from '@stripe/stripe-js';\n\nasync function getStripeCustomers() {\n // Load Stripe with your secret key\n const stripe = await loadStripe(process.env.STRIPE_SECRET_KEY);\n\n if (stripe) {\n // Retrieve a list of customers\n const customers = await stripe.customers.list();\n\n // Use the `customers` variable here\n console.log(customers);\n }\n}\n\nfunction App() {\n useEffect(() => {\n // Fetch the Stripe customers when the component mounts\n getStripeCustomers();\n }, []);\n\n // ...\n}\n loadStripe()" }, { "answer_id": 74669051, "author": "Paiman Rasoli", "author_id": 17462012, "author_profile": "https://Stackoverflow.com/users/17462012", "pm_score": 2, "selected": true, "text": "// api/payment/get-all-customers.js\n\nimport Stripe from \"stripe\";\nexport default async function handler(req, res) {\nif (req.method === \"POST\") {\n const { token } = JSON.parse(req.body);\nif (!token) {\n return res.status(403).json({ msg: \"Forbidden\" });\n }\n const stripe = new Stripe(process.env.NEXT_PUBLIC_STRIPE_SECRET, {\n apiVersion: \"2020-08-27\",\n});\ntry {\n const customers = await stripe.customers.list(); // returns all customers sorted by createdDate\n res.status(200).json(customers);\n} catch (err) {\n console.log(err);\n res.status(500).json({ error: true });\n}\n }\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4433288/" ]
74,664,429
<p>I have 2 lists and I want to see how many of the text in list 1 is in list 2 but I don't really know of a way to like combine them the output isn't summed and I have tried sum method but it does it for all words counted not each word.</p> <p>Code:</p> <pre class="lang-py prettyprint-override"><code>l1 = ['hello', 'hi'] l2 = ['hey', 'hi', 'hello', 'hello'] for i in l2: print(f'{l1.count(i)}: {i}') </code></pre> <p>Output:</p> <pre class="lang-py prettyprint-override"><code>0: hey 1: hi 1: hello 1: hello </code></pre> <p>What I want is something more like this:</p> <pre class="lang-py prettyprint-override"><code>0: hey 1: hi 2: hello </code></pre>
[ { "answer_id": 74664448, "author": "kenjoe41", "author_id": 4671205, "author_profile": "https://Stackoverflow.com/users/4671205", "pm_score": 1, "selected": false, "text": "from collections import Counter\n\nl1 = ['hello', 'hi']\nl2 = ['hey', 'hi', 'hello', 'hello']\n\n# Create a Counter object to count the occurrences of each element in l1 that is also in l2\ncounter = Counter()\n\n# Loop over each element in l1 and check if it is in l2\nfor element in l1:\n if element in l2:\n # If the element is in l2, increment the count for that element\n counter[element] += 1\n\n# Print the count for each element\nfor element, count in counter.items():\n print(f'{count}: {element}')\n 1: hi\n2: hello\n" }, { "answer_id": 74664452, "author": "chivalrous-nerd", "author_id": 7347835, "author_profile": "https://Stackoverflow.com/users/7347835", "pm_score": 1, "selected": false, "text": "l1 = ['hello', 'hi']\nl2 = ['hey', 'hi', 'hello', 'hello']\n\n# Create an empty dictionary\ncounts = {}\n\n# Loop through each word in l1\nfor word in l1:\n # Initialize the count for this word to 0\n counts[word] = 0\n # Loop through each word in l2\n for word2 in l2:\n # If the word from l1 appears in l2, increment the count\n if word == word2:\n counts[word] += 1\n\n# Print the counts for each word\nfor word in l1:\n print(f'{counts[word]}: {word}')\n 2: hello 1: hi" }, { "answer_id": 74664474, "author": "ddastrodd", "author_id": 5656617, "author_profile": "https://Stackoverflow.com/users/5656617", "pm_score": 3, "selected": true, "text": "l1 = ['hello', 'hi']\nl2 = ['hey', 'hi', 'hello', 'hello']\nfor i in l1:\n print(f'{l2.count(i)}: {i}')\n 2: hello\n1: hi\n" }, { "answer_id": 74664491, "author": "codester_09", "author_id": 17507911, "author_profile": "https://Stackoverflow.com/users/17507911", "pm_score": 0, "selected": false, "text": "\nfrom collections import Counter\n\nl1 = ['hello', 'hi']\nl2 = ['hey', 'hi', 'hello', 'hello']\n\nc = Counter(l2)\n\n\nfor a in l1:\n print(f\"{c[a]}: {a}\")\n c.pop(a)\n\nprint(*[\"0: \" + a for a in c.keys()], sep='\\n')\n\n 2: hello\n1: hi\n0: hey\n\n" }, { "answer_id": 74664694, "author": "Sbagaria2710", "author_id": 10111454, "author_profile": "https://Stackoverflow.com/users/10111454", "pm_score": 0, "selected": false, "text": "# define the two lists\nlist1 = [\"apple\", \"banana\", \"cherry\"]\nlist2 = [\"apple\", \"grape\", \"cherry\", \"apple\", \"orange\", \"banana\", \"apple\"]\n\n# initialize a count variable\ncount = 0\n\n# iterate over the first list\nfor word in list1:\n # count the number of times the word appears in the second list\n count += list2.count(word)\n\n# print the final count\nprint(count)\n\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19533292/" ]
74,664,451
<p>So another prolog question here.</p> <p>As the title indicated, I tried to add one element on each sublist of a list. But things really don't go well. Here's my code so far:</p> <pre><code>add_char(Char, Motif, NewM):- append(Motif, [Char], NewM). add_all(Char, [], _, RE). add_all(Char, [H|T], Pred, RE):- add_char(Char, H, NewH), append(Pred, [NewH], RE), add_all(Char, T, RE, NewRE). </code></pre> <p>My code just wanna return the head instead of the whole list as result. like:</p> <pre><code>?- add_all(h, [(v=[1,2,3]), (i = [5,6,7]), (e = [r,e,w])], [],X). X = [v=[1, 2, 3, h]] </code></pre> <p>What I expect is</p> <pre><code>X = [v=[1, 2, 3, h],i = [5,6,7,h],e = [r,e,w,h]]. </code></pre> <p>Can anyone help?</p>
[ { "answer_id": 74665530, "author": "TessellatingHeckler", "author_id": 478656, "author_profile": "https://Stackoverflow.com/users/478656", "pm_score": 1, "selected": true, "text": "=(v,[1,2,3]) add_char(Char, (X=Motif), (X=NewM)) :- % destructures v=[1,2,3]\n append(Motif, [Char], NewM). % appends to [1,2,3]\n\n\nadd_all(_, [], []). % stops when [H|T] is empty []\n\nadd_all(Char, [H|T], [NewH|Rs]):- % relates [H|T] and [NewH|NewHs]\n add_char(Char, H, NewH), % adds this one\n add_all(Char, T, Rs). % does the rest\n = (v=[1,2,3]) v-[1,2,3] [H|T]" }, { "answer_id": 74665533, "author": "damianodamiano", "author_id": 6478085, "author_profile": "https://Stackoverflow.com/users/6478085", "pm_score": 1, "selected": false, "text": "append/3 add_all(_,[],[]).\nadd_all(El,[(V=L)|T],[(V=L1)|T1]):-\n append(L,[El],L1),\n add_all(El,T,T1).\n\n? add_all(h, [(v=[1,2,3]), (i = [5,6,7]), (e = [r,e,w])], X).\nX = [v=[1, 2, 3, h], i=[5, 6, 7, h], e=[r, e, w, h]]\nfalse\n false !" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20632687/" ]
74,664,488
<p>I want to fillna values in the 'last unique id' column based on the increment values from the previous row</p> <pre><code>**input is** Channel last unique id 0 MYNTRA MN000351370 1 NYKAA NYK00038219 2 NYKAA NaN 3 NYKAA NaN 4 NYKAA NaN 5 NYKAA NaN 6 MYNTRA NaN 7 MYNTRA NaN 8 MYNTRA NaN 9 MYNTRA NaN 10 MYNTRA NaN 11 MYNTRA NaN Expected output Channel last unique id 0 MYNTRA MN000351370 1 NYKAA NYK00038219 2 NYKAA NYK00038220 3 NYKAA NYK00038221 4 NYKAA NYK00038222 5 NYKAA NYK00038223 6 MYNTRA MN000351371 7 MYNTRA MN000351372 8 MYNTRA MN000351373 9 MYNTRA MN000351374 10 MYNTRA MN000351375 11 MYNTRA MN000351376 </code></pre> <p>Hope you understood the problem</p>
[ { "answer_id": 74665530, "author": "TessellatingHeckler", "author_id": 478656, "author_profile": "https://Stackoverflow.com/users/478656", "pm_score": 1, "selected": true, "text": "=(v,[1,2,3]) add_char(Char, (X=Motif), (X=NewM)) :- % destructures v=[1,2,3]\n append(Motif, [Char], NewM). % appends to [1,2,3]\n\n\nadd_all(_, [], []). % stops when [H|T] is empty []\n\nadd_all(Char, [H|T], [NewH|Rs]):- % relates [H|T] and [NewH|NewHs]\n add_char(Char, H, NewH), % adds this one\n add_all(Char, T, Rs). % does the rest\n = (v=[1,2,3]) v-[1,2,3] [H|T]" }, { "answer_id": 74665533, "author": "damianodamiano", "author_id": 6478085, "author_profile": "https://Stackoverflow.com/users/6478085", "pm_score": 1, "selected": false, "text": "append/3 add_all(_,[],[]).\nadd_all(El,[(V=L)|T],[(V=L1)|T1]):-\n append(L,[El],L1),\n add_all(El,T,T1).\n\n? add_all(h, [(v=[1,2,3]), (i = [5,6,7]), (e = [r,e,w])], X).\nX = [v=[1, 2, 3, h], i=[5, 6, 7, h], e=[r, e, w, h]]\nfalse\n false !" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16173748/" ]
74,664,498
<p>I am new to go and now evaluate a demo function about slice with Fibonacci sequence</p> <pre><code>package main import &quot;fmt&quot; func fbn(n int) []uint64 { fbnSlice := make([]uint64, n) fbnSlice[0] = 1 fbnSlice[1] = 1 for i := 2; i &lt; n; i++ { fbnSlice[i] = fbnSlice[i-1] + fbnSlice[i-2] } return fbnSlice } func main() { fnbSlice := fbn(5) fmt.Println(fnbSlice) } </code></pre> <p>It will print &quot;[1 1 2 3 5]&quot; My doubt is how the slice add it's len to 5, thanks!</p>
[ { "answer_id": 74665530, "author": "TessellatingHeckler", "author_id": 478656, "author_profile": "https://Stackoverflow.com/users/478656", "pm_score": 1, "selected": true, "text": "=(v,[1,2,3]) add_char(Char, (X=Motif), (X=NewM)) :- % destructures v=[1,2,3]\n append(Motif, [Char], NewM). % appends to [1,2,3]\n\n\nadd_all(_, [], []). % stops when [H|T] is empty []\n\nadd_all(Char, [H|T], [NewH|Rs]):- % relates [H|T] and [NewH|NewHs]\n add_char(Char, H, NewH), % adds this one\n add_all(Char, T, Rs). % does the rest\n = (v=[1,2,3]) v-[1,2,3] [H|T]" }, { "answer_id": 74665533, "author": "damianodamiano", "author_id": 6478085, "author_profile": "https://Stackoverflow.com/users/6478085", "pm_score": 1, "selected": false, "text": "append/3 add_all(_,[],[]).\nadd_all(El,[(V=L)|T],[(V=L1)|T1]):-\n append(L,[El],L1),\n add_all(El,T,T1).\n\n? add_all(h, [(v=[1,2,3]), (i = [5,6,7]), (e = [r,e,w])], X).\nX = [v=[1, 2, 3, h], i=[5, 6, 7, h], e=[r, e, w, h]]\nfalse\n false !" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7452990/" ]
74,664,508
<p>I'm trying to find a way to create a nested list out of an already-existing non-empty list using built-in list fuctions.</p> <p>Here is a small example: <code>a=['Groceries', 'School Fees', 'Medicines', 'Furniture']</code> When I try <code>a[0].insert(0, 1000)</code> for example, I'm met with an error. Is there any way to do this?</p>
[ { "answer_id": 74665530, "author": "TessellatingHeckler", "author_id": 478656, "author_profile": "https://Stackoverflow.com/users/478656", "pm_score": 1, "selected": true, "text": "=(v,[1,2,3]) add_char(Char, (X=Motif), (X=NewM)) :- % destructures v=[1,2,3]\n append(Motif, [Char], NewM). % appends to [1,2,3]\n\n\nadd_all(_, [], []). % stops when [H|T] is empty []\n\nadd_all(Char, [H|T], [NewH|Rs]):- % relates [H|T] and [NewH|NewHs]\n add_char(Char, H, NewH), % adds this one\n add_all(Char, T, Rs). % does the rest\n = (v=[1,2,3]) v-[1,2,3] [H|T]" }, { "answer_id": 74665533, "author": "damianodamiano", "author_id": 6478085, "author_profile": "https://Stackoverflow.com/users/6478085", "pm_score": 1, "selected": false, "text": "append/3 add_all(_,[],[]).\nadd_all(El,[(V=L)|T],[(V=L1)|T1]):-\n append(L,[El],L1),\n add_all(El,T,T1).\n\n? add_all(h, [(v=[1,2,3]), (i = [5,6,7]), (e = [r,e,w])], X).\nX = [v=[1, 2, 3, h], i=[5, 6, 7, h], e=[r, e, w, h]]\nfalse\n false !" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12819949/" ]
74,664,526
<p>I'm just trying to figure out how to toggle a css class for an individual button that is generated from a mapped array.</p> <p>My code works, but it toggles <em>every</em> mapped button, not just the button selected.</p> <pre><code> &lt;div className='synonym-keeper'&gt; {synArr.map((syn) =&gt; ( &lt;button className={`synonym ${isPressed &amp;&amp; 'active'}`} onClick={() =&gt; toggleIsPressed(!isPressed)} &gt; {syn} &lt;/button&gt; ))} &lt;/div&gt; </code></pre> <p>How do I make just the selected button's css toggle?</p>
[ { "answer_id": 74664575, "author": "Amila Senadheera", "author_id": 8510405, "author_profile": "https://Stackoverflow.com/users/8510405", "pm_score": 3, "selected": true, "text": "Togglebutton const synArr = [\"button 1\", \"button 2\", \"button 3\"];\n\nconst ToggleButton = ({ text }) => {\n const [isPressed, toggleIsPressed] = React.useState(false);\n\n return (\n <button\n className={`synonym ${isPressed && \"active\"}`}\n onClick={() => toggleIsPressed(!isPressed)}\n >\n {text}\n </button>\n );\n};\n\nfunction App() {\n return (\n <div className=\"synonym-keeper\">\n {synArr.map((syn) => (\n <ToggleButton text={syn} key={syn}/>\n ))}\n </div>\n );\n}\n\nReactDOM.render(<App />, document.querySelector('.react')); .synonym.active {\n background-color: green;\n} <script crossorigin src=\"https://unpkg.com/react@16/umd/react.development.js\"></script>\n<script crossorigin src=\"https://unpkg.com/react-dom@16/umd/react-dom.development.js\"></script>\n<div class='react'></div>" }, { "answer_id": 74671117, "author": "Fiattarone", "author_id": 17502217, "author_profile": "https://Stackoverflow.com/users/17502217", "pm_score": 0, "selected": false, "text": " <div className='synonym-keeper'>\n {synArr.map((syn, idx) => (\n <button\n className={`synonym ${isPressed[idx]}`}\n onClick={() => {\n const newIsPressed = [...isPressed];\n newIsPressed[idx] === ''\n ? (newIsPressed[idx] = 'active')\n : (newIsPressed[idx] = '');\n setIsPressed(newIsPressed);\n }}\n >\n {syn}\n </button>\n ))}\n </div>\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17502217/" ]
74,664,542
<p>I have login information in my list. I am trying to match login id and password with list. My code only allow to test correct id and password. If id or password is not matched then my code is not allow me to re enter the id and password.</p> <p>Here is my code:</p> <pre><code>System.out.println(&quot;*** Welcome back Student ***&quot;); System.out.println(&quot;Please enter your Student Id :&quot;); studentID = br.readLine(); System.out.println(&quot;Please enter your password :&quot;); password = br.readLine(); // Iterate through list of students to see if we have a match for (Student student : listOfStudents) { if (student.getStudentID().equals(studentID)) { if (student.getPassword().equals(password)) { loggedInStudent = student; break; } } } for (Student student : listOfStudents) { if (loggedInStudent != null) { System.out.println(&quot;Successfully Login&quot;); break; } else if (!student.getStudentID().equals(studentID)) { System.out.println(&quot;Wrong Student ID, please check and re-enter your Student ID&quot;); break; } else { System.out.println(&quot;Wrong password, please check and re-enter your password&quot;); break; } } </code></pre>
[ { "answer_id": 74664575, "author": "Amila Senadheera", "author_id": 8510405, "author_profile": "https://Stackoverflow.com/users/8510405", "pm_score": 3, "selected": true, "text": "Togglebutton const synArr = [\"button 1\", \"button 2\", \"button 3\"];\n\nconst ToggleButton = ({ text }) => {\n const [isPressed, toggleIsPressed] = React.useState(false);\n\n return (\n <button\n className={`synonym ${isPressed && \"active\"}`}\n onClick={() => toggleIsPressed(!isPressed)}\n >\n {text}\n </button>\n );\n};\n\nfunction App() {\n return (\n <div className=\"synonym-keeper\">\n {synArr.map((syn) => (\n <ToggleButton text={syn} key={syn}/>\n ))}\n </div>\n );\n}\n\nReactDOM.render(<App />, document.querySelector('.react')); .synonym.active {\n background-color: green;\n} <script crossorigin src=\"https://unpkg.com/react@16/umd/react.development.js\"></script>\n<script crossorigin src=\"https://unpkg.com/react-dom@16/umd/react-dom.development.js\"></script>\n<div class='react'></div>" }, { "answer_id": 74671117, "author": "Fiattarone", "author_id": 17502217, "author_profile": "https://Stackoverflow.com/users/17502217", "pm_score": 0, "selected": false, "text": " <div className='synonym-keeper'>\n {synArr.map((syn, idx) => (\n <button\n className={`synonym ${isPressed[idx]}`}\n onClick={() => {\n const newIsPressed = [...isPressed];\n newIsPressed[idx] === ''\n ? (newIsPressed[idx] = 'active')\n : (newIsPressed[idx] = '');\n setIsPressed(newIsPressed);\n }}\n >\n {syn}\n </button>\n ))}\n </div>\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20672431/" ]
74,664,554
<p>I have an JSON file similar to this:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;version&quot;: &quot;2.0&quot;, &quot;stage&quot; : { &quot;objects&quot; : [ { &quot;foo&quot; : 1100, &quot;bar&quot; : false, &quot;id&quot; : &quot;56a983f1-8111-4abc-a1eb-263d41cfb098&quot; }, { &quot;foo&quot; : 1100, &quot;bar&quot; : false, &quot;id&quot; : &quot;6369df4b-90c4-4695-8a9c-6bb2b8da5976&quot; }], &quot;bish&quot; : &quot;#FFFFFF&quot; }, &quot;more&quot;: &quot;abcd&quot; } </code></pre> <p>I would like the output to be exactly the same, with the exception of an incrementing integer in place of the &quot;id&quot; : &quot;guid&quot; - something like:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;version&quot;: &quot;2.0&quot;, &quot;stage&quot; : { &quot;objects&quot; : [ { &quot;foo&quot; : 1100, &quot;bar&quot; : false, &quot;id&quot; : 1 }, { &quot;foo&quot; : 1100, &quot;bar&quot; : false, &quot;id&quot; : 2 }], &quot;bish&quot; : &quot;#FFFFFF&quot; }, &quot;more&quot;: &quot;abcd&quot; } </code></pre> <p>I'm new to jq. I can set the id's to a fixed integer with .stage.objects[].id |= 1.</p> <pre class="lang-json prettyprint-override"><code>{ &quot;version&quot;: &quot;2.0&quot;, &quot;stage&quot;: { &quot;objects&quot;: [ { &quot;foo&quot;: 1100, &quot;bar&quot;: false, &quot;id&quot;: 1 }, { &quot;foo&quot;: 1100, &quot;bar&quot;: false, &quot;id&quot;: 1 } ], &quot;bish&quot;: &quot;#FFFFFF&quot; }, &quot;more&quot;: &quot;abcd&quot; } </code></pre> <p>I can't figure out the syntax to make the assigned number iterate.</p> <p>I tried various combinations of map, reduce, to_entries, foreach and other strategies mentioned in answers to similar questions but the data in those examples always consisted of something simple.</p>
[ { "answer_id": 74664887, "author": "knittl", "author_id": 112968, "author_profile": "https://Stackoverflow.com/users/112968", "pm_score": 1, "selected": false, "text": "to_entries .stage.objects |= (to_entries | map(.value.id = .key + 1 | .value))\n .stage.objects |= (to_entries | map(.value += {id: (.key + 1)} | .value))\n {\n \"version\": \"2.0\",\n \"stage\": {\n \"objects\": [\n {\n \"foo\": 1100,\n \"bar\": false,\n \"id\": 1\n },\n {\n \"foo\": 1100,\n \"bar\": false,\n \"id\": 2\n }\n ],\n \"bish\": \"#FFFFFF\"\n },\n \"more\": \"abcd\"\n}\n" }, { "answer_id": 74666476, "author": "pmf", "author_id": 2158479, "author_profile": "https://Stackoverflow.com/users/2158479", "pm_score": 1, "selected": true, "text": "reduce keys .stage.objects |= reduce keys[] as $i (.; .[$i].id = $i + 1)\n {\n \"version\": \"2.0\",\n \"stage\": {\n \"objects\": [\n {\n \"foo\": 1100,\n \"bar\": false,\n \"id\": 1\n },\n {\n \"foo\": 1100,\n \"bar\": false,\n \"id\": 2\n }\n ],\n \"bish\": \"#FFFFFF\"\n },\n \"more\": \"abcd\"\n}\n .children recurse(.[].children | arrays) (.stage.objects | recurse(.[].children | arrays)) |=\n reduce keys[] as $i (.; .[$i].id = $i + 1)\n .children 1 path to_entries setpath reduce (\n [path(.stage.objects[] | recurse(.children | arrays[]).id)] | to_entries[]\n) as $i (.; setpath($i.value; $i.key + 1))\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20672299/" ]
74,664,596
<p>I'm very new to React JS but watched a few video tutorials on how to build my own portfolio. I want to map my portfolio items which contain an image, title, description, role and link. I managed to map everything except for the link to the detailed page of the respective portfolio item.</p> <p>Could anyone please help me understand what I'm doing wrong and how to solve it please?</p> <p>This is my folder structure:</p> <p><code>src =&gt; pages</code> where the main pages retain and <code>src =&gt; pages =&gt; case-studies</code> where the detailed pages of my portfolio items retain.</p> <p><a href="https://i.stack.imgur.com/APyrT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/APyrT.png" alt="enter image description here" /></a></p> <p>Here's what I got to so far:</p> <p><strong>Work.jsx</strong> in the src =&gt; pages folder</p> <pre><code>import React, { useEffect, useState } from &quot;react&quot;; import Loader from &quot;./Loader&quot;; import &quot;./Work.css&quot;; import WorkCard from &quot;./WorkCard&quot;; import WorkData from &quot;./WorkData&quot;; const Work = () =&gt; { return ( &lt;div className=&quot;work&quot;&gt; &lt;section className=&quot;work-section&quot;&gt; &lt;div className=&quot;card&quot;&gt; &lt;h1 className=&quot;underline&quot;&gt;My portfolio&lt;/h1&gt; &lt;p&gt;Here are the case studies of my projects...&lt;/p&gt; &lt;div className=&quot;grid-layout grid-2&quot;&gt; { WorkData.map((val, index) =&gt; { return ( &lt;WorkCard key={index} url={val.url} image={val.image} name={val.name} description={val.description} role={val.role} /&gt; ); }) } &lt;/div&gt; &lt;/div&gt; &lt;/section&gt; &lt;/div&gt; ); } export default Work; </code></pre> <p><strong>WorkCard.jsx</strong> in the src =&gt; pages folder</p> <pre><code>import React from &quot;react&quot;; import { NavLink } from &quot;react-router-dom&quot;; const WorkCard = (props) =&gt; { return ( &lt;NavLink to={props.url} className=&quot;tile-card&quot;&gt; &lt;img src={props.image} alt={props.name} /&gt; &lt;div className=&quot;details&quot;&gt; &lt;h2&gt;{props.name}&lt;/h2&gt; &lt;p className=&quot;description&quot; title={props.description}&gt;{props.description}&lt;/p&gt; &lt;h4 className=&quot;role&quot; title={props.role}&gt;Role: {props.role}&lt;/h4&gt; &lt;/div&gt; &lt;/NavLink&gt; ); } export default WorkCard; </code></pre> <p><strong>WorkData.jsx</strong> in the src =&gt; pages folder</p> <pre><code>import EcoPizza from &quot;../assets/project-icons/ecoPizza.webp&quot;; import Squared from &quot;../assets/project-icons/Squared.webp&quot;; import { EcoPizzaCaseStudy, SquaredCaseStudy } from &quot;./case-studies&quot;; const WorkData = [ { &quot;image&quot;: EcoPizza, &quot;name&quot;: &quot;The UX portfolio item name&quot;, &quot;description&quot;: &quot;This is description part&quot;, &quot;role&quot;: &quot;My role in that project&quot;, &quot;url&quot;: EcoPizzaCaseStudy }, { &quot;image&quot;: Squared, &quot;name&quot;: &quot;The UX portfolio item name&quot;, &quot;description&quot;: &quot;This is description part&quot;, &quot;role&quot;: &quot;My role in that project&quot;, &quot;url&quot;: SquaredCaseStudy } ]; export default WorkData; </code></pre> <p><strong>index.js</strong> in the src =&gt; pages =&gt; case-studies folder</p> <pre><code>export { default as EcoPizzaCaseStudy } from &quot;./eco-pizza/EcoPizzaCaseStudy&quot;; export { default as SquaredCaseStudy } from &quot;./squared/SquaredCaseStudy&quot;; </code></pre> <p><strong>App.js</strong></p> <pre><code>import React from &quot;react&quot;; import { BrowserRouter as Router, Route, Routes } from &quot;react-router-dom&quot;; import { Navigation } from &quot;./components/Navigation&quot;; import { Home, About, Work, Contact, PageNotFound, UnderConstruction } from &quot;./pages&quot;; import { Footer } from &quot;./components/Footer&quot;; function App() { return ( &lt;div className=&quot;App&quot;&gt; &lt;Router&gt; &lt;Navigation /&gt; &lt;main&gt; &lt;Routes&gt; &lt;Route path=&quot;/&quot; element={&lt;Home /&gt;} /&gt; &lt;Route path=&quot;/about&quot; element={&lt;About /&gt;} /&gt; &lt;Route path=&quot;/work&quot; element={&lt;Work /&gt;} /&gt; &lt;Route path=&quot;/under-construction&quot; element={&lt;UnderConstruction /&gt;} /&gt; &lt;Route path=&quot;/contact&quot; element={&lt;Contact /&gt;} /&gt; &lt;Route path='*' element={&lt;PageNotFound /&gt;}/&gt; &lt;/Routes&gt; &lt;/main&gt; &lt;Footer /&gt; &lt;/Router&gt; &lt;/div&gt; ); } export default App; </code></pre>
[ { "answer_id": 74664876, "author": "ClusterH", "author_id": 15119024, "author_profile": "https://Stackoverflow.com/users/15119024", "pm_score": 0, "selected": false, "text": "import React, { Suspense, lazy } from 'react';\nimport { BrowserRouter as Router, Routes, Route } from 'react-router-dom';\n\nconst Work = lazy(() => import('./pages/Work'));\nconst EcoPizzaCaseStudy = lazy(() => import('./case-studies/eco-pizza/EcoPizzaCaseStudy'));\nconst SquaredCaseStudy = lazy(() => import('./case-studies/squared/SquaredCaseStudy'));\n\nconst App = () => (\n <Router>\n <Suspense fallback={<div>Loading...</div>}>\n <Routes>\n <Route path=\"/work\" element={<Home />} />\n <Route path=\"/coPizzaCaseStudy/\" element={<EcoPizzaCaseStudy />} />\n <Route path=\"/squaredCaseStudy/\" element={<SquaredCaseStudy />} />\n </Routes>\n </Suspense>\n </Router>\n);\n coPizzaCaseStudy squaredCaseStudy Work.css WorkData.jsx WorkData.jsx WorkData.js" }, { "answer_id": 74664918, "author": "aarnas", "author_id": 13256340, "author_profile": "https://Stackoverflow.com/users/13256340", "pm_score": 2, "selected": true, "text": "import React from \"react\";\nimport { BrowserRouter as Router, Route, Routes } from \"react-router-dom\";\nimport { Navigation } from \"./components/Navigation\";\nimport { Home, About, Work, Contact, PageNotFound, UnderConstruction } from \"./pages\";\nimport { Footer } from \"./components/Footer\";\n//import required components\nimport { EcoPizzaCaseStudy, SquaredCaseStudy } from \"./case-studies\";\n\nfunction App() {\n return (\n <div className=\"App\">\n <Router>\n <Navigation />\n <main>\n <Routes>\n <Route path=\"/\" element={<Home />} />\n <Route path=\"/about\" element={<About />} />\n <Route path=\"/work\" element={<Work />} />\n <Route path=\"/under-construction\" element={<UnderConstruction />} />\n <Route path=\"/contact\" element={<Contact />} />\n // Add your routes\n <Route path=\"/eco-pizza-case-study\" element={<EcoPizzaCaseStudy/>} />\n <Route path=\"/squared-case-study\" element={<SquaredCaseStudy/>} />\n <Route path='*' element={<PageNotFound />}/>\n </Routes>\n </main>\n <Footer />\n </Router>\n </div>\n );\n}\n\nexport default App;\n \"url\": SquaredCaseStudy \"url\": \"/squared-case-study\" /study/squared" }, { "answer_id": 74664929, "author": "Drew Reese", "author_id": 8690857, "author_profile": "https://Stackoverflow.com/users/8690857", "pm_score": 0, "selected": false, "text": "\"/work/EcoPizzaCaseStudy\" PageNotFound import EcoPizza from \"../assets/project-icons/ecoPizza.webp\";\nimport Squared from \"../assets/project-icons/Squared.webp\";\nimport { EcoPizzaCaseStudy, SquaredCaseStudy } from \"./case-studies\";\n\nconst WorkData = [\n {\n \"image\": EcoPizza,\n \"name\": \"The UX portfolio item name\",\n \"description\": \"This is description part\",\n \"role\": \"My role in that project\",\n \"url\": EcoPizzaCaseStudy // <-- React component, not a path string\n },\n {\n \"image\": Squared,\n \"name\": \"The UX portfolio item name\",\n \"description\": \"This is description part\",\n \"role\": \"My role in that project\",\n \"url\": SquaredCaseStudy // <-- React component, not a path string\n }\n];\n Route import EcoPizza from \"../assets/project-icons/ecoPizza.webp\";\nimport Squared from \"../assets/project-icons/Squared.webp\";\nimport { EcoPizzaCaseStudy, SquaredCaseStudy } from \"./case-studies\";\n\nconst WorkData = [\n {\n image: EcoPizza,\n name: \"The UX portfolio item name\",\n description: \"This is description part\",\n role: \"My role in that project\",\n element: <EcoPizzaCaseStudy />, // <-- route element\n path: \"eco-pizza\", // <-- route path\n },\n {\n image: Squared,\n name: \"The UX portfolio item name\",\n description: \"This is description part\",\n role: \"My role in that project\",\n element: <SquaredCaseStudy />,\n path: \"squared\",\n }\n];\n\nexport default WorkData;\n WorkCard path \"/work\" \"/work/eco-pizza\" const Work = () => {\n return (\n <div className=\"work\">\n <section className=\"work-section\">\n <div className=\"card\">\n <h1 className=\"underline\">My portfolio</h1>\n <p>Here are the case studies of my projects...</p>\n\n <div className=\"grid-layout grid-2\">\n {\n WorkData.map((val) => {\n return (\n <WorkCard\n key={val.path}\n path={val.path} // <-- path path through\n image={val.image}\n name={val.name}\n description={val.description}\n role={val.role}\n />\n );\n })\n }\n </div>\n </div>\n </section>\n </div>\n );\n}\n const WorkCard = (props) => {\n return (\n <NavLink to={props.path} className=\"tile-card\">\n <img src={props.image} alt={props.name} />\n <div className=\"details\">\n <h2>{props.name}</h2>\n <p className=\"description\" title={props.description}>\n {props.description}\n </p>\n <h4 className=\"role\" title={props.role}>Role: {props.role}</h4>\n </div>\n </NavLink>\n );\n}\n WorkData ...\nimport WorkData from \"./WorkData\";\n...\n\nfunction App() {\n return (\n <div className=\"App\">\n <Router>\n <Navigation />\n <main>\n <Routes>\n <Route path=\"/\" element={<Home />} />\n <Route path=\"/about\" element={<About />} />\n <Route path=\"/work\">\n <Route index element={<Work />} />\n {/* \"/work/eco-pizza\", \"/work/squared\", etc... */}\n {WorkData.map(({ path, element }) => (\n <Route key={path} {...{ path, element }} />\n ))}\n </Route>\n <Route path=\"/under-construction\" element={<UnderConstruction />} />\n <Route path=\"/contact\" element={<Contact />} />\n <Route path='*' element={<PageNotFound />}/>\n </Routes>\n </main>\n <Footer />\n </Router>\n </div>\n );\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4599636/" ]
74,664,597
<p>I have these two plots (a heatmap and a stacked barplot). How can I put these plots near each other? Indeed I want to integrate these two plots.</p> <p>Thanks for any help.</p> <p>Here is my script:</p> <pre><code>df.bar &lt;- data.frame(Gene.name=c('Gene1','Gene1','Gene1','Gene2','Gene2','Gene2','Gene3','Gene3','Gene3', 'Gene4','Gene4','Gene4'), Alteration.frequency=c(0.0909, 2.1838, 0.6369, 0.1819, 1.0919, 0.3639, 0.4549,0.7279, 0.7279, 0.000, 0.3639, 0.4549), Alteration.Type=c(&quot;Deep deletion&quot;, &quot;Amplification&quot;, &quot;Point mutation&quot;, &quot;Deep deletion&quot;, &quot;Amplification&quot;, &quot;Point mutation&quot;, &quot;Deep deletion&quot;, &quot;Amplification&quot; , &quot;Point mutation&quot;, &quot;Deep deletion&quot;, &quot;Amplification&quot; , &quot;Point mutation&quot;)) library(ggplot2) ggplot(df.bar, aes(fill=factor(Alteration.Type, levels = c('Point mutation','Amplification','Deep deletion')), y=Alteration.frequency, x=Gene.name)) + geom_bar(position=&quot;stack&quot;, stat=&quot;identity&quot;)+theme_bw()+ theme(axis.text.x = element_text(size = 10, angle = 45, hjust = 1, colour = 'black'))+ scale_fill_manual(values=c(&quot;seagreen2&quot;, &quot;maroon2&quot;,'deepskyblue3'))+ labs(fill = 'Alteration type') </code></pre> <p><a href="https://i.stack.imgur.com/XHESH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XHESH.png" alt="enter image description here" /></a></p> <pre><code>df.heatmap &lt;- data.frame(Gene_name=c('Gene1','Gene2','Gene3','Gene4'), log2FC=c(0.56,-1.5,-0.8,2)) library(gplots) heatmap.2(cbind(df.heatmap$log2FC, df.heatmap$log2FC), trace=&quot;n&quot;, Colv = NA, dendrogram = &quot;none&quot;, labCol = &quot;&quot;, labRow = df$Gene_name, cexRow = 0.75, col=my_palette) </code></pre> <p><a href="https://i.stack.imgur.com/nMyWW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nMyWW.png" alt="enter image description here" /></a></p> <p>I need such this plot.</p> <p><a href="https://i.stack.imgur.com/rntA0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rntA0.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74665519, "author": "Allan Cameron", "author_id": 12500315, "author_profile": "https://Stackoverflow.com/users/12500315", "pm_score": 3, "selected": true, "text": "heatmap.2 ggplot heatmap.2 library(gplots)\nlibrary(ggplot2)\nlibrary(patchwork)\nlibrary(gridGraphics)\n\np1 <- ggplot(df.bar,\n aes(fill = factor(Alteration.Type, levels = c('Point mutation',\n 'Amplification', \n 'Deep deletion')),\n y = Alteration.frequency, x = Gene.name)) + \n geom_col(position = \"stack\") +\n theme_bw() +\n theme(axis.text.x = element_text(size = 10, angle = 45, hjust = 1, \n colour = 'black')) +\n scale_fill_manual(values = c(\"seagreen2\", \"maroon2\", 'deepskyblue3')) +\n labs(fill = 'Alteration type')\n\nheatmap.2(cbind(df.heatmap$log2FC, df.heatmap$log2FC), trace = \"n\", \n Colv = NA, dendrogram = \"none\", labCol = \"\", \n labRow = df.heatmap$Gene_name, cexRow = 0.75, \n col = colorRampPalette(c(\"red\", \"white\", \"blue\")))\n\ngrid.echo()\np2 <- wrap_elements(grid.grab())\n\np1 + p2\n heatmap.2 library(ggplot2)\nlibrary(patchwork)\n\np1 <- ggplot(df.bar,\n aes(fill = factor(Alteration.Type, levels = c('Point mutation',\n 'Amplification', \n 'Deep deletion')),\n y = Alteration.frequency, x = Gene.name)) + \n geom_col(position = \"stack\") +\n theme_bw() +\n theme(axis.text.x = element_blank()) +\n scale_fill_manual(values = c(\"seagreen2\", \"maroon2\", 'deepskyblue3')) +\n labs(fill = 'Alteration type', x = NULL)\n\np2 <- ggplot(df.heatmap, aes(y = \"A\", x = Gene_name,\n fill = log2FC)) +\n geom_tile() +\n scale_fill_viridis_c() +\n scale_y_discrete(NULL, position = \"right\") +\n scale_x_discrete(NULL, expand = c(0.17, 0.1)) +\n theme_minimal() +\n theme(axis.text.y = element_blank(),\n plot.title = element_blank())\n\np1 / p2 + plot_layout(height = c(3, 1))\n" }, { "answer_id": 74665705, "author": "Quinten", "author_id": 14282714, "author_profile": "https://Stackoverflow.com/users/14282714", "pm_score": 1, "selected": false, "text": "plot_grid cowplot ~ library(ggplot2)\nlibrary(cowplot)\nlibrary(gridGraphics)\nlibrary(gplots)\n\n# first plot\np1 <- ggplot(df.bar,\n aes(fill=factor(Alteration.Type, levels = c('Point mutation','Amplification','Deep deletion')),\n y=Alteration.frequency, x=Gene.name)) + \n geom_bar(position=\"stack\", stat=\"identity\")+theme_bw()+\n theme(axis.text.x = element_text(size = 10, angle = 45, hjust = 1, colour = 'black'))+\n scale_fill_manual(values=c(\"seagreen2\", \"maroon2\",'deepskyblue3'))+\n labs(fill = 'Alteration type')\n\n# Second plot\np2<- ~heatmap.2(cbind(df.heatmap$log2FC, df.heatmap$log2FC), trace=\"n\", Colv = NA, \n dendrogram = \"none\", labCol = \"\", labRow = df.heatmap$Gene_name, cexRow = 0.75,\n col=my_palette, key.par=list(mar=c(3,0,3,0), cex.main = 0.75), keysize = 1.5)\n\n# combine all plots together\nplot_grid(p1, p2)\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15521046/" ]
74,664,603
<p>I'm trying to create a graph that lists the high and low temperature per city on a specific day, but it seems like the y axes are just overlapping instead of plotting the point along it. Here is what I have:</p> <pre><code>fig, al = plt.subplots() al.scatter(al_cities, al_min) al.scatter(al_cities, al_max, c='red') al.plot(al_cities, al_min, c='lightblue') al.plot(al_cities, al_max, c='orange') al.fill_between(al_cities, al_max, al_min, facecolor='gray', alpha=.3) al.set_title('Highs and Lows in Alabama on January 10, 2016', fontsize=18) al.set_xlabel('City', fontsize=14) al.set_ylabel('Temperature', fontsize=14) </code></pre> <p>And this is what the graph looks like: <a href="https://i.stack.imgur.com/hw09H.png" rel="nofollow noreferrer">y-axis jumps around between numbers and doesn't count upwards</a></p>
[ { "answer_id": 74664864, "author": "ScottC", "author_id": 20174226, "author_profile": "https://Stackoverflow.com/users/20174226", "pm_score": 2, "selected": true, "text": "al_min al_max ['1','2','3'] [1,2,3] al_min = list(map(int, al_min))\nal_max = list(map(int, al_max))\n import matplotlib.pyplot as plt\n\n# Create the data for the example\nal_cities = ['Birmingham', 'Huntsville', 'Mobile', 'Montgomery']\nal_min = ['36','34', '39', '38']\nal_max = ['52', '50', '57', '55']\n\n# Convert strings to integers\nal_min = list(map(int, al_min))\nal_max = list(map(int, al_max))\n\n# Here is your code (unchanged)\nfig, al = plt.subplots()\nal.scatter(al_cities, al_min)\nal.scatter(al_cities, al_max, c='red')\nal.plot(al_cities, al_min, c='lightblue')\nal.plot(al_cities, al_max, c='orange')\nal.fill_between(al_cities, al_max, al_min, facecolor='gray', alpha=.3)\nal.set_title('Highs and Lows in Alabama on January 10, 2016', fontsize=18)\nal.set_xlabel('City', fontsize=14)\nal.set_ylabel('Temperature', fontsize=14)\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14490539/" ]
74,664,615
<p>I have a dataset that looks something like this:</p> <pre><code>name = c(&quot;john&quot;, &quot;john&quot;, &quot;john&quot;, &quot;alex&quot;,&quot;alex&quot;, &quot;tim&quot;, &quot;tim&quot;, &quot;tim&quot;, &quot;ralph&quot;, &quot;ralph&quot;) year = c(2010, 2011, 2012, 2011, 2012, 2010, 2011, 2012, 2014, 2016) my_data = data.frame(name, year) name year 1 john 2010 2 john 2011 3 john 2012 4 alex 2011 5 alex 2012 6 tim 2010 7 tim 2011 8 tim 2012 9 ralph 2014 10 ralph 2016 </code></pre> <p>I want to count the two following things in this dataset:</p> <ul> <li> <ol> <li><strong>Groups based on all years</strong></li> </ol> </li> <li> <ol start="2"> <li><strong>And of these groups, the number of groups with at least one non-consecutive year</strong></li> </ol> </li> </ul> <p>As an example for 1):</p> <pre><code># sample output for 1) year count 1 2010, 2011, 2012 2 2 2011, 2012 1 3 2014, 2016 1 </code></pre> <p>And as an example of 2) - only row 3 (in the above data frame) contains a missing year (i.e. 2014 to 2016 without 2015). Thus, the output would look something like this:</p> <pre><code># sample output for 2) year count 1 2014, 2016 1 </code></pre> <p>Can someone please show me how to do this in R? And is there a way to make sure that (2011, 2012) is considered the same as (2012, 2011) ? </p> <p>EDIT: For anyone using an older version of R, @Rui Barradas provided an answer for 2) - I have included it here so that there is no ambiguity when copy/pasting:</p> <pre><code>agg &lt;- aggregate(year ~ name, my_data, c) agg &lt;- agg$year[sapply(agg$year, function(y) any(diff(y) != 1))] as.data.frame(table(sapply(agg, paste, collapse = &quot;, &quot;))) </code></pre>
[ { "answer_id": 74664749, "author": "Rui Barradas", "author_id": 8245406, "author_profile": "https://Stackoverflow.com/users/8245406", "pm_score": 3, "selected": true, "text": "# 1.\nagg <- aggregate(year ~ name, my_data, paste, collapse = \", \")\nas.data.frame(table(agg$year))\n#> Var1 Freq\n#> 1 2010, 2011, 2012 2\n#> 2 2011, 2012 1\n#> 3 2014, 2016 1\n\n# 2.\nagg <- aggregate(year ~ name, my_data, c)\nagg <- agg$year[sapply(agg$year, \\(y) any(diff(y) != 1))]\nas.data.frame(table(sapply(agg, paste, collapse = \", \")))\n#> Var1 Freq\n#> 1 2014, 2016 1\n\n# final clean up\nrm(agg) \n name my_data <- my_data[order(my_data$name, my_data$year), ]\n" }, { "answer_id": 74664857, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 1, "selected": false, "text": "dplyr tidyr library(dplyr)\nlibrary(tidyr)\n\n### 1.\nmy_data %>% \n group_by(name) %>% \n mutate(year = toString(year)) %>% \n distinct(year) %>% \n ungroup() %>% \n count(year, name=\"count\")\n\nyear count\n<chr> <int>\n1 2010, 2011, 2012 2\n2 2011, 2012 1\n3 2014, 2016 1\n\n### 2. \nmy_data %>% \n group_by(name) %>% \n mutate(x = lead(year) - year) %>% \n fill(x, .direction = \"down\") %>% \n ungroup () %>% \n filter(x >= max(x)) %>% \n mutate(year = toString(year)) %>% \n distinct(year) %>% \n ungroup() %>% \n count(year, name=\"count\")\n\nyear count\n<chr> <int>\n1 2014, 2016 1\n" }, { "answer_id": 74665094, "author": "jay.sf", "author_id": 6574038, "author_profile": "https://Stackoverflow.com/users/6574038", "pm_score": 1, "selected": false, "text": "toString sort by by(my_data$year, my_data$name, \\(x) toString(sort(x))) |> table() |> as.data.frame()\n# Var1 Freq\n# 1 2010, 2011, 2012 2\n# 2 2011, 2012 1\n# 3 2014, 2016 1\n set.seed(42)\nmy_data <- my_data[sample(nrow(my_data)), ]\nby(my_data$year, my_data$name, \\(x) toString(sort(x))) |> table() |> as.data.frame()\n# Var1 Freq\n# 1 2010, 2011, 2012 2\n# 2 2011, 2012 1\n# 3 2014, 2016 1\n my_data <- structure(list(name = c(\"john\", \"john\", \"john\", \"alex\", \"alex\", \n\"tim\", \"tim\", \"tim\", \"ralph\", \"ralph\"), year = c(2010, 2011, \n2012, 2011, 2012, 2010, 2011, 2012, 2014, 2016)), class = \"data.frame\", row.names = c(NA, \n-10L))\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13203841/" ]
74,664,657
<p>Given an array of songs that are different versions of the same song:</p> <pre><code>const songArray = [&quot;Holiday&quot;, &quot;Holiday - Remastered Remix&quot;, &quot;Holiday - Live in Portugal&quot;, &quot;Holiday (Remix)&quot;, &quot;Like a Prayer&quot;, &quot;Like a Prayer - Remaster&quot;, &quot;Like a Prayer - Remixed 2012&quot;, &quot;Music&quot;, &quot;Music (Remix)&quot; ] </code></pre> <p>How can I loop through using another array of &quot;filter words&quot; I've created:</p> <pre><code>const filterWords = [&quot;Remaster&quot;, &quot;- Live in&quot;, &quot;Remix&quot;] </code></pre> <p>To get back everything that does NOT include those filters.</p> <p>ie:</p> <pre><code>const filteredSongs = [&quot;Holiday&quot;, &quot;Like a Prayer&quot;, &quot;Music&quot;] </code></pre> <p>I've tried finding the answer online, but I seem to only find examples that search for one filter word, not multiple.</p> <p>I've tried nested looping, .includes(), .filter(), and I'm also having problems because some tracks will contain more than one of the filter words (eg. &quot;Holiday - Remastered Remix&quot; contains both &quot;Remaster&quot; and &quot;Remix&quot;), and so will be pushed to a new array twice.</p> <p>something like:</p> <pre><code> songArray = [&quot;Holiday&quot;, &quot;Holiday - Remastered Remix&quot;, &quot;Holiday - Live in Portugal&quot;, &quot;Holiday (Remix)&quot;, &quot;Like a Prayer&quot;, &quot;Like a Prayer - Remaster&quot;, &quot;Like a Prayer - Remixed 2012&quot;, &quot;Music&quot;, &quot;Music (Remix)&quot; ] const filterWords = [&quot;Remaster&quot;, &quot;- Live in&quot;, &quot;Remix&quot;] newArray = [] songArray.forEach((song) =&gt; { filterWords.forEach((filterWord) =&gt; { if song.includes(filterWord){ newArray.push(song) }) }) </code></pre> <p>expected: [&quot;Holiday&quot;, &quot;Like a Prayer&quot;, &quot;Music&quot;]</p>
[ { "answer_id": 74664688, "author": "Amila Senadheera", "author_id": 8510405, "author_profile": "https://Stackoverflow.com/users/8510405", "pm_score": 1, "selected": false, "text": "Array.prototype.some() const songArray = [ \"Holiday\", \"Holiday - Remastered Remix\", \"Holiday - Live in Portugal\", \"Holiday (Remix)\", \"Like a Prayer\", \"Like a Prayer - Remaster\", \"Like a Prayer - Remixed 2012\", \"Music\", \"Music (Remix)\", ];\n\nconst filterWords = [\"Remaster\", \"- Live in\", \"Remix\"];\n\nconst output = songArray.filter(\n (song) => !filterWords.some((word) => song.includes(word))\n);\n\nconsole.log(output);" }, { "answer_id": 74664713, "author": "Emilien", "author_id": 18143359, "author_profile": "https://Stackoverflow.com/users/18143359", "pm_score": 0, "selected": false, "text": "songArray = [\n \"Holiday\",\n \"Holiday - Remastered Remix\",\n \"Holiday - Live in Portugal\",\n \"Holiday (Remix)\",\n \"Like a Prayer\",\n \"Like a Prayer - Remaster\",\n \"Like a Prayer - Remixed 2012\",\n \"Music\",\n \"Music (Remix)\",\n];\n\nconst filterWords = [\"Remaster\", \"- Live in\", \"Remix\"];\n\nnewArray = [];\n\nsongArray.forEach((song) => {\n let found = false;\n filterWords.forEach((filterWord) => {\n if (song.includes(filterWord)) {\n found = true;\n }\n });\n if (!found) {\n newArray.push(song);\n }\n});\n\nconsole.log(newArray);\n\n" }, { "answer_id": 74664715, "author": "Emiel Zuurbier", "author_id": 11619647, "author_profile": "https://Stackoverflow.com/users/11619647", "pm_score": 0, "selected": false, "text": "filter every const songs = [\"Holiday\", \"Holiday - Remastered Remix\", \"Holiday - Live in Portugal\", \"Holiday (Remix)\", \"Like a Prayer\", \"Like a Prayer - Remaster\", \"Like a Prayer - Remixed 2012\", \"Music\", \"Music (Remix)\"];\n\nconst filters = [\"Remaster\", \"- Live in\", \"Remix\"];\n\nconst filteredSongs = songs.filter(song => \n filters.every(filter => !song.includes(filter))\n);\n\nconsole.log(filteredSongs);" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20672514/" ]
74,664,671
<p>I am trying to make a responsive card layout as shown in the image.</p> <p><a href="https://i.stack.imgur.com/Bzgbd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Bzgbd.png" alt="enter image description here" /></a></p> <p>Currently what I am doing is that I am separately creating layouts for computers, tablets and mobile. then which the help of a <code>media query</code> I set the display property as <code>display: none</code> for the other two views.</p> <p>For example: if I am in computer view the card layout for the computer will not have a display set as none while the other two will have a <code>display as none</code>.</p> <p>This works but is causing a lot of redundancy. There is a way to achieve all three layouts using a flex or grid.</p> <p>Please guide me.</p>
[ { "answer_id": 74664781, "author": "Ashok Shah", "author_id": 1530567, "author_profile": "https://Stackoverflow.com/users/1530567", "pm_score": 2, "selected": true, "text": "/* tablet view */\n@media only screen and (max-width: 768px){\n .parent-container {\n max-width: 320px;\n }\n}\n\n\n/* mobile view */\n@media only screen and (max-width: 480px){\n .parent-container {\n flex-direction: column;\n align-items: center;\n }\n}\n" }, { "answer_id": 74664960, "author": "SQZ11", "author_id": 15363754, "author_profile": "https://Stackoverflow.com/users/15363754", "pm_score": 0, "selected": false, "text": "display: none min-width: 768px max-width: 600px orientation //for mobile\n @media query and only screen(max-width: 600px) \n {\n display:flex;\n //some more css-code\n }\n \n//for tablet\n @media query and only screen(min-width: 600px) \n {\n\n display: flex;\n //some more css-code\n\n }\n \n//for desktop size\n @media query and only screen(min-width: 768px) \n {\n display: flex;\n //some more css-Code\n }" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17348251/" ]
74,664,718
<p>Is there any way in which we can have literal '#' character in replacement-list of C preprocessor macro?</p> <p>'#' character in replacement-list of C preprocessor is an operator that performs stringification of argument, for example-</p> <pre><code>#define foo(words) #words foo(Hello World!) </code></pre> <p>will result-</p> <pre><code>&quot;Hello World!&quot; </code></pre> <p>Is there any way we can have '#' as a literal character in replacement-list like-</p> <pre><code>#define foo(p1, p2) p1 # p2 // ^ is there any way to specify that- this isn't # operator? foo(arg1, arg2) // will result- arg1 &quot;arg2&quot; // What I wanted was // arg1 # arg2 </code></pre> <p>I tried a macro like-</p> <pre><code>#define foo(p1, p2, p3) p1 p2 p3 // And then foo(arg1, #, arg2) // Which resulted in arg1 # arg2 </code></pre> <p>This was getting the work done but wasn't better than typing <code>arg1 # arg2</code> manually.</p> <p>Then I tried defining a <code>foo</code> macro which in turn will call <code>metafoo</code> with '#' as argument-</p> <pre><code>#define metafoo(p1, p2, p3) p1 p2 p3 #define foo(p1, p2) metafoo(p1, #, p2) foo(arg1, arg2) </code></pre> <p>which resulted in a error <code>error: '#' is not followed by a macro parameter</code>, because # was getting interpreted like stringification operator.</p>
[ { "answer_id": 74664781, "author": "Ashok Shah", "author_id": 1530567, "author_profile": "https://Stackoverflow.com/users/1530567", "pm_score": 2, "selected": true, "text": "/* tablet view */\n@media only screen and (max-width: 768px){\n .parent-container {\n max-width: 320px;\n }\n}\n\n\n/* mobile view */\n@media only screen and (max-width: 480px){\n .parent-container {\n flex-direction: column;\n align-items: center;\n }\n}\n" }, { "answer_id": 74664960, "author": "SQZ11", "author_id": 15363754, "author_profile": "https://Stackoverflow.com/users/15363754", "pm_score": 0, "selected": false, "text": "display: none min-width: 768px max-width: 600px orientation //for mobile\n @media query and only screen(max-width: 600px) \n {\n display:flex;\n //some more css-code\n }\n \n//for tablet\n @media query and only screen(min-width: 600px) \n {\n\n display: flex;\n //some more css-code\n\n }\n \n//for desktop size\n @media query and only screen(min-width: 768px) \n {\n display: flex;\n //some more css-Code\n }" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9724232/" ]
74,664,728
<p>I am trying to do this problem:</p> <p><a href="https://www.chegg.com/homework-help/questions-and-answers/blocks-pyramid-def-pyramidblocks-n-m-h-pyramid-structure-although-ancient-mesoamerican-fam-q38542637" rel="nofollow noreferrer">https://www.chegg.com/homework-help/questions-and-answers/blocks-pyramid-def-pyramidblocks-n-m-h-pyramid-structure-although-ancient-mesoamerican-fam-q38542637</a></p> <p>This is my code:</p> <pre><code>def pyramid_blocks(n, m, h): return sum((n+i)*(m+i) for i in range(h)) </code></pre> <p>But the problem is that whenever I try to test it, it tells me that it is too slow, so is there a way to make it take less time? I also tried to do it with lists, but with that too it takes too much time.</p> <pre><code>def pyramid_blocks(n, m, h): return sum((n+i)*(m+i) for i in range(h)) </code></pre> <pre><code>def pyramid_blocks(n, m, h): r=[] t=[] mlp=[] for i in range(h): r.append(n+i) t.append(m+i) for i, j in zip(r,t): mlp.append(i*j) return sum(mlp) </code></pre>
[ { "answer_id": 74664781, "author": "Ashok Shah", "author_id": 1530567, "author_profile": "https://Stackoverflow.com/users/1530567", "pm_score": 2, "selected": true, "text": "/* tablet view */\n@media only screen and (max-width: 768px){\n .parent-container {\n max-width: 320px;\n }\n}\n\n\n/* mobile view */\n@media only screen and (max-width: 480px){\n .parent-container {\n flex-direction: column;\n align-items: center;\n }\n}\n" }, { "answer_id": 74664960, "author": "SQZ11", "author_id": 15363754, "author_profile": "https://Stackoverflow.com/users/15363754", "pm_score": 0, "selected": false, "text": "display: none min-width: 768px max-width: 600px orientation //for mobile\n @media query and only screen(max-width: 600px) \n {\n display:flex;\n //some more css-code\n }\n \n//for tablet\n @media query and only screen(min-width: 600px) \n {\n\n display: flex;\n //some more css-code\n\n }\n \n//for desktop size\n @media query and only screen(min-width: 768px) \n {\n display: flex;\n //some more css-Code\n }" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20672626/" ]
74,664,741
<p>I am trying to add Notification feature in Moodle Mobile App using Firebase Cloud Messaging, and I am getting an error while building the Ionic app.</p> <blockquote> <p>cordova build android Conflict found, edit-config changes from config.xml will overwrite plugin.xml changes Removing permission &quot;android.permission.REQUEST_INSTALL_PACKAGES&quot; from AndroidManifest.xml cordova-plugin-androidx-adapter: Processed 122 source files in 3077ms [cordova-plugin-push::before-compile] skipping before_compile hookscript. Checking Java JDK and Android SDK versions ANDROID_SDK_ROOT=/home/egp/Android/Sdk (recommended setting) ANDROID_HOME=/home/egp/Android/Sdk (DEPRECATED) Using Android SDK: /home/egp/Android/Sdk Starting a Gradle Daemon, 2 incompatible and 1 stopped Daemons could not be reused, use --status for details</p> <p>Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.</p> <p>You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.</p> <p>See <a href="https://docs.gradle.org/7.5.1/userguide/command_line_interface.html#sec:command_line_warnings" rel="nofollow noreferrer">https://docs.gradle.org/7.5.1/userguide/command_line_interface.html#sec:command_line_warnings</a></p> <p>BUILD SUCCESSFUL in 41s 1 actionable task: 1 executed Subproject Path: CordovaLib Subproject Path: app Starting a Gradle Daemon, 1 busy and 2 incompatible and 1 stopped Daemons could not be reused, use --status for details</p> <p>Configure project :app Adding classpath: com.google.gms:google-services:4.3.10 Warning: The 'kotlin-android-extensions' Gradle plugin is deprecated. Please use this migration guide (<a href="https://goo.gle/kotlin-android-extensions-deprecation" rel="nofollow noreferrer">https://goo.gle/kotlin-android-extensions-deprecation</a>) to start working with View Binding (<a href="https://developer.android.com/topic/libraries/view-binding" rel="nofollow noreferrer">https://developer.android.com/topic/libraries/view-binding</a>) and the 'kotlin-parcelize' plugin. WARNING:: Configuration 'compile' is obsolete and has been replaced with 'implementation' and 'api'. It will be removed in version 7.0 of the Android Gradle plugin. For more information, see <a href="http://d.android.com/r/tools/update-dependency-configurations.html" rel="nofollow noreferrer">http://d.android.com/r/tools/update-dependency-configurations.html</a>.</p> <p>FAILURE: Build failed with an exception.</p> <p>Where: Build file '/home/egp/moodleapp_with_notification_github/moodleapp/platforms/android/app/build.gradle' line: 352</p> <p>What went wrong: A problem occurred evaluating project ':app'. Failed to apply plugin 'com.google.gms.google-services'. Cannot add extension with name 'googleServices', as there is an extension already registered with that name.</p> <p>Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.</p> <p>Get more help at <a href="https://help.gradle.org" rel="nofollow noreferrer">https://help.gradle.org</a></p> <p>Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.</p> <p>You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.</p> <p>See <a href="https://docs.gradle.org/7.1.1/userguide/command_line_interface.html#sec:command_line_warnings" rel="nofollow noreferrer">https://docs.gradle.org/7.1.1/userguide/command_line_interface.html#sec:command_line_warnings</a></p> <p>BUILD FAILED in 1m 11s Command failed with exit code 1: /home/egp/moodleapp_with_notification_github/moodleapp/platforms/android/gradlew cdvBuildDebug -b /home/egp/moodleapp_with_notification_github/moodleapp/platforms/android/build.gradle [ERROR] An error occurred while running subprocess cordova.</p> <p>cordova build android exited with exit code 1.</p> <p>Re-running this command with the --verbose flag may provide more information.</p> </blockquote>
[ { "answer_id": 74664781, "author": "Ashok Shah", "author_id": 1530567, "author_profile": "https://Stackoverflow.com/users/1530567", "pm_score": 2, "selected": true, "text": "/* tablet view */\n@media only screen and (max-width: 768px){\n .parent-container {\n max-width: 320px;\n }\n}\n\n\n/* mobile view */\n@media only screen and (max-width: 480px){\n .parent-container {\n flex-direction: column;\n align-items: center;\n }\n}\n" }, { "answer_id": 74664960, "author": "SQZ11", "author_id": 15363754, "author_profile": "https://Stackoverflow.com/users/15363754", "pm_score": 0, "selected": false, "text": "display: none min-width: 768px max-width: 600px orientation //for mobile\n @media query and only screen(max-width: 600px) \n {\n display:flex;\n //some more css-code\n }\n \n//for tablet\n @media query and only screen(min-width: 600px) \n {\n\n display: flex;\n //some more css-code\n\n }\n \n//for desktop size\n @media query and only screen(min-width: 768px) \n {\n display: flex;\n //some more css-Code\n }" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19052339/" ]
74,664,746
<p>I am attempting to populate values from one DataFrame to another DataFrame based on a common column present in both DataFrames.</p> <p>The code I wrote for this operation is as follows:</p> <pre><code>for i in df1.zipcodes: for j in df2.zipcodes.unique(): if i == j: #print(&quot;this is i:&quot;,i, &quot;this is j:&quot;,j) df1['rent'] = df2['rent'] </code></pre> <p>The Dataframes (df1) in question looks as such with shape (131942, 2):</p> <pre><code>Providing 1st ten rows of df1: zipcodes districts 018906 01 018907 01 018910 01 018915 01 018916 01 018925 01 018926 01 018927 01 018928 01 018929 01 018930 01 Additionally, there are no duplicates for the Zipcodes column, but the district column has 28 unique values. No Nan values are present. </code></pre> <p>The other DataFrame(df2) looks as such with shape (77996, 4)</p> <pre><code> Providing 1st ten rows of df2 street zipcodes district rent E ROAD 545669 15 3600 E ROAD 545669 15 6200 E ROAD 545669 15 5500 E ROAD 545669 15 3200 H DRIVE 459108 19 3050 H DRIVE 459108 19 2000 A VIEW 098619 03 4200 A VIEW 098619 03 4500 J ROAD 018947 10 19500 O DRIVE 100088 04 9600 Note: The Zipcodes in df2 can repeat. </code></pre> <p>Now, I want to populate a column in df1 called rent, if the zipcodes in df1 matches the zipcode of df2. If the zipcodes match but there are multiple entries with the same zipcode in df2 then I want to populate the average as the rent. If there is only one entry for the zipcode then I want to populate the rent corresponding to that zipcode.</p> <p>Any help on the above will be greatly appreciated.</p>
[ { "answer_id": 74664781, "author": "Ashok Shah", "author_id": 1530567, "author_profile": "https://Stackoverflow.com/users/1530567", "pm_score": 2, "selected": true, "text": "/* tablet view */\n@media only screen and (max-width: 768px){\n .parent-container {\n max-width: 320px;\n }\n}\n\n\n/* mobile view */\n@media only screen and (max-width: 480px){\n .parent-container {\n flex-direction: column;\n align-items: center;\n }\n}\n" }, { "answer_id": 74664960, "author": "SQZ11", "author_id": 15363754, "author_profile": "https://Stackoverflow.com/users/15363754", "pm_score": 0, "selected": false, "text": "display: none min-width: 768px max-width: 600px orientation //for mobile\n @media query and only screen(max-width: 600px) \n {\n display:flex;\n //some more css-code\n }\n \n//for tablet\n @media query and only screen(min-width: 600px) \n {\n\n display: flex;\n //some more css-code\n\n }\n \n//for desktop size\n @media query and only screen(min-width: 768px) \n {\n display: flex;\n //some more css-Code\n }" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15183282/" ]
74,664,861
<p>I would like to ask question related to fetching. I'm required to create a weather website. For this, firstly, I registered in weather api, got a key, and formulated my 'url' by following api doc. Now, the url itself seems works; 'https://api.openweathermap.org/data/2.5/weather?q=London&amp;units=metric&amp;appid=01d9f2d66b5fb9c863aa86b5cb001cd2', because the details are shown when paste in browser. The problem itself is that, when I use 'url' in my code with 'fetch', the api doesn't provide any info. the code is the following:</p> <pre><code>let weather = { fetchWeather : function() { fetch(&quot;https://api.openweathermap.org/data/2.5/weather?q=London&amp;units=metric&amp;appid=01d9f2d66b5fb9c863aa86b5cb001cd2&quot;) .then((response) =&gt; response.json()) .then((data) =&gt; console.log(data)); }, }; </code></pre> <p>the result:</p> <pre><code>VM1176:3 GET https://api.openweathermap.org/data/2.5/weather?q=London&amp;units=metric&amp;appid=01d9f2d66b5fb9c863aa86b5cb001cd2 net::ERR_FAILED fetchWeather @ VM1176:3 (anonymous) @ VM1217:1 VM1176:3 Uncaught (in promise) TypeError: Failed to fetch at Object.fetchWeather (&lt;anonymous&gt;:3:9) at &lt;anonymous&gt;:1:9 </code></pre> <p>could you pls help me how to solve the problem?</p> <p>I want to know why the problem occurs and how to solve it</p>
[ { "answer_id": 74664957, "author": "JohnVersus", "author_id": 9243755, "author_profile": "https://Stackoverflow.com/users/9243755", "pm_score": -1, "selected": false, "text": "let weather = {\n fetchWeather : function() {\n const requestOptions = {\n method: 'GET',\n redirect: 'follow'\n };\n\nfetch(\"https://api.openweathermap.org/data/2.5/weather?q=London&units=metric&appid=01d9f2d66b5fb9c863aa86b5cb001cd2\", requestOptions)\n .then(response => response.json())\n .then(result => console.log(result))\n .catch(error => console.log('error', error));\n },\n};\n" }, { "answer_id": 74679738, "author": "Philippe Fery", "author_id": 10675247, "author_profile": "https://Stackoverflow.com/users/10675247", "pm_score": 0, "selected": false, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <script> \n function fetchWeather() {\n var city = document.getElementById('city').value;\n var metrics = document.getElementById('metrics').value;\n \n let weather = fetch(\n \"https://api.openweathermap.org/data/2.5/weather?\"\n + new URLSearchParams(\n {\n q: city,\n units: metrics,\n appid: '01d9f2d66b5fb9c863aa86b5cb001cd2'\n }\n )\n )\n .then(response => response.json())\n .then(jsonObj => JSON.stringify(jsonObj))\n .then(data => console.log(data));\n }\n </script>\n</head>\n\n<body>\n <section>\n <form action=\"javascript:fetchWeather();\">\n <input type=\"text\" id=\"city\" name=\"city\"><br>\n <input type=\"radio\" id=\"metrics\" name=\"unitType\" value=\"metrics\" checked=\"checked\">\n <label for=\"metrics\">Metrics</label><br>\n <input type=\"radio\" id=\"imperial\" name=\"unitType\" value=\"imperial\">\n <label for=\"imperial\">Imperial</label><br>\n <input type=\"submit\" value=\"Submit\">\n </form>\n </section>\n</body>\n</html>\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19063067/" ]
74,664,870
<p>I have two dictionaries:</p> <pre><code>first_dict = {'a': ['1', '2', '3'], 'b': ['4', '5'], 'c': ['6'], } </code></pre> <pre><code>second_dict = {'1': 'wqeewe', '2': 'efsafa', '4': 'fsasaf', '6': 'kgoeew', '7': 'fkowew' } </code></pre> <p>I want to have a third dict that will contain the key of second_dict and its corresponding value from first_dict's key. This way, I will have :</p> <pre><code>third_dict = {'1' : 'a', '2' : 'a', '4' : 'b', '6' : 'c', '7' : None, } </code></pre> <p>here is my way:</p> <pre><code>def key_return(name): for key, value in first_dict.items(): if name == value: return key if isinstance(value, list) and name in value: return key return None </code></pre> <p>reference: <a href="https://stackoverflow.com/questions/69134423/python-return-key-from-value-but-its-a-list-in-the-dictionary">Python return key from value, but its a list in the dictionary</a></p> <p>However, I wondering that the another way using dict.get() or something else. Any help would be appreciated. Thanks.</p>
[ { "answer_id": 74665012, "author": "pizoooo", "author_id": 10902484, "author_profile": "https://Stackoverflow.com/users/10902484", "pm_score": 1, "selected": false, "text": "first_dict = {'a': ['1', '2', '3'],\n 'b': ['4', '5'],\n 'c': ['6'],\n }\n\nsecond_dict = {'1': 'wqeewe',\n '2': 'efsafa',\n '4': 'fsasaf',\n '6': 'kgoeew',\n '7': 'fkowew'\n }\n\nthird_dict = dict()\n\nfor second_key in second_dict.keys():\n found = False\n for first_key, value in first_dict.items():\n if second_key in value:\n third_dict.setdefault(second_key, first_key )\n found = True\n if not found:\n third_dict.setdefault(second_key, None)\n \nprint(third_dict)\n {'1': 'a', '2': 'a', '4': 'b', '6': 'c', '7': None}\n" }, { "answer_id": 74665027, "author": "Dmitriy Neledva", "author_id": 16786350, "author_profile": "https://Stackoverflow.com/users/16786350", "pm_score": 2, "selected": true, "text": "a_dict.get() third_dict = {i: {i:k for k,v in first_dict.items() for i in v}.get(i) for i in second_dict.keys()}\n {i:k for k,v in first_dict.items() for i in v} {'1': 'a', '2': 'a', '3': 'a', '4': 'b', '5': 'b', '6': 'c'}" }, { "answer_id": 74665055, "author": "Igor Moraru", "author_id": 4645291, "author_profile": "https://Stackoverflow.com/users/4645291", "pm_score": 0, "selected": false, "text": "values_map = dict([a for k, v in first_dict.items() for a in zip(v, k*len(v))])\n third_dict = {key: values_map.get(key) for key, value in second_dict.items()}\n first_dict = dict(map(lambda x: (x[0], x[1]) if isinstance(x[1], list) else (x[0], [str(x[1])]), first_dict.items()))\n" }, { "answer_id": 74665361, "author": "gog", "author_id": 3494774, "author_profile": "https://Stackoverflow.com/users/3494774", "pm_score": 0, "selected": false, "text": "res = {\n x: k\n for k, xs in first_dict.items()\n for x in xs\n if x in second_dict\n}\n 1:a , 2:a, 4:b 7:None res = {k: None for k in second_dict} | {\n x: k\n for k, xs in first_dict.items()\n for x in xs\n if x in second_dict\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20395754/" ]
74,664,892
<p>I am trying to change the state in the App components from a child components and I fell i would result to an issue later in my app</p> <p>i tried passing the setFunction down to the child components then having it change the value in the app components</p>
[ { "answer_id": 74665012, "author": "pizoooo", "author_id": 10902484, "author_profile": "https://Stackoverflow.com/users/10902484", "pm_score": 1, "selected": false, "text": "first_dict = {'a': ['1', '2', '3'],\n 'b': ['4', '5'],\n 'c': ['6'],\n }\n\nsecond_dict = {'1': 'wqeewe',\n '2': 'efsafa',\n '4': 'fsasaf',\n '6': 'kgoeew',\n '7': 'fkowew'\n }\n\nthird_dict = dict()\n\nfor second_key in second_dict.keys():\n found = False\n for first_key, value in first_dict.items():\n if second_key in value:\n third_dict.setdefault(second_key, first_key )\n found = True\n if not found:\n third_dict.setdefault(second_key, None)\n \nprint(third_dict)\n {'1': 'a', '2': 'a', '4': 'b', '6': 'c', '7': None}\n" }, { "answer_id": 74665027, "author": "Dmitriy Neledva", "author_id": 16786350, "author_profile": "https://Stackoverflow.com/users/16786350", "pm_score": 2, "selected": true, "text": "a_dict.get() third_dict = {i: {i:k for k,v in first_dict.items() for i in v}.get(i) for i in second_dict.keys()}\n {i:k for k,v in first_dict.items() for i in v} {'1': 'a', '2': 'a', '3': 'a', '4': 'b', '5': 'b', '6': 'c'}" }, { "answer_id": 74665055, "author": "Igor Moraru", "author_id": 4645291, "author_profile": "https://Stackoverflow.com/users/4645291", "pm_score": 0, "selected": false, "text": "values_map = dict([a for k, v in first_dict.items() for a in zip(v, k*len(v))])\n third_dict = {key: values_map.get(key) for key, value in second_dict.items()}\n first_dict = dict(map(lambda x: (x[0], x[1]) if isinstance(x[1], list) else (x[0], [str(x[1])]), first_dict.items()))\n" }, { "answer_id": 74665361, "author": "gog", "author_id": 3494774, "author_profile": "https://Stackoverflow.com/users/3494774", "pm_score": 0, "selected": false, "text": "res = {\n x: k\n for k, xs in first_dict.items()\n for x in xs\n if x in second_dict\n}\n 1:a , 2:a, 4:b 7:None res = {k: None for k in second_dict} | {\n x: k\n for k, xs in first_dict.items()\n for x in xs\n if x in second_dict\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14215391/" ]
74,664,899
<p>I have a dataframe contains one column which has multiple strings separated by the comma, but in this string, I want to remove all matter after hyphen (including hyphen), main point is after in some cases hyphen is not there but directed parenthesis is there so I also want to remove that as well and carry all the after the comma how can I do it? You can see this case in last row.</p> <pre><code>dd = pd.DataFrame() dd['sin'] = ['U147(BCM), U35(BCM)','P01-00(ECM), P02-00(ECM)', 'P3-00(ECM), P032-00(ECM)','P034-00(ECM)', 'P23F5(PCM), P04-00(ECM)'] </code></pre> <p>Expected output</p> <pre><code>dd['sin'] # output U147 U35 P01 P02 P3 P032 P034 P23F5 P04 </code></pre> <p>Want to carry only string before the hyphen or parenthesis or any special character.</p>
[ { "answer_id": 74665011, "author": "Frodnar", "author_id": 15534441, "author_profile": "https://Stackoverflow.com/users/15534441", "pm_score": 1, "selected": false, "text": "dd['sin'] = dd['sin'].str.split(\", \")\ndd = dd.explode('sin').reset_index()\ndd['sin'] = dd['sin'].str.replace('\\W.*', '', regex=True)\n dd['sin'] 0 U147\n1 U35\n2 P01\n3 P02\n4 P3\n5 P032\n6 P034\n7 P23F5\n8 P04\nName: sin, dtype: object\n .reset_index()" }, { "answer_id": 74665381, "author": "ScottC", "author_id": 20174226, "author_profile": "https://Stackoverflow.com/users/20174226", "pm_score": 1, "selected": true, "text": "r\"-\\d{2}|\\([EBP]CM\\)|\\s\"\n sin = ['U147(BCM), U35(BCM)','P01-00(ECM), P02-00(ECM)', 'P3-00(ECM), P032-00(ECM)','P034-00(ECM)', 'P23F5(PCM), P04-00(ECM)']\n\ndd = pd.DataFrame()\ndd['sin'] = sin\ndd['sin'] = dd['sin'].str.replace(r'-\\d{2}|\\([EBP]CM\\)|\\s', '', regex=True)\nprint(dd)\n sin\n0 U147,U35\n1 P01,P02\n2 P3,P032\n3 P034\n4 P23F5,P04\n dd['sin'] = dd['sin'].str.replace(r'-\\d{2}|\\([EBP]CM\\)|\\s', '', regex=True).str.replace(',',' ')\n sin\n0 U147 U35\n1 P01 P02\n2 P3 P032\n3 P034\n4 P23F5 P04\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15543946/" ]
74,664,926
<p>I have visualization like this:</p> <p><img src="https://i.stack.imgur.com/iEuqw.png" alt="enter image description here" /></p> <p>I want to change the marker icon into a <strong>football icon</strong> with the <strong>same color as the line</strong></p> <p>My code looks like this :</p> <pre><code>fig, ax = plt.subplots(figsize=(12,6)) ax.step(x = a_df['minute'], y = a_df['a_cum'], where = 'post', label= ateam, linewidth=2) ax.step(x = h_df['minute'], y = h_df['h_cum'], where = 'post', color ='red', label= hteam,linewidth=2) plt.scatter(x= a_goal['minute'], y = a_goal['a_cum'] , marker = 'o') plt.scatter(x= h_goal['minute'], y = h_goal['h_cum'] , marker = 'o',color = 'red') plt.xticks([0,15,30,45,60,75,90]) plt.yticks([0, 0.5, 1, 1.5, 2, 2.5, 3]) plt.grid() ax.title.set_text('The Expected Goals(xG) Chart Final Champions League 2010/2011') plt.ylabel(&quot;Expected Goals (xG)&quot;) plt.xlabel(&quot;Minutes&quot;) ax.legend() plt.show() </code></pre> <p>I don't have any clue to do it.</p>
[ { "answer_id": 74665691, "author": "GenZ", "author_id": 19921706, "author_profile": "https://Stackoverflow.com/users/19921706", "pm_score": 1, "selected": true, "text": "matplotlib import matplotlib.pyplot as plt\nfrom matplotlib.offsetbox import OffsetImage, AnnotationBbox\n\ndef getImage(path):\n return OffsetImage(plt.imread(path), zoom=.02)\nx_coords = [8.2, 4.5, 3.3, 6.9]\ny_coords = [5.4, 3.5, 4.7, 7.1]\nfig, ax = plt.subplots()\nfor x0, y0 in zip(x_coords, y_coords):\n ab = AnnotationBbox(getImage('football_icon.png'), (x0, y0), frameon=False)\n ax.add_artist(ab)\n \nplt.xticks(range(10))\nplt.yticks(range(10))\nplt.show()\n" }, { "answer_id": 74666383, "author": "virxen", "author_id": 12860757, "author_profile": "https://Stackoverflow.com/users/12860757", "pm_score": 1, "selected": false, "text": "import matplotlib.pyplot as plt\nfrom matplotlib.path import Path\n\nvertices=[[ 1.86622681e+00, -9.69864442e+01], [-5.36324682e+01, -9.69864442e+01],\n [-9.86337733e+01, -5.19851396e+01], [-9.86337733e+01, 3.51356038e+00],\n [-9.86337733e+01, 5.90122504e+01], [-5.36324682e+01, 1.04013560e+02],\n [ 1.86622681e+00, 1.04013560e+02], [ 5.73649168e+01, 1.04013560e+02],\n [ 1.02366227e+02, 5.90122504e+01], [ 1.02366227e+02, 3.51356038e+00],\n [ 1.02366227e+02, -5.19851396e+01], [ 5.73649168e+01, -9.69864442e+01],\n [ 1.86622681e+00, -9.69864442e+01], [ 1.86622681e+00, -9.69864442e+01],\n [ 1.86622681e+00, -9.69864442e+01], [ 1.86622681e+00, -9.59864442e+01], \n [ 1.49396568e+01, -9.59864442e+01], [ 2.74005268e+01, -9.34457032e+01],\n [ 3.88349768e+01, -8.88614442e+01], [ 3.93477668e+01, -8.39473616e+01],\n [ 3.91766768e+01, -7.84211406e+01], [ 3.83349768e+01, -7.24551946e+01],\n [ 2.54705168e+01, -7.17582316e+01], [ 1.38598668e+01, -6.91771276e+01],\n [ 3.49122681e+00, -6.47364446e+01], [-5.88483119e+00, -7.07454276e+01],\n [-1.85084882e+01, -7.43878696e+01], [-3.31337732e+01, -7.44239446e+01],\n [-3.31639232e+01, -8.07006846e+01], [-3.34889082e+01, -8.56747886e+01],\n [-3.41025232e+01, -8.92676942e+01], [-2.29485092e+01, -9.35925582e+01],\n [-1.08166852e+01, -9.59864442e+01], [ 1.86622681e+00, -9.59864442e+01],\n [ 1.86622681e+00, -9.59864442e+01], [ 1.86622681e+00, -9.59864442e+01],\n [ 3.98974768e+01, -8.84239444e+01], [ 6.30273268e+01, -7.88377716e+01],\n [ 8.17782368e+01, -6.07995616e+01], [ 9.22412268e+01, -3.81426946e+01],\n [ 8.94287268e+01, -3.42676946e+01], [ 8.27048568e+01, -3.89413496e+01],\n [ 7.41977468e+01, -4.19580876e+01], [ 6.55537268e+01, -4.39551946e+01],\n [ 6.55507268e+01, -4.39600946e+01], [ 6.55258268e+01, -4.39502946e+01],\n [ 6.55225268e+01, -4.39551946e+01], [ 5.64622368e+01, -5.74584576e+01],\n [ 4.77347768e+01, -6.68825886e+01], [ 3.93037768e+01, -7.22051946e+01],\n [ 4.01409768e+01, -7.80795846e+01], [ 4.03596968e+01, -8.35092576e+01],\n [ 3.98975268e+01, -8.84239444e+01], [ 3.98974768e+01, -8.84239444e+01],\n [ 3.98974768e+01, -8.84239444e+01], [-3.33525232e+01, -7.34239446e+01],\n [-3.33343532e+01, -7.34304446e+01], [-3.33081932e+01, -7.34174446e+01],\n [-3.32900232e+01, -7.34239446e+01], [-1.87512102e+01, -7.34136546e+01],\n [-6.26111319e+00, -6.98403626e+01], [ 2.95997681e+00, -6.39239446e+01],\n [ 4.88356681e+00, -5.29429786e+01], [ 6.50358681e+00, -4.13393356e+01],\n [ 7.80372681e+00, -2.91114446e+01], [-8.09469019e+00, -1.58596306e+01],\n [-1.93481942e+01, -5.40333762e+00], [-2.47587732e+01, 1.32605538e+00],\n [-3.69631432e+01, -2.50275662e+00], [-4.85465082e+01, -5.39578762e+00],\n [-5.95087732e+01, -7.36144462e+00], [-6.28171902e+01, -1.66250136e+01],\n [-6.52187002e+01, -2.98372096e+01], [-6.58837732e+01, -4.57989446e+01],\n [-5.53582062e+01, -6.01863506e+01], [-4.45266302e+01, -6.94131916e+01],\n [-3.33525232e+01, -7.34239446e+01], [-3.33525232e+01, -7.34239446e+01],\n [-3.33525232e+01, -7.34239446e+01], [-7.57587732e+01, -4.67676946e+01],\n [-7.29041812e+01, -4.67440446e+01], [-6.99334012e+01, -4.63526666e+01],\n [-6.68837732e+01, -4.56426946e+01], [-6.62087282e+01, -2.96768106e+01],\n [-6.37905682e+01, -1.64255576e+01], [-6.04462732e+01, -7.04894462e+00],\n [-6.81326882e+01, 3.32535038e+00], [-7.26804032e+01, 1.40097104e+01],\n [-7.40712732e+01, 2.50135604e+01], [-7.99916232e+01, 2.63222104e+01],\n [-8.66133452e+01, 2.67559804e+01], [-9.31650233e+01, 2.54510604e+01],\n [-9.31681733e+01, 2.54460604e+01], [-9.31931223e+01, 2.54560604e+01],\n [-9.31962733e+01, 2.54510604e+01], [-9.44043873e+01, 2.37123804e+01],\n [-9.54279373e+01, 2.17334704e+01], [-9.63212733e+01, 1.95448104e+01],\n [-9.71662733e+01, 1.43262704e+01], [-9.76337733e+01, 8.97093038e+00],\n [-9.76337733e+01, 3.51356038e+00], [-9.76337733e+01, -1.43647536e+01],\n [-9.29174773e+01, -3.11438126e+01], [-8.46650232e+01, -4.56426946e+01],\n [-8.18063532e+01, -4.64180796e+01], [-7.88476312e+01, -4.67932816e+01],\n [-7.57587732e+01, -4.67676946e+01], [-7.57587732e+01, -4.67676946e+01],\n [-7.57587732e+01, -4.67676946e+01], [ 6.55224768e+01, -4.28926946e+01],\n [ 7.40107668e+01, -4.09146326e+01], [ 8.23640768e+01, -3.79999686e+01],\n [ 8.88662268e+01, -3.34864446e+01], [ 9.61553068e+01, -1.55950616e+01],\n [ 9.94808868e+01, -1.66158462e+00], [ 9.88662268e+01, 8.32606038e+00],\n [ 9.42289868e+01, 2.15752904e+01], [ 8.77410868e+01, 3.15965604e+01],\n [ 8.11474768e+01, 3.82010604e+01], [ 7.17659368e+01, 3.38334104e+01],\n [ 6.38899668e+01, 3.03415204e+01], [ 5.74912268e+01, 2.77635604e+01],\n [ 5.68036568e+01, 1.50717604e+01], [ 5.35581368e+01, -9.16606169e-02],\n [ 4.82412268e+01, -1.60489446e+01], [ 5.52234668e+01, -2.62259056e+01],\n [ 6.09897268e+01, -3.51652306e+01], [ 6.55224768e+01, -4.28926946e+01],\n [ 6.55224768e+01, -4.28926946e+01], [ 6.55224768e+01, -4.28926946e+01],\n [ 8.42872681e+00, -2.83614446e+01], [ 2.13772368e+01, -2.57261866e+01],\n [ 3.43239568e+01, -2.15154036e+01], [ 4.72724768e+01, -1.57364446e+01],\n [ 5.25849968e+01, 2.07647383e-01], [ 5.58247068e+01, 1.53619304e+01],\n [ 5.64912268e+01, 2.79510604e+01], [ 5.64917568e+01, 2.79612604e+01],\n [ 5.64906868e+01, 2.79721604e+01], [ 5.64912268e+01, 2.79822604e+01],\n [ 4.74302668e+01, 3.88992704e+01], [ 3.74260968e+01, 4.79380604e+01],\n [ 2.64912268e+01, 5.51072604e+01], [ 1.05529568e+01, 5.24508804e+01],\n [-4.02431919e+00, 4.78459804e+01], [-1.52900232e+01, 4.18885104e+01],\n [-1.91554652e+01, 2.63828404e+01], [-2.20678242e+01, 1.30703504e+01],\n [-2.40400232e+01, 1.98226038e+00], [-1.87588732e+01, -4.60782062e+00],\n [-7.49875919e+00, -1.50853886e+01], [ 8.42872681e+00, -2.83614946e+01],\n [ 8.42872681e+00, -2.83614446e+01], [ 8.42872681e+00, -2.83614446e+01],\n [ 9.97724768e+01, 8.82606038e+00], [ 1.01209977e+02, 9.29481038e+00],\n [ 9.97891268e+01, 3.41125404e+01], [ 8.92576668e+01, 5.64775904e+01],\n [ 7.29287268e+01, 7.31385604e+01], [ 7.01162268e+01, 7.01073104e+01],\n [ 7.65398468e+01, 5.90945204e+01], [ 8.04306168e+01, 4.87012104e+01],\n [ 8.18037268e+01, 3.89510604e+01], [ 8.85060268e+01, 3.22487504e+01],\n [ 9.50869868e+01, 2.21436404e+01], [ 9.97724768e+01, 8.82606038e+00],\n [ 9.97724768e+01, 8.82606038e+00], [ 9.97724768e+01, 8.82606038e+00],\n [-7.39150232e+01, 2.60448104e+01], [-6.92374072e+01, 3.77382804e+01],\n [-6.07391432e+01, 4.81501604e+01], [-4.84150232e+01, 5.72948104e+01],\n [-4.77543102e+01, 6.78197404e+01], [-4.56607662e+01, 7.76814004e+01],\n [-4.11025232e+01, 8.57010604e+01], [-4.52341512e+01, 8.65620704e+01],\n [-4.97579362e+01, 8.64646604e+01], [-5.46650232e+01, 8.53885604e+01],\n [-7.24317802e+01, 7.30970204e+01], [-8.60276902e+01, 5.51787904e+01],\n [-9.28212733e+01, 3.42010604e+01], [-9.28243733e+01, 3.41920604e+01],\n [-9.28181733e+01, 3.41792604e+01], [-9.28212733e+01, 3.41698604e+01],\n [-9.30130013e+01, 3.14875704e+01], [-9.31144113e+01, 2.89274504e+01],\n [-9.31337733e+01, 2.64511104e+01], [-8.65119202e+01, 2.77331304e+01],\n [-7.98647022e+01, 2.73522904e+01], [-7.39150232e+01, 2.60448604e+01],\n [-7.39150232e+01, 2.60448104e+01], [-7.39150232e+01, 2.60448104e+01],\n [-1.56650232e+01, 4.27948104e+01], [-4.35766519e+00, 4.87636404e+01],\n [ 1.01466668e+01, 5.33700304e+01], [ 2.60224768e+01, 5.60448104e+01],\n [ 2.85590568e+01, 6.43435004e+01], [ 3.07827468e+01, 7.29492504e+01],\n [ 3.27099768e+01, 8.18573104e+01], [ 2.55039768e+01, 9.03537704e+01],\n [ 1.39714968e+01, 9.64983204e+01], [-1.13376819e+00, 9.85135604e+01],\n [-1.57753392e+01, 9.71825004e+01], [-2.87516412e+01, 9.28553404e+01],\n [-4.00712732e+01, 8.55448104e+01], [-4.46513912e+01, 7.76614604e+01],\n [-4.67507882e+01, 6.78133804e+01], [-4.74150232e+01, 5.72323104e+01],\n [-3.59060892e+01, 5.27285604e+01], [-2.53218622e+01, 4.79159104e+01],\n [-1.56650232e+01, 4.27948104e+01], [-1.56650232e+01, 4.27948104e+01],\n [ 6.94599768e+01, 7.08573104e+01], [ 7.22412268e+01, 7.38573104e+01],\n [ 5.42332468e+01, 9.18657304e+01], [ 2.93485768e+01, 1.03013560e+02],\n [ 1.86622681e+00, 1.03013560e+02], [ 1.03891181e+00, 1.03013560e+02],\n [ 2.19951808e-01, 1.03002360e+02], [-6.02518192e-01, 1.02982360e+02],\n [-1.00876819e+00, 9.94823604e+01], [ 1.43154268e+01, 9.74387404e+01],\n [ 2.60994568e+01, 9.12180804e+01], [ 3.34912268e+01, 8.24823604e+01],\n [ 4.89375568e+01, 8.17496704e+01], [ 6.09313968e+01, 7.78789204e+01],\n [ 6.94599768e+01, 7.08573604e+01], [ 6.94599768e+01, 7.08573104e+01],\n [ 6.94599768e+01, 7.08573104e+01]]\ncodes=[1,4,4,4,4,4,4,4,4,4,4,4,4,2,79,\n1,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,2,79,\n1,4,4,4,2,4,4,4,4,4,4,4,4,4,4,4,4,2,79,\n1,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,2,79,\n1,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,2,79,\n1,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,2,79,\n1,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,2,79,\n1,2,4,4,4,2,4,4,4,4,4,4,2,79,\n1,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,2,79,\n1,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,79,\n1,2,4,4,4,4,4,4,2,4,4,4,4,4,4,2, 79]\nprint(Path.MOVETO,Path.LINETO,Path.CURVE3,Path.CURVE4,Path.CLOSEPOLY)\nball=Path(vertices,codes)\nfig, ax = plt.subplots(figsize=(12,6))\nplt.plot(15,1,color='b',marker=ball,markersize=30)\nplt.xticks([0,15,30,45,60,75,90])\nplt.yticks([0, 0.5, 1, 1.5, 2, 2.5, 3])\nplt.grid()\nax.title.set_text('The Expected Goals(xG) Chart Final Champions League 2010/2011')\nplt.ylabel(\"Expected Goals (xG)\")\nplt.xlabel(\"Minutes\")\nax.legend()\nplt.show()\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20336070/" ]
74,664,944
<p>Cannot instal nuxt and create app. I used <a href="https://nuxtjs.org/docs/get-started/installation" rel="nofollow noreferrer">https://nuxtjs.org/docs/get-started/installation</a> and <a href="https://github.com/nuxt/create-nuxt-app" rel="nofollow noreferrer">https://github.com/nuxt/create-nuxt-app</a> for creating app but this error occurs: &quot;create-nuxt-app&quot; is not internal or external command executed by a program or batch file.</p> <pre><code>npm ERR! path C:\Users\Acer\Desktop\nuxt npm ERR! command failed npm ERR! command C:\Windows\system32\cmd.exe /d /s /c create-nuxt-app &quot;hacker-news&quot; npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\Acer\AppData\Local\npm-cache\_logs\2022-12-03T06_03_59_129Z-debug-0.log``` Please help! PS: node js and npm are installed </code></pre>
[ { "answer_id": 74665691, "author": "GenZ", "author_id": 19921706, "author_profile": "https://Stackoverflow.com/users/19921706", "pm_score": 1, "selected": true, "text": "matplotlib import matplotlib.pyplot as plt\nfrom matplotlib.offsetbox import OffsetImage, AnnotationBbox\n\ndef getImage(path):\n return OffsetImage(plt.imread(path), zoom=.02)\nx_coords = [8.2, 4.5, 3.3, 6.9]\ny_coords = [5.4, 3.5, 4.7, 7.1]\nfig, ax = plt.subplots()\nfor x0, y0 in zip(x_coords, y_coords):\n ab = AnnotationBbox(getImage('football_icon.png'), (x0, y0), frameon=False)\n ax.add_artist(ab)\n \nplt.xticks(range(10))\nplt.yticks(range(10))\nplt.show()\n" }, { "answer_id": 74666383, "author": "virxen", "author_id": 12860757, "author_profile": "https://Stackoverflow.com/users/12860757", "pm_score": 1, "selected": false, "text": "import matplotlib.pyplot as plt\nfrom matplotlib.path import Path\n\nvertices=[[ 1.86622681e+00, -9.69864442e+01], [-5.36324682e+01, -9.69864442e+01],\n [-9.86337733e+01, -5.19851396e+01], [-9.86337733e+01, 3.51356038e+00],\n [-9.86337733e+01, 5.90122504e+01], [-5.36324682e+01, 1.04013560e+02],\n [ 1.86622681e+00, 1.04013560e+02], [ 5.73649168e+01, 1.04013560e+02],\n [ 1.02366227e+02, 5.90122504e+01], [ 1.02366227e+02, 3.51356038e+00],\n [ 1.02366227e+02, -5.19851396e+01], [ 5.73649168e+01, -9.69864442e+01],\n [ 1.86622681e+00, -9.69864442e+01], [ 1.86622681e+00, -9.69864442e+01],\n [ 1.86622681e+00, -9.69864442e+01], [ 1.86622681e+00, -9.59864442e+01], \n [ 1.49396568e+01, -9.59864442e+01], [ 2.74005268e+01, -9.34457032e+01],\n [ 3.88349768e+01, -8.88614442e+01], [ 3.93477668e+01, -8.39473616e+01],\n [ 3.91766768e+01, -7.84211406e+01], [ 3.83349768e+01, -7.24551946e+01],\n [ 2.54705168e+01, -7.17582316e+01], [ 1.38598668e+01, -6.91771276e+01],\n [ 3.49122681e+00, -6.47364446e+01], [-5.88483119e+00, -7.07454276e+01],\n [-1.85084882e+01, -7.43878696e+01], [-3.31337732e+01, -7.44239446e+01],\n [-3.31639232e+01, -8.07006846e+01], [-3.34889082e+01, -8.56747886e+01],\n [-3.41025232e+01, -8.92676942e+01], [-2.29485092e+01, -9.35925582e+01],\n [-1.08166852e+01, -9.59864442e+01], [ 1.86622681e+00, -9.59864442e+01],\n [ 1.86622681e+00, -9.59864442e+01], [ 1.86622681e+00, -9.59864442e+01],\n [ 3.98974768e+01, -8.84239444e+01], [ 6.30273268e+01, -7.88377716e+01],\n [ 8.17782368e+01, -6.07995616e+01], [ 9.22412268e+01, -3.81426946e+01],\n [ 8.94287268e+01, -3.42676946e+01], [ 8.27048568e+01, -3.89413496e+01],\n [ 7.41977468e+01, -4.19580876e+01], [ 6.55537268e+01, -4.39551946e+01],\n [ 6.55507268e+01, -4.39600946e+01], [ 6.55258268e+01, -4.39502946e+01],\n [ 6.55225268e+01, -4.39551946e+01], [ 5.64622368e+01, -5.74584576e+01],\n [ 4.77347768e+01, -6.68825886e+01], [ 3.93037768e+01, -7.22051946e+01],\n [ 4.01409768e+01, -7.80795846e+01], [ 4.03596968e+01, -8.35092576e+01],\n [ 3.98975268e+01, -8.84239444e+01], [ 3.98974768e+01, -8.84239444e+01],\n [ 3.98974768e+01, -8.84239444e+01], [-3.33525232e+01, -7.34239446e+01],\n [-3.33343532e+01, -7.34304446e+01], [-3.33081932e+01, -7.34174446e+01],\n [-3.32900232e+01, -7.34239446e+01], [-1.87512102e+01, -7.34136546e+01],\n [-6.26111319e+00, -6.98403626e+01], [ 2.95997681e+00, -6.39239446e+01],\n [ 4.88356681e+00, -5.29429786e+01], [ 6.50358681e+00, -4.13393356e+01],\n [ 7.80372681e+00, -2.91114446e+01], [-8.09469019e+00, -1.58596306e+01],\n [-1.93481942e+01, -5.40333762e+00], [-2.47587732e+01, 1.32605538e+00],\n [-3.69631432e+01, -2.50275662e+00], [-4.85465082e+01, -5.39578762e+00],\n [-5.95087732e+01, -7.36144462e+00], [-6.28171902e+01, -1.66250136e+01],\n [-6.52187002e+01, -2.98372096e+01], [-6.58837732e+01, -4.57989446e+01],\n [-5.53582062e+01, -6.01863506e+01], [-4.45266302e+01, -6.94131916e+01],\n [-3.33525232e+01, -7.34239446e+01], [-3.33525232e+01, -7.34239446e+01],\n [-3.33525232e+01, -7.34239446e+01], [-7.57587732e+01, -4.67676946e+01],\n [-7.29041812e+01, -4.67440446e+01], [-6.99334012e+01, -4.63526666e+01],\n [-6.68837732e+01, -4.56426946e+01], [-6.62087282e+01, -2.96768106e+01],\n [-6.37905682e+01, -1.64255576e+01], [-6.04462732e+01, -7.04894462e+00],\n [-6.81326882e+01, 3.32535038e+00], [-7.26804032e+01, 1.40097104e+01],\n [-7.40712732e+01, 2.50135604e+01], [-7.99916232e+01, 2.63222104e+01],\n [-8.66133452e+01, 2.67559804e+01], [-9.31650233e+01, 2.54510604e+01],\n [-9.31681733e+01, 2.54460604e+01], [-9.31931223e+01, 2.54560604e+01],\n [-9.31962733e+01, 2.54510604e+01], [-9.44043873e+01, 2.37123804e+01],\n [-9.54279373e+01, 2.17334704e+01], [-9.63212733e+01, 1.95448104e+01],\n [-9.71662733e+01, 1.43262704e+01], [-9.76337733e+01, 8.97093038e+00],\n [-9.76337733e+01, 3.51356038e+00], [-9.76337733e+01, -1.43647536e+01],\n [-9.29174773e+01, -3.11438126e+01], [-8.46650232e+01, -4.56426946e+01],\n [-8.18063532e+01, -4.64180796e+01], [-7.88476312e+01, -4.67932816e+01],\n [-7.57587732e+01, -4.67676946e+01], [-7.57587732e+01, -4.67676946e+01],\n [-7.57587732e+01, -4.67676946e+01], [ 6.55224768e+01, -4.28926946e+01],\n [ 7.40107668e+01, -4.09146326e+01], [ 8.23640768e+01, -3.79999686e+01],\n [ 8.88662268e+01, -3.34864446e+01], [ 9.61553068e+01, -1.55950616e+01],\n [ 9.94808868e+01, -1.66158462e+00], [ 9.88662268e+01, 8.32606038e+00],\n [ 9.42289868e+01, 2.15752904e+01], [ 8.77410868e+01, 3.15965604e+01],\n [ 8.11474768e+01, 3.82010604e+01], [ 7.17659368e+01, 3.38334104e+01],\n [ 6.38899668e+01, 3.03415204e+01], [ 5.74912268e+01, 2.77635604e+01],\n [ 5.68036568e+01, 1.50717604e+01], [ 5.35581368e+01, -9.16606169e-02],\n [ 4.82412268e+01, -1.60489446e+01], [ 5.52234668e+01, -2.62259056e+01],\n [ 6.09897268e+01, -3.51652306e+01], [ 6.55224768e+01, -4.28926946e+01],\n [ 6.55224768e+01, -4.28926946e+01], [ 6.55224768e+01, -4.28926946e+01],\n [ 8.42872681e+00, -2.83614446e+01], [ 2.13772368e+01, -2.57261866e+01],\n [ 3.43239568e+01, -2.15154036e+01], [ 4.72724768e+01, -1.57364446e+01],\n [ 5.25849968e+01, 2.07647383e-01], [ 5.58247068e+01, 1.53619304e+01],\n [ 5.64912268e+01, 2.79510604e+01], [ 5.64917568e+01, 2.79612604e+01],\n [ 5.64906868e+01, 2.79721604e+01], [ 5.64912268e+01, 2.79822604e+01],\n [ 4.74302668e+01, 3.88992704e+01], [ 3.74260968e+01, 4.79380604e+01],\n [ 2.64912268e+01, 5.51072604e+01], [ 1.05529568e+01, 5.24508804e+01],\n [-4.02431919e+00, 4.78459804e+01], [-1.52900232e+01, 4.18885104e+01],\n [-1.91554652e+01, 2.63828404e+01], [-2.20678242e+01, 1.30703504e+01],\n [-2.40400232e+01, 1.98226038e+00], [-1.87588732e+01, -4.60782062e+00],\n [-7.49875919e+00, -1.50853886e+01], [ 8.42872681e+00, -2.83614946e+01],\n [ 8.42872681e+00, -2.83614446e+01], [ 8.42872681e+00, -2.83614446e+01],\n [ 9.97724768e+01, 8.82606038e+00], [ 1.01209977e+02, 9.29481038e+00],\n [ 9.97891268e+01, 3.41125404e+01], [ 8.92576668e+01, 5.64775904e+01],\n [ 7.29287268e+01, 7.31385604e+01], [ 7.01162268e+01, 7.01073104e+01],\n [ 7.65398468e+01, 5.90945204e+01], [ 8.04306168e+01, 4.87012104e+01],\n [ 8.18037268e+01, 3.89510604e+01], [ 8.85060268e+01, 3.22487504e+01],\n [ 9.50869868e+01, 2.21436404e+01], [ 9.97724768e+01, 8.82606038e+00],\n [ 9.97724768e+01, 8.82606038e+00], [ 9.97724768e+01, 8.82606038e+00],\n [-7.39150232e+01, 2.60448104e+01], [-6.92374072e+01, 3.77382804e+01],\n [-6.07391432e+01, 4.81501604e+01], [-4.84150232e+01, 5.72948104e+01],\n [-4.77543102e+01, 6.78197404e+01], [-4.56607662e+01, 7.76814004e+01],\n [-4.11025232e+01, 8.57010604e+01], [-4.52341512e+01, 8.65620704e+01],\n [-4.97579362e+01, 8.64646604e+01], [-5.46650232e+01, 8.53885604e+01],\n [-7.24317802e+01, 7.30970204e+01], [-8.60276902e+01, 5.51787904e+01],\n [-9.28212733e+01, 3.42010604e+01], [-9.28243733e+01, 3.41920604e+01],\n [-9.28181733e+01, 3.41792604e+01], [-9.28212733e+01, 3.41698604e+01],\n [-9.30130013e+01, 3.14875704e+01], [-9.31144113e+01, 2.89274504e+01],\n [-9.31337733e+01, 2.64511104e+01], [-8.65119202e+01, 2.77331304e+01],\n [-7.98647022e+01, 2.73522904e+01], [-7.39150232e+01, 2.60448604e+01],\n [-7.39150232e+01, 2.60448104e+01], [-7.39150232e+01, 2.60448104e+01],\n [-1.56650232e+01, 4.27948104e+01], [-4.35766519e+00, 4.87636404e+01],\n [ 1.01466668e+01, 5.33700304e+01], [ 2.60224768e+01, 5.60448104e+01],\n [ 2.85590568e+01, 6.43435004e+01], [ 3.07827468e+01, 7.29492504e+01],\n [ 3.27099768e+01, 8.18573104e+01], [ 2.55039768e+01, 9.03537704e+01],\n [ 1.39714968e+01, 9.64983204e+01], [-1.13376819e+00, 9.85135604e+01],\n [-1.57753392e+01, 9.71825004e+01], [-2.87516412e+01, 9.28553404e+01],\n [-4.00712732e+01, 8.55448104e+01], [-4.46513912e+01, 7.76614604e+01],\n [-4.67507882e+01, 6.78133804e+01], [-4.74150232e+01, 5.72323104e+01],\n [-3.59060892e+01, 5.27285604e+01], [-2.53218622e+01, 4.79159104e+01],\n [-1.56650232e+01, 4.27948104e+01], [-1.56650232e+01, 4.27948104e+01],\n [ 6.94599768e+01, 7.08573104e+01], [ 7.22412268e+01, 7.38573104e+01],\n [ 5.42332468e+01, 9.18657304e+01], [ 2.93485768e+01, 1.03013560e+02],\n [ 1.86622681e+00, 1.03013560e+02], [ 1.03891181e+00, 1.03013560e+02],\n [ 2.19951808e-01, 1.03002360e+02], [-6.02518192e-01, 1.02982360e+02],\n [-1.00876819e+00, 9.94823604e+01], [ 1.43154268e+01, 9.74387404e+01],\n [ 2.60994568e+01, 9.12180804e+01], [ 3.34912268e+01, 8.24823604e+01],\n [ 4.89375568e+01, 8.17496704e+01], [ 6.09313968e+01, 7.78789204e+01],\n [ 6.94599768e+01, 7.08573604e+01], [ 6.94599768e+01, 7.08573104e+01],\n [ 6.94599768e+01, 7.08573104e+01]]\ncodes=[1,4,4,4,4,4,4,4,4,4,4,4,4,2,79,\n1,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,2,79,\n1,4,4,4,2,4,4,4,4,4,4,4,4,4,4,4,4,2,79,\n1,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,2,79,\n1,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,2,79,\n1,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,2,79,\n1,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,2,79,\n1,2,4,4,4,2,4,4,4,4,4,4,2,79,\n1,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,2,79,\n1,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,79,\n1,2,4,4,4,4,4,4,2,4,4,4,4,4,4,2, 79]\nprint(Path.MOVETO,Path.LINETO,Path.CURVE3,Path.CURVE4,Path.CLOSEPOLY)\nball=Path(vertices,codes)\nfig, ax = plt.subplots(figsize=(12,6))\nplt.plot(15,1,color='b',marker=ball,markersize=30)\nplt.xticks([0,15,30,45,60,75,90])\nplt.yticks([0, 0.5, 1, 1.5, 2, 2.5, 3])\nplt.grid()\nax.title.set_text('The Expected Goals(xG) Chart Final Champions League 2010/2011')\nplt.ylabel(\"Expected Goals (xG)\")\nplt.xlabel(\"Minutes\")\nax.legend()\nplt.show()\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20146550/" ]
74,664,964
<p>I am tryin to take user input in a parameterized java constructor but I am failing. It gives the following error</p> <pre><code>Exception in thread &quot;main&quot; java.util.NoSuchElementException: No line found at java.base/java.util.Scanner.nextLine(Scanner.java:1651) at Main.main(Main.java:24) </code></pre> <p>Here is my code</p> <pre><code>import java.util.Scanner; class Student { String name; String date; Student( String name, String Date) { this.name=name; this.date=date; } } public class Main { public static void main(String args[]) { System.out.println(&quot;Here is the date&quot;); Scanner myObj = new Scanner(System.in); // Create a Scanner object System.out.println(&quot;Enter username&quot;); String name = myObj.nextLine(); System.out.println(&quot;Enter date&quot;); String date = myObj.nextLine(); Student s1= new Student(name,date); } } </code></pre>
[ { "answer_id": 74664991, "author": "Novaordo", "author_id": 20594686, "author_profile": "https://Stackoverflow.com/users/20594686", "pm_score": -1, "selected": false, "text": " public Student( String name, String date) {\n this.name=name;\n this.date=date;\n }\n static class Student {\n /*\n ...\n */\n}\n Date date Student( String name, String Date)" }, { "answer_id": 74665088, "author": "jurez", "author_id": 8338100, "author_profile": "https://Stackoverflow.com/users/8338100", "pm_score": 1, "selected": false, "text": "Scanner System.in Scanner" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12393492/" ]
74,664,972
<p>I have a text file structured like this:</p> <pre><code>[timestamp1] header with space [timestamp2] data1 [timestamp3] data2 [timestamp4] data3 [timestamp5] .. [timestamp6] footer with space [timestamp7] junk [timestamp8] header with space [timestamp9] data4 [timestamp10] data5 [timestamp11] ... [timestamp12] footer with space [timestamp13] junk [timestamp14] header with space [timestamp15] data6 [timestamp16] data7 [timestamp17] data8 [timestamp18] .. [timestamp19] footer with space </code></pre> <p>I need to find each part between <code>header</code> and <code>footer</code> and save it in another file. For example the <em>file1</em> should contain (with or without timestamps; doesn't matter):</p> <pre><code>data1 data2 data3 .. </code></pre> <p>and the next pack should be saved as <em>file2</em> and so on. This seems like a routine process, but I haven't find a solution yet.</p> <p>I have this <em>sed</em> command that finds the first packet.</p> <pre><code>sed -n &quot;/header/,/footer/{p;/footer/q}&quot; file </code></pre> <p>But I don't know how to iterate that over the next matches. Maybe I should delete the first match after copying it to another file and repeat the same command</p>
[ { "answer_id": 74665003, "author": "Itération 122442", "author_id": 6213883, "author_profile": "https://Stackoverflow.com/users/6213883", "pm_score": 2, "selected": false, "text": "BEGIN {\n i = 0\n}\n{\n if ($0 == \"header\") {\n write = 1\n } else if ($0 == \"footer\") {\n write = 0\n i = i + 1\n } else {\n if (write == 1) {\n print $0 > \"file\"i\n }\n }\n}\n" }, { "answer_id": 74666163, "author": "Daweo", "author_id": 10785975, "author_profile": "https://Stackoverflow.com/users/10785975", "pm_score": 3, "selected": true, "text": "AWK file.txt [timestamp1] header with space\n[timestamp2] data1 \n[timestamp3] data2\n[timestamp4] data3\n[timestamp5] ..\n[timestamp6] footer with space\n[timestamp7] junk\n[timestamp8] header with space\n[timestamp9] data4\n[timestamp10] data5\n[timestamp11] ...\n[timestamp12] footer with space\n[timestamp13] junk\n[timestamp14] header with space\n[timestamp15] data6\n[timestamp16] data7\n[timestamp17] data8\n[timestamp18] ..\n[timestamp19] footer with space\n awk '/header/{c+=1;p=1;next}/footer/{close(\"file\" c);p=0}p{print $0 > (\"file\" c)}' file.txt\n file1 [timestamp1] header with space\n[timestamp2] data1 \n[timestamp3] data2\n[timestamp4] data3\n[timestamp5] ..\n file2 [timestamp8] header with space\n[timestamp9] data4\n[timestamp10] data5\n[timestamp11] ...\n file3 [timestamp15] data6\n[timestamp16] data7\n[timestamp17] data8\n[timestamp18] ..\n header c p next footer file p p print $0 file /header/ /footer/" }, { "answer_id": 74669036, "author": "Ed Morton", "author_id": 1745001, "author_profile": "https://Stackoverflow.com/users/1745001", "pm_score": 2, "selected": false, "text": "$ awk '/footer/{f=0} f{print > out} /header/{close(out); out=\"file\" (++c); f=1}' file\n $ head file?*\n==> file1 <==\n[timestamp2] data1\n[timestamp3] data2\n[timestamp4] data3\n[timestamp5] ..\n\n==> file2 <==\n[timestamp9] data4\n[timestamp10] data5\n[timestamp11] ...\n\n==> file3 <==\n[timestamp15] data6\n[timestamp16] data7\n[timestamp17] data8\n[timestamp18] ..\n" }, { "answer_id": 74671821, "author": "potong", "author_id": 967492, "author_profile": "https://Stackoverflow.com/users/967492", "pm_score": 1, "selected": false, "text": "csplit -qf file -b '%d' --supp file '/header/' '{*}' && sed -i '/footer/,$d' file? && rm file0\n file filen header footer file0 sed -En '/header/{x;s/.*/echo $((0&+1))/e;x};/header/,/footer/!b;//b;G;s/(.*)\\n/echo \"\\1\" >>file/e' file\n" }, { "answer_id": 74672116, "author": "dawg", "author_id": 298607, "author_profile": "https://Stackoverflow.com/users/298607", "pm_score": 1, "selected": false, "text": "ruby -e 'cnt=1\n$<.read.scan(/^.*\\bheader\\b.*\\s+([\\s\\S]*?)(?=^.*\\bfooter\\b)/){\n |b| File.write(\"File_#{cnt}.txt\", b[0])\n cnt+=1\n}' file \n $ head File_*\n==> File_1.txt <==\n[timestamp2] data1 \n[timestamp3] data2\n[timestamp4] data3\n[timestamp5] ..\n\n==> File_2.txt <==\n[timestamp9] data4\n[timestamp10] data5\n[timestamp11] ...\n\n==> File_3.txt <==\n[timestamp15] data6\n[timestamp16] data7\n[timestamp17] data8\n[timestamp18] ..\n ruby -e 'cnt=1\n$<.read.scan(/^.*\\bheader\\b.*\\s+([\\s\\S]*?)(?=^.*\\bfooter\\b)/){ |b| \n File.write(\"File_#{cnt}.txt\", b[0].gsub(/^\\[[^\\]]+\\]\\s+/,\"\"))\n cnt+=1\n}' file \n\n$ head File_*\n==> File_1.txt <==\ndata1 \ndata2\ndata3\n..\n\n==> File_2.txt <==\ndata4\ndata5\n...\n\n==> File_3.txt <==\ndata6\ndata7\ndata8\n..\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9439683/" ]
74,664,982
<p>I am trying to create a discord bot, but I am caught in an unending loop of problems. In every video I've watched, it is recommended that you write the cog loading function as thus:</p> <pre><code>async def load_auto(): for filename in os.listdir('./cogs'): if filename.endswith('.py'): await bot.load_extension(f'cogs.{filename[:-3]}') </code></pre> <p>but every time I use this form of cog loading it gives me this error:</p> <pre><code>C:\Users\galan\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py:618: RuntimeWarning: coroutine 'setup' was never awaited setup(self) RuntimeWarning: Enable tracemalloc to get the object allocation traceback Traceback (most recent call last): File &quot;c:/Users/galan/Desktop/new sambot/main.py&quot;, line 118, in &lt;module&gt; asyncio.get_event_loop().run_until_complete(main()) File &quot;C:\Users\galan\AppData\Local\Programs\Python\Python38-32\lib\asyncio\base_events.py&quot;, line 616, in run_until_completereturn future.result() File &quot;c:/Users/galan/Desktop/new sambot/main.py&quot;, line 115, in main await load_auto() File &quot;c:/Users/galan/Desktop/new sambot/main.py&quot;, line 16, in load_auto await bot.load_extension(f'cogs.{filename[:-3]}') TypeError: object NoneType can't be used in 'await' expression </code></pre> <p>I've tried not <em>await</em>ing the bot.load_extension which resulted in it giving a</p> <pre><code>C:\Users\galan\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py:618: RuntimeWarning: coroutine 'setup' was never awaited setup(self) </code></pre> <p>while this may look better, it still does not load the cogs. and it doesn't follow others' code where it seemed like it was working.</p> <p>Here is a part of my main.py file:</p> <pre><code>from discord.ext import commands import discord import os import asyncio intents = discord.Intents.all() intents.members= True sambot_var = ('sambot', 'sambot!', 'sambot?') bot = commands.Bot(command_prefix='$', intents=intents) async def load_auto(): for filename in os.listdir('./cogs'): if filename.endswith('.py'): bot.load_extension(f'cogs.{filename[:-3]}') async def main(): await load_auto() await bot.start('token') asyncio.get_event_loop().run_until_complete(main()) asyncio.run(main()) </code></pre> <p>and one of my cogs:</p> <pre><code>from discord.ext import commands import sys import discord import random sys.path.append(&quot;..&quot;) import datetime import pytz import re import asyncio class Personality(commands.Cog): def init(self, client): self.client = client ... async def setup(bot): await bot.add_cog(Personality(bot)) </code></pre> <p>My questions are:</p> <ol> <li>Does await bot.load_extension(cogs) actually not need to be awaited?</li> <li>Where did I go wrong?</li> <li>What is the solution?</li> </ol> <p>EDIT: The problem was that I had the old discord package ffs. My code worked fine, it just didn't work fine on my device. The problem of <code>await bot.load_extension(cog)</code> was caused by my outdated package.</p> <p>It's always the most simplest answer. Either way, thank you for answering my questions.</p>
[ { "answer_id": 74665003, "author": "Itération 122442", "author_id": 6213883, "author_profile": "https://Stackoverflow.com/users/6213883", "pm_score": 2, "selected": false, "text": "BEGIN {\n i = 0\n}\n{\n if ($0 == \"header\") {\n write = 1\n } else if ($0 == \"footer\") {\n write = 0\n i = i + 1\n } else {\n if (write == 1) {\n print $0 > \"file\"i\n }\n }\n}\n" }, { "answer_id": 74666163, "author": "Daweo", "author_id": 10785975, "author_profile": "https://Stackoverflow.com/users/10785975", "pm_score": 3, "selected": true, "text": "AWK file.txt [timestamp1] header with space\n[timestamp2] data1 \n[timestamp3] data2\n[timestamp4] data3\n[timestamp5] ..\n[timestamp6] footer with space\n[timestamp7] junk\n[timestamp8] header with space\n[timestamp9] data4\n[timestamp10] data5\n[timestamp11] ...\n[timestamp12] footer with space\n[timestamp13] junk\n[timestamp14] header with space\n[timestamp15] data6\n[timestamp16] data7\n[timestamp17] data8\n[timestamp18] ..\n[timestamp19] footer with space\n awk '/header/{c+=1;p=1;next}/footer/{close(\"file\" c);p=0}p{print $0 > (\"file\" c)}' file.txt\n file1 [timestamp1] header with space\n[timestamp2] data1 \n[timestamp3] data2\n[timestamp4] data3\n[timestamp5] ..\n file2 [timestamp8] header with space\n[timestamp9] data4\n[timestamp10] data5\n[timestamp11] ...\n file3 [timestamp15] data6\n[timestamp16] data7\n[timestamp17] data8\n[timestamp18] ..\n header c p next footer file p p print $0 file /header/ /footer/" }, { "answer_id": 74669036, "author": "Ed Morton", "author_id": 1745001, "author_profile": "https://Stackoverflow.com/users/1745001", "pm_score": 2, "selected": false, "text": "$ awk '/footer/{f=0} f{print > out} /header/{close(out); out=\"file\" (++c); f=1}' file\n $ head file?*\n==> file1 <==\n[timestamp2] data1\n[timestamp3] data2\n[timestamp4] data3\n[timestamp5] ..\n\n==> file2 <==\n[timestamp9] data4\n[timestamp10] data5\n[timestamp11] ...\n\n==> file3 <==\n[timestamp15] data6\n[timestamp16] data7\n[timestamp17] data8\n[timestamp18] ..\n" }, { "answer_id": 74671821, "author": "potong", "author_id": 967492, "author_profile": "https://Stackoverflow.com/users/967492", "pm_score": 1, "selected": false, "text": "csplit -qf file -b '%d' --supp file '/header/' '{*}' && sed -i '/footer/,$d' file? && rm file0\n file filen header footer file0 sed -En '/header/{x;s/.*/echo $((0&+1))/e;x};/header/,/footer/!b;//b;G;s/(.*)\\n/echo \"\\1\" >>file/e' file\n" }, { "answer_id": 74672116, "author": "dawg", "author_id": 298607, "author_profile": "https://Stackoverflow.com/users/298607", "pm_score": 1, "selected": false, "text": "ruby -e 'cnt=1\n$<.read.scan(/^.*\\bheader\\b.*\\s+([\\s\\S]*?)(?=^.*\\bfooter\\b)/){\n |b| File.write(\"File_#{cnt}.txt\", b[0])\n cnt+=1\n}' file \n $ head File_*\n==> File_1.txt <==\n[timestamp2] data1 \n[timestamp3] data2\n[timestamp4] data3\n[timestamp5] ..\n\n==> File_2.txt <==\n[timestamp9] data4\n[timestamp10] data5\n[timestamp11] ...\n\n==> File_3.txt <==\n[timestamp15] data6\n[timestamp16] data7\n[timestamp17] data8\n[timestamp18] ..\n ruby -e 'cnt=1\n$<.read.scan(/^.*\\bheader\\b.*\\s+([\\s\\S]*?)(?=^.*\\bfooter\\b)/){ |b| \n File.write(\"File_#{cnt}.txt\", b[0].gsub(/^\\[[^\\]]+\\]\\s+/,\"\"))\n cnt+=1\n}' file \n\n$ head File_*\n==> File_1.txt <==\ndata1 \ndata2\ndata3\n..\n\n==> File_2.txt <==\ndata4\ndata5\n...\n\n==> File_3.txt <==\ndata6\ndata7\ndata8\n..\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74664982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20672587/" ]
74,665,004
<p>I want to create a two column card layout and I'm using reusable widget I created. But I'm having renderflow issues. Below are the errors. i already tried to make it smaller, it worked but not as what i want it to look like.</p> <p>════════ Exception caught by rendering library ═════════════════════════════════ A RenderFlex overflowed by 99853 pixels on the right. The relevant error-causing widget was Row lib\…\student\subjects.dart:158 ════════════════════════════════════════════════════════════════════════════════</p> <p><a href="https://i.stack.imgur.com/Tomrd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Tomrd.png" alt="enter image description here" /></a></p> <p>subjects.dart</p> <pre><code>SingleChildScrollView( child: Container( padding: const EdgeInsets.symmetric(horizontal: 32), child: Column( children : [ // A Row for the top Row(children: [ SubjectCard(link: '', source: '', subjectNo: 'SUBJECT 1'), const SizedBox(width: 5,), SubjectCard(link: '', source: '', subjectNo: 'SUBJECT 1') ] ), const SizedBox(height: 5,), Row(children: [ SubjectCard(link: '', source: '', subjectNo: 'SUBJECT 2'), const SizedBox(width: 5,), SubjectCard(link: '', source: '', subjectNo: 'SUBJECT 2') ] ), ], ), ), ) </code></pre> <p>card</p> <pre><code>return SizedBox( height: 140, width: width * 0.4, child: Card( clipBehavior: Clip.antiAlias, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12) ), child: Stack( alignment: Alignment.topLeft, children: [ // Ink.image( // // image: NetworkImage(link), // image: AssetImage(widget.link), // height: 200, // fit: BoxFit.cover, // //colorFilter: ColorFilters.greyscale, // child: InkWell( // onTap: () =&gt; Navigator.of(context).pushNamed( // widget.source, // arguments: 'Text from homepage', // ), // ), // ), Padding( padding:const EdgeInsets.only(top: 0), child: Container( color: Colors.white60, height: 50, width: double.infinity, ), ), Padding( padding: const EdgeInsets.only(left: 10, top: 5, bottom: 0), child: Text(subjectName, style: GoogleFonts.smoochSans( textStyle: const TextStyle(color: Colors.black,fontWeight: FontWeight.bold, fontSize: 30), ) ), ), Padding( padding: const EdgeInsets.only(left: 10, top: 28, bottom: 0), child: Text(profesor, style: GoogleFonts.smoochSans( textStyle: const TextStyle(color: Colors.black,fontWeight: FontWeight.bold, fontSize: 18), ) ), ), Padding( padding: const EdgeInsets.only(left: 10, top: 43, bottom: 0), child: Text('$start -', style: GoogleFonts.smoochSans( textStyle: const TextStyle(color: Colors.black,fontWeight: FontWeight.bold, fontSize: 18), ) ), ), Padding( padding: const EdgeInsets.only(left: 10, top: 56, bottom: 0), child: Text('$end', style: GoogleFonts.smoochSans( textStyle: const TextStyle(color: Colors.black,fontWeight: FontWeight.bold, fontSize: 18), ) ), ), ], ), ), ); </code></pre> <p>The edge of the RenderFlex that is overflowing has been marked in the rendering with a yellow and black striped pattern. This is usually caused by the contents being too big for the RenderFlex.</p> <p>Consider applying a flex factor (e.g. using an Expanded widget) to force the children of the RenderFlex to fit within the available space instead of being sized to their natural size. This is considered an error condition because it indicates that there is content that cannot be seen. If the content is legitimately bigger than the available space, consider clipping it with a ClipRect widget before putting it in the flex, or using a scrollable container rather than a Flex, like a ListView.</p> <p>The specific RenderFlex in question is: RenderFlex#8390f OVERFLOWING ════════════════════════════════════════════════════════════════════════════════</p> <hr /> <p>Edit</p> <p>here is my new code. thanks to your suggestions</p> <pre><code>Expanded( flex: 1, child: SingleChildScrollView( child: SizedBox( // height: height, width: MediaQuery.of(context).size.width, child: SizedBox( child: Column( children : [ // A Row for the top Row( children: const [ SubjectCard(link: &quot;assets/images/subject.jpg&quot;, source: '', subjectNo: 'SUBJECT 1'), SizedBox(width: 10,), SubjectCard(link: &quot;assets/images/subject.jpg&quot;, source: '', subjectNo: 'SUBJECT 1') ] ), const SizedBox(height: 10,), Row( children: const [ SubjectCard(link: &quot;assets/images/subject.jpg&quot;, source: '', subjectNo: 'SUBJECT 1'), SizedBox(width: 10,), SubjectCard(link: &quot;assets/images/subject.jpg&quot;, source: '', subjectNo: 'SUBJECT 1') ] ), const SizedBox(height: 10,), Row(children: const [ SubjectCard(link: &quot;assets/images/Student.JPG&quot;, source: '', subjectNo: 'SUBJECT 2'), SizedBox(width: 10,), SubjectCard(link: &quot;assets/images/subject.jpg&quot;, source: '', subjectNo: 'SUBJECT 1') ] ), const SizedBox(height: 10,), Row(children: const [ SubjectCard(link: &quot;assets/images/subject.jpg&quot;, source: '', subjectNo: 'SUBJECT 1'), SizedBox(width: 10,), SubjectCard(link: &quot;assets/images/Student.JPG&quot;, source: '', subjectNo: 'SUBJECT 2') ] ),const SizedBox(height: 10,), Row(children: const [ SubjectCard(link: &quot;assets/images/subject.jpg&quot;, source: '', subjectNo: 'SUBJECT 1'), SizedBox(width: 10,), SubjectCard(link: &quot;assets/images/Student.JPG&quot;, source: '', subjectNo: 'SUBJECT 2') ] ),const SizedBox(height: 10,), Row(children: const [ SubjectCard(link: &quot;assets/images/subject.jpg&quot;, source: '', subjectNo: 'SUBJECT 1'), SizedBox(width: 10,), SubjectCard(link: &quot;assets/images/Student.JPG&quot;, source: '', subjectNo: 'SUBJECT 2') ] ), ], ), ), ), ), ) </code></pre>
[ { "answer_id": 74665003, "author": "Itération 122442", "author_id": 6213883, "author_profile": "https://Stackoverflow.com/users/6213883", "pm_score": 2, "selected": false, "text": "BEGIN {\n i = 0\n}\n{\n if ($0 == \"header\") {\n write = 1\n } else if ($0 == \"footer\") {\n write = 0\n i = i + 1\n } else {\n if (write == 1) {\n print $0 > \"file\"i\n }\n }\n}\n" }, { "answer_id": 74666163, "author": "Daweo", "author_id": 10785975, "author_profile": "https://Stackoverflow.com/users/10785975", "pm_score": 3, "selected": true, "text": "AWK file.txt [timestamp1] header with space\n[timestamp2] data1 \n[timestamp3] data2\n[timestamp4] data3\n[timestamp5] ..\n[timestamp6] footer with space\n[timestamp7] junk\n[timestamp8] header with space\n[timestamp9] data4\n[timestamp10] data5\n[timestamp11] ...\n[timestamp12] footer with space\n[timestamp13] junk\n[timestamp14] header with space\n[timestamp15] data6\n[timestamp16] data7\n[timestamp17] data8\n[timestamp18] ..\n[timestamp19] footer with space\n awk '/header/{c+=1;p=1;next}/footer/{close(\"file\" c);p=0}p{print $0 > (\"file\" c)}' file.txt\n file1 [timestamp1] header with space\n[timestamp2] data1 \n[timestamp3] data2\n[timestamp4] data3\n[timestamp5] ..\n file2 [timestamp8] header with space\n[timestamp9] data4\n[timestamp10] data5\n[timestamp11] ...\n file3 [timestamp15] data6\n[timestamp16] data7\n[timestamp17] data8\n[timestamp18] ..\n header c p next footer file p p print $0 file /header/ /footer/" }, { "answer_id": 74669036, "author": "Ed Morton", "author_id": 1745001, "author_profile": "https://Stackoverflow.com/users/1745001", "pm_score": 2, "selected": false, "text": "$ awk '/footer/{f=0} f{print > out} /header/{close(out); out=\"file\" (++c); f=1}' file\n $ head file?*\n==> file1 <==\n[timestamp2] data1\n[timestamp3] data2\n[timestamp4] data3\n[timestamp5] ..\n\n==> file2 <==\n[timestamp9] data4\n[timestamp10] data5\n[timestamp11] ...\n\n==> file3 <==\n[timestamp15] data6\n[timestamp16] data7\n[timestamp17] data8\n[timestamp18] ..\n" }, { "answer_id": 74671821, "author": "potong", "author_id": 967492, "author_profile": "https://Stackoverflow.com/users/967492", "pm_score": 1, "selected": false, "text": "csplit -qf file -b '%d' --supp file '/header/' '{*}' && sed -i '/footer/,$d' file? && rm file0\n file filen header footer file0 sed -En '/header/{x;s/.*/echo $((0&+1))/e;x};/header/,/footer/!b;//b;G;s/(.*)\\n/echo \"\\1\" >>file/e' file\n" }, { "answer_id": 74672116, "author": "dawg", "author_id": 298607, "author_profile": "https://Stackoverflow.com/users/298607", "pm_score": 1, "selected": false, "text": "ruby -e 'cnt=1\n$<.read.scan(/^.*\\bheader\\b.*\\s+([\\s\\S]*?)(?=^.*\\bfooter\\b)/){\n |b| File.write(\"File_#{cnt}.txt\", b[0])\n cnt+=1\n}' file \n $ head File_*\n==> File_1.txt <==\n[timestamp2] data1 \n[timestamp3] data2\n[timestamp4] data3\n[timestamp5] ..\n\n==> File_2.txt <==\n[timestamp9] data4\n[timestamp10] data5\n[timestamp11] ...\n\n==> File_3.txt <==\n[timestamp15] data6\n[timestamp16] data7\n[timestamp17] data8\n[timestamp18] ..\n ruby -e 'cnt=1\n$<.read.scan(/^.*\\bheader\\b.*\\s+([\\s\\S]*?)(?=^.*\\bfooter\\b)/){ |b| \n File.write(\"File_#{cnt}.txt\", b[0].gsub(/^\\[[^\\]]+\\]\\s+/,\"\"))\n cnt+=1\n}' file \n\n$ head File_*\n==> File_1.txt <==\ndata1 \ndata2\ndata3\n..\n\n==> File_2.txt <==\ndata4\ndata5\n...\n\n==> File_3.txt <==\ndata6\ndata7\ndata8\n..\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20501864/" ]
74,665,030
<p><a href="https://i.stack.imgur.com/7iR85.jpg" rel="nofollow noreferrer">enter image description here</a> - Relationships</p> <p>Find employees who took some kind of management class (i.e., a class whose name ends with management). List employees’ last and first name, class name, and the class date. Sort the query output by last name in ascending.</p> <p>I did the following, But the query is not working. Cannot find the ClassName that ends with management.</p> <pre><code>SELECT E.Last, E.First, C.ClassName, C.Date FROM EMPLOYEES AS E, EMPLOYEE_TRAINING AS ET, CLASSES AS C WHERE E.EmployeeID = ET.EmployeeID AND C.ClassID = ET.ClassID AND C.ClassName LIKE &quot;Management*&quot; ORDER BY E.Last ASC; </code></pre>
[ { "answer_id": 74665003, "author": "Itération 122442", "author_id": 6213883, "author_profile": "https://Stackoverflow.com/users/6213883", "pm_score": 2, "selected": false, "text": "BEGIN {\n i = 0\n}\n{\n if ($0 == \"header\") {\n write = 1\n } else if ($0 == \"footer\") {\n write = 0\n i = i + 1\n } else {\n if (write == 1) {\n print $0 > \"file\"i\n }\n }\n}\n" }, { "answer_id": 74666163, "author": "Daweo", "author_id": 10785975, "author_profile": "https://Stackoverflow.com/users/10785975", "pm_score": 3, "selected": true, "text": "AWK file.txt [timestamp1] header with space\n[timestamp2] data1 \n[timestamp3] data2\n[timestamp4] data3\n[timestamp5] ..\n[timestamp6] footer with space\n[timestamp7] junk\n[timestamp8] header with space\n[timestamp9] data4\n[timestamp10] data5\n[timestamp11] ...\n[timestamp12] footer with space\n[timestamp13] junk\n[timestamp14] header with space\n[timestamp15] data6\n[timestamp16] data7\n[timestamp17] data8\n[timestamp18] ..\n[timestamp19] footer with space\n awk '/header/{c+=1;p=1;next}/footer/{close(\"file\" c);p=0}p{print $0 > (\"file\" c)}' file.txt\n file1 [timestamp1] header with space\n[timestamp2] data1 \n[timestamp3] data2\n[timestamp4] data3\n[timestamp5] ..\n file2 [timestamp8] header with space\n[timestamp9] data4\n[timestamp10] data5\n[timestamp11] ...\n file3 [timestamp15] data6\n[timestamp16] data7\n[timestamp17] data8\n[timestamp18] ..\n header c p next footer file p p print $0 file /header/ /footer/" }, { "answer_id": 74669036, "author": "Ed Morton", "author_id": 1745001, "author_profile": "https://Stackoverflow.com/users/1745001", "pm_score": 2, "selected": false, "text": "$ awk '/footer/{f=0} f{print > out} /header/{close(out); out=\"file\" (++c); f=1}' file\n $ head file?*\n==> file1 <==\n[timestamp2] data1\n[timestamp3] data2\n[timestamp4] data3\n[timestamp5] ..\n\n==> file2 <==\n[timestamp9] data4\n[timestamp10] data5\n[timestamp11] ...\n\n==> file3 <==\n[timestamp15] data6\n[timestamp16] data7\n[timestamp17] data8\n[timestamp18] ..\n" }, { "answer_id": 74671821, "author": "potong", "author_id": 967492, "author_profile": "https://Stackoverflow.com/users/967492", "pm_score": 1, "selected": false, "text": "csplit -qf file -b '%d' --supp file '/header/' '{*}' && sed -i '/footer/,$d' file? && rm file0\n file filen header footer file0 sed -En '/header/{x;s/.*/echo $((0&+1))/e;x};/header/,/footer/!b;//b;G;s/(.*)\\n/echo \"\\1\" >>file/e' file\n" }, { "answer_id": 74672116, "author": "dawg", "author_id": 298607, "author_profile": "https://Stackoverflow.com/users/298607", "pm_score": 1, "selected": false, "text": "ruby -e 'cnt=1\n$<.read.scan(/^.*\\bheader\\b.*\\s+([\\s\\S]*?)(?=^.*\\bfooter\\b)/){\n |b| File.write(\"File_#{cnt}.txt\", b[0])\n cnt+=1\n}' file \n $ head File_*\n==> File_1.txt <==\n[timestamp2] data1 \n[timestamp3] data2\n[timestamp4] data3\n[timestamp5] ..\n\n==> File_2.txt <==\n[timestamp9] data4\n[timestamp10] data5\n[timestamp11] ...\n\n==> File_3.txt <==\n[timestamp15] data6\n[timestamp16] data7\n[timestamp17] data8\n[timestamp18] ..\n ruby -e 'cnt=1\n$<.read.scan(/^.*\\bheader\\b.*\\s+([\\s\\S]*?)(?=^.*\\bfooter\\b)/){ |b| \n File.write(\"File_#{cnt}.txt\", b[0].gsub(/^\\[[^\\]]+\\]\\s+/,\"\"))\n cnt+=1\n}' file \n\n$ head File_*\n==> File_1.txt <==\ndata1 \ndata2\ndata3\n..\n\n==> File_2.txt <==\ndata4\ndata5\n...\n\n==> File_3.txt <==\ndata6\ndata7\ndata8\n..\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20113736/" ]
74,665,078
<p>I understand a bit about the useEffect hook but I think there’s still more knowledge to grasp. Some of which are not in the documentation. Please any contribution will help a lot y’all.</p> <p>Some of my questions are:</p> <ol> <li><p>Does useEffect get called on initial render even in production just like in development?</p> </li> <li><p>If it does, how do we control this the best way?</p> </li> <li><p>How can we use a clean up function on this Hook?</p> </li> <li><p>How can we make asynchronous calls in useEffect?</p> </li> </ol> <p>My attempts on useEffect usually makes me feel like a bad developer</p>
[ { "answer_id": 74665003, "author": "Itération 122442", "author_id": 6213883, "author_profile": "https://Stackoverflow.com/users/6213883", "pm_score": 2, "selected": false, "text": "BEGIN {\n i = 0\n}\n{\n if ($0 == \"header\") {\n write = 1\n } else if ($0 == \"footer\") {\n write = 0\n i = i + 1\n } else {\n if (write == 1) {\n print $0 > \"file\"i\n }\n }\n}\n" }, { "answer_id": 74666163, "author": "Daweo", "author_id": 10785975, "author_profile": "https://Stackoverflow.com/users/10785975", "pm_score": 3, "selected": true, "text": "AWK file.txt [timestamp1] header with space\n[timestamp2] data1 \n[timestamp3] data2\n[timestamp4] data3\n[timestamp5] ..\n[timestamp6] footer with space\n[timestamp7] junk\n[timestamp8] header with space\n[timestamp9] data4\n[timestamp10] data5\n[timestamp11] ...\n[timestamp12] footer with space\n[timestamp13] junk\n[timestamp14] header with space\n[timestamp15] data6\n[timestamp16] data7\n[timestamp17] data8\n[timestamp18] ..\n[timestamp19] footer with space\n awk '/header/{c+=1;p=1;next}/footer/{close(\"file\" c);p=0}p{print $0 > (\"file\" c)}' file.txt\n file1 [timestamp1] header with space\n[timestamp2] data1 \n[timestamp3] data2\n[timestamp4] data3\n[timestamp5] ..\n file2 [timestamp8] header with space\n[timestamp9] data4\n[timestamp10] data5\n[timestamp11] ...\n file3 [timestamp15] data6\n[timestamp16] data7\n[timestamp17] data8\n[timestamp18] ..\n header c p next footer file p p print $0 file /header/ /footer/" }, { "answer_id": 74669036, "author": "Ed Morton", "author_id": 1745001, "author_profile": "https://Stackoverflow.com/users/1745001", "pm_score": 2, "selected": false, "text": "$ awk '/footer/{f=0} f{print > out} /header/{close(out); out=\"file\" (++c); f=1}' file\n $ head file?*\n==> file1 <==\n[timestamp2] data1\n[timestamp3] data2\n[timestamp4] data3\n[timestamp5] ..\n\n==> file2 <==\n[timestamp9] data4\n[timestamp10] data5\n[timestamp11] ...\n\n==> file3 <==\n[timestamp15] data6\n[timestamp16] data7\n[timestamp17] data8\n[timestamp18] ..\n" }, { "answer_id": 74671821, "author": "potong", "author_id": 967492, "author_profile": "https://Stackoverflow.com/users/967492", "pm_score": 1, "selected": false, "text": "csplit -qf file -b '%d' --supp file '/header/' '{*}' && sed -i '/footer/,$d' file? && rm file0\n file filen header footer file0 sed -En '/header/{x;s/.*/echo $((0&+1))/e;x};/header/,/footer/!b;//b;G;s/(.*)\\n/echo \"\\1\" >>file/e' file\n" }, { "answer_id": 74672116, "author": "dawg", "author_id": 298607, "author_profile": "https://Stackoverflow.com/users/298607", "pm_score": 1, "selected": false, "text": "ruby -e 'cnt=1\n$<.read.scan(/^.*\\bheader\\b.*\\s+([\\s\\S]*?)(?=^.*\\bfooter\\b)/){\n |b| File.write(\"File_#{cnt}.txt\", b[0])\n cnt+=1\n}' file \n $ head File_*\n==> File_1.txt <==\n[timestamp2] data1 \n[timestamp3] data2\n[timestamp4] data3\n[timestamp5] ..\n\n==> File_2.txt <==\n[timestamp9] data4\n[timestamp10] data5\n[timestamp11] ...\n\n==> File_3.txt <==\n[timestamp15] data6\n[timestamp16] data7\n[timestamp17] data8\n[timestamp18] ..\n ruby -e 'cnt=1\n$<.read.scan(/^.*\\bheader\\b.*\\s+([\\s\\S]*?)(?=^.*\\bfooter\\b)/){ |b| \n File.write(\"File_#{cnt}.txt\", b[0].gsub(/^\\[[^\\]]+\\]\\s+/,\"\"))\n cnt+=1\n}' file \n\n$ head File_*\n==> File_1.txt <==\ndata1 \ndata2\ndata3\n..\n\n==> File_2.txt <==\ndata4\ndata5\n...\n\n==> File_3.txt <==\ndata6\ndata7\ndata8\n..\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16770846/" ]
74,665,089
<p>I have an array and I want to assign values in group of 3s Name, Id, Population, Name, Id, Population, Name, Id, Population etc. Is there a way to do that? This is what I have</p> <pre class="lang-java prettyprint-override"><code>while (scanner.hasNext()) { ` scanner.useDelimiter(&quot;,&quot;);` list.add(scanner.nextLine());}` for(int i=0; i&lt;list.size(); i++){ String n = list.get(i); System.out.println(&quot;Hopefully going thru &quot; + n);} //for me to check String ar =list.toString(); Object [] a = ar.split(&quot;,&quot;);// splitting the array for each string for(int h=0;h&lt;a.length;h+=3) { // for [0] += 3 is Name for(int j=1;j&lt;a.length; j+=3) { // for [1] += 3 is Id for(int k=2; k&lt;a.length;k+=3) { //for[2]+= is Population String name = a[h].toString(); String id = a[j].toString(); String population = a[k].toString(); System.out.println(&quot;name is &quot;+ name);// this is just to check correct values System.out.println(&quot;id is &quot;+ id);// this is just to check correct values System.out.println(&quot;population is &quot; +population);// this is just to check correct values CityRow cityRow = new CityRow(name,id,population); //?? I want every set of [0][1][2] to create a new object` </code></pre>
[ { "answer_id": 74665003, "author": "Itération 122442", "author_id": 6213883, "author_profile": "https://Stackoverflow.com/users/6213883", "pm_score": 2, "selected": false, "text": "BEGIN {\n i = 0\n}\n{\n if ($0 == \"header\") {\n write = 1\n } else if ($0 == \"footer\") {\n write = 0\n i = i + 1\n } else {\n if (write == 1) {\n print $0 > \"file\"i\n }\n }\n}\n" }, { "answer_id": 74666163, "author": "Daweo", "author_id": 10785975, "author_profile": "https://Stackoverflow.com/users/10785975", "pm_score": 3, "selected": true, "text": "AWK file.txt [timestamp1] header with space\n[timestamp2] data1 \n[timestamp3] data2\n[timestamp4] data3\n[timestamp5] ..\n[timestamp6] footer with space\n[timestamp7] junk\n[timestamp8] header with space\n[timestamp9] data4\n[timestamp10] data5\n[timestamp11] ...\n[timestamp12] footer with space\n[timestamp13] junk\n[timestamp14] header with space\n[timestamp15] data6\n[timestamp16] data7\n[timestamp17] data8\n[timestamp18] ..\n[timestamp19] footer with space\n awk '/header/{c+=1;p=1;next}/footer/{close(\"file\" c);p=0}p{print $0 > (\"file\" c)}' file.txt\n file1 [timestamp1] header with space\n[timestamp2] data1 \n[timestamp3] data2\n[timestamp4] data3\n[timestamp5] ..\n file2 [timestamp8] header with space\n[timestamp9] data4\n[timestamp10] data5\n[timestamp11] ...\n file3 [timestamp15] data6\n[timestamp16] data7\n[timestamp17] data8\n[timestamp18] ..\n header c p next footer file p p print $0 file /header/ /footer/" }, { "answer_id": 74669036, "author": "Ed Morton", "author_id": 1745001, "author_profile": "https://Stackoverflow.com/users/1745001", "pm_score": 2, "selected": false, "text": "$ awk '/footer/{f=0} f{print > out} /header/{close(out); out=\"file\" (++c); f=1}' file\n $ head file?*\n==> file1 <==\n[timestamp2] data1\n[timestamp3] data2\n[timestamp4] data3\n[timestamp5] ..\n\n==> file2 <==\n[timestamp9] data4\n[timestamp10] data5\n[timestamp11] ...\n\n==> file3 <==\n[timestamp15] data6\n[timestamp16] data7\n[timestamp17] data8\n[timestamp18] ..\n" }, { "answer_id": 74671821, "author": "potong", "author_id": 967492, "author_profile": "https://Stackoverflow.com/users/967492", "pm_score": 1, "selected": false, "text": "csplit -qf file -b '%d' --supp file '/header/' '{*}' && sed -i '/footer/,$d' file? && rm file0\n file filen header footer file0 sed -En '/header/{x;s/.*/echo $((0&+1))/e;x};/header/,/footer/!b;//b;G;s/(.*)\\n/echo \"\\1\" >>file/e' file\n" }, { "answer_id": 74672116, "author": "dawg", "author_id": 298607, "author_profile": "https://Stackoverflow.com/users/298607", "pm_score": 1, "selected": false, "text": "ruby -e 'cnt=1\n$<.read.scan(/^.*\\bheader\\b.*\\s+([\\s\\S]*?)(?=^.*\\bfooter\\b)/){\n |b| File.write(\"File_#{cnt}.txt\", b[0])\n cnt+=1\n}' file \n $ head File_*\n==> File_1.txt <==\n[timestamp2] data1 \n[timestamp3] data2\n[timestamp4] data3\n[timestamp5] ..\n\n==> File_2.txt <==\n[timestamp9] data4\n[timestamp10] data5\n[timestamp11] ...\n\n==> File_3.txt <==\n[timestamp15] data6\n[timestamp16] data7\n[timestamp17] data8\n[timestamp18] ..\n ruby -e 'cnt=1\n$<.read.scan(/^.*\\bheader\\b.*\\s+([\\s\\S]*?)(?=^.*\\bfooter\\b)/){ |b| \n File.write(\"File_#{cnt}.txt\", b[0].gsub(/^\\[[^\\]]+\\]\\s+/,\"\"))\n cnt+=1\n}' file \n\n$ head File_*\n==> File_1.txt <==\ndata1 \ndata2\ndata3\n..\n\n==> File_2.txt <==\ndata4\ndata5\n...\n\n==> File_3.txt <==\ndata6\ndata7\ndata8\n..\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20627734/" ]
74,665,120
<p>Implement a function that is given 2 positive integers representing 2 angles of a triangle. If the triangle is right, isosceles, or both, the function should return 1, 2 or 3, respectively. Otherwise it should return 0.</p> <p>im actually just started learning C language and cant move on cause i cant find an answer to this problem. would like a reference to see where are my mistakes.</p> <p>dont need to print it, only the function. without using loops only if statements.</p> <pre><code>int TriangleType (unsigned num1, unsigned num2){ int result; if(num1 == 90 || num2 == 90 || num1 + num2 == 90){ result = 1; } else if(num1 == num2 || 180 - (num1+num2) == num1 || 180 - (num1+num2) == num2) { result = 2; } else if((num1 == 90 || num2 == 90 || num1 + num2 == 90) &amp;&amp; (num1 == num2 || 180 - (num1+num2) == num1 || 180 - (num1+num2) == num2)){ result = 3; } else if (num1 + num2 &gt;= 180){ result = -1; } else { result = 0; } return result; } </code></pre> <p>thats the start so u can see what is the direction... maybe got mistakes even here at the start =)</p>
[ { "answer_id": 74665811, "author": "Juraj", "author_id": 14091997, "author_profile": "https://Stackoverflow.com/users/14091997", "pm_score": 0, "selected": false, "text": "int TriangleType(unsigned num1, unsigned num2)\n{\n int result;\n if (num1 == 90 || num2 == 90 || num1 + num2 == 90) {\n if (num1 == num2 || 180 - (num1 + num2) == num1 || 180 - (num1 + num2) == num2)\n result = 3;\n else\n result = 1;\n } else if (num1 == num2 || 180 - (num1 + num2) == num1 || 180 - (num1 + num2) == num2) {\n result = 2;\n } else if (num1 + num2 >= 180) {\n result = -1;\n } else {\n result = 0;\n }\n return result;\n}\n if (num1 == 90 || num2 == 90 || num1 + num2 == 90) {\n if (num1 == num2 || 180 - (num1 + num2) == num1 || 180 - (num1 + num2) == num2)\n result = 3;\n else\n result = 1;\n }\n int is_isosceles(unsigned num1, unsigned num2)\n{\n if (num1 == num2 || 180 - (num1 + num2) == num1 || 180 - (num1 + num2) == num2)\n return 1;\n else\n return 0;\n}\n\nint TriangleType(unsigned num1, unsigned num2)\n{\n int result;\n if (num1 == 90 || num2 == 90 || num1 + num2 == 90) {\n if (is_isosceles(num1, num2))\n result = 3;\n else\n result = 1;\n } else if (is_isosceles(num1, num2)) {\n result = 2;\n } else if (num1 + num2 >= 180) {\n result = -1;\n } else {\n result = 0;\n }\n return result;\n}\n #include <stdbool.h>\n" }, { "answer_id": 74665829, "author": "Tony", "author_id": 4124887, "author_profile": "https://Stackoverflow.com/users/4124887", "pm_score": 0, "selected": false, "text": "int TriangleType (unsigned num1, unsigned num2){\n\n int right = 0;\n int isosceles = 0;\n int result = 0;\n\n if( /* conditions for right angle */ ){\n right = 1;\n } \n\n if( /* conditions for isosceles */ ) {\n isosceles = 1;\n } \n\n if ( right == 1 && isosceles == 1 ) {\n result = 3;\n } else if ( right == 1) {\n result = 1;\n } else if ( isosceles == 1 ) { \n /* ... */\n } /*...*/\n return result;\n}\n" }, { "answer_id": 74665835, "author": "HungryFoolish", "author_id": 1553151, "author_profile": "https://Stackoverflow.com/users/1553151", "pm_score": 1, "selected": false, "text": "int TriangleType (unsigned num1, unsigned num2)\n{\n //Calculate the third angle and keep in num3\n unsigned num3 = 180 - (num1 + num2); \n \n //We declare a variable \"result\" and initialize it with 0\n //This way if none of our if conditions match, we would simply return 0 by \"return result;\". \n unsigned int result = 0; \n\n if (num1 == 90 || num2 == 90 || num3 == 90) //if any of our angles are 90-degree\n result += 1; //Add 1 to result (which is 0 at this point)\n if ((num1==num2) || (num2 == num3) || (num1 == num3)) //if any two angles are same i.e. isosceles\n result += 2; //Add 2 to result (which is 1 if previous if condition was true otherwise its 0) )\n \n /*\n At this point :\n 1) If it was neither right-angled or isoscles \n both the if statements will be false and result will remain 0\n\n 2) If it was right-angled we did \"result += 1\" i.e. \"result = result + 1\"\n So, In case first \"if\" condition is true, result is 1 otherwise its 0\n\n 3) If it was isoscles we did \"result += 2\" i.e. \"result = result + 2\"\n So, second \"if\" condition is true, result becomes result + 2 ie \n if result was 0 it becomes 2 or if it was 1 it becomes 3.\n */\n\n\n return result;\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19357198/" ]
74,665,124
<pre class="lang-py prettyprint-override"><code>import re, datetime def add_months(datestr, months): ref_year, ref_month = &quot;&quot;, &quot;&quot; ref_year_is_leap_year = False aux_date = str(datetime.datetime.strptime(datestr, &quot;%Y-%m-%d&quot;)) print(repr(aux_date)) for i_month in range(int(months)): # I add a unit since the months are &quot;numerical quantities&quot;, # that is, they are expressed in natural numbers, so I need it # to start from 1 and not from 0 like the iter variable in python i_month = i_month + 1 m1 = re.search( r&quot;(?P&lt;year&gt;\d*)-(?P&lt;month&gt;\d{2})-(?P&lt;startDay&gt;\d{2})&quot;, aux_date, re.IGNORECASE, ) if m1: ref_year, ref_month = ( str(m1.groups()[0]).strip(), str(m1.groups()[1]).strip(), ) number_of_days_in_each_month = { &quot;01&quot;: &quot;31&quot;, &quot;02&quot;: &quot;28&quot;, &quot;03&quot;: &quot;31&quot;, &quot;04&quot;: &quot;30&quot;, &quot;05&quot;: &quot;31&quot;, &quot;06&quot;: &quot;30&quot;, &quot;07&quot;: &quot;31&quot;, &quot;08&quot;: &quot;31&quot;, &quot;09&quot;: &quot;30&quot;, &quot;10&quot;: &quot;31&quot;, &quot;11&quot;: &quot;30&quot;, &quot;12&quot;: &quot;31&quot;, } n_days_in_this_i_month = number_of_days_in_each_month[ref_month] print(n_days_in_this_i_month) # nro days to increment in each i month iteration if ( int(ref_year) % 4 == 0 and int(ref_year) % 100 == 0 and int(ref_year) % 400 != 0 ): ref_year_is_leap_year = True # divisible entre 4 y 10 y no entre 400, para determinar que sea un año bisciesto if ref_year_is_leap_year == True and ref_month == &quot;02&quot;: n_days_in_this_i_month = str(int(n_days_in_this_i_month) + 1) # 28 --&gt; 29 aux_date = ( datetime.datetime.strptime(datestr, &quot;%Y-%m-%d&quot;) + datetime.timedelta(days=int(n_days_in_this_i_month)) ).strftime(&quot;%Y-%m-%d&quot;) print(repr(aux_date)) return aux_date print(repr(add_months(&quot;2022-12-30&quot;, &quot;3&quot;))) </code></pre> <p>Why does the <code>aux_date</code> variable, instead of <strong>progressively increasing</strong> the number of days of the elapsed months, only limit itself to adding 31 days of that month of January, and then add them back to the original amount, staying stuck there instead of advancing each iteration of this <code>for</code> loop?</p> <p>The objective of this <code>for</code> loop is to achieve an <strong>incremental iteration loop</strong> where the days are added and not one that always returns to the original amount to add the same content over and over again.</p> <hr /> <p><strong>Updated function Algorithm</strong></p> <p>In this edit I have modified some details and redundancies, and also fixed some bugs that are present in the original code.</p> <pre><code>def add_months(datestr, months): ref_year, ref_month = &quot;&quot;, &quot;&quot; ref_year_is_leap_year = False #condicional booleano, cuya logica binaria intenta establecer si es o no bisiesto el año tomado como referencia aux_date = datetime.datetime.strptime(datestr, &quot;%Y-%m-%d&quot;) for i_month in range(int(months)): i_month = i_month + 1 # I add a unit since the months are &quot;numerical quantities&quot;, that is, they are expressed in natural numbers, so I need it to start from 1 and not from 0 like the iter variable in python m1 = re.search( r&quot;(?P&lt;year&gt;\d*)-(?P&lt;month&gt;\d{2})-(?P&lt;startDay&gt;\d{2})&quot;, str(aux_date), re.IGNORECASE, ) if m1: ref_year, ref_month = ( str(m1.groups()[0]).strip(), str( int(m1.groups()[1]) + 1).strip(), ) if( len(ref_month) == 1 ): ref_month = &quot;0&quot; + ref_month if( int(ref_month) &gt; 12 ): ref_month = &quot;01&quot; print(ref_month) number_of_days_in_each_month = { &quot;01&quot;: &quot;31&quot;, &quot;02&quot;: &quot;28&quot;, &quot;03&quot;: &quot;31&quot;, &quot;04&quot;: &quot;30&quot;, &quot;05&quot;: &quot;31&quot;, &quot;06&quot;: &quot;30&quot;, &quot;07&quot;: &quot;31&quot;, &quot;08&quot;: &quot;31&quot;, &quot;09&quot;: &quot;30&quot;, &quot;10&quot;: &quot;31&quot;, &quot;11&quot;: &quot;30&quot;, &quot;12&quot;: &quot;31&quot;, } n_days_in_this_i_month = number_of_days_in_each_month[ref_month] if ( int(ref_year) % 4 == 0 and int(ref_year) % 100 != 0 ) or ( int(ref_year) % 400 == 0 ): ref_year_is_leap_year = True ref_year_is_leap_year = True # divisible entre 4 y 10 y no entre 400, para determinar que sea un año bisciesto if ref_year_is_leap_year == True and ref_month == &quot;02&quot;: n_days_in_this_i_month = str(int(n_days_in_this_i_month) + 1) # 28 --&gt; 29 print(n_days_in_this_i_month) # nro days to increment in each i month iteration aux_date = aux_date + datetime.timedelta(days=int(n_days_in_this_i_month)) return datetime.datetime.strftime(aux_date, &quot;%Y-%m-%d&quot;) </code></pre>
[ { "answer_id": 74665811, "author": "Juraj", "author_id": 14091997, "author_profile": "https://Stackoverflow.com/users/14091997", "pm_score": 0, "selected": false, "text": "int TriangleType(unsigned num1, unsigned num2)\n{\n int result;\n if (num1 == 90 || num2 == 90 || num1 + num2 == 90) {\n if (num1 == num2 || 180 - (num1 + num2) == num1 || 180 - (num1 + num2) == num2)\n result = 3;\n else\n result = 1;\n } else if (num1 == num2 || 180 - (num1 + num2) == num1 || 180 - (num1 + num2) == num2) {\n result = 2;\n } else if (num1 + num2 >= 180) {\n result = -1;\n } else {\n result = 0;\n }\n return result;\n}\n if (num1 == 90 || num2 == 90 || num1 + num2 == 90) {\n if (num1 == num2 || 180 - (num1 + num2) == num1 || 180 - (num1 + num2) == num2)\n result = 3;\n else\n result = 1;\n }\n int is_isosceles(unsigned num1, unsigned num2)\n{\n if (num1 == num2 || 180 - (num1 + num2) == num1 || 180 - (num1 + num2) == num2)\n return 1;\n else\n return 0;\n}\n\nint TriangleType(unsigned num1, unsigned num2)\n{\n int result;\n if (num1 == 90 || num2 == 90 || num1 + num2 == 90) {\n if (is_isosceles(num1, num2))\n result = 3;\n else\n result = 1;\n } else if (is_isosceles(num1, num2)) {\n result = 2;\n } else if (num1 + num2 >= 180) {\n result = -1;\n } else {\n result = 0;\n }\n return result;\n}\n #include <stdbool.h>\n" }, { "answer_id": 74665829, "author": "Tony", "author_id": 4124887, "author_profile": "https://Stackoverflow.com/users/4124887", "pm_score": 0, "selected": false, "text": "int TriangleType (unsigned num1, unsigned num2){\n\n int right = 0;\n int isosceles = 0;\n int result = 0;\n\n if( /* conditions for right angle */ ){\n right = 1;\n } \n\n if( /* conditions for isosceles */ ) {\n isosceles = 1;\n } \n\n if ( right == 1 && isosceles == 1 ) {\n result = 3;\n } else if ( right == 1) {\n result = 1;\n } else if ( isosceles == 1 ) { \n /* ... */\n } /*...*/\n return result;\n}\n" }, { "answer_id": 74665835, "author": "HungryFoolish", "author_id": 1553151, "author_profile": "https://Stackoverflow.com/users/1553151", "pm_score": 1, "selected": false, "text": "int TriangleType (unsigned num1, unsigned num2)\n{\n //Calculate the third angle and keep in num3\n unsigned num3 = 180 - (num1 + num2); \n \n //We declare a variable \"result\" and initialize it with 0\n //This way if none of our if conditions match, we would simply return 0 by \"return result;\". \n unsigned int result = 0; \n\n if (num1 == 90 || num2 == 90 || num3 == 90) //if any of our angles are 90-degree\n result += 1; //Add 1 to result (which is 0 at this point)\n if ((num1==num2) || (num2 == num3) || (num1 == num3)) //if any two angles are same i.e. isosceles\n result += 2; //Add 2 to result (which is 1 if previous if condition was true otherwise its 0) )\n \n /*\n At this point :\n 1) If it was neither right-angled or isoscles \n both the if statements will be false and result will remain 0\n\n 2) If it was right-angled we did \"result += 1\" i.e. \"result = result + 1\"\n So, In case first \"if\" condition is true, result is 1 otherwise its 0\n\n 3) If it was isoscles we did \"result += 2\" i.e. \"result = result + 2\"\n So, second \"if\" condition is true, result becomes result + 2 ie \n if result was 0 it becomes 2 or if it was 1 it becomes 3.\n */\n\n\n return result;\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17696880/" ]
74,665,141
<p>I want to delete child component, parent will delete the last child only and after that, it shows that index is -1 from hostView and can't delete the child from view</p> <p>this is my Child View</p> <pre><code>&lt;button (click)=&quot;remove_me()&quot; &gt;I am a Child {{unique_key}}, click to Remove &lt;/button&gt; </code></pre> <p>this is my Child Component</p> <pre><code>import { Component } from '@angular/core'; import { ParentComponent } from '../parent/parent.component'; @Component({ selector: 'app-child', templateUrl: './child.component.html', styleUrls: ['./child.component.css'], }) export class ChildComponent { public unique_key: number; public parentRef: ParentComponent; constructor() {} remove_me() { console.log(this.unique_key); this.parentRef.remove(this.unique_key); } } </code></pre> <p>this is my Parent View</p> <pre><code>&lt;button type=&quot;button&quot; (click)=&quot;AddChild()&quot;&gt; I am Parent, Click to create Child &lt;/button&gt; &lt;div&gt; &lt;ng-template #viewContainerRef&gt;&lt;/ng-template&gt; &lt;/div&gt; </code></pre> <p>this is my Parent Component</p> <pre><code>import { ComponentRef, ViewContainerRef, ViewChild, Component, } from '@angular/core'; import { ChildComponent } from '../child/child.component'; @Component({ selector: 'app-parent', templateUrl: './parent.component.html', styleUrls: ['./parent.component.css'], }) export class ParentComponent { @ViewChild('viewContainerRef', { read: ViewContainerRef }) vcr!: ViewContainerRef; ref!: ComponentRef&lt;ChildComponent&gt;; child_unique_key: number = 0; componentsReferences = Array&lt;ComponentRef&lt;ChildComponent&gt;&gt;(); constructor() {} AddChild() { this.ref = this.vcr.createComponent(ChildComponent); let childComponent = this.ref.instance; childComponent.unique_key = ++this.child_unique_key; childComponent.parentRef = this; } remove(key: number) { const index = this.vcr.indexOf(this.ref.hostView); console.log(index); if (index != -1) { this.vcr.remove(index); } // removing component from the list this.componentsReferences = this.componentsReferences.filter( (x) =&gt; x.instance.unique_key !== key ); } } </code></pre> <p>I tried the methods from older Angular versions that supports ComponentFactoryResolver, but I want to upgrade the version of Angular</p>
[ { "answer_id": 74665811, "author": "Juraj", "author_id": 14091997, "author_profile": "https://Stackoverflow.com/users/14091997", "pm_score": 0, "selected": false, "text": "int TriangleType(unsigned num1, unsigned num2)\n{\n int result;\n if (num1 == 90 || num2 == 90 || num1 + num2 == 90) {\n if (num1 == num2 || 180 - (num1 + num2) == num1 || 180 - (num1 + num2) == num2)\n result = 3;\n else\n result = 1;\n } else if (num1 == num2 || 180 - (num1 + num2) == num1 || 180 - (num1 + num2) == num2) {\n result = 2;\n } else if (num1 + num2 >= 180) {\n result = -1;\n } else {\n result = 0;\n }\n return result;\n}\n if (num1 == 90 || num2 == 90 || num1 + num2 == 90) {\n if (num1 == num2 || 180 - (num1 + num2) == num1 || 180 - (num1 + num2) == num2)\n result = 3;\n else\n result = 1;\n }\n int is_isosceles(unsigned num1, unsigned num2)\n{\n if (num1 == num2 || 180 - (num1 + num2) == num1 || 180 - (num1 + num2) == num2)\n return 1;\n else\n return 0;\n}\n\nint TriangleType(unsigned num1, unsigned num2)\n{\n int result;\n if (num1 == 90 || num2 == 90 || num1 + num2 == 90) {\n if (is_isosceles(num1, num2))\n result = 3;\n else\n result = 1;\n } else if (is_isosceles(num1, num2)) {\n result = 2;\n } else if (num1 + num2 >= 180) {\n result = -1;\n } else {\n result = 0;\n }\n return result;\n}\n #include <stdbool.h>\n" }, { "answer_id": 74665829, "author": "Tony", "author_id": 4124887, "author_profile": "https://Stackoverflow.com/users/4124887", "pm_score": 0, "selected": false, "text": "int TriangleType (unsigned num1, unsigned num2){\n\n int right = 0;\n int isosceles = 0;\n int result = 0;\n\n if( /* conditions for right angle */ ){\n right = 1;\n } \n\n if( /* conditions for isosceles */ ) {\n isosceles = 1;\n } \n\n if ( right == 1 && isosceles == 1 ) {\n result = 3;\n } else if ( right == 1) {\n result = 1;\n } else if ( isosceles == 1 ) { \n /* ... */\n } /*...*/\n return result;\n}\n" }, { "answer_id": 74665835, "author": "HungryFoolish", "author_id": 1553151, "author_profile": "https://Stackoverflow.com/users/1553151", "pm_score": 1, "selected": false, "text": "int TriangleType (unsigned num1, unsigned num2)\n{\n //Calculate the third angle and keep in num3\n unsigned num3 = 180 - (num1 + num2); \n \n //We declare a variable \"result\" and initialize it with 0\n //This way if none of our if conditions match, we would simply return 0 by \"return result;\". \n unsigned int result = 0; \n\n if (num1 == 90 || num2 == 90 || num3 == 90) //if any of our angles are 90-degree\n result += 1; //Add 1 to result (which is 0 at this point)\n if ((num1==num2) || (num2 == num3) || (num1 == num3)) //if any two angles are same i.e. isosceles\n result += 2; //Add 2 to result (which is 1 if previous if condition was true otherwise its 0) )\n \n /*\n At this point :\n 1) If it was neither right-angled or isoscles \n both the if statements will be false and result will remain 0\n\n 2) If it was right-angled we did \"result += 1\" i.e. \"result = result + 1\"\n So, In case first \"if\" condition is true, result is 1 otherwise its 0\n\n 3) If it was isoscles we did \"result += 2\" i.e. \"result = result + 2\"\n So, second \"if\" condition is true, result becomes result + 2 ie \n if result was 0 it becomes 2 or if it was 1 it becomes 3.\n */\n\n\n return result;\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20673042/" ]
74,665,143
<p>I am in serious trouble. I have been uploading to the s3 bucket using aws-sdk javascript, downloading it through object link. Using s3 to store images/assets to be used for the nextjs website. I have set the bucket to the read only for everyone. I just realize that this is serious problem, as anyone will be able to download from my bucket unilimited time, and the cost will be through the roof. How can I secure the download to be only from my website through presigned link(I haven't configured the presigned link on my side)? Please help me. I will provide more details below:</p> <p>current bucket policy:</p> <pre><code>{ &quot;Version&quot;: &quot;2012-10-17&quot;, &quot;Statement&quot;: [ { &quot;Sid&quot;: &quot;PublicRead&quot;, &quot;Effect&quot;: &quot;Allow&quot;, &quot;Principal&quot;: &quot;*&quot;, &quot;Action&quot;: [ &quot;s3:GetObject&quot;, &quot;s3:GetObjectVersion&quot; ], &quot;Resource&quot;: &quot;arn:aws:s3:::bucketname/*&quot; } ] } </code></pre> <p>CORS:</p> <pre><code>[ { &quot;AllowedHeaders&quot;: [ &quot;*&quot; ], &quot;AllowedMethods&quot;: [ &quot;PUT&quot;, &quot;POST&quot;, &quot;DELETE&quot;, &quot;GET&quot;, &quot;HEAD&quot; ], &quot;AllowedOrigins&quot;: [ &quot;*&quot; ], &quot;ExposeHeaders&quot;: [ &quot;x-amz-server-side-encryption&quot;, &quot;x-amz-request-id&quot;, &quot;x-amz-id-2&quot; ], &quot;MaxAgeSeconds&quot;: 3000 } ] </code></pre>
[ { "answer_id": 74665811, "author": "Juraj", "author_id": 14091997, "author_profile": "https://Stackoverflow.com/users/14091997", "pm_score": 0, "selected": false, "text": "int TriangleType(unsigned num1, unsigned num2)\n{\n int result;\n if (num1 == 90 || num2 == 90 || num1 + num2 == 90) {\n if (num1 == num2 || 180 - (num1 + num2) == num1 || 180 - (num1 + num2) == num2)\n result = 3;\n else\n result = 1;\n } else if (num1 == num2 || 180 - (num1 + num2) == num1 || 180 - (num1 + num2) == num2) {\n result = 2;\n } else if (num1 + num2 >= 180) {\n result = -1;\n } else {\n result = 0;\n }\n return result;\n}\n if (num1 == 90 || num2 == 90 || num1 + num2 == 90) {\n if (num1 == num2 || 180 - (num1 + num2) == num1 || 180 - (num1 + num2) == num2)\n result = 3;\n else\n result = 1;\n }\n int is_isosceles(unsigned num1, unsigned num2)\n{\n if (num1 == num2 || 180 - (num1 + num2) == num1 || 180 - (num1 + num2) == num2)\n return 1;\n else\n return 0;\n}\n\nint TriangleType(unsigned num1, unsigned num2)\n{\n int result;\n if (num1 == 90 || num2 == 90 || num1 + num2 == 90) {\n if (is_isosceles(num1, num2))\n result = 3;\n else\n result = 1;\n } else if (is_isosceles(num1, num2)) {\n result = 2;\n } else if (num1 + num2 >= 180) {\n result = -1;\n } else {\n result = 0;\n }\n return result;\n}\n #include <stdbool.h>\n" }, { "answer_id": 74665829, "author": "Tony", "author_id": 4124887, "author_profile": "https://Stackoverflow.com/users/4124887", "pm_score": 0, "selected": false, "text": "int TriangleType (unsigned num1, unsigned num2){\n\n int right = 0;\n int isosceles = 0;\n int result = 0;\n\n if( /* conditions for right angle */ ){\n right = 1;\n } \n\n if( /* conditions for isosceles */ ) {\n isosceles = 1;\n } \n\n if ( right == 1 && isosceles == 1 ) {\n result = 3;\n } else if ( right == 1) {\n result = 1;\n } else if ( isosceles == 1 ) { \n /* ... */\n } /*...*/\n return result;\n}\n" }, { "answer_id": 74665835, "author": "HungryFoolish", "author_id": 1553151, "author_profile": "https://Stackoverflow.com/users/1553151", "pm_score": 1, "selected": false, "text": "int TriangleType (unsigned num1, unsigned num2)\n{\n //Calculate the third angle and keep in num3\n unsigned num3 = 180 - (num1 + num2); \n \n //We declare a variable \"result\" and initialize it with 0\n //This way if none of our if conditions match, we would simply return 0 by \"return result;\". \n unsigned int result = 0; \n\n if (num1 == 90 || num2 == 90 || num3 == 90) //if any of our angles are 90-degree\n result += 1; //Add 1 to result (which is 0 at this point)\n if ((num1==num2) || (num2 == num3) || (num1 == num3)) //if any two angles are same i.e. isosceles\n result += 2; //Add 2 to result (which is 1 if previous if condition was true otherwise its 0) )\n \n /*\n At this point :\n 1) If it was neither right-angled or isoscles \n both the if statements will be false and result will remain 0\n\n 2) If it was right-angled we did \"result += 1\" i.e. \"result = result + 1\"\n So, In case first \"if\" condition is true, result is 1 otherwise its 0\n\n 3) If it was isoscles we did \"result += 2\" i.e. \"result = result + 2\"\n So, second \"if\" condition is true, result becomes result + 2 ie \n if result was 0 it becomes 2 or if it was 1 it becomes 3.\n */\n\n\n return result;\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14899600/" ]
74,665,149
<p>I expect the User to provide a sentence.</p> <p>And as an output, they will reverse a string with only the odd-length words reversed (<em>i.e. even-length words should remain intact</em>).</p> <pre><code>static String secretAgentII(String s) { StringBuffer sb = new StringBuffer(); String[] newStr = s.split(&quot; &quot;); String result = &quot;&quot;; for (int i = 0; i &lt; newStr.length; i++) { if (newStr[i].length() % 2 != 0) { sb.append(newStr[i]).reverse(); result += sb + &quot; &quot;; } result += newStr[i] + &quot; &quot;; } return result; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.nextLine(); System.out.println(secretAgentII(s)); } </code></pre> <p><em>Input:</em></p> <blockquote> <p>One two three Four</p> </blockquote> <p><em>Expected Output:</em></p> <blockquote> <p>enO owT eerhT Four</p> </blockquote> <p><em>The actual Output:</em></p> <blockquote> <p>enO One owtOne two eerhtenOtwo three Four</p> </blockquote> <p>How can I fix that?</p>
[ { "answer_id": 74665811, "author": "Juraj", "author_id": 14091997, "author_profile": "https://Stackoverflow.com/users/14091997", "pm_score": 0, "selected": false, "text": "int TriangleType(unsigned num1, unsigned num2)\n{\n int result;\n if (num1 == 90 || num2 == 90 || num1 + num2 == 90) {\n if (num1 == num2 || 180 - (num1 + num2) == num1 || 180 - (num1 + num2) == num2)\n result = 3;\n else\n result = 1;\n } else if (num1 == num2 || 180 - (num1 + num2) == num1 || 180 - (num1 + num2) == num2) {\n result = 2;\n } else if (num1 + num2 >= 180) {\n result = -1;\n } else {\n result = 0;\n }\n return result;\n}\n if (num1 == 90 || num2 == 90 || num1 + num2 == 90) {\n if (num1 == num2 || 180 - (num1 + num2) == num1 || 180 - (num1 + num2) == num2)\n result = 3;\n else\n result = 1;\n }\n int is_isosceles(unsigned num1, unsigned num2)\n{\n if (num1 == num2 || 180 - (num1 + num2) == num1 || 180 - (num1 + num2) == num2)\n return 1;\n else\n return 0;\n}\n\nint TriangleType(unsigned num1, unsigned num2)\n{\n int result;\n if (num1 == 90 || num2 == 90 || num1 + num2 == 90) {\n if (is_isosceles(num1, num2))\n result = 3;\n else\n result = 1;\n } else if (is_isosceles(num1, num2)) {\n result = 2;\n } else if (num1 + num2 >= 180) {\n result = -1;\n } else {\n result = 0;\n }\n return result;\n}\n #include <stdbool.h>\n" }, { "answer_id": 74665829, "author": "Tony", "author_id": 4124887, "author_profile": "https://Stackoverflow.com/users/4124887", "pm_score": 0, "selected": false, "text": "int TriangleType (unsigned num1, unsigned num2){\n\n int right = 0;\n int isosceles = 0;\n int result = 0;\n\n if( /* conditions for right angle */ ){\n right = 1;\n } \n\n if( /* conditions for isosceles */ ) {\n isosceles = 1;\n } \n\n if ( right == 1 && isosceles == 1 ) {\n result = 3;\n } else if ( right == 1) {\n result = 1;\n } else if ( isosceles == 1 ) { \n /* ... */\n } /*...*/\n return result;\n}\n" }, { "answer_id": 74665835, "author": "HungryFoolish", "author_id": 1553151, "author_profile": "https://Stackoverflow.com/users/1553151", "pm_score": 1, "selected": false, "text": "int TriangleType (unsigned num1, unsigned num2)\n{\n //Calculate the third angle and keep in num3\n unsigned num3 = 180 - (num1 + num2); \n \n //We declare a variable \"result\" and initialize it with 0\n //This way if none of our if conditions match, we would simply return 0 by \"return result;\". \n unsigned int result = 0; \n\n if (num1 == 90 || num2 == 90 || num3 == 90) //if any of our angles are 90-degree\n result += 1; //Add 1 to result (which is 0 at this point)\n if ((num1==num2) || (num2 == num3) || (num1 == num3)) //if any two angles are same i.e. isosceles\n result += 2; //Add 2 to result (which is 1 if previous if condition was true otherwise its 0) )\n \n /*\n At this point :\n 1) If it was neither right-angled or isoscles \n both the if statements will be false and result will remain 0\n\n 2) If it was right-angled we did \"result += 1\" i.e. \"result = result + 1\"\n So, In case first \"if\" condition is true, result is 1 otherwise its 0\n\n 3) If it was isoscles we did \"result += 2\" i.e. \"result = result + 2\"\n So, second \"if\" condition is true, result becomes result + 2 ie \n if result was 0 it becomes 2 or if it was 1 it becomes 3.\n */\n\n\n return result;\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17934589/" ]
74,665,162
<p>This is a <a href="https://docs.raku.org/language/nativecall" rel="nofollow noreferrer">NativeCall</a> question.</p> <p>I have 8 bytes (little endian) in a <code>CArray</code> representing a memory address. How do I create a <code>Pointer</code> out it?</p> <p>(<code>CArray</code> and <code>Pointer</code> are two of NativeCall's C compatible types. <code>Pointer</code>s are 8 bytes long. Things should line up, but how does one put the pointer address in a <code>CArray</code> into a <code>Pointer</code> in a way acceptable to NativeCall?)</p>
[ { "answer_id": 74672031, "author": "Håkon Hægland", "author_id": 2173773, "author_profile": "https://Stackoverflow.com/users/2173773", "pm_score": 0, "selected": false, "text": "my $ptr = nativecast(CArray[Pointer], $array);\nmy Pointer $ptr2 = $ptr[$idx];\n" }, { "answer_id": 74674303, "author": "Håkon Hægland", "author_id": 2173773, "author_profile": "https://Stackoverflow.com/users/2173773", "pm_score": 0, "selected": false, "text": "#include <stdio.h>\n#include <stdint.h>\n#include <stdlib.h>\n\ntypedef struct myStruct\n{\n int32_t A;\n double B;\n} mstruct;\n\nvoid set_pointer(mstruct **arrayOfStruct)\n{\n mstruct *ptr = (mstruct *) malloc(sizeof(mstruct)*2);\n printf(\"allocated memory at address: %p\\n\", ptr);\n ptr[0].A = 10;\n ptr[0].B = 1.1;\n ptr[1].A = 20;\n ptr[1].B = 2.1;\n *arrayOfStruct = ptr;\n}\n use v6;\nuse NativeCall;\n\nclass myStruct is repr('CStruct') {\n has int32 $.A is rw;\n has num64 $.B is rw;\n}\n\nsub set_pointer(Pointer[CArray[myStruct]] is rw) is native(\"./libtest.so\") { * };\n\nmy $array-ptr = Pointer[CArray[myStruct]].new();\nset_pointer($array-ptr);\nmy $array = nativecast(Pointer[myStruct], $array-ptr.deref);\nsay $array[0].A;\nsay $array[0].B;\nsay $array[1].A;\nsay $array[1].B;\n allocated memory at address: 0x5579f0d95ef0\n10\n1.1\n20\n2.1\n" }, { "answer_id": 74677850, "author": "Håkon Hægland", "author_id": 2173773, "author_profile": "https://Stackoverflow.com/users/2173773", "pm_score": 1, "selected": false, "text": "use NativeCall;\n\nconstant BYTE := uint8;\nconstant DWORD := uint32;\nconstant WTS_CURRENT_SERVER_HANDLE = 0; # Current (local) server\nconstant LPSTR := Str;\n\nenum WTS_CONNECTSTATE_CLASS (\n WTSActive => 0,\n WTSConnected =>1,\n WTSConnectQuery => 2,\n WTSShadow => 3,\n WTSDisconnected => 4,\n WTSIdle => 5,\n WTSListen => 6,\n WTSReset => 7,\n WTSDown => 8,\n WTSInit => 9\n);\n\nconstant WTS_CONNECTSTATE_CLASS_int := int32;\n\nclass WTS_SESSION_INFOA is repr('CStruct') {\n has DWORD $.SessionId is rw;\n has LPSTR $.pWinStationName is rw;\n has WTS_CONNECTSTATE_CLASS_int $.State;\n}\n\nsub GetWTSEnumerateSession(\n #`{\n C++\n BOOL WTSEnumerateSessionsA(\n [in] HANDLE hServer,\n [in] DWORD Reserved,\n [in] DWORD Version,\n [out] PWTS_SESSION_INFOA *ppSessionInfo,\n [out] DWORD *pCount\n );\n Returns zero if this function fails.\n }\n DWORD $hServer, # [in] HANDLE\n DWORD $Reserved, # [in] always 0\n DWORD $Version, # [in] always 1\n Pointer[Pointer] $ppSessionInf is rw, # [out] see _WTS_SESSION_INFOA and _WTS_CONNECTSTATE_CLASS;\n DWORD $pCount is rw # [out] DWORD\n )\n is native(\"Wtsapi32.dll\")\n is symbol(\"WTSEnumerateSessionsA\")\n returns DWORD # If the function fails, the return value is zero.\n { * };\n\n\nmy $hServer = Pointer[void].new();\n$hServer = WTS_CURRENT_SERVER_HANDLE; # let windows figure out what current handle is\nmy $ppSession = Pointer[Pointer].new(); # A pointer to another pointer to an array of WTS_SESSION_INFO\nmy DWORD $pCount;\n\nmy $ret-code = GetWTSEnumerateSession $hServer, 0, 1, $ppSession, $pCount;\nsay \"Return code: \" ~ $ret-code;\nmy $array = nativecast(Pointer[WTS_SESSION_INFOA], $ppSession.deref);\nsay \"Number of session info structs: \" ~ $pCount;\nfor 0..^ $pCount -> $i {\n say \"{$i} : Session id: \" ~ $array[$i].SessionId;\n say \"{$i} : Station name: \" ~ $array[$i].pWinStationName;\n say \"{$i} : Connection state: \" ~ $array[$i].State;\n}\n Return code: 1\nNumber of session info structs: 2\n0 : Session id: 0\n0 : Station name: Services\n0 : Connection state: 4\n1 : Session id: 1\n1 : Station name: Console\n1 : Connection state: 0\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9713817/" ]
74,665,170
<p>i want to asking this problem. this output is the expected output</p> <pre><code>* *# *#% *#%* *#%*# *#%*#% </code></pre> <p>and this is my solution</p> <pre><code>#include &lt;iostream&gt; using namespace std; int main(){ int a,b,n; cout &lt;&lt; &quot;Input the row&quot;; cin &gt;&gt; n; for (a = 1; a &lt;= n; a++){ for(b = 1; b &lt;= a; b++){ if (b == 1 || b == 1 + 3){ cout &lt;&lt; &quot;*&quot;; } if (b ==2 || b == 2 + 3){ cout &lt;&lt; &quot;#&quot;; } if (b ==3 || b == 3 + 3){ cout &lt;&lt; &quot;%&quot;; } } cout &lt;&lt; endl; } } </code></pre> <p>this solution is only work if the n = 6. what should i do if i want this work in every row when user input the row to the n thank you in advance.</p>
[ { "answer_id": 74672031, "author": "Håkon Hægland", "author_id": 2173773, "author_profile": "https://Stackoverflow.com/users/2173773", "pm_score": 0, "selected": false, "text": "my $ptr = nativecast(CArray[Pointer], $array);\nmy Pointer $ptr2 = $ptr[$idx];\n" }, { "answer_id": 74674303, "author": "Håkon Hægland", "author_id": 2173773, "author_profile": "https://Stackoverflow.com/users/2173773", "pm_score": 0, "selected": false, "text": "#include <stdio.h>\n#include <stdint.h>\n#include <stdlib.h>\n\ntypedef struct myStruct\n{\n int32_t A;\n double B;\n} mstruct;\n\nvoid set_pointer(mstruct **arrayOfStruct)\n{\n mstruct *ptr = (mstruct *) malloc(sizeof(mstruct)*2);\n printf(\"allocated memory at address: %p\\n\", ptr);\n ptr[0].A = 10;\n ptr[0].B = 1.1;\n ptr[1].A = 20;\n ptr[1].B = 2.1;\n *arrayOfStruct = ptr;\n}\n use v6;\nuse NativeCall;\n\nclass myStruct is repr('CStruct') {\n has int32 $.A is rw;\n has num64 $.B is rw;\n}\n\nsub set_pointer(Pointer[CArray[myStruct]] is rw) is native(\"./libtest.so\") { * };\n\nmy $array-ptr = Pointer[CArray[myStruct]].new();\nset_pointer($array-ptr);\nmy $array = nativecast(Pointer[myStruct], $array-ptr.deref);\nsay $array[0].A;\nsay $array[0].B;\nsay $array[1].A;\nsay $array[1].B;\n allocated memory at address: 0x5579f0d95ef0\n10\n1.1\n20\n2.1\n" }, { "answer_id": 74677850, "author": "Håkon Hægland", "author_id": 2173773, "author_profile": "https://Stackoverflow.com/users/2173773", "pm_score": 1, "selected": false, "text": "use NativeCall;\n\nconstant BYTE := uint8;\nconstant DWORD := uint32;\nconstant WTS_CURRENT_SERVER_HANDLE = 0; # Current (local) server\nconstant LPSTR := Str;\n\nenum WTS_CONNECTSTATE_CLASS (\n WTSActive => 0,\n WTSConnected =>1,\n WTSConnectQuery => 2,\n WTSShadow => 3,\n WTSDisconnected => 4,\n WTSIdle => 5,\n WTSListen => 6,\n WTSReset => 7,\n WTSDown => 8,\n WTSInit => 9\n);\n\nconstant WTS_CONNECTSTATE_CLASS_int := int32;\n\nclass WTS_SESSION_INFOA is repr('CStruct') {\n has DWORD $.SessionId is rw;\n has LPSTR $.pWinStationName is rw;\n has WTS_CONNECTSTATE_CLASS_int $.State;\n}\n\nsub GetWTSEnumerateSession(\n #`{\n C++\n BOOL WTSEnumerateSessionsA(\n [in] HANDLE hServer,\n [in] DWORD Reserved,\n [in] DWORD Version,\n [out] PWTS_SESSION_INFOA *ppSessionInfo,\n [out] DWORD *pCount\n );\n Returns zero if this function fails.\n }\n DWORD $hServer, # [in] HANDLE\n DWORD $Reserved, # [in] always 0\n DWORD $Version, # [in] always 1\n Pointer[Pointer] $ppSessionInf is rw, # [out] see _WTS_SESSION_INFOA and _WTS_CONNECTSTATE_CLASS;\n DWORD $pCount is rw # [out] DWORD\n )\n is native(\"Wtsapi32.dll\")\n is symbol(\"WTSEnumerateSessionsA\")\n returns DWORD # If the function fails, the return value is zero.\n { * };\n\n\nmy $hServer = Pointer[void].new();\n$hServer = WTS_CURRENT_SERVER_HANDLE; # let windows figure out what current handle is\nmy $ppSession = Pointer[Pointer].new(); # A pointer to another pointer to an array of WTS_SESSION_INFO\nmy DWORD $pCount;\n\nmy $ret-code = GetWTSEnumerateSession $hServer, 0, 1, $ppSession, $pCount;\nsay \"Return code: \" ~ $ret-code;\nmy $array = nativecast(Pointer[WTS_SESSION_INFOA], $ppSession.deref);\nsay \"Number of session info structs: \" ~ $pCount;\nfor 0..^ $pCount -> $i {\n say \"{$i} : Session id: \" ~ $array[$i].SessionId;\n say \"{$i} : Station name: \" ~ $array[$i].pWinStationName;\n say \"{$i} : Connection state: \" ~ $array[$i].State;\n}\n Return code: 1\nNumber of session info structs: 2\n0 : Session id: 0\n0 : Station name: Services\n0 : Connection state: 4\n1 : Session id: 1\n1 : Station name: Console\n1 : Connection state: 0\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20545573/" ]
74,665,232
<p>My goal is to embed an iframe (I have no control over it) with <strong>variable height</strong> and crop off the bottom 100px. The code I have so far is this:</p> <pre class="lang-html prettyprint-override"><code>&lt;iframe id=&quot;booking-content&quot; title=&quot;booking-content&quot; src=&quot;https://outlook.office365.com/owa/calendar/SDRRetailConsulting@sdrretail.com/bookings/&quot; scrolling=&quot;no&quot; allowfullscreen=&quot;allowfullscreen&quot; style=&quot;width: 1024px; height: 100vh; clip-path: inset(0px 0px 100px 0px); overflow: hidden; margin:0 auto; border:none;&quot;&gt; &lt;/iframe&gt; </code></pre> <p>Unfortunately, <code>clip-path</code> generates a white border on the bottom, see: <a href="https://i.stack.imgur.com/XQNwK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XQNwK.png" alt="screenshot" /></a></p> <p>The working sample with the code to the picture above is <a href="https://html-css-js.com/?html=%3C!DOCTYPE%20html%3E%0A%3Chtml%3E%0A%20%20%3Chead%3E%0A%20%20%20%20%3Ctitle%3EHTML%20CSS%20JS%3C/title%3E%0A%20%20%3C/head%3E%0A%20%20%3Cbody%3E%0A%20%20%20%20%3Ch1%20i$*$d=%22welcome%22%3ECropping%20an%20iframe%3C/h1%3E%0A%20%20%20%20%3Cp%3EHow%20can%20I%20get%20ri$*$d%20of%20the%20white%20space%20on%20the%20bottom?%20(due%20to%20clip-path)%3C/p%3E%0A%0A%20%20%20%20%3Ciframe%20i$*$d=%22booking-content%22%20title=%22booking-content%22%0A%20%20%20%20%20%20%20%20%20%20%20%20src=%22https://en.wikipedia.org/wiki/World_Wi$*$de_Web%22%0A%20%20%20%20%20%20%20%20%20%20%20%20scrolling=%22no%22%20allowfullscreen=%22allowfullscreen%22%0A%20%20%20%20%20%20%20%20%20%20%20%20style=%22wi$*$dth:%201024px;%20height:%20100vh;%20clip-path:%20inset(0px%200px%20100px%200px);%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20overflow:%20hi$*$dden;%20margin:0%20auto;%20border:none;%22%3E%0A%20%20%20%20%3C/iframe%3E%0A%0A%0A%20%20%3C/body%3E%0A%3C/html%3E&amp;css=/*%20CSS%20styles%20*/%0Ah1%20%7B%0Afont-family:%20Impact,%20sans-serif;%0Acolor:%20#CE5937;%0A%7D%0A%09%20%20&amp;js=//%20JavaScript%0Adocument.getElementById(%27welcome%27).innerText%20%20=%20%0A%22%20Editors%22;%0A" rel="nofollow noreferrer">here</a>.</p> <p>Thx a lot! (<a href="https://stackoverflow.com/questions/47127122/html-crop-iframe-from-bottom">This</a> question is somewhat related)</p>
[ { "answer_id": 74672031, "author": "Håkon Hægland", "author_id": 2173773, "author_profile": "https://Stackoverflow.com/users/2173773", "pm_score": 0, "selected": false, "text": "my $ptr = nativecast(CArray[Pointer], $array);\nmy Pointer $ptr2 = $ptr[$idx];\n" }, { "answer_id": 74674303, "author": "Håkon Hægland", "author_id": 2173773, "author_profile": "https://Stackoverflow.com/users/2173773", "pm_score": 0, "selected": false, "text": "#include <stdio.h>\n#include <stdint.h>\n#include <stdlib.h>\n\ntypedef struct myStruct\n{\n int32_t A;\n double B;\n} mstruct;\n\nvoid set_pointer(mstruct **arrayOfStruct)\n{\n mstruct *ptr = (mstruct *) malloc(sizeof(mstruct)*2);\n printf(\"allocated memory at address: %p\\n\", ptr);\n ptr[0].A = 10;\n ptr[0].B = 1.1;\n ptr[1].A = 20;\n ptr[1].B = 2.1;\n *arrayOfStruct = ptr;\n}\n use v6;\nuse NativeCall;\n\nclass myStruct is repr('CStruct') {\n has int32 $.A is rw;\n has num64 $.B is rw;\n}\n\nsub set_pointer(Pointer[CArray[myStruct]] is rw) is native(\"./libtest.so\") { * };\n\nmy $array-ptr = Pointer[CArray[myStruct]].new();\nset_pointer($array-ptr);\nmy $array = nativecast(Pointer[myStruct], $array-ptr.deref);\nsay $array[0].A;\nsay $array[0].B;\nsay $array[1].A;\nsay $array[1].B;\n allocated memory at address: 0x5579f0d95ef0\n10\n1.1\n20\n2.1\n" }, { "answer_id": 74677850, "author": "Håkon Hægland", "author_id": 2173773, "author_profile": "https://Stackoverflow.com/users/2173773", "pm_score": 1, "selected": false, "text": "use NativeCall;\n\nconstant BYTE := uint8;\nconstant DWORD := uint32;\nconstant WTS_CURRENT_SERVER_HANDLE = 0; # Current (local) server\nconstant LPSTR := Str;\n\nenum WTS_CONNECTSTATE_CLASS (\n WTSActive => 0,\n WTSConnected =>1,\n WTSConnectQuery => 2,\n WTSShadow => 3,\n WTSDisconnected => 4,\n WTSIdle => 5,\n WTSListen => 6,\n WTSReset => 7,\n WTSDown => 8,\n WTSInit => 9\n);\n\nconstant WTS_CONNECTSTATE_CLASS_int := int32;\n\nclass WTS_SESSION_INFOA is repr('CStruct') {\n has DWORD $.SessionId is rw;\n has LPSTR $.pWinStationName is rw;\n has WTS_CONNECTSTATE_CLASS_int $.State;\n}\n\nsub GetWTSEnumerateSession(\n #`{\n C++\n BOOL WTSEnumerateSessionsA(\n [in] HANDLE hServer,\n [in] DWORD Reserved,\n [in] DWORD Version,\n [out] PWTS_SESSION_INFOA *ppSessionInfo,\n [out] DWORD *pCount\n );\n Returns zero if this function fails.\n }\n DWORD $hServer, # [in] HANDLE\n DWORD $Reserved, # [in] always 0\n DWORD $Version, # [in] always 1\n Pointer[Pointer] $ppSessionInf is rw, # [out] see _WTS_SESSION_INFOA and _WTS_CONNECTSTATE_CLASS;\n DWORD $pCount is rw # [out] DWORD\n )\n is native(\"Wtsapi32.dll\")\n is symbol(\"WTSEnumerateSessionsA\")\n returns DWORD # If the function fails, the return value is zero.\n { * };\n\n\nmy $hServer = Pointer[void].new();\n$hServer = WTS_CURRENT_SERVER_HANDLE; # let windows figure out what current handle is\nmy $ppSession = Pointer[Pointer].new(); # A pointer to another pointer to an array of WTS_SESSION_INFO\nmy DWORD $pCount;\n\nmy $ret-code = GetWTSEnumerateSession $hServer, 0, 1, $ppSession, $pCount;\nsay \"Return code: \" ~ $ret-code;\nmy $array = nativecast(Pointer[WTS_SESSION_INFOA], $ppSession.deref);\nsay \"Number of session info structs: \" ~ $pCount;\nfor 0..^ $pCount -> $i {\n say \"{$i} : Session id: \" ~ $array[$i].SessionId;\n say \"{$i} : Station name: \" ~ $array[$i].pWinStationName;\n say \"{$i} : Connection state: \" ~ $array[$i].State;\n}\n Return code: 1\nNumber of session info structs: 2\n0 : Session id: 0\n0 : Station name: Services\n0 : Connection state: 4\n1 : Session id: 1\n1 : Station name: Console\n1 : Connection state: 0\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9189492/" ]
74,665,237
<p>One of my event’s variables isn’t getting defined.</p> <p>The <code>title</code> variable isn’t getting defined so I think I made a mistake.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var addToCartButtons = document.getElementsByClassName('item-button') for (var i = 0; i &lt; addToCartButtons.length; i++) { var button = addToCartButtons[i] button.addEventListener('click', addToCartClicked) } function addToCartClicked(event) { var button = event.target var shopItem = button.parentElement.parentElement var title = storeitem.getElementsByClassName('product-name')[0].innerHTML console.log('title') }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="store-item"&gt; &lt;span class="product-name"&gt;CPU 1&lt;/span&gt; &lt;img class="cpu-image" src="Images/CPU-1.jpg"&gt; &lt;div class="product-details"&gt; &lt;span class="item-price"&gt;$229.99&lt;/span&gt; &lt;button class="btn btn-primary item-button" role="button"&gt;ADD TO CART&lt;/button&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74665279, "author": "haggbart", "author_id": 15949328, "author_profile": "https://Stackoverflow.com/users/15949328", "pm_score": 1, "selected": false, "text": "addToCartClicked storeitem.getElementsByClassName('product-name')[0].innerHTML shopItem storeitem shopItem button.parentElement.parentElement storeitem shopItem" }, { "answer_id": 74665293, "author": "DSDmark", "author_id": 16517581, "author_profile": "https://Stackoverflow.com/users/16517581", "pm_score": 0, "selected": false, "text": "shopItem var addToCartButtons = document.getElementsByClassName('item-button')\n\nfor (var i = 0; i < addToCartButtons.length; i++) {\n var button = addToCartButtons[i]\n button.addEventListener('click', addToCartClicked)\n}\n\nfunction addToCartClicked(event) {\n var button = event.target\n \n var shopItem = button.parentElement.parentElement\n\n // error here 'storeitem' variable is defined.\n var title = shopItem.getElementsByClassName('product-name')[0].innerHTML\n \n console.log('title')\n console.log(title) // you means title varible\n} <div class=\"store-item\">\n <span class=\"product-name\">CPU 1</span>\n <img class=\"cpu-image\" src=\"Images/CPU-1.jpg\">\n <div class=\"product-details\">\n <span class=\"item-price\">$229.99</span>\n <button class=\"btn btn-primary item-button\" role=\"button\">ADD TO CART</button>\n </div>\n</div>" }, { "answer_id": 74665343, "author": "Frostishyper03", "author_id": 20642557, "author_profile": "https://Stackoverflow.com/users/20642557", "pm_score": 0, "selected": false, "text": "function addToCartClicked(event) {\n var button = event.target\n var shopItem = button.parentElement.parentElement\n var title = shopItem.getElementsByClassName('product-name')[0].innerHTML\n console.log(title)\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20642557/" ]
74,665,243
<p>I am pretty new to Python and couldn't understand the origin of this problem.</p> <p>I'm trying to implement an interface, I have downloaded the <code>zope.interface</code> package, and imported it in my file like this</p> <pre><code>import zope.interface </code></pre> <p>Now when I write</p> <pre><code>class MyInterface(zope.interface.Interface) </code></pre> <p>I get this error:</p> <pre><code>&quot;message&quot;: &quot;Inheriting 'zope.interface.Interface', which is not a class.&quot; </code></pre> <p>but when I do</p> <pre><code>class MyInterface(zope.interface.interface.InterfaceClass): </code></pre> <p>it works fine.</p> <p>I don't understand the difference.</p>
[ { "answer_id": 74665279, "author": "haggbart", "author_id": 15949328, "author_profile": "https://Stackoverflow.com/users/15949328", "pm_score": 1, "selected": false, "text": "addToCartClicked storeitem.getElementsByClassName('product-name')[0].innerHTML shopItem storeitem shopItem button.parentElement.parentElement storeitem shopItem" }, { "answer_id": 74665293, "author": "DSDmark", "author_id": 16517581, "author_profile": "https://Stackoverflow.com/users/16517581", "pm_score": 0, "selected": false, "text": "shopItem var addToCartButtons = document.getElementsByClassName('item-button')\n\nfor (var i = 0; i < addToCartButtons.length; i++) {\n var button = addToCartButtons[i]\n button.addEventListener('click', addToCartClicked)\n}\n\nfunction addToCartClicked(event) {\n var button = event.target\n \n var shopItem = button.parentElement.parentElement\n\n // error here 'storeitem' variable is defined.\n var title = shopItem.getElementsByClassName('product-name')[0].innerHTML\n \n console.log('title')\n console.log(title) // you means title varible\n} <div class=\"store-item\">\n <span class=\"product-name\">CPU 1</span>\n <img class=\"cpu-image\" src=\"Images/CPU-1.jpg\">\n <div class=\"product-details\">\n <span class=\"item-price\">$229.99</span>\n <button class=\"btn btn-primary item-button\" role=\"button\">ADD TO CART</button>\n </div>\n</div>" }, { "answer_id": 74665343, "author": "Frostishyper03", "author_id": 20642557, "author_profile": "https://Stackoverflow.com/users/20642557", "pm_score": 0, "selected": false, "text": "function addToCartClicked(event) {\n var button = event.target\n var shopItem = button.parentElement.parentElement\n var title = shopItem.getElementsByClassName('product-name')[0].innerHTML\n console.log(title)\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20673138/" ]
74,665,251
<p>I have a <a href="https://rigcount.bakerhughes.com/static-files/127758f8-64a3-4c59-a0d1-3011dc4a0000" rel="nofollow noreferrer">Spreadsheet of Time series Data</a></p> <p>It has separate tables for each year with a single row gap in between. I want to have the Year from table header as part of the date column. So that I can plot charts and do simple comparisons of the data (YoY) etc</p> <pre><code>import pandas as pd RigCountWorld_df = pd.read_excel(open('Worldwide Rig Count Nov 2022.xlsx', 'rb'), sheet_name='Worldwide_Rigcount',index_col=None, header=6) RigCountWorld_df </code></pre> <p>The code I have is no where near helpful. Even the names of pandas operations I need to use will be helpful for me.</p> <p>I need a continuous table with data from all years. It would make sense to have latest data at the very end.</p> <p>Even transposing the tables separately and adding them as new columns would make sense (with the column headers containing Year-Month names.</p>
[ { "answer_id": 74666198, "author": "abokey", "author_id": 16120011, "author_profile": "https://Stackoverflow.com/users/16120011", "pm_score": 1, "selected": false, "text": "pandas import pandas as pd\n\ndf = pd.read_excel(\"Worldwide Rig Count Nov 2022.xlsx\",\n sheet_name=\"Worldwide_Rigcount\", header=None, usecols=\"B:K\", skiprows=6)\n ​\ndf.dropna(how=\"all\", inplace=True)\ndf.insert(0, \"Year\", np.where(df[10].eq(\"Total World\"), df[1], None))\ndf[\"Year\"].ffill(inplace=True)\ndf.drop_duplicates(subset= df.columns[2:], inplace=True)\ndf.columns = [\"Year\", \"Month\"] + df.loc[0, 2:].tolist()\ndf = df.loc[1:, :].reset_index(drop=True)\n print(df.sample(5).to_string())\n​\n Year Month Latin America Europe Africa Middle East Asia Pacific Total Intl. Canada U.S. Total World\n613 1975 Mar 310 113 122 173 208 926 192 1651 2769\n588 1977 Apr 324 135 165 185 167 976 129 1907 3012\n596 1977 Dec 353 142 172 195 182 1044 259 2141 3444\n221 2005 Jan 307 57 50 242 204 860 550 1255 2665\n566 1979 Aug 440 149 199 144 219 1151 376 2222 3749\n print(df.groupby(\"Year\").size().value_counts())\n\n13 48\ndtype: int64\n" }, { "answer_id": 74666224, "author": "Mania", "author_id": 18190852, "author_profile": "https://Stackoverflow.com/users/18190852", "pm_score": 0, "selected": false, "text": "melt() concat() assign() datetime.strptime() import pandas as pd\n\n# create a list of sheet names\nsheets = ['Worldwide_Rigcount_2020', 'Worldwide_Rigcount_2021', 'Worldwide_Rigcount_2022']\n\n# create an empty list to store the dataframes\ndfs = []\n\n# loop through each sheet\nfor sheet in sheets:\n # read the sheet into a dataframe\n df = pd.read_excel('Worldwide Rig Count Nov 2022.xlsx', sheet_name=sheet, index_col=None, header=6)\n \n # extract the year from the sheet name\n year = int(sheet.split('_')[-1])\n \n # melt the dataframe from wide to long format\n df_melted = df.melt(id_vars=['Date'])\n \n # add the year from the sheet name to the dataframe\n df_melted = df_melted.assign(year=year)\n \n # convert the date column to datetime objects\n df_melted['Date'] = pd.to_datetime(df_melted['Date'], format='%b %Y', errors='coerce').dt.strftime('%Y-%m-%d') + '-' + df_melted['year'].astype(str)\n \n # append the dataframe to the list\n dfs.append(df_melted)\n \n# concat the list of dataframes into a single dataframe\ndf_final = pd.concat(dfs)\n\n# print the final dataframe\nprint(df_final)\n" }, { "answer_id": 74666247, "author": "Andreas", "author_id": 11492317, "author_profile": "https://Stackoverflow.com/users/11492317", "pm_score": 0, "selected": false, "text": "RigCountWorld_df df = RigCountWorld_df.copy()\nfirst_col = 2 # First column with data\ncolumn_names = df.iloc[0, first_col:].to_list()\ndf[\"Year\"] = df.iloc[:,[1]].where(df.iloc[:,1].astype(str).str.match(r\"^20\\d\\d$\"), None).ffill()\ndf[\"Month\"] = df.iloc[:,[1]].where(df.iloc[:,1].astype(str).isin((\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\")), None)\ndf = df[df['Month'].notna()]\ndf = df.iloc[:, first_col:].set_index([\"Year\", \"Month\"])\ndf.columns = column_names\ndf\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4399016/" ]
74,665,281
<p>I have created a program that creates an object called &quot;Point&quot; in the class &quot;Point&quot;. Now I wonder how to find the distance between two points created in the Main method. The instructions from my teacher are :</p> <blockquote> <p>Add a new method to the Point class named &quot;distance&quot;.</p> </blockquote> <pre><code>public double distance (Point other) </code></pre> <p>Returns the distance between the current Point object and the given other Point object. The distance between two points is equal to the square root of the sum of the squares of the differences of their x- and y- coordinates. In other words, the distance between two points (x1, y1) and (x2, y2) can be expressed as the square root of (x2 - x1)^2 + (y2 - y1) ^2. Two points with the same (x, y) coordinates should return a distance of 0.0.</p> <p>Below you can see my code and the task is to calculate the distance between point a and point b.</p> <pre><code>//Dimitar Kapitanov 11/6 using System; public class PointClassPt2 { public static void Main(String[] args) { //main method Point a = new Point(); Console.WriteLine(&quot;First Point&quot;); Console.Write(&quot;X: &quot;); double x = Convert.ToDouble(Console.ReadLine()); Console.Write(&quot;Y: &quot;); double y = Convert.ToDouble(Console.ReadLine()); a.setCoordinate(x, y); Point b = new Point(x, y); Console.WriteLine(&quot;\nSecond Point&quot;); Console.Write(&quot;X: &quot;); x = Convert.ToDouble(Console.ReadLine()); Console.Write(&quot;Y: &quot;); y = Convert.ToDouble(Console.ReadLine()); b.setCoordinate(x, y); Console.WriteLine(&quot;\nPoint A: (&quot; + a.getXCoordinate() + &quot; , &quot; + a.getYCoordinate() + &quot;)&quot;); Console.WriteLine(&quot;Point B: (&quot; + b.getXCoordinate() + &quot; , &quot; + b.getYCoordinate() + &quot;)&quot;); Point c = new Point(); c.setCoordinate(-x, -y); Console.WriteLine(&quot;Point C: (&quot; + c.getXCoordinate() + &quot; , &quot; + c.getYCoordinate() + &quot;)&quot;); Console.WriteLine(&quot;Distance from A to B: &quot;); } } class Point { public double _x; public double _y; public Point() { _x = 0; _y = 0; } public Point(double x, double y) { _x = x; _y = y; } public double getXCoordinate() { return _x; } public double getYCoordinate() { return _y; } public void setCoordinate(double x, double y) { _x = x; _y = y; } } </code></pre> <p>The thing that I don't understand is how to get the double values of the coordinates of Point a and Point b in order to calculate the distance in the method distance. And what does he mean by the sending the method distance &quot;Point other&quot;. Can someone help me what the method distance should look like and what should I send it as parameters in the main method?</p>
[ { "answer_id": 74665348, "author": "Charles Han", "author_id": 11514907, "author_profile": "https://Stackoverflow.com/users/11514907", "pm_score": 3, "selected": true, "text": "Point distance public double distance (Point other)\n{\n var otherX = other.getXCoordinate();\n var otherY = other.getYCoordinate();\n //you already have access to the current point _x and _y\n //now you can do the distance calculation here.\n var distance = //your formula\n return distance;\n}\n" }, { "answer_id": 74665355, "author": "Anand Sowmithiran", "author_id": 14973743, "author_profile": "https://Stackoverflow.com/users/14973743", "pm_score": 1, "selected": false, "text": "public double Distance(Point other)\n{\n if(null == other )\n return 0;\n\n //calculate the distance with the formula you already mentioned\n //double dist = sqrt( Math.Pow((other.getXcoordinate() - _x),2) + ...\n return dist;\n}\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20178516/" ]
74,665,337
<p>I have data on this form in a data.table DT:</p> <pre><code>DT = data.table( year=c('1981', '1981', '1981', '2005', '2005', '2005'), value=c(2, 8, 16, 3, 9, 27), order =c(1,2,3,1,2,3)) </code></pre> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">year</th> <th style="text-align: left;">value</th> <th style="text-align: left;">order</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">'1981'</td> <td style="text-align: left;">2</td> <td style="text-align: left;">1</td> </tr> <tr> <td style="text-align: left;">'1981'</td> <td style="text-align: left;">8</td> <td style="text-align: left;">2</td> </tr> <tr> <td style="text-align: left;">'1981'</td> <td style="text-align: left;">16</td> <td style="text-align: left;">3</td> </tr> <tr> <td style="text-align: left;">'2005'</td> <td style="text-align: left;">3</td> <td style="text-align: left;">1</td> </tr> <tr> <td style="text-align: left;">'2005'</td> <td style="text-align: left;">9</td> <td style="text-align: left;">2</td> </tr> <tr> <td style="text-align: left;">'2005'</td> <td style="text-align: left;">27</td> <td style="text-align: left;">3</td> </tr> </tbody> </table> </div> <p>And I want to create new columns based first on the order within a specific year, but then sequentially on the order if I shift it. As you can see value=16 which starts as order=3 on row 1, is logged as order = 2 on row 2, etc.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">year</th> <th style="text-align: left;">order1</th> <th style="text-align: left;">order2</th> <th style="text-align: left;">order3</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">'1981'</td> <td style="text-align: left;">2</td> <td style="text-align: left;">8</td> <td style="text-align: left;">16</td> </tr> <tr> <td style="text-align: left;">'1981'</td> <td style="text-align: left;">8</td> <td style="text-align: left;">16</td> <td style="text-align: left;">NA</td> </tr> <tr> <td style="text-align: left;">'1981'</td> <td style="text-align: left;">16</td> <td style="text-align: left;">NA</td> <td style="text-align: left;">NA</td> </tr> <tr> <td style="text-align: left;">'2005'</td> <td style="text-align: left;">3</td> <td style="text-align: left;">9</td> <td style="text-align: left;">27</td> </tr> <tr> <td style="text-align: left;">'2005'</td> <td style="text-align: left;">9</td> <td style="text-align: left;">27</td> <td style="text-align: left;">NA</td> </tr> <tr> <td style="text-align: left;">'2005'</td> <td style="text-align: left;">27</td> <td style="text-align: left;">NA</td> <td style="text-align: left;">NA</td> </tr> </tbody> </table> </div> <p>If I wanted it just by order, and get rows 1 and 4 as output, I could do:</p> <pre><code>dcast(DT, year ~ order, value.var = c('value')) </code></pre> <p>But how can I cast based on order while incorporating this reordering?</p> <p>I could perhaps create new columns indicating the new shifted order, using:</p> <pre><code>DT[,order_2:= c(NA,1,2,NA,1,2)] DT[,order_3:= c(NA,NA,1,NA,NA,1)] </code></pre> <p>But then how do I do casting on all three columns? Is there a more elegant way than just casting 3 times and then joining the results?</p>
[ { "answer_id": 74665667, "author": "jay.sf", "author_id": 6574038, "author_profile": "https://Stackoverflow.com/users/6574038", "pm_score": 2, "selected": false, "text": "dcast DT[, lapply(seq_along(value), \\(v) {l <- length(value); `length<-`(value[v:l], l)}), by=year]\n# year V1 V2 V3\n# 1: 1981 2 8 16\n# 2: 1981 8 16 NA\n# 3: 1981 16 NA NA\n# 4: 2005 3 9 27\n# 5: 2005 9 27 NA\n# 6: 2005 27 NA NA\n" }, { "answer_id": 74669269, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 1, "selected": false, "text": "shift transpose library(data.table)\nDT[, setNames(transpose(shift(value, n = seq_len(.N)-1, type = \"lead\")), \n paste0(\"order\", order)), year]\n year order1 order2 order3\n1: 1981 2 8 16\n2: 1981 8 16 NA\n3: 1981 16 NA NA\n4: 2005 3 9 27\n5: 2005 9 27 NA\n6: 2005 27 NA NA\n" }, { "answer_id": 74672397, "author": "r2evans - GO NAVY BEAT ARMY", "author_id": 3358272, "author_profile": "https://Stackoverflow.com/users/3358272", "pm_score": 1, "selected": false, "text": "dcast library(data.table)\ndcast(year + order ~ paste0(\"order\", ord2),\n data = DT[DT, on = .(year == year, order <= order)][, ord2 := seq(.N), by = .(year, order)],\n value.var = \"i.value\"\n )[, order := NULL\n ][, lapply(.SD, sort, na.last = TRUE), .SDcols = patterns(\"^order\"), by = .(year)][]\ndcast(year + order ~ paste0(\"order\", ord2), data = DT[DT, on = .(year == year, order <= order)][, ord2 := seq(.N), by = .(year, order)], value.var = \"i.value\")[, order := NULL][, lapply(.SD, sort, na.last = TRUE), .SDcols = patterns(\"^order\"), by = .(year)][]\n# year order1 order2 order3\n# <char> <num> <num> <num>\n# 1: 1981 2 8 16\n# 2: 1981 8 16 NA\n# 3: 1981 16 NA NA\n# 4: 2005 3 9 27\n# 5: 2005 9 27 NA\n# 6: 2005 27 NA NA\n bench::mark(\n jay.sf = DT[, lapply(seq_along(value), \\(v) {l <- length(value); `length<-`(value[v:l], l)}), by=year],\n akrun = DT[, setNames(transpose(shift(value, n = seq_len(.N)-1, type = \"lead\")), paste0(\"order\", order)), year],\n r2evans = dcast(year + order ~ paste0(\"order\", ord2), data = DT[DT, on = .(year == year, order <= order)][, ord2 := seq(.N), by = .(year, order)], value.var = \"i.value\")[, order := NULL][, lapply(.SD, sort, na.last = TRUE), .SDcols = patterns(\"^order\"), by = .(year)][],\n check = FALSE)\n# # A tibble: 3 x 13\n# expression min median `itr/sec` mem_alloc `gc/sec` n_itr n_gc total_time result memory time gc \n# <bch:expr> <bch:tm> <bch:tm> <dbl> <bch:byt> <dbl> <int> <dbl> <bch:tm> <list> <list> <list> <list> \n# 1 jay.sf 225.2us 266.15us 3642. 48.6KB 5.38 1354 2 372ms <NULL> <Rprofmem [11 x 3]> <bench_tm [1,356]> <tibble [1,356 x 3]>\n# 2 akrun 262.9us 307.4us 3149. 48.6KB 2.41 1305 1 414ms <NULL> <Rprofmem [12 x 3]> <bench_tm [1,306]> <tibble [1,306 x 3]>\n# 3 r2evans 2.74ms 2.99ms 330. 453.3KB 2.30 143 1 434ms <NULL> <Rprofmem [91 x 3]> <bench_tm [144]> <tibble [144 x 3]> \n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9730443/" ]
74,665,341
<p>I want to use BINARY UUIDs as my primary key in my tables, but using my own custom functions that generates optimised UUIDs loosely based on this article: <a href="https://mariadb.com/kb/en/guiduuid-performance/" rel="nofollow noreferrer">https://mariadb.com/kb/en/guiduuid-performance/</a></p> <p>The table structure and two main functions of interest here are:</p> <pre><code>CREATE TABLE `Test` ( `Id` BINARY(16), `Data` VARCHAR(100) ) ENGINE=InnoDB ROW_FORMAT=DYNAMIC CHARACTER SET 'utf8mb4' COLLATE 'utf8mb4_unicode_ci'; CREATE DEFINER = 'user'@'%' FUNCTION `OPTIMISE_UUID_STR`(`_uuid` VARCHAR(36)) RETURNS VARCHAR(32) CHARACTER SET utf8mb4 DETERMINISTIC NO SQL SQL SECURITY INVOKER COMMENT '' BEGIN /* FROM 00 10 20 30 123456789012345678901234567890123456 ==================================== AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE TO 00 10 20 30 12345678901234567890123456789012 ================================ CCCCBBBBAAAAAAAADDDDEEEEEEEEEEEE */ RETURN UCASE(CONCAT( SUBSTR(_uuid, 15, 4), /* Time nodes reversed */ SUBSTR(_uuid, 10, 4), SUBSTR(_uuid, 1, 8), SUBSTR(_uuid, 20, 4), /* MAC nodes last */ SUBSTR(_uuid, 25, 12))); END; CREATE DEFINER = 'user'@'%' FUNCTION `CONVERT_OPTIMISED_UUID_STR_TO_BIN`(`_hexstr` BINARY(32)) RETURNS BINARY(16) DETERMINISTIC NO SQL SQL SECURITY INVOKER COMMENT '' BEGIN /* Convert optimised UUID from string hex representation to binary. If the UUID is not optimised, it makes no sense to convert */ RETURN UNHEX(_hexstr); END; </code></pre> <p>I cannot use my custom functions in column definition as shown below</p> <pre><code>CREATE TABLE `Test` ( `Id` BINARY(16) NOT NULL DEFAULT CONVERT_OPTIMISED_UUID_STR_TO_BIN(OPTIMISE_UUID_STR(UUID())), </code></pre> <p>I get the error &quot;Function or expression '<code>OPTIMISE_UUID_STR</code>()' cannot be used in the DEFAULT clause of <code>Id</code>&quot;</p> <p>So I tried using the same in Triggers:</p> <pre><code>CREATE DEFINER = 'user'@'%' TRIGGER `Test_before_ins_tr1` BEFORE INSERT ON `Test` FOR EACH ROW BEGIN IF (new.Id IS NULL) OR (new.Id = X'0000000000000000') OR (new.Id = X'FFFFFFFFFFFFFFFF') THEN SET new.Id = CONVERT_OPTIMISED_UUID_STR_TO_BIN(OPTIMISE_UUID_STR(UUID())); END IF; END; </code></pre> <p>The above works pretty good, but the issue is that I cannot define the <code>Id</code> column as PRIMARY KEY, which I want to because PRIMARY KEYs have to be NOT NULL, and setting this means I have to pre-generate optimised UUIDs. I do not want to do this as I would like the DB to take care of generating the optimised UUIDs.</p> <p>As you might have inferred looking at the above Trigger definition, I tried setting a default value on the <code>Id</code> column, such as:</p> <pre><code>Id` BINARY(16) NOT NULL DEFAULT X'0000000000000000' </code></pre> <p>and</p> <pre><code>Id` BINARY(16) NOT NULL DEFAULT X'FFFFFFFFFFFFFFFF' </code></pre> <p>and</p> <pre><code>Id` BINARY(16) NOT NULL DEFAULT '0' /* I tried setting 0, but always seem to revert to '0' */ </code></pre> <p>and this default value would be picked up by the trigger and a correct optimised UUID assigned. But that also does not work as the DB complains &quot;Column 'Id' cannot be null&quot; even though a DEFAULT value has been set.</p> <p>So my actual question is: Can I generate a custom (optimised UUID) BINARY value for a PRIMARY KEY column?</p>
[ { "answer_id": 74665667, "author": "jay.sf", "author_id": 6574038, "author_profile": "https://Stackoverflow.com/users/6574038", "pm_score": 2, "selected": false, "text": "dcast DT[, lapply(seq_along(value), \\(v) {l <- length(value); `length<-`(value[v:l], l)}), by=year]\n# year V1 V2 V3\n# 1: 1981 2 8 16\n# 2: 1981 8 16 NA\n# 3: 1981 16 NA NA\n# 4: 2005 3 9 27\n# 5: 2005 9 27 NA\n# 6: 2005 27 NA NA\n" }, { "answer_id": 74669269, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 1, "selected": false, "text": "shift transpose library(data.table)\nDT[, setNames(transpose(shift(value, n = seq_len(.N)-1, type = \"lead\")), \n paste0(\"order\", order)), year]\n year order1 order2 order3\n1: 1981 2 8 16\n2: 1981 8 16 NA\n3: 1981 16 NA NA\n4: 2005 3 9 27\n5: 2005 9 27 NA\n6: 2005 27 NA NA\n" }, { "answer_id": 74672397, "author": "r2evans - GO NAVY BEAT ARMY", "author_id": 3358272, "author_profile": "https://Stackoverflow.com/users/3358272", "pm_score": 1, "selected": false, "text": "dcast library(data.table)\ndcast(year + order ~ paste0(\"order\", ord2),\n data = DT[DT, on = .(year == year, order <= order)][, ord2 := seq(.N), by = .(year, order)],\n value.var = \"i.value\"\n )[, order := NULL\n ][, lapply(.SD, sort, na.last = TRUE), .SDcols = patterns(\"^order\"), by = .(year)][]\ndcast(year + order ~ paste0(\"order\", ord2), data = DT[DT, on = .(year == year, order <= order)][, ord2 := seq(.N), by = .(year, order)], value.var = \"i.value\")[, order := NULL][, lapply(.SD, sort, na.last = TRUE), .SDcols = patterns(\"^order\"), by = .(year)][]\n# year order1 order2 order3\n# <char> <num> <num> <num>\n# 1: 1981 2 8 16\n# 2: 1981 8 16 NA\n# 3: 1981 16 NA NA\n# 4: 2005 3 9 27\n# 5: 2005 9 27 NA\n# 6: 2005 27 NA NA\n bench::mark(\n jay.sf = DT[, lapply(seq_along(value), \\(v) {l <- length(value); `length<-`(value[v:l], l)}), by=year],\n akrun = DT[, setNames(transpose(shift(value, n = seq_len(.N)-1, type = \"lead\")), paste0(\"order\", order)), year],\n r2evans = dcast(year + order ~ paste0(\"order\", ord2), data = DT[DT, on = .(year == year, order <= order)][, ord2 := seq(.N), by = .(year, order)], value.var = \"i.value\")[, order := NULL][, lapply(.SD, sort, na.last = TRUE), .SDcols = patterns(\"^order\"), by = .(year)][],\n check = FALSE)\n# # A tibble: 3 x 13\n# expression min median `itr/sec` mem_alloc `gc/sec` n_itr n_gc total_time result memory time gc \n# <bch:expr> <bch:tm> <bch:tm> <dbl> <bch:byt> <dbl> <int> <dbl> <bch:tm> <list> <list> <list> <list> \n# 1 jay.sf 225.2us 266.15us 3642. 48.6KB 5.38 1354 2 372ms <NULL> <Rprofmem [11 x 3]> <bench_tm [1,356]> <tibble [1,356 x 3]>\n# 2 akrun 262.9us 307.4us 3149. 48.6KB 2.41 1305 1 414ms <NULL> <Rprofmem [12 x 3]> <bench_tm [1,306]> <tibble [1,306 x 3]>\n# 3 r2evans 2.74ms 2.99ms 330. 453.3KB 2.30 143 1 434ms <NULL> <Rprofmem [91 x 3]> <bench_tm [144]> <tibble [144 x 3]> \n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15433936/" ]
74,665,344
<p>I have a requirement to create a network receiver thread by storing the thread join handle inside a network receiver struct. But I'm getting errors <code>error[E0506]: cannot assign to self.join_handle because it is borrowed</code> and <code>error[E0521]: borrowed data escapes outside of associated function</code>, while I'm creating the thread inside the start method. This is my code</p> <pre><code>use std::thread; use std::sync::atomic::{AtomicBool, Ordering}; pub struct NetworkReceiver { terminate_flag: AtomicBool, join_handle: Option&lt;thread::JoinHandle&lt;()&gt;&gt; } impl NetworkReceiver { pub fn new() -&gt; NetworkReceiver { let net_recv_intf = NetworkReceiver { terminate_flag: AtomicBool::new(false), join_handle: None }; net_recv_intf } pub fn start(&amp;mut self) { self.join_handle = Some(thread::spawn(|| self.run())); } pub fn run(&amp;mut self) { while !self.terminate_flag.load(Ordering::Relaxed) { } } pub fn terminate(&amp;mut self) { self.terminate_flag.store(true, Ordering::Relaxed); } } </code></pre>
[ { "answer_id": 74665451, "author": "Juicyrook", "author_id": 20250235, "author_profile": "https://Stackoverflow.com/users/20250235", "pm_score": -1, "selected": false, "text": "use std::thread;\nuse std::sync::atomic::{AtomicBool, Ordering};\n\npub struct NetworkReceiver {\n terminate_flag: AtomicBool,\n join_handle: Option<thread::JoinHandle<()>>\n}\n\nimpl NetworkReceiver {\n pub fn new() -> NetworkReceiver {\n let net_recv_intf = NetworkReceiver {\n terminate_flag: AtomicBool::new(false),\n join_handle: None\n };\n\n net_recv_intf\n }\n\n pub fn start(&mut self) {\n let join_handle = thread::spawn(|| self.run());\n self.join_handle = Some(join_handle);\n }\n\n fn run(&self) {\n let mut buff: [u8; 2048] = [0; 2048];\n\n while !self.terminate_flag.load(Ordering::Relaxed) {\n // Do something here\n }\n }\n\n pub fn terminate(&mut self) {\n self.terminate_flag.store(true, Ordering::Relaxed);\n }\n}\n\nfn main() {\n let mut net_recv = NetworkReceiver::new();\n net_recv.start();\n net_recv.terminate();\n}\n" }, { "answer_id": 74665511, "author": "user20673258", "author_id": 20673258, "author_profile": "https://Stackoverflow.com/users/20673258", "pm_score": 0, "selected": false, "text": "(thread::spawn(|| self.run()); self self NetworkReceiver::new() fn foo(&mut self) fn foo(self: Arc<Self>)" }, { "answer_id": 74665825, "author": "cafce25", "author_id": 442760, "author_profile": "https://Stackoverflow.com/users/442760", "pm_score": 2, "selected": false, "text": "join_handle NetworkReceiver use std::thread;\nuse std::sync::{\n atomic::{AtomicBool, Ordering},\n Arc,\n};\n\npub struct NetworkReceiver {\n terminate_flag: AtomicBool,\n}\npub struct RunningNetworkReceiver {\n join_handle: thread::JoinHandle<()>,\n network_receiver: Arc<NetworkReceiver>,\n}\n\nimpl NetworkReceiver {\n pub fn new() -> NetworkReceiver {\n let net_recv_intf = NetworkReceiver {\n terminate_flag: AtomicBool::new(false),\n };\n\n net_recv_intf\n }\n\n pub fn start(self) -> RunningNetworkReceiver {\n let network_receiver = Arc::new(self);\n let join_handle = {\n let network_receiver = network_receiver.clone();\n thread::spawn(move || network_receiver.run())\n };\n RunningNetworkReceiver {\n join_handle,\n network_receiver,\n }\n }\n pub fn run(&self) {\n while !self.terminate_flag.load(Ordering::Relaxed) {\n }\n }\n}\nimpl RunningNetworkReceiver {\n pub fn terminate(&self) {\n self.network_receiver.terminate_flag.store(true, Ordering::Relaxed);\n }\n}\n NetworkReceiver RwLock Mutex" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3938402/" ]
74,665,350
<p>We need to find the sum of the following number to a given range n which describes is n=5 then the last term will be 55555.</p>
[ { "answer_id": 74665424, "author": "bn_ln", "author_id": 10535824, "author_profile": "https://Stackoverflow.com/users/10535824", "pm_score": 2, "selected": true, "text": "mul def find_sum(digit, max_repeats):\n return sum(int(str(digit)*(i+1)) for i in range(max_repeats))\n\nprint(find_sum(5, 5))\n#output 61725\n" }, { "answer_id": 74665481, "author": "fflores", "author_id": 13576060, "author_profile": "https://Stackoverflow.com/users/13576060", "pm_score": 0, "selected": false, "text": "def sum(n):\n # This will be multiplied.\n nbr=0\n # This will be the return value.\n ret=0\n for i in range(0, n):\n # Every iteration this will add 1 to the nbr: 1, 11, 111, etc.\n nbr = nbr + 10 ** i\n # Multiply by 5 and sum with the previous value: 5 + 55 + 555 + etc.\n ret = nbr * 5 + ret\n print(ret)\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20622172/" ]
74,665,377
<p>I have the following structure User is a parent to Assignee and Submitter. A Submitter has a one to many relationship with Request. A Request is Many to Many relationship with Assignee.</p> <p>I have the following 2 queries that I'd like to combine into one table:</p> <pre><code>Select r.request_number, u.first_name as Assignee from requests r, users u join request_assignee ra on r.id = ra.request_id join assignee a on u.id = ra.assignee_id; Select requests.request_number as Request_Number, users.first_name as Submitter from requests Join submitter on requests.submitter_id = submitter.id Join request_assignee on requests.id = request_assignee.request_id join users on submitter.id = users.id; </code></pre> <p>There can be more than one assignee to the request. How can I do 1 query to display results in one table?</p> <p>Here is a picture that might help with the tables:</p> <p><a href="https://i.stack.imgur.com/JnALW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JnALW.png" alt="schema" /></a></p>
[ { "answer_id": 74665424, "author": "bn_ln", "author_id": 10535824, "author_profile": "https://Stackoverflow.com/users/10535824", "pm_score": 2, "selected": true, "text": "mul def find_sum(digit, max_repeats):\n return sum(int(str(digit)*(i+1)) for i in range(max_repeats))\n\nprint(find_sum(5, 5))\n#output 61725\n" }, { "answer_id": 74665481, "author": "fflores", "author_id": 13576060, "author_profile": "https://Stackoverflow.com/users/13576060", "pm_score": 0, "selected": false, "text": "def sum(n):\n # This will be multiplied.\n nbr=0\n # This will be the return value.\n ret=0\n for i in range(0, n):\n # Every iteration this will add 1 to the nbr: 1, 11, 111, etc.\n nbr = nbr + 10 ** i\n # Multiply by 5 and sum with the previous value: 5 + 55 + 555 + etc.\n ret = nbr * 5 + ret\n print(ret)\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4079729/" ]
74,665,384
<p>Below is my code from leetcode. I think that I have write proper logic code but it not work only for edge case - &quot;race a car&quot;. It returns true for that but it should be false. why it is? Link of question - <a href="https://leetcode.com/problems/valid-palindrome" rel="nofollow noreferrer">https://leetcode.com/problems/valid-palindrome</a></p> <p>I know I can find answers with more approaches in solutions section but <strong>I want to that what is missing in my code.</strong></p> <pre><code>class Solution { public: bool isPalindrome(string s) { int st =0, e=s.size()-1; vector&lt;char&gt; ans1; vector&lt;char&gt; ans2; while(st&lt;=e){ if((s[st] &gt;= 'a' &amp;&amp; s[st] &lt;= 'z') || (s[st] &gt;= 'A' &amp;&amp; s[st] &lt;= 'Z') || (s[st] &gt;= '0' &amp;&amp; s[st] &lt;= '9')){ ans1.push_back(islower(s[st])); } if((s[st] &gt;= 'a' &amp;&amp; s[st] &lt;= 'z') || (s[st] &gt;= 'A' &amp;&amp; s[st] &lt;= 'Z') || (s[st] &gt;= '0' &amp;&amp; s[st] &lt;= '9')){ ans2.push_back(islower(s[e])); } st++; e--; } if(ans1 == ans2){return 1;} return 0; } }; </code></pre>
[ { "answer_id": 74665424, "author": "bn_ln", "author_id": 10535824, "author_profile": "https://Stackoverflow.com/users/10535824", "pm_score": 2, "selected": true, "text": "mul def find_sum(digit, max_repeats):\n return sum(int(str(digit)*(i+1)) for i in range(max_repeats))\n\nprint(find_sum(5, 5))\n#output 61725\n" }, { "answer_id": 74665481, "author": "fflores", "author_id": 13576060, "author_profile": "https://Stackoverflow.com/users/13576060", "pm_score": 0, "selected": false, "text": "def sum(n):\n # This will be multiplied.\n nbr=0\n # This will be the return value.\n ret=0\n for i in range(0, n):\n # Every iteration this will add 1 to the nbr: 1, 11, 111, etc.\n nbr = nbr + 10 ** i\n # Multiply by 5 and sum with the previous value: 5 + 55 + 555 + etc.\n ret = nbr * 5 + ret\n print(ret)\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19148152/" ]
74,665,422
<p>Hello I'm a total beginner to Unity and just installed. Every time I try to create new 3D project, Error window pop up &quot;Failed to resolve project template: [com.unity.template.3d] is not a valid project template.&quot; any suggestions on what to do? Unity 3.3.0</p> <p>I tried googling the answer but it seems that the Error for everyone else is different than mine.</p>
[ { "answer_id": 74665424, "author": "bn_ln", "author_id": 10535824, "author_profile": "https://Stackoverflow.com/users/10535824", "pm_score": 2, "selected": true, "text": "mul def find_sum(digit, max_repeats):\n return sum(int(str(digit)*(i+1)) for i in range(max_repeats))\n\nprint(find_sum(5, 5))\n#output 61725\n" }, { "answer_id": 74665481, "author": "fflores", "author_id": 13576060, "author_profile": "https://Stackoverflow.com/users/13576060", "pm_score": 0, "selected": false, "text": "def sum(n):\n # This will be multiplied.\n nbr=0\n # This will be the return value.\n ret=0\n for i in range(0, n):\n # Every iteration this will add 1 to the nbr: 1, 11, 111, etc.\n nbr = nbr + 10 ** i\n # Multiply by 5 and sum with the previous value: 5 + 55 + 555 + etc.\n ret = nbr * 5 + ret\n print(ret)\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20673299/" ]
74,665,430
<p>I have a program which checks whether a given number from 0 to 9999 is a prime number or not (It was provided as a sample solution):</p> <pre><code>public class Primzahl { public static void main(String[] args) { for (int i = 0; i &lt; 10000; i++) { System.out.println(i + &quot; &quot; + isPrimzahl(i)); } System.out.println(); } public static boolean isPrimzahl(int zahl) { for (int i = 2; i &lt; (zahl / 2 + 1); i++) { if (zahl % i == 0) { return false; } } return true; } } </code></pre> <p>However, I am having problems with understanding parts of the code:</p> <pre><code>i &lt; (zahl / 2 + 1) </code></pre> <p>How is this part working?</p> <p>And:</p> <pre><code> if (zahl % i == 0) { return false; } </code></pre> <p>With how many numbers is a given <code>zahl</code> checked in this program?</p> <p>Edit: typo.</p>
[ { "answer_id": 74665475, "author": "Andrew B", "author_id": 7325087, "author_profile": "https://Stackoverflow.com/users/7325087", "pm_score": 2, "selected": true, "text": "i < (zahl / 2 + 1)\n if (zahl % i == 0) {\n return false;\n }\n zahl % i == 0" }, { "answer_id": 74665493, "author": "Hiran Chaudhuri", "author_id": 4222206, "author_profile": "https://Stackoverflow.com/users/4222206", "pm_score": 0, "selected": false, "text": "i < (zahl / 2 + 1)\n zahl i zahl % i == 0\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9240628/" ]
74,665,441
<p>I have</p> <pre><code>x= ['AA', 'BB', 'CC'] </code></pre> <p>and I want to lower case only <code>'BB'</code>.</p>
[ { "answer_id": 74665475, "author": "Andrew B", "author_id": 7325087, "author_profile": "https://Stackoverflow.com/users/7325087", "pm_score": 2, "selected": true, "text": "i < (zahl / 2 + 1)\n if (zahl % i == 0) {\n return false;\n }\n zahl % i == 0" }, { "answer_id": 74665493, "author": "Hiran Chaudhuri", "author_id": 4222206, "author_profile": "https://Stackoverflow.com/users/4222206", "pm_score": 0, "selected": false, "text": "i < (zahl / 2 + 1)\n zahl i zahl % i == 0\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20673289/" ]
74,665,453
<p>I'm creating a Twitter/Reddit style website. I've been wondering what is the best way to securely send the in-depth details of comment data via a reply button press, grabbing it in JS and sending it back to my database</p> <p>If there are 100 comments with 100 reply buttons, can I store the comment ID in the value field of the button or is this too open? My feelings are that even if users know the ID values of the comment they reply to, anyone that attempts to abuse a system with spam would get automatically limited or banned via server side detection.</p> <p>Note that on the server side, a user already has a session so spam should be quite visible... right?</p> <p>I've seen the option to use type=&quot;hidden&quot;, eg: but it seems this can be pulled with a little jquery anyway. Thoughts?</p> <p>Thanks.</p>
[ { "answer_id": 74665475, "author": "Andrew B", "author_id": 7325087, "author_profile": "https://Stackoverflow.com/users/7325087", "pm_score": 2, "selected": true, "text": "i < (zahl / 2 + 1)\n if (zahl % i == 0) {\n return false;\n }\n zahl % i == 0" }, { "answer_id": 74665493, "author": "Hiran Chaudhuri", "author_id": 4222206, "author_profile": "https://Stackoverflow.com/users/4222206", "pm_score": 0, "selected": false, "text": "i < (zahl / 2 + 1)\n zahl i zahl % i == 0\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17370936/" ]
74,665,469
<p>I have this code and when I run it I get this: <code>[I@2c7b84de</code>.</p> <p>Can someone explain to me why I get that?</p> <pre><code>public class EJer22 { public static void main(String[] args){ int[] numeros = { 50, 21, 6, 97, 18 }; System.out.println(numeros); } public static int[] pruebas (int[] P){ int[] S = new int[P.length]; if(P.length &lt; 10){ System.out.println(&quot;Hay mas de 10 numeros&quot;); } else { for(int i = 0; i &lt; P.length; i++){ //S = P[i]; if(10 &gt;= P[i]){ S[i] = -1; }else{ S[i] = P[i]; } } } return S; } } </code></pre>
[ { "answer_id": 74665475, "author": "Andrew B", "author_id": 7325087, "author_profile": "https://Stackoverflow.com/users/7325087", "pm_score": 2, "selected": true, "text": "i < (zahl / 2 + 1)\n if (zahl % i == 0) {\n return false;\n }\n zahl % i == 0" }, { "answer_id": 74665493, "author": "Hiran Chaudhuri", "author_id": 4222206, "author_profile": "https://Stackoverflow.com/users/4222206", "pm_score": 0, "selected": false, "text": "i < (zahl / 2 + 1)\n zahl i zahl % i == 0\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20673338/" ]
74,665,502
<p>So, I am following the <a href="https://www.mongodb.com/languages/mern-stack-tutorial" rel="nofollow noreferrer">MERN stack tutorial</a> from the MongoDB official website.</p> <p>In the create.js file we create the <code>Create</code> component. Follows the code sample:</p> <pre><code>import React, { useState } from 'react'; import { useNavigate } from 'react-router'; export default function Create() { const [form, setForm] = useState({ name: '', position: '', level: '', }); const navigate = useNavigate(); // These methods will update the state properties. function updateForm(value) { return setForm((prev) =&gt; { return { ...prev, ...value }; }); } // This function will handle the submission. async function onSubmit(e) { e.preventDefault(); // When a post request is sent to the create url, we'll add a new record to the database. const newPerson = { ...form }; await fetch('http://localhost:5005/record/add', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(form), }).catch((error) =&gt; { window.alert(error); return; }); setForm({ name: '', position: '', level: '' }); navigate('/'); } // This following section will display the form that takes the input from the user. return ( &lt;div&gt; &lt;h3&gt;Create New Record&lt;/h3&gt; &lt;form onSubmit={onSubmit}&gt; &lt;div className=&quot;form-group&quot;&gt; &lt;label htmlFor=&quot;name&quot;&gt;Name&lt;/label&gt; &lt;input type=&quot;text&quot; className=&quot;form-control&quot; id=&quot;name&quot; value={form.name} onChange={(e) =&gt; updateForm({ name: e.target.value })} /&gt; &lt;/div&gt; &lt;div className=&quot;form-group&quot;&gt; &lt;label htmlFor=&quot;position&quot;&gt;Position&lt;/label&gt; &lt;input type=&quot;text&quot; className=&quot;form-control&quot; id=&quot;position&quot; value={form.position} onChange={(e) =&gt; updateForm({ position: e.target.value })} /&gt; &lt;/div&gt; &lt;div className=&quot;form-group&quot;&gt; &lt;div className=&quot;form-check form-check-inline&quot;&gt; &lt;input className=&quot;form-check-input&quot; type=&quot;radio&quot; name=&quot;positionOptions&quot; id=&quot;positionIntern&quot; value=&quot;Intern&quot; checked={form.level === 'Intern'} onChange={(e) =&gt; updateForm({ level: e.target.value })} /&gt; &lt;label htmlFor=&quot;positionIntern&quot; className=&quot;form-check-label&quot;&gt; Intern &lt;/label&gt; &lt;/div&gt; &lt;div className=&quot;form-check form-check-inline&quot;&gt; &lt;input className=&quot;form-check-input&quot; type=&quot;radio&quot; name=&quot;positionOptions&quot; id=&quot;positionJunior&quot; value=&quot;Junior&quot; checked={form.level === 'Junior'} onChange={(e) =&gt; updateForm({ level: e.target.value })} /&gt; &lt;label htmlFor=&quot;positionJunior&quot; className=&quot;form-check-label&quot;&gt; Junior &lt;/label&gt; &lt;/div&gt; &lt;div className=&quot;form-check form-check-inline&quot;&gt; &lt;input className=&quot;form-check-input&quot; type=&quot;radio&quot; name=&quot;positionOptions&quot; id=&quot;positionSenior&quot; value=&quot;Senior&quot; checked={form.level === 'Senior'} onChange={(e) =&gt; updateForm({ level: e.target.value })} /&gt; &lt;label htmlFor=&quot;positionSenior&quot; className=&quot;form-check-label&quot;&gt; Senior &lt;/label&gt; &lt;/div&gt; &lt;/div&gt; &lt;div className=&quot;form-group&quot;&gt; &lt;input type=&quot;submit&quot; value=&quot;Create person&quot; className=&quot;btn btn-primary&quot; /&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; ); } </code></pre> <p>I have difficulty to decode what updateForm() does exactly</p> <pre><code>function updateForm(value) { return setForm((prev) =&gt; { return { ...prev, ...value }; }); } </code></pre> <p>My questions are:</p> <ol> <li>What is the value of <code>prev</code> parameter? I don't understand how this works as we don't place any value in this parameter.</li> <li>How <code>setForm()</code> manipulates <code>{ ...prev, ...value }</code>. Why couldn't we use <code>setForm({ value })</code> instead?</li> </ol>
[ { "answer_id": 74665475, "author": "Andrew B", "author_id": 7325087, "author_profile": "https://Stackoverflow.com/users/7325087", "pm_score": 2, "selected": true, "text": "i < (zahl / 2 + 1)\n if (zahl % i == 0) {\n return false;\n }\n zahl % i == 0" }, { "answer_id": 74665493, "author": "Hiran Chaudhuri", "author_id": 4222206, "author_profile": "https://Stackoverflow.com/users/4222206", "pm_score": 0, "selected": false, "text": "i < (zahl / 2 + 1)\n zahl i zahl % i == 0\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17095078/" ]
74,665,525
<p>I am making a web application with NextJs. In the page I need to fetch an api to get data and display it. But it compiles I have got an error.</p> <p>The error is : <code>Error: Your `getStaticProps` function did not return an object. Did you forget to add a `return`?</code></p> <p>And there is my function :</p> <pre><code>export async function getStaticProps(context) { try { const res = await fetch(ApiLinks.players.all) .then((response) =&gt; response.json()) .then((response) =&gt; response.data.teamMembers) const responsePlayers = res.players; const responseStaff = res.staff; return { props: { responsePlayers, responseStaff, } } } catch (err) { console.error(err); } } </code></pre>
[ { "answer_id": 74665475, "author": "Andrew B", "author_id": 7325087, "author_profile": "https://Stackoverflow.com/users/7325087", "pm_score": 2, "selected": true, "text": "i < (zahl / 2 + 1)\n if (zahl % i == 0) {\n return false;\n }\n zahl % i == 0" }, { "answer_id": 74665493, "author": "Hiran Chaudhuri", "author_id": 4222206, "author_profile": "https://Stackoverflow.com/users/4222206", "pm_score": 0, "selected": false, "text": "i < (zahl / 2 + 1)\n zahl i zahl % i == 0\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17906472/" ]
74,665,531
<p>I have plupload and I have microphone, I want to add and send audio I have recorded from plupload to server. How can I do it with close to zero needless actions ? I tried to use addFile, but it do not work</p> <pre><code>var uploader = new plupload.Uploader({ runtimes : 'html5,flash,silverlight,html4', browse_button : 'pickfiles', // you can pass in id... container: document.getElementById('container'), // ... or DOM Element itself url : &quot;upload.php&quot;, chunk_size : '1mb', init: { PostInit: function() { document.getElementById('filelist').innerHTML = ''; document.getElementById('uploadfiles').onclick = function() { { uploader.start(); $(&quot;#uploadfiles&quot;).hide(); return false; } }; }, FilesAdded: function(up, files) { plupload.each(files, function(file) { document.getElementById('filelist').innerHTML += '&lt;div id=&quot;' + file.id + '&quot;&gt;' + file.name + ' (' + plupload.formatSize(file.size) + ') &lt;b&gt;&lt;/b&gt;&lt;/div&gt;'; $(&quot;#uploadfiles&quot;).show(); }); }, Error: function(up, err) { document.getElementById('console').innerHTML += &quot;\nError #&quot; + err.code + &quot;: &quot; + err.message; } } }); </code></pre> <p>below is audio example I want to save from microphone</p> <pre><code>(437) [Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, Blob, …] [0 … 99] [100 … 199] [200 … 299] [300 … 399] [400 … 436] </code></pre>
[ { "answer_id": 74665475, "author": "Andrew B", "author_id": 7325087, "author_profile": "https://Stackoverflow.com/users/7325087", "pm_score": 2, "selected": true, "text": "i < (zahl / 2 + 1)\n if (zahl % i == 0) {\n return false;\n }\n zahl % i == 0" }, { "answer_id": 74665493, "author": "Hiran Chaudhuri", "author_id": 4222206, "author_profile": "https://Stackoverflow.com/users/4222206", "pm_score": 0, "selected": false, "text": "i < (zahl / 2 + 1)\n zahl i zahl % i == 0\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20447769/" ]
74,665,577
<p>Im learning Python here so please spare me for silly questions. I Encounter an issue with adding attribute to a class instance</p> <p>I have a dictionary of people with name,age and strength, i.e</p> <pre><code>{ &quot;Mary&quot;: {&quot;age&quot;:25, &quot;strength&quot;: 80}, &quot;John&quot;: {&quot;age&quot;: 40, &quot;strength&quot;: 70}, ... } </code></pre> <p>and a class that will get in list of people as constructor input and add them as its own attribute, and when that attribute is called, it will return the age</p> <p>i.e:</p> <pre><code>group = Person({dictionary of person}) # call person name as attribute, get back age first_person = group.Mary # return 25 here group.John # return 40 here </code></pre> <p>However, each attribute will also need to maintain its behavior as a dict/object</p> <pre><code>group.Mary[&quot;strength&quot;] # return 80 here </code></pre> <p>I tried <code>__get()__</code> but it seems to work only on class variables which is not this case since I need to create multiple group instances of class Person and they don't share variables.</p> <p>Also tried <code>setattr()</code> but it will keep each attribute as a dict and therefore cannot directly call like <code>group.Mary</code>to get age</p> <p>May I know is there any way in Python to implement this requirement?</p>
[ { "answer_id": 74665475, "author": "Andrew B", "author_id": 7325087, "author_profile": "https://Stackoverflow.com/users/7325087", "pm_score": 2, "selected": true, "text": "i < (zahl / 2 + 1)\n if (zahl % i == 0) {\n return false;\n }\n zahl % i == 0" }, { "answer_id": 74665493, "author": "Hiran Chaudhuri", "author_id": 4222206, "author_profile": "https://Stackoverflow.com/users/4222206", "pm_score": 0, "selected": false, "text": "i < (zahl / 2 + 1)\n zahl i zahl % i == 0\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14759425/" ]
74,665,592
<p>I accidentally deleted a piece of code on <code>Visual Studio Code</code>. I haven't closed visual studio yet.</p> <p><code>CTRL + Z</code> doesn't work. <code>Edit + Undo</code> doesn't work either. The variables are still stored. It was accidental. I just happen to close a jupyter notebook box</p> <p>Any idea how I can recover thank you?</p>
[ { "answer_id": 74665679, "author": "bravopapa", "author_id": 20176161, "author_profile": "https://Stackoverflow.com/users/20176161", "pm_score": 1, "selected": false, "text": "CTRL +Z .ipynb" }, { "answer_id": 74665770, "author": "Warkaz", "author_id": 10985412, "author_profile": "https://Stackoverflow.com/users/10985412", "pm_score": 2, "selected": true, "text": "timeline Right click on your .ipynb file Open Timeline Restore contents" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20176161/" ]
74,665,618
<p>If you have a constructor which calls this() when is super() called? In the first constructor called? Or in the last constructor without the keyword this()?</p> <p>Main calls: new B()</p> <pre><code>public class A { public A(){ System.out.print(&quot;A &quot;); } } public class B extends A { public B(){ // is super called here? Option 1 this(1); System.out.print(&quot;B0 &quot;); } public B(int i){ // or is super called here? Option 2 System.out.print(&quot;B1 &quot;); } } </code></pre> <p>In this example the Output is: &quot;A B1 B0&quot;. But it isn't clear to me, if the super() constructor is called at Option 1 or Option 2 (because the Output would be the same, in this case).</p>
[ { "answer_id": 74666240, "author": "Mario Mateaș", "author_id": 14808001, "author_profile": "https://Stackoverflow.com/users/14808001", "pm_score": 0, "selected": false, "text": "new B() public B() this() super() System.out.print(\"B0); super() this(1) int this() super() super() super() print A() A B1 this(1) B0 super() public B(int i) this() super() this() super()" }, { "answer_id": 74666344, "author": "Mike Nakis", "author_id": 773113, "author_profile": "https://Stackoverflow.com/users/773113", "pm_score": 2, "selected": false, "text": "B() B(int)" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13519512/" ]
74,665,643
<p>I've tried to write a program which converts decimal to binary and vice versa but when I try 23, it flags line 17 (answer2 -= x) as a type error.</p> <pre><code> import math x = 4096 y = &quot;&quot; z = 10 q = 1 final_answer = 0 answer1 = str(input(&quot;Do you want to convert decimal into binary (1) or binary into decimal (2)?&quot;)) if answer1 == &quot;1&quot;: answer2 = input(&quot;What number do you want to convert to binary? It can't be larger than 4096&quot;) p = answer2.isdigit() if p: for i in range(13): if int(answer2) &gt;= x: y = y + &quot;1&quot; answer2 -= x else: y = y + &quot;0&quot; x /= 2 print(y) elif not p: print(&quot;That's not a number&quot;) </code></pre> <p>I tried to convert the variables of answer2 and x to float and int but the same problem still comes up.</p>
[ { "answer_id": 74665694, "author": "Lexpj", "author_id": 10229386, "author_profile": "https://Stackoverflow.com/users/10229386", "pm_score": 1, "selected": false, "text": "answer2 = float(answer2)\n" }, { "answer_id": 74665916, "author": "chivalrous-nerd", "author_id": 7347835, "author_profile": "https://Stackoverflow.com/users/7347835", "pm_score": 0, "selected": false, "text": "answer2 x import math\n\nx = 4096\ny = \"\"\nz = 10\nq = 1\nfinal_answer = 0\n\nanswer1 = str(input(\"Do you want to convert decimal into binary (1) or binary into decimal (2)?\"))\nif answer1 == \"1\":\n answer2 = input(\"What number do you want to convert to binary? It can't be larger than 4096\")\n p = answer2.isdigit()\n if p:\n # Convert the string value of answer2 to an integer\n answer2 = int(answer2)\n for i in range(13):\n if answer2 >= x:\n y = y + \"1\"\n answer2 -= x\n else:\n y = y + \"0\"\n\n x /= 2\n\n print(y)\n elif not p:\n print(\"That's not a number\")\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20340948/" ]
74,665,675
<p>I am trying to determine the majority in a list of lists for a project I am working on. My problem is that the code will run in an environment that not allow me to use packages. Can someone refer me to an algorithm that does what I am asking or let me know about a way to do it with pre built functions in python that don't require outside packages?. Thank you for your time.</p> <p><strong>Example:</strong></p> <p><code>data = [ [&quot;hello&quot;, 1], [&quot;hello&quot;, 1], [&quot;hello&quot;, 1], [&quot;other&quot;, 32] ]</code></p> <p><strong>Output:</strong></p> <p><code>[&quot;hello&quot;, 1]</code></p>
[ { "answer_id": 74665694, "author": "Lexpj", "author_id": 10229386, "author_profile": "https://Stackoverflow.com/users/10229386", "pm_score": 1, "selected": false, "text": "answer2 = float(answer2)\n" }, { "answer_id": 74665916, "author": "chivalrous-nerd", "author_id": 7347835, "author_profile": "https://Stackoverflow.com/users/7347835", "pm_score": 0, "selected": false, "text": "answer2 x import math\n\nx = 4096\ny = \"\"\nz = 10\nq = 1\nfinal_answer = 0\n\nanswer1 = str(input(\"Do you want to convert decimal into binary (1) or binary into decimal (2)?\"))\nif answer1 == \"1\":\n answer2 = input(\"What number do you want to convert to binary? It can't be larger than 4096\")\n p = answer2.isdigit()\n if p:\n # Convert the string value of answer2 to an integer\n answer2 = int(answer2)\n for i in range(13):\n if answer2 >= x:\n y = y + \"1\"\n answer2 -= x\n else:\n y = y + \"0\"\n\n x /= 2\n\n print(y)\n elif not p:\n print(\"That's not a number\")\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19916855/" ]
74,665,703
<p>if i have a value like this :</p> <blockquote> <p>C:100% B:90% A:80%</p> </blockquote> <p>i want to add comma after every % so the output is like this :</p> <blockquote> <p>C:100%,B:90%,A:80%</p> </blockquote> <p>i've tried somthing like :</p> <pre><code>data['Final'] = data['Final'].str.replace(r'(%)\n\b', r'\1,', regex=True) </code></pre>
[ { "answer_id": 74665800, "author": "abokey", "author_id": 16120011, "author_profile": "https://Stackoverflow.com/users/16120011", "pm_score": 0, "selected": false, "text": "df['final']= df['final'].str.replace(r'%\\s*\\b', r'%,', regex=True)\n print(df)\n\n final\n0 C:100%,B:90%,A:80%\n" }, { "answer_id": 74665813, "author": "Agni", "author_id": 8106804, "author_profile": "https://Stackoverflow.com/users/8106804", "pm_score": 1, "selected": false, "text": "re.sub re import re\n\n# Your original string\nstring = \"C:100% B:90% A:80%\"\n\n# Use regex to replace all occurrences of '%' with ',%'\nstring = re.sub(\"%\", \",%\", string)\n\n# The resulting string will be: \"C:100%, B:90%, A:80%\"\n import pandas as pd\nimport re\n\n# Create a DataFrame with a column of strings\ndf = pd.DataFrame({\"values\": [\"C:100% B:90% A:80%\", \"D:70% E:60% F:50%\"]})\n\n# Use the apply method to apply the regex substitution to each value in the column\ndf[\"values\"] = df[\"values\"].apply(lambda x: re.sub(\"% \", \"%,\", x))\n 0 C:100%,B:90%,A:80%\n1 D:70%,E:60%,F:50%\n" }, { "answer_id": 74666063, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 0, "selected": false, "text": "\\s+ data = pd.DataFrame({\"Final\": [\"C:100% B:90% A:80%\"]})\ndata['Final'] = data['Final'].str.replace(r'(%) \\b', r'\\1,', regex=True)\nprint(data)\n Final\n0 C:100%,B:90%,A:80%\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20671365/" ]
74,665,717
<p>Here is my sample data</p> <pre><code>const data = [{&quot;amount&quot;: &quot;600,000&quot;, &quot;cover&quot;: null, &quot;id&quot;: &quot;1&quot;, &quot;img&quot;: &quot;636e56de36301.1.png&quot;, &quot;make&quot;: &quot;bmw&quot;, &quot;model&quot;: &quot;bmw&quot;, &quot;name&quot;: &quot;APA&quot;, &quot;policy&quot;: &quot;Motor Insurance&quot;, &quot;rate&quot;: &quot;6&quot;}, {&quot;amount&quot;: &quot;300,000&quot;, &quot;cover&quot;: null, &quot;id&quot;: &quot;2&quot;, &quot;img&quot;: &quot;63723574a81ce.1.png&quot;, &quot;make&quot;: &quot;ferrari&quot;, &quot;model&quot;: &quot;ferrari&quot;, &quot;name&quot;: &quot;CIC&quot;, &quot;policy&quot;: &quot;Motor Insurance&quot;, &quot;rate&quot;: &quot;3&quot;}, {&quot;amount&quot;: &quot;450,000&quot;, &quot;cover&quot;: null, &quot;id&quot;: &quot;3&quot;, &quot;img&quot;: &quot;63723726cb1df.1.png&quot;, &quot;make&quot;: &quot;audi&quot;, &quot;model&quot;: &quot;audi&quot;, &quot;name&quot;: &quot;Mayfair Insurance&quot;, &quot;policy&quot;: &quot;Motor Insurance&quot;, &quot;rate&quot;: &quot;4.5&quot;}] </code></pre> <p>and here is the code am using to return the array for id 3.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const data = [{"amount": "600,000", "cover": null, "id": "1", "img": "636e56de36301.1.png", "make": "bmw", "model": "bmw", "name": "APA", "policy": "Motor Insurance", "rate": "6"}, {"amount": "300,000", "cover": null, "id": "2", "img": "63723574a81ce.1.png", "make": "ferrari", "model": "ferrari", "name": "CIC", "policy": "Motor Insurance", "rate": "3"}, {"amount": "450,000", "cover": null, "id": "3", "img": "63723726cb1df.1.png", "make": "audi", "model": "audi", "name": "Mayfair Insurance", "policy": "Motor Insurance", "rate": "4.5"}] const id = ['3'] const provider = data.reduce((prv, item) =&gt; { if(id.includes(item.id)){ return prv } return prv }); console.log('This is provider' ,provider);</code></pre> </div> </div> </p> <p>Unfortunately, the return am getting is data with an id of 1</p> <p>Output:</p> <pre><code> This is provider {&quot;amount&quot;: &quot;600,000&quot;, &quot;cover&quot;: null, &quot;id&quot;: &quot;1&quot;, &quot;img&quot;: &quot;636e56de36301.1.png&quot;, &quot;make&quot;: &quot;bmw&quot;, &quot;model&quot;: &quot;bmw&quot;, &quot;name&quot;: &quot;APA&quot;, &quot;policy&quot;: &quot;Motor Insurance&quot;, &quot;rate&quot;: &quot;6&quot;} </code></pre> <p>can someone tell what am doing wrong please</p>
[ { "answer_id": 74665784, "author": "Asraf", "author_id": 20361860, "author_profile": "https://Stackoverflow.com/users/20361860", "pm_score": 2, "selected": true, "text": "reduce() reduce() reduce item if(id.includes(item.id)) return item prev .reduce() const data = [{\"amount\": \"600,000\", \"cover\": null, \"id\": \"1\", \"img\": \"636e56de36301.1.png\", \"make\": \"bmw\", \"model\": \"bmw\", \"name\": \"APA\", \"policy\": \"Motor Insurance\", \"rate\": \"6\"}, {\"amount\": \"300,000\", \"cover\": null, \"id\": \"2\", \"img\": \"63723574a81ce.1.png\", \"make\": \"ferrari\", \"model\": \"ferrari\", \"name\": \"CIC\", \"policy\": \"Motor Insurance\", \"rate\": \"3\"}, {\"amount\": \"450,000\", \"cover\": null, \"id\": \"3\", \"img\": \"63723726cb1df.1.png\", \"make\": \"audi\", \"model\": \"audi\", \"name\": \"Mayfair Insurance\", \"policy\": \"Motor Insurance\", \"rate\": \"4.5\"}]\n\nconst id = ['3'];\nconst provider = data.reduce((prv, item) => {\n if(id.includes(item.id)){\n return item \n }\nreturn prv\n}, {});\n\nconsole.log(provider); .filter() const data = [{\"amount\": \"600,000\", \"cover\": null, \"id\": \"1\", \"img\": \"636e56de36301.1.png\", \"make\": \"bmw\", \"model\": \"bmw\", \"name\": \"APA\", \"policy\": \"Motor Insurance\", \"rate\": \"6\"}, {\"amount\": \"300,000\", \"cover\": null, \"id\": \"2\", \"img\": \"63723574a81ce.1.png\", \"make\": \"ferrari\", \"model\": \"ferrari\", \"name\": \"CIC\", \"policy\": \"Motor Insurance\", \"rate\": \"3\"}, {\"amount\": \"450,000\", \"cover\": null, \"id\": \"3\", \"img\": \"63723726cb1df.1.png\", \"make\": \"audi\", \"model\": \"audi\", \"name\": \"Mayfair Insurance\", \"policy\": \"Motor Insurance\", \"rate\": \"4.5\"}]\n\nconst id = ['3'];\nconsole.log(data.filter(it => id.includes(it.id)));" }, { "answer_id": 74674637, "author": "Isfan Bogdan", "author_id": 2915547, "author_profile": "https://Stackoverflow.com/users/2915547", "pm_score": 0, "selected": false, "text": "const data = [\n {\n \"amount\": \"600,000\",\n \"cover\": null,\n \"id\": \"1\",\n \"img\": \"636e56de36301.1.png\",\n \"make\": \"bmw\",\n \"model\": \"bmw\",\n \"name\": \"APA\",\n \"policy\": \"Motor Insurance\",\n \"rate\": \"6\"\n },\n {\n \"amount\": \"300,000\",\n \"cover\": null,\n \"id\": \"2\",\n \"img\": \"63723574a81ce.1.png\",\n \"make\": \"ferrari\",\n \"model\": \"ferrari\",\n \"name\": \"CIC\",\n \"policy\": \"Motor Insurance\",\n \"rate\": \"3\"\n },\n {\n \"amount\": \"450,000\",\n \"cover\": null,\n \"id\": \"3\",\n \"img\": \"63723726cb1df.1.png\",\n \"make\": \"audi\",\n \"model\": \"audi\",\n \"name\": \"Mayfair Insurance\",\n \"policy\": \"Motor Insurance\",\n \"rate\": \"4.5\"\n }\n];\n\nconst id = ['3'];\n\nconst provider = data.filter(item => id.includes(item.id));\nconsole.log('This is provider', provider);\n [\n {\n \"amount\": \"450,000\",\n \"cover\": null,\n \"id\": \"3\",\n \"img\": \"63723726cb1df.1.png\",\n \"make\": \"audi\",\n \"model\": \"audi\",\n \"name\": \"Mayfair Insurance\",\n \"policy\": \"Motor Insurance\",\n \"rate\": \"4.5\"\n }\n]\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11114439/" ]
74,665,726
<p>Let's say I have a list with a bunch of numbers in it, I'm looking to make a function that will list and return the numbers that are being repeated in <strong>most</strong> of them.</p> <p>Example code:</p> <pre><code>—ListOfNumbers = [1234, 9912349, 578] -print(GetPatern(ListOfNumbers)) 1234 </code></pre>
[ { "answer_id": 74665942, "author": "chivalrous-nerd", "author_id": 7347835, "author_profile": "https://Stackoverflow.com/users/7347835", "pm_score": 1, "selected": false, "text": "def get_pattern(numbers):\n # First, we will create a dictionary where the keys are the numbers in our list,\n # and the values are the number of times those numbers appear in the list\n number_count = {}\n for number in numbers:\n if number not in number_count:\n number_count[number] = 1\n else:\n number_count[number] += 1\n\n # Next, we will find the number that appears the most times in the list\n # by looping through the dictionary and finding the key with the highest value\n max_count = 0\n max_number = 0\n for number, count in number_count.items():\n if count > max_count:\n max_count = count\n max_number = number\n\n # Finally, we will return the numbers that appear the most times in the list\n # by checking each number in the list and adding it to the result if it matches\n # the number with the highest count\n result = []\n for number in numbers:\n if number == max_number:\n result.append(number)\n\n return result\n ListOfNumbers = [1234, 9912349, 578]\nprint(get_pattern(ListOfNumbers)) # This should print [1234]\n 1234" }, { "answer_id": 74666162, "author": "Frank Gallagher", "author_id": 15374745, "author_profile": "https://Stackoverflow.com/users/15374745", "pm_score": 0, "selected": false, "text": "from collections import Counter \ndef pattern_finder(lst_of_numbers, length_of_pattern):\n pattern_lst = []\n\n # loop over numbers and transform them to strings\n for number in lst_of_numbers:\n num_str = str(number) \n \n # iterate over the string looking for subtrings that match the \n # length specified in the input and append them to list \n for idx, val in enumerate(num_str): \n pat = num_str[idx:idx+length_of_pattern]\n if len(pat) == length_of_pattern: \n pattern_lst.append(pat)\n\n # extract the subtrings with the max occurence\n count_lst = Counter(pattern_lst)\n lst_max_pattern = [pattern for pattern, count in count_lst.items() if count==max(count_lst.values())]\n return lst_max_pattern\n lst_of_numbers = [1234, 9912349, 9578, 929578]\npattern_finder(lst_of_numbers, length_of_pattern=4)\n ['1234', '9578']\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19519009/" ]
74,665,763
<p>I am making a simple web-shop application prototype and need to pass shopping cart items (which are stored in localStorage) to our SQLServer. The localStorage is as follows</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>{"grootfigure":{"name":"Groot figure","tag":"grootfigure","price":600,"inCart":2},"owlfigure":{"name":"Owl figure","tag":"owlfigure","price":350,"inCart":4},"dragonfigure":{"name":"Dragon figure","tag":"dragonfigure","price":475,"inCart":5}}</code></pre> </div> </div> </p> <p>The first idea was to pass the quantity of each product in cart to each counter variable in C# and then use a separate method in C# to run an SQL Query. But this seemed difficult to accomplish.</p> <p>When I tried to pass variables between JS and C# by</p> <pre class="lang-js prettyprint-override"><code>function addOwl(){ @Globals.String = localStorage.getItem('productsInCart') alert(@Globals.String) } </code></pre> <p>I get this in the web browser console</p> <p><code>Uncaught ReferenceError: addOwl is not defined at HTMLButtonElement.onclick (cart:71:68)</code></p> <p>Any ideas how I can easily run SQL query from localStorage values? Thank you</p>
[ { "answer_id": 74670846, "author": "Avrohom Yisroel", "author_id": 706346, "author_profile": "https://Stackoverflow.com/users/706346", "pm_score": 0, "selected": false, "text": "@Globals.String = localStorage.getItem('productsInCart')\n String Globals jim function addOwl(){\n jim = localStorage.getItem('productsInCart')\n alert(jim)\n\n \n }\n" }, { "answer_id": 74671246, "author": "Zero Sense", "author_id": 8607935, "author_profile": "https://Stackoverflow.com/users/8607935", "pm_score": 1, "selected": false, "text": "function sendCartData() {\n // Get the shopping cart data from localStorage\n var cartData = localStorage.getItem('productsInCart');\n\n // Use jQuery's $.ajax() method to send the data to a server-side endpoint\n $.ajax({\n url: '/your-server-endpoint',\n type: 'POST',\n data: { cartData: cartData },\n success: function(response) {\n // Handle the response from the server\n }\n });\n} [HttpPost]\npublic IActionResult SaveCartData(string cartData) {\n // Validate and sanitize the cart data before using it in an SQL query\n\n // Use Entity Framework or another ORM to save the data to your database\n using (var db = new YourDbContext()) {\n // Create a new ShoppingCart object and populate it with the cart data\n var cart = new ShoppingCart {\n // Parse the cart data and populate the ShoppingCart object\n };\n\n // Save the ShoppingCart object to the database\n db.ShoppingCarts.Add(cart);\n db.SaveChanges();\n }\n\n // Return a success response to the client\n return Json(new { success = true });\n}" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14944885/" ]
74,665,768
<p>NullReferenceException: Object reference not set to an instance of an object</p> <p>StarterAssets.ThirdPersonController.Move () (at Assets/Scripts/ThirdPersonController.cs:258)</p> <p>StarterAssets.ThirdPersonController.Update () (at Assets/Scripts/ThirdPersonController.cs:161)</p> <p>from 155 to 161 line:</p> <pre><code>private void Update() { _hasAnimator = TryGetComponent(out _animator); JumpAndGravity(); GroundedCheck(); Move(); </code></pre> <p>from 257 to 265</p> <pre><code>{ _targetRotation = Mathf.Atan2(inputDirection.x, inputDirection.z) * Mathf.Rad2Deg + _mainCamera.transform.eulerAngles.y; float rotation = Mathf.SmoothDampAngle(transform.eulerAngles.y, _targetRotation, ref _rotationVelocity, RotationSmoothTime); // rotate to face input direction relative to camera position transform.rotation = Quaternion.Euler(0.0f, rotation, 0.0f); } </code></pre> <p>What causes the error?</p>
[ { "answer_id": 74670846, "author": "Avrohom Yisroel", "author_id": 706346, "author_profile": "https://Stackoverflow.com/users/706346", "pm_score": 0, "selected": false, "text": "@Globals.String = localStorage.getItem('productsInCart')\n String Globals jim function addOwl(){\n jim = localStorage.getItem('productsInCart')\n alert(jim)\n\n \n }\n" }, { "answer_id": 74671246, "author": "Zero Sense", "author_id": 8607935, "author_profile": "https://Stackoverflow.com/users/8607935", "pm_score": 1, "selected": false, "text": "function sendCartData() {\n // Get the shopping cart data from localStorage\n var cartData = localStorage.getItem('productsInCart');\n\n // Use jQuery's $.ajax() method to send the data to a server-side endpoint\n $.ajax({\n url: '/your-server-endpoint',\n type: 'POST',\n data: { cartData: cartData },\n success: function(response) {\n // Handle the response from the server\n }\n });\n} [HttpPost]\npublic IActionResult SaveCartData(string cartData) {\n // Validate and sanitize the cart data before using it in an SQL query\n\n // Use Entity Framework or another ORM to save the data to your database\n using (var db = new YourDbContext()) {\n // Create a new ShoppingCart object and populate it with the cart data\n var cart = new ShoppingCart {\n // Parse the cart data and populate the ShoppingCart object\n };\n\n // Save the ShoppingCart object to the database\n db.ShoppingCarts.Add(cart);\n db.SaveChanges();\n }\n\n // Return a success response to the client\n return Json(new { success = true });\n}" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19358776/" ]
74,665,774
<p>I'm learning purpose of JWT tokens in ASP.NET Core, but I don't understand one thing. Why does every blog calling JWT authentication? If we pass a token to an authenticated (logged-in) user. I mean why JWT is not authorization but authentication? Can't understand which point I'm skipping in this topic.</p> <p><a href="https://i.stack.imgur.com/C697b.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/C697b.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74670846, "author": "Avrohom Yisroel", "author_id": 706346, "author_profile": "https://Stackoverflow.com/users/706346", "pm_score": 0, "selected": false, "text": "@Globals.String = localStorage.getItem('productsInCart')\n String Globals jim function addOwl(){\n jim = localStorage.getItem('productsInCart')\n alert(jim)\n\n \n }\n" }, { "answer_id": 74671246, "author": "Zero Sense", "author_id": 8607935, "author_profile": "https://Stackoverflow.com/users/8607935", "pm_score": 1, "selected": false, "text": "function sendCartData() {\n // Get the shopping cart data from localStorage\n var cartData = localStorage.getItem('productsInCart');\n\n // Use jQuery's $.ajax() method to send the data to a server-side endpoint\n $.ajax({\n url: '/your-server-endpoint',\n type: 'POST',\n data: { cartData: cartData },\n success: function(response) {\n // Handle the response from the server\n }\n });\n} [HttpPost]\npublic IActionResult SaveCartData(string cartData) {\n // Validate and sanitize the cart data before using it in an SQL query\n\n // Use Entity Framework or another ORM to save the data to your database\n using (var db = new YourDbContext()) {\n // Create a new ShoppingCart object and populate it with the cart data\n var cart = new ShoppingCart {\n // Parse the cart data and populate the ShoppingCart object\n };\n\n // Save the ShoppingCart object to the database\n db.ShoppingCarts.Add(cart);\n db.SaveChanges();\n }\n\n // Return a success response to the client\n return Json(new { success = true });\n}" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13249741/" ]
74,665,777
<p>I have this drawer I learned to make on youtube</p> <p><a href="https://www.youtube.com/watch?v=JLICaBEiJS0&amp;list=PLQkwcJG4YTCSpJ2NLhDTHhi6XBNfk9WiC&amp;index=31" rel="nofollow noreferrer">https://www.youtube.com/watch?v=JLICaBEiJS0&amp;list=PLQkwcJG4YTCSpJ2NLhDTHhi6XBNfk9WiC&amp;index=31</a> Philipp Lackner</p> <p><a href="https://i.stack.imgur.com/eZuP6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eZuP6.png" alt="SwipeScreen" /></a> <a href="https://i.stack.imgur.com/WPJXO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WPJXO.png" alt="enter image description here" /></a></p> <p>I want to add the drawer to my app which has multiple screens and some of them don't need the drawer so I implemented navigation with screens , and some of the screens need to also have the drawer ontop of them wrap them.</p> <p>this is the code of the drawer</p> <pre><code> val scaffoldState = rememberScaffoldState() val scope = rememberCoroutineScope() Scaffold( drawerGesturesEnabled = scaffoldState.drawerState.isOpen, scaffoldState = scaffoldState, topBar = { AppBar(onNavigationIconClick = { scope.launch { scaffoldState.drawerState.open() } }) }, drawerContent = { DrawerHeader() DrawerBody(items = listOf( MenuItem( id = &quot;home&quot;, title = &quot;Home&quot;, contentDescription = &quot;Go to home screen&quot;, icon = Icons.Default.Home ), MenuItem( id = &quot;settings&quot;, title = &quot;Settings&quot;, contentDescription = &quot;Go to Settings screen&quot;, icon = Icons.Default.Settings ), MenuItem( id = &quot;help&quot;, title = &quot;Help&quot;, contentDescription = &quot;Go to help screen&quot;, icon = Icons.Default.Info ), ), onItemClick = { println(&quot;Clicked on ${it.title}&quot;) when (it.id) { &quot;home&quot; -&gt; { println(&quot;Clicked on ${it.title}&quot;) } &quot;settings&quot; -&gt; { println(&quot;Clicked on ${it.title}&quot;) } &quot;help&quot; -&gt; { println(&quot;Clicked on ${it.title}&quot;) } } }) }) { Text(text = &quot;Hello World&quot;) } </code></pre> <p>the Text = Hellow world is where I want to pass my parameter of the screen which I don't know how to do it. I want to add a parameter that takes a composable function and runs it inside</p> <p>and I followed this navigation video on how to navigate in kotlin</p> <p><a href="https://www.youtube.com/watch?v=4gUeyNkGE3g&amp;list=PLQkwcJG4YTCSpJ2NLhDTHhi6XBNfk9WiC&amp;index=18" rel="nofollow noreferrer">https://www.youtube.com/watch?v=4gUeyNkGE3g&amp;list=PLQkwcJG4YTCSpJ2NLhDTHhi6XBNfk9WiC&amp;index=18</a></p> <p>which has 3 big files so if you ask I post them here but I will try to be more specific about what is needed</p> <pre><code>composable(route = Screen.RegisterScreen.route) { RegisterScreen(navController = navCotroller) } </code></pre> <p>and if I put the code in the drawer it works well but I want to split the code to be cleaner because I use the drawer in more places</p> <p>the code work like the example bellow</p> <pre><code>composable(route = Screen.PreferenceScreen.route) { val scaffoldState = rememberScaffoldState() val scope = rememberCoroutineScope() Scaffold( drawerGesturesEnabled = scaffoldState.drawerState.isOpen, scaffoldState = scaffoldState, topBar = { AppBar(onNavigationIconClick = { scope.launch { scaffoldState.drawerState.open() } }) }, drawerContent = { DrawerHeader() DrawerBody(items = listOf( MenuItem( id = &quot;swipe&quot;, title = &quot;Swipe&quot;, contentDescription = &quot;Go to Swipe screen&quot;, icon = Icons.Default.Home ), MenuItem( id = &quot;settings&quot;, title = &quot;Settings&quot;, contentDescription = &quot;Go to Settings screen&quot;, icon = Icons.Default.Settings ), MenuItem( id = &quot;profile&quot;, title = &quot;Profile&quot;, contentDescription = &quot;Go to profile screen&quot;, icon = Icons.Default.Info ), ), onItemClick = { when (it.id) { &quot;swipe&quot; -&gt; { navCotroller.navigate(Screen.SwipeScreen.route) } &quot;settings&quot; -&gt; { navCotroller.navigate(Screen.PreferenceScreen.route) } &quot;profile&quot; -&gt; { navCotroller.navigate(Screen.CelebProfileScreen.route) } } }) }) { -----&gt; PreferenceScreen(navController = navCotroller) } } </code></pre> <p>but it is not clean code!! how can I use a function pointer to make this work ??</p> <p><a href="https://i.stack.imgur.com/cVHat.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cVHat.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74670846, "author": "Avrohom Yisroel", "author_id": 706346, "author_profile": "https://Stackoverflow.com/users/706346", "pm_score": 0, "selected": false, "text": "@Globals.String = localStorage.getItem('productsInCart')\n String Globals jim function addOwl(){\n jim = localStorage.getItem('productsInCart')\n alert(jim)\n\n \n }\n" }, { "answer_id": 74671246, "author": "Zero Sense", "author_id": 8607935, "author_profile": "https://Stackoverflow.com/users/8607935", "pm_score": 1, "selected": false, "text": "function sendCartData() {\n // Get the shopping cart data from localStorage\n var cartData = localStorage.getItem('productsInCart');\n\n // Use jQuery's $.ajax() method to send the data to a server-side endpoint\n $.ajax({\n url: '/your-server-endpoint',\n type: 'POST',\n data: { cartData: cartData },\n success: function(response) {\n // Handle the response from the server\n }\n });\n} [HttpPost]\npublic IActionResult SaveCartData(string cartData) {\n // Validate and sanitize the cart data before using it in an SQL query\n\n // Use Entity Framework or another ORM to save the data to your database\n using (var db = new YourDbContext()) {\n // Create a new ShoppingCart object and populate it with the cart data\n var cart = new ShoppingCart {\n // Parse the cart data and populate the ShoppingCart object\n };\n\n // Save the ShoppingCart object to the database\n db.ShoppingCarts.Add(cart);\n db.SaveChanges();\n }\n\n // Return a success response to the client\n return Json(new { success = true });\n}" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13104490/" ]
74,665,788
<p>I have list of numbers as str</p> <pre class="lang-py prettyprint-override"><code>li = ['1', '4', '8.6'] </code></pre> <p>if I use <code>int</code> to convert the result is <code>[1, 4, 8]</code>. If I use <code>float</code> to convert the result is <code>[1.0, 4.0, 8.6]</code></p> <p>I want to convert them to <code>[1, 4, 8.6]</code></p> <p>I've tried this:</p> <pre class="lang-py prettyprint-override"><code>li = [1, 4, 8.6] intli = list(map(lambda x: int(x),li)) floatli = list(map(lambda x: float(x),li)) print(intli) print(floatli) &gt;&gt; [1, 4, 8] &gt;&gt; [1.0, 4.0, 8.6] </code></pre>
[ { "answer_id": 74665819, "author": "Lexpj", "author_id": 10229386, "author_profile": "https://Stackoverflow.com/users/10229386", "pm_score": 2, "selected": false, "text": "isdigit() True li = ['1', '4', '8.6']\nlst = [int(x) if x.isdigit() else float(x) for x in li]\nprint(lst)\n types = [type(i) for i in lst]\nprint(types)\n" }, { "answer_id": 74665939, "author": "Aivar Paalberg", "author_id": 8663760, "author_profile": "https://Stackoverflow.com/users/8663760", "pm_score": 0, "selected": false, "text": ">>> from ast import literal_eval\n>>> spam = ['1', '4', '8.6']\n>>> [literal_eval(item) for item in spam]\n[1, 4, 8.6]\n >>> '1²'.isdigit()\nTrue\n" }, { "answer_id": 74665943, "author": "Amir reza Riahi", "author_id": 12016688, "author_profile": "https://Stackoverflow.com/users/12016688", "pm_score": 0, "selected": false, "text": "ast.literal_eval from ast import literal_eval\n\nli = ['1', '4', '8.6']\nnumbers = list(map(literal_eval, li))\n str.isidigit True >>> '-3'.isdigit()\nFalse\n" }, { "answer_id": 74666093, "author": "gog", "author_id": 3494774, "author_profile": "https://Stackoverflow.com/users/3494774", "pm_score": 0, "selected": false, "text": "def to_float_or_int(s):\n n = float(s)\n return int(n) if n.is_integer() else n\n result = [to_float_or_int(s) for s in li]\n" }, { "answer_id": 74666124, "author": "Arifa Chan", "author_id": 19574157, "author_profile": "https://Stackoverflow.com/users/19574157", "pm_score": 0, "selected": false, "text": "map loads json from json import loads\nli = ['1', '4', '8.6']\nli = [*map(loads,li)]\nprint(li)\n\n# [1, 4, 8.6]\n eval() print(li:=[*map(eval,['1','4','8.6','-1','-2.3'])])\n\n# [1, 4, 8.6, -1, -2.3]\n json.loads() ast.literal_eval eval()" }, { "answer_id": 74666154, "author": "Sbagaria2710", "author_id": 10111454, "author_profile": "https://Stackoverflow.com/users/10111454", "pm_score": 0, "selected": false, "text": "string = \"123\"\nnumber = int(string)\n string = \"3.1415\"\nnumber = float(string)\n string = \"hello\"\ntry:\n number = int(string)\nexcept ValueError:\n print(\"The string cannot be converted to a number.\")\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20673588/" ]
74,665,796
<p>i want apply lambda to do multiplication which is condition type data float value like this</p> <p>0.412</p> <p>0.0036</p> <p>0.0467</p> <p>0.000678</p> <p>0.00000342</p> <p>expected output</p> <p>0.41</p> <p>0.36</p> <p>0.47</p> <p>0.68</p> <p>0.34</p>
[ { "answer_id": 74665972, "author": "abokey", "author_id": 16120011, "author_profile": "https://Stackoverflow.com/users/16120011", "pm_score": 1, "selected": false, "text": "replace astype round df[\"col\"] = df[\"col\"].replace(\"\\.0*\", \".\", regex=True).astype(float).round(2)\n print(df)\n\n col\n0 0.41\n1 0.36\n2 0.47\n3 0.68\n4 0.34\n" }, { "answer_id": 74666785, "author": "Immature trader", "author_id": 13387730, "author_profile": "https://Stackoverflow.com/users/13387730", "pm_score": 0, "selected": false, "text": "import re\nlambda_func = lambda x: re.sub(r'(\\.0*)', r'.', str(x))\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8321274/" ]
74,665,845
<p>When I saw the term &quot;Concurrent render&quot; or &quot;Concurrent features&quot; in React 18, it confused me. Because I know the browser handle tasks on a single main thread. How react render concurrently on a single thread ?</p> <p>Does react use event loop and task queue internally ?</p>
[ { "answer_id": 74665972, "author": "abokey", "author_id": 16120011, "author_profile": "https://Stackoverflow.com/users/16120011", "pm_score": 1, "selected": false, "text": "replace astype round df[\"col\"] = df[\"col\"].replace(\"\\.0*\", \".\", regex=True).astype(float).round(2)\n print(df)\n\n col\n0 0.41\n1 0.36\n2 0.47\n3 0.68\n4 0.34\n" }, { "answer_id": 74666785, "author": "Immature trader", "author_id": 13387730, "author_profile": "https://Stackoverflow.com/users/13387730", "pm_score": 0, "selected": false, "text": "import re\nlambda_func = lambda x: re.sub(r'(\\.0*)', r'.', str(x))\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15387782/" ]
74,665,887
<p>I am receiving various errors like this after I do</p> <blockquote> <p>ionic build --prod --release</p> </blockquote> <pre><code>src/app/pages/top-media/top-media.page.ts:18:16 18 templateUrl: './top-media.page.html', ~~~~~~~~~~~~~~~~~~~~~~~ Error occurs in the template of component TopMediaPage. Error: src/app/pages/top-media/top-media.page.html:106:36 - error TS2339: Property 'type' does not exist on type 'unknown'. </code></pre> <p>106 &lt;ng-container *ngIf=&quot;media?.type==='T'&quot;&gt;</p> <p>html</p> <pre><code> &lt;ion-row *ngFor=&quot;let media of topMedia | filterByType: mediaType | slice:1; let i = index&quot;&gt; &lt;ng-container *ngIf=&quot;media?.type==='T'&quot;&gt; {{media?.message | slice:0:2000}} &lt;/p&gt; </code></pre> <p>ts</p> <pre><code>topMedia:any =[]; constructor( ... ) { this.topMediaSet(); } topMediaSet(refresher?:any) { this.offset = 0; if (typeof refresher == 'undefined') { this.loading = true; } this.userData.topMedias(this.offset).pipe( map((data: any) =&gt; { if (data.success) { this.topMedia = data.topMedia; } if (typeof refresher != 'undefined') { refresher.target.complete(); } this.loading = false; }) ).subscribe() } </code></pre> <p>the properties of the topMedia array of objects is shown on the image and as you can see one of them has property message null</p> <p>[![enter image description here][1]][1]</p> <p>Thanks</p>
[ { "answer_id": 74665972, "author": "abokey", "author_id": 16120011, "author_profile": "https://Stackoverflow.com/users/16120011", "pm_score": 1, "selected": false, "text": "replace astype round df[\"col\"] = df[\"col\"].replace(\"\\.0*\", \".\", regex=True).astype(float).round(2)\n print(df)\n\n col\n0 0.41\n1 0.36\n2 0.47\n3 0.68\n4 0.34\n" }, { "answer_id": 74666785, "author": "Immature trader", "author_id": 13387730, "author_profile": "https://Stackoverflow.com/users/13387730", "pm_score": 0, "selected": false, "text": "import re\nlambda_func = lambda x: re.sub(r'(\\.0*)', r'.', str(x))\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20378337/" ]
74,665,888
<p>I have a table named &quot;table1&quot; and I'm splitting it based on a criterion, and then joining the split parts one by one in for loop. The following is a representation of what I am trying to do.</p> <p><a href="https://i.stack.imgur.com/UwqXX.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UwqXX.jpg" alt="enter image description here" /></a></p> <p>When I joined them, the joining time increased exponentially.</p> <pre><code>0.7423694133758545 join 0.4046192169189453 join 0.5775985717773438 join 5.664674758911133 join 1.0985417366027832 join 2.2664384841918945 join 3.833379030227661 join 12.762675762176514 join 44.14520192146301 join 124.86295890808105 join 389.46189188957214 </code></pre> <p>. Following are my parameters</p> <pre><code>spark = SparkSession.builder.appName(&quot;xyz&quot;).getOrCreate() sqlContext = HiveContext(spark) sqlContext.setConf(&quot;spark.sql.join.preferSortMergeJoin&quot;, &quot;true&quot;) sqlContext.setConf(&quot;spark.serializer&quot;,&quot;org.apache.spark.serializer.KryoSerializer&quot;) sqlContext.setConf(&quot;spark.sql.shuffle.partitions&quot;, &quot;48&quot;) </code></pre> <p>and</p> <pre><code>--executor-memory 16G --num-executors 8 --executor-cores 8 --driver-memory 32G </code></pre> <p>Source table</p> <p><a href="https://i.stack.imgur.com/PcFe1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PcFe1.png" alt="enter image description here" /></a></p> <p>Desired output table</p> <p><a href="https://i.stack.imgur.com/RiD2T.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RiD2T.png" alt="enter image description here" /></a></p> <p>In the join iteration, I also increased the partitions to 2000 and decreased it to 4, and cached the DF data frame by df.cached(), but nothing worked. I know I am doing something terribly wrong but I don't know what. Please can you guide me on how to correct this.</p> <p>I would really appreciate any help :)</p> <p>code:</p> <pre><code> df = spark.createDataFrame([], schema=SCHEMA) for i, column in enumerate(columns): df.cache() df_part = df_to_transpose.where(col('key') == column) df_part = df_part.withColumnRenamed(&quot;value&quot;, column) if (df_part.count() != 0 and df.count() != 0): df = df_part.join(broadcast(df), 'tuple') </code></pre>
[ { "answer_id": 74665972, "author": "abokey", "author_id": 16120011, "author_profile": "https://Stackoverflow.com/users/16120011", "pm_score": 1, "selected": false, "text": "replace astype round df[\"col\"] = df[\"col\"].replace(\"\\.0*\", \".\", regex=True).astype(float).round(2)\n print(df)\n\n col\n0 0.41\n1 0.36\n2 0.47\n3 0.68\n4 0.34\n" }, { "answer_id": 74666785, "author": "Immature trader", "author_id": 13387730, "author_profile": "https://Stackoverflow.com/users/13387730", "pm_score": 0, "selected": false, "text": "import re\nlambda_func = lambda x: re.sub(r'(\\.0*)', r'.', str(x))\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9178472/" ]
74,665,906
<p>I have created a <code>clamp</code> function to bound value in a given range. <em>(Almost every one of you know what a clamp function does)</em></p> <p>So this the function I created (using <code>TS</code>)</p> <pre class="lang-js prettyprint-override"><code>function clamp(value: number, min: number, max: number) { return Math.min(Math.max(value, min), max) } </code></pre> <p>but, there are some use cases where I want to get rid of converting all three <code>params</code> to <code>Number</code> type to pass it inside the function. I know I would have done something like this</p> <pre class="lang-js prettyprint-override"><code>function clamp(value: number, min: number, max: number) { return Math.min(Math.max(Number(value), Number(min)), Number(max)) } </code></pre> <p>converting every single <code>param</code> to <code>Number</code> type.</p> <blockquote> <p>I want to know if there is/are any other way/ways where I can just convert every <code>param</code> to <code>Number</code> type at once??</p> </blockquote>
[ { "answer_id": 74666023, "author": "pizzamanyes", "author_id": 20670513, "author_profile": "https://Stackoverflow.com/users/20670513", "pm_score": 0, "selected": false, "text": "function clamp(value: number, min: number, max: number) {\n // Use the '+' operator to convert all of the parameters to the 'Number' type\n return Math.min(Math.max(+value, +min), +max)\n}\n" }, { "answer_id": 74666030, "author": "KooiInc", "author_id": 58186, "author_profile": "https://Stackoverflow.com/users/58186", "pm_score": 3, "selected": true, "text": "Array.map Number function allNumbers(...values) {\n return values.map(Number).filter(v => !isNaN(v));\n}\n\nconsole.log(`${allNumbers(1,`26`, 42)}`);\nconsole.log(`${allNumbers(...[...`123`])}`);\nconsole.log(`${allNumbers(`20`, `+`, `22`, `=`, 42)}`);\nconsole.log(`${allNumbers(...(`20+22=42`.split(/[+=]/)))}`); function clamp(...values: Array<number|string>) {\n const numbers: (number|Nan)[] = values.map(Number);\n if (numbers.filter(v => !isNaN(v)).length === 3) {\n const [value, min, max] = numbers;\n return Math.min(Math.max(value, min), max);\n }\n return `insufficient argument(s)`;\n}\n\nconsole.log(clamp(42));\nconsole.log(clamp(1,3,`42`));" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15748278/" ]
74,665,909
<ul> <li>Joining 2 tables (orders, addresses)</li> <li>Orders contains columns delivery_address_id (contains NULL values) and invoice_address_id (does NOT contain NULL values)</li> <li>Addresses contains id column (does NOT contain NULL values)</li> </ul> <p>Primarily, the LEFT JOIN must be performed on orders.delivery_address_id. However, in the case when its value is NULL in the row, perform LEFT JOIN on orders.invoice_address_id.</p> <p>How do I deal with this?</p> <p>I tried the operator <code>OR</code> but the result was not correct. I was also thinking about a CASE WHEN statement. My expectations are to get the LEFT JOIN working.</p>
[ { "answer_id": 74665979, "author": "forpas", "author_id": 10498828, "author_profile": "https://Stackoverflow.com/users/10498828", "pm_score": 2, "selected": false, "text": "OR ON SELECT ....\nFROM Orders o LEFT JOIN Addresses a\nON a.id = o.delivery_address_id \nOR (o.delivery_address_id IS NULL AND a.id = o.invoice_address_id);\n COALESCE() SELECT ....\nFROM Orders o LEFT JOIN Addresses a\nON a.id = COALESCE(o.delivery_address_id, o.invoice_address_id);\n" }, { "answer_id": 74666039, "author": "Paddy Alton", "author_id": 9044370, "author_profile": "https://Stackoverflow.com/users/9044370", "pm_score": 1, "selected": false, "text": "delivery_address_id NULL invoice_address_id COALESCE(delivery_address_id, invoice_address_id) NULL SELECT\n orders.some_field,\n addresses.address\n FROM\n orders\n LEFT JOIN\n addresses\n ON\n COALESCE(orders.delivery_address_id, orders.invoice_address_id) = addresses.id \n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14830125/" ]
74,665,921
<p>On input consider db-dump(from dbeaver), having this format:</p> <pre><code>{ &quot;select&quot;: [ {&lt;row1&gt;}, {&lt;row2&gt;} ], &quot;select&quot;: {} } </code></pre> <p>say that I'm debugging bigger script, and just want to see first few rows, from first statement. How to do that effectively in rather huge file?</p> <p>Template:</p> <pre><code>jq 'keys[0] as $k|.[$k]|limit(1;.[])' dump </code></pre> <p>isn't really great, as it need to fetch all keys first. Template</p> <pre><code>jq '.[0]|limit(1;.[])' dump </code></pre> <p>sadly does not seem to be valid one, and</p> <pre><code>jq 'first(.[])|limit(1;.[])' dump </code></pre> <p>does not seem to have any performance benefit.</p> <p>What would be the best way to just access first field in object without actually testing it's name or caring for rest of fields?</p>
[ { "answer_id": 74665979, "author": "forpas", "author_id": 10498828, "author_profile": "https://Stackoverflow.com/users/10498828", "pm_score": 2, "selected": false, "text": "OR ON SELECT ....\nFROM Orders o LEFT JOIN Addresses a\nON a.id = o.delivery_address_id \nOR (o.delivery_address_id IS NULL AND a.id = o.invoice_address_id);\n COALESCE() SELECT ....\nFROM Orders o LEFT JOIN Addresses a\nON a.id = COALESCE(o.delivery_address_id, o.invoice_address_id);\n" }, { "answer_id": 74666039, "author": "Paddy Alton", "author_id": 9044370, "author_profile": "https://Stackoverflow.com/users/9044370", "pm_score": 1, "selected": false, "text": "delivery_address_id NULL invoice_address_id COALESCE(delivery_address_id, invoice_address_id) NULL SELECT\n orders.some_field,\n addresses.address\n FROM\n orders\n LEFT JOIN\n addresses\n ON\n COALESCE(orders.delivery_address_id, orders.invoice_address_id) = addresses.id \n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1534084/" ]
74,665,959
<p>So i am going to have 4 questions and each question is worth 25 points and full point is 100. I am not sure how to count the answer base on my code and form score code. Thank you for helping me out. (I put 1 question to make the code shorter but in my VS there are 4 questions)</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MCQuiz { class Program { static void Main(string[] args) { string answer; Console.WriteLine(&quot;Q1-Every Statement in C# language must terminate with: &quot;); Console.WriteLine(&quot; \t a. ; &quot;); Console.WriteLine(&quot; \t b. , &quot;); Console.WriteLine(&quot; \t c. . &quot;); Console.WriteLine(&quot; \t d. ? &quot;); Console.WriteLine(); Console.Write(&quot;Enter the letter (a, b, c, d) for correct Answer: &quot;) answer = Console.ReadLine(); if (answer == &quot;a&quot;) { Console.WriteLine(&quot;Your Answer '{0}' is Correct.&quot;, answer); } else { Console.WriteLine(&quot;Your Answer '{0}' is Wrong.&quot;, answer); } Console.WriteLine(); Console.WriteLine(&quot;****************************************&quot;); } } } </code></pre>
[ { "answer_id": 74665991, "author": "ˈvɔlə", "author_id": 1865613, "author_profile": "https://Stackoverflow.com/users/1865613", "pm_score": 1, "selected": false, "text": "+= totalScore = totalScore + 25 class Program\n{\n static void Main(string[] args)\n {\n int totalScore = 0; // initiate variable\n string answer;\n\n Console.WriteLine(\"Q1-Every Statement in C# language must terminate with: \");\n Console.WriteLine(\" \\t a. ; \");\n Console.WriteLine(\" \\t b. , \");\n Console.WriteLine(\" \\t c. . \");\n Console.WriteLine(\" \\t d. ? \");\n Console.WriteLine();\n\n\n Console.Write(\"Enter the letter (a, b, c, d) for correct Answer: \")\n\n answer = Console.ReadLine();\n\n if (answer == \"a\")\n {\n totalScore += 25; // add score\n Console.WriteLine(\"Your Answer '{0}' is Correct.\", answer);\n }\n else\n {\n Console.WriteLine(\"Your Answer '{0}' is Wrong.\", answer);\n }\n Console.WriteLine();\n Console.WriteLine(\"****************************************\");\n Console.WriteLine($\"You scored {totalScore} points\"); // output result\n }\n}\n" }, { "answer_id": 74668479, "author": "Kanhaya Tyagi", "author_id": 14945515, "author_profile": "https://Stackoverflow.com/users/14945515", "pm_score": -1, "selected": false, "text": " using System;\n using System.Collections.Generic;\n using System.Linq;\n using System.Text;\n using System.Threading.Tasks;\n \n namespace MCQuiz\n {\n class Program\n {\n static void Main(string[] args)\n {\n \n \n string answer;\n string totalScore = 0;\n \n Console.WriteLine(\"Q1-Every Statement in C# language must terminate with: \");\n Console.WriteLine(\" \\t a. ; \");\n Console.WriteLine(\" \\t b. , \");\n Console.WriteLine(\" \\t c. . \");\n Console.WriteLine(\" \\t d. ? \");\n Console.WriteLine();\n \n \n Console.Write(\"Enter the letter (a, b, c, d) for correct Answer: \")\n \n answer = Console.ReadKey();\n \n if (answer == \"a\")\n {\n totalScore += 25;\n Console.WriteLine(\"Your Answer '{0}' is Correct.\", answer);\n }\n else\n {\n Console.WriteLine(\"Your Answer '{0}' is Wrong.\", answer);\n }\n Console.WriteLine();\n Console.WriteLine(\"****************************************\");\n \n }\n }\n }\n\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74665959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20598174/" ]
74,666,005
<p>I need to figure out what beers from table 'Beer' were not ordered by top 3 buyers from table 'Buyers'. Beer.BeerId is foreign key in Buyers.BeerId. Other important columns in 'Buyers' are: BuyId, PubId, StoreId and Quantity</p> <p>dbo.Beer</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>BeerId</th> </tr> </thead> <tbody> <tr> <td>1</td> </tr> <tr> <td>2</td> </tr> <tr> <td>3</td> </tr> <tr> <td>4</td> </tr> <tr> <td>5</td> </tr> </tbody> </table> </div> <p>dbo.Buyers</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>BuyId</th> <th>PubId</th> <th>StoreId</th> <th>BeerId</th> <th>Quantity</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>1</td> <td>NULL</td> <td>1</td> <td>30</td> </tr> <tr> <td>2</td> <td>NULL</td> <td>1</td> <td>2</td> <td>40</td> </tr> <tr> <td>3</td> <td>2</td> <td>NULL</td> <td>3</td> <td>50</td> </tr> <tr> <td>4</td> <td>NULL</td> <td>2</td> <td>4</td> <td>10</td> </tr> </tbody> </table> </div> <p>I tried doing this query but it gives me no results.</p> <pre><code>SELECT Be.BeerId FROM Beer be left outer join Buyer bu ON be.BeerId=bu.BeerId WHERE not exists ( SELECT TOP(3) BuyId, bu.BeerId, SUM(Quantity) as TotalOrdered FROM Buyer bu GROUP BY BuyId, bu.BeerId ORDER BY SUM(Quantity) DESC) </code></pre> <p>What I would expect to see is that from the top 3 results, beers that are not ordered are BeerId=4 and BeerId=5</p>
[ { "answer_id": 74665991, "author": "ˈvɔlə", "author_id": 1865613, "author_profile": "https://Stackoverflow.com/users/1865613", "pm_score": 1, "selected": false, "text": "+= totalScore = totalScore + 25 class Program\n{\n static void Main(string[] args)\n {\n int totalScore = 0; // initiate variable\n string answer;\n\n Console.WriteLine(\"Q1-Every Statement in C# language must terminate with: \");\n Console.WriteLine(\" \\t a. ; \");\n Console.WriteLine(\" \\t b. , \");\n Console.WriteLine(\" \\t c. . \");\n Console.WriteLine(\" \\t d. ? \");\n Console.WriteLine();\n\n\n Console.Write(\"Enter the letter (a, b, c, d) for correct Answer: \")\n\n answer = Console.ReadLine();\n\n if (answer == \"a\")\n {\n totalScore += 25; // add score\n Console.WriteLine(\"Your Answer '{0}' is Correct.\", answer);\n }\n else\n {\n Console.WriteLine(\"Your Answer '{0}' is Wrong.\", answer);\n }\n Console.WriteLine();\n Console.WriteLine(\"****************************************\");\n Console.WriteLine($\"You scored {totalScore} points\"); // output result\n }\n}\n" }, { "answer_id": 74668479, "author": "Kanhaya Tyagi", "author_id": 14945515, "author_profile": "https://Stackoverflow.com/users/14945515", "pm_score": -1, "selected": false, "text": " using System;\n using System.Collections.Generic;\n using System.Linq;\n using System.Text;\n using System.Threading.Tasks;\n \n namespace MCQuiz\n {\n class Program\n {\n static void Main(string[] args)\n {\n \n \n string answer;\n string totalScore = 0;\n \n Console.WriteLine(\"Q1-Every Statement in C# language must terminate with: \");\n Console.WriteLine(\" \\t a. ; \");\n Console.WriteLine(\" \\t b. , \");\n Console.WriteLine(\" \\t c. . \");\n Console.WriteLine(\" \\t d. ? \");\n Console.WriteLine();\n \n \n Console.Write(\"Enter the letter (a, b, c, d) for correct Answer: \")\n \n answer = Console.ReadKey();\n \n if (answer == \"a\")\n {\n totalScore += 25;\n Console.WriteLine(\"Your Answer '{0}' is Correct.\", answer);\n }\n else\n {\n Console.WriteLine(\"Your Answer '{0}' is Wrong.\", answer);\n }\n Console.WriteLine();\n Console.WriteLine(\"****************************************\");\n \n }\n }\n }\n\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74666005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20649041/" ]
74,666,017
<p>Let's say I have a dictionary called my_dic:</p> <pre><code>my_dict = {'a': {'spam': {'foo': None, 'bar': None, 'baz': None},'eggs': None}, 'b': {'ham': None}} </code></pre> <p>Then if I input <code>spam</code>, it should return <code>a</code>, and if I input <code>bar</code> it should return <code>spam</code>. If I input <code>b</code>, it should return <code>None</code>. Basically getting the parent of the dictionary.</p> <p>How would I go about doing this?</p>
[ { "answer_id": 74666140, "author": "chivalrous-nerd", "author_id": 7347835, "author_profile": "https://Stackoverflow.com/users/7347835", "pm_score": -1, "selected": false, "text": ".get() my_dict = {'a': {'spam': {'foo': None, 'bar': None, 'baz': None},'eggs'}, 'b': {'ham'}}\n\n# Check if 'spam' is a key in my_dict and get its value\nif 'spam' in my_dict:\n print(my_dict['spam']) # Output: {'foo': None, 'bar': None, 'baz': None}\nelse:\n print('Key not found')\n\n# Check if 'bar' is a key in my_dict and get its value\nif 'bar' in my_dict:\n print(my_dict['bar']) # Output: Key not found\nelse:\n print('Key not found')\n\n# Use .get() to check if 'b' is a key in my_dict and get its value\nvalue = my_dict.get('b')\nif value is not None:\n print(value) # Output: {'ham'}\nelse:\n print('Key not found')\n" }, { "answer_id": 74666315, "author": "deceze", "author_id": 476, "author_profile": "https://Stackoverflow.com/users/476", "pm_score": 1, "selected": true, "text": "needle in v needle in v my_dict = {'a': {'spam': {'foo': None, 'bar': None, 'baz': None},'eggs': None}, 'b': {'ham': None}}\n\ndef get_parent_key(d: dict, needle: str):\n for k, v in d.items():\n if isinstance(v, dict):\n if needle in v:\n return k\n \n if found := get_parent_key(v, needle):\n return found\n \nprint(get_parent_key(my_dict, 'bar'))\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74666017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18421761/" ]
74,666,064
<p>hi I have multiple items with different categories. I want to display all item with its Category name as a title at header. My code displaying each item but category Title repeats with each item. I want Category title only one time at the top and then its items list. MY Code is this</p> <pre class="lang-js prettyprint-override"><code>{ formsList.map((item, index,temp=0) =&gt; { if(temp!==item.cat_id) { temp = item?.cat_id; return ( &lt;div className=&quot;custom-control custom-radio mb-3&quot;&gt; &lt;div className=&quot;form-control-label&quot;&gt; {item.category_title}&lt;/div&gt; &lt;input className=&quot;custom-control-input&quot; id= {item.id} name= {item.cat_id} type=&quot;radio&quot; /&gt; &lt;label className=&quot;custom-control-label&quot; htmlFor={item.id}&gt; {item.form_title} {temp} &lt;/label&gt; &lt;/div&gt; ) } return ( &lt;div className=&quot;custom-control custom-radio mb-3&quot;&gt; &lt;input className=&quot;custom-control-input&quot; id= {item.id} name= {item.cat_id} type=&quot;radio&quot; /&gt; &lt;label className=&quot;custom-control-label&quot; htmlFor={item.id}&gt; {item.form_title} &lt;/label&gt; &lt;/div&gt; ) }) } </code></pre> <p>My Json array is like this.</p> <pre><code> {&quot;forms&quot;: [ {&quot;id&quot;:1,&quot;category_title&quot;:&quot;Individual Tax Return&quot;,&quot;cat_id&quot;:1, &quot;form_title&quot;:&quot;Single}, {&quot;id&quot;:2,&quot;category_title&quot;:&quot;Individual Tax Return&quot;,&quot;cat_id&quot;:1, &quot;form_title&quot;:&quot;Married Filing Separately&quot;}, {&quot;id&quot;:3,&quot;category_title&quot;:&quot;Business Type&quot;, &quot;cat_id&quot;:2, &quot;form_title&quot;:&quot;SoleProprietorships&quot;}, {&quot;id&quot;:4,&quot;category_title&quot;:&quot;Business Type&quot;,&quot;cat_id&quot;:2, &quot;form_title&quot;:&quot; Partnership&quot;} ] } </code></pre> <p>I want to display this one like as below //////////////////</p> <pre><code> Individual Tax Return Single Married Filing Separately Business Type SoleProprietorships Partnership </code></pre> <p>///////////////////////// Please check and help with thanks</p>
[ { "answer_id": 74666140, "author": "chivalrous-nerd", "author_id": 7347835, "author_profile": "https://Stackoverflow.com/users/7347835", "pm_score": -1, "selected": false, "text": ".get() my_dict = {'a': {'spam': {'foo': None, 'bar': None, 'baz': None},'eggs'}, 'b': {'ham'}}\n\n# Check if 'spam' is a key in my_dict and get its value\nif 'spam' in my_dict:\n print(my_dict['spam']) # Output: {'foo': None, 'bar': None, 'baz': None}\nelse:\n print('Key not found')\n\n# Check if 'bar' is a key in my_dict and get its value\nif 'bar' in my_dict:\n print(my_dict['bar']) # Output: Key not found\nelse:\n print('Key not found')\n\n# Use .get() to check if 'b' is a key in my_dict and get its value\nvalue = my_dict.get('b')\nif value is not None:\n print(value) # Output: {'ham'}\nelse:\n print('Key not found')\n" }, { "answer_id": 74666315, "author": "deceze", "author_id": 476, "author_profile": "https://Stackoverflow.com/users/476", "pm_score": 1, "selected": true, "text": "needle in v needle in v my_dict = {'a': {'spam': {'foo': None, 'bar': None, 'baz': None},'eggs': None}, 'b': {'ham': None}}\n\ndef get_parent_key(d: dict, needle: str):\n for k, v in d.items():\n if isinstance(v, dict):\n if needle in v:\n return k\n \n if found := get_parent_key(v, needle):\n return found\n \nprint(get_parent_key(my_dict, 'bar'))\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74666064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11185806/" ]
74,666,114
<p>Each time I start the program, the message &quot;This message 2&quot; is displayed in a random order relative to other messages.</p> <pre><code>#include &lt;stdio.h&gt; int main() { fprintf(stdout,&quot;This is message 1\n&quot;); fprintf(stderr,&quot;This is message 2\n&quot;); fprintf(stdout,&quot;This is message 3\n&quot;); return 0; } </code></pre> <p>Examples:</p> <p><a href="https://i.stack.imgur.com/VX6rD.png" rel="nofollow noreferrer">Example 1</a></p> <p><a href="https://i.stack.imgur.com/wOlNJ.png" rel="nofollow noreferrer">Example 2</a></p> <p>Why is this happening and how to fix it?</p>
[ { "answer_id": 74666429, "author": "Eric Postpischil", "author_id": 298225, "author_profile": "https://Stackoverflow.com/users/298225", "pm_score": 2, "selected": false, "text": "\"This is message 2\\n\" fflush(stdout) setvbuf(stdout, 0, _IOLBF, 0); // Must be before stdout is used.\n setvbuf" }, { "answer_id": 74667453, "author": "bolov", "author_id": 2805305, "author_profile": "https://Stackoverflow.com/users/2805305", "pm_score": 0, "selected": false, "text": "stdout stderr stdout stderr" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74666114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20673562/" ]
74,666,126
<p>I am trying to dockerize a PHP laravel app. I am using a PHP and a composer image to achieve this. However, when I run <em>composer install</em>, I get all my packages installed but then run into this error:</p> <p><code>/app/vendor does not exist and could not be created.</code></p> <p>I want composer to create the /vendor directory! Could this be a permission issue?</p> <p>Here is my Dockerfile:</p> <pre><code>FROM php:7.4.3-cli # Install system dependencies RUN apt-get update &amp;&amp; apt-get install -y \ git \ curl \ libpng-dev \ libonig-dev \ libxml2-dev \ zip \ unzip # Clear cache RUN apt-get clean &amp;&amp; rm -rf /var/lib/apt/lists/* # Install PHP extensions RUN docker-php-ext-install pdo_mysql mbstring exif pcntl bcmath gd COPY --from=composer:2.4.4 /usr/bin/composer /usr/local/bin/composer # Set working directory WORKDIR /app COPY . . # Add a new user &quot;john&quot; with user id 8877 RUN useradd -u 8877 john # Change to non-root privilege USER john RUN composer install </code></pre> <p>I created a user with an arbitrary ID since it's a bad practice to run <em>composer install</em> as root security-wise.</p>
[ { "answer_id": 74666430, "author": "J0ker98", "author_id": 3218962, "author_profile": "https://Stackoverflow.com/users/3218962", "pm_score": 2, "selected": false, "text": "# Create the vendor directory\nRUN mkdir -p /app/vendor\n\n# Give the john user permission to write to the vendor directory\nRUN chown john:john /app/vendor\n --no-plugins --no-scripts composer install # Run composer install as the john user, without running any scripts or plugins\nRUN composer install --no-plugins --no-scripts\n" }, { "answer_id": 74669586, "author": "RedDoumham", "author_id": 5637429, "author_profile": "https://Stackoverflow.com/users/5637429", "pm_score": 0, "selected": false, "text": "FROM php:7.4.3-cli\n\n# Install system dependencies\nRUN apt-get update && apt-get install -y \\\n git \\\n curl \\\n libpng-dev \\\n libonig-dev \\\n libxml2-dev \\\n zip \\\n unzip\n\n# Clear cache\nRUN apt-get clean && rm -rf /var/lib/apt/lists/*\n\n# Install PHP extensions\nRUN docker-php-ext-install pdo_mysql mbstring exif pcntl bcmath gd\n\nCOPY --from=composer:2.4.4 /usr/bin/composer /usr/local/bin/composer\n\n# Add a new user \"john\" with user id 8877\nRUN useradd -u 8877 john\n\n# Set working directory\nWORKDIR /app\nCOPY . . \n\nRUN chmod -R 775 /app\nRUN chown -R john:john /app\n\n# Change to non-root privilege\nUSER john\n\nRUN composer install --no-scripts --no-plugins\n" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74666126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5637429/" ]
74,666,142
<p>I need to manipulate drawing of a SVG, so I have attribute &quot;d&quot; values like this:</p> <p><code>d = &quot;M561.5402,268.917 C635.622,268.917 304.476,565.985 379.298,565.985&quot;</code></p> <p>What I want is to &quot;purify&quot; all the values (to strip the chars from them), to calculate them (for the sake of simplicity, let's say to add 100 to each value), to deconstruct the string, calculate the values inside and then concatenate it all back together so the final result is something like this:</p> <p><code>d = &quot;M661.5402,368.917 C735.622,368.917 404.476,665.985 479.298,665.985&quot;</code></p> <p>Have in mind that:</p> <ul> <li>some values can start with a character</li> <li>values are delimited by comma</li> <li>some values within comma delimiter can be delimited by space</li> <li>values are decimal</li> </ul> <p>This is my try:</p> <pre><code> let arr1 = d.split(','); arr1 = arr1.map(element =&gt; { let arr2 = element.split(' '); if (arr2.length &gt; 1) { arr2 = arr2.map(el =&gt; { let startsWithChar = el.match(/\D+/); if (startsWithChar) { el = el.replace(/\D/g,''); } el = parseFloat(el) + 100; if (startsWithChar) { el = startsWithChar[0] + el; } }) } else { let startsWithChar = element.match(/\D+/); if (startsWithChar) { element = element.replace(/\D/g,''); } element = parseFloat(element) + 100; if (startsWithChar) { element = startsWithChar[0] + element; } } }); d = arr1.join(','); </code></pre> <p>I tried with regex <code>replace(/\D/g,'')</code> but then it strips the decimal dot from the value also, so I think my solution is full of holes.</p> <p>Maybe another solution would be to somehow modify directly each of path values/commands, I'm opened to that solution also, but I don't know how.</p>
[ { "answer_id": 74666182, "author": "Andrew Parks", "author_id": 5898421, "author_profile": "https://Stackoverflow.com/users/5898421", "pm_score": 3, "selected": true, "text": "const s = 'M561.5402,268.917 C635.622,268.917 304.476,565.985 379.298,565.985'\n\nconsole.log(s.replaceAll(/[\\d.]+/g, m=>+m+100))" }, { "answer_id": 74666348, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 1, "selected": false, "text": "([ ,]?\\b[A-Z]?)(\\d+\\.\\d+)\\b\n ( [ ,]?\\b[A-Z]? ) ( \\d+\\.\\d+ ) \\b const d = \"M561.5402,268.917 C635.622,268.917 304.476,565.985 379.298,565.985\";\nconst regex = /([ ,]?\\b[A-Z]?)(\\d+\\.\\d+)\\b/g;\nconst res = Array.from(\n d.matchAll(regex), m => m[1] + (+m[2] + 100)\n).join('');\n\nconsole.log(res);" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74666142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1738094/" ]
74,666,151
<p>Main list:</p> <pre><code>data = [ [&quot;629-2, text1, 12&quot;], [&quot;629-2, text2, 12&quot;], [&quot;407-3, text9, 6&quot;], [&quot;407-3, text4, 6&quot;], [&quot;000-5, text7, 0&quot;], [&quot;000-5, text6, 0&quot;], ] </code></pre> <p>I want to get a list comprised of unique lists like so:</p> <pre><code>data_unique = [ [&quot;629-2, text1, 12&quot;], [&quot;407-3, text9, 6&quot;], [&quot;000-5, text6, 0&quot;], ] </code></pre> <p>I've tried using <code>numpy.unique</code> but I need to pare it down further as I need the list to be populated by lists containing a single unique version of the numerical designator in the beginning of the string, ie. 629-2...</p> <p>I've also tried using <code>chain</code> from <code>itertools</code> like this:</p> <pre><code>def get_unique(data): return list(set(chain(*data))) </code></pre> <p>But that only got me as far as <code>numpy.unique</code>.</p> <p>Thanks in advance.</p>
[ { "answer_id": 74666208, "author": "a5zima", "author_id": 14034634, "author_profile": "https://Stackoverflow.com/users/14034634", "pm_score": 0, "selected": false, "text": "# Convert the list of lists to a set\ndata_set = set(tuple(x) for x in data)\n\n# Convert the set back to a list\ndata_unique = [list(x) for x in data_set]\n" }, { "answer_id": 74666257, "author": "Punit Choudhary", "author_id": 13527252, "author_profile": "https://Stackoverflow.com/users/13527252", "pm_score": 0, "selected": false, "text": "def get_unique(lst):\n if not lst:\n return []\n if lst[0] in lst[1:]:\n return get_unique(lst[1:])\n else:\n return [lst[0]] + get_unique(lst[1:])\n\ndata = [\n[\"629-2, text1, 12\"],\n[\"629-2, text2, 12\"],\n[\"407-3, text9, 6\"],\n[\"407-3, text4, 6\"],\n[\"000-5, text7, 0\"],\n[\"000-5, text6, 0\"],\n]\nprint(get_unique(data))\n" }, { "answer_id": 74666343, "author": "DarrylG", "author_id": 3066077, "author_profile": "https://Stackoverflow.com/users/3066077", "pm_score": 3, "selected": true, "text": "from itertools import groupby\n\ndef get_unique(data):\n def designated_version(item):\n return item[0].split(',')[0]\n\n return [list(v)[0] \n for _, v in groupby(sorted(data, \n key = designated_version),\n designated_version)\n ]\n\n \n print(get_unique(data))\n# Output\n[['629-2, text1, 12'], ['407-3, text9, 6'], ['000-5, text7, 0']]\n lambda item: item[0].split(',')[0] list(v)[0]" } ]
2022/12/03
[ "https://Stackoverflow.com/questions/74666151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11468748/" ]