qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,608,937
|
<p>So I come across this simple lines of code from a tutorial on YouTube. It's about recursion.</p>
<pre><code>public class whatever{
public static void main (string[] args){
factorial(7);
}
private static int factorial(int num){
if(num<1) return 1;
return num * factorial(num -1);
}
}
</code></pre>
<p>Wouldn't it run forever because once the num reaches 0, it will return 1, then it will be -1, still return 1, then -2, return 1?
please correct me.</p>
<p>I know I am probably wrong logically so please correct me.</p>
|
[
{
"answer_id": 74608997,
"author": "Dropout",
"author_id": 1964272,
"author_profile": "https://Stackoverflow.com/users/1964272",
"pm_score": 1,
"selected": false,
"text": "factorial(0) 1 f(7) = n * f(6)\nn * f(6) = n * n-1 * f(5)\n .....\n f(7) = n * n-1 * n-2 * ... * n-6 + 1\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19242261/"
] |
74,608,944
|
<p>I have a dataframe as follows:</p>
<pre><code>s = df.head().to_dict()
print(s)
{'BoP transfers': {1998: 12.346282212735618,
1999: 19.06438060024298,
2000: 18.24888031473687,
2001: 24.860019912667006,
2002: 32.38242225822908},
'Current balance': {1998: -6.7953,
1999: -2.9895,
2000: -3.9694,
2001: 1.1716,
2002: 5.7433},
'Domestic demand': {1998: 106.8610389799729,
1999: 104.70302507466538,
2000: 104.59254229534136,
2001: 103.83532232336977,
2002: 102.81709401489702},
'Effective exchange rate': {1998: 88.134,
1999: 95.6425,
2000: 99.927725,
2001: 101.92745,
2002: 107.85565},
'RoR (foreign liabilities)': {1998: 0.0433,
1999: 0.0437,
2000: 0.0542,
2001: 0.0539,
2002: 0.0474},
'Gross foreign assets': {1998: 19.720897432405103,
1999: 22.66200738564236,
2000: 25.18270679890144,
2001: 30.394226651732836,
2002: 37.26477320359688},
'Gross domestic income': {1998: 104.9037939043707,
1999: 103.15361867816479,
2000: 103.06777792080423,
2001: 102.85886528974339,
2002: 102.28518242008846},
'Gross foreign liabilities': {1998: 60.59784839338306,
1999: 61.03308220978983,
2000: 64.01438055825233,
2001: 67.07798172469921,
2002: 70.16108592109364},
'Inflation rate': {1998: 52.6613,
1999: 19.3349,
2000: 16.0798,
2001: 15.076,
2002: 17.236},
'Credit': {1998: 0.20269913592846378,
1999: 0.2154280880177353,
2000: 0.282948948505006,
2001: 0.3954812893893278,
2002: 0.3578263032373988}}
</code></pre>
<p>which can be converted back to its original form using:</p>
<pre><code>df = pd.DataFrame.from_dict(s)
</code></pre>
<p>Suppose, I want to move the column named "Gross foreign liabilities" to the first column. I know this can be done by reindexing. However, in my case the dataframe has 100 columns. How can I move say a specific column the very beginning? I read about pandas pop() method, but in my framework I get an error.</p>
|
[
{
"answer_id": 74608960,
"author": "Jason Baker",
"author_id": 3249641,
"author_profile": "https://Stackoverflow.com/users/3249641",
"pm_score": 1,
"selected": false,
"text": "columns = df.columns.tolist()\ncolumns.insert(0, columns.pop(columns.index(\"Gross foreign liabilities\")))\ndf = df.reindex(columns=columns)\n col = [\"Gross foreign liabilities\"]\ndf = df[col + [x for x in df.columns if x not in col]]\n"
},
{
"answer_id": 74608970,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 1,
"selected": true,
"text": "pop insert name = 'Gross foreign liabilities'\ndf.insert(0, name, df.pop(name))\n def move_first(df, name):\n df.insert(0, name, df.pop(name))\n\nmove_first(df, 'Gross foreign liabilities')\n Gross foreign liabilities BoP transfers Current balance \\\n1998 60.597848 12.346282 -6.7953 \n1999 61.033082 19.064381 -2.9895 \n2000 64.014381 18.248880 -3.9694 \n2001 67.077982 24.860020 1.1716 \n2002 70.161086 32.382422 5.7433 \n\n Domestic demand Effective exchange rate RoR (foreign liabilities) \\\n1998 106.861039 88.134000 0.0433 \n1999 104.703025 95.642500 0.0437 \n2000 104.592542 99.927725 0.0542 \n2001 103.835322 101.927450 0.0539 \n2002 102.817094 107.855650 0.0474 \n\n Gross foreign assets Gross domestic income Inflation rate Credit \n1998 19.720897 104.903794 52.6613 0.202699 \n1999 22.662007 103.153619 19.3349 0.215428 \n2000 25.182707 103.067778 16.0798 0.282949 \n2001 30.394227 102.858865 15.0760 0.395481 \n2002 37.264773 102.285182 17.2360 0.357826 \n"
},
{
"answer_id": 74608983,
"author": "Panda Kim",
"author_id": 20430449,
"author_profile": "https://Stackoverflow.com/users/20430449",
"pm_score": 0,
"selected": false,
"text": "data = {'col1': {0: 0, 1: 2}, 'col2': {0: 1, 1: 3}, 'col3': {0: 2, 1: 4}}\ndf = pd.DataFrame(data)\n df col1 col2 col3\n0 0 1 2\n1 2 3 4\n df.insert(0, 'col3', df.pop('col3'))\n df col3 col1 col2\n0 2 0 1\n1 4 2 3\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13609298/"
] |
74,608,957
|
<p>My problem should be a variant of N queens problem:</p>
<p>Is there an algorithm to print all ways to place N queens in a k*k chessboard?</p>
<p>I have tried to modify the DFS method used in the N-queens problem like the following but soon realized that I could only search the first "queen_number" of rows in the chessboard.</p>
<pre><code> def dfs(self, n, queen, queen_number, ret):
if len(queen) == queen_number:
ret.append(queen[:])
return
for i in range(n):
if i in queen:
continue
flag = False
for j, idx in enumerate(queen):
if abs(len(queen) - j) == abs(idx - i):
flag = True
break
if flag:
continue
queen.append(i)
self.dfs(n, queen, ret)
queen.pop()
</code></pre>
<p>If there is a better way to accomplish this task, I am also interested to learn it.</p>
|
[
{
"answer_id": 74610912,
"author": "scr",
"author_id": 18781246,
"author_profile": "https://Stackoverflow.com/users/18781246",
"pm_score": 0,
"selected": false,
"text": "from typing import Dict, List, Callable, Optional\n\n\ndef create_k_by_k_board(k: int) -> Dict[int, bool]:\n # True means the spot is available, False means it has a queen and None means it is checked by a Queen\n if k <= 0:\n raise ValueError(\"k must be higher than 0\")\n return {i: True for i in range(1, k**2+1)}\n\n\ndef check_position(conditions: List[Callable], position: int) -> bool:\n # Checks if any function returns True\n for func in conditions:\n if func(position):\n return True\n return False\n\n\ndef get_all_checked_positions(queen_location: int, board_size: int) -> List[int]:\n from math import sqrt\n row_len = int(sqrt(board_size))\n conditions = [\n # Horizontal check\n lambda x: ((x - 1) // row_len) == ((queen_location - 1) // row_len),\n # Vertical check\n lambda x: (x % row_len) == (queen_location % row_len),\n # Right diagonal check\n lambda x: (x % (row_len + 1)) == (queen_location % (row_len + 1)),\n # Left diagonal check\n lambda x: (x % (row_len - 1)) == (queen_location % (row_len - 1)),\n ]\n return [\n position for position in range(1, board_size + 1)\n if position != queen_location\n and check_position(conditions, position)\n ]\n\n\ndef place_queen_on_board(board: Dict[int, Optional[bool]], position: int) -> Dict[int, Optional[bool]]:\n # We don't want to edit the board in place because we may need to go back to it\n new_board = board.copy()\n if new_board[position] is True:\n # Place a new queen\n new_board[position] = False\n for checked_position in get_all_checked_positions(position, len(board)):\n # Set the location as checked (no risk of erasing queens)\n new_board[checked_position] = None\n return new_board\n else:\n raise ValueError(f\"Tried to add queen to position {position} in board {board}\")\n\n\ndef get_all_queen_configurations(numb_queens: int, row_length: int) -> List[Dict[int, Optional[bool]]]:\n board = create_k_by_k_board(row_length)\n\n def recursive_queen_search(curr_round: int, curr_board: Dict[int, Optional[bool]]) -> List[Dict[int, Optional[bool]]]:\n successful_boards = []\n available_spots = [position for position, is_free in curr_board.items() if is_free is True]\n for spot in available_spots:\n new_board = place_queen_on_board(curr_board, spot)\n if curr_round < numb_queens:\n successful_boards.extend(\n recursive_queen_search(curr_round+1, new_board)\n )\n else:\n successful_boards.append(new_board)\n return successful_boards\n\n success_boards_with_duplicates = recursive_queen_search(1, board)\n success_boards = []\n for success_board in success_boards_with_duplicates:\n if success_board not in success_boards:\n success_boards.append(success_board)\n return success_boards\n\n\ndef visualize_board(board: Dict[int, Optional[bool]]) -> None:\n from math import sqrt\n row_len = int(sqrt(len(board)))\n parse_dict = {\n False: \"Q\",\n }\n for row in range(len(board), 0, -row_len):\n print(\n \"[\" + \"][\".join([parse_dict.get(board[x], \" \") for x in range(row - row_len + 1, row + 1)]) + \"]\"\n )\n >>> a = get_all_queen_configurations(3,4)\n>>> visualize_board(a[0])\n[ ][ ][Q][ ]\n[ ][ ][ ][ ]\n[ ][ ][ ][Q]\n[Q][ ][ ][ ]\n>>> visualize_board(a[1])\n[ ][Q][ ][ ]\n[ ][ ][ ][Q]\n[ ][ ][ ][ ]\n[Q][ ][ ][ ]\n>>> visualize_board(a[2])\n[ ][ ][ ][Q]\n[Q][ ][ ][ ]\n[ ][ ][ ][ ]\n[ ][Q][ ][ ]\n>>> visualize_board(a[3])\n[ ][ ][ ][Q]\n[ ][ ][ ][ ]\n[Q][ ][ ][ ]\n[ ][ ][Q][ ]\n"
},
{
"answer_id": 74611290,
"author": "Paul Hankin",
"author_id": 1400793,
"author_profile": "https://Stackoverflow.com/users/1400793",
"pm_score": 2,
"selected": false,
"text": "def queens(n, k, i=0, a=[], b=[], c=[]):\n if k == 0:\n yield a + [None] * (n - len(a))\n return\n for j in range(n):\n if j not in a and i+j not in b and i-j not in c:\n yield from queens(n, k-1, i+1, a+[j], b+[i+j], c+[i-j])\n if k < n - i:\n yield from queens(n, k, i+1, a+[None], b, c)\n\nfor i, solution in enumerate(queens(10, 9)):\n print(i, solution)\n a b c k"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20628945/"
] |
74,608,971
|
<p>Looking to convey more information in a Rich Table by using colors (specifically to track which modules given classes come from).</p>
<p>On the web, it's fairly easy on find color palettes that are optimized for contrast, rather than esthetics. Here's a <a href="https://www.schemecolor.com/high-contrast.php" rel="nofollow noreferrer">6 color example</a>. Then it's just question of using the RGB/HSL specs to drive your CSS.</p>
<p>Rich has a nice list of ANSI colors in <code>rich.colors.ANSI_COLOR_NAMES</code>. But there is no indication of what colors would constitute a high-contrast 10-12 color palette.</p>
<p>Are there such lists available, for ANSI colors to be used in terminal apps? Or should I just find a web palette and use <code>rich.colors.Color.from_rgb()</code> to build myself such a palette?</p>
|
[
{
"answer_id": 74610912,
"author": "scr",
"author_id": 18781246,
"author_profile": "https://Stackoverflow.com/users/18781246",
"pm_score": 0,
"selected": false,
"text": "from typing import Dict, List, Callable, Optional\n\n\ndef create_k_by_k_board(k: int) -> Dict[int, bool]:\n # True means the spot is available, False means it has a queen and None means it is checked by a Queen\n if k <= 0:\n raise ValueError(\"k must be higher than 0\")\n return {i: True for i in range(1, k**2+1)}\n\n\ndef check_position(conditions: List[Callable], position: int) -> bool:\n # Checks if any function returns True\n for func in conditions:\n if func(position):\n return True\n return False\n\n\ndef get_all_checked_positions(queen_location: int, board_size: int) -> List[int]:\n from math import sqrt\n row_len = int(sqrt(board_size))\n conditions = [\n # Horizontal check\n lambda x: ((x - 1) // row_len) == ((queen_location - 1) // row_len),\n # Vertical check\n lambda x: (x % row_len) == (queen_location % row_len),\n # Right diagonal check\n lambda x: (x % (row_len + 1)) == (queen_location % (row_len + 1)),\n # Left diagonal check\n lambda x: (x % (row_len - 1)) == (queen_location % (row_len - 1)),\n ]\n return [\n position for position in range(1, board_size + 1)\n if position != queen_location\n and check_position(conditions, position)\n ]\n\n\ndef place_queen_on_board(board: Dict[int, Optional[bool]], position: int) -> Dict[int, Optional[bool]]:\n # We don't want to edit the board in place because we may need to go back to it\n new_board = board.copy()\n if new_board[position] is True:\n # Place a new queen\n new_board[position] = False\n for checked_position in get_all_checked_positions(position, len(board)):\n # Set the location as checked (no risk of erasing queens)\n new_board[checked_position] = None\n return new_board\n else:\n raise ValueError(f\"Tried to add queen to position {position} in board {board}\")\n\n\ndef get_all_queen_configurations(numb_queens: int, row_length: int) -> List[Dict[int, Optional[bool]]]:\n board = create_k_by_k_board(row_length)\n\n def recursive_queen_search(curr_round: int, curr_board: Dict[int, Optional[bool]]) -> List[Dict[int, Optional[bool]]]:\n successful_boards = []\n available_spots = [position for position, is_free in curr_board.items() if is_free is True]\n for spot in available_spots:\n new_board = place_queen_on_board(curr_board, spot)\n if curr_round < numb_queens:\n successful_boards.extend(\n recursive_queen_search(curr_round+1, new_board)\n )\n else:\n successful_boards.append(new_board)\n return successful_boards\n\n success_boards_with_duplicates = recursive_queen_search(1, board)\n success_boards = []\n for success_board in success_boards_with_duplicates:\n if success_board not in success_boards:\n success_boards.append(success_board)\n return success_boards\n\n\ndef visualize_board(board: Dict[int, Optional[bool]]) -> None:\n from math import sqrt\n row_len = int(sqrt(len(board)))\n parse_dict = {\n False: \"Q\",\n }\n for row in range(len(board), 0, -row_len):\n print(\n \"[\" + \"][\".join([parse_dict.get(board[x], \" \") for x in range(row - row_len + 1, row + 1)]) + \"]\"\n )\n >>> a = get_all_queen_configurations(3,4)\n>>> visualize_board(a[0])\n[ ][ ][Q][ ]\n[ ][ ][ ][ ]\n[ ][ ][ ][Q]\n[Q][ ][ ][ ]\n>>> visualize_board(a[1])\n[ ][Q][ ][ ]\n[ ][ ][ ][Q]\n[ ][ ][ ][ ]\n[Q][ ][ ][ ]\n>>> visualize_board(a[2])\n[ ][ ][ ][Q]\n[Q][ ][ ][ ]\n[ ][ ][ ][ ]\n[ ][Q][ ][ ]\n>>> visualize_board(a[3])\n[ ][ ][ ][Q]\n[ ][ ][ ][ ]\n[Q][ ][ ][ ]\n[ ][ ][Q][ ]\n"
},
{
"answer_id": 74611290,
"author": "Paul Hankin",
"author_id": 1400793,
"author_profile": "https://Stackoverflow.com/users/1400793",
"pm_score": 2,
"selected": false,
"text": "def queens(n, k, i=0, a=[], b=[], c=[]):\n if k == 0:\n yield a + [None] * (n - len(a))\n return\n for j in range(n):\n if j not in a and i+j not in b and i-j not in c:\n yield from queens(n, k-1, i+1, a+[j], b+[i+j], c+[i-j])\n if k < n - i:\n yield from queens(n, k, i+1, a+[None], b, c)\n\nfor i, solution in enumerate(queens(10, 9)):\n print(i, solution)\n a b c k"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74608971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1394353/"
] |
74,609,000
|
<p>The antd tables work well with Input components. I have been using the editable cell example at <a href="https://ant.design/components/table#components-table-demo-edit-cell" rel="nofollow noreferrer">https://ant.design/components/table#components-table-demo-edit-cell</a> and it works well with undo / redo functionality.</p>
<p>The Select / Options and Date Picker components however do not have any documentation in the context of a table that's hooked up to a state. I have gotten the Options / Date Picker to work but when implementing undo / redo logic, it looks like their state does not by default update like the Input fields. If you Google this, it is a tricky part of React in general to get these components to update automatically with state changes in a Form.</p>
<p><strong>Is there an example of an antd table with select or date picker that's hooked up to state information?</strong></p>
<p>I got the Select / Option to work correctly visually e.g. default states load correctly, depending on selection color changes etc. I can manipulate the data as needed. Similarly, got the Date Picker to work. However, where I am stuck is automatically tying state changes to update the components. I can probably do some crazy stuff like force render but before going that route wanted to check if there is a cleaner / better antd way of doing this.</p>
|
[
{
"answer_id": 74610912,
"author": "scr",
"author_id": 18781246,
"author_profile": "https://Stackoverflow.com/users/18781246",
"pm_score": 0,
"selected": false,
"text": "from typing import Dict, List, Callable, Optional\n\n\ndef create_k_by_k_board(k: int) -> Dict[int, bool]:\n # True means the spot is available, False means it has a queen and None means it is checked by a Queen\n if k <= 0:\n raise ValueError(\"k must be higher than 0\")\n return {i: True for i in range(1, k**2+1)}\n\n\ndef check_position(conditions: List[Callable], position: int) -> bool:\n # Checks if any function returns True\n for func in conditions:\n if func(position):\n return True\n return False\n\n\ndef get_all_checked_positions(queen_location: int, board_size: int) -> List[int]:\n from math import sqrt\n row_len = int(sqrt(board_size))\n conditions = [\n # Horizontal check\n lambda x: ((x - 1) // row_len) == ((queen_location - 1) // row_len),\n # Vertical check\n lambda x: (x % row_len) == (queen_location % row_len),\n # Right diagonal check\n lambda x: (x % (row_len + 1)) == (queen_location % (row_len + 1)),\n # Left diagonal check\n lambda x: (x % (row_len - 1)) == (queen_location % (row_len - 1)),\n ]\n return [\n position for position in range(1, board_size + 1)\n if position != queen_location\n and check_position(conditions, position)\n ]\n\n\ndef place_queen_on_board(board: Dict[int, Optional[bool]], position: int) -> Dict[int, Optional[bool]]:\n # We don't want to edit the board in place because we may need to go back to it\n new_board = board.copy()\n if new_board[position] is True:\n # Place a new queen\n new_board[position] = False\n for checked_position in get_all_checked_positions(position, len(board)):\n # Set the location as checked (no risk of erasing queens)\n new_board[checked_position] = None\n return new_board\n else:\n raise ValueError(f\"Tried to add queen to position {position} in board {board}\")\n\n\ndef get_all_queen_configurations(numb_queens: int, row_length: int) -> List[Dict[int, Optional[bool]]]:\n board = create_k_by_k_board(row_length)\n\n def recursive_queen_search(curr_round: int, curr_board: Dict[int, Optional[bool]]) -> List[Dict[int, Optional[bool]]]:\n successful_boards = []\n available_spots = [position for position, is_free in curr_board.items() if is_free is True]\n for spot in available_spots:\n new_board = place_queen_on_board(curr_board, spot)\n if curr_round < numb_queens:\n successful_boards.extend(\n recursive_queen_search(curr_round+1, new_board)\n )\n else:\n successful_boards.append(new_board)\n return successful_boards\n\n success_boards_with_duplicates = recursive_queen_search(1, board)\n success_boards = []\n for success_board in success_boards_with_duplicates:\n if success_board not in success_boards:\n success_boards.append(success_board)\n return success_boards\n\n\ndef visualize_board(board: Dict[int, Optional[bool]]) -> None:\n from math import sqrt\n row_len = int(sqrt(len(board)))\n parse_dict = {\n False: \"Q\",\n }\n for row in range(len(board), 0, -row_len):\n print(\n \"[\" + \"][\".join([parse_dict.get(board[x], \" \") for x in range(row - row_len + 1, row + 1)]) + \"]\"\n )\n >>> a = get_all_queen_configurations(3,4)\n>>> visualize_board(a[0])\n[ ][ ][Q][ ]\n[ ][ ][ ][ ]\n[ ][ ][ ][Q]\n[Q][ ][ ][ ]\n>>> visualize_board(a[1])\n[ ][Q][ ][ ]\n[ ][ ][ ][Q]\n[ ][ ][ ][ ]\n[Q][ ][ ][ ]\n>>> visualize_board(a[2])\n[ ][ ][ ][Q]\n[Q][ ][ ][ ]\n[ ][ ][ ][ ]\n[ ][Q][ ][ ]\n>>> visualize_board(a[3])\n[ ][ ][ ][Q]\n[ ][ ][ ][ ]\n[Q][ ][ ][ ]\n[ ][ ][Q][ ]\n"
},
{
"answer_id": 74611290,
"author": "Paul Hankin",
"author_id": 1400793,
"author_profile": "https://Stackoverflow.com/users/1400793",
"pm_score": 2,
"selected": false,
"text": "def queens(n, k, i=0, a=[], b=[], c=[]):\n if k == 0:\n yield a + [None] * (n - len(a))\n return\n for j in range(n):\n if j not in a and i+j not in b and i-j not in c:\n yield from queens(n, k-1, i+1, a+[j], b+[i+j], c+[i-j])\n if k < n - i:\n yield from queens(n, k, i+1, a+[None], b, c)\n\nfor i, solution in enumerate(queens(10, 9)):\n print(i, solution)\n a b c k"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20629180/"
] |
74,609,005
|
<p>I am trying to add NavigationLink inside NavigationView in which there is a custom designed button.
I want to navigate on that button tap but NavigationLink code gives compilation error. it requires localisedTitle which I don't want to display and also tried to give Custom button in place of label but not working. Any help would be appreciated</p>
<p><code>Here is my code! I am using Xcode 13.3.1 </code></p>
<pre><code> @State private var isShowingSignupView = false
var body: some View {
NavigationView {
VStack {
Spacer()
VStack(alignment: .center, spacing: 12) {
AppTextField(Constants.Email, text: $email)
AppTextField(Constants.Password, text: $password, isSecure: $isSecure, leftImage: "lock",rightImage: Image(systemName: "eye.fill"), rightSelectedImage: Image(systemName: "eye.slash.fill"))
AppButtonText(title: Constants.ForgotPassword) {
debugPrint("Forgot Password tapped")
}
.frame(maxWidth: .infinity, maxHeight: 20, alignment: .trailing)
AppButton(title: Constants.Login) {
}
}
Spacer()
NavigationLink($isShowingSignupView, destination: Signup) {
AppButtonText(title: Constants.SignUp) {
isShowingSignupView = true
}
}
}
.padding()
}
.navigationTitle("Login")
}
</code></pre>
<h1>**ERROR:-</h1>
<ol>
<li>Cannot convert value of type 'Signup.Type' to expected argument type '() -> Destination'</li>
<li>Generic parameter 'Destination' could not be inferred**</li>
</ol>
<p>**I have also tried after replacing this **</p>
<pre><code>NavigationLink(destination: Signup()) {
AppButtonText(title: Constants.SignUp) {
isShowingSignupView = true
}
}
</code></pre>
<p>Which just removed error but does not navigate on new screen</p>
|
[
{
"answer_id": 74610912,
"author": "scr",
"author_id": 18781246,
"author_profile": "https://Stackoverflow.com/users/18781246",
"pm_score": 0,
"selected": false,
"text": "from typing import Dict, List, Callable, Optional\n\n\ndef create_k_by_k_board(k: int) -> Dict[int, bool]:\n # True means the spot is available, False means it has a queen and None means it is checked by a Queen\n if k <= 0:\n raise ValueError(\"k must be higher than 0\")\n return {i: True for i in range(1, k**2+1)}\n\n\ndef check_position(conditions: List[Callable], position: int) -> bool:\n # Checks if any function returns True\n for func in conditions:\n if func(position):\n return True\n return False\n\n\ndef get_all_checked_positions(queen_location: int, board_size: int) -> List[int]:\n from math import sqrt\n row_len = int(sqrt(board_size))\n conditions = [\n # Horizontal check\n lambda x: ((x - 1) // row_len) == ((queen_location - 1) // row_len),\n # Vertical check\n lambda x: (x % row_len) == (queen_location % row_len),\n # Right diagonal check\n lambda x: (x % (row_len + 1)) == (queen_location % (row_len + 1)),\n # Left diagonal check\n lambda x: (x % (row_len - 1)) == (queen_location % (row_len - 1)),\n ]\n return [\n position for position in range(1, board_size + 1)\n if position != queen_location\n and check_position(conditions, position)\n ]\n\n\ndef place_queen_on_board(board: Dict[int, Optional[bool]], position: int) -> Dict[int, Optional[bool]]:\n # We don't want to edit the board in place because we may need to go back to it\n new_board = board.copy()\n if new_board[position] is True:\n # Place a new queen\n new_board[position] = False\n for checked_position in get_all_checked_positions(position, len(board)):\n # Set the location as checked (no risk of erasing queens)\n new_board[checked_position] = None\n return new_board\n else:\n raise ValueError(f\"Tried to add queen to position {position} in board {board}\")\n\n\ndef get_all_queen_configurations(numb_queens: int, row_length: int) -> List[Dict[int, Optional[bool]]]:\n board = create_k_by_k_board(row_length)\n\n def recursive_queen_search(curr_round: int, curr_board: Dict[int, Optional[bool]]) -> List[Dict[int, Optional[bool]]]:\n successful_boards = []\n available_spots = [position for position, is_free in curr_board.items() if is_free is True]\n for spot in available_spots:\n new_board = place_queen_on_board(curr_board, spot)\n if curr_round < numb_queens:\n successful_boards.extend(\n recursive_queen_search(curr_round+1, new_board)\n )\n else:\n successful_boards.append(new_board)\n return successful_boards\n\n success_boards_with_duplicates = recursive_queen_search(1, board)\n success_boards = []\n for success_board in success_boards_with_duplicates:\n if success_board not in success_boards:\n success_boards.append(success_board)\n return success_boards\n\n\ndef visualize_board(board: Dict[int, Optional[bool]]) -> None:\n from math import sqrt\n row_len = int(sqrt(len(board)))\n parse_dict = {\n False: \"Q\",\n }\n for row in range(len(board), 0, -row_len):\n print(\n \"[\" + \"][\".join([parse_dict.get(board[x], \" \") for x in range(row - row_len + 1, row + 1)]) + \"]\"\n )\n >>> a = get_all_queen_configurations(3,4)\n>>> visualize_board(a[0])\n[ ][ ][Q][ ]\n[ ][ ][ ][ ]\n[ ][ ][ ][Q]\n[Q][ ][ ][ ]\n>>> visualize_board(a[1])\n[ ][Q][ ][ ]\n[ ][ ][ ][Q]\n[ ][ ][ ][ ]\n[Q][ ][ ][ ]\n>>> visualize_board(a[2])\n[ ][ ][ ][Q]\n[Q][ ][ ][ ]\n[ ][ ][ ][ ]\n[ ][Q][ ][ ]\n>>> visualize_board(a[3])\n[ ][ ][ ][Q]\n[ ][ ][ ][ ]\n[Q][ ][ ][ ]\n[ ][ ][Q][ ]\n"
},
{
"answer_id": 74611290,
"author": "Paul Hankin",
"author_id": 1400793,
"author_profile": "https://Stackoverflow.com/users/1400793",
"pm_score": 2,
"selected": false,
"text": "def queens(n, k, i=0, a=[], b=[], c=[]):\n if k == 0:\n yield a + [None] * (n - len(a))\n return\n for j in range(n):\n if j not in a and i+j not in b and i-j not in c:\n yield from queens(n, k-1, i+1, a+[j], b+[i+j], c+[i-j])\n if k < n - i:\n yield from queens(n, k, i+1, a+[None], b, c)\n\nfor i, solution in enumerate(queens(10, 9)):\n print(i, solution)\n a b c k"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13301227/"
] |
74,609,041
|
<p>im trying to validate a column using postgresql
where values in the column are (0000-ASZAS) four numerical values-five alphbets</p>
<pre><code>SELECT invoice_number,
CASE
WHEN invoice_number = '[0-9][0-9][0-9][0-9]-[A-Z][A-Z][A-Z][A-Z][A-Z]'
THEN 'valid'
ELSE 'invalid'
END
from invoices;
</code></pre>
<p>also tried LIKE instead of =</p>
<p>sorry wrong column customer_id with alpha numeric values
invoice_number is numeric. thank you for the correction</p>
|
[
{
"answer_id": 74609084,
"author": "Lennart - Slava Ukraini",
"author_id": 3592396,
"author_profile": "https://Stackoverflow.com/users/3592396",
"pm_score": 2,
"selected": true,
"text": "WHEN invoice_number ~ '[0-9][0-9][0-9][0-9]-[A-Z][A-Z][A-Z][A-Z][A-Z]' \n"
},
{
"answer_id": 74609086,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 1,
"selected": false,
"text": "~ SELECT invoice_number,\n CASE WHEN invoice_number ~ '^[0-9]{4}-[A-Z]{5}$' \n THEN 'valid'\n ELSE 'invalid' END\nFROM invoices;\n"
},
{
"answer_id": 74609393,
"author": "duff_y",
"author_id": 20629273,
"author_profile": "https://Stackoverflow.com/users/20629273",
"pm_score": 0,
"selected": false,
"text": "SELECT customer_id FROM invoices\nWHERE customer_id !~ '[0-9][0-9][0-9][0-9]-[A-Z][A-Z][A-Z][A-Z][A-Z]';\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20629273/"
] |
74,609,047
|
<p>df</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Season</th>
<th>Date</th>
<th>Team</th>
<th>Team_Season_Code</th>
<th>TS</th>
<th>L</th>
<th>Opponent</th>
<th>Opponent_Season_Code</th>
<th>OS</th>
</tr>
</thead>
<tbody>
<tr>
<td>2019</td>
<td>20181109</td>
<td>Abilene_Chr</td>
<td>1_2019</td>
<td>94</td>
<td>Home</td>
<td>Arkansas_St</td>
<td>15_2019</td>
<td>73</td>
</tr>
<tr>
<td>2019</td>
<td>20181115</td>
<td>Abilene_Chr</td>
<td>1_2019</td>
<td>67</td>
<td>Away</td>
<td>Denver</td>
<td>82_2019</td>
<td>61</td>
</tr>
<tr>
<td>2019</td>
<td>20181122</td>
<td>Abilene_Chr</td>
<td>1_2019</td>
<td>72</td>
<td>N</td>
<td>Elon</td>
<td>70_2019</td>
<td>56</td>
</tr>
<tr>
<td>2019</td>
<td>20181123</td>
<td>Abilene_Chr</td>
<td>1_2019</td>
<td>73</td>
<td>Away</td>
<td>Pacific</td>
<td>224_2019</td>
<td>71</td>
</tr>
<tr>
<td>2019</td>
<td>20181124</td>
<td>Abilene_Chr</td>
<td>1_2019</td>
<td>60</td>
<td>N</td>
<td>UC_Riverside</td>
<td>306_2019</td>
<td>48</td>
</tr>
</tbody>
</table>
</div>
<p>Overall_Season_Avg</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Team_Season_Code</th>
<th>Team</th>
<th>TS</th>
<th>OS</th>
<th>MOV</th>
</tr>
</thead>
<tbody>
<tr>
<td>15_2019</td>
<td>Arkansas_St</td>
<td>70.909091</td>
<td>65.242424</td>
<td>5.666667</td>
</tr>
<tr>
<td>70_2019</td>
<td>Elon</td>
<td>73.636364</td>
<td>71.818182</td>
<td>1.818182</td>
</tr>
<tr>
<td>82_2019</td>
<td>Denver</td>
<td>74.03125</td>
<td>72.15625</td>
<td>1.875</td>
</tr>
<tr>
<td>224_2019</td>
<td>Pacific</td>
<td>78.333333</td>
<td>76.466667</td>
<td>1.866667</td>
</tr>
<tr>
<td>306_2019</td>
<td>UC_Riverside</td>
<td>79.545455</td>
<td>78.060606</td>
<td>1.484848</td>
</tr>
</tbody>
</table>
</div>
<p>I have these two dataframes and I want to be able to look up the Opponent_Season_Code from df in Overall_Season_Avg - "Team_Season_Code" and bring back "TS" and "OS" to create a new column in df called "OOS" and "OTS"
So a new column for row 1 in df should have Column name OOS with data - 65.24... and Column name OTS with data 70.90...</p>
<p>In excel its a simple vlookup but i haven't been able to use the solutions that i have found to the vlookup question on overflow so i decided to post my own question. I will also say that the Overall_Season_Avg dataframe was created through by <code>Overall_Season_Avg = df.groupby(['Team_Season_Code', 'Team']).agg({'TS': np.mean, 'OS': np.mean, 'MOV': np.mean})</code></p>
|
[
{
"answer_id": 74609100,
"author": "Panda Kim",
"author_id": 20430449,
"author_profile": "https://Stackoverflow.com/users/20430449",
"pm_score": 0,
"selected": false,
"text": "df.merge(Overall_Season_Avg, on=['Team_Season_Code', 'Team'], how='left')\n transform agg"
},
{
"answer_id": 74609101,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 3,
"selected": true,
"text": "merge Overall_Season_Avg df.merge(Overall_Season_Avg\n .set_index(['Team_Season_Code', 'Team'])\n [['OS', 'TS']].add_prefix('O'),\n left_on=['Opponent_Season_Code', 'Opponent'],\n right_index=True, how='left'\n )\n Season Date Team Team_Season_Code TS L Opponent Opponent_Season_Code OS OOS OTS\n0 2019 20181109 Abilene_Chr 1_2019 94 Home Arkansas_St 15_2019 73 65.242424 70.909091\n1 2019 20181115 Abilene_Chr 1_2019 67 Away Denver 82_2019 61 72.156250 74.031250\n2 2019 20181122 Abilene_Chr 1_2019 72 N Elon 70_2019 56 71.818182 73.636364\n3 2019 20181123 Abilene_Chr 1_2019 73 Away Pacific 224_2019 71 76.466667 78.333333\n4 2019 20181124 Abilene_Chr 1_2019 60 N UC_Riverside 306_2019 48 78.060606 79.545455\n Opponent_Season_Code Team_Season_Code df.merge(Overall_Season_Avg\n .set_index('Team_Season_Code')\n [['OS', 'TS']].add_prefix('O'),\n left_on=['Opponent_Season_Code'],\n right_index=True, how='left'\n )\n Season Date Team Team_Season_Code TS L Opponent Opponent_Season_Code OS OOS OTS\n0 2019 20181109 Abilene_Chr 1_2019 94 Home Arkansas_St 15_2019 73 65.242424 70.909091\n1 2019 20181115 Abilene_Chr 1_2019 67 Away Denver 82_2019 61 72.156250 74.031250\n2 2019 20181122 Abilene_Chr 1_2019 72 N Elon 70_2019 56 71.818182 73.636364\n3 2019 20181123 Abilene_Chr 1_2019 73 Away Pacific 224_2019 71 76.466667 78.333333\n4 2019 20181124 Abilene_Chr 1_2019 60 N UC_Riverside 306_2019 48 78.060606 79.545455\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19154784/"
] |
74,609,065
|
<p>I'm writing a dissector <sup>(to be added to <code>DissectorTable.get("tcp.port")</code>)</sup> for a TCP-based application. I've gone through the Wireshark API <a href="https://www.wireshark.org/docs/wsdg_html_chunked/wsluarm_modules.html" rel="nofollow noreferrer">doc</a> but could not find out how to get TCP header's info like</p>
<ul>
<li>SYN/ACK flags</li>
<li>Sequence number</li>
<li>ACK'ed sequence number</li>
</ul>
|
[
{
"answer_id": 74631350,
"author": "Christopher Maynard",
"author_id": 2755698,
"author_profile": "https://Stackoverflow.com/users/2755698",
"pm_score": 2,
"selected": true,
"text": "local tcp_flags_syn = Field.new(\"tcp.flags.syn\")\nlocal tcp_flags_ack = Field.new(\"tcp.flags.ack\")\n\n-- If you want relative sequence/acknowledgment numbers:\nlocal tcp_seq = Field.new(\"tcp.seq\")\nlocal tcp_ack = Field.new(\"tcp.ack\")\n\n-- If you want absolute sequence/acknowledgment numbers:\nlocal tcp_seq_raw = Field.new(\"tcp.seq_raw\")\nlocal tcp_ack_raw = Field.new(\"tcp.ack_raw\")\n"
},
{
"answer_id": 74644226,
"author": "pynexj",
"author_id": 900078,
"author_profile": "https://Stackoverflow.com/users/900078",
"pm_score": 0,
"selected": false,
"text": "local proto = Proto(\"myproto\", \"my proto\")\n\n-- ...\n-- ...\n\n--\n-- A Field object can only be created *outside* of the callback\n-- functions of dissectors, post-dissectors, heuristic-dissectors,\n-- and taps.\n--\nlocal F_tcp_seq_rel = Field.new('tcp.seq') -- relative seq num\nlocal F_tcp_seq_raw = Field.new('tcp.seq_raw') -- raw seq num\n\nfunction proto.dissector(tvbuf, pinfo, tree)\n\n -- ...\n -- ...\n\n local seq_rel = F_tcp_seq_rel() -- yes the Field object is callable!\n local seq_raw = F_tcp_seq_raw()\n\n -- ...\n -- ...\nend\n\nDissectorTable.get(\"tcp.port\"):add(12345, proto)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/900078/"
] |
74,609,090
|
<p>I'm creating an employee leave form, with 3 categories of permissions coming from another table, namely: "Terlambat", "Pulang Cepat ", "Sakit".
<a href="https://i.stack.imgur.com/8lBHy.png" rel="nofollow noreferrer">select option for categories</a></p>
<p>For "SAKIT" category, the data was successfully saved to the database because there are no jam_mulai and jam_selesai to be filled in.
<a href="https://i.stack.imgur.com/FJzGw.png" rel="nofollow noreferrer">form for category "SAKIT"</a></p>
<p>For "Terlambat", "Pulang Cepat " categories. if selected, the jam_mulai and jam_selesai form will appear. as well as the jml_jam field I created in the controller too. However, when submitted, the data that I DD($IZIN) does not appear and returns to the index.blade.php page.
<a href="https://i.stack.imgur.com/WQLiO.png" rel="nofollow noreferrer">form for "TERLAMBAT" and "PULANG CEPAT"</a></p>
<p>this is the response on the network side when inspected:
<a href="https://i.stack.imgur.com/4RfQI.png" rel="nofollow noreferrer">preview</a>
<a href="https://i.stack.imgur.com/5KIIz.png" rel="nofollow noreferrer">header in network</a></p>
<p>this is the code for FORM MODALS ADD DATA PERMISSION:</p>
<pre><code>enter code here {{-- FORM PENGAJUAN IZIN--}}
{{-- bbootsrapt clockpicker --}}
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/clockpicker/0.0.7/bootstrap-clockpicker.min.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/clockpicker/0.0.7/bootstrap-clockpicker.min.js"></script>
<div class="modal fade" id="smallModal" tabindex="-1" role="dialog" aria-labelledby="smallModal" aria-hidden="true">
<div class="modal-dialog modal-md">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
<h4 class="modal-title" id="myModalLabel">Form Permohonan Izin</h4>
</div>
<div class="modal-body">
<form class="input" action="{{ route('izinstore')}}" method="POST" enctype="multipart/form-data">
@csrf
@method('POST')
<div class="form-group">
<label for="id_karyawan" class="col-form-label">Nama</label>
<input type="text" class="form-control" id="id_karyawan" value="{{Auth::user()->name}}" readonly>
<input type="hidden" class="form-control" name="id_karyawan" id="id_karyawan" value="{{$karyawan}}" hidden>
</div>
<div class="form-group col-sm" id="jenisizin">
<label for="id_jenisizin" class="col-form-label">Kategori Izin</label>
<select name="id_jenisizin" id="id_jenisizin" class="form-control">
<option>-- Pilih Kategori --</option>
@foreach ($jenisizin as $data)
<option value="{{ $data->id}}"
{{ old('id_jenisizin') == $data->id ? 'selected' : '' }}
>{{ $data->jenis_izin }}
</option>
@endforeach
</select>
</div>
<div class="form-group">
<label for="keperluan" class="col-form-label">Keperluan</label>
<input type="text" class="form-control" name="keperluan" id="keperluan" required>
</div>
<div class="row">
<div class="col-sm-6">
<div class="">
{{-- <form class="" action="#"> --}}
<div class="form-group">
<label for="tgl_mulai" class="form-label">Tanggal Mulai</label>
<div class="input-group">
<input type="text" class="form-control" placeholder="mm/dd/yyyy" id="datepicker-autoclose3" name="tgl_mulai" onchange=(jumlahhari()) autocomplete="off" required>
<span class="input-group-addon bg-custom b-0"><i class="mdi mdi-calendar text-white"></i></span>
</div>
</div>
{{-- </form> --}}
</div>
</div>
<div class="col-sm-6">
<div class="">
{{-- <form class="" action="#"> --}}
<div class="form-group">
<label for="tgl_selesai" class="form-label">Tanggal Selesai</label>
<div class="input-group">
<input type="text" class="form-control" placeholder="mm/dd/yyyy" id="datepicker-autoclose4" name="tgl_selesai" onchange=(jumlahhari()) autocomplete="off" required>
<span class="input-group-addon bg-custom b-0"><i class="mdi mdi-calendar text-white"></i></span>
</div>
</div>
{{-- </form> --}}
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6" id="jmulai">
<div class="">
<label for="jam_mulai">Dari Jam</label>
<div class="input-group clockpicker pull-center" data-placement="top" data-align="top" autocomplete="off" data-autoclose="true">
<input type="text" class="form-control" name="jam_mulai" id="mulai" value="{{ old('jam_mulai') }}">
<span class="input-group-addon">
<span class="fa fa-clock-o"></span>
</span>
</div>
</div>
</div>
<div class="col-lg-6" id="jselesai">
<div class="">
<label for="jam_selesai">Sampai Jam</label>
<div class="input-group clockpicker pull-center" data-placement="top" data-align="top" autocomplete="off" data-autoclose="true">
<input type="text" class="form-control" name="jam_selesai" id="selesai" value="{{ old('jam_selesai') }}">
<span class="input-group-addon">
<span class="fa fa-clock-o"></span>
</span>
</div>
</div>
</div>
</div>
<div class="form-group col-sm" id="jumlahhari">
<label for="jml_hari" class="col-form-label">Jumlah Hari</label>
<input type="text" class="form-control" name="jml_hari" id="jml" readonly>
</div>
<div class="form-group col-sm" id="jumlahjam">
{{-- <label for="jml_jam" class="col-form-label">Jumlah Jam</label> --}}
<input type="hidden" class="form-control" name="jml_jam" value="{{old('jml_jam')}}" id="jam">
</div>
<div class="form-group col-sm">
<input type="hidden" class="form-control" name="status" id="status" value="Pending" hidden>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-success" value="save">Send</button>
</div>
</form>
</div>
</div>
</div>
</div>
<script type="text/javascript">
//show clockpicker
jQuery(function(j){
j('.clockpicker').clockpicker()
.find('input').change(function()
{
console.log(this.value);
});
var input = j('#single-input').clockpicker({
placement: 'bottom',
align: 'left',
autoclose: true,
'default': 'now'
});
});
//show/hide clockpicker when id_jenisizin selected
$(function()
{
$('#jmulai').prop("hidden", true);
$('#jselesai').prop("hidden", true);
// $('#jumlahjam').prop("hidden", true);
$('#jumlahhari').prop("hidden", true);
$('#jenisizin').on('change', function(e)
{
if(e.target.value== 1 || e.target.value== 2)
{
$('#jmulai').prop("hidden", false);
$('#jselesai').prop("hidden", false);
// $('#jumlahjam').prop("hidden", false);
$('#jumlahhari').prop("hidden", false);
//selisih waktu jika terlambat
if(e.target.value== 1)
{
//set nilai jam_mulai
$('#mulai').val('08:00');
$('#mulai').attr('readonly', false);
$('#mulai').css('background-color' , '#DEDEDE');
}else {
//set nilai jam_selesai
$('#selesai').val('17:00');
$('#selesai').attr('readonly', false);
$('#selesai').css('background-color' , '#DEDEDE');
}
// alert('DATA ADA');
} else {
$('#jmulai').prop("hidden", true);
$('#jselesai').prop("hidden", true);
// $('#jumlahjam').prop("hidden", true);
$('#jumlahhari').prop("hidden", false);
}
// alert('id:' + e.target.value);
});
});
// =========================================================
//datepicker for tgl_mulai & tgl_selesai
$('#datepicker-autoclose3').datepicker({
autoclose: true,
});
$('#datepicker-autoclose4').datepicker({
autoclose: true,
});
function jumlahhari(){
var start= $('#datepicker-autoclose3').val();
var end = $('#datepicker-autoclose4').val();
var start_date= new Date(start);
var end_date = new Date(end) ;
var daysOfYear= [];
//mendapatkan jumlah hari izin jika sakit
for (var d = start_date; d <= end_date; d.setDate(d.getDate() + 1)){
//cek workdays
let tgl = new Date(d);
if(tgl.getDay() !=0 && tgl.getDay() !=6){
daysOfYear.push(tgl);
console.log(tgl);
} else{
console.log("hari Libur" + tgl.getDay());
};
};
//mengambil value tanggal mulai
$('#start_date').on('change', function(){
jumlahhari();
});
//mengambil value tanggal selesai
$('#end_date').on('change', function(){
jumlahhari();
});
console.info(daysOfYear);
$('#jml').val(daysOfYear.length ?? 0);
};
</script>
<!-- jQuery -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
<script src="assets/js/modernizr.min.js"></script>
<script src="assets/js/detect.js"></script>
<script src="assets/js/fastclick.js"></script>
<script src="assets/js/jquery.slimscroll.js"></script>
<script src="assets/js/jquery.blockUI.js"></script>
<script src="assets/js/waves.js"></script>
<script src="assets/js/wow.min.js"></script>
<script src="assets/js/jquery.nicescroll.js"></script>
<script src="assets/js/jquery.scrollTo.min.js"></script>
{{-- plugin js --}}
<script src="assets/plugins/bootstrap-datepicker/js/bootstrap-datepicker.min.js"></script>
{{-- // Datatable init js --}}
<script src="assets/pages/datatables.init.js"></script>
<script src="assets/js/app.js"></script>
{{-- // Plugins Init js --}}
<script src="assets/pages/form-advanced.js"></script>
</code></pre>
<p>this is the code store data in CONTROLLER:</p>
<pre><code>public function store(Request $request)
{
$karyawan = Auth::user()->karyawans->id;
// dd($request->id_jenisizin);
if($request->has('jam_mulai') && $request->has('jam_selesai'))
{
if($request->id_jenisizin == 1 || $request->id_jenisizin == 2)
{
// dd($request->all());
$validate = $request->validate([
'id_karyawan' => 'required',
'id_jenisizin' => 'required',
'keperluan' => 'required',
'tgl_mulai' => 'required',
'tgl_selesai' => 'required',
'jam_mulai' => 'required',
'jam_selesai' => 'required',
'jml_hari' => 'required',
'jml_jam' => 'required',
'status' => 'required',
]);
// dd($validate);
$izin = New Izin;
$izin->id_karyawan = $karyawan;
$izin->id_jenisizin= $request->id_jenisizin;
$izin->keperluan = $request->keperluan;
$izin->tgl_mulai = Carbon::now()->format("Y-m-d");
$izin->tgl_selesai = Carbon::now()->format("Y-m-d");
$izin->jam_mulai = $request->jam_mulai;
$izin->jam_selesai = $request->jam_selesai;
$izin->jml_hari = $request->jml_hari;
$jammulai = Carbon::parse($request->jam_mulai);
$jamselesai= Carbon::parse($request->jam_selesai);
$time_range= $jamselesai->diff($jammulai)->format("%H:%I");
$izin->jml_jam = $time_range;
$izin->status = 'Pending';
$izin->save();
dd($izin);
return redirect()->back()->withInput();
}else{
// dd($request->all());
$validate = $request->validate([
'id_karyawan' => 'required',
'id_jenisizin' => 'required',
'keperluan' => 'required',
'tgl_mulai' => 'required',
'tgl_selesai' => 'required',
'jml_hari' => 'required',
'status' => 'required',
]);
// dd($validate);
$izin = New Izin;
$izin->id_karyawan = $karyawan;
$izin->id_jenisizin= $request->id_jenisizin;
$izin->keperluan = $request->keperluan;
$izin->tgl_mulai = Carbon::now()->format("Y-m-d");
$izin->tgl_selesai = Carbon::now()->format("Y-m-d");
$izin->jml_hari = $request->jml_hari;
$izin->status = 'Pending';
$izin->save();
// dd($izin);
return redirect()->back()->withInput();
};
}
}
</code></pre>
<p>and this is the PERMISSION table in laragon database:
<a href="https://i.stack.imgur.com/pfGNe.png" rel="nofollow noreferrer">table IZIN in database</a></p>
|
[
{
"answer_id": 74611477,
"author": "Piyush Sapariya",
"author_id": 5527729,
"author_profile": "https://Stackoverflow.com/users/5527729",
"pm_score": 1,
"selected": false,
"text": "if($validator->fails()) {\n return Redirect::back()->withErrors($validator);\n}\n @if($errors->any())\n {{ implode('', $errors->all('<div>:message</div>')) }}\n@endif\n"
},
{
"answer_id": 74612569,
"author": "Top-Master",
"author_id": 8740349,
"author_profile": "https://Stackoverflow.com/users/8740349",
"pm_score": 0,
"selected": false,
"text": "public function store(Request $request)\n{\n $karyawan = Auth::user()->karyawans->id;\n\n $rules = [\n 'id_karyawan' => 'required',\n 'id_jenisizin' => 'required',\n 'keperluan' => 'required',\n 'tgl_mulai' => 'required',\n 'tgl_selesai' => 'required',\n 'jml_hari' => 'required',\n 'status' => 'required',\n ];\n\n $needsJmlJam = $request->id_jenisizin == 1\n || $request->id_jenisizin == 2;\n\n if ($needsJmlJam) {\n $rules = array_replace($rules, [\n 'jam_mulai' => 'required',\n 'jam_selesai' => 'required',\n 'jml_jam' => 'required',\n ]);\n }\n\n $request->validate($rules);\n\n $izin = New Izin;\n $izin->id_karyawan = $karyawan;\n $izin->id_jenisizin= $request->id_jenisizin;\n $izin->keperluan = $request->keperluan;\n $izin->tgl_mulai = Carbon::now()->format(\"Y-m-d\");\n $izin->tgl_selesai = Carbon::now()->format(\"Y-m-d\");\n $izin->jml_hari = $request->jml_hari;\n $izin->status = 'Pending';\n\n if ($needsJmlJam) {\n $izin->jam_mulai = $request->jam_mulai;\n $izin->jam_selesai = $request->jam_selesai;\n\n $jammulai = Carbon::parse($request->jam_mulai);\n $jamselesai= Carbon::parse($request->jam_selesai);\n $time_range= $jamselesai->diff($jammulai)->format(\"%H:%I\");\n\n $izin->jml_jam = $time_range;\n }\n\n $izin->save();\n\n return redirect()->back()->withInput();\n}\n .blade.php @if($errors->any())\n <div class=\"alert alert-danger show\" role=\"alert\">\n <strong>Whoops!</strong> There were some problems with your input.<br>\n <ul>\n @foreach ($errors->all() as $fieldError)\n <li>{{$fieldError}}</li>\n @endforeach\n </ul>\n </div>\n@endif\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17729116/"
] |
74,609,093
|
<p>I have a string of the form:</p>
<pre><code>Abu Dhabi1.90Morrisville Samp Army1.90
Deccan Gladiators1.40The Chennai Braves2.87
Bangla Tigers1.90Delhi Bulls1.90
New Zealand1.68India2.15
Australia1.09Draw14.00West Indies13.00
Sri Lanka1.51Afghanistan2.50
Tas Tigers1.28South Australia3.50
</code></pre>
<p>Is there a regular expression that can be used so that the final output looks like</p>
<pre><code>Abu Dhabi , 1.90 ,Morrisville Samp Army,1.90
Deccan Gladiators, 1.40,The Chennai Braves,2.87
Bangla Tigers, 1.90, Delhi Bulls, 1.90
New Zealand, 1.68, India, 2.15
Australia, 1.09, Draw, 14.00, West Indies, 13.00
Sri Lanka, 1.51, Afghanistan, 2.50
Tas Tigers, 1.28, South Australia, 3.50
</code></pre>
|
[
{
"answer_id": 74611477,
"author": "Piyush Sapariya",
"author_id": 5527729,
"author_profile": "https://Stackoverflow.com/users/5527729",
"pm_score": 1,
"selected": false,
"text": "if($validator->fails()) {\n return Redirect::back()->withErrors($validator);\n}\n @if($errors->any())\n {{ implode('', $errors->all('<div>:message</div>')) }}\n@endif\n"
},
{
"answer_id": 74612569,
"author": "Top-Master",
"author_id": 8740349,
"author_profile": "https://Stackoverflow.com/users/8740349",
"pm_score": 0,
"selected": false,
"text": "public function store(Request $request)\n{\n $karyawan = Auth::user()->karyawans->id;\n\n $rules = [\n 'id_karyawan' => 'required',\n 'id_jenisizin' => 'required',\n 'keperluan' => 'required',\n 'tgl_mulai' => 'required',\n 'tgl_selesai' => 'required',\n 'jml_hari' => 'required',\n 'status' => 'required',\n ];\n\n $needsJmlJam = $request->id_jenisizin == 1\n || $request->id_jenisizin == 2;\n\n if ($needsJmlJam) {\n $rules = array_replace($rules, [\n 'jam_mulai' => 'required',\n 'jam_selesai' => 'required',\n 'jml_jam' => 'required',\n ]);\n }\n\n $request->validate($rules);\n\n $izin = New Izin;\n $izin->id_karyawan = $karyawan;\n $izin->id_jenisizin= $request->id_jenisizin;\n $izin->keperluan = $request->keperluan;\n $izin->tgl_mulai = Carbon::now()->format(\"Y-m-d\");\n $izin->tgl_selesai = Carbon::now()->format(\"Y-m-d\");\n $izin->jml_hari = $request->jml_hari;\n $izin->status = 'Pending';\n\n if ($needsJmlJam) {\n $izin->jam_mulai = $request->jam_mulai;\n $izin->jam_selesai = $request->jam_selesai;\n\n $jammulai = Carbon::parse($request->jam_mulai);\n $jamselesai= Carbon::parse($request->jam_selesai);\n $time_range= $jamselesai->diff($jammulai)->format(\"%H:%I\");\n\n $izin->jml_jam = $time_range;\n }\n\n $izin->save();\n\n return redirect()->back()->withInput();\n}\n .blade.php @if($errors->any())\n <div class=\"alert alert-danger show\" role=\"alert\">\n <strong>Whoops!</strong> There were some problems with your input.<br>\n <ul>\n @foreach ($errors->all() as $fieldError)\n <li>{{$fieldError}}</li>\n @endforeach\n </ul>\n </div>\n@endif\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6781859/"
] |
74,609,117
|
<p>I want to add some extra features after new user login with a google login in Flutter.so I need to know if a user is new or not . if the user is new then I want to add some user information. other wise navigate to another page.</p>
<p>So how can I check If the User is new or not?</p>
|
[
{
"answer_id": 74609150,
"author": "Frank van Puffelen",
"author_id": 209103,
"author_profile": "https://Stackoverflow.com/users/209103",
"pm_score": 2,
"selected": false,
"text": "User metadata creationTime lastSignInTime"
},
{
"answer_id": 74609446,
"author": "Ayyaz meo",
"author_id": 10105487,
"author_profile": "https://Stackoverflow.com/users/10105487",
"pm_score": 0,
"selected": false,
"text": "bool isNewUser(User user) {\n DateTime now = DateTime.now();\n DateTime cTime = user.metadata.creationTime;\n int longAgo = 15; // to check account creation under last 15 seconds\n return now.difference(cTime).inSeconds > longAgo;\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13773550/"
] |
74,609,129
|
<p>I have about 100,000 price-table records in XML and I need to remove entries where the price amount is 0.00. The data is structured as follows:</p>
<pre class="lang-xml prettyprint-override"><code><data>
<price-table product-id="100109a">
<amount quantity="1">10.00</amount>
</price-table>
<price-table product-id="201208c">
<amount quantity="1">0.00</amount>
</price-table>
</data>
</code></pre>
<p>I'm trying to use Python to do the work and I have the following:</p>
<pre class="lang-py prettyprint-override"><code>from xml.etree import ElementTree as ET
def readfile():
with open('prices.xml') as f:
contents = f.read()
return(contents)
xml_string = readfile()
root = ET.fromstring(xml_string)
for price_table in root.findall('price-table'):
amount = price_table.find('amount')
if float(amount.text) != 0:
root.remove(price_table)
xmltowrite = ET.tostring(root)
#print(xmltowrite)
with open('xmlwrite.txt', 'w') as j:
j.write(xmltowrite)
</code></pre>
<p>When I run this, the error I get is:</p>
<blockquote>
<p>TypeError: write() argument must be str, not bytes</p>
</blockquote>
<p>But my understanding is that the ET.tostring() function should be converting the xmltowrite value to a string... Why is that not a string at the end?</p>
|
[
{
"answer_id": 74614816,
"author": "Hermann12",
"author_id": 12621346,
"author_profile": "https://Stackoverflow.com/users/12621346",
"pm_score": 1,
"selected": false,
"text": "type(xmltowrite) <class 'bytes'> ET.tostring(root).decode(\"Utf-8\") <class 'str'>"
},
{
"answer_id": 74614987,
"author": "mzjn",
"author_id": 407651,
"author_profile": "https://Stackoverflow.com/users/407651",
"pm_score": 2,
"selected": false,
"text": "tostring() bytes encoding=\"unicode\" open() fromstring() tostring() ElementTree ElementTree.write() from xml.etree import ElementTree as ET\n\ntree = ET.parse(\"prices.xml\")\nroot = tree.getroot()\n\nfor price_table in root.findall('price-table'):\n amount = price_table.find('amount')\n if float(amount.text) != 0:\n root.remove(price_table)\n\ntree.write('xmlwrite.txt')\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7483676/"
] |
74,609,139
|
<p>I am new to Docker, and as a learning exercise, I want to make a custom Python package available through a Docker image. The package is called <code>hashtable-nicolerg</code> and includes a <code>HashTable</code> class that can be imported with <code>from hashtable_nicolerg.hashtable import HashTable</code>.</p>
<p>It is straightforward to create an image with additional Python packages installed:</p>
<ol>
<li>Write a Dockerfile
<pre><code># Dockerfile
FROM python:3
RUN pip install --no-cache-dir hashtable-nicolerg
</code></pre>
</li>
<li>Build the image
<pre><code>docker build -t python-hashtable .
</code></pre>
</li>
</ol>
<p>However, the goal, which I realize is hardly an abundant use-case for Docker images, is <strong>for the user to be able to create <code>HashTable</code> instances as soon as the container's Python prompt starts</strong>.</p>
<p>Specifically, this is the current behavior:</p>
<pre><code>$ docker run -it python-hashtable
Python 3.11.0 (main, Nov 15 2022, 19:58:01) [GCC 10.2.1 20210110] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> hash_table = HashTable(capacity=100)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'HashTable' is not defined
>>> from hashtable_nicolerg.hashtable import HashTable
>>> hash_table = HashTable(capacity=100)
</code></pre>
<p>And this is the desired behavior:</p>
<pre><code>$ docker run -it python-hashtable
Python 3.11.0 (main, Nov 15 2022, 19:58:01) [GCC 10.2.1 20210110] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> hash_table = HashTable(capacity=100)
</code></pre>
<p>I don't want my imaginary users to have to type <code>from hashtable_nicolerg.hashtable import HashTable</code> every time they run a container from this image. So, is it possible for me to effectively run <code>from hashtable_nicolerg.hashtable import HashTable</code> within my Docker image so that users don't have to manually import this module?</p>
<p>Again, I realize this is not the most popular use-case for a Docker image. I'm using this as an exercise to learn more about Python and Docker. I'd appreciate any help!</p>
|
[
{
"answer_id": 74609167,
"author": "Silvio Mayolo",
"author_id": 2288659,
"author_profile": "https://Stackoverflow.com/users/2288659",
"pm_score": 3,
"selected": true,
"text": "PYTHONSTARTUP PYTHONSTARTUP .bashrc # .bashrc\nexport PYTHONSTARTUP=~/.python_startup\n # .python_startup\nfrom hashtable_nicolerg.hashtable import HashTable\n"
},
{
"answer_id": 74618181,
"author": "larenite",
"author_id": 17800293,
"author_profile": "https://Stackoverflow.com/users/17800293",
"pm_score": 1,
"selected": false,
"text": "~/.bashrc # Dockerfile\nFROM python:3\nRUN pip install --no-cache-dir hashtable-nicolerg\n\nWORKDIR /\nCOPY .python_startup .\nENV PYTHONSTARTUP=./.python_startup\n docker build -t python-hashtable . $ docker run -it python-hashtable\nPython 3.11.0 (main, Nov 15 2022, 19:58:01) [GCC 10.2.1 20210110] on linux\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> hash_table = HashTable(capacity=100)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17800293/"
] |
74,609,162
|
<p>`Hi everyone, I am new to Swift and following a biometrics authentication tutorial to click a button and use Face ID or Touch ID.</p>
<p>Nothing happens when the biometric authentication button is pressed because canEvaluate etc do not get set to true. Details below.</p>
<p>variables and the relevant function</p>
<pre><code>
private(set) var context = LAContext()
@Published private(set) var biometryType: LABiometryType = .none
private(set) var canEvaluatePolicy = false
@Published private(set) var isAuthenticated = false`
</code></pre>
<pre><code> func getBiometryType(){
context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil)
biometryType = context.biometryType
}
func authenticatedWithBiometrics() async {
context = LAContext()
print("inside auth func")
if canEvaluatePolicy{
let reason = "to log in to your account"
do{
let success = try await context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason)
print(success)
if success {
DispatchQueue.main.async {
self.isAuthenticated = true
print("is authenticated", self.isAuthenticated)
}
}
}
catch{ //if fail to authenticate, throw an error, show it, no biometry
print(error.localizedDescription)
DispatchQueue.main.async {
self.errorDescription = error.localizedDescription
self.showAlert = true
self.biometryType = .none
}
}
}
}
</code></pre>
<p>The issue: nothing happens when I click on the button that calls authenticatedwithbiometrics(). The function is called, the issue is that canEvaluatePolicy is FALSE and does not get set to true in getBiometryType. If I manually configure variables canEvaluatePolicy and success to true, we eventually run into the error.localizedDescription -> "biometry is not enrolled".</p>
<p>I've tried different simulators: iPhone 13, 14, 14 Pro, 14Pro Max, and SE which uses TouchID, and that also does nothing.</p>
<p>I've seen someone who had a same problem, but then it was solved by trying different simulators. That did not solve my issue.</p>
<p>I don't think it's an issue with the code because it's literally copied from a working tutorial. Do I need to configure something in the simulator?</p>
<p><a href="https://stackoverflow.com/questions/47159066/can-we-test-face-id-in-simulator">Can we test Face ID in simulator?</a> this type of answer is not useful to me because I cannot even evoke the gray popup that initiates the face or touch ID process.</p>
<p>I am using the newest version of xcode.</p>
<p>Thank you. `</p>
|
[
{
"answer_id": 74609167,
"author": "Silvio Mayolo",
"author_id": 2288659,
"author_profile": "https://Stackoverflow.com/users/2288659",
"pm_score": 3,
"selected": true,
"text": "PYTHONSTARTUP PYTHONSTARTUP .bashrc # .bashrc\nexport PYTHONSTARTUP=~/.python_startup\n # .python_startup\nfrom hashtable_nicolerg.hashtable import HashTable\n"
},
{
"answer_id": 74618181,
"author": "larenite",
"author_id": 17800293,
"author_profile": "https://Stackoverflow.com/users/17800293",
"pm_score": 1,
"selected": false,
"text": "~/.bashrc # Dockerfile\nFROM python:3\nRUN pip install --no-cache-dir hashtable-nicolerg\n\nWORKDIR /\nCOPY .python_startup .\nENV PYTHONSTARTUP=./.python_startup\n docker build -t python-hashtable . $ docker run -it python-hashtable\nPython 3.11.0 (main, Nov 15 2022, 19:58:01) [GCC 10.2.1 20210110] on linux\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> hash_table = HashTable(capacity=100)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19511822/"
] |
74,609,188
|
<p>I want to compare all the values in column B with the values in column A using the < operator, then display the results in a label..</p>
<p>i got this code which counts how many data have value < 0 in column A. and displays the result in label.</p>
<pre><code> int Col_A = Dt.AsEnumerable().Where(x => x.Field<decimal>("Column_A") < 0).Count();
lbCount.Text = numberOfRecords2.ToString();
</code></pre>
<p>what i want is "Column_B < Column_A = result".
<br>Thank you :)</p>
|
[
{
"answer_id": 74609167,
"author": "Silvio Mayolo",
"author_id": 2288659,
"author_profile": "https://Stackoverflow.com/users/2288659",
"pm_score": 3,
"selected": true,
"text": "PYTHONSTARTUP PYTHONSTARTUP .bashrc # .bashrc\nexport PYTHONSTARTUP=~/.python_startup\n # .python_startup\nfrom hashtable_nicolerg.hashtable import HashTable\n"
},
{
"answer_id": 74618181,
"author": "larenite",
"author_id": 17800293,
"author_profile": "https://Stackoverflow.com/users/17800293",
"pm_score": 1,
"selected": false,
"text": "~/.bashrc # Dockerfile\nFROM python:3\nRUN pip install --no-cache-dir hashtable-nicolerg\n\nWORKDIR /\nCOPY .python_startup .\nENV PYTHONSTARTUP=./.python_startup\n docker build -t python-hashtable . $ docker run -it python-hashtable\nPython 3.11.0 (main, Nov 15 2022, 19:58:01) [GCC 10.2.1 20210110] on linux\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> hash_table = HashTable(capacity=100)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15895383/"
] |
74,609,206
|
<p>I have a table in below format:</p>
<p>Table Name: <em>employee</em></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>code</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>e1</td>
</tr>
<tr>
<td>2</td>
<td>e2</td>
</tr>
</tbody>
</table>
</div>
<p>Need help in insert command:</p>
<pre><code>INSERT INTO employee
(id, code)
VALUES
(SELECT max(id) + 1
FROM employee,
SELECT CONCAT('e', (SELECT MAX(id) + 1 FROM employee)) FROM dual
);
</code></pre>
<p>am getting an error on this, need help</p>
|
[
{
"answer_id": 74609782,
"author": "d r",
"author_id": 19023353,
"author_profile": "https://Stackoverflow.com/users/19023353",
"pm_score": 1,
"selected": false,
"text": "INSERT INTO EMPLOYEE (ID, CODE)\n(Select Nvl(Max(ID), 0) + 1 \"NEW_ID\", 'e' || To_Char(Nvl(Max(ID), 0) + 1) \"NEW_CODE\"\n From EMPLOYEE)\n"
},
{
"answer_id": 74609796,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 0,
"selected": false,
"text": "SQL> select * from employee;\n\n ID CO\n---------- --\n 1 e1\n 2 e2\n\nSQL> insert into employee (id, code)\n 2 with temp (max_id) as\n 3 (select nvl(max(e.id), 0) + 1 from employee e)\n 4 select t.max_id,\n 5 'e' || t.max_id\n 6 from temp t;\n\n1 row created.\n\nSQL> select * from employee;\n\n ID CO\n---------- --\n 1 e1\n 2 e2\n 3 e3\n\nSQL>\n MAX + 1 ID"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1361143/"
] |
74,609,236
|
<p>How to convert a list into map form and get results like this:</p>
<pre><code>{"data":[{"id_pet":"63","id_habit":0},{"id_pet":"64","id_habbit":0}]}
</code></pre>
<p>My code:</p>
<pre><code>event.listPet.asMap();
</code></pre>
<p>My list:</p>
<pre><code>↓ pet: List (2 items)
↓ [0]: Pet
id_pet: 1
id_habbit: 1
↓ [1]: Pet
id_pet: 2
id_habbit: 2
</code></pre>
|
[
{
"answer_id": 74609262,
"author": "Rahul",
"author_id": 16569443,
"author_profile": "https://Stackoverflow.com/users/16569443",
"pm_score": 0,
"selected": false,
"text": "return {\"data\": event.listPet.map((e) => e.toMap()).toList(),};\n toMap"
},
{
"answer_id": 74609292,
"author": "Jungwon",
"author_id": 15134376,
"author_profile": "https://Stackoverflow.com/users/15134376",
"pm_score": -1,
"selected": false,
"text": "fromIterable Map<String, dynamic> map1 = {\n \"id_pet\":\"63\",\n \"id_habit\": 0\n };\n \n Map<String, dynamic> map2 = {\n \"id_pet\":\"64\",\n \"id_habit\": 0\n };\n List<Map<String, dynamic>> list = [];\n \n list.add(map1);\n list.add(map2);\n \n var map3 = Map.fromIterable(list, key: (e) => \"data\", value: (e) => list);\n print(map3);\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19646043/"
] |
74,609,238
|
<p>I want React to render key presses from a non-React context, more specifically the string array <code>keys</code>:</p>
<pre><code>import * as React from "react";
import { render } from "react-dom";
let keys: string[] = [];
function handleKeypress(event: any) {
keys.push(event.key);
console.log(keys);
// there will be more code here unrelated to React.
}
document.removeEventListener("keypress", handleKeypress);
document.addEventListener("keypress", handleKeypress);
function App() {
const [keysState, setKeysState] = React.useState<string[]>([]);
React.useEffect(() => {
function updateKeysState() {
setKeysState([...keys]);
}
// if you uncomment this, the code inside useEffect will run forever
// updateKeysState()
console.log("Hello world");
}, [keysState]);
return (
<div>
{keys.map((key: string, id) => (
<li key={id}>{key}</li>
))}
</div>
);
}
const rootElement = document.getElementById("root");
render(<App />, rootElement);
</code></pre>
<p>I almost accomplished that ... the problem is, the code inside <code>React.useEffect</code> runs in an infinite loop.</p>
<p>I thought passing <code>[keysState]</code> as a second argument to <code>React.useEffect</code> would stop the infinite loop. But it didn't.</p>
<p>Why is this and how to fix it?</p>
<p>Live code: <a href="https://codesandbox.io/s/changing-props-on-react-root-component-forked-eu16oj?file=/src/index.tsx" rel="nofollow noreferrer">https://codesandbox.io/s/changing-props-on-react-root-component-forked-eu16oj?file=/src/index.tsx</a></p>
|
[
{
"answer_id": 74609264,
"author": "CertainPerformance",
"author_id": 9515207,
"author_profile": "https://Stackoverflow.com/users/9515207",
"pm_score": 3,
"selected": true,
"text": "function App() {\n const [keys, setKeys] = React.useState<string[]>([]);\n useEffect(() => {\n function handleKeypress(event: KeyboardEvent) {\n setKeys([...keys, event.key]);\n // There will be more code here that's unrelated to React.\n }\n document.addEventListener(\"keypress\", handleKeypress);\n return () => {\n document.removeEventListener(\"keypress\", handleKeypress);\n };\n }, []);\n React.useEffect let setKeysOuter;\n\nfunction handleKeypress(event: KeyboardEvent) {\n setKeysOuter?.(keys => [...keys, event.key]);\n // There will be more code here that's unrelated to React.\n}\n\nfunction App() {\n const [keys, setKeys] = React.useState<string[]>([]);\n setKeysOuter = setKeys;\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122536/"
] |
74,609,243
|
<p>I upgraded my Spring Boot project to Spring Boot 3.0.0 and Hibernate 6.x. The application starts without any error and when I access any table information that has <code>Instant</code> date type, I get below error</p>
<pre><code>Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: The conversion from datetime2 to DATETIMEOFFSET is unsupported.
</code></pre>
<p>I am using SQL Server 2016 with Spring Data 3.0.0</p>
|
[
{
"answer_id": 74609291,
"author": "Pavan Jadda",
"author_id": 9244861,
"author_profile": "https://Stackoverflow.com/users/9244861",
"pm_score": 0,
"selected": false,
"text": "Instant 2020-08-03 14:54:40.0000000 2020-08-03 14:54:40.0000000 +00:00 spring.jpa.properties.hibernate.type.preferred_instant_jdbc_type=TIMESTAMP"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9244861/"
] |
74,609,276
|
<p>I keep reading that Lisp macros are one of the most powerful features of the language. But reading over the specifications and manuals, they are just functions whose arguments are unevaluated.</p>
<p>Given any macro <code>(defmacro example (arg1 ... argN) (body-forms))</code> I could just write <code>(defun example (arg1 ... argN) ... (body-forms))</code> with the last body-form turned into a list and then call it like <code>(eval (example 'arg1 ... 'argN))</code> to emulate the same behavior of the macro. If this were the case, then macros would just be syntactic sugar, but I doubt that syntactic sugar would be called a powerful language feature. What am I missing? Are there cases where I cannot carry out this procedure to emulate a macro?</p>
|
[
{
"answer_id": 74609291,
"author": "Pavan Jadda",
"author_id": 9244861,
"author_profile": "https://Stackoverflow.com/users/9244861",
"pm_score": 0,
"selected": false,
"text": "Instant 2020-08-03 14:54:40.0000000 2020-08-03 14:54:40.0000000 +00:00 spring.jpa.properties.hibernate.type.preferred_instant_jdbc_type=TIMESTAMP"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19484949/"
] |
74,609,279
|
<p>May I know how to read and parse .xml file with groovy? The groovy file needs to read the xml and grab shop id and country information</p>
<pre><code><?xml version="1.0"?>
<Someinformation>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.</description>
</book>
</catalog>
<Shops>
<shop id ="shop1" index ="1">
<ctr country="Japan">01</ctr>
<ctr country="Korea">02</ctr>
</shop>
<shop id ="shop2" index ="2">
<ctr country="England">03</ctr>
<ctr country="Germany">04</ctr>
</shop>
</Shops>
</Someinformation>
</code></pre>
<p>To open the .xml :</p>
<pre><code>def xml=new XmlSlurper().parse("book.xml")
</code></pre>
<p>But how to grab the xml contents?</p>
|
[
{
"answer_id": 74610053,
"author": "Andrej Istomin",
"author_id": 1842599,
"author_profile": "https://Stackoverflow.com/users/1842599",
"pm_score": 1,
"selected": false,
"text": "def xml = new groovy.xml.XmlSlurper().parse(\"book.xml\")\n\ndef total = xml.'*'.size()\nprintln \"Total amount of books: $total\"\nfor (i in 0..<total) {\n def book = xml.book[i]\n println \"-------------------------\"\n println \"ID: ${book.@id.text()}\"\n println \"Author: ${book.author.text()}\"\n println \"Title: ${book.title.text()}\"\n println \"-------------------------\"\n}\n\n"
},
{
"answer_id": 74614731,
"author": "Michael Easter",
"author_id": 12704,
"author_profile": "https://Stackoverflow.com/users/12704",
"pm_score": 1,
"selected": false,
"text": "def someInfo = new XmlSlurper().parse(\"book.xml\") \n\nsomeInfo.Shops.shop.each { thisShop ->\n // thisShop is the current node <shop> in XML\n println \"shop id: \" + thisShop.\"@id\"\n thisShop.ctr.each { thisCtr ->\n // thisCtr is the current node <ctr> in XML\n println \"country: \" + thisCtr.country + \" code: \" + thisCtr.text()\n }\n}\n shop id: shop1\ncountry: code: 01\ncountry: code: 02\nshop id: shop2\ncountry: code: 03\ncountry: code: 04\n"
},
{
"answer_id": 74615062,
"author": "injecteer",
"author_id": 1682820,
"author_profile": "https://Stackoverflow.com/users/1682820",
"pm_score": 0,
"selected": false,
"text": "String xml = '''<?xml version=\"1.0\"?> <Someinformation> <catalog> <book id=\"bk101\"> <author>Gambardella, Matthew</author> <title>XML Developer's Guide</title> <genre>Computer</genre> <price>44.95</price> <publish_date>2000-10-01</publish_date> <description>An in-depth look at creating applications with XML.</description> </book> <book id=\"bk102\"> <author>Ralls, Kim</author> <title>Midnight Rain</title> <genre>Fantasy</genre> <price>5.95</price> <publish_date>2000-12-16</publish_date> <description>A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.</description> </book> </catalog> <Shops> <shop id =\"shop1\" index =\"1\"> <ctr country=\"Japan\">01</ctr> <ctr country=\"Korea\">02</ctr> </shop> <shop id =\"shop2\" index =\"2\"> <ctr country=\"England\">03</ctr> <ctr country=\"Germany\">04</ctr> </shop> </Shops> </Someinformation>'''\n\ndef shopIds = ( xml =~ /<shop id =\"(\\w+)\" index =\"\\d\">/ ).findAll()*.last()\nassert shopIds == ['shop1', 'shop2']\n\ndef countries = ( xml =~ /<ctr country=\"(\\w+)\">/ ).findAll()*.last()\nassert countries == ['Japan', 'Korea', 'England', 'Germany']\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9960443/"
] |
74,609,290
|
<p>The perfect answer to my question already exists as the first answer by @akrun to this question <a href="https://www.stackoverflow.com/questions/66894918/sum-variable-between-dates-in-r">Sum variable between dates in R?</a></p>
<p>the answer by @akrun is exactly what I am looking for, but when I run the code with the example data in the original question I do not get a sum of the value column between the two dates, instead I get the last value in the date interval...</p>
<p>Any suggestions?</p>
<p>Example data:</p>
<pre><code>df1 <- data.frame(Start = as.Date(c('1/1/20', '5/1/20', '10/1/20', '2/2/21', '3/20/21'),"%m/%d/%y"), End = as.Date(c('1/7/20', '5/7/20', '10/7/20', '2/7/21', '3/30/21'),"%m/%d/%y"))
df2 <- data.frame(Date = as.Date(c('1/1/20','1/3/20' ,'5/1/20','5/2/20','6/2/20' ,'6/4/20','10/1/20', '2/2/21', '3/20/21'),"%m/%d/%y"),value=as.numeric(c('1','2','5','15','20','2','3','78','100')))
</code></pre>
<p>@akrun code:</p>
<pre><code> setDT(df1)[df2, value := sum(value),
on = .(Start <= Date, End >= Date), by = .EACHI]
</code></pre>
|
[
{
"answer_id": 74609426,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 2,
"selected": false,
"text": "fuzzyjoin match_fun library(fuzzyjoin)\nlibrary(dplyr)\n\nfuzzy_left_join(\n df2, df1,\n by = c(\n \"Date\" = \"Start\",\n \"Date\" = \"End\"\n ),\n match_fun = list(`>=`, `<=`)\n) %>% \n group_by(Start, End) %>% \n summarise(sum = sum(value))\n Start End sum\n <date> <date> <dbl>\n1 2020-01-01 2020-01-07 3\n2 2020-05-01 2020-05-07 20\n3 2020-10-01 2020-10-07 3\n4 2021-02-02 2021-02-07 78\n5 2021-03-20 2021-03-30 100\n6 NA NA 22\n"
},
{
"answer_id": 74647920,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": true,
"text": "library(data.table)\nsetDT(df2)[df1, .(value = sum(value)), \n on = .(Date >= Start, Date <= End ), by = .EACHI]\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20629476/"
] |
74,609,317
|
<p>I have a country field and a state field. I want to show the state field when the user chooses United States. Otherwise, I want it to be hidden.</p>
<p>This is my js script:</p>
<pre><code>@section Scripts {
<script type="text/javascript">
$("#Country").change(function () {
var value = $("#Country").val()
if (value === "1") {
$("#State").show();
}
if (value != "1") {
$("#State").hide();
}
});
</script>
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
</code></pre>
<p>This is my cshtml page of the form.</p>
<pre><code><div class="form-group col-sm-4 mt-4">
<label asp-for="Form.Country" class="control-label"></label>
<select asp-for="Form.Country" class="form-control">
<option disabled selected>Choose your Country</option>
<option>Canada</option>
<option>United States</option>
<option>Mexico</option>
</select>
<span asp-validation-for="Form.Country" class="text-danger"></span>
</div>
<div class="form-group col-sm-4 mt-4">
<label asp-for="Form.State" class="control-label"></label>
<select asp-for="Form.State" asp-items="Model.States" class="form-select">
<option disabled selected>Choose your State</option>
</select>
<span asp-validation-for="Form.State" class="text-danger"></span>
</div>
</code></pre>
|
[
{
"answer_id": 74609426,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 2,
"selected": false,
"text": "fuzzyjoin match_fun library(fuzzyjoin)\nlibrary(dplyr)\n\nfuzzy_left_join(\n df2, df1,\n by = c(\n \"Date\" = \"Start\",\n \"Date\" = \"End\"\n ),\n match_fun = list(`>=`, `<=`)\n) %>% \n group_by(Start, End) %>% \n summarise(sum = sum(value))\n Start End sum\n <date> <date> <dbl>\n1 2020-01-01 2020-01-07 3\n2 2020-05-01 2020-05-07 20\n3 2020-10-01 2020-10-07 3\n4 2021-02-02 2021-02-07 78\n5 2021-03-20 2021-03-30 100\n6 NA NA 22\n"
},
{
"answer_id": 74647920,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": true,
"text": "library(data.table)\nsetDT(df2)[df1, .(value = sum(value)), \n on = .(Date >= Start, Date <= End ), by = .EACHI]\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20517307/"
] |
74,609,346
|
<p>I'm trying to use react-router-dom v6.4+ in my project. I implemented it as a route array of objects. Its worked as routing but suddenly I got another issue realated this. I can't call any hook inside the Component which located on <code>element</code> property in route array.<br />
In the <code>route.ts</code> file:</p>
<pre><code>import MainLayout from './container/layouts/mainLayout/MainLayout'
import ErrorPage from './view/Error'
import Home from './view/Home'
const routes: RouteObject[] = [
{
path: '/',
element: MainLayout(),
children: [
{
index: true,
element: Home(),
},
],
},
{
path: '*',
element: ChangeRoute('/404'),
},
{
path: '/404',
element: ErrorPage(),
},
]
const router = createBrowserRouter(routes)
export default router
</code></pre>
<p>and in the <code>app.ts</code> file:</p>
<pre><code><RouterProvider router={router} fallbackElement={<React.Fragment>Loading ...</React.Fragment>} />
</code></pre>
<p>But If I try to use any hook , inside <strong>MainLayout</strong> component , its saying<br />
<a href="https://i.stack.imgur.com/G295q.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/G295q.png" alt="this error in console" /></a></p>
<p>code in <code>MainLayout</code> component :</p>
<pre><code>const MainLayout = () => {
const [collapsed, setCollapsed] = useState(false)
return (
<Layout className='layout'>
<SideBar collapsed={collapsed} />
<Layout>
<Topbar collapsed={collapsed} setCollapsed={setCollapsed} />
<Outlet />
</Layout>
</Layout>
)
}
export default MainLayout
</code></pre>
<p>I think if I use <code>element: <MainLayout/></code> instead of <code>element: MainLayout()</code>, then this issue will resolve. but typescript doesnt allow me to do this. and on the documentation every thing is on plain javascript. only one type defination there <a href="https://reactrouter.com/en/main/routers/create-browser-router#type-declaration" rel="nofollow noreferrer">is this</a></p>
<p>How to solve this? Kindly guide me.</p>
<p><strong>Edit</strong>
Here is the codesandbox demo : <a href="https://codesandbox.io/s/thirsty-gates-fw1fhv?file=/src/routes.ts" rel="nofollow noreferrer">visit sandbox</a></p>
|
[
{
"answer_id": 74609426,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 2,
"selected": false,
"text": "fuzzyjoin match_fun library(fuzzyjoin)\nlibrary(dplyr)\n\nfuzzy_left_join(\n df2, df1,\n by = c(\n \"Date\" = \"Start\",\n \"Date\" = \"End\"\n ),\n match_fun = list(`>=`, `<=`)\n) %>% \n group_by(Start, End) %>% \n summarise(sum = sum(value))\n Start End sum\n <date> <date> <dbl>\n1 2020-01-01 2020-01-07 3\n2 2020-05-01 2020-05-07 20\n3 2020-10-01 2020-10-07 3\n4 2021-02-02 2021-02-07 78\n5 2021-03-20 2021-03-30 100\n6 NA NA 22\n"
},
{
"answer_id": 74647920,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": true,
"text": "library(data.table)\nsetDT(df2)[df1, .(value = sum(value)), \n on = .(Date >= Start, Date <= End ), by = .EACHI]\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19761597/"
] |
74,609,348
|
<p>In Power BI, I have a table based on <code>UNION</code> of 2 different tables:</p>
<pre><code>ResultTable =
UNION (
SELECTCOLUMNS (
'Table1',
"Name", 'Table1'[name] ,
"Number", 'Table1'[number]
) ,
SELECTCOLUMNS (
'Table2',
"Name", 'Table2'[name] ,
"Number", 'Table2'[number]
)
)
</code></pre>
<p>Here is the <code>ResultTable</code> output:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Name</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>1</td>
</tr>
<tr>
<td>A</td>
<td>2</td>
</tr>
<tr>
<td>A</td>
<td>3</td>
</tr>
<tr>
<td>A</td>
<td>1</td>
</tr>
<tr>
<td>A</td>
<td>2</td>
</tr>
<tr>
<td>C</td>
<td>5</td>
</tr>
<tr>
<td>A</td>
<td>3</td>
</tr>
<tr>
<td>B</td>
<td>4</td>
</tr>
</tbody>
</table>
</div>
<p>Can I get distinct rows based on the <code>Number</code> column so that it becomes:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Name</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>1</td>
</tr>
<tr>
<td>A</td>
<td>2</td>
</tr>
<tr>
<td>A</td>
<td>3</td>
</tr>
<tr>
<td>C</td>
<td>5</td>
</tr>
<tr>
<td>B</td>
<td>4</td>
</tr>
</tbody>
</table>
</div>
|
[
{
"answer_id": 74609426,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 2,
"selected": false,
"text": "fuzzyjoin match_fun library(fuzzyjoin)\nlibrary(dplyr)\n\nfuzzy_left_join(\n df2, df1,\n by = c(\n \"Date\" = \"Start\",\n \"Date\" = \"End\"\n ),\n match_fun = list(`>=`, `<=`)\n) %>% \n group_by(Start, End) %>% \n summarise(sum = sum(value))\n Start End sum\n <date> <date> <dbl>\n1 2020-01-01 2020-01-07 3\n2 2020-05-01 2020-05-07 20\n3 2020-10-01 2020-10-07 3\n4 2021-02-02 2021-02-07 78\n5 2021-03-20 2021-03-30 100\n6 NA NA 22\n"
},
{
"answer_id": 74647920,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": true,
"text": "library(data.table)\nsetDT(df2)[df1, .(value = sum(value)), \n on = .(Date >= Start, Date <= End ), by = .EACHI]\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18443805/"
] |
74,609,355
|
<ul>
<li><p>I want to loop through an array of strings</p>
</li>
<li><p>When a new string, from the array, is selected I want to print out a
substring of the selected string every 0.1 second</p>
</li>
<li><p>After the entire string is printed I want to pause and then select the
next string in the array</p>
</li>
<li><p>Repeat</p>
<p>eg ['one', 'two']
output:
o
on
one
// pause 1 second
t
tw
two
// pause 1 second
o
on
one
// pause 1 second</p>
</li>
</ul>
<p>I have tried this but it only loops through once</p>
<pre><code> useEffect(() => {
let i = 0
function increment() {
i++
console.log(i)
}
const incrementTimer = setInterval(increment, 100)
setInterval(() => {
clearInterval(incrementTimer)
}, 1000)
}, [])
</code></pre>
|
[
{
"answer_id": 74609426,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 2,
"selected": false,
"text": "fuzzyjoin match_fun library(fuzzyjoin)\nlibrary(dplyr)\n\nfuzzy_left_join(\n df2, df1,\n by = c(\n \"Date\" = \"Start\",\n \"Date\" = \"End\"\n ),\n match_fun = list(`>=`, `<=`)\n) %>% \n group_by(Start, End) %>% \n summarise(sum = sum(value))\n Start End sum\n <date> <date> <dbl>\n1 2020-01-01 2020-01-07 3\n2 2020-05-01 2020-05-07 20\n3 2020-10-01 2020-10-07 3\n4 2021-02-02 2021-02-07 78\n5 2021-03-20 2021-03-30 100\n6 NA NA 22\n"
},
{
"answer_id": 74647920,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": true,
"text": "library(data.table)\nsetDT(df2)[df1, .(value = sum(value)), \n on = .(Date >= Start, Date <= End ), by = .EACHI]\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2135210/"
] |
74,609,360
|
<p>I have started learning linked list in python and after going through a lot material for leaning linked list. I found out that linked list is made of nodes(each node has two values namely the data and a address) and the first node is called the HEAD node and last node points towards the None value showing it to be the end of linked list. A linked list is formed when the previous node contains the address of the next node. In python to achieve connecting one node to another we simply assign an object to the head variable. The below code is an example</p>
<pre><code>class Node:
def __init__(self,data):
self.data = data
self.link = None
class SingleLinkedList:
def __init__(self):
self.head = None
def display(self):
if self.head is None:
print("Its a Empty Linked list")
else:
temp = self.head
while temp:
print(temp,"-->"end='')
temp = temp.link
L = SingleLinkedList()
n = Node(10)
L.head = n
n1 = Node(20)
L.head.link = n1
n2 =Node(30)
n1.link = n2
L.display()
</code></pre>
<p>My question is that in the linked list the node's link value(also known as reference/address value)should be contain the address of the next node, how is that achieved by the 18th line(L.head = n) of code</p>
<p>My assumption is that when we assign an object to a variable(head) we are actually assigning the address of that object to the variable.</p>
<p>I would like to know whether my assumption is correct or wrong and if its wrong why is it wrong</p>
<p>can someone explain the flow of the code shown in the question.</p>
<p>Thanks in Advance</p>
|
[
{
"answer_id": 74609455,
"author": "rootExplorr",
"author_id": 4861910,
"author_profile": "https://Stackoverflow.com/users/4861910",
"pm_score": -1,
"selected": false,
"text": "L = SingleLinkedList()\n n = Node(10)\n n = Node(10)\nL.head = n\n n2 =Node(30)\nn1.link = n2\nL.display()\n"
},
{
"answer_id": 74614572,
"author": "trincot",
"author_id": 5459839,
"author_profile": "https://Stackoverflow.com/users/5459839",
"pm_score": 2,
"selected": true,
"text": "head id L = SingleLinkedList()\n SingleLinkedList __init__ L ┌────────────┐\nL:─┤ head: None │\n └────────────┘\n n = Node(10) Node data data link n ┌────────────┐\nL:─┤ head: None │\n └────────────┘\n\n ┌────────────┐\nn:─┤ data: 10 │\n │ link: None │\n └────────────┘\n L.head = n ┌────────────┐\nL:─┤ head: ─┐ │\n └────────│───┘\n │\n ┌────────┴───┐\nn:─┤ data: 10 │\n │ link: None │\n └────────────┘\n n L.head Node n2 =Node(30) Node ┌────────────┐\nL:─┤ head: ─┐ │\n └────────│───┘\n │\n ┌────────┴───┐ ┌────────────┐\nn:─┤ data: 10 │ n2:─┤ data: 30 │\n │ link: None │ │ link: None │\n └────────────┘ └────────────┘\n n1.link = n2 n1 ┌────────────┐\nL:─┤ head: ─┐ │\n └────────│───┘\n │\n ┌────────┴───┐ ┌────────────┐\nn:─┤ data: 10 │ n2:─┤ data: 30 │\n │ link: ────────────┤ link: None │\n └────────────┘ └────────────┘\n display temp self.head self L ┌────────────┐\nL:─┤ head: ─┐ │\n └────────│───┘\n temp:─┐ │\n ┌──────┴─┴───┐ ┌────────────┐\nn:─┤ data: 10 │ n2:─┤ data: 30 │\n │ link: ────────────┤ link: None │\n └────────────┘ └────────────┘\n temp = temp.link temp ┌────────────┐\nL:─┤ head: ─┐ │\n └────────│───┘\n │ temp:─┐ \n ┌────────┴───┐ ┌─────┴──────┐\nn:─┤ data: 10 │ n2:─┤ data: 30 │\n │ link: ────────────┤ link: None │\n └────────────┘ └────────────┘\n temp None display"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15010931/"
] |
74,609,511
|
<p>I had a network security class in my university.
And there is a challenge for finding a secret number.
Here is the code</p>
<pre><code>#include <stdlib.h>
#include <time.h>
#include <stdio.h>
void init() {
setbuf(stdin, NULL);
setbuf(stdout, NULL);
}
int main() {
init();
srand(time(0));
int secret = 0;
puts("Your secret: ");
scanf("%d", &secret);
if(secret == rand()) {
system("/bin/sh");
} else {
puts("failed");
}
}
</code></pre>
<p>I actually could not understand my professor's explanation.
Anyone can explain the meaning of this code, and how can i find the secret number?</p>
|
[
{
"answer_id": 74609608,
"author": "Guss",
"author_id": 53538,
"author_profile": "https://Stackoverflow.com/users/53538",
"pm_score": 2,
"selected": false,
"text": "time() time() srand() time() srand() /dev/urandom"
},
{
"answer_id": 74610502,
"author": "marco-a",
"author_id": 2005038,
"author_profile": "https://Stackoverflow.com/users/2005038",
"pm_score": 2,
"selected": true,
"text": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(void) {\n srand(0);\n\n printf(\"random number 1: %d\\n\", rand());\n printf(\"random number 2: %d\\n\", rand());\n printf(\"random number 3: %d\\n\", rand());\n printf(\"random number 4: %d\\n\", rand());\n\n return 0;\n}\n a.out marco@Marcos-MacBook-Pro-16 Desktop % ./a.out\nrandom number 1: 520932930\nrandom number 2: 28925691\nrandom number 3: 822784415\nrandom number 4: 890459872\nmarco@Marcos-MacBook-Pro-16 Desktop % ./a.out\nrandom number 1: 520932930\nrandom number 2: 28925691\nrandom number 3: 822784415\nrandom number 4: 890459872\nmarco@Marcos-MacBook-Pro-16 Desktop % ./a.out\nrandom number 1: 520932930\nrandom number 2: 28925691\nrandom number 3: 822784415\nrandom number 4: 890459872\nmarco@Marcos-MacBook-Pro-16 Desktop % ./a.out\nrandom number 1: 520932930\nrandom number 2: 28925691\nrandom number 3: 822784415\nrandom number 4: 890459872\n #include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nint main(void) {\n srand(time(0));\n\n printf(\"the secret number is %d\\n\", rand());\n\n return 0;\n}\n time() #include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include <string.h>\n\n// where to put the \"random\" number on disk\nconst char *tmp_file = \"/tmp/input\";\n// where the executable of your professor is\nconst char *executable = \"/path/to/your/professors/executable\";\n\nvoid writeRandomNumberToDisk(const char *path, int number) {\n char buf[128];\n\n // convert int to string\n memset(buf, 0, sizeof(buf));\n snprintf(buf, sizeof(buf), \"%d\\n\", number);\n\n FILE *fp = fopen(path, \"w+\");\n fwrite(buf, strlen(buf), 1, fp);\n fclose(fp);\n}\n\nint main(void) {\n srand(time(0));\n\n int secret = rand();\n\n printf(\"the secret number is %d\\n\", secret);\n\n writeRandomNumberToDisk(tmp_file, secret);\n\n char buf[512];\n\n memset(buf, 0, sizeof(buf));\n snprintf(buf, sizeof(buf), \"/bin/sh -c 'cat %s | %s'\", tmp_file, executable);\n\n printf(\"Now executing %s\\n\", buf);\n system(buf);\n\n return 0;\n}\n #include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include <string.h>\n\n// where the executable of your professor is\nconst char *executable = \"/path/to/your/professors/executable\";\n\nint main(void) {\n srand(time(0));\n\n int secret = rand();\n\n printf(\"the secret number is %d\\n\", secret);\n\n char buf[512];\n\n memset(buf, 0, sizeof(buf));\n snprintf(buf, sizeof(buf), \"/bin/sh -c 'printf \\\"%d\\\\n\\\" | %s'\", secret, executable);\n\n printf(\"Now executing %s\\n\", buf);\n system(buf);\n\n return 0;\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17611024/"
] |
74,609,517
|
<p>I can limit the quantity of input if the user use the built in arrow icon inside the <code>textfield</code>. But when the user type it, it's not working</p>
<p><a href="https://i.stack.imgur.com/jjogP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jjogP.png" alt="User use the keyboard" /></a></p>
<pre><code><TextField variant="outlined" label="Quantity"
onChange={(e) => setItemName({...itemName, quantity: e.target.value})}
type="number"
fullWidth name="quantity" InputProps={{ inputProps: { min: 0, max: 10, maxLength: 2}}}
pattern="^-?[0-9]\d*\.?\d*$"
/>
</code></pre>
|
[
{
"answer_id": 74610080,
"author": "George Chond",
"author_id": 17730652,
"author_profile": "https://Stackoverflow.com/users/17730652",
"pm_score": 2,
"selected": true,
"text": "onInput={(e) => {e.target.value > 10 ? e.target.value = 10 : e.target.value}}\n"
},
{
"answer_id": 74610166,
"author": "Awais Rafiq Chaudhry",
"author_id": 12281539,
"author_profile": "https://Stackoverflow.com/users/12281539",
"pm_score": -1,
"selected": false,
"text": "onChange input max max input <TextField\n variant=\"outlined\"\n label=\"Quantity\" \n onChange={(e) => {\n const { target: { value, max } } = e;\n let inputValue = value;\n if (inputValue > max) inputValue = max;\n setItemName({ ...itemName, quantity: inputValue })\n }\n type=\"number\"\n fullWidth\n name=\"quantity\"\n InputProps={{ inputProps: { min: 0, max: 10, maxLength: 2}}} \n pattern=\"^-?[0-9]\\d*\\.?\\d*$\"\n/>\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18478430/"
] |
74,609,560
|
<p>Here is the example data I am working with. What I am trying to accomplish is 1) subtract b column from column a and 2) create the C column in front of a and b columns. I would like to loop through and create the C column for x, y and z.</p>
<pre><code>import pandas as pd
df = pd.DataFrame(data=[[100,200,400,500,111,222], [77,28,110,211,27,81], [11,22,33,11,22,33],[213,124,136,147,54,56]])
df.columns = pd.MultiIndex.from_product([['x', 'y', 'z'], list('ab')])
print (df)
</code></pre>
<p>Below is what I am trying to get.</p>
<p><a href="https://i.stack.imgur.com/0ChAd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0ChAd.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74609788,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 3,
"selected": true,
"text": "DataFrame.xs drop_level=False rename concat DataFrame.sort_index dfa = df.xs('a', axis=1, level=1, drop_level=False).rename(columns={'a':'c'})\ndfb = df.xs('b', axis=1, level=1, drop_level=False).rename(columns={'b':'c'})\n\ndf = pd.concat([df, dfa.sub(dfb)], axis=1).sort_index(axis=1)\nprint (df)\n x y z \n a b c a b c a b c\n0 100 200 -100 400 500 -100 111 222 -111\n1 77 28 49 110 211 -101 27 81 -54\n2 11 22 -11 33 11 22 22 33 -11\n3 213 124 89 136 147 -11 54 56 -2\n Series DataFrame.sort_index for c in df.columns.levels[0]:\n df[(c, 'c')] = df[(c, 'a')].sub(df[(c, 'b')])\n\ndf = df.sort_index(axis=1)\nprint (df)\n x y z \n a b c a b c a b c\n0 100 200 -100 400 500 -100 111 222 -111\n1 77 28 49 110 211 -101 27 81 -54\n2 11 22 -11 33 11 22 22 33 -11\n3 213 124 89 136 147 -11 54 56 -2\n"
},
{
"answer_id": 74609838,
"author": "Panda Kim",
"author_id": 20430449,
"author_profile": "https://Stackoverflow.com/users/20430449",
"pm_score": 2,
"selected": false,
"text": "a = df.xs('a', level=1, axis=1)\nb = df.xs('b', level=1, axis=1)\ndf1 = pd.concat([a.sub(b)], keys=['c'], axis=1).swaplevel(0, 1, axis=1)\n df1 x y z\n c c c\n0 -100 -100 -111\n1 49 -101 -54\n2 -11 22 -11\n3 89 -11 -2\n pd.concat([df, df1], axis=1).sort_index(axis=1)\n df.stack(level=0).assign(c=lambda x: x['b'] - x['a']).stack().unstack([1, 2])\n x y z\n a b c a b c a b c\n0 100 200 100 400 500 100 111 222 111\n1 77 28 -49 110 211 101 27 81 54\n2 11 22 11 33 11 -22 22 33 11\n3 213 124 -89 136 147 11 54 56 2\n"
},
{
"answer_id": 74611757,
"author": "sammywemmy",
"author_id": 7175713,
"author_profile": "https://Stackoverflow.com/users/7175713",
"pm_score": 1,
"selected": false,
"text": "result = df.loc(axis=1)[:,'a'].to_numpy() - df.loc(axis=1)[:, 'b'].to_numpy()\nheader = pd.MultiIndex.from_product([['x','y','z'], ['c']])\nresult = pd.DataFrame(result, columns=header)\npd.concat([df, result], axis=1).sort_index(axis=1)\n\n x y z\n a b c a b c a b c\n0 100 200 -100 400 500 -100 111 222 -111\n1 77 28 49 110 211 -101 27 81 -54\n2 11 22 -11 33 11 22 22 33 -11\n3 213 124 89 136 147 -11 54 56 -2\n pipe result = df.swaplevel(axis=1).pipe(lambda df: df['a'] - df['b'])\nresult.columns = pd.MultiIndex.from_product([result.columns, ['c']])\npd.concat([df, result], axis=1).sort_index(axis=1)\n\n x y z\n a b c a b c a b c\n0 100 200 -100 400 500 -100 111 222 -111\n1 77 28 49 110 211 -101 27 81 -54\n2 11 22 -11 33 11 22 22 33 -11\n3 213 124 89 136 147 -11 54 56 -2\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18708380/"
] |
74,609,659
|
<p><strong>The text:</strong></p>
<pre><code>23 81 96
...
...
...
...;
23 81 96
...
...
...
...
...
...
...;
51 67 16
...
...
...
...
...
...
...
...;
23 81 96
...
...
...
...
...
...
...
...
...
...
...
...
...;
</code></pre>
<p><strong>What do I want?</strong></p>
<p>I'm trying to match the text from <code>23 81 96</code> to <code>;</code> and the result must be 3 matches.</p>
<p><strong>Here is the expected result:</strong></p>
<p><a href="https://i.stack.imgur.com/kwRpi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kwRpi.png" alt="enter image description here" /></a></p>
<p><strong>Here is what I tried:</strong></p>
<pre><code>23 81 96 (.|\n)*;
</code></pre>
|
[
{
"answer_id": 74609696,
"author": "blhsing",
"author_id": 6890912,
"author_profile": "https://Stackoverflow.com/users/6890912",
"pm_score": 2,
"selected": true,
"text": "? . \\n 23 81 96.*?;\n"
},
{
"answer_id": 74609721,
"author": "Guss",
"author_id": 53538,
"author_profile": "https://Stackoverflow.com/users/53538",
"pm_score": 0,
"selected": false,
"text": "23 81 96[^;]*;\n ;"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7474282/"
] |
74,609,670
|
<p>I have a private repository that I have already docker pushed my image into.</p>
<p>Here is my one image in this repository:
<a href="https://i.stack.imgur.com/hhMpo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hhMpo.png" alt="enter image description here" /></a></p>
<p>However, when I got into the url, this shows up</p>
<p><a href="https://i.stack.imgur.com/TaFJF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TaFJF.png" alt="enter image description here" /></a></p>
<p>How do i make it so that this doesn't show up? (And also, what do the mean by username and password? my IAM user doesn't have a password, only access key id and secret key as far as I know)</p>
|
[
{
"answer_id": 74609696,
"author": "blhsing",
"author_id": 6890912,
"author_profile": "https://Stackoverflow.com/users/6890912",
"pm_score": 2,
"selected": true,
"text": "? . \\n 23 81 96.*?;\n"
},
{
"answer_id": 74609721,
"author": "Guss",
"author_id": 53538,
"author_profile": "https://Stackoverflow.com/users/53538",
"pm_score": 0,
"selected": false,
"text": "23 81 96[^;]*;\n ;"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19741062/"
] |
74,609,707
|
<p>I have a posts collection and I want to return the latest posts and featured posts with 1 query.</p>
<p>post document sample</p>
<pre><code>{
"title":"Hello World",
"author":"Bob Paul",
"featured":True,
"published":True,
"created_at":"2019-01-15 10:27:16.354Z"
}
</code></pre>
<p>This is what I want returned:</p>
<pre><code>{
"latest": [post1,post2,post3],
"featured": [post7,post10]
}
</code></pre>
<p>Seems like you'd have to do 2 match expressions on the same collection. Is that even possible?
I was thinking I could extract the featured posts in a different collection and use $unionWith.</p>
|
[
{
"answer_id": 74609696,
"author": "blhsing",
"author_id": 6890912,
"author_profile": "https://Stackoverflow.com/users/6890912",
"pm_score": 2,
"selected": true,
"text": "? . \\n 23 81 96.*?;\n"
},
{
"answer_id": 74609721,
"author": "Guss",
"author_id": 53538,
"author_profile": "https://Stackoverflow.com/users/53538",
"pm_score": 0,
"selected": false,
"text": "23 81 96[^;]*;\n ;"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9695723/"
] |
74,609,719
|
<p>Here, I'm trying to swap the number using PHP but not able to swap.
How to solve that problem.</p>
<p>My Code :</p>
<pre><code><?php
$a = 45;
$b = 78;
echo "Before swapping:<br><br>";
echo "a =".$a." b=".$b;
echo "<br/><br/>";
// Swapping Logic
$a=$a+$b;
$b=$a-$b;
$a=$a+$b;
echo "After swapping:<br><br>";
echo "a =".$a." b=".$b;
?>
</code></pre>
<p>I'm a beginner in php just learning about logic but getting exception so any body can help how to solve it?</p>
|
[
{
"answer_id": 74609732,
"author": "Bhavik",
"author_id": 20529186,
"author_profile": "https://Stackoverflow.com/users/20529186",
"pm_score": 3,
"selected": true,
"text": "// Swapping Logic \n\n $a=$a+$b; \n $b=$a-$b; \n $a=$a+$b; \n $a=$a+$b; \n $b=$a-$b; \n $a=$a-$b;\n"
},
{
"answer_id": 74609769,
"author": "Ross_102",
"author_id": 3657308,
"author_profile": "https://Stackoverflow.com/users/3657308",
"pm_score": 2,
"selected": false,
"text": "list($a, $b) = array($b, $a);\n"
},
{
"answer_id": 74610055,
"author": "Harvir",
"author_id": 16195196,
"author_profile": "https://Stackoverflow.com/users/16195196",
"pm_score": 0,
"selected": false,
"text": " $a=$a+$b; \n $b=$a-$b; \n $a=$a-$b;\n\n\n\n// Swapping Logic \n$third = $a; \n$a = $b; \n$b = $third; \n"
},
{
"answer_id": 74610321,
"author": "Tangentially Perpendicular",
"author_id": 14853083,
"author_profile": "https://Stackoverflow.com/users/14853083",
"pm_score": 0,
"selected": false,
"text": "<?php\n$a = 1;\n$b = 2;\n\n[$b,$a] = [$a,$b];\n\necho $a,' ', $b; // 2 1\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20580686/"
] |
74,609,733
|
<p>I've written this piece of code to see if I could convert simple numbers from decimal to, for example, binary numbers per base (e.g. binary base = 2) I know it wouldn't really be the correct number for hex, or anything above base = 9 for that matter, (that's why I added a space in <code>printf (temp[I])</code> so I could see the separate base^index-1 ) but here's my problem: after compiling and running it, I can enter decimal and base, then it prints those 2 and then... nothing. It's ignoring <code>convert();</code> and <code>for(){printf}</code> completely for some reason. PS: the reason I <code>calloc</code> exactly decimal times <code>sizeof int</code> is because maybe some one types base = 1 yk just in case. Also wouldn't really matter, as I count the length of the array anyway per int counter, right?</p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void convert(int decimal, int base, int counter, int temp[])
{
int remainder;
int quotient;
int i = 0;
while (decimal > 0)
{
remainder = decimal % base; // remainder is stored
quotient = (decimal - remainder) / base; //quotient is stored
decimal = quotient; // decimal is assigned quotient for next operation
counter++; //counter is incremented so we can printf correct lentgh of array
temp[i] = remainder; // sets our array at i = remainder
i = i + 1; //to increment i for every decimal > 0
}
}
int main ()
{
int counter = 0;
int decimal;
int base;
//enterNumbers(decimal, base); // doesnt work yet
printf("enter decimal:");
scanf("%d", &decimal);
printf("enter base:");
scanf("%d", &base);
// gets input decimal and base
int *temp = calloc(decimal, sizeof(int));
// alloc memory for array, worst case base = 1
printf("decimal:%d, base:%d", decimal, base);
// for test
convert(decimal, base, counter, temp);
// converts decimal into base number and sorts into array
for (int i = 0; i < counter; i++)
{
printf(" %d,", temp[i]);
}
//should printf the array, which is the base number
return 0;
}
</code></pre>
<p>well as stated above</p>
|
[
{
"answer_id": 74609960,
"author": "Allan Wind",
"author_id": 9706,
"author_profile": "https://Stackoverflow.com/users/9706",
"pm_score": 0,
"selected": false,
"text": "main() counter = 0 for() decimal == 0 scanf() calloc() free() temp #include <stdio.h>\n#include <stdlib.h>\n\nvoid convert(int decimal, int base, int *counter, int temp[])\n{\n int remainder;\n int quotient;\n int i = 0;\n while (decimal > 0)\n {\n remainder = decimal % base; // remainder is stored\n quotient = (decimal - remainder) / base; //quotient is stored\n decimal = quotient; // decimal is assigned quotient for next operation\n (*counter)++; //counter is incremented so we can printf correct lentgh of array\n temp[i] = remainder; // sets our array at i = remainder\n i = i + 1; //to increment i for every decimal > 0\n }\n}\n\nint main ()\n{\n int counter = 0;\n int decimal;\n int base;\n\n //enterNumbers(decimal, base); // doesnt work yet\n\n printf(\"enter decimal:\");\n if(scanf(\"%d\", &decimal) != 1) {\n printf(\"scanf failed\\n\");\n return 1;\n }\n printf(\"enter base:\");\n if(scanf(\"%d\", &base) != 1) {\n printf(\"scanf failed\\n\");\n return 1;\n }\n // gets input decimal and base\n int *temp = calloc(decimal, sizeof(int));\n if(!temp) {\n printf(\"calloc failed\\n\");\n return 1;\n }\n // alloc memory for array, worst case base = 1\n printf(\"decimal:%d, base:%d\", decimal, base);\n // for test\n\n convert(decimal + 1, base, &counter, temp);\n // converts decimal into base number and sorts into array\n\n for (int i = 0; i < counter; i++)\n {\n printf(\" %d,\", temp[i]);\n }\n //should printf the array, which is the base number\n free(temp);\n}\n enter decimal:10\nenter base:2\ndecimal:10, base:2 0, 1, 0, 1,\n 10 * sizeof(int) = 80 #include <stdio.h>\n#include <stdlib.h>\n#include <values.h>\n\nvoid print(size_t n, unsigned char a[n], const char *field_separator, const char *record_separator) {\n for(size_t i = 0; i < n; i++) {\n printf(\"%d%s\", a[i], i + 1 < n ? field_separator : record_separator);\n }\n}\n\nsize_t reverse(size_t n, unsigned char a[n]) {\n for(size_t i = 0; i < n/2; i++) {\n unsigned char tmp = a[i];\n a[i] = a[(n-1)-i];\n a[(n-1)-i] = tmp;\n }\n return n;\n}\n\nint convert(unsigned decimal, unsigned base, unsigned char temp[]) {\n int i = 0;\n for(; decimal > 0; i++) {\n temp[i] = decimal % base;\n decimal = (decimal - temp[i]) / base;\n }\n return reverse(i, temp);\n}\n\nint main(void) {\n printf(\"enter decimal: \");\n unsigned decimal;\n if(scanf(\"%u\", &decimal) != 1) {\n printf(\"scanf failed\\n\");\n return 1;\n }\n\n printf(\"enter base: \");\n unsigned base;\n if(scanf(\"%u\", &base) != 1) {\n printf(\"scanf failed\\n\");\n return 1;\n }\n if(base < 2 || base > 10) {\n printf(\"base must be between 2 and 10\\n\");\n return 1;\n }\n\n unsigned char temp[sizeof(int) * CHAR_BIT];\n int counter = convert(decimal, base, temp);\n print(counter, temp, \", \", \"\\n\");\n}\n enter decimal: 10\nenter base: 2\n1, 0, 1, 0\n"
},
{
"answer_id": 74610362,
"author": "Aconcagua",
"author_id": 1312382,
"author_profile": "https://Stackoverflow.com/users/1312382",
"pm_score": 1,
"selected": false,
"text": "main for void convert(int decimal, int base, int* counter, int temp[])\n// ^ (!)\n{\n // code as is, but use *counter instead of counter now\n}\n temp int temp[] int* temp i *counter i convert(decimal, base, &counter, temp);\n// ^ (!)\n i size_t convert(int decimal, int base, temp)\n{\n size_t i = 0;\n // rest as you have, dropping any references to counter\n return i;\n}\n size_t #include<stddef.h> unsigned int int decimal convert temp free(temp) calloc scanf scanf 1210dal fgets"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20630035/"
] |
74,609,766
|
<p>Whenever my home page was reloaded my data was updated but I want to reflect data instantly.
That's why I need a method that can refresh my page or method after every 1 second(flutter).
pls, help me.</p>
|
[
{
"answer_id": 74609960,
"author": "Allan Wind",
"author_id": 9706,
"author_profile": "https://Stackoverflow.com/users/9706",
"pm_score": 0,
"selected": false,
"text": "main() counter = 0 for() decimal == 0 scanf() calloc() free() temp #include <stdio.h>\n#include <stdlib.h>\n\nvoid convert(int decimal, int base, int *counter, int temp[])\n{\n int remainder;\n int quotient;\n int i = 0;\n while (decimal > 0)\n {\n remainder = decimal % base; // remainder is stored\n quotient = (decimal - remainder) / base; //quotient is stored\n decimal = quotient; // decimal is assigned quotient for next operation\n (*counter)++; //counter is incremented so we can printf correct lentgh of array\n temp[i] = remainder; // sets our array at i = remainder\n i = i + 1; //to increment i for every decimal > 0\n }\n}\n\nint main ()\n{\n int counter = 0;\n int decimal;\n int base;\n\n //enterNumbers(decimal, base); // doesnt work yet\n\n printf(\"enter decimal:\");\n if(scanf(\"%d\", &decimal) != 1) {\n printf(\"scanf failed\\n\");\n return 1;\n }\n printf(\"enter base:\");\n if(scanf(\"%d\", &base) != 1) {\n printf(\"scanf failed\\n\");\n return 1;\n }\n // gets input decimal and base\n int *temp = calloc(decimal, sizeof(int));\n if(!temp) {\n printf(\"calloc failed\\n\");\n return 1;\n }\n // alloc memory for array, worst case base = 1\n printf(\"decimal:%d, base:%d\", decimal, base);\n // for test\n\n convert(decimal + 1, base, &counter, temp);\n // converts decimal into base number and sorts into array\n\n for (int i = 0; i < counter; i++)\n {\n printf(\" %d,\", temp[i]);\n }\n //should printf the array, which is the base number\n free(temp);\n}\n enter decimal:10\nenter base:2\ndecimal:10, base:2 0, 1, 0, 1,\n 10 * sizeof(int) = 80 #include <stdio.h>\n#include <stdlib.h>\n#include <values.h>\n\nvoid print(size_t n, unsigned char a[n], const char *field_separator, const char *record_separator) {\n for(size_t i = 0; i < n; i++) {\n printf(\"%d%s\", a[i], i + 1 < n ? field_separator : record_separator);\n }\n}\n\nsize_t reverse(size_t n, unsigned char a[n]) {\n for(size_t i = 0; i < n/2; i++) {\n unsigned char tmp = a[i];\n a[i] = a[(n-1)-i];\n a[(n-1)-i] = tmp;\n }\n return n;\n}\n\nint convert(unsigned decimal, unsigned base, unsigned char temp[]) {\n int i = 0;\n for(; decimal > 0; i++) {\n temp[i] = decimal % base;\n decimal = (decimal - temp[i]) / base;\n }\n return reverse(i, temp);\n}\n\nint main(void) {\n printf(\"enter decimal: \");\n unsigned decimal;\n if(scanf(\"%u\", &decimal) != 1) {\n printf(\"scanf failed\\n\");\n return 1;\n }\n\n printf(\"enter base: \");\n unsigned base;\n if(scanf(\"%u\", &base) != 1) {\n printf(\"scanf failed\\n\");\n return 1;\n }\n if(base < 2 || base > 10) {\n printf(\"base must be between 2 and 10\\n\");\n return 1;\n }\n\n unsigned char temp[sizeof(int) * CHAR_BIT];\n int counter = convert(decimal, base, temp);\n print(counter, temp, \", \", \"\\n\");\n}\n enter decimal: 10\nenter base: 2\n1, 0, 1, 0\n"
},
{
"answer_id": 74610362,
"author": "Aconcagua",
"author_id": 1312382,
"author_profile": "https://Stackoverflow.com/users/1312382",
"pm_score": 1,
"selected": false,
"text": "main for void convert(int decimal, int base, int* counter, int temp[])\n// ^ (!)\n{\n // code as is, but use *counter instead of counter now\n}\n temp int temp[] int* temp i *counter i convert(decimal, base, &counter, temp);\n// ^ (!)\n i size_t convert(int decimal, int base, temp)\n{\n size_t i = 0;\n // rest as you have, dropping any references to counter\n return i;\n}\n size_t #include<stddef.h> unsigned int int decimal convert temp free(temp) calloc scanf scanf 1210dal fgets"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19842804/"
] |
74,609,823
|
<p>I am making a function that gets the students' Id, score, last name, and first name and compares them according to their Score, then the last name, and then the first name and prints the result in the descending format.</p>
<p>I have used a Comparator to compare the elements of the array. The problem is that when the user enters <code>-1</code> as <code>score</code> or <code>ID</code>, the program needs to break and show the result but when I use break, it will add a null value to my array which prevents comparing.</p>
<p>This is my code:</p>
<pre><code>import java.util.Arrays;
import java.util.Scanner;
import java.util.*;
public class Main {
private static class Student {
String fName;
String lName;
int id;
int score;
public Student(String fName, String lName, int id, int score) {
this.fName = fName;
this.lName = lName;
this.id = id;
this.score = score;
}
public int getScore() {
return score;
}
public String getFirstName() {
return fName;
}
public String getLastName() {
return lName;
}
public int getId() {
return id;
}
@Override
public String toString() {
return "id: " + this.id + " " + "fName: " + this.fName + " " + "lName: " + this.lName + " " + "score: " + this.score;
}
}
public static boolean alphabetic(String str) {
char[] charArray = str.toCharArray();
for (char c : charArray) {
if (!Character.isLetter(c)) {
if (c != ' ') {
return false;
}
}
}
return true;
}
static class Comparators implements Comparator<Student> {
@Override
public int compare(Student s1, Student s2) {
int n = Integer.compare(s2.getScore(), s1.getScore());
if (n == 0) {
int last = s1.getLastName().compareTo(s2.getLastName());
return last == 0 ? s1.getFirstName().compareTo(s2.getFirstName()) : last;
} else {
return n;
}
}
}
public static void main(String[] args) {
System.out.println("Enter the number of students");
Scanner input = new Scanner(System.in);
HashSet<Integer> used = new HashSet<>();
List<List<Object>> listData = new ArrayList<List<Object>>();
int k = input.nextInt();
Student[] students = new Student[k];
for (int i = 0; i < k; ) {
System.out.println("Enter id");
int id = input.nextInt();
if (id == -1) {
break;
}
input.nextLine();
System.out.println("Enter first name ");
String fName;
while (alphabetic(fName = input.nextLine()) == false) {
System.out.println("Wrong! please enter again");
}
fName = fName.replace(" ", "");
System.out.println("Enter last name ");
String lName;
while (alphabetic(lName = input.nextLine()) == false) {
System.out.println("Wrong! please enter again");
}
lName = lName.replace(" ", "");
System.out.println("Enter score ");
int score = input.nextInt();
if (score == -1) {
break;
}
if (used.contains(id)) {
listData.add(Arrays.asList(id, lName, fName, score));
continue;
}
used.add(id);
students[i++] = new Student(fName, lName, id, score);
}
Arrays.toString(students);
System.out.println(Arrays.toString(students));
Arrays.sort(students, new Comparators());
Arrays.toString(students);
System.out.println("Data without duplication:");
for (int i = 0; i < k; i++) {
System.out.println(students[i]);
}
if (listData.toArray().length == 0) {
System.out.println("No duplicated Data");
} else {
System.out.println("Data with duplication:");
System.out.println("ID/ LastName/Name/ Score");
System.out.println(Arrays.toString(listData.toArray()));
}
</code></pre>
<p>I have tried nullhandlingExpectation methods but I could not get the result I want.</p>
<p>Is there any method to avoid adding the null value to the array while breaking, or remove the null from the array before comparing?</p>
|
[
{
"answer_id": 74609960,
"author": "Allan Wind",
"author_id": 9706,
"author_profile": "https://Stackoverflow.com/users/9706",
"pm_score": 0,
"selected": false,
"text": "main() counter = 0 for() decimal == 0 scanf() calloc() free() temp #include <stdio.h>\n#include <stdlib.h>\n\nvoid convert(int decimal, int base, int *counter, int temp[])\n{\n int remainder;\n int quotient;\n int i = 0;\n while (decimal > 0)\n {\n remainder = decimal % base; // remainder is stored\n quotient = (decimal - remainder) / base; //quotient is stored\n decimal = quotient; // decimal is assigned quotient for next operation\n (*counter)++; //counter is incremented so we can printf correct lentgh of array\n temp[i] = remainder; // sets our array at i = remainder\n i = i + 1; //to increment i for every decimal > 0\n }\n}\n\nint main ()\n{\n int counter = 0;\n int decimal;\n int base;\n\n //enterNumbers(decimal, base); // doesnt work yet\n\n printf(\"enter decimal:\");\n if(scanf(\"%d\", &decimal) != 1) {\n printf(\"scanf failed\\n\");\n return 1;\n }\n printf(\"enter base:\");\n if(scanf(\"%d\", &base) != 1) {\n printf(\"scanf failed\\n\");\n return 1;\n }\n // gets input decimal and base\n int *temp = calloc(decimal, sizeof(int));\n if(!temp) {\n printf(\"calloc failed\\n\");\n return 1;\n }\n // alloc memory for array, worst case base = 1\n printf(\"decimal:%d, base:%d\", decimal, base);\n // for test\n\n convert(decimal + 1, base, &counter, temp);\n // converts decimal into base number and sorts into array\n\n for (int i = 0; i < counter; i++)\n {\n printf(\" %d,\", temp[i]);\n }\n //should printf the array, which is the base number\n free(temp);\n}\n enter decimal:10\nenter base:2\ndecimal:10, base:2 0, 1, 0, 1,\n 10 * sizeof(int) = 80 #include <stdio.h>\n#include <stdlib.h>\n#include <values.h>\n\nvoid print(size_t n, unsigned char a[n], const char *field_separator, const char *record_separator) {\n for(size_t i = 0; i < n; i++) {\n printf(\"%d%s\", a[i], i + 1 < n ? field_separator : record_separator);\n }\n}\n\nsize_t reverse(size_t n, unsigned char a[n]) {\n for(size_t i = 0; i < n/2; i++) {\n unsigned char tmp = a[i];\n a[i] = a[(n-1)-i];\n a[(n-1)-i] = tmp;\n }\n return n;\n}\n\nint convert(unsigned decimal, unsigned base, unsigned char temp[]) {\n int i = 0;\n for(; decimal > 0; i++) {\n temp[i] = decimal % base;\n decimal = (decimal - temp[i]) / base;\n }\n return reverse(i, temp);\n}\n\nint main(void) {\n printf(\"enter decimal: \");\n unsigned decimal;\n if(scanf(\"%u\", &decimal) != 1) {\n printf(\"scanf failed\\n\");\n return 1;\n }\n\n printf(\"enter base: \");\n unsigned base;\n if(scanf(\"%u\", &base) != 1) {\n printf(\"scanf failed\\n\");\n return 1;\n }\n if(base < 2 || base > 10) {\n printf(\"base must be between 2 and 10\\n\");\n return 1;\n }\n\n unsigned char temp[sizeof(int) * CHAR_BIT];\n int counter = convert(decimal, base, temp);\n print(counter, temp, \", \", \"\\n\");\n}\n enter decimal: 10\nenter base: 2\n1, 0, 1, 0\n"
},
{
"answer_id": 74610362,
"author": "Aconcagua",
"author_id": 1312382,
"author_profile": "https://Stackoverflow.com/users/1312382",
"pm_score": 1,
"selected": false,
"text": "main for void convert(int decimal, int base, int* counter, int temp[])\n// ^ (!)\n{\n // code as is, but use *counter instead of counter now\n}\n temp int temp[] int* temp i *counter i convert(decimal, base, &counter, temp);\n// ^ (!)\n i size_t convert(int decimal, int base, temp)\n{\n size_t i = 0;\n // rest as you have, dropping any references to counter\n return i;\n}\n size_t #include<stddef.h> unsigned int int decimal convert temp free(temp) calloc scanf scanf 1210dal fgets"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20315005/"
] |
74,609,829
|
<p>Exercise: “Let’s go Grocery Shopping”</p>
<p>A mother wants to list down the things she needs to buy, however, she needs a simple list that be run every time and can be modified whenever she changes her mind.
Starting with just an empty list, write a function that creates a grocery list that does the following:</p>
<p>• Add an Item (takes a string input from the user and add it to the existing list)</p>
<p>• Remove an Item (takes a string input from the user and removes all instances from the list)</p>
<p>• Print entire list (prints out all the contents of the list)</p>
<p>• Exit (exit the program)</p>
<p>The items are taken and stored as strings. Duplicates are allowed. When removing an item, it must not be case sensitive when matching with the item in the list for it to be removed (in other words “Eggs” and “eggS” still refer to the same item). The program should still continue running until the user decides the terminate it by doing the Exit command. Otherwise, it should catch all errors whenever possible.</p>
<p><a href="https://i.stack.imgur.com/tPT88.png" rel="nofollow noreferrer">mycode</a>
This is my code. I have a problem in remove function, it should remove all the duplicates despite the letter case. What should my code be? Thank you.</p>
|
[
{
"answer_id": 74609960,
"author": "Allan Wind",
"author_id": 9706,
"author_profile": "https://Stackoverflow.com/users/9706",
"pm_score": 0,
"selected": false,
"text": "main() counter = 0 for() decimal == 0 scanf() calloc() free() temp #include <stdio.h>\n#include <stdlib.h>\n\nvoid convert(int decimal, int base, int *counter, int temp[])\n{\n int remainder;\n int quotient;\n int i = 0;\n while (decimal > 0)\n {\n remainder = decimal % base; // remainder is stored\n quotient = (decimal - remainder) / base; //quotient is stored\n decimal = quotient; // decimal is assigned quotient for next operation\n (*counter)++; //counter is incremented so we can printf correct lentgh of array\n temp[i] = remainder; // sets our array at i = remainder\n i = i + 1; //to increment i for every decimal > 0\n }\n}\n\nint main ()\n{\n int counter = 0;\n int decimal;\n int base;\n\n //enterNumbers(decimal, base); // doesnt work yet\n\n printf(\"enter decimal:\");\n if(scanf(\"%d\", &decimal) != 1) {\n printf(\"scanf failed\\n\");\n return 1;\n }\n printf(\"enter base:\");\n if(scanf(\"%d\", &base) != 1) {\n printf(\"scanf failed\\n\");\n return 1;\n }\n // gets input decimal and base\n int *temp = calloc(decimal, sizeof(int));\n if(!temp) {\n printf(\"calloc failed\\n\");\n return 1;\n }\n // alloc memory for array, worst case base = 1\n printf(\"decimal:%d, base:%d\", decimal, base);\n // for test\n\n convert(decimal + 1, base, &counter, temp);\n // converts decimal into base number and sorts into array\n\n for (int i = 0; i < counter; i++)\n {\n printf(\" %d,\", temp[i]);\n }\n //should printf the array, which is the base number\n free(temp);\n}\n enter decimal:10\nenter base:2\ndecimal:10, base:2 0, 1, 0, 1,\n 10 * sizeof(int) = 80 #include <stdio.h>\n#include <stdlib.h>\n#include <values.h>\n\nvoid print(size_t n, unsigned char a[n], const char *field_separator, const char *record_separator) {\n for(size_t i = 0; i < n; i++) {\n printf(\"%d%s\", a[i], i + 1 < n ? field_separator : record_separator);\n }\n}\n\nsize_t reverse(size_t n, unsigned char a[n]) {\n for(size_t i = 0; i < n/2; i++) {\n unsigned char tmp = a[i];\n a[i] = a[(n-1)-i];\n a[(n-1)-i] = tmp;\n }\n return n;\n}\n\nint convert(unsigned decimal, unsigned base, unsigned char temp[]) {\n int i = 0;\n for(; decimal > 0; i++) {\n temp[i] = decimal % base;\n decimal = (decimal - temp[i]) / base;\n }\n return reverse(i, temp);\n}\n\nint main(void) {\n printf(\"enter decimal: \");\n unsigned decimal;\n if(scanf(\"%u\", &decimal) != 1) {\n printf(\"scanf failed\\n\");\n return 1;\n }\n\n printf(\"enter base: \");\n unsigned base;\n if(scanf(\"%u\", &base) != 1) {\n printf(\"scanf failed\\n\");\n return 1;\n }\n if(base < 2 || base > 10) {\n printf(\"base must be between 2 and 10\\n\");\n return 1;\n }\n\n unsigned char temp[sizeof(int) * CHAR_BIT];\n int counter = convert(decimal, base, temp);\n print(counter, temp, \", \", \"\\n\");\n}\n enter decimal: 10\nenter base: 2\n1, 0, 1, 0\n"
},
{
"answer_id": 74610362,
"author": "Aconcagua",
"author_id": 1312382,
"author_profile": "https://Stackoverflow.com/users/1312382",
"pm_score": 1,
"selected": false,
"text": "main for void convert(int decimal, int base, int* counter, int temp[])\n// ^ (!)\n{\n // code as is, but use *counter instead of counter now\n}\n temp int temp[] int* temp i *counter i convert(decimal, base, &counter, temp);\n// ^ (!)\n i size_t convert(int decimal, int base, temp)\n{\n size_t i = 0;\n // rest as you have, dropping any references to counter\n return i;\n}\n size_t #include<stddef.h> unsigned int int decimal convert temp free(temp) calloc scanf scanf 1210dal fgets"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20630177/"
] |
74,609,836
|
<p>I am doing a node.js <a href="https://youtu.be/JmJ1WUoUIK4?t=13552" rel="nofollow noreferrer">manual</a> and trying to display the information obtained from <a href="https://jsonplaceholder.typicode.com/posts" rel="nofollow noreferrer">jsonplaceholder</a></p>
<pre><code>app.get('/posts', async (req, res) => {
const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
console.log(typeof response.data);
console.log(response.data);
res.render('posts',{
posts: response.data,
});
});
</code></pre>
<p>I see in the console that the data obtained is in an unreadable format</p>
<p>when validating the valid data type that it is a string when it should be an object (json).</p>
<p><a href="https://i.stack.imgur.com/ib6zR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ib6zR.png" alt="enter image description here" /></a></p>
<p><strong>I don't know if <a href="https://jsonplaceholder.typicode.com/posts" rel="nofollow noreferrer">jsonplaceholder</a> changed the way to present your information or what additional code I should add to be able to display the information in my template.</strong></p>
<p>Template code</p>
<pre><code><%- include('partials/header'); %>
<h1>Posts</h1>
<p><%= posts %></p>
<% for(let i = 0; i < posts.length; i++) { %>
<article>
<h1><%= posts[i].title %></h1>
<p><%= posts[i].body %></p>
</article>
<% } %>
<%- include('partials/footer'); %>
</code></pre>
<p>The template shows the tag that loads all request.data because of the tag <code><p><%= posts %></p></code></p>
<p><a href="https://i.stack.imgur.com/YY57S.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YY57S.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74610268,
"author": "iiromutikainen",
"author_id": 15104470,
"author_profile": "https://Stackoverflow.com/users/15104470",
"pm_score": 2,
"selected": true,
"text": "axios"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5125876/"
] |
74,609,852
|
<p>Hi when I assign the simple setTimeOut() function to a variable and console the variable, it produces some integer value as below:</p>
<p><a href="https://i.stack.imgur.com/XBHvV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XBHvV.png" alt="enter image description here" /></a></p>
<p>So, I want clarification on what the value denotes. The value is changing when I try the same again. So please provide me an explanation of the value we get while assigning the setTimeOut() to a variable.</p>
|
[
{
"answer_id": 74610268,
"author": "iiromutikainen",
"author_id": 15104470,
"author_profile": "https://Stackoverflow.com/users/15104470",
"pm_score": 2,
"selected": true,
"text": "axios"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19541341/"
] |
74,609,867
|
<p>Why do I get this error when I make my page an async function? everything works fine when it isn't an async function. The only difference is that it returns a pending object which isn't what I want.</p>
<p>this is how I fetch the data:</p>
<pre><code>const getData = async (id) => {
const res = await fetch({
url: "http://localhost:3000/api/user/getOne",
method: "POST",
credentials: true,
body: {
userId: "637846eb8f36e20663a9c948",
},
});
return res;
</code></pre>
<p>};</p>
<p>and then this is the page function</p>
<pre><code>export default async function Page() {
const profileData = await getData();
useEffect(() => {
console.log(profileData);
}, []);
return(<div><p>Hello</p></div>)
}
</code></pre>
<p>I think the problem has to do with the async function and the await. How do I fix this?</p>
|
[
{
"answer_id": 74609881,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 1,
"selected": false,
"text": "export default function Page() { \n \n useEffect(() => { \n \n const getAll= async () => {\n const profileData = await getData();\n console.log(profileData);\n\n };\n\n getAll(); // run it, run it\n }, []);\n \n return(<div><p>Hello</p></div>)\n}\n"
},
{
"answer_id": 74610082,
"author": "Ha Tai",
"author_id": 14036048,
"author_profile": "https://Stackoverflow.com/users/14036048",
"pm_score": 1,
"selected": false,
"text": "import { useState } from \"react\";\n\nexport default async function Page() {\n const [profileData, setProfileData] = useState([]);\n async function initDate() {\n const response = await getData();\n setProfileData(response);\n }\n useEffect(() => {\n initDate();\n console.log(profileData);\n }, []);\n return (<div><p>Hello</p></div>)\n}\n"
},
{
"answer_id": 74610929,
"author": "Amirhossein",
"author_id": 11342834,
"author_profile": "https://Stackoverflow.com/users/11342834",
"pm_score": 0,
"selected": false,
"text": "useEffect(() => {\n // your code\n}, []);\n useEffect(() => {\n // your code\n}, [/* list of the dependencies */]);\n useEffect(() => {\n const getProfileData = async () => {\n await getData();\n }\n\n getProfileData();\n}, []);\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13586781/"
] |
74,609,896
|
<p>Hello my code is basically on collision it will start the coroutine of slowing the enemy then after 3.2 seconds it reverts back to original.</p>
<pre><code> private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag == "slowProjectile")
{
StartCoroutine(slowEnemy());
}
}
// FROZEN ENEMY BEHAVIOUR
public bool isFrozen = true;
IEnumerator slowEnemy()
{
if (isFrozen == true)
{
isFrozen = false;
Debug.Log("FROZEN");
// Turns the enemy into color blue
this.GetComponent<SpriteRenderer>().color = Color.blue;
enemyMovementSpeed = enemyMovementSpeed / 2;
// waits for 3.2 seconds
yield return new WaitForSeconds(3.2f);
// Then return the enemy movement speed and color to its original state.
enemyMovementSpeed = enemyMovementSpeed * 2;
this.GetComponent<SpriteRenderer>().color = Color.white;
}
else
{
isFrozen = true;
}
}
</code></pre>
<p>problem is the coroutine is stacking meaning it will run x2 and lost the original value also the projectile fires every 3 seconds. Think of it as A shooter that shoots every 3 seconds and on impact slows the enemy for 3 seconds. ( Like a Snow Pea if you play Plants Vs Zombie )</p>
|
[
{
"answer_id": 74609999,
"author": "Willard Peng",
"author_id": 10259001,
"author_profile": "https://Stackoverflow.com/users/10259001",
"pm_score": 1,
"selected": true,
"text": "the Frozen effect doesn't stack public bool isFrozen = false;\n\nprivate void OnTriggerEnter2D(Collider2D collision)\n{\n if (collision.tag == \"slowProjectile\")\n {\n if (!isFrozen)\n {\n StartCoroutine(slowEnemy());\n } \n }\n}\n\nIEnumerator slowEnemy()\n{\n isFrozen = true;\n \n Debug.Log(\"FROZEN\");\n // Turns the enemy into color blue\n this.GetComponent<SpriteRenderer>().color = Color.blue;\n enemyMovementSpeed = enemyMovementSpeed / 2;\n\n // waits for 3.2 seconds \n yield return new WaitForSeconds(3.2f);\n\n // Then return the enemy movement speed and color to its original state.\n enemyMovementSpeed = enemyMovementSpeed * 2;\n this.GetComponent<SpriteRenderer>().color = Color.white; \n \n isFrozen = false;\n}\n while the Speed Change doesn't stack, the Frozen Time neither stack the Frozen Time and not stack Speed Change at the same time Forzen Stack Counter public int forenStackCount = 0;\n\nprivate void OnTriggerEnter2D(Collider2D collision)\n{\n if (collision.tag == \"slowProjectile\")\n { \n StartCoroutine(slowEnemy());\n }\n}\n\nprivate IEnumerator slowEnemy()\n{\n if (forenStackCount == 0)\n {\n StartFrozenEffect();\n }\n\n forenStackCount++;\n\n yield return new WaitForSeconds(3.2f);\n\n forenStackCount--;\n\n if (forenStackCount == 0)\n {\n EndFrozenEffect();\n }\n}\n\nprivate void StartFrozenEffect()\n{\n Debug.Log(\"FROZEN\");\n // Turns the enemy into color blue\n this.GetComponent<SpriteRenderer>().color = Color.blue;\n enemyMovementSpeed = enemyMovementSpeed / 2;\n}\n\nprivate void EndFrozenEffect()\n{\n enemyMovementSpeed = enemyMovementSpeed * 2;\n this.GetComponent<SpriteRenderer>().color = Color.white;\n} \n"
},
{
"answer_id": 74611305,
"author": "Everts",
"author_id": 1429487,
"author_profile": "https://Stackoverflow.com/users/1429487",
"pm_score": 1,
"selected": false,
"text": "private float m_timer;\nprivate IEnumerator m_coroutine;\n\nprivate void OnTriggerEnter2D(Collider2D collision)\n{\n if (collision.tag == \"slowProjectile\")\n { \n m_timer = 0f;\n if (m_coroutine == null){\n m_coroutine = FreezeTime();\n StartCoroutine(m_coroutine);\n } \n }\n}\n\nIEnumerator FreezeTime()\n{\n while (m_timer < 3.2f){\n m_timer += Time.deltaTime;\n yield return null;\n }\n m_coroutine = null;\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20449786/"
] |
74,609,908
|
<p>I have SQLite DB one table contains datetime field</p>
<p>with datatype "timestamp" REAL value is 18696.0</p>
<p><a href="https://i.stack.imgur.com/NR1j5.png" rel="nofollow noreferrer">attach image for table structure</a></p>
<p>So, I want this 18696.0 value to be converted into MySQL Y-m-d format and result should be 2021-03-10</p>
<p>I have didn't found any solution online. any help would be appreciated.</p>
<p>SQLite timestamp converted into MySQL timestamp.</p>
|
[
{
"answer_id": 74609955,
"author": "Coderio",
"author_id": 13379052,
"author_profile": "https://Stackoverflow.com/users/13379052",
"pm_score": -1,
"selected": false,
"text": "<?php\n echo date('Y-m-d H:i:s', 17889);\n?>\n 1970-01-01 04:58:09"
},
{
"answer_id": 74610034,
"author": "Jacob Mulquin",
"author_id": 1427345,
"author_profile": "https://Stackoverflow.com/users/1427345",
"pm_score": 1,
"selected": false,
"text": "function realDateToYmd($real, $outputFormat='Y-m-d')\n{\n $date = new DateTime('1970-01-01');\n $date->modify('+' . intval($real) . ' days');\n \n return $date->format($outputFormat);\n}\n\necho realDateToYmd('18696.0');\n// returns 2021-03-10\n REAL jdtogregorian function JDtoISO8601($JD) {\n if ($JD <= 1721425) $JD += 365;\n list($month, $day, $year) = explode('/', jdtogregorian($JD));\n return sprintf('%+05d-%02d-%02d', $year, $month, $day);\n}\n\necho JDtoISO8601('17889.0');\n// Results in -4664-11-16\n"
},
{
"answer_id": 74624405,
"author": "jspit",
"author_id": 7271221,
"author_profile": "https://Stackoverflow.com/users/7271221",
"pm_score": 0,
"selected": false,
"text": "$days = 18696.0;\n\n$dt = date_create('@'.((int)($days * 86400)));\n$mysqlDate = $dt->format('Y-m-d'); //\"2021-03-10\"\n $mySqlDate = gmdate('Y-m-d',$days*86400);\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20470803/"
] |
74,609,923
|
<pre><code>const BottomTabCard=({props,navigation})=> {
const [isActive, setIsActive] = useState('');
return (
<View
style={[
styles.container,
{height: props.TabHeight, width: props.TabWidth},
]}>
<View style={{flexDirection: 'row'}}>
<TouchableOpacity onPress={() => setIsActive('home')}>
<Icons
name="home"
size={35}
style={[
styles.iconHome,
{color: isActive == 'home' ? 'green' : 'grey'},
]}
/>
</TouchableOpacity>
<TouchableOpacity onPress={() => setIsActive('shopping-cart')}>
<Icons
name="shopping-cart"
size={35}
style={[
styles.iconCart,
{color: isActive == 'shopping-cart' ? 'green' : 'grey'},
]}
/>
</TouchableOpacity>
<TouchableOpacity onPress={() => setIsActive('search')}>
<Icons
name="search"
size={35}
style={[
styles.iconSearch,
{color: isActive == 'search' ? 'green' : 'grey'},
]}
/>
</TouchableOpacity>
<TouchableOpacity onPress={() => setIsActive('person')}>
<Icons
name="person"
size={35}
style={[
styles.iconPerson,
{color: isActive == 'person' ? 'green' : 'grey'},
]}
/>
</TouchableOpacity>
<TouchableOpacity onPress={() => setIsActive('credit-card'),{navigation.navigate(ROUTE_NAME.ORDER)}}>
<Icons
name="credit-card"
size={35}
style={[
styles.iconCard,
{color: isActive == 'credit-card' ? 'green' : 'grey'},
]}
/>
</TouchableOpacity>
</View>
</View>
);
}
export default BottomTabCard;
</code></pre>
<p>I want to navigate creditcard icon to corressponding page, But it shows the error</p>
<p>** TypeError: Cannot read property 'TabHeight' of undefined**</p>
<pre><code>This error is located at:
in BottomTabCard (created by Login)
in RCTView (created by View)
in View (created by Login)
in Login (created by SceneView)
in StaticContainer
in EnsureSingleNavigator (created by SceneView)
in SceneView (created by SceneView)
in RCTView (created by View)
in View (created by DebugContainer)
in DebugContainer (created by MaybeNestedStack)
in MaybeNestedStack (created by SceneView)
in RCTView (created by View)
in View (created by SceneView)
in RNSScreen (created by AnimatedComponent)
in AnimatedComponent
in AnimatedComponentWrapper (created by InnerScreen)
in Suspender (created by Freeze)
in Suspense (created by Freeze)
in Freeze (created by DelayedFreeze)
in DelayedFreeze (created by InnerScreen)
in InnerScreen (created by Screen)
in Screen (created by SceneView)
in SceneView (created by NativeStackViewInner)
in Suspender (created by Freeze)
in Suspense (created by Freeze)
in Freeze (created by DelayedFreeze)
in DelayedFreeze (created by ScreenStack)
in RNSScreenStack (created by ScreenStack)
in ScreenStack (created by NativeStackViewInner)
in NativeStackViewInner (created by NativeStackView)
in RNCSafeAreaProvider (created by SafeAreaProvider)
in SafeAreaProvider (created by SafeAreaInsetsContext)
in SafeAreaProviderCompat (created by NativeStackView)
in NativeStackView (created by NativeStackNavigator)
in PreventRemoveProvider (created by NavigationContent)
in NavigationContent
in Unknown (created by NativeStackNavigator)
in NativeStackNavigator (created by MyStack)
in MyStack (created by Route)
in EnsureSingleNavigator
in BaseNavigationContainer
in ThemeProvider
in NavigationContainerInner (created by Route)
in Route (created by App)
in Provider (created by App)
in App
in RCTView (created by View)
in View (created by AppContainer)
in RCTView (created by View)
in View (created by AppContainer)
in AppContainer
in behalal(RootComponent), js engine: hermes
</code></pre>
<p>Here I am using custom component as BottomTabCard
Is is it possible to both props and navigation in functional component together.</p>
<p>in Login page I worte,</p>
<p>Login page contains all other card componets</p>
|
[
{
"answer_id": 74609955,
"author": "Coderio",
"author_id": 13379052,
"author_profile": "https://Stackoverflow.com/users/13379052",
"pm_score": -1,
"selected": false,
"text": "<?php\n echo date('Y-m-d H:i:s', 17889);\n?>\n 1970-01-01 04:58:09"
},
{
"answer_id": 74610034,
"author": "Jacob Mulquin",
"author_id": 1427345,
"author_profile": "https://Stackoverflow.com/users/1427345",
"pm_score": 1,
"selected": false,
"text": "function realDateToYmd($real, $outputFormat='Y-m-d')\n{\n $date = new DateTime('1970-01-01');\n $date->modify('+' . intval($real) . ' days');\n \n return $date->format($outputFormat);\n}\n\necho realDateToYmd('18696.0');\n// returns 2021-03-10\n REAL jdtogregorian function JDtoISO8601($JD) {\n if ($JD <= 1721425) $JD += 365;\n list($month, $day, $year) = explode('/', jdtogregorian($JD));\n return sprintf('%+05d-%02d-%02d', $year, $month, $day);\n}\n\necho JDtoISO8601('17889.0');\n// Results in -4664-11-16\n"
},
{
"answer_id": 74624405,
"author": "jspit",
"author_id": 7271221,
"author_profile": "https://Stackoverflow.com/users/7271221",
"pm_score": 0,
"selected": false,
"text": "$days = 18696.0;\n\n$dt = date_create('@'.((int)($days * 86400)));\n$mysqlDate = $dt->format('Y-m-d'); //\"2021-03-10\"\n $mySqlDate = gmdate('Y-m-d',$days*86400);\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19254334/"
] |
74,609,928
|
<p>whenever I try to full screen my application, it doesn't scale. I've made multiple copies of this application trying different methods but none seem to work right.</p>
<p>First attempt: Application was a <code>Parent</code>, it would scale the background but the elements inside wouldn't scale to screen size.</p>
<p><a href="https://i.stack.imgur.com/pFp1C.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pFp1C.png" alt="As a Parent" /></a></p>
<p>As an update: here is the actual <code>Parent</code> that was made. The layout is the original one I wrote and has no issues when it's windowed. It has a preset <code>WIDTH</code> and <code>HEIGHT</code> but when full screened, The first example picture is what it looks like where the <code>WIDTH</code> of the the <code>TextField</code> doesn't update (since it's preset and not updating to the highest <code>WIDTH</code> of the screen it's running on). There are two parts to this that CAN be fixed when only one is fixed. The displayed <code>Text</code> has a set wrapping length of the console, though it is set by using <code>WIDTH</code>.</p>
<p>Here's what the console looks like when it's windowed:
<a href="https://i.stack.imgur.com/8Sk85.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8Sk85.png" alt="enter image description here" /></a></p>
<p>If I could find a way to change the <code>WIDTH</code>, I'm thinking this can be fixed for both the <code>TextField</code> and the <code>setWrappingWidth()</code>.</p>
<pre><code>package application.console;
import application.areas.startingArea.SA;
import application.areas.vanguardForest.VFCmds;
import application.areas.vanguardForest.VFNavi;
import application.areas.vanguardForest.VFPkups;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Parent;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.ScrollPane.ScrollBarPolicy;
import javafx.scene.control.TextField;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
public class Ce extends Region {
public static boolean fullscreen = false;
public static double WIDTH = 990;
// 990;
// Screen.getPrimary().getBounds().getMaxX();
public static double HEIGHT = 525;
// 525;
// Screen.getPrimary().getBounds().getMaxY();
public static Font Cinzel = (Font.loadFont("file:fonts/static/Cinzel-Medium.ttf", 16));
public static VBox console = new VBox(2);
public static TextField input = new TextField();
public static ScrollPane scroll = new ScrollPane();
public static BorderPane root = new BorderPane();
public static String s;
public static Parent Window() {
root.setMinSize(WIDTH, (HEIGHT - input.getHeight()));
root.setStyle("-fx-background-color: #232323;");
scroll.setContent(console);
root.setCenter(scroll);
scroll.setStyle("-fx-background: #232323;"
+ "-fx-background-color: transparent;"
+ "-fx-border-color: #232323;"
+ "-fx-focus-color: #232323;"
);
scroll.setHbarPolicy(ScrollBarPolicy.NEVER);
scroll.setVbarPolicy(ScrollBarPolicy.NEVER);
scroll.setBackground(new Background(new BackgroundFill(Color.TRANSPARENT, null, null)));
console.setStyle("-fx-background-color: #232323;"
+ "-fx-focus-color: #232323;");
console.heightProperty().addListener(new ChangeListener<Object>() {
@Override
public void changed(ObservableValue<?> observable, Object oldValue, Object newValue) {
scroll.setVvalue((Double)newValue);
}
});
HBox hbox = new HBox();
hbox.setPrefSize(WIDTH, 16);
root.setBottom(hbox);
Text carrot = new Text(" >");
carrot.setFont(Font.loadFont("file:fonts/static/Cinzel-Medium.ttf", 26));
carrot.setFill(Color.WHITE);
input.setStyle("-fx-background-color: transparent;"
+ "-fx-text-fill: #FFFFFF;"
+ "-fx-highlight-fill: #FFFFFF;"
+ "-fx-highlight-text-fill: #232323;"
// + "-fx-border-color: #FFFFFF;"
// + "-fx-border-width: .5;"
);
input.setFont(Cinzel);
input.setMinWidth(console.getWidth());
input.setOnAction(e -> {
String s = (input.getText()).stripTrailing();
input.clear();
});
Pane pane = new Pane();
root.getChildren().add(pane);
hbox.getChildren().addAll(carrot, input);
return root;
}
</code></pre>
<p>This isn't the main issue as I've stated, once getting the scaled width for the <code>TextField</code> the process of for <code>setWrappingWidth()</code> for displaying the text should be the if a solution is found, here's how it goes:</p>
<pre><code>@SuppressWarnings("static-access")
public void print(String s, Color c) {
Ce Ce = new Ce();
HBox text1 = new HBox();
text1.setMinWidth(Ce.WIDTH);
text1.setMaxWidth(Ce.WIDTH);
Text tCarrot = new Text(" > ");
tCarrot.setFont(Ce.Cinzel);
tCarrot.setFill(c);
Text text2 = new Text();
final IntegerProperty i = new SimpleIntegerProperty(0);
Timeline tl = new Timeline();
KeyFrame kf = new KeyFrame(
Duration.seconds(textSpeed(fastText)),
e1 -> {
if(i.get() > s.length()) {
tl.stop();
} else {
text2.setText(s.substring(0, i.get()));
i.set(i.get() + 1);
}
});
tl.getKeyFrames().add(kf);
tl.setCycleCount(Animation.INDEFINITE);
tl.play();
text2.setFill(c);
text2.setFont(Ce.Cinzel);
text2.setWrappingWidth(Ce.WIDTH - 40);
text1.getChildren().addAll(tCarrot, text2);
Ce.console.getChildren().add(text1);
Ce.console.setMargin(text1, new Insets(5, 0, 0, 3));
}
</code></pre>
<p>Lastly, the <code>HEIGHT</code> of the <code>VBox</code> for the displayed <code>Text</code> works just as intended, it's just the setting/updating the <code>WIDTH</code> to set it to the size of the window whether Windowed of Full screened that is the main issue here.</p>
|
[
{
"answer_id": 74612801,
"author": "Mr.Typo",
"author_id": 14790684,
"author_profile": "https://Stackoverflow.com/users/14790684",
"pm_score": -1,
"selected": false,
"text": "import javafx.application.Application;\nimport javafx.beans.binding.Bindings;\nimport javafx.beans.binding.ObjectBinding;\nimport javafx.beans.property.SimpleDoubleProperty;\nimport javafx.event.EventHandler;\nimport javafx.geometry.Insets;\nimport javafx.geometry.Pos;\nimport javafx.scene.Parent;\nimport javafx.scene.Scene;\nimport javafx.scene.control.ScrollPane;\nimport javafx.scene.control.TextField;\nimport javafx.scene.input.ScrollEvent;\nimport javafx.scene.layout.*;\nimport javafx.scene.paint.Color;\nimport javafx.scene.text.Font;\nimport javafx.scene.text.Text;\nimport javafx.stage.Stage;\n\npublic class ConsoleTest extends Application {\n @Override\n public void start(Stage stage) {\n Scene scene = new Scene(new GameWindow().Console(), 600, 600);\n stage.setTitle(\"Console\");\n stage.setScene(scene);\n stage.show();\n }\n\n public static void main(String[] args) {\n launch();\n }\n}\n\nclass GameWindow {\n\n public static Console c = new Console();\n\n public Parent Console() {\n for (int i = 0; i < 100; i++) c.addText(new Text(\"Test\" + i));\n return c;\n }\n\n}\n\nclass Console extends BorderPane {\n\n private final SimpleDoubleProperty fontSize = new SimpleDoubleProperty(20);\n private final ObjectBinding<Font> fontBinding = Bindings.createObjectBinding(() -> Font.font(fontSize.get()), fontSize);\n\n private final VBox console;\n\n public Console() {\n console = new VBox();\n console.setBackground(new Background(new BackgroundFill(Color.BLACK, CornerRadii.EMPTY, Insets.EMPTY)));\n\n ScrollPane scroll = new ScrollPane(console);\n scroll.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);\n scroll.setVbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);\n scroll.setFitToHeight(true);\n scroll.setFitToWidth(true);\n scroll.setPadding(Insets.EMPTY);\n\n Text caret = new Text(\" >\");\n caret.fontProperty().bind(fontBinding);\n caret.setFill(Color.WHITE);\n\n TextField input = new TextField();\n input.setStyle(\"-fx-background-color: transparent;\" + \"-fx-text-fill: #FFFFFF;\" + \"-fx-highlight-fill: #FFFFFF;\" + \"-fx-highlight-text-fill: #232323;\");\n input.fontProperty().bind(fontBinding);\n\n HBox inputBar = new HBox(2, caret, input);\n inputBar.setStyle(\"-fx-background-color: #232323;\");\n inputBar.setAlignment(Pos.CENTER_LEFT);\n\n setCenter(scroll);\n setBottom(inputBar);\n\n EventHandler<ScrollEvent> scrollEvent = e -> {\n if (e.isControlDown()) {\n if (e.getDeltaY() > 0) {\n fontSize.set(fontSize.doubleValue() + 2);\n } else {\n double old;\n fontSize.set((old = fontSize.doubleValue()) < 10 ? old : old - 2);\n }\n e.consume();\n }\n };\n\n inputBar.setOnScroll(scrollEvent);\n console.setOnScroll(scrollEvent);\n }\n\n public void addText(Text text) {\n text.fontProperty().bind(fontBinding);\n text.setFill(Color.WHITE);\n console.getChildren().add(text);\n }\n}\n"
},
{
"answer_id": 74622040,
"author": "jewelsea",
"author_id": 1155209,
"author_profile": "https://Stackoverflow.com/users/1155209",
"pm_score": 2,
"selected": true,
"text": "import javafx.collections.FXCollections;\nimport javafx.collections.ObservableList;\nimport javafx.geometry.Pos;\nimport javafx.scene.control.*;\nimport javafx.scene.layout.*;\nimport javafx.scene.text.Text;\nimport javafx.stage.Stage;\n\npublic class Console extends VBox {\n private final ObservableList<String> consoleLog = FXCollections.observableArrayList();\n private final ListView<String> logView = new ListView<>(consoleLog);\n\n public Console(Stage stage) {\n VBox.setVgrow(logView, Priority.ALWAYS);\n\n HBox ribbon = createRibbon(\n createFullScreenToggle(stage)\n );\n ribbon.setMinHeight(HBox.USE_PREF_SIZE);\n\n getChildren().addAll(\n ribbon,\n logView\n );\n }\n\n private ToggleButton createFullScreenToggle(Stage stage) {\n ToggleButton fullScreenToggle = new ToggleButton(\"Toggle full screen\");\n fullScreenToggle.setOnAction(e ->\n stage.setFullScreen(\n fullScreenToggle.isSelected()\n )\n );\n \n return fullScreenToggle;\n }\n\n private HBox createRibbon(ToggleButton fullscreenToggle) {\n Text prompt = new Text(\">\");\n\n TextField input = new TextField();\n input.setOnAction(e -> {\n consoleLog.add(0, input.getText());\n logView.scrollTo(0);\n\n input.clear();\n });\n HBox.setHgrow(input, Priority.ALWAYS);\n\n HBox ribbon = new HBox(10, \n prompt, \n input, \n fullscreenToggle\n );\n ribbon.setAlignment(Pos.BASELINE_LEFT);\n\n return ribbon;\n }\n\n public ObservableList<String> getConsoleLog() {\n return consoleLog;\n }\n}\n import javafx.application.Application;\nimport javafx.scene.Scene;\nimport javafx.stage.Stage;\n\npublic class ConsoleApplication extends Application {\n @Override\n public void start(Stage stage) {\n Console console = new Console(stage);\n console.getConsoleLog().addAll(\n TEXT.lines().toList()\n );\n\n stage.setScene(\n new Scene(\n console\n )\n );\n\n stage.show();\n }\n\n public static void main(String[] args) {\n launch(args);\n }\n\n private static final String TEXT = \"\"\" \n W. Shakespeare - Sonnet 148\n O me, what eyes hath Love put in my head,\n Which have no correspondence with true sight!\n Or, if the have, where is my judgement fled,\n That censures falsely what they see aright?\n If that be fair whereon my false eyes dote,\n What means the world to say it is not so?\n If it be not, then love doth well denote\n Love’s eye is not so true as all men’s ‘No.’\n How can it? O, how can Love’s eye be true,\n That is so vex’d with watching and with tears?\n No marvel then, though I mistake my view;\n The sun itself sees not till heaven clears.\n O cunning Love! with tears thou keep’st me blind.\n Lest eyes well-seeing thy foul faults should find.\n \"\"\";\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18969521/"
] |
74,609,949
|
<p>i am trying to pass value from login and register into dashbord since sign is a unique compont i dont know how to pass log from login and register can someone help</p>
<p><strong>sign.js</strong></p>
<pre><code>export default function Sign({navigation}) {
async function onGoogleButtonPress() {
await GoogleSignin.hasPlayServices();
const userInfo = await GoogleSignin.signIn();
setuserInfo(userInfo);
navigation.navigate('dash', {userInfo});
}
return (
<View style={styles.prheight}>
<View style={styles.buttonw}>
<GoogleSigninButton
style={{width: 192, height: 48}}
size={GoogleSigninButton.Size.Wide}
color={GoogleSigninButton.Color.Light}
onPress={onGoogleButtonPress}
// disabled={this.state.isSigninInProgress}
/>
</View>
</View>
);
}
</code></pre>
<p><strong>register.js</strong></p>
<pre><code>export default function Register(props) {
return (
<View style={styles.prheight}>
<View style={styles.buttonw}>
<Sign navigation={props.navigation} log={name:"register"} />
</View>
</View>
);
}
</code></pre>
<p><strong>login</strong></p>
<pre><code>export default function login(props) {
return (
<View style={styles.prheight}>
<View style={styles.buttonw}>
<Sign navigation={props.navigation} log={name:"login"} />
</View>
</View>
</code></pre>
<p><strong>dash.js</strong></p>
<pre><code>export default function dash(props) {
const [text, setTextbaby] = useState();
const {userInfo} = props?.route?.params;
console.log(props.log);
</code></pre>
|
[
{
"answer_id": 74610145,
"author": "rafiulah",
"author_id": 17426448,
"author_profile": "https://Stackoverflow.com/users/17426448",
"pm_score": -1,
"selected": false,
"text": "async-storage react-navigation import { Text, View, Button } from 'react-native';\nimport { NavigationContainer } from '@react-navigation/native';\nimport { createNativeStackNavigator } from '@react-navigation/native-stack';\n\nfunction HomeScreen({ navigation }) {\n return (\n <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>\n <Text>Home Screen</Text>\n <Button\n title=\"Go to Details\"\n onPress={() => {\n /* 1. Navigate to the Details route with params */\n navigation.navigate('Details', {\n itemId: 86,\n otherParam: 'anything you want here',\n });\n }}\n />\n </View>\n );\n}\n\nfunction DetailsScreen({ route, navigation }) {\n /* 2. Get the param */\n const { itemId } = route.params;\n const { otherParam } = route.params;\n return (\n <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>\n <Text>Details Screen</Text>\n <Text>itemId: {JSON.stringify(itemId)}</Text>\n <Text>otherParam: {JSON.stringify(otherParam)}</Text>\n <Button\n title=\"Go to Details... again\"\n onPress={() =>\n navigation.push('Details', {\n itemId: Math.floor(Math.random() * 100),\n })\n }\n />\n <Button title=\"Go to Home\" onPress={() => navigation.navigate('Home')} />\n <Button title=\"Go back\" onPress={() => navigation.goBack()} />\n </View>\n );\n}\n\nconst Stack = createNativeStackNavigator();\n\nexport default function App() {\n return (\n <NavigationContainer>\n <Stack.Navigator>\n <Stack.Screen name=\"Home\" component={HomeScreen} />\n <Stack.Screen name=\"Details\" component={DetailsScreen} />\n </Stack.Navigator>\n </NavigationContainer>\n );\n}```\n"
},
{
"answer_id": 74610169,
"author": "Avetik Nersisyan",
"author_id": 14938670,
"author_profile": "https://Stackoverflow.com/users/14938670",
"pm_score": 3,
"selected": true,
"text": "log export default function Sign({ navigation, log }) {\n async function onGoogleButtonPress() {\n await GoogleSignin.hasPlayServices();\n const userInfo = await GoogleSignin.signIn();\n setuserInfo(userInfo);\n navigation.navigate('dash', {userInfo, log});\n }\n// some code\n\n}\n log props.route.params export default function dash(props) {\n const [text, setTextbaby] = useState();\n\n const {userInfo, log} = props?.route?.params;\n console.log(log);\n\n}\n log={{name: \"register\"}}\nlog={{name: \"login\"}}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17814678/"
] |
74,609,962
|
<p>I made this custom hook.</p>
<pre><code>import axios from "axios";
import Cookies from "js-cookie";
import React from "react";
const useGetConferList= () => {
let token = JSON.parse(localStorage.getItem("AuthToken"));
const Idperson = JSON.parse(Cookies.get("user")).IdPerson;
const [response, setResponse] = React.useState();
const fetchConfer= (datePrensence, idInsurance, timePrensence) => {
axios({
method: "post",
url: `${process.env.REACT_APP_API_URL_API_GET_ERJASERVICE_LIST}`,
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
data: JSON.stringify({
datePrensence,
idInsurance,
Idperson,
searchfield: "",
timePrensence: parseInt(timePrensence) * 60,
}),
})
.then((r) => {
setResponse(r.data.Data);
})
.catch(() => alert("NetworkError"));
};
return { fetchConfer, response };
};
export default useGetConferList;
</code></pre>
<p>as you can see I export the fetchConfer function. but I want to make it async. for example, calling the function and then doing something else like this:</p>
<pre><code>fetchConfer(Date, Time, Id).then((r) => {
if (search !== "") {
window.sessionStorage.setItem(
"searchList",
JSON.stringify(
r.data
)
);
}
});
</code></pre>
<p>as you can see in non async situation, I can't use <code>then</code>.</p>
|
[
{
"answer_id": 74610145,
"author": "rafiulah",
"author_id": 17426448,
"author_profile": "https://Stackoverflow.com/users/17426448",
"pm_score": -1,
"selected": false,
"text": "async-storage react-navigation import { Text, View, Button } from 'react-native';\nimport { NavigationContainer } from '@react-navigation/native';\nimport { createNativeStackNavigator } from '@react-navigation/native-stack';\n\nfunction HomeScreen({ navigation }) {\n return (\n <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>\n <Text>Home Screen</Text>\n <Button\n title=\"Go to Details\"\n onPress={() => {\n /* 1. Navigate to the Details route with params */\n navigation.navigate('Details', {\n itemId: 86,\n otherParam: 'anything you want here',\n });\n }}\n />\n </View>\n );\n}\n\nfunction DetailsScreen({ route, navigation }) {\n /* 2. Get the param */\n const { itemId } = route.params;\n const { otherParam } = route.params;\n return (\n <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>\n <Text>Details Screen</Text>\n <Text>itemId: {JSON.stringify(itemId)}</Text>\n <Text>otherParam: {JSON.stringify(otherParam)}</Text>\n <Button\n title=\"Go to Details... again\"\n onPress={() =>\n navigation.push('Details', {\n itemId: Math.floor(Math.random() * 100),\n })\n }\n />\n <Button title=\"Go to Home\" onPress={() => navigation.navigate('Home')} />\n <Button title=\"Go back\" onPress={() => navigation.goBack()} />\n </View>\n );\n}\n\nconst Stack = createNativeStackNavigator();\n\nexport default function App() {\n return (\n <NavigationContainer>\n <Stack.Navigator>\n <Stack.Screen name=\"Home\" component={HomeScreen} />\n <Stack.Screen name=\"Details\" component={DetailsScreen} />\n </Stack.Navigator>\n </NavigationContainer>\n );\n}```\n"
},
{
"answer_id": 74610169,
"author": "Avetik Nersisyan",
"author_id": 14938670,
"author_profile": "https://Stackoverflow.com/users/14938670",
"pm_score": 3,
"selected": true,
"text": "log export default function Sign({ navigation, log }) {\n async function onGoogleButtonPress() {\n await GoogleSignin.hasPlayServices();\n const userInfo = await GoogleSignin.signIn();\n setuserInfo(userInfo);\n navigation.navigate('dash', {userInfo, log});\n }\n// some code\n\n}\n log props.route.params export default function dash(props) {\n const [text, setTextbaby] = useState();\n\n const {userInfo, log} = props?.route?.params;\n console.log(log);\n\n}\n log={{name: \"register\"}}\nlog={{name: \"login\"}}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20395245/"
] |
74,609,978
|
<p>I am have a xml layout, when I set onClick in java code to imageview with the id <code>iv_contact</code> and imageview with id <code>iv_user</code>, the imageview on top doesn't work, it caught the onClick event of the bottom ImageView, how to solve this problem?</p>
<p>This is my xml layout:</p>
<pre><code><androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/cl_contains_content"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/iv_contact"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:scaleType="centerCrop" />
<androidx.cardview.widget.CardView
android:id="@+id/cv_video_send"
android:layout_width="@dimen/dp0"
android:layout_height="@dimen/dp0"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginTop="@dimen/dp12"
android:layout_marginRight="@dimen/dp12"
app:cardCornerRadius="@dimen/dp16"
app:layout_constraintHeight_percent="0.25"
app:layout_constraintWidth_percent="0.3"
app:layout_constraintWidth_min="@dimen/dp110"
app:layout_constraintHeight_min="@dimen/dp175">
<ImageView
android:id="@+id/iv_user"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>
</code></pre>
<p>This is the setOnClick code:</p>
<pre><code>ivImageUser.setOnClickListener(v -> {
Intent getIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(getIntent, REQUEST_USER_IMAGE);
});
ivContact.setOnClickListener(v -> {
Intent getIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(getIntent, REQUEST_CONTACT_IMAGE);
});
</code></pre>
<p>I tried different ways like setting <code>android:clickable="true"</code> however the results are not very positive, any help is greatly appreciated. Thanks everyone</p>
|
[
{
"answer_id": 74610145,
"author": "rafiulah",
"author_id": 17426448,
"author_profile": "https://Stackoverflow.com/users/17426448",
"pm_score": -1,
"selected": false,
"text": "async-storage react-navigation import { Text, View, Button } from 'react-native';\nimport { NavigationContainer } from '@react-navigation/native';\nimport { createNativeStackNavigator } from '@react-navigation/native-stack';\n\nfunction HomeScreen({ navigation }) {\n return (\n <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>\n <Text>Home Screen</Text>\n <Button\n title=\"Go to Details\"\n onPress={() => {\n /* 1. Navigate to the Details route with params */\n navigation.navigate('Details', {\n itemId: 86,\n otherParam: 'anything you want here',\n });\n }}\n />\n </View>\n );\n}\n\nfunction DetailsScreen({ route, navigation }) {\n /* 2. Get the param */\n const { itemId } = route.params;\n const { otherParam } = route.params;\n return (\n <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>\n <Text>Details Screen</Text>\n <Text>itemId: {JSON.stringify(itemId)}</Text>\n <Text>otherParam: {JSON.stringify(otherParam)}</Text>\n <Button\n title=\"Go to Details... again\"\n onPress={() =>\n navigation.push('Details', {\n itemId: Math.floor(Math.random() * 100),\n })\n }\n />\n <Button title=\"Go to Home\" onPress={() => navigation.navigate('Home')} />\n <Button title=\"Go back\" onPress={() => navigation.goBack()} />\n </View>\n );\n}\n\nconst Stack = createNativeStackNavigator();\n\nexport default function App() {\n return (\n <NavigationContainer>\n <Stack.Navigator>\n <Stack.Screen name=\"Home\" component={HomeScreen} />\n <Stack.Screen name=\"Details\" component={DetailsScreen} />\n </Stack.Navigator>\n </NavigationContainer>\n );\n}```\n"
},
{
"answer_id": 74610169,
"author": "Avetik Nersisyan",
"author_id": 14938670,
"author_profile": "https://Stackoverflow.com/users/14938670",
"pm_score": 3,
"selected": true,
"text": "log export default function Sign({ navigation, log }) {\n async function onGoogleButtonPress() {\n await GoogleSignin.hasPlayServices();\n const userInfo = await GoogleSignin.signIn();\n setuserInfo(userInfo);\n navigation.navigate('dash', {userInfo, log});\n }\n// some code\n\n}\n log props.route.params export default function dash(props) {\n const [text, setTextbaby] = useState();\n\n const {userInfo, log} = props?.route?.params;\n console.log(log);\n\n}\n log={{name: \"register\"}}\nlog={{name: \"login\"}}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74609978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,610,014
|
<p>The following is the exception i receive .Net core and rabbitMQ :
The AMQP operation was interrupted: AMQP close-reason, initiated by Peer, code=405, text='RESOURCE_LOCKED - cannot obtain exclusive access to locked queue 'demo-queue' in vhost '/'. It could be originally declared on another connection or the exclusive property value does not match that of the original declaration.', classId=50, methodId=10</p>
<p><a href="https://i.stack.imgur.com/6Qqxy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6Qqxy.png" alt="enter image description here" /></a></p>
<p>Producer :</p>
<pre><code>var factory = new ConnectionFactory
{
Uri = new Uri("amqp://guest:guest@localhost:5672")
};
using var connection= factory.CreateConnection();
using var channel= connection.CreateModel();
channel.QueueDeclare("demo-queue",durable:true,exclusive:true,autoDelete:false, arguments:null);
var message = new
{
Name = "Producer",
Message = "Hello!"
};
var body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message));
channel.BasicPublish("", "demo-queue",null,body);
</code></pre>
<p>Consumer:</p>
<pre><code> var factory = new ConnectionFactory
{
Uri = new Uri("amqp://guest:guest@localhost:5672")
};
using var connection = factory.CreateConnection();
using var channel = connection.CreateModel();
channel.QueueDeclare("demo-queue", durable: true,
exclusive: true, autoDelete: false,
arguments: null);
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (sender, e) =>
{
var body = e.Body.ToArray();
var message = Encoding.UTF8.GetString(body);
Console.WriteLine(message);
};
channel.BasicConsume("demo-queue",true,consumer);
</code></pre>
<p>Is it the right practice or right way IF I Change the name of the queue that I have given in producer or consumer? which is the right way to handle this?</p>
|
[
{
"answer_id": 74610145,
"author": "rafiulah",
"author_id": 17426448,
"author_profile": "https://Stackoverflow.com/users/17426448",
"pm_score": -1,
"selected": false,
"text": "async-storage react-navigation import { Text, View, Button } from 'react-native';\nimport { NavigationContainer } from '@react-navigation/native';\nimport { createNativeStackNavigator } from '@react-navigation/native-stack';\n\nfunction HomeScreen({ navigation }) {\n return (\n <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>\n <Text>Home Screen</Text>\n <Button\n title=\"Go to Details\"\n onPress={() => {\n /* 1. Navigate to the Details route with params */\n navigation.navigate('Details', {\n itemId: 86,\n otherParam: 'anything you want here',\n });\n }}\n />\n </View>\n );\n}\n\nfunction DetailsScreen({ route, navigation }) {\n /* 2. Get the param */\n const { itemId } = route.params;\n const { otherParam } = route.params;\n return (\n <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>\n <Text>Details Screen</Text>\n <Text>itemId: {JSON.stringify(itemId)}</Text>\n <Text>otherParam: {JSON.stringify(otherParam)}</Text>\n <Button\n title=\"Go to Details... again\"\n onPress={() =>\n navigation.push('Details', {\n itemId: Math.floor(Math.random() * 100),\n })\n }\n />\n <Button title=\"Go to Home\" onPress={() => navigation.navigate('Home')} />\n <Button title=\"Go back\" onPress={() => navigation.goBack()} />\n </View>\n );\n}\n\nconst Stack = createNativeStackNavigator();\n\nexport default function App() {\n return (\n <NavigationContainer>\n <Stack.Navigator>\n <Stack.Screen name=\"Home\" component={HomeScreen} />\n <Stack.Screen name=\"Details\" component={DetailsScreen} />\n </Stack.Navigator>\n </NavigationContainer>\n );\n}```\n"
},
{
"answer_id": 74610169,
"author": "Avetik Nersisyan",
"author_id": 14938670,
"author_profile": "https://Stackoverflow.com/users/14938670",
"pm_score": 3,
"selected": true,
"text": "log export default function Sign({ navigation, log }) {\n async function onGoogleButtonPress() {\n await GoogleSignin.hasPlayServices();\n const userInfo = await GoogleSignin.signIn();\n setuserInfo(userInfo);\n navigation.navigate('dash', {userInfo, log});\n }\n// some code\n\n}\n log props.route.params export default function dash(props) {\n const [text, setTextbaby] = useState();\n\n const {userInfo, log} = props?.route?.params;\n console.log(log);\n\n}\n log={{name: \"register\"}}\nlog={{name: \"login\"}}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12033398/"
] |
74,610,023
|
<p>Hazelcast cluster running in different hosts IP1, IP2...
hazelcast.xml configure the TCP-IP members
<a href="https://i.stack.imgur.com/RQCRa.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>Now I want to expanding the cluster to support more service.
I install a new hazelcast in new IP3</p>
<p>How can I add the new IP3 to the exsiting cluster without restarting IP1, IP2?</p>
|
[
{
"answer_id": 74610145,
"author": "rafiulah",
"author_id": 17426448,
"author_profile": "https://Stackoverflow.com/users/17426448",
"pm_score": -1,
"selected": false,
"text": "async-storage react-navigation import { Text, View, Button } from 'react-native';\nimport { NavigationContainer } from '@react-navigation/native';\nimport { createNativeStackNavigator } from '@react-navigation/native-stack';\n\nfunction HomeScreen({ navigation }) {\n return (\n <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>\n <Text>Home Screen</Text>\n <Button\n title=\"Go to Details\"\n onPress={() => {\n /* 1. Navigate to the Details route with params */\n navigation.navigate('Details', {\n itemId: 86,\n otherParam: 'anything you want here',\n });\n }}\n />\n </View>\n );\n}\n\nfunction DetailsScreen({ route, navigation }) {\n /* 2. Get the param */\n const { itemId } = route.params;\n const { otherParam } = route.params;\n return (\n <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>\n <Text>Details Screen</Text>\n <Text>itemId: {JSON.stringify(itemId)}</Text>\n <Text>otherParam: {JSON.stringify(otherParam)}</Text>\n <Button\n title=\"Go to Details... again\"\n onPress={() =>\n navigation.push('Details', {\n itemId: Math.floor(Math.random() * 100),\n })\n }\n />\n <Button title=\"Go to Home\" onPress={() => navigation.navigate('Home')} />\n <Button title=\"Go back\" onPress={() => navigation.goBack()} />\n </View>\n );\n}\n\nconst Stack = createNativeStackNavigator();\n\nexport default function App() {\n return (\n <NavigationContainer>\n <Stack.Navigator>\n <Stack.Screen name=\"Home\" component={HomeScreen} />\n <Stack.Screen name=\"Details\" component={DetailsScreen} />\n </Stack.Navigator>\n </NavigationContainer>\n );\n}```\n"
},
{
"answer_id": 74610169,
"author": "Avetik Nersisyan",
"author_id": 14938670,
"author_profile": "https://Stackoverflow.com/users/14938670",
"pm_score": 3,
"selected": true,
"text": "log export default function Sign({ navigation, log }) {\n async function onGoogleButtonPress() {\n await GoogleSignin.hasPlayServices();\n const userInfo = await GoogleSignin.signIn();\n setuserInfo(userInfo);\n navigation.navigate('dash', {userInfo, log});\n }\n// some code\n\n}\n log props.route.params export default function dash(props) {\n const [text, setTextbaby] = useState();\n\n const {userInfo, log} = props?.route?.params;\n console.log(log);\n\n}\n log={{name: \"register\"}}\nlog={{name: \"login\"}}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20630141/"
] |
74,610,026
|
<p>I have 2 sets of URLs. I want to loop through one set and compare each value with <code>.has</code> to the 2nd set.</p>
<p>To that effect I have:</p>
<pre><code> urlSet1.forEach(function(value) {
if (urlSet2.has(value) == false) {
newUrl = value;
return false;
}
})
</code></pre>
<p>However, of course, this keeps continuing to loop through.</p>
<p>I tried using <code>every</code> but I get the error:</p>
<p><code>urlSet1.every is not a function</code></p>
<p>And of course <code>break;</code> does not work on this either.</p>
<p>Would anyone know how to achieve this?</p>
|
[
{
"answer_id": 74610145,
"author": "rafiulah",
"author_id": 17426448,
"author_profile": "https://Stackoverflow.com/users/17426448",
"pm_score": -1,
"selected": false,
"text": "async-storage react-navigation import { Text, View, Button } from 'react-native';\nimport { NavigationContainer } from '@react-navigation/native';\nimport { createNativeStackNavigator } from '@react-navigation/native-stack';\n\nfunction HomeScreen({ navigation }) {\n return (\n <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>\n <Text>Home Screen</Text>\n <Button\n title=\"Go to Details\"\n onPress={() => {\n /* 1. Navigate to the Details route with params */\n navigation.navigate('Details', {\n itemId: 86,\n otherParam: 'anything you want here',\n });\n }}\n />\n </View>\n );\n}\n\nfunction DetailsScreen({ route, navigation }) {\n /* 2. Get the param */\n const { itemId } = route.params;\n const { otherParam } = route.params;\n return (\n <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>\n <Text>Details Screen</Text>\n <Text>itemId: {JSON.stringify(itemId)}</Text>\n <Text>otherParam: {JSON.stringify(otherParam)}</Text>\n <Button\n title=\"Go to Details... again\"\n onPress={() =>\n navigation.push('Details', {\n itemId: Math.floor(Math.random() * 100),\n })\n }\n />\n <Button title=\"Go to Home\" onPress={() => navigation.navigate('Home')} />\n <Button title=\"Go back\" onPress={() => navigation.goBack()} />\n </View>\n );\n}\n\nconst Stack = createNativeStackNavigator();\n\nexport default function App() {\n return (\n <NavigationContainer>\n <Stack.Navigator>\n <Stack.Screen name=\"Home\" component={HomeScreen} />\n <Stack.Screen name=\"Details\" component={DetailsScreen} />\n </Stack.Navigator>\n </NavigationContainer>\n );\n}```\n"
},
{
"answer_id": 74610169,
"author": "Avetik Nersisyan",
"author_id": 14938670,
"author_profile": "https://Stackoverflow.com/users/14938670",
"pm_score": 3,
"selected": true,
"text": "log export default function Sign({ navigation, log }) {\n async function onGoogleButtonPress() {\n await GoogleSignin.hasPlayServices();\n const userInfo = await GoogleSignin.signIn();\n setuserInfo(userInfo);\n navigation.navigate('dash', {userInfo, log});\n }\n// some code\n\n}\n log props.route.params export default function dash(props) {\n const [text, setTextbaby] = useState();\n\n const {userInfo, log} = props?.route?.params;\n console.log(log);\n\n}\n log={{name: \"register\"}}\nlog={{name: \"login\"}}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1433268/"
] |
74,610,032
|
<p>I'm migrating multiple projects from Java 8 to Java 11 and I was wondering if Java 8 is forward compatible with Java 11.
In other words, is it possible to use artifacts compiled against Java 11 in Java 8 projects?</p>
|
[
{
"answer_id": 74610145,
"author": "rafiulah",
"author_id": 17426448,
"author_profile": "https://Stackoverflow.com/users/17426448",
"pm_score": -1,
"selected": false,
"text": "async-storage react-navigation import { Text, View, Button } from 'react-native';\nimport { NavigationContainer } from '@react-navigation/native';\nimport { createNativeStackNavigator } from '@react-navigation/native-stack';\n\nfunction HomeScreen({ navigation }) {\n return (\n <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>\n <Text>Home Screen</Text>\n <Button\n title=\"Go to Details\"\n onPress={() => {\n /* 1. Navigate to the Details route with params */\n navigation.navigate('Details', {\n itemId: 86,\n otherParam: 'anything you want here',\n });\n }}\n />\n </View>\n );\n}\n\nfunction DetailsScreen({ route, navigation }) {\n /* 2. Get the param */\n const { itemId } = route.params;\n const { otherParam } = route.params;\n return (\n <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>\n <Text>Details Screen</Text>\n <Text>itemId: {JSON.stringify(itemId)}</Text>\n <Text>otherParam: {JSON.stringify(otherParam)}</Text>\n <Button\n title=\"Go to Details... again\"\n onPress={() =>\n navigation.push('Details', {\n itemId: Math.floor(Math.random() * 100),\n })\n }\n />\n <Button title=\"Go to Home\" onPress={() => navigation.navigate('Home')} />\n <Button title=\"Go back\" onPress={() => navigation.goBack()} />\n </View>\n );\n}\n\nconst Stack = createNativeStackNavigator();\n\nexport default function App() {\n return (\n <NavigationContainer>\n <Stack.Navigator>\n <Stack.Screen name=\"Home\" component={HomeScreen} />\n <Stack.Screen name=\"Details\" component={DetailsScreen} />\n </Stack.Navigator>\n </NavigationContainer>\n );\n}```\n"
},
{
"answer_id": 74610169,
"author": "Avetik Nersisyan",
"author_id": 14938670,
"author_profile": "https://Stackoverflow.com/users/14938670",
"pm_score": 3,
"selected": true,
"text": "log export default function Sign({ navigation, log }) {\n async function onGoogleButtonPress() {\n await GoogleSignin.hasPlayServices();\n const userInfo = await GoogleSignin.signIn();\n setuserInfo(userInfo);\n navigation.navigate('dash', {userInfo, log});\n }\n// some code\n\n}\n log props.route.params export default function dash(props) {\n const [text, setTextbaby] = useState();\n\n const {userInfo, log} = props?.route?.params;\n console.log(log);\n\n}\n log={{name: \"register\"}}\nlog={{name: \"login\"}}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20630375/"
] |
74,610,066
|
<p>In the application there is column type where the type are: Users and Admin.</p>
<p>I want to separate the app file of users to admin.</p>
<p>I already edited the file of</p>
<p><strong>AuthenticatedSessionController</strong></p>
<pre><code>if($user_details->type != 0)
{
return redirect()->intended(RouteServiceProvider::HOME);
}else{
return redirect()->intended(RouteServiceProvider::SUPERADMINHOME);
}
</code></pre>
<p>I added SUPERADMINHOME in RouteServiceProvider</p>
<p><strong>RouteServiceProvider</strong></p>
<pre><code>public const SUPERADMINHOME = '/app/super-admin/dashboard';
</code></pre>
<p>In web, I also added the route</p>
<p>My problem is, when the user logged in the superadmin it should load the super-admin-app not the app.blade.php</p>
<p>Reason why I want to separate the app file because whenever there will be change in app(for example) it should not effect the other one.</p>
<p>Question: Is it possible to separate the app file of users & admin?</p>
|
[
{
"answer_id": 74610145,
"author": "rafiulah",
"author_id": 17426448,
"author_profile": "https://Stackoverflow.com/users/17426448",
"pm_score": -1,
"selected": false,
"text": "async-storage react-navigation import { Text, View, Button } from 'react-native';\nimport { NavigationContainer } from '@react-navigation/native';\nimport { createNativeStackNavigator } from '@react-navigation/native-stack';\n\nfunction HomeScreen({ navigation }) {\n return (\n <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>\n <Text>Home Screen</Text>\n <Button\n title=\"Go to Details\"\n onPress={() => {\n /* 1. Navigate to the Details route with params */\n navigation.navigate('Details', {\n itemId: 86,\n otherParam: 'anything you want here',\n });\n }}\n />\n </View>\n );\n}\n\nfunction DetailsScreen({ route, navigation }) {\n /* 2. Get the param */\n const { itemId } = route.params;\n const { otherParam } = route.params;\n return (\n <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>\n <Text>Details Screen</Text>\n <Text>itemId: {JSON.stringify(itemId)}</Text>\n <Text>otherParam: {JSON.stringify(otherParam)}</Text>\n <Button\n title=\"Go to Details... again\"\n onPress={() =>\n navigation.push('Details', {\n itemId: Math.floor(Math.random() * 100),\n })\n }\n />\n <Button title=\"Go to Home\" onPress={() => navigation.navigate('Home')} />\n <Button title=\"Go back\" onPress={() => navigation.goBack()} />\n </View>\n );\n}\n\nconst Stack = createNativeStackNavigator();\n\nexport default function App() {\n return (\n <NavigationContainer>\n <Stack.Navigator>\n <Stack.Screen name=\"Home\" component={HomeScreen} />\n <Stack.Screen name=\"Details\" component={DetailsScreen} />\n </Stack.Navigator>\n </NavigationContainer>\n );\n}```\n"
},
{
"answer_id": 74610169,
"author": "Avetik Nersisyan",
"author_id": 14938670,
"author_profile": "https://Stackoverflow.com/users/14938670",
"pm_score": 3,
"selected": true,
"text": "log export default function Sign({ navigation, log }) {\n async function onGoogleButtonPress() {\n await GoogleSignin.hasPlayServices();\n const userInfo = await GoogleSignin.signIn();\n setuserInfo(userInfo);\n navigation.navigate('dash', {userInfo, log});\n }\n// some code\n\n}\n log props.route.params export default function dash(props) {\n const [text, setTextbaby] = useState();\n\n const {userInfo, log} = props?.route?.params;\n console.log(log);\n\n}\n log={{name: \"register\"}}\nlog={{name: \"login\"}}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6858228/"
] |
74,610,073
|
<p>Dear Excel masters please take a look. Here's the formula that I want to use:</p>
<pre><code>Filter(A1:A4,ISNUMBER(SEARCH({"aa","bb","cc","dd","ee","ff","gg"},B2:B4)))
</code></pre>
<p>What ISNUMBER returned is a table of array that Filter function doesn't recognize. Any help?</p>
|
[
{
"answer_id": 74610145,
"author": "rafiulah",
"author_id": 17426448,
"author_profile": "https://Stackoverflow.com/users/17426448",
"pm_score": -1,
"selected": false,
"text": "async-storage react-navigation import { Text, View, Button } from 'react-native';\nimport { NavigationContainer } from '@react-navigation/native';\nimport { createNativeStackNavigator } from '@react-navigation/native-stack';\n\nfunction HomeScreen({ navigation }) {\n return (\n <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>\n <Text>Home Screen</Text>\n <Button\n title=\"Go to Details\"\n onPress={() => {\n /* 1. Navigate to the Details route with params */\n navigation.navigate('Details', {\n itemId: 86,\n otherParam: 'anything you want here',\n });\n }}\n />\n </View>\n );\n}\n\nfunction DetailsScreen({ route, navigation }) {\n /* 2. Get the param */\n const { itemId } = route.params;\n const { otherParam } = route.params;\n return (\n <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>\n <Text>Details Screen</Text>\n <Text>itemId: {JSON.stringify(itemId)}</Text>\n <Text>otherParam: {JSON.stringify(otherParam)}</Text>\n <Button\n title=\"Go to Details... again\"\n onPress={() =>\n navigation.push('Details', {\n itemId: Math.floor(Math.random() * 100),\n })\n }\n />\n <Button title=\"Go to Home\" onPress={() => navigation.navigate('Home')} />\n <Button title=\"Go back\" onPress={() => navigation.goBack()} />\n </View>\n );\n}\n\nconst Stack = createNativeStackNavigator();\n\nexport default function App() {\n return (\n <NavigationContainer>\n <Stack.Navigator>\n <Stack.Screen name=\"Home\" component={HomeScreen} />\n <Stack.Screen name=\"Details\" component={DetailsScreen} />\n </Stack.Navigator>\n </NavigationContainer>\n );\n}```\n"
},
{
"answer_id": 74610169,
"author": "Avetik Nersisyan",
"author_id": 14938670,
"author_profile": "https://Stackoverflow.com/users/14938670",
"pm_score": 3,
"selected": true,
"text": "log export default function Sign({ navigation, log }) {\n async function onGoogleButtonPress() {\n await GoogleSignin.hasPlayServices();\n const userInfo = await GoogleSignin.signIn();\n setuserInfo(userInfo);\n navigation.navigate('dash', {userInfo, log});\n }\n// some code\n\n}\n log props.route.params export default function dash(props) {\n const [text, setTextbaby] = useState();\n\n const {userInfo, log} = props?.route?.params;\n console.log(log);\n\n}\n log={{name: \"register\"}}\nlog={{name: \"login\"}}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8963010/"
] |
74,610,092
|
<p>I am trying to build a c++ application that uses sql.</p>
<p>For that I need <code>sqlite3</code> header. I have already installed sql in my system and</p>
<p><code>sqlite3</code> in terminal gives:</p>
<p><code>SQLite version 3.36.0 2021-06-18 18:36:39 Enter ".help" for usage hints. Connected to a transient in-memory database. Use ".open FILENAME" to reopen on a persistent database. sqlite></code></p>
<p>I have tried searching for this over web and found many relevant solutions including <a href="https://stackoverflow.com/questions/28969543/fatal-error-sqlite3-h-no-such-file-or-directory">this</a>.</p>
<p>Since I am working on Windows,</p>
<pre><code>$ sudo apt-get install libsqlite3-dev
</code></pre>
<p>did not work.
I also tried to change</p>
<pre><code>#include <sqlite3.h>
</code></pre>
<p>to</p>
<pre><code>#include "sqlite3.h"
</code></pre>
<p>with sqlite.h file in the same directory as my cpp code file(as I found people using it in videos). But this time I ended up with
'''
C:\Users\username\AppData\Local\Temp\ccwQfHZB.o:temp.cpp:(.text+0x1e): undefined reference to `sqlite3_open'
collect2.exe: error: ld returned 1 exit status
'''</p>
<p>I am quite new to it, so any help is appreciated. Thanks.</p>
|
[
{
"answer_id": 74610145,
"author": "rafiulah",
"author_id": 17426448,
"author_profile": "https://Stackoverflow.com/users/17426448",
"pm_score": -1,
"selected": false,
"text": "async-storage react-navigation import { Text, View, Button } from 'react-native';\nimport { NavigationContainer } from '@react-navigation/native';\nimport { createNativeStackNavigator } from '@react-navigation/native-stack';\n\nfunction HomeScreen({ navigation }) {\n return (\n <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>\n <Text>Home Screen</Text>\n <Button\n title=\"Go to Details\"\n onPress={() => {\n /* 1. Navigate to the Details route with params */\n navigation.navigate('Details', {\n itemId: 86,\n otherParam: 'anything you want here',\n });\n }}\n />\n </View>\n );\n}\n\nfunction DetailsScreen({ route, navigation }) {\n /* 2. Get the param */\n const { itemId } = route.params;\n const { otherParam } = route.params;\n return (\n <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>\n <Text>Details Screen</Text>\n <Text>itemId: {JSON.stringify(itemId)}</Text>\n <Text>otherParam: {JSON.stringify(otherParam)}</Text>\n <Button\n title=\"Go to Details... again\"\n onPress={() =>\n navigation.push('Details', {\n itemId: Math.floor(Math.random() * 100),\n })\n }\n />\n <Button title=\"Go to Home\" onPress={() => navigation.navigate('Home')} />\n <Button title=\"Go back\" onPress={() => navigation.goBack()} />\n </View>\n );\n}\n\nconst Stack = createNativeStackNavigator();\n\nexport default function App() {\n return (\n <NavigationContainer>\n <Stack.Navigator>\n <Stack.Screen name=\"Home\" component={HomeScreen} />\n <Stack.Screen name=\"Details\" component={DetailsScreen} />\n </Stack.Navigator>\n </NavigationContainer>\n );\n}```\n"
},
{
"answer_id": 74610169,
"author": "Avetik Nersisyan",
"author_id": 14938670,
"author_profile": "https://Stackoverflow.com/users/14938670",
"pm_score": 3,
"selected": true,
"text": "log export default function Sign({ navigation, log }) {\n async function onGoogleButtonPress() {\n await GoogleSignin.hasPlayServices();\n const userInfo = await GoogleSignin.signIn();\n setuserInfo(userInfo);\n navigation.navigate('dash', {userInfo, log});\n }\n// some code\n\n}\n log props.route.params export default function dash(props) {\n const [text, setTextbaby] = useState();\n\n const {userInfo, log} = props?.route?.params;\n console.log(log);\n\n}\n log={{name: \"register\"}}\nlog={{name: \"login\"}}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15031437/"
] |
74,610,101
|
<p>I have a matrix A of size NXN with float values and another boolean matrix B of size NXN</p>
<p>For every row, I need to find the mean of all values in A belonging to indices where True is the corresponding value for that index in matrix B</p>
<p>Similarly, I need to find the mean of all values in A belonging to indices where False is the corresponding value for that index in matrix B</p>
<p>Finally, I need to find the count of number of rows where "True" mean is lesser than "False" mean</p>
<p>For example :</p>
<pre><code>A = [[1.0, 2.0, 3.0]
[4.0, 5.0, 6.0]
[7.0, 8.0, 9.0]]
B = [[True, True, False]
[False, False, True]
[True, False, True]]
</code></pre>
<p>Initially, count = 0</p>
<p>For row 1, true_mean = 1.0+2.0 / 2 = 1.5 and false_mean = 3.0 <br>
true_mean < false_mean, so count = 0+1=1</p>
<p>For row 2, true_mean = 6.0 and false_mean = 4.0+5.0 / 2 = 4.5 <br>
true_mean > false_mean, so count remains same</p>
<p>For row 3, true_mean = 7.0+9.0 / 2 = 8.0 and false_mean = 8.0 <br>
true_mean == false_mean, so count remains same</p>
<p>Final count value = 1</p>
<p>My attempt:-</p>
<pre><code>true_mat = np.where(B, A, 0)
false_mat = np.where(B, 0, A)
true_mean = true_mat.mean(axis=1)
false_mean = false_mat.mean(axis=1)
</code></pre>
<p>But this actually gives wrong answer since denominator is not exactly the count of number of True/False values in that row but instead 'N'</p>
<p>I only need the count, I don't need the true_mean and false_mean</p>
<p>Anyway to fix it?</p>
|
[
{
"answer_id": 74610145,
"author": "rafiulah",
"author_id": 17426448,
"author_profile": "https://Stackoverflow.com/users/17426448",
"pm_score": -1,
"selected": false,
"text": "async-storage react-navigation import { Text, View, Button } from 'react-native';\nimport { NavigationContainer } from '@react-navigation/native';\nimport { createNativeStackNavigator } from '@react-navigation/native-stack';\n\nfunction HomeScreen({ navigation }) {\n return (\n <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>\n <Text>Home Screen</Text>\n <Button\n title=\"Go to Details\"\n onPress={() => {\n /* 1. Navigate to the Details route with params */\n navigation.navigate('Details', {\n itemId: 86,\n otherParam: 'anything you want here',\n });\n }}\n />\n </View>\n );\n}\n\nfunction DetailsScreen({ route, navigation }) {\n /* 2. Get the param */\n const { itemId } = route.params;\n const { otherParam } = route.params;\n return (\n <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>\n <Text>Details Screen</Text>\n <Text>itemId: {JSON.stringify(itemId)}</Text>\n <Text>otherParam: {JSON.stringify(otherParam)}</Text>\n <Button\n title=\"Go to Details... again\"\n onPress={() =>\n navigation.push('Details', {\n itemId: Math.floor(Math.random() * 100),\n })\n }\n />\n <Button title=\"Go to Home\" onPress={() => navigation.navigate('Home')} />\n <Button title=\"Go back\" onPress={() => navigation.goBack()} />\n </View>\n );\n}\n\nconst Stack = createNativeStackNavigator();\n\nexport default function App() {\n return (\n <NavigationContainer>\n <Stack.Navigator>\n <Stack.Screen name=\"Home\" component={HomeScreen} />\n <Stack.Screen name=\"Details\" component={DetailsScreen} />\n </Stack.Navigator>\n </NavigationContainer>\n );\n}```\n"
},
{
"answer_id": 74610169,
"author": "Avetik Nersisyan",
"author_id": 14938670,
"author_profile": "https://Stackoverflow.com/users/14938670",
"pm_score": 3,
"selected": true,
"text": "log export default function Sign({ navigation, log }) {\n async function onGoogleButtonPress() {\n await GoogleSignin.hasPlayServices();\n const userInfo = await GoogleSignin.signIn();\n setuserInfo(userInfo);\n navigation.navigate('dash', {userInfo, log});\n }\n// some code\n\n}\n log props.route.params export default function dash(props) {\n const [text, setTextbaby] = useState();\n\n const {userInfo, log} = props?.route?.params;\n console.log(log);\n\n}\n log={{name: \"register\"}}\nlog={{name: \"login\"}}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4508623/"
] |
74,610,105
|
<p>I am trying to understand how numpy handles the float32 datatype.</p>
<p>The following code produces 0.25815687</p>
<pre><code>print(np.float32(0.2581568658351898).astype(str)) # 0.25815687
</code></pre>
<p>But an online float converter <a href="https://www.h-schmidt.net/FloatConverter/IEEE754.html" rel="nofollow noreferrer">https://www.h-schmidt.net/FloatConverter/IEEE754.html</a> gives 0.2581568658351898193359375, Is Numpy doing something special when printing the single-precision float or there is something I missed?
<a href="https://i.stack.imgur.com/ejBvX.png" rel="nofollow noreferrer">Online converter result</a></p>
|
[
{
"answer_id": 74611682,
"author": "rveronese",
"author_id": 4664776,
"author_profile": "https://Stackoverflow.com/users/4664776",
"pm_score": 0,
"selected": false,
"text": "print(f\"{np.float32(0.2581568658351898):.25f}\")\n :.25f"
},
{
"answer_id": 74612193,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 2,
"selected": true,
"text": "0.2581568658351898193359375 0x1.085a46p-2 0.2581568658351898193359375 0.25815687 0.2581568 658351898 Source code\n0.2581568 658351898193359375 True value\n0.2581568 7 Output \n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18347885/"
] |
74,610,108
|
<p>I want the slider to not pass a certain limit. How can I set this is HTML and also change it in javascript?</p>
<pre class="lang-html prettyprint-override"><code><input type="range" min="0" max="100" value="30">
</code></pre>
<p>I want to set it so that the slider can never go past a certain value though the value will be there on slider i.e slider should have min:0 max:100 but never go past say 70.</p>
|
[
{
"answer_id": 74610193,
"author": "Layhout",
"author_id": 17308201,
"author_profile": "https://Stackoverflow.com/users/17308201",
"pm_score": 3,
"selected": true,
"text": "function test(e, el) {\n if (e.target.value > 70) el.value = 70;\n document.querySelector(\"h1\").innerHTML = \"range value: \" + e.target.value;\n} <input type=\"range\" min=\"0\" max=\"100\" style=\"width: 100%;\" oninput=\"test(event, this)\">\n<br>\n<h1>range value: 50</h1>"
},
{
"answer_id": 74610304,
"author": "Dream Bold",
"author_id": 12743692,
"author_profile": "https://Stackoverflow.com/users/12743692",
"pm_score": 1,
"selected": false,
"text": "<h1>Display a Range Field</h1>\n\n\n <label for=\"vol\">Volume <span id=\"currentvalue\"> </span> (between 0 and 100):</label>\n <input type=\"range\" id=\"vol\" name=\"vol\" min=\"0\" max=\"100\" value=\"30\">\n\n<script type=\"text/javascript\">\ndocument.getElementById(\"currentvalue\").innerHTML = document.getElementById(\"vol\").value;\ndocument.getElementById(\"vol\").addEventListener(\"change\", function(e){\n \n if(e.target.value > 70) {\n alert(\"You can't pick above 70 for now!\"); \n this.value = 70;\n }\n document.getElementById(\"currentvalue\").innerHTML = e.target.value;\n e.preventDefault();\n e.stopPropagation();\n})\n \n</script>"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20173895/"
] |
74,610,114
|
<p>i need help with my app. iam new to flutter and wanted to try to make a homepage with an intresting button. i have design my homepage in figma but i dont really know how to make the button to be the same, so here's my figma UI design that i want to implement</p>
<p><a href="https://i.stack.imgur.com/Tgo2Z.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Tgo2Z.png" alt="enter image description here" /></a></p>
<p>i use an SVG icon for the button.</p>
<p>and so far in my code, my HomePage only looks like this</p>
<p><a href="https://i.stack.imgur.com/fKa2I.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fKa2I.png" alt="enter image description here" /></a></p>
<p>and btw this is my HomePage code</p>
<pre><code>import 'package:flutter/material.dart';
import 'package:get/get_navigation/get_navigation.dart';
import 'package:medreminder/NewsArticle/news_home.dart';
import 'Reminder/ui/home_reminder.dart';
import 'Reminder/ui/widgets/button.dart';
import 'package:medreminder/main_reminder.dart';
import 'package:medreminder/home_page.dart';
void main() {
// debugPaintSizeEnabled = true;
runApp(const HomePage());
}
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: const Text('Medicine Reminder App'),
),
body: Column(
children: [
Stack(
children: [
Image.asset(
'images/MenuImg.jpg',
width: 600,
height: 200,
fit: BoxFit.cover,
),
],
),
const SizedBox(height: 10.0),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
ElevatedButton(
child: const Text('Reminder'),
onPressed: () {
Navigator.of(context, rootNavigator: true).push(
MaterialPageRoute(builder: (context) => const ReminderHomePage()),
);
},
),
ElevatedButton(
child: const Text('News & Article'),
onPressed: () {
Navigator.of(context, rootNavigator: true).push(
MaterialPageRoute(builder: (context) => const NewsHomePage()),
);
},
),
ElevatedButton(
child: const Text('Healty Food Recipe'),
onPressed: () {},
),
],
),
],
),
),
);
}
}
</code></pre>
<p>thankyou guys for the attention, any help would mean so much to me. thankyou</p>
|
[
{
"answer_id": 74610182,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 2,
"selected": false,
"text": "asset Widget buildCustomButton(String imagePath, String title, Function()? onTap) {\n return InkWell(\n onTap: onTap,\n child: Column(\n crossAxisAlignment: CrossAxisAlignment.center,\n children: [\n Container(\n clipBehavior: Clip.antiAlias,\n height: 50,\n width: 50,\n decoration: BoxDecoration(\n shape: BoxShape.circle,\n ),\n child: Image.asset(imagePath, fit: BoxFit.none),\n ),\n SizedBox(\n height: 8,\n ),\n Text(\n title,\n textAlign: TextAlign.center,\n )\n ],\n ),\n );\n }\n buildCustomButton('assets/images/reminder.png', 'Reminder', () {\n print(\"Reminder click\");\n }),\n"
},
{
"answer_id": 74610235,
"author": "Kemal Yilmaz",
"author_id": 20518203,
"author_profile": "https://Stackoverflow.com/users/20518203",
"pm_score": 1,
"selected": false,
"text": "InkWell(\n onTap: () {},\n child: Container(\n child: FlutterLogo(\n size: 80,\n ),\n ))\n"
},
{
"answer_id": 74611490,
"author": "Umesh Rajput",
"author_id": 19842804,
"author_profile": "https://Stackoverflow.com/users/19842804",
"pm_score": 1,
"selected": false,
"text": " GestureDetector (onTap:()\n {Your Method('Where you want to naviagate')},\n child:Your Design})\n \n \n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20229067/"
] |
74,610,117
|
<p>I'm using <code>ng-bootstrap</code> modal</p>
<p>import { NgbModal, ModalDismissReasons } from "@ng-bootstrap/ng-bootstrap";</p>
<p>On button click it is opened properly</p>
<pre><code><button class="btn labelbtn accountbtn customnavbtn"(click)="demobutton(UploadModal)" type="button"> Open </button>
demobutton(UploadModal:any) {
this.modalService
.open(UploadModal, {
windowClass: "modal",
ariaLabelledBy: "modal-basic-title",
backdrop: false,
})
.result.then(
(result) => {},
(reason) => {}
);
}
</code></pre>
<p>but when i try to open through function it is not opening properly only some of the divs are visible content is not visible.</p>
<pre><code>async open(files){
this.modalService.dismissAll();
setTimeout(() => {
this.demobutton('UploadModal');
}, 2000);
</code></pre>
<p>Any solution Thanks</p>
|
[
{
"answer_id": 74610182,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 2,
"selected": false,
"text": "asset Widget buildCustomButton(String imagePath, String title, Function()? onTap) {\n return InkWell(\n onTap: onTap,\n child: Column(\n crossAxisAlignment: CrossAxisAlignment.center,\n children: [\n Container(\n clipBehavior: Clip.antiAlias,\n height: 50,\n width: 50,\n decoration: BoxDecoration(\n shape: BoxShape.circle,\n ),\n child: Image.asset(imagePath, fit: BoxFit.none),\n ),\n SizedBox(\n height: 8,\n ),\n Text(\n title,\n textAlign: TextAlign.center,\n )\n ],\n ),\n );\n }\n buildCustomButton('assets/images/reminder.png', 'Reminder', () {\n print(\"Reminder click\");\n }),\n"
},
{
"answer_id": 74610235,
"author": "Kemal Yilmaz",
"author_id": 20518203,
"author_profile": "https://Stackoverflow.com/users/20518203",
"pm_score": 1,
"selected": false,
"text": "InkWell(\n onTap: () {},\n child: Container(\n child: FlutterLogo(\n size: 80,\n ),\n ))\n"
},
{
"answer_id": 74611490,
"author": "Umesh Rajput",
"author_id": 19842804,
"author_profile": "https://Stackoverflow.com/users/19842804",
"pm_score": 1,
"selected": false,
"text": " GestureDetector (onTap:()\n {Your Method('Where you want to naviagate')},\n child:Your Design})\n \n \n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3653474/"
] |
74,610,150
|
<p>I'm trying to iterate through a nested object to retrieve a specific object identified by a string. In the sample object below, the identifier string is the "label" property. I don't know how to iterate down through the tree to return the appropriate object.</p>
<p>My Ruby and Rails versions are pretty old.
<strong>Ruby - 1.9.3
Rails - 3.0.9</strong></p>
<p>`</p>
<pre><code>company_tree = {
label: 'Autos',
subs: [
{
label: 'SUVs',
subs: []
},
{
label: 'Trucks',
subs: [
{
label: '2 Wheel Drive',
subs: []
},
{
label: '4 Wheel Drive',
subs: [
{
label: 'Ford',
subs: []
},
{
label: 'Chevrolet',
subs: []
}
]
}
]
},
{
label: 'Sedan',
subs: []
}
]
}
</code></pre>
<p>`</p>
<p>I tried using below code. But I didn't worked. It only return the second array only. It won't go beyond that.</p>
<p>`</p>
<pre><code>data = JSON.parse(requestData)
data['company_tree']['subs'].each do |element|
puts "element=> #{element['subs']}"
end
</code></pre>
<p>`</p>
|
[
{
"answer_id": 74610182,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 2,
"selected": false,
"text": "asset Widget buildCustomButton(String imagePath, String title, Function()? onTap) {\n return InkWell(\n onTap: onTap,\n child: Column(\n crossAxisAlignment: CrossAxisAlignment.center,\n children: [\n Container(\n clipBehavior: Clip.antiAlias,\n height: 50,\n width: 50,\n decoration: BoxDecoration(\n shape: BoxShape.circle,\n ),\n child: Image.asset(imagePath, fit: BoxFit.none),\n ),\n SizedBox(\n height: 8,\n ),\n Text(\n title,\n textAlign: TextAlign.center,\n )\n ],\n ),\n );\n }\n buildCustomButton('assets/images/reminder.png', 'Reminder', () {\n print(\"Reminder click\");\n }),\n"
},
{
"answer_id": 74610235,
"author": "Kemal Yilmaz",
"author_id": 20518203,
"author_profile": "https://Stackoverflow.com/users/20518203",
"pm_score": 1,
"selected": false,
"text": "InkWell(\n onTap: () {},\n child: Container(\n child: FlutterLogo(\n size: 80,\n ),\n ))\n"
},
{
"answer_id": 74611490,
"author": "Umesh Rajput",
"author_id": 19842804,
"author_profile": "https://Stackoverflow.com/users/19842804",
"pm_score": 1,
"selected": false,
"text": " GestureDetector (onTap:()\n {Your Method('Where you want to naviagate')},\n child:Your Design})\n \n \n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20519909/"
] |
74,610,230
|
<p>I have a JS where I can detect if uppercase is being entered, but I'm unable to convert the text text to lower case. i have used CSS <code>text-transform: lowercase;</code> but this shows that it's lower but once submitted, it shows the text as normal (original format).
I have tried with jquery <code>toLowerCase();</code> but I don't know what I have missed here coz it didn't work.
this is my script,</p>
<pre><code> const setup = function(fieldSelector) {
const field = $(fieldSelector);
const upperCase= new RegExp('[A-Z]');
const applyStyle = function() {
if (field.val().match(upperCase)) {
field.val().toLowerCase();
} else {
field.val();
}
};
field.on('change', applyStyle);
applyStyle();
}
// Note: Change the ID according to the custom field you want to target.
setup('#issue_custom_field_values_17');
});
</code></pre>
<p>this code is used for redmine "View customize plugin"</p>
|
[
{
"answer_id": 74610620,
"author": "bobi",
"author_id": 18990544,
"author_profile": "https://Stackoverflow.com/users/18990544",
"pm_score": 2,
"selected": false,
"text": "$('input').keyup(function(){\n let val = $(this).val().toLowerCase()\n $(this).val(val)\n}) <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<input type=\"text\">"
},
{
"answer_id": 74610780,
"author": "sulanjala dickshan",
"author_id": 6142809,
"author_profile": "https://Stackoverflow.com/users/6142809",
"pm_score": 0,
"selected": false,
"text": "const char = string.charAt(field.val());\nconst isUpperCaseLetter = (/[A-Z]/.test(char));\n"
},
{
"answer_id": 74610903,
"author": "Cheteel",
"author_id": 20519869,
"author_profile": "https://Stackoverflow.com/users/20519869",
"pm_score": 0,
"selected": false,
"text": " const setup = function(fieldSelector) {\n const field = $(fieldSelector);\n const upperCase= new RegExp('[A-Z]');\n // Here's the change\n const applyStyle = function() {\n field.val( field.val().toLowerCase() )\n };\n field.on('change', applyStyle);\n applyStyle();\n }\n // Note: Change the ID according to the custom field you want to target.\n setup('#issue_custom_field_values_17');\n });\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17016121/"
] |
74,610,270
|
<p>I have a database with <code>users</code> collection which contains a <code>verified</code> field in its schema. I want users that have not been verified 5min after account creation to be deleted. How can I do this?</p>
<p>I am already familiar with the <code>expires</code> option, but I am not sure how I can apply it conditionally.</p>
|
[
{
"answer_id": 74610620,
"author": "bobi",
"author_id": 18990544,
"author_profile": "https://Stackoverflow.com/users/18990544",
"pm_score": 2,
"selected": false,
"text": "$('input').keyup(function(){\n let val = $(this).val().toLowerCase()\n $(this).val(val)\n}) <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<input type=\"text\">"
},
{
"answer_id": 74610780,
"author": "sulanjala dickshan",
"author_id": 6142809,
"author_profile": "https://Stackoverflow.com/users/6142809",
"pm_score": 0,
"selected": false,
"text": "const char = string.charAt(field.val());\nconst isUpperCaseLetter = (/[A-Z]/.test(char));\n"
},
{
"answer_id": 74610903,
"author": "Cheteel",
"author_id": 20519869,
"author_profile": "https://Stackoverflow.com/users/20519869",
"pm_score": 0,
"selected": false,
"text": " const setup = function(fieldSelector) {\n const field = $(fieldSelector);\n const upperCase= new RegExp('[A-Z]');\n // Here's the change\n const applyStyle = function() {\n field.val( field.val().toLowerCase() )\n };\n field.on('change', applyStyle);\n applyStyle();\n }\n // Note: Change the ID according to the custom field you want to target.\n setup('#issue_custom_field_values_17');\n });\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20023779/"
] |
74,610,287
|
<p>im trying to display my api products but it is not displaying in browser</p>
<p>[1[2<a href="https://i.stack.imgur.com/LoOiL.png" rel="nofollow noreferrer">enter image description here</a>](<a href="https://i.stack.imgur.com/HsE8K.png" rel="nofollow noreferrer">https://i.stack.imgur.com/HsE8K.png</a>)](<a href="https://i.stack.imgur.com/QvAm6.png" rel="nofollow noreferrer">https://i.stack.imgur.com/QvAm6.png</a>)</p>
|
[
{
"answer_id": 74610620,
"author": "bobi",
"author_id": 18990544,
"author_profile": "https://Stackoverflow.com/users/18990544",
"pm_score": 2,
"selected": false,
"text": "$('input').keyup(function(){\n let val = $(this).val().toLowerCase()\n $(this).val(val)\n}) <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<input type=\"text\">"
},
{
"answer_id": 74610780,
"author": "sulanjala dickshan",
"author_id": 6142809,
"author_profile": "https://Stackoverflow.com/users/6142809",
"pm_score": 0,
"selected": false,
"text": "const char = string.charAt(field.val());\nconst isUpperCaseLetter = (/[A-Z]/.test(char));\n"
},
{
"answer_id": 74610903,
"author": "Cheteel",
"author_id": 20519869,
"author_profile": "https://Stackoverflow.com/users/20519869",
"pm_score": 0,
"selected": false,
"text": " const setup = function(fieldSelector) {\n const field = $(fieldSelector);\n const upperCase= new RegExp('[A-Z]');\n // Here's the change\n const applyStyle = function() {\n field.val( field.val().toLowerCase() )\n };\n field.on('change', applyStyle);\n applyStyle();\n }\n // Note: Change the ID according to the custom field you want to target.\n setup('#issue_custom_field_values_17');\n });\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20630578/"
] |
74,610,295
|
<p>I have an array of objects, I want to be able to join it a string followed by having some of those array objects as part of a newly formed ordered list.</p>
<p>My code:</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>let arr = [
{
'message': "message 1",
'date': "date 1",
'text': "text 1"
},
{
'message': "message 2",
'date': "date 2",
'text': "text 2"
},
{
'message': "message 3",
'date': "date 3",
'text': "text 3"
},
];
let new_arr = [];
arr.forEach(d => {
new_arr.push(`The following messages: ${d.message} at ${d.date}`);
});
console.log(new_arr);</code></pre>
</div>
</div>
</p>
<p>Is there any way I can get the code to do something like this:</p>
<pre><code>The following messages:
1. message 1 at date 1
2. message 2 at date 2
3. message 3 at date 3
</code></pre>
|
[
{
"answer_id": 74610384,
"author": "Andrew Parks",
"author_id": 5898421,
"author_profile": "https://Stackoverflow.com/users/5898421",
"pm_score": 2,
"selected": false,
"text": "let arr = [{\"message\":\"message 1\",\"date\":\"date 1\",\"text\":\"text 1\"},\n {\"message\":\"message 2\",\"date\":\"date 2\",\"text\":\"text 2\"},\n {\"message\":\"message 3\",\"date\":\"date 3\",\"text\":\"text 3\"}]\n\n\nconsole.log('The following messages:');\narr.forEach((e,i)=>console.log(` ${i+1}. ${e.message} at ${e.date}`))"
},
{
"answer_id": 74610424,
"author": "Layhout",
"author_id": 17308201,
"author_profile": "https://Stackoverflow.com/users/17308201",
"pm_score": 2,
"selected": true,
"text": "let arr = [{\n 'message': \"message 1\",\n 'date': \"date 1\",\n 'text': \"text 1\"\n },\n {\n 'message': \"message 2\",\n 'date': \"date 2\",\n 'text': \"text 2\"\n },\n {\n 'message': \"message 3\",\n 'date': \"date 3\",\n 'text': \"text 3\"\n },\n];\nlet result_string = \"The following messages:\\n\\t\";\nresult_string += arr.map((a, i) => `${i+1}. ${a.message} at ${a.date}`).join(\"\\n\\t\");\nconsole.log(result_string);"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10034685/"
] |
74,610,307
|
<p>I would like to add a description in Swagger documentation that some parameters in request body are optional.</p>
<p>Should I use <code>@ApiParam</code> annotation for such description ? I tried to use <code>@ApiModelProperty(notes = "")</code> but it didnt work.</p>
<pre class="lang-java prettyprint-override"><code>@PostMapping(value = "/users/")
public ResponseEntity<Object> users(@RequestBody PostUserRequest postUserRequest) {}
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class PostUserRequest {
@ApiParam(value = "This is optional parameter")
private String phone;
}
</code></pre>
|
[
{
"answer_id": 74610384,
"author": "Andrew Parks",
"author_id": 5898421,
"author_profile": "https://Stackoverflow.com/users/5898421",
"pm_score": 2,
"selected": false,
"text": "let arr = [{\"message\":\"message 1\",\"date\":\"date 1\",\"text\":\"text 1\"},\n {\"message\":\"message 2\",\"date\":\"date 2\",\"text\":\"text 2\"},\n {\"message\":\"message 3\",\"date\":\"date 3\",\"text\":\"text 3\"}]\n\n\nconsole.log('The following messages:');\narr.forEach((e,i)=>console.log(` ${i+1}. ${e.message} at ${e.date}`))"
},
{
"answer_id": 74610424,
"author": "Layhout",
"author_id": 17308201,
"author_profile": "https://Stackoverflow.com/users/17308201",
"pm_score": 2,
"selected": true,
"text": "let arr = [{\n 'message': \"message 1\",\n 'date': \"date 1\",\n 'text': \"text 1\"\n },\n {\n 'message': \"message 2\",\n 'date': \"date 2\",\n 'text': \"text 2\"\n },\n {\n 'message': \"message 3\",\n 'date': \"date 3\",\n 'text': \"text 3\"\n },\n];\nlet result_string = \"The following messages:\\n\\t\";\nresult_string += arr.map((a, i) => `${i+1}. ${a.message} at ${a.date}`).join(\"\\n\\t\");\nconsole.log(result_string);"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7720801/"
] |
74,610,334
|
<p>I want to write a REGEX that removes all combination of a group of characters from the end of strings. For instance removes "k", "t", "a", "u" and all of their combinations from the end of the string:</p>
<p><strong>Input:</strong></p>
<pre><code>["Rajakatu","Lapinlahdenktau","Nurmenkaut","Linnakoskenkuat"]
</code></pre>
<p><strong>Output</strong>:</p>
<pre><code>["Raja","Lapinlahden","Nurmen","Linnakosken"]
</code></pre>
|
[
{
"answer_id": 74610622,
"author": "Buttered_Toast",
"author_id": 12522652,
"author_profile": "https://Stackoverflow.com/users/12522652",
"pm_score": 2,
"selected": true,
"text": "[ktau]{4}\\b aaaa"
},
{
"answer_id": 74610684,
"author": "Kavya Kommuri",
"author_id": 18726537,
"author_profile": "https://Stackoverflow.com/users/18726537",
"pm_score": 0,
"selected": false,
"text": "from itertools import permutations\n\nmystr = [[\"Rajakatu\",\"Lapinlahdenktau\",\"Nurmenkaut\",\"Linnakoskenkuat\"]]\n\n#to get the last four letters of whose permutations you need\nx = mystr[0][0]\nexclude= x[-4:]\n\n#get the permutations\nperms = [''.join(p) for p in permutations(exclude)]\nperms\n\n#remove the last for letters of the string if it lies in the perms\nfor i in range(4):\n curr = mystr[0][i]\n last4 = curr[-4:]\n \n if(last4 in perms):\n mystr[0][i]=curr[:-4]\n \nprint(mystr)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5116559/"
] |
74,610,345
|
<p>Here i have created my trigger and it is working. how to call that trigger inside the procedure. please provide any solution for this.</p>
<p>below is my trigger</p>
<pre><code>create or replace Trigger emp_trigger
Before update on Required_table
Begin
delete from log_table;
insert into log_table(employee_name,phone_number,company_name,location,currency)
(select employee_name,phone_number,company_name,location,currency
from Required_table);
end;
</code></pre>
<p>here is my procedure code and here i want to call that above trigger code</p>
<pre><code>create or replace procedure excercise_one
is
cursor test_cur is
select employee_details.emp_name,employee_details.emp_mobile_no,company.company_name,
location.area,currency.currency
from
employee_details, company, location, currency
where
employee_details.id = company.emp_no and
company.location = location.country and
location.location_id = currency.location;
ename employee_details.emp_name%type;
emp_mob Employee_Details.Emp_Mobile_No%type;
cname company.company_name%type;
l_area location.area%type;
cur currency.currency%type;
begin
open test_cur;
loop
fetch test_cur into ename,emp_mob,cname,l_area,cur;
if test_cur%Found Then
insert into Required_table values (ename,emp_mob,cname,l_area,cur);
else
exit;
end if;
end loop;
close test_cur;
end;
</code></pre>
|
[
{
"answer_id": 74610622,
"author": "Buttered_Toast",
"author_id": 12522652,
"author_profile": "https://Stackoverflow.com/users/12522652",
"pm_score": 2,
"selected": true,
"text": "[ktau]{4}\\b aaaa"
},
{
"answer_id": 74610684,
"author": "Kavya Kommuri",
"author_id": 18726537,
"author_profile": "https://Stackoverflow.com/users/18726537",
"pm_score": 0,
"selected": false,
"text": "from itertools import permutations\n\nmystr = [[\"Rajakatu\",\"Lapinlahdenktau\",\"Nurmenkaut\",\"Linnakoskenkuat\"]]\n\n#to get the last four letters of whose permutations you need\nx = mystr[0][0]\nexclude= x[-4:]\n\n#get the permutations\nperms = [''.join(p) for p in permutations(exclude)]\nperms\n\n#remove the last for letters of the string if it lies in the perms\nfor i in range(4):\n curr = mystr[0][i]\n last4 = curr[-4:]\n \n if(last4 in perms):\n mystr[0][i]=curr[:-4]\n \nprint(mystr)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18904720/"
] |
74,610,358
|
<p>I have student and event tables linked by sid.</p>
<pre><code> CREATE TABLE `students` (
`sid` int(8) NOT NULL COMMENT 'use',
`active` enum('Yes','No','vac','Grad') NOT NULL DEFAULT 'Yes',
`name` varchar(130) DEFAULT NULL,
`bus` varchar(130) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `students` (`sid`, `LEFT(name, 2)`, `bus`) VALUES
(51, 'Me', 'BusA'),
(52, 'Hi', 'BusA'),
(59, 'An', 'BusA'),
(70, 'Mi', 'BusB'),
(100, 'Yu', 'BusB');
CREATE TABLE `STATevent` (
`eventid` int(24) NOT NULL,
`sid` int(4) NOT NULL,
`date` datetime NOT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`level` enum('absent','bus') CHARACTER SET utf8 NOT NULL,
`color` varchar(10) NOT NULL,
`Percent` tinyint(5) NOT NULL,
`note` varchar(266) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `STATevent` (`eventid`, `sid`, `date`, `created`, `level`, `color`, `Percent`, `note`) VALUES
(43, 59, '2022-11-30 21:17:04', '2022-11-28 12:17:04', 'bus', 'red', 100, '');
</code></pre>
<p>The student can select not to get bus service, which shows as an entry (like eventid 43 above). I can get the list of 'bus students', along with an id to show who cancelled service and who hasn't.</p>
<pre><code>SELECT C.name, C.sid, O.sid AS 'bid', C.bus FROM students C
LEFT JOIN STATevent O ON C.sid = O.sid
WHERE C.bus LIKE 'Bus%' AND C.active = 'Yes' ;
</code></pre>
<p>However, when I try to limit <em>where</em> with the date, the result shows only the one who cancelled service.</p>
<pre><code>SELECT C.name, C.sid, O.sid AS 'bid', C.bus FROM students C
LEFT JOIN STATevent O ON C.sid = O.sid
WHERE C.bus LIKE 'Bus%' AND C.active = 'Yes' AND O.date LIKE '2022-11-29%';
</code></pre>
<p>How can I add this limiter and get the full results like the first query?
Thanks in advance for your help.</p>
|
[
{
"answer_id": 74610393,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 3,
"selected": true,
"text": "ON SELECT c.name, c.sid, o.sid AS bid, c.bus\nFROM students c\nLEFT JOIN STATevent o\n ON o.sid = c.sid AND\n DATE(o.date) = '2022-11-29'\nWHERE c.bus LIKE 'Bus%' AND c.active = 'Yes';\n bid"
},
{
"answer_id": 74610607,
"author": "Thorsten Kettner",
"author_id": 2270762,
"author_profile": "https://Stackoverflow.com/users/2270762",
"pm_score": 1,
"selected": false,
"text": "NOT EXISTS NOT IN SELECT *\nFROM `students`\nWHERE bus LIKE 'Bus%' AND active = 'Yes'\nAND sid NOT IN\n(\n SELECT sid\n FROM `STATevent`\n WHERE DATE(date) = DATE '2022-11-30'\n)\nORDER BY sid;\n SELECT s.*\n sid IN\n (\n SELECT sid\n FROM `STATevent`\n WHERE DATE(date) = DATE '2022-11-30'\n ) AS opt_out\nFROM `students` s\nWHERE bus LIKE 'Bus%' AND active = 'Yes'\nORDER BY sid;\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2772814/"
] |
74,610,426
|
<p>I have a data file (<code>file.txt</code>) contains the below lines:</p>
<pre class="lang-none prettyprint-override"><code>123 pro=tegs, ETA=12:00, team=xyz,user1=tom,dom=dby.com
345 pro=rbs, team=abc,user1=chan,dom=sbc.int,ETA=23:00
456 team=efg, pro=bvy,ETA=22:00,dom=sss.co.uk,user2=lis
</code></pre>
<p>I'm expecting to get the first column (<code>$1</code>) only if the <code>ETA=</code> number is greater than 15, like here I will have 2nd and 3rd line first column only is expected.</p>
<pre><code>345
456
</code></pre>
<p>I tried like <code>cat file.txt | awk -F [,TPF=]' '{print $1}'</code> but its print whole line which has ETA at the end.</p>
|
[
{
"answer_id": 74610619,
"author": "tripleee",
"author_id": 874188,
"author_profile": "https://Stackoverflow.com/users/874188",
"pm_score": 2,
"selected": false,
"text": "cat -F $1 split awk -F 'ETA=' '$2 > 15 { split($0, n, /[ \\t]+/); print n[1] }' file.txt\n $2 12:00, team=xyz,user1=tom,dom=dby.com $0 n"
},
{
"answer_id": 74610702,
"author": "Daweo",
"author_id": 10785975,
"author_profile": "https://Stackoverflow.com/users/10785975",
"pm_score": 2,
"selected": false,
"text": "AWK file.txt 123 pro=tegs, ETA=12:00, team=xyz,user1=tom,dom=dby.com\n345 pro=rbs, team=abc,user1=chan,dom=sbc.int,ETA=23:00\n456 team=efg, pro=bvy,ETA=02:00,dom=sss.co.uk,user2=lis\n awk 'substr($0,index($0,\"ETA=\")+4,2)+0>15{print $1}' file.txt\n 345\n index ETA= substr ETA= ETA= index +0 15 ETA="
},
{
"answer_id": 74610923,
"author": "HatLess",
"author_id": 16372109,
"author_profile": "https://Stackoverflow.com/users/16372109",
"pm_score": 2,
"selected": false,
"text": "awk $ awk -F\"[=, ]\" '{for (i=1;i<NF;i++) if ($i==\"ETA\") if ($(i+1) > 15) print $1}' input_file\n345\n456\n"
},
{
"answer_id": 74611200,
"author": "RavinderSingh13",
"author_id": 5866580,
"author_profile": "https://Stackoverflow.com/users/5866580",
"pm_score": 3,
"selected": false,
"text": "awk match awk (^[0-9]+).*ETA=([0-9]+):[0-9]+ awk '\nmatch($0,/(^[0-9]+).*\\<ETA=([0-9]+):[0-9]+/,arr) && arr[2]+0>15{\n print arr[1]\n}\n' Input_file\n"
},
{
"answer_id": 74613496,
"author": "The fourth bird",
"author_id": 5424988,
"author_profile": "https://Stackoverflow.com/users/5424988",
"pm_score": 2,
"selected": false,
"text": "awk ETA= awk '/^[0-9]/ && match($0, /ETA=[0-9]+/) {\n if(substr($0, RSTART+4, RLENGTH-4)+0 > 15) print $1\n}' file\n 345\n456\n awk '/^[0-9]/ && match($0, /ETA=[0-9]+/) {\n if(substr($0, RSTART+4, RLENGTH-4) > 15)+0 print $1\n}' file\n"
},
{
"answer_id": 74614908,
"author": "Ed Morton",
"author_id": 1745001,
"author_profile": "https://Stackoverflow.com/users/1745001",
"pm_score": 2,
"selected": false,
"text": "tag=value v[] $ cat tst.awk\nBEGIN {\n FS = \"[, =]+\"\n OFS = \",\"\n}\n{\n delete v\n for ( i=2; i<NF; i+=2 ) {\n v[$i] = $(i+1)\n }\n}\nv[\"ETA\"]+0 > 15 {\n print $1\n}\n $ awk -f tst.awk file\n345\n456\n $ cat tst.awk\nBEGIN {\n FS = \"[, =]+\"\n OFS = \",\"\n}\n{\n delete v\n for ( i=2; i<NF; i+=2 ) {\n v[$i] = $(i+1)\n }\n}\n(v[\"pro\"] ~ /b/) && (v[\"ETA\"]+0 > 15) {\n print $1, v[\"team\"], v[\"dom\"]\n}\n $ awk -f tst.awk file\n345,abc,sbc.int\n456,efg,sss.co.uk\n"
},
{
"answer_id": 74660301,
"author": "Begging",
"author_id": 16606223,
"author_profile": "https://Stackoverflow.com/users/16606223",
"pm_score": 0,
"selected": false,
"text": "awk '$1 > digit {print $1}' file.txt\n awk -F '[,= ]' '$6 > 15 {print $1}' file.txt\n $ cat file.txt\n123 pro=tegs, ETA=12:00, team=xyz,user1=tom,dom=dby.com\n345 pro=rbs, team=abc,user1=chan,dom=sbc.int,ETA=23:00\n456 team=efg, pro=bvy,ETA=22:00,dom=sss.co.uk,user2=lis\n\n$ awk -F '[,= ]' '$6 > 15 {print $1}' file.txt\n345\n456\n"
},
{
"answer_id": 74663483,
"author": "Sahaj Raj Malla",
"author_id": 11773575,
"author_profile": "https://Stackoverflow.com/users/11773575",
"pm_score": 0,
"selected": false,
"text": "awk -F, '{if ($4 > 15) print $1}' file.txt\n awk -F, '{if ($4 > 15) print $1}' file.txt | awk '{print $1}'\n\n"
},
{
"answer_id": 74669507,
"author": "thatthing",
"author_id": 624493,
"author_profile": "https://Stackoverflow.com/users/624493",
"pm_score": 0,
"selected": false,
"text": "awk -F '[, ]' '$4 == \"ETA=\" && substr($5, 1, 2) > 15 {print $1}' file.txt\n -F option $4 == \"ETA=\" substr($5, 1, 2) > 15 HH:MM (hours:minutes) substr"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20630621/"
] |
74,610,476
|
<p>I want to find all files with specific name "stdout.1.0", move it two/three levels up from its location. While moving it two/three levels up, I also want to rename it to "testjob.out".</p>
<p>All "stdout.1.0" files are located six levels down from parent directory.</p>
<pre><code>./dirXXXXXX/dirXXXXXX/dirXXXXXX/dirXXXXXX/dirXXXXXX/dirXXXXXX/stdout.1.0
</code></pre>
<p>I used:</p>
<pre><code>find . -type f -name stdout.1.0
</code></pre>
<p>and it outputs:</p>
<pre><code>./dir100000/dir110000/dir111000/dir111100/dir111110/dir111111/stdout.1.0
./dir100000/dir110000/dir112000/dir111100/dir111110/dir111111/stdout.1.0
./dir100000/dir110000/dir113000/dir111100/dir111110/dir111111/stdout.1.0
./dir200000/dir210000/dir211000/dir211100/dir211110/dir211111/stdout.1.0
./dir200000/dir210000/dir212000/dir211100/dir211110/dir211111/stdout.1.0
./dir200000/dir210000/dir213000/dir211100/dir211110/dir211111/stdout.1.0
./dir300000/dir310000/dir311000/dir311100/dir311110/dir311111/stdout.1.0
./dir300000/dir310000/dir312000/dir311100/dir311110/dir311111/stdout.1.0
./dir300000/dir310000/dir313000/dir311100/dir311110/dir311111/stdout.1.0
.
.
./dirXXX000/dirXXX000/dirXXX000/dirXXX100/dirXXX110/dirXXX111/stdout.1.0
</code></pre>
<p>The directories above is just representative of where the file is, but there are multiple "stdout.1.0" files starting three levels down from parent directory.</p>
|
[
{
"answer_id": 74610537,
"author": "Dominique",
"author_id": 4279155,
"author_profile": "https://Stackoverflow.com/users/4279155",
"pm_score": 1,
"selected": false,
"text": "find . -type f -name stdout.1.0\n .. find . -type f -name stdout.1.0 -execdir mv {} ../../testjob.out \\;\n cp mv"
},
{
"answer_id": 74610736,
"author": "M. Nejat Aydin",
"author_id": 13809001,
"author_profile": "https://Stackoverflow.com/users/13809001",
"pm_score": 3,
"selected": true,
"text": "bash globstar find #!/bin/bash\n\nshopt -s globstar\nfor file in **/stdout.1.0; do\n echo mv \"$file\" \"${file%/*/*/*}/testjob.out\"\ndone\n echo"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20630415/"
] |
74,610,486
|
<p>I have a sample dataframe as below</p>
<p><a href="https://i.stack.imgur.com/2zCvM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2zCvM.png" alt="Column_Name Datatype
FirstName string
LastName string
Department integer
EmployeeID string" /></a></p>
<p>I want this dataframe converted to this below format in python so I can pass it into dtype</p>
<p>{
'FirstName':'string',
'LastName':'string',
'Department':'integer',
'EmployeeID':'string', }</p>
<p>Could anyone please let me know how this can be done.</p>
<p>To note above: I need the exact string <strong>{'FirstName': 'string', 'LastName': 'string', 'Department': 'integer', 'EmployeeID': 'string'}</strong> from the exact dataframe.</p>
<p>The dataframe has list of primary key names and its datatype. I want to pass this primary_key and datatype combination into <strong>concat_df.to_csv(csv_buffer, sep=",", index=False, dtype = {'FirstName': 'string', 'LastName': 'string', 'Department': 'integer', 'EmployeeID': 'string'})</strong></p>
|
[
{
"answer_id": 74610625,
"author": "Ravnclaw",
"author_id": 14571316,
"author_profile": "https://Stackoverflow.com/users/14571316",
"pm_score": 0,
"selected": false,
"text": "data = pd.DataFrame({'Column_Name' : ['FirstName', 'LastName', 'Department'], 'Datatype' : ['Jane', 'Doe', 666]}) {n[0]:n[1] for n in data.to_numpy()} {'FirstName': 'Jane', 'LastName': 'Doe', 'Department': '666'}"
},
{
"answer_id": 74610665,
"author": "AKX",
"author_id": 51685,
"author_profile": "https://Stackoverflow.com/users/51685",
"pm_score": 2,
"selected": false,
"text": "dict zip import pandas as pd\n\ndata = pd.DataFrame({\n 'Column_Name': ['FirstName', 'LastName', 'Department', 'EmployeeID'],\n 'Datatype': ['string', 'string', 'integer', 'string'],\n})\n\nmapping = dict(zip(data['Column_Name'], data['Datatype']))\n\nprint(mapping)\n {'FirstName': 'string', 'LastName': 'string', 'Department': 'integer', 'EmployeeID': 'string'}\n"
},
{
"answer_id": 74611070,
"author": "Bhargav",
"author_id": 15358800,
"author_profile": "https://Stackoverflow.com/users/15358800",
"pm_score": 1,
"selected": false,
"text": "print(dict(df.to_records(index=False)))\n {'FirstName': 'string', 'LastName': 'string', 'Department': 'integer', 'EmployeeID': 'string'}\n d = dict(df.to_records(index=False))\n\nprint(list(d.keys()))\n ['FirstName', 'LastName', 'Department', 'EmployeeID']\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4819146/"
] |
74,610,494
|
<p>I have just started learning useContext hook and I am struck in this problem.</p>
<p>I am not able use the hook itself when I am trying to print that in console its says undefined.</p>
<p>This is the App.js</p>
<pre><code>import "./styles.css";
import NoteState from "./Context/Notes/NoteState";
import About from "./components/About";
export default function App() {
return (
<>
<About />
<div>ankit</div>
<NoteState>
<About />
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
</NoteState>
</>
);
}
</code></pre>
<p>These are the files where the hook is defined</p>
<pre><code> import { createContext } from "react";
const noteContext = createContext();
export default noteContext;
Second one is
import React from "react";
import NoteContext from "./NoteContext";
const NoteState = (props) => {
const state = {
name: "Name",
surname: "Surname"
};
return (
<>
<NoteContext.Provider value={state}>
{props.childern}
</NoteContext.Provider>
</>
);
};
export default NoteState;
</code></pre>
<p>I am trying to use this in <code>About.jsx</code></p>
<pre><code>import React from "react";
import noteContext from "../Context/Notes/NoteContext";
import { useContext } from "react";
const About = () => {
const a = useContext(noteContext);
console.log(a); - >> comes undefined
return (
<>
{/* <div>this is about note me but {a.name}</div> */} this gives error
</>
);
};
export default About;
</code></pre>
<p>You can see the same in this codesand box link.
<a href="https://codesandbox.io/s/trusting-bessie-x1y23s?file=/src/components/About.jsx:0-365" rel="nofollow noreferrer">link</a></p>
|
[
{
"answer_id": 74610646,
"author": "lpizzinidev",
"author_id": 13211263,
"author_profile": "https://Stackoverflow.com/users/13211263",
"pm_score": 0,
"selected": false,
"text": "NoteContext import NoteContext from './NoteContext';\n\nexport default function App() {\n return (\n <>\n <NoteContext.Provider value={state}>\n <About />\n <div>ankit</div>\n <NoteState>\n <About />\n <div className='App'>\n <h1>Hello CodeSandbox</h1>\n <h2>Start editing to see some magic happen!</h2>\n </div>\n </NoteState>\n </NoteContext.Provider>\n </>\n );\n}\n"
},
{
"answer_id": 74610670,
"author": "arvir",
"author_id": 11971137,
"author_profile": "https://Stackoverflow.com/users/11971137",
"pm_score": 3,
"selected": true,
"text": "props.children childern"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19731938/"
] |
74,610,527
|
<p>I am running Next.js 13.0.5 with Yarn 3.2.1 and Lerna 5.6.1.</p>
<p>It seems like the main problem here is the build tool, because when I run the Next.js server itself (<code>yarn dev</code>) everything works perfectly.</p>
<p>What error am I getting?</p>
<pre><code>Type error: Cannot find module 'next/app' or its corresponding type declarations.
</code></pre>
<p>which happens here right at the start of the program</p>
<pre><code>import type { AppProps } from 'next/app'
^
</code></pre>
<pre><code>function MyApp({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />
}
</code></pre>
<p>After looking around I tried some experimental features like <code>swcFileReading : false</code>
but it doesn't seem to have any effect.</p>
|
[
{
"answer_id": 74610646,
"author": "lpizzinidev",
"author_id": 13211263,
"author_profile": "https://Stackoverflow.com/users/13211263",
"pm_score": 0,
"selected": false,
"text": "NoteContext import NoteContext from './NoteContext';\n\nexport default function App() {\n return (\n <>\n <NoteContext.Provider value={state}>\n <About />\n <div>ankit</div>\n <NoteState>\n <About />\n <div className='App'>\n <h1>Hello CodeSandbox</h1>\n <h2>Start editing to see some magic happen!</h2>\n </div>\n </NoteState>\n </NoteContext.Provider>\n </>\n );\n}\n"
},
{
"answer_id": 74610670,
"author": "arvir",
"author_id": 11971137,
"author_profile": "https://Stackoverflow.com/users/11971137",
"pm_score": 3,
"selected": true,
"text": "props.children childern"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1759249/"
] |
74,610,553
|
<p>I have the following problem:</p>
<p>I need to be able to log commands bound to the buttons in my code. The system that I am working on has all it's buttons as <code>RelayCommand</code>.
I have found a website that explains how to do this, but with <code>RoutedCommands</code>. The link is a the button of the post. Here is an example of how it works with <code>RoutedCommands</code>:</p>
<pre><code>public partial class Window1 : System.Windows.Window
{
public Window1()
{
InitializeComponent();
CommandManager.AddPreviewExecutedHandler(this, this.OnPreviewCommandExecuted);
CommandManager.AddCanExecuteHandler(this, this.OnCommandCanExecute);
}
void OnPreviewCommandExecuted(object sender, ExecutedRoutedEventArgs e)
{
StringBuilder msg = new StringBuilder();
msg.AppendLine();
RoutedCommand cmd = e.Command as RoutedCommand;
string name = cmd == null ? "n/a" : cmd.Name;
msg.AppendFormat(" Name={0}; Parameter={1}; Source={2}", name, e.Parameter, e.Source);
msg.AppendLine();
Logger.Log(msg.ToString());
}
void OnCommandCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
// For the sake of this demo, just allow all
// commands to be executed.
e.CanExecute = true;
}
}
}
</code></pre>
<p>My problem is this doesn't work with <code>RelayCommands</code> and I can't afford to change all the <code>RelayCommands</code> to <code>RoutedCommands</code>.</p>
<p>Does anybody know how this can be implemented with <code>RelayCommands</code>?</p>
<p>Here is a example of a <code>RelayCommand</code> in my code:</p>
<pre><code> private RelayCommand _closePopupCommand = new RelayCommand(() => Window.PopUpViewModel = null);
public RelayCommand ClosePopupCommand
{
get => _closePopupCommand;
set
{
_closePopupCommand = value;
RaisePropertyChanged();
}
}
</code></pre>
<p>And a the codebehind to route events:</p>
<pre><code> public readonly RoutedEvent ConditionalClickEvent = EventManager.RegisterRoutedEvent("test", RoutingStrategy.Direct, typeof(RoutedEventHandler), typeof(Button));
</code></pre>
<p>Link to the website that implements <code>RoutedCommands</code>:
<a href="https://joshsmithonwpf.wordpress.com/2007/10/25/logging-routed-commands/" rel="nofollow noreferrer">https://joshsmithonwpf.wordpress.com/2007/10/25/logging-routed-commands/</a></p>
<p>I have tried with <code>RelayCommands</code> but they don't seem to have the same functionality as <code>RoutedCommands</code>
I think it has to do with the <code>RoutedEvents</code>, that <code>RoutedCommands</code> binds.
From what I see, there are 3 options:</p>
<ol>
<li>Can't be done</li>
<li>I will have to change the <code>RelayCommands</code> to <code>RoutedCommands</code></li>
<li>Use something like <code>RegisterEventHandlers</code></li>
</ol>
|
[
{
"answer_id": 74611509,
"author": "EldHasp",
"author_id": 13349759,
"author_profile": "https://Stackoverflow.com/users/13349759",
"pm_score": 1,
"selected": false,
"text": " public MainWindow()\n {\n InitializeComponent();\n\n AddHandler(ButtonBase.ClickEvent, (RoutedEventHandler)OnClickLoger, true);\n\n }\n\n private void OnClickLoger(object sender, RoutedEventArgs e)\n {\n if (e.Source is ButtonBase button && button.Command is ICommand command)\n {\n if (command is RoutedCommand routedCommand)\n {\n Debug.WriteLine($\"Button: Name=\\\"{button.Name}\\\"; RoutedCommand=\\\"{routedCommand.Name}\\\"; CommandParameter={button.CommandParameter} \");\n }\n else\n {\n var be = button.GetBindingExpression(ButtonBase.CommandProperty);\n if (be is null)\n {\n Debug.WriteLine($\"Button: Name=\\\"{button.Name}\\\"; Command=\\\"{command}\\\"; CommandParameter={button.CommandParameter} \");\n }\n else\n {\n Debug.WriteLine($\"Button: Name=\\\"{button.Name}\\\"; Command Path=\\\"{be.ParentBinding.Path.Path}\\\"; CommandParameter={button.CommandParameter} \");\n }\n }\n }\n }\n"
},
{
"answer_id": 74620769,
"author": "BionicCode",
"author_id": 3141792,
"author_profile": "https://Stackoverflow.com/users/3141792",
"pm_score": 0,
"selected": false,
"text": "RelayCommand RelayCommand.Execute RelayCommand.Executed RoutedCommand RelayCommand RelayCommand Name Target Executed public class RelayCommand : ICommand\n{\n /**** Added members ****/\n public class ExecutedEventArgs : EventArgs\n {\n public ExecutedEventArgs(object commandParameter)\n {\n this.CommandParameter = commandParameter;\n }\n\n public object CommandParameter { get; }\n }\n\n public string Name { get; }\n public object Target => this._execute.Target;\n public event EventHandler<ExecutedEventArgs> Executed;\n\n // Constructor to set the command name\n public RelayCommand(string commandName, Action<object> execute, Predicate<object> canExecute)\n {\n this.Name = commandName;\n\n if (execute == null)\n throw new ArgumentNullException(\"execute\");\n _execute = execute;\n _canExecute = canExecute;\n }\n\n // Invoked by ICommand.Execute (added below)\n protected virtual void OnExecuted(object commandParameter)\n => this.Executed?.Invoke(this, new ExecutedEventArgs(commandParameter));\n\n /**** End added members ****/\n\n #region Fields \n readonly Action<object> _execute;\n readonly Predicate<object> _canExecute;\n private readonly Action<string> _loggerDelegate;\n #endregion // Fields \n #region Constructors \n public RelayCommand(Action<object> execute)\n : this(string.Empty, execute, null)\n { }\n\n public RelayCommand(Action<object> execute, Predicate<object> canExecute)\n : this(string.Empty, execute, canExecute)\n { }\n #endregion // Constructors \n #region ICommand Members \n public bool CanExecute(object parameter)\n {\n return _canExecute == null ? true : _canExecute(parameter);\n }\n\n public event EventHandler CanExecuteChanged\n {\n add { CommandManager.RequerySuggested += value; }\n remove { CommandManager.RequerySuggested -= value; }\n }\n\n public void Execute(object parameter)\n {\n _execute(parameter);\n OnExecuted(parameter);\n }\n #endregion // ICommand Members \n}\n public class CommandContext\n{\n public Type CommandSource { get; }\n public Type CommandTarget { get; }\n public string CommandName { get; }\n public Type Command { get; }\n public object CommandParameter { get; }\n public string CommandSourceElementName { get; }\n public DateTime Timestamp { get; }\n\n public CommandContext(string commandName, Type command, object commandParameter, Type commandSource, string sourceElementName, Type commandTarget, DateTime timestamp)\n {\n this.CommandSource = commandSource;\n this.CommandTarget = commandTarget;\n this.CommandName = commandName;\n this.Command = command;\n this.CommandParameter = commandParameter;\n this.CommandSourceElementName = sourceElementName;\n this.Timestamp = timestamp;\n }\n}\n CommandContextTracer RoutedCommand RoutedCommand ICommand ButtonBase.ClickEvent ButtonBase Click CommandContextTracer Action<CommandContext> CommandContextTracer static static UIElement UIElement public static class CommandContextTracer\n{\n private static Dictionary<object, Action<CommandContext>> LoghandlerTable { get; } = new Dictionary<object, Action<CommandContext>>();\n\n public static void RegisterCommandScopeElement(UIElement commandScopeElement, Action<CommandContext> logHandler)\n {\n if (!LoghandlerTable.TryAdd(commandScopeElement, logHandler))\n {\n return;\n }\n\n CommandManager.AddPreviewExecutedHandler(commandScopeElement, OnExecutingCommand);\n EventManager.RegisterClassHandler(commandScopeElement.GetType(), ButtonBase.ClickEvent, new RoutedEventHandler(OnEvent), true);\n }\n\n // Use this method to trace a command that is not invoked by a control.\n // TODO::Provide an Unregister(RelayCommand) method\n public static void RegisterRelayCommandInNonUiContext(RelayCommand relayCommand, Action<CommandContext> logHandler)\n {\n if (!LoghandlerTable.TryAdd(relayCommand, logHandler))\n {\n return;\n }\n\n relayCommand.Executed += OnNonUiRelayCommandExecuted;\n }\n\n private static void OnNonUiRelayCommandExecuted(object sender, RelayCommand.ExecutedEventArgs e)\n {\n var command = sender as RelayCommand;\n CommandContext context = new CommandContext(command.Name, command.GetType(), e.CommandParameter, null, string.Empty, command.Target.GetType());\n WriteContext(command, context);\n }\n\n private static void OnExecutingCommand(object sender, ExecutedRoutedEventArgs e)\n {\n if (e.Source is not ICommandSource commandSource)\n {\n return;\n }\n\n CommandContext context = CreateCommandContext(e, commandSource);\n WriteContext(sender, context);\n }\n\n private static void OnEvent(object sender, RoutedEventArgs e)\n {\n if (e.Source is not ICommandSource commandSource\n || commandSource.Command is RoutedCommand)\n {\n return;\n }\n\n CommandContext context = CreateCommandContext(e, commandSource);\n WriteContext(sender, context);\n }\n\n private static CommandContext CreateCommandContext(RoutedEventArgs e, ICommandSource commandSource)\n {\n string elementName = e.Source is FrameworkElement frameworkElement\n ? frameworkElement.Name\n : string.Empty;\n\n string commandName = commandSource.Command switch\n {\n RelayCommand relayCommand => relayCommand.Name,\n RoutedCommand routedCommand => routedCommand.Name,\n _ => string.Empty\n };\n\n Type? commandTarget = commandSource.Command switch\n {\n RelayCommand relayCommand => relayCommand.Target?.GetType(),\n RoutedCommand routedCommand => commandSource.CommandTarget?.GetType(),\n _ => null\n };\n\n return new CommandContext(\n commandName,\n commandSource.Command.GetType(),\n commandSource.CommandParameter,\n commandSource.GetType(),\n elementName,\n commandTarget,\n DateTime.Now);\n }\n\n public static void WriteContext(object contextScopeElement, CommandContext context)\n => LoghandlerTable[contextScopeElement].Invoke(context);\n}\n partial class MainWindow : Window\n{\n public static RoutedCommand NextPageCommand { get; } = new RoutedCommand(\"NextPageCommand\", typeof(MainWindow));\n\n public MainWindow()\n {\n InitializeComponent();\n this.DataContext = new TestViewModel();\n\n // Trace RoutedCommands and other ICommand\n CommandContextTracer.RegisterCommandScopeElement(this, WriteCommandContextToLogger);\n }\n \n // The actual log handler\n private void WriteCommandContextToLogger(CommandContext commandContext)\n {\n string message = $\"[{commandContext.Timestamp}] CommandName={commandContext.CommandName}; Command={commandContext.Command}; Parameter={commandContext.CommandParameter}; Source={commandContext.CommandSource}; SourceElementName={commandContext.CommandSourceElementName}; Target={commandContext.CommandTarget}\";\n\n Logger.Log(message);\n // Debug.WriteLine(message);\n }\n}\n RelayCommand public class TestViewModel : INotifyPropertyChanged\n{\n public RelayCommand TestCommand { get; }\n\n public TestViewModel()\n {\n this.TestCommand = new RelayCommand(nameof(this.TestCommand, ExecuteTestCommand);\n\n // Explicit command tracing. Only use when the command is not invoked by a control (non UI scenario)\n CommandContextTracer.RegisterRelayCommandInNonUiContext(this.TestCommand, WriteCommandContextToLogger);\n }\n\n private void WriteCommandContextToLogger(CommandContext commandContext)\n {\n string message = $\"<From TestViewModel>[{commandContext.Timestamp}] CommandName={commandContext.CommandName}; Command={commandContext.Command}; Parameter={commandContext.CommandParameter}; Source={commandContext.CommandSource}; SourceElementName={commandContext.CommandSourceElementName}; Target={commandContext.CommandTarget}\";\n\n Logger.Log(message);\n // Debug.WriteLine(message);\n }\n}\n <Window>\n <StackPanel>\n <Button x:Name=\"RelayCommandTestButton\"\n Content=\"RelayCommand\"\n Command=\"{Binding TestCommand}\"\n CommandParameter=\"1\" />\n <Button x:Name=\"RoutedCommandTestButton\"\n Content=\"RoutedCommand\"\n Command=\"{x:Static local:MainWindow.NextPageCommand}\"\n CommandParameter=\"2\" />\n </StackPanel>\n</Window>\n \"[01/01/2022 00:00:00] CommandName=TestCommand; Command=Net.Wpf.RelayCommand; Parameter=1; Source=System.Windows.Controls.Button; SourceElementName=RelayCommandTestButton; Target=Net.Wpf.TestViewModel\" \n\"[01/01/2022 00:00:00] CommandName=NextPageCommand; Command=System.Windows.Input.RoutedCommand; Parameter=2; Source=System.Windows.Controls.Button; SourceElementName=RoutedCommandTestButton; Target=\" \n\"<From TestViewModel>[01/01/2022 00:00:00] CommandName=TestCommand; Command=Net.Wpf.RelayCommand; Parameter=2; Source=unknown; SourceElementName=; Target=Net.Wpf.TestViewModel\"\n\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20600659/"
] |
74,610,565
|
<p>How would you write this without the help of any packages ?
(same layout where mergeSort(int[] A) (take input of one array) and same with merge(int[] a, int[] l, int[] r)).
Main issue is transalting Arrays.copyOfRange into the non -package version of java into this code.
Thank you for answering this question.</p>
<p>Another question of mine would be of how to implelment a merge function with 3 arrays this time in its parameters.</p>
<p>this is code i tried:</p>
<pre><code> public static int[] mergeArrays3(int[] a, int[] b, int[] c) {
int[] result = new int[a.length + b.length +c.length];
int i = 0, j = 0, k = 0, l=0;
while(i<a.length &&j<b.length && l<c.length)
{
// if (b[i] < a[j] || b[i] <c[i]) {
// result[k] = c[i];
// j++;
// }
if (c[i] < b[j] || c[i] <a[i]) {
result[k] = c[i];
l++;
}
if (a[i] < b[j] || a[i] <c[i]) {
result[k] = a[i];
i++;
}
else {
result[k] = b[j];
j++;
}
k++;
}
while(i<a.length)
{
result[k] = a[i];
i++;
k++;
}
while(j<b.length)
{
result[k] = b[j];
j++;
k++;
}
while(l<c.length)
{
result[k]=c[l];
l++;
k++;
}
return result;
}
```
import java.io.*;
import java.util.Arrays;
public class MergeSort {
public static void main(String[] args) throws IOException{
BufferedReader R = new BufferedReader(new InputStreamReader(System.in));
int arraySize = Integer.parseInt(R.readLine());
int[] inputArray = new int[arraySize];
for (int i = 0; i < arraySize; i++) {
inputArray[i] = Integer.parseInt(R.readLine());
}
mergeSort(inputArray);
for (int j = 0; j < inputArray.length; j++) {
System.out.println(inputArray[j]);
}
}
static void mergeSort(int[] A) {
if (A.length > 1) {
int q = A.length/2;
//changed range of leftArray from 0-to-q to 0-to-(q-1),how would you edit Arrays.copyOfRange to manually make the same function without using any packages?
*int[] leftArray = Arrays.copyOfRange(A, 0, q-1);
//changed range of rightArray from q-to-A.length to q-to-(A.length-1)
int[] rightArray = Arrays.copyOfRange(A,q,A.length-1);*
mergeSort(leftArray);
mergeSort(rightArray);
merge(A,leftArray,rightArray);
}
}
static void merge(int[] a, int[] l, int[] r) {
int totElem = l.length + r.length;
//int[] a = new int[totElem];
int i,li,ri;
i = li = ri = 0;
while ( i < totElem) {
if ((li < l.length) && (ri<r.length)) {
if (l[li] < r[ri]) {
a[i] = l[li];
i++;
li++;
}
else {
a[i] = r[ri];
i++;
ri++;
}
}
else {
if (li >= l.length) {
while (ri < r.length) {
a[i] = r[ri];
i++;
ri++;
}
}
if (ri >= r.length) {
while (li < l.length) {
a[i] = l[li];
li++;
i++;
}
}
}
}
//return a;
}
</code></pre>
<p>}</p>
<pre><code>
</code></pre>
|
[
{
"answer_id": 74610831,
"author": "Rustam",
"author_id": 15322661,
"author_profile": "https://Stackoverflow.com/users/15322661",
"pm_score": 0,
"selected": false,
"text": "Arrays.copyOfRange private static int[] copyArray(int[] original, int from, int to) {\n int [] res = new int[to-from];\n for (int i = from; i< to; i++) {\n res[i - from] = original[i];\n }\n return res;\n}\n"
},
{
"answer_id": 74620660,
"author": "rcgldr",
"author_id": 3282056,
"author_profile": "https://Stackoverflow.com/users/3282056",
"pm_score": -1,
"selected": false,
"text": "bb ee static void MergeSort(int[] a)\n {\n if(a.length < 2) // if < 2 elements, nothing to sort\n return;\n int [] b = new int[a.length]; // b[] = a[] | int[]b = a.clone();\n for(int i = 0; i < a.length; i++)\n b[i] = a[i];\n MergeSortR(b, a, 0, a.length); // sort b[] to a[]\n }\n\n static void MergeSortR(int[] b, int[] a, int bb, int ee)\n {\n if(ee - bb < 2) // if < 2 elements, nothing to sort\n return;\n if(ee - bb == 2){ // if 2 elements\n if(a[bb] > a[bb+1]){\n int t = a[bb];\n a[bb] = a[bb+1];\n a[bb+1] = t;\n }\n return;\n }\n int m1 = bb+(ee+0-bb)/3; // split into 3 parts\n int m2 = m1+(ee+1-bb)/3;\n MergeSortR(a, b, bb, m1); // sort a[] to b[]\n MergeSortR(a, b, m1, m2);\n MergeSortR(a, b, m2, ee);\n Merge(b, a, bb, m1, m2, ee); // merge b[] to a[]\n }\n \n static void Merge(int[] a, int[] b, int bb, int m1, int m2, int ee)\n {\n int b0 = bb; // b[] index\n int a0 = bb; // a[] indexes\n int a1 = m1;\n int a2 = m2;\n while(true){ // 3 way merge\n if(a[a0] <= a[a1]){\n if(a[a0] <= a[a2]){\n b[b0] = a[a0]; // a[a0] smallest\n b0++;\n a0++;\n if(a0 < m1) // if not end of run\n continue; // continue\n a0 = a1; // else setup for 2 way merge\n a1 = a2;\n m1 = m2;\n m2 = ee;\n break;\n } else {\n b[b0] = a[a2]; // a[a2] smallest\n b0++;\n a2++;\n if(a2 < ee) // if not end of run\n continue; // continue\n break; // else setup for 2 way merge\n }\n } else {\n if(a[a1] <= a[a2]){\n b[b0] = a[a1]; // a[a1] smallest\n b0++;\n a1++;\n if(a1 < m2) // if not end of run\n continue; // continue\n a1 = a2; // else setup for 2 way merge\n m2 = ee;\n break;\n } else {\n b[b0] = a[a2]; // a[a2] smallest\n b0++;\n a2++;\n if(a2 < ee) // if not end of run\n continue; // continue\n break; // else setup for 2 way merge\n }\n }\n } \n while(true){ // 2 way merge\n if(a[a0] <= a[a1]){\n b[b0] = a[a0];\n b0++;\n a0++;\n if(a0 < m1) // if not end of run\n continue; // continue\n a0 = a1; // else setup for copy\n m1 = m2;\n break;\n }else{\n b[b0] = a[a1];\n b0++;\n a1++;\n if(a1 < m2) // if not end of run\n continue; // continue\n break; // else setup for copy\n }\n }\n while(true){ // copy rest of remaining run\n b[b0] = a[a0];\n b0++;\n a0++;\n if(a0 < m1)\n continue;\n break;\n }\n }\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20627192/"
] |
74,610,569
|
<p>i want to use controller and initialValue both at same time but showing error</p>
<pre><code>TextFormField(
controller: txtEmail,
initialValue: initialValues['emailAddress'],
decoration: InputDecoration(
prefixIcon: Icon(Icons.email),
label: Text('Email Address'),
focusedBorder: UnderlineInputBorder(borderSide: BorderSide(color: accentColor)),
enabledBorder: UnderlineInputBorder(borderSide: BorderSide(color: iconColor))
),
),
</code></pre>
|
[
{
"answer_id": 74610831,
"author": "Rustam",
"author_id": 15322661,
"author_profile": "https://Stackoverflow.com/users/15322661",
"pm_score": 0,
"selected": false,
"text": "Arrays.copyOfRange private static int[] copyArray(int[] original, int from, int to) {\n int [] res = new int[to-from];\n for (int i = from; i< to; i++) {\n res[i - from] = original[i];\n }\n return res;\n}\n"
},
{
"answer_id": 74620660,
"author": "rcgldr",
"author_id": 3282056,
"author_profile": "https://Stackoverflow.com/users/3282056",
"pm_score": -1,
"selected": false,
"text": "bb ee static void MergeSort(int[] a)\n {\n if(a.length < 2) // if < 2 elements, nothing to sort\n return;\n int [] b = new int[a.length]; // b[] = a[] | int[]b = a.clone();\n for(int i = 0; i < a.length; i++)\n b[i] = a[i];\n MergeSortR(b, a, 0, a.length); // sort b[] to a[]\n }\n\n static void MergeSortR(int[] b, int[] a, int bb, int ee)\n {\n if(ee - bb < 2) // if < 2 elements, nothing to sort\n return;\n if(ee - bb == 2){ // if 2 elements\n if(a[bb] > a[bb+1]){\n int t = a[bb];\n a[bb] = a[bb+1];\n a[bb+1] = t;\n }\n return;\n }\n int m1 = bb+(ee+0-bb)/3; // split into 3 parts\n int m2 = m1+(ee+1-bb)/3;\n MergeSortR(a, b, bb, m1); // sort a[] to b[]\n MergeSortR(a, b, m1, m2);\n MergeSortR(a, b, m2, ee);\n Merge(b, a, bb, m1, m2, ee); // merge b[] to a[]\n }\n \n static void Merge(int[] a, int[] b, int bb, int m1, int m2, int ee)\n {\n int b0 = bb; // b[] index\n int a0 = bb; // a[] indexes\n int a1 = m1;\n int a2 = m2;\n while(true){ // 3 way merge\n if(a[a0] <= a[a1]){\n if(a[a0] <= a[a2]){\n b[b0] = a[a0]; // a[a0] smallest\n b0++;\n a0++;\n if(a0 < m1) // if not end of run\n continue; // continue\n a0 = a1; // else setup for 2 way merge\n a1 = a2;\n m1 = m2;\n m2 = ee;\n break;\n } else {\n b[b0] = a[a2]; // a[a2] smallest\n b0++;\n a2++;\n if(a2 < ee) // if not end of run\n continue; // continue\n break; // else setup for 2 way merge\n }\n } else {\n if(a[a1] <= a[a2]){\n b[b0] = a[a1]; // a[a1] smallest\n b0++;\n a1++;\n if(a1 < m2) // if not end of run\n continue; // continue\n a1 = a2; // else setup for 2 way merge\n m2 = ee;\n break;\n } else {\n b[b0] = a[a2]; // a[a2] smallest\n b0++;\n a2++;\n if(a2 < ee) // if not end of run\n continue; // continue\n break; // else setup for 2 way merge\n }\n }\n } \n while(true){ // 2 way merge\n if(a[a0] <= a[a1]){\n b[b0] = a[a0];\n b0++;\n a0++;\n if(a0 < m1) // if not end of run\n continue; // continue\n a0 = a1; // else setup for copy\n m1 = m2;\n break;\n }else{\n b[b0] = a[a1];\n b0++;\n a1++;\n if(a1 < m2) // if not end of run\n continue; // continue\n break; // else setup for copy\n }\n }\n while(true){ // copy rest of remaining run\n b[b0] = a[a0];\n b0++;\n a0++;\n if(a0 < m1)\n continue;\n break;\n }\n }\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20377589/"
] |
74,610,606
|
<p>How can I use observeEvent capture the HTML input id in shiny ?</p>
<pre><code>shinyApp(
ui = basicPage( HTML('<input type="button" name = "b1" value="Travel time"/>')),
server = function(input, output, session) {
observeEvent(input$b1, {
print(paste("This will only be printed once; all",
"subsequent button clicks won't do anything"))
}, once = TRUE)
}
)
</code></pre>
<p>I want to implement the function use HTML in shiny that when I clicked the 'Travel time',the event can be observeed.</p>
|
[
{
"answer_id": 74611706,
"author": "Bertil Baron",
"author_id": 1951485,
"author_profile": "https://Stackoverflow.com/users/1951485",
"pm_score": 1,
"selected": false,
"text": "shinyjs shinyApp(\n ui = basicPage(\n shinyjs::useShinyjs(),\n HTML('<input type=\"button\" id = \"b1\" value=\"Travel time\"/>')\n ),\n \n server = function(input, output, session) {\n shinyjs::onclick(\n \"b1\",\n {\n shinyjs::disable(id = \"b1\")\n print(paste(\"This will only be printed once; all\",\n \"subsequent button clicks won't do anything\"))\n }\n )\n \n }\n)\n"
},
{
"answer_id": 74614236,
"author": "Stéphane Laurent",
"author_id": 1100107,
"author_profile": "https://Stackoverflow.com/users/1100107",
"pm_score": 3,
"selected": true,
"text": "shinyApp(\n ui = basicPage( \n HTML('<button type=\"button\" id=\"b1\" class=\"action-button\">Travel time</button>')\n ),\n \n server = function(input, output, session) {\n observeEvent(input$b1, {\n print(paste(\"This will only be printed once; all\",\n \"subsequent button clicks won't do anything\"))\n }, once = TRUE) \n }\n\n)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20297769/"
] |
74,610,638
|
<p>I am trying to change the eraser icon of a slicer in power BI! is it possible to change it?</p>
|
[
{
"answer_id": 74611706,
"author": "Bertil Baron",
"author_id": 1951485,
"author_profile": "https://Stackoverflow.com/users/1951485",
"pm_score": 1,
"selected": false,
"text": "shinyjs shinyApp(\n ui = basicPage(\n shinyjs::useShinyjs(),\n HTML('<input type=\"button\" id = \"b1\" value=\"Travel time\"/>')\n ),\n \n server = function(input, output, session) {\n shinyjs::onclick(\n \"b1\",\n {\n shinyjs::disable(id = \"b1\")\n print(paste(\"This will only be printed once; all\",\n \"subsequent button clicks won't do anything\"))\n }\n )\n \n }\n)\n"
},
{
"answer_id": 74614236,
"author": "Stéphane Laurent",
"author_id": 1100107,
"author_profile": "https://Stackoverflow.com/users/1100107",
"pm_score": 3,
"selected": true,
"text": "shinyApp(\n ui = basicPage( \n HTML('<button type=\"button\" id=\"b1\" class=\"action-button\">Travel time</button>')\n ),\n \n server = function(input, output, session) {\n observeEvent(input$b1, {\n print(paste(\"This will only be printed once; all\",\n \"subsequent button clicks won't do anything\"))\n }, once = TRUE) \n }\n\n)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13002545/"
] |
74,610,668
|
<p>How do you replace numbers with np.nan in selected columns if the number falls in between 2 ranges?</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
</tr>
</thead>
<tbody>
<tr>
<td>2</td>
<td>3</td>
<td>5</td>
<td>7</td>
</tr>
<tr>
<td>2</td>
<td>8</td>
<td>9</td>
<td>7</td>
</tr>
<tr>
<td>5</td>
<td>3</td>
<td>6</td>
<td>7</td>
</tr>
</tbody>
</table>
</div>
<p>select columns B & C replace numbers if number is <=5 and >=7</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
</tr>
</thead>
<tbody>
<tr>
<td>2</td>
<td>NaN</td>
<td>5</td>
<td>7</td>
</tr>
<tr>
<td>2</td>
<td>NaN</td>
<td>NaN</td>
<td>7</td>
</tr>
<tr>
<td>5</td>
<td>NaN</td>
<td>6</td>
<td>7</td>
</tr>
</tbody>
</table>
</div>
|
[
{
"answer_id": 74610767,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 3,
"selected": true,
"text": "cols = ['B', 'C']\nm = (df[cols].gt(7)|df[cols].lt(5)).reindex(columns=df.columns, fill_value=False)\n\ndf[m] = np.nan\n cols = ['B', 'C']\nout = df.mask((df[cols].gt(7)|df[cols].lt(5))\n .reindex(columns=df.columns, fill_value=False))\n A B C D\n0 2 NaN 5.0 7\n1 2 NaN NaN 7\n2 5 NaN 6.0 7\n (df[cols].gt(7)|df[cols].lt(5))\n\n B C\n0 True False\n1 True True\n2 True False\n\n(df[cols].gt(7)|df[cols].lt(5)).reindex(columns=df.columns, fill_value=False)\n\n A B C D\n0 False True False False\n1 False True True False\n2 False True False False\n"
},
{
"answer_id": 74610939,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 0,
"selected": false,
"text": "DataFrame.mask cols = ['B', 'C']\n\ndf[cols] = df[cols].mask(df[cols].gt(7) | df[cols].lt(5))\nprint (df)\n A B C D\n0 2 NaN 5.0 7\n1 2 NaN NaN 7\n2 5 NaN 6.0 7\n numpy.where cols = ['B', 'C']\n\ndf[cols] = np.where(df[cols].gt(7) | df[cols].lt(5), np.nan, df[cols])\nprint (df)\n A B C D\n0 2 NaN 5.0 7\n1 2 NaN NaN 7\n2 5 NaN 6.0 7\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10062025/"
] |
74,610,682
|
<p>I want to write a cobol program when my input is 15.65778 then output should me 15.66
and When my input is 15.65000 then Output should be 15.65.
Here rules is Basically two digits after the decimal point if its zero then output should be same otherwise input should be incremented by 0.1</p>
<p>Iam expecting a solution for this.</p>
|
[
{
"answer_id": 74615945,
"author": "Roie",
"author_id": 4205233,
"author_profile": "https://Stackoverflow.com/users/4205233",
"pm_score": 0,
"selected": false,
"text": "input pic 99v9(5)\ntemp pic 99v99\nres-r pic 99.99\n\nIF input(5:1) > 4 OR = ZERO \n COMPUTE temp ROUNDED = input\n move temp to res-r \nELSE\n COMPUTE temp = input + 0.01\n move temp to res-r \nEND-IF \n"
},
{
"answer_id": 74615954,
"author": "Rick Smith",
"author_id": 9170346,
"author_profile": "https://Stackoverflow.com/users/9170346",
"pm_score": 1,
"selected": false,
"text": "REM data division.\n working-storage section.\n 01 values-table.\n 03 pic 99v9(5) value 15.65000.\n 03 pic 99v9(5) value 15.65001.\n 03 pic 99v9(5) value 15.65778.\n 01 redefines values-table.\n 03 values-entry pic 99v9(5) occurs 3 indexed idx.\n 01 r pic v9(5). *> remainder\n 01 out-value pic 99.9(5).\n 01 out-result pic 99.99.\n procedure division.\n perform varying idx from 1 by 1\n until idx > 3\n move values-entry (idx) to out-value\n\n *> find the value beyond two decimal places\n compute r = function rem (values-entry (idx) 0.01)\n\n *> if that value is greater than zero\n if r > 0\n\n *> add 0.01 before truncating the result\n compute out-result = values-entry (idx) + 0.01\n else\n\n *> otherwise truncate the result\n move values-entry (idx) to out-result\n end-if\n\n display out-value \" : \" out-result\n end-perform\n goback\n .\n 15.65000 : 15.65\n15.65001 : 15.66\n15.65778 : 15.66\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20563397/"
] |
74,610,692
|
<p>I would like to have my EKS nodes being able to host new pods only after a particular daemonSet pod is up and running.
If a better way is to schedule pods only after ALL daemonsets are up, I am okay with that.</p>
<p>How should I approach it?</p>
|
[
{
"answer_id": 74615945,
"author": "Roie",
"author_id": 4205233,
"author_profile": "https://Stackoverflow.com/users/4205233",
"pm_score": 0,
"selected": false,
"text": "input pic 99v9(5)\ntemp pic 99v99\nres-r pic 99.99\n\nIF input(5:1) > 4 OR = ZERO \n COMPUTE temp ROUNDED = input\n move temp to res-r \nELSE\n COMPUTE temp = input + 0.01\n move temp to res-r \nEND-IF \n"
},
{
"answer_id": 74615954,
"author": "Rick Smith",
"author_id": 9170346,
"author_profile": "https://Stackoverflow.com/users/9170346",
"pm_score": 1,
"selected": false,
"text": "REM data division.\n working-storage section.\n 01 values-table.\n 03 pic 99v9(5) value 15.65000.\n 03 pic 99v9(5) value 15.65001.\n 03 pic 99v9(5) value 15.65778.\n 01 redefines values-table.\n 03 values-entry pic 99v9(5) occurs 3 indexed idx.\n 01 r pic v9(5). *> remainder\n 01 out-value pic 99.9(5).\n 01 out-result pic 99.99.\n procedure division.\n perform varying idx from 1 by 1\n until idx > 3\n move values-entry (idx) to out-value\n\n *> find the value beyond two decimal places\n compute r = function rem (values-entry (idx) 0.01)\n\n *> if that value is greater than zero\n if r > 0\n\n *> add 0.01 before truncating the result\n compute out-result = values-entry (idx) + 0.01\n else\n\n *> otherwise truncate the result\n move values-entry (idx) to out-result\n end-if\n\n display out-value \" : \" out-result\n end-perform\n goback\n .\n 15.65000 : 15.65\n15.65001 : 15.66\n15.65778 : 15.66\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9733887/"
] |
74,610,700
|
<p>I have this class:</p>
<pre><code>public class Division
{
public int Id { get; set; }
public string Naam { get; set; }
public ICollection<Division> Children { get; set; }
}
</code></pre>
<p>Example of the filled object/list:</p>
<pre><code>
Id 1
Name "HQ"
Children
0
Id 200
Name "HR"
Children
0
Id 800
Name "Payrolls"
Children
0
Id 1001
Name "Years"
Children
1
Id 1002
Name "Level"
Children
1
Id 900
Name "Functions"
Children
0
Id 2000
Naam "Grades"
Children
...
</code></pre>
<p>Each item can have many nested 'Children'.
Now I want to find an item by Id, how can I achieve this?</p>
<p>I tried to put the result into a list.
<code>lstDivision = Division.Children.ToList();</code></p>
<p>and find the item by:
<code>Division d = lstDivision.SelectMany(d => d.Children).Where(c => c.Id==2000).FirstOrDefault();</code></p>
<p>The result is null.</p>
|
[
{
"answer_id": 74610933,
"author": "Fildor",
"author_id": 982149,
"author_profile": "https://Stackoverflow.com/users/982149",
"pm_score": 0,
"selected": false,
"text": "// given: `Division` is a nullable reference type, probably a class\n// I am refering to the `Division` class as given in question at the time of writing.\n\npublic Division FindDivisionByID( Division parent, int targetID )\n{\n // Do we have the Node we were looking for already?\n // Yes: Return it.\n if( parent.Id == targetId ) return parent;\n\n // No: Process Children one by one\n foreach( var child in parent.Children )\n // Little assignment for OP: ^^ this does not take into account\n // that `parent.Children` could be null and will throw if it is.\n // You would want to fortify against that.\n {\n // If a descendant of this child or the child itself\n // was the one we are looking for, `childResult` will \n // point to it. If not it will be null.\n var childResult = FindDivisionByID( child, targetID );\n // The requested Node was in this child's subtree?\n // Yes: Return it.\n if( childResult is not null ) return childResult;\n // No: Next child if there is one.\n }\n // Neither this Node nor any of its Children nor any of their \n // descendants was the one we are looking for.\n return null;\n}\n"
},
{
"answer_id": 74611028,
"author": "Jodrell",
"author_id": 659190,
"author_profile": "https://Stackoverflow.com/users/659190",
"pm_score": 1,
"selected": false,
"text": "public static IEnumerable<T> DepthFirstTraversal<T>(\n this T root,\n Func<T, IEnumerable<T>> branchSelector)\n{\n ArgumentNullException.ThrowIfNull(branchSelector);\n \n var stack = new Stack<T>();\n stack.Push(root);\n while(stack.Count > 0)\n {\n var current = stack.Pop();\n yield return current;\n \n if (current == null)\n {\n continue;\n }\n \n foreach(var child in branchSelector(current))\n {\n stack.Push(child);\n }\n }\n}\n division\n .DepthFirstTraversal(d => d.Children)\n .Where(c => c.Id==2000)\n .FirstOrDefault();\n \n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20630814/"
] |
74,610,714
|
<p>I am trying to read cells for a xlsx file(provided by user) using Apache POI.</p>
<pre><code>val workbook: org.apache.poi.ss.usermodel = ...
workbook.getName("cellname")
</code></pre>
<p>This works fine for one of the input file, but returns null for another file.
Do we need to make any specific changes in input file first to make it compatible with this API?</p>
|
[
{
"answer_id": 74610933,
"author": "Fildor",
"author_id": 982149,
"author_profile": "https://Stackoverflow.com/users/982149",
"pm_score": 0,
"selected": false,
"text": "// given: `Division` is a nullable reference type, probably a class\n// I am refering to the `Division` class as given in question at the time of writing.\n\npublic Division FindDivisionByID( Division parent, int targetID )\n{\n // Do we have the Node we were looking for already?\n // Yes: Return it.\n if( parent.Id == targetId ) return parent;\n\n // No: Process Children one by one\n foreach( var child in parent.Children )\n // Little assignment for OP: ^^ this does not take into account\n // that `parent.Children` could be null and will throw if it is.\n // You would want to fortify against that.\n {\n // If a descendant of this child or the child itself\n // was the one we are looking for, `childResult` will \n // point to it. If not it will be null.\n var childResult = FindDivisionByID( child, targetID );\n // The requested Node was in this child's subtree?\n // Yes: Return it.\n if( childResult is not null ) return childResult;\n // No: Next child if there is one.\n }\n // Neither this Node nor any of its Children nor any of their \n // descendants was the one we are looking for.\n return null;\n}\n"
},
{
"answer_id": 74611028,
"author": "Jodrell",
"author_id": 659190,
"author_profile": "https://Stackoverflow.com/users/659190",
"pm_score": 1,
"selected": false,
"text": "public static IEnumerable<T> DepthFirstTraversal<T>(\n this T root,\n Func<T, IEnumerable<T>> branchSelector)\n{\n ArgumentNullException.ThrowIfNull(branchSelector);\n \n var stack = new Stack<T>();\n stack.Push(root);\n while(stack.Count > 0)\n {\n var current = stack.Pop();\n yield return current;\n \n if (current == null)\n {\n continue;\n }\n \n foreach(var child in branchSelector(current))\n {\n stack.Push(child);\n }\n }\n}\n division\n .DepthFirstTraversal(d => d.Children)\n .Where(c => c.Id==2000)\n .FirstOrDefault();\n \n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2444661/"
] |
74,610,715
|
<p>We're using WebSphere AppServer 8.5 for Web processing, but at a specific point in time, such as 8 a.m., we get thread deadlocks and eventually the thread hangs. One hour later, the AppServer is running slowly. One hour later, however, the AppServer recovers. After checking the scheduled tasks of the operating system, it is found that no task is executed at 8:00 a.m.</p>
<pre><code>1CIJAVAVERSION JRE 1.7.0 Windows 7 x86-32 build (pwi3270sr9-20150417_01(SR9) )
1CIVMVERSION VM build R26_Java726_SR9_20150406_1443_B242981
1CIJITVERSION tr.r11_20150401_88894
1CIGCVERSION GC - R26_Java726_SR9_20150406_1443_B242981
1CIJITMODES JIT enabled, AOT enabled, FSD disabled, HCR disabled
1CIRUNNINGAS Running as a standalone JVM
1CIPROCESSID Process ID: 10332 (0x285C)
1CICMDLINE C:\IBMRPT_871\SDP\jdk\bin\java.exe -DrptNextgenDebug -Drptserver.rootDiscoveryUrl=http://9.84.122.22:7081/deployment/ -Drptagent.agentName=localhost -Drptagent.engineName=localhost -Drptagent.scheduleName=sched2 -Drptagent.rptDeployDir=file:/C:/Users/IBM_ADMIN/IBM/RPTCitrixTest871/deployment_root/gdaronde/A1E515CFE7BA0690C143E56139636135/ -Drptagent.secure=false -Drptagent.securePort=7444 -Drptagent.installBase=C:/IBMRPT_871/SDP/Majordomo/ -Xmx1200m -DrptLocale=fr_FR -Drptserver.domoHeavyClass=com.ibm.rational.test.lt.kernel.runner.impl.RPTNextgenRunner -Drptserver.domoLiteUrl=file:/C:/IBMRPT_871/SDP/Majordomo/lib/ -Drptserver.domoLiteClass=com.ibm.rational.test.lt.nextgen.Domo -cp C:\IBMRPT_871\SDP\Majordomo\lib\boot.jar com.ibm.rational.test.lt.boot.DomoBooter
1CIJAVAHOMEDIR Java Home Dir: C:\IBMRPT_871\SDP\jdk\jre
1CIJAVADLLDIR Java DLL Dir: C:\IBMRPT_871\SDP\jdk\jre\bin
1CISYSCP Sys Classpath: C:\IBMRPT_871\SDP\jdk\jre\bin\default\jclSC170\vm.jar;C:\IBMRPT_871\SDP\jdk\jre\lib\se-service.jar;C:\IBMRPT_871\SDP\jdk\jre\lib\math.jar;C:\IBMRPT_871\SDP\jdk\jre\lib\jlm.jar;C:\IBMRPT_871\SDP\jdk\jre\lib\ibmorb.jar;C:\IBMRPT_871\SDP\jdk\jre\lib\ibmorbapi.jar;C:\IBMRPT_871\SDP\jdk\jre\lib\ibmcfw.jar;C:\IBMRPT_871\SDP\jdk\jre\lib\ibmpkcs.jar;C:\IBMRPT_871\SDP\jdk\jre\lib\ibmcertpathfw.jar;C:\IBMRPT_871\SDP\jdk\jre\lib\ibmjgssfw.jar;C:\IBMRPT_871\SDP\jdk\jre\lib\ibmjssefw.jar;C:\IBMRPT_871\SDP\jdk\jre\lib\ibmsaslfw.jar;C:\IBMRPT_871\SDP\jdk\jre\lib\ibmjcefw.jar;C:\IBMRPT_871\SDP\jdk\jre\lib\ibmjgssprovider.jar;C:\IBMRPT_871\SDP\jdk\jre\lib\ibmjsseprovider2.jar;C:\IBMRPT_871\SDP\jdk\jre\lib\ibmcertpathprovider.jar;C:\IBMRPT_871\SDP\jdk\jre\lib\xmldsigfw.jar;C:\IBMRPT_871\SDP\jdk\jre\lib\xml.jar;C:\IBMRPT_871\SDP\jdk\jre\lib\charsets.jar;C:\IBMRPT_871\SDP\jdk\jre\lib\resources.jar;C:\IBMRPT_871\SDP\jdk\jre\lib\rt.jar;C:\IBMRPT_871\SDP\jdk\jre\lib\ibmgpu.jar;
1CIUSERARGS UserArgs:
2CIUSERARG -Xoptionsfile=C:\IBMRPT_871\SDP\jdk\jre\bin\default\options.default
</code></pre>
<pre><code>0MEMUSER
1MEMUSER JRE: 1,320,399,028 bytes / 2770 allocations
1MEMUSER |
2MEMUSER +--VM: 1,315,550,900 bytes / 2282 allocations
2MEMUSER | |
3MEMUSER | +--Classes: 16,393,128 bytes / 508 allocations
2MEMUSER | |
3MEMUSER | +--Memory Manager (GC): 1,284,062,768 bytes / 446 allocations
3MEMUSER | | |
4MEMUSER | | +--Java Heap: 1,258,291,200 bytes / 1 allocation
3MEMUSER | | |
4MEMUSER | | +--Other: 25,771,568 bytes / 445 allocations
2MEMUSER | |
3MEMUSER | +--Threads: 13,546,748 bytes / 236 allocations
3MEMUSER | | |
4MEMUSER | | +--Java Stack: 475,728 bytes / 50 allocations
3MEMUSER | | |
4MEMUSER | | +--Native Stack: 12,746,752 bytes / 50 allocations
3MEMUSER | | |
4MEMUSER | | +--Other: 324,268 bytes / 136 allocations
2MEMUSER | |
3MEMUSER | +--Trace: 444,968 bytes / 353 allocations
2MEMUSER | |
3MEMUSER | +--JVMTI: 17,328 bytes / 13 allocations
2MEMUSER | |
3MEMUSER | +--JNI: 70,504 bytes / 290 allocations
2MEMUSER | |
3MEMUSER | +--Port Library: 9,632 bytes / 74 allocations
2MEMUSER | |
3MEMUSER | +--Other: 1,005,824 bytes / 362 allocations
1MEMUSER |
2MEMUSER +--JIT: 3,880,280 bytes / 225 allocations
2MEMUSER | |
3MEMUSER | +--JIT Code Cache: 1,048,576 bytes / 2 allocations
2MEMUSER | |
3MEMUSER | +--JIT Data Cache: 524,336 bytes / 1 allocation
2MEMUSER | |
3MEMUSER | +--Other: 2,307,368 bytes / 222 allocations
1MEMUSER |
2MEMUSER +--Class Libraries: 967,848 bytes / 263 allocations
2MEMUSER | |
3MEMUSER | +--Harmony Class Libraries: 1,024 bytes / 1 allocation
2MEMUSER | |
3MEMUSER | +--VM Class Libraries: 966,824 bytes / 262 allocations
3MEMUSER | | |
4MEMUSER | | +--sun.misc.Unsafe: 72,360 bytes / 10 allocations
4MEMUSER | | | |
5MEMUSER | | | +--Direct Byte Buffers: 66,040 bytes / 8 allocations
4MEMUSER | | | |
5MEMUSER | | | +--Other: 6,320 bytes / 2 allocations
3MEMUSER | | |
4MEMUSER | | +--Other: 894,464 bytes / 252 allocations
</code></pre>
<pre><code>3XMTHREADINFO "Brother-7" J9VMThread:0x518FDD00, j9thread_t:0x527F7634, java/lang/Thread:0x030B1D80, state:P, prio=5
3XMJAVALTHREAD (java/lang/Thread getId:0x32, isDaemon:true)
3XMTHREADINFO1 (native thread ID:0xA44, native priority:0x5, native policy:UNKNOWN, vmstate:P, vm thread flags:0x01020000)
3XMCPUTIME CPU usage total: 0.0 secs, user: 0.0 secs, system: 0.0 secs
3XMTHREADBLOCK Parked on: java/util/concurrent/locks/AbstractQueuedSynchronizer$ConditionObject@0x02E83C68 Owned by: <unknown>
3XMHEAPALLOC Heap bytes allocated since last GC cycle=0 (0x0)
3XMTHREADINFO3 Java callstack:
4XESTACKTRACE at sun/misc/Unsafe.park(Native Method)
4XESTACKTRACE at java/util/concurrent/locks/LockSupport.park(LockSupport.java:198)
4XESTACKTRACE at java/util/concurrent/locks/AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2055)
4XESTACKTRACE at java/util/concurrent/LinkedBlockingDeque.takeFirst(LinkedBlockingDeque.java:501)
4XESTACKTRACE at java/util/concurrent/LinkedBlockingDeque.take(LinkedBlockingDeque.java:690)
4XESTACKTRACE at java/util/concurrent/ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1080)
4XESTACKTRACE at java/util/concurrent/ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
4XESTACKTRACE at java/util/concurrent/ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:627)
4XESTACKTRACE at java/lang/Thread.run(Thread.java:798)
3XMTHREADINFO3 Native callstack:
4XENATIVESTACK NtWaitForSingleObject+0x15 (0x77A0F8CD [ntdll+0x1f8cd])
4XENATIVESTACK WaitForSingleObjectEx+0x43 (0x75491194 [kernel32+0x11194])
4XENATIVESTACK WaitForSingleObject+0x12 (0x75491148 [kernel32+0x11148])
4XENATIVESTACK j9thread_park+0xba (j9thread.c:2631, 0x73B71C8A [J9THR26+0x1c8a])
4XENATIVESTACK jclCallThreadPark+0x198 (threadpark.c:82, 0x666C2F88 [jclse7b_26+0x42f88])
4XENATIVESTACK sun_misc_Unsafe_park+0x5a (smunsafe.asm:14351, 0x666B760A [jclse7b_26+0x3760a])
4XENATIVESTACK javaProtectedThreadProc+0x9d (vmthread.c:1881, 0x66831DBD [j9vm26+0x51dbd])
4XENATIVESTACK j9sig_protect+0x44 (j9signal.c:150, 0x6BB9F8B4 [J9PRT26+0xf8b4])
4XENATIVESTACK javaThreadProc+0x39 (vmthread.c:298, 0x66832739 [j9vm26+0x52739])
4XENATIVESTACK thread_wrapper+0xda (j9thread.c:1154, 0x73B747AA [J9THR26+0x47aa])
4XENATIVESTACK _endthread+0x48 (0x67E3C55C [msvcr100+0x5c55c])
4XENATIVESTACK _endthread+0xe8 (0x67E3C5FC [msvcr100+0x5c5fc])
4XENATIVESTACK BaseThreadInitThunk+0x12 (0x7549337A [kernel32+0x1337a])
4XENATIVESTACK RtlInitializeExceptionChain+0x63 (0x77A292B2 [ntdll+0x392b2])
4XENATIVESTACK RtlInitializeExceptionChain+0x36 (0x77A29285 [ntdll+0x39285])
</code></pre>
<p>We analyzed the thread information and found that there may be a GC conflict between WebSphere AppServer 8.5 and JDK 1.7, which will be resolved after the server is restarted.</p>
|
[
{
"answer_id": 74610933,
"author": "Fildor",
"author_id": 982149,
"author_profile": "https://Stackoverflow.com/users/982149",
"pm_score": 0,
"selected": false,
"text": "// given: `Division` is a nullable reference type, probably a class\n// I am refering to the `Division` class as given in question at the time of writing.\n\npublic Division FindDivisionByID( Division parent, int targetID )\n{\n // Do we have the Node we were looking for already?\n // Yes: Return it.\n if( parent.Id == targetId ) return parent;\n\n // No: Process Children one by one\n foreach( var child in parent.Children )\n // Little assignment for OP: ^^ this does not take into account\n // that `parent.Children` could be null and will throw if it is.\n // You would want to fortify against that.\n {\n // If a descendant of this child or the child itself\n // was the one we are looking for, `childResult` will \n // point to it. If not it will be null.\n var childResult = FindDivisionByID( child, targetID );\n // The requested Node was in this child's subtree?\n // Yes: Return it.\n if( childResult is not null ) return childResult;\n // No: Next child if there is one.\n }\n // Neither this Node nor any of its Children nor any of their \n // descendants was the one we are looking for.\n return null;\n}\n"
},
{
"answer_id": 74611028,
"author": "Jodrell",
"author_id": 659190,
"author_profile": "https://Stackoverflow.com/users/659190",
"pm_score": 1,
"selected": false,
"text": "public static IEnumerable<T> DepthFirstTraversal<T>(\n this T root,\n Func<T, IEnumerable<T>> branchSelector)\n{\n ArgumentNullException.ThrowIfNull(branchSelector);\n \n var stack = new Stack<T>();\n stack.Push(root);\n while(stack.Count > 0)\n {\n var current = stack.Pop();\n yield return current;\n \n if (current == null)\n {\n continue;\n }\n \n foreach(var child in branchSelector(current))\n {\n stack.Push(child);\n }\n }\n}\n division\n .DepthFirstTraversal(d => d.Children)\n .Where(c => c.Id==2000)\n .FirstOrDefault();\n \n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5358803/"
] |
74,610,722
|
<p>I have 2 functions that read a csv file and count the following as checks:</p>
<ol>
<li>number of rows in that csv</li>
<li>number of rows that have a null value in the 'ID' column</li>
</ol>
<p>I am trying to create a dataframe that looks like this</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Checks</th>
<th>Summary</th>
<th>Findings</th>
</tr>
</thead>
<tbody>
<tr>
<td>Check #1</td>
<td>Number of records on file</td>
<td>function #1 results (Number of records on file: 10)</td>
</tr>
<tr>
<td>Check #2</td>
<td>Number of records missing an ID</td>
<td>function #2 results (Number of records missing an ID: 2)</td>
</tr>
</tbody>
</table>
</div>
<p>function 1 looks like this:</p>
<pre><code>def function1():
with open('data.csv') as file:
record_number = len(list(file))
print("Number of records on file:",record_number)
function1()
</code></pre>
<p>and outputs "Number of records on file: 10"</p>
<p>function 2 looks like this:</p>
<pre><code>def function2():
df = pd.read_csv('data.csv', low_memory=False)
missing_id = df["IDs"].isna().sum()
print("Number of records missing an ID:", missing_id)
function2()
</code></pre>
<p>and outputs "Number of records missing an ID: 2"</p>
<p>I attempt to create a dictionary first and create my dictionary</p>
<pre><code>table = {
'Checks' : ['Check #1', 'Check #2'],
'Summary' : ['Number of records on file', 'Number of records missing an ID'],
'Findings' : [function1, function2]
}
df = pd.DataFrame(table)
df
</code></pre>
<p>However, this is what the dataframe looks like:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Checks</th>
<th>Summary</th>
<th>Findings</th>
</tr>
</thead>
<tbody>
<tr>
<td>Check #1</td>
<td>Number of records on file</td>
<td><function function1 at 0x7efd2d76a730></td>
</tr>
<tr>
<td>Check #2</td>
<td>Number of records missing an ID</td>
<td><function2 at 0x7efd25cd0b70></td>
</tr>
</tbody>
</table>
</div>
<p>Is there any way to make it so that my Findings column outputs the actual results as seen above?</p>
|
[
{
"answer_id": 74610756,
"author": "Koedlt",
"author_id": 15405732,
"author_profile": "https://Stackoverflow.com/users/15405732",
"pm_score": 2,
"selected": false,
"text": "function1 != function1() table = {\n 'Checks' : ['Check #1', 'Check #2'],\n 'Summary' : ['Number of records on file', 'Number of records missing an ID'],\n 'Findings' : [function1(), function2()]\n}\ndf = pd.DataFrame(table)\ndf\n return"
},
{
"answer_id": 74610775,
"author": "Daweo",
"author_id": 10785975,
"author_profile": "https://Stackoverflow.com/users/10785975",
"pm_score": 3,
"selected": true,
"text": "return def function1():\n with open('data.csv') as file:\n record_number = len(list(file))\n return record_number\n def function2():\n df = pd.read_csv('data.csv', low_memory=False)\n return df[\"IDs\"].isna().sum()\n table = {\n 'Checks' : ['Check #1', 'Check #2'],\n 'Summary' : ['Number of records on file', 'Number of records missing an ID'],\n 'Findings' : [function1(), function2()]\n}\ndf = pd.DataFrame(table)\ndf\n"
},
{
"answer_id": 74610784,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 0,
"selected": false,
"text": "return f-strings def function1():\n with open('data.csv') as file:\n record_number = len(list(file))\n return f\"function #1 results (Number of records on file: {record_number})\")\n\n\ndef function2():\n df = pd.read_csv('data.csv', low_memory=False)\n missing_id = df[\"IDs\"].isna().sum()\n return f\"function #2 results (Number of records missing an ID: {missing_id})\")\n\n\ntable = {\n 'Checks' : ['Check #1', 'Check #2'],\n 'Summary' : ['Number of records on file', 'Number of records missing an ID'],\n 'Findings' : [function1(), function2()]\n}\ndf = pd.DataFrame(table)\n def function():\n with open('data.csv') as file:\n record_number = len(list(file))\n missing_id = df[\"IDs\"].isna().sum()\n \n return [f\"function #1 results (Number of records on file: {record_number})\"),\n f\"function #2 results (Number of records missing an ID: {missing_id})\")]\n\n\ntable = {\n 'Checks' : ['Check #1', 'Check #2'],\n 'Summary' : ['Number of records on file', 'Number of records missing an ID'],\n 'Findings' : function()\n}\ndf = pd.DataFrame(table)\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16633745/"
] |
74,610,740
|
<p>Hi it's my first time using slick carousel. I need to change the position of the arrow, so the arrow will be at the top level like the red arrow in the picture, and not at the side of the slider. I try using similar solution I find on the forum, but no one work for me.
I trying using position absolute and top properties but can't find the good CSS to fix this issue. I am trying to put the arrow in the class: <code>carousel_btn_arrow</code></p>
<p>HTML</p>
<pre><code>
<div class="carousel_wrap">
<div class="carousel_header">
<div class="carousel_title typography__headline4">${Recommendation title}</div>
<div class="carousel_btn_arrow">
</div>
</div>
<div class="carousel_content">
${#Recommendation}
<div class="product_grid_item" data-shortId="${shortId}" data-sku="${sku}">
<a href="${url}">
<div class="product_grid_item_img"><img src=${Image_url}></div>
</a>
<div class="product_grid_item_title typography__text1">${Name}</div>
<div class="product_grid_item_price typography__text4">$${Price}</div>
</div>
${/Recommendation}
</div>
</div>
</code></pre>
<p>CSS</p>
<pre><code>.carousel_wrap
{
display:flex;
flex-direction: column;
}
.carousel_header
{
display:flex;
justify-content: space-between;
margin-bottom: var(--size-250);
}
.carousel_content
{
display:flex;
gap: var(--size-125);
}
.product_grid_item
{
display:flex;
flex-direction:column;
gap:var(--size-50);
}
.product_grid_item_img
{
background: var(--color-grid-item-blend);
}
.product_grid_item_img img
{
mix-blend-mode: multiply;
}
.slick-slide
{
margin-left: var(--size-125);
}
.slick-arrow
{
cursor: pointer;
background: transparent;
border:none;
}
.slick-arrow::before
{
border: 0;
}
.slick-prev::before
{
background: url("arrow_prev.svg") no-repeat center;
margin-right: var(--size);
}
.slick-next::before
{
background: url("arrow_next.svg") no-repeat center;
}
</code></pre>
<p>JS</p>
<pre><code>$(document).ready(function()
{
$(".carousel_content").slick({
arrows:true,
slidesToShow: 3.99,
slideToScroll: 1,
infinite: true,
prevArrow:"<button type='button' class='slick-prev'></button>",
nextArrow:"<button type='button' class='slick-next'></button>"
});
});
</code></pre>
<p><a href="https://i.stack.imgur.com/yyOzf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yyOzf.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74610871,
"author": "Every Screamer",
"author_id": 3863593,
"author_profile": "https://Stackoverflow.com/users/3863593",
"pm_score": 1,
"selected": false,
"text": "prevArrow: $(\"specificIDorspecificClass\")"
},
{
"answer_id": 74613317,
"author": "Jaswinder Kaur",
"author_id": 15258737,
"author_profile": "https://Stackoverflow.com/users/15258737",
"pm_score": 3,
"selected": true,
"text": "<link href=\"https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.9.0/slick.min.css\" rel=\"stylesheet\" />\n<link href=\"https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.9.0/slick-theme.css\" rel=\"stylesheet\" />\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.9.0/slick.min.js\"></script>\n\n<div class=\"carousel_wrap\">\n <div class=\"carousel_header\">\n <div class=\"carousel_title typography__headline4\">Heading</div>\n\n <div class=\"carousel_btn_arrow\">\n \n </div>\n </div>\n\n<div class=\"carousel_content\">\n\n<div class=\"product_grid_item\" data-shortId=\"${shortId}\" data-sku=\"${sku}\">\n <a href=\"${url}\">\n <div class=\"product_grid_item_img\"><img src=\"makeup.jpg\"></div>\n </a>\n <div class=\"product_grid_item_title typography__text1\">abc</div>\n <div class=\"product_grid_item_price typography__text4\">text</div>\n</div>\n\n\n<div class=\"product_grid_item\" data-shortId=\"${shortId}\" data-sku=\"${sku}\">\n <a href=\"${url}\">\n <div class=\"product_grid_item_img\"><img src=\"makeup.jpg\"></div>\n </a>\n <div class=\"product_grid_item_title typography__text1\">abc</div>\n <div class=\"product_grid_item_price typography__text4\">text</div>\n</div>\n\n\n<div class=\"product_grid_item\" data-shortId=\"${shortId}\" data-sku=\"${sku}\">\n <a href=\"${url}\">\n <div class=\"product_grid_item_img\"><img src=\"makeup.jpg\"></div>\n </a>\n <div class=\"product_grid_item_title typography__text1\">abc</div>\n <div class=\"product_grid_item_price typography__text4\">text</div>\n</div>\n\n<div class=\"product_grid_item\" data-shortId=\"${shortId}\" data-sku=\"${sku}\">\n <a href=\"${url}\">\n <div class=\"product_grid_item_img\"><img src=\"makeup.jpg\"></div>\n </a>\n <div class=\"product_grid_item_title typography__text1\">abc</div>\n <div class=\"product_grid_item_price typography__text4\">text</div>\n</div>\n\n</div>\n</div>\n <style>\n.carousel_wrap\n{\n display:flex;\n flex-direction: column;\n \n}\n.carousel_header\n{\n display:flex;\n justify-content: space-between;\n margin-bottom: var(--size-250);\n padding-bottom: 40px;\n}\n.carousel_content\n{\n display:flex;\n gap: var(--size-125);\n}\n\n.product_grid_item\n{\n display:flex;\n flex-direction:column;\n gap:var(--size-50);\n}\n.product_grid_item_img\n{\n background: var(--color-grid-item-blend);\n padding: 10px;\n}\n\n.product_grid_item_img img \n{\n mix-blend-mode: multiply;\n}\n.slick-slide\n{\n margin-left: var(--size-125);\n}\n\n.slick-slide img {\n display: block;\n width: 100%;\n}\n.slick-arrow\n{\n\n cursor: pointer;\n background: transparent;\n border:none;\n}\n.slick-arrow::before\n{\n border: 0;\n}\n.slick-prev::before\n{\n background: url(\"arrow_prev.svg\") no-repeat center;\n margin-right: var(--size);\n}\n.slick-next::before\n{\n background: url(\"arrow_next.svg\") no-repeat center;\n}\n\n.slick-prev.slick-arrow {\n position: absolute;\nfont-size: 40px;\ncolor: red !important;\nright: 90px;\ntop: -40px;\n left: auto;\n}\n.slick-next.slick-arrow {\n position: absolute;\n font-size: 40px;\n color: red !important;\n right: 30px;\n top: -40px;\n left: auto;\n}\n</style>\n <script>\n$(document).ready(function()\n{\n $(\".carousel_content\").slick({\n arrows:true,\n slidesToShow: 3.99,\n slideToScroll: 1,\n infinite: true,\n prevArrow:\"<button type='button' class='slick-prev'> ← </button>\",\n nextArrow:\"<button type='button' class='slick-next'> → </button>\"\n });\n \n});\n\n</script>\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19533023/"
] |
74,610,747
|
<p>I want to pass the props from router to component</p>
<pre><code>function TestComponent({myProps: string}): {
console.log(myProps)
useEffect(...)
return (
<>...</>
)
};
</code></pre>
<p>My router use react lazy like this</p>
<pre><code>import React, { lazy } from 'react';
export const routes = [
...
{
path: '/test/testComponent',
exact: true,
component: lazy(
() => import('pages/test/TestComponent/index'),
),
},
...
];
</code></pre>
<p>I find this way</p>
<pre><code>{
path: '/test/testComponent',
component(): React.ReactElement {
return <DeviceAssignmentLog myProps=''hello />;
},
},
</code></pre>
<p>but I have to use lazy with that</p>
<p>how can I solve...</p>
|
[
{
"answer_id": 74610871,
"author": "Every Screamer",
"author_id": 3863593,
"author_profile": "https://Stackoverflow.com/users/3863593",
"pm_score": 1,
"selected": false,
"text": "prevArrow: $(\"specificIDorspecificClass\")"
},
{
"answer_id": 74613317,
"author": "Jaswinder Kaur",
"author_id": 15258737,
"author_profile": "https://Stackoverflow.com/users/15258737",
"pm_score": 3,
"selected": true,
"text": "<link href=\"https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.9.0/slick.min.css\" rel=\"stylesheet\" />\n<link href=\"https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.9.0/slick-theme.css\" rel=\"stylesheet\" />\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.9.0/slick.min.js\"></script>\n\n<div class=\"carousel_wrap\">\n <div class=\"carousel_header\">\n <div class=\"carousel_title typography__headline4\">Heading</div>\n\n <div class=\"carousel_btn_arrow\">\n \n </div>\n </div>\n\n<div class=\"carousel_content\">\n\n<div class=\"product_grid_item\" data-shortId=\"${shortId}\" data-sku=\"${sku}\">\n <a href=\"${url}\">\n <div class=\"product_grid_item_img\"><img src=\"makeup.jpg\"></div>\n </a>\n <div class=\"product_grid_item_title typography__text1\">abc</div>\n <div class=\"product_grid_item_price typography__text4\">text</div>\n</div>\n\n\n<div class=\"product_grid_item\" data-shortId=\"${shortId}\" data-sku=\"${sku}\">\n <a href=\"${url}\">\n <div class=\"product_grid_item_img\"><img src=\"makeup.jpg\"></div>\n </a>\n <div class=\"product_grid_item_title typography__text1\">abc</div>\n <div class=\"product_grid_item_price typography__text4\">text</div>\n</div>\n\n\n<div class=\"product_grid_item\" data-shortId=\"${shortId}\" data-sku=\"${sku}\">\n <a href=\"${url}\">\n <div class=\"product_grid_item_img\"><img src=\"makeup.jpg\"></div>\n </a>\n <div class=\"product_grid_item_title typography__text1\">abc</div>\n <div class=\"product_grid_item_price typography__text4\">text</div>\n</div>\n\n<div class=\"product_grid_item\" data-shortId=\"${shortId}\" data-sku=\"${sku}\">\n <a href=\"${url}\">\n <div class=\"product_grid_item_img\"><img src=\"makeup.jpg\"></div>\n </a>\n <div class=\"product_grid_item_title typography__text1\">abc</div>\n <div class=\"product_grid_item_price typography__text4\">text</div>\n</div>\n\n</div>\n</div>\n <style>\n.carousel_wrap\n{\n display:flex;\n flex-direction: column;\n \n}\n.carousel_header\n{\n display:flex;\n justify-content: space-between;\n margin-bottom: var(--size-250);\n padding-bottom: 40px;\n}\n.carousel_content\n{\n display:flex;\n gap: var(--size-125);\n}\n\n.product_grid_item\n{\n display:flex;\n flex-direction:column;\n gap:var(--size-50);\n}\n.product_grid_item_img\n{\n background: var(--color-grid-item-blend);\n padding: 10px;\n}\n\n.product_grid_item_img img \n{\n mix-blend-mode: multiply;\n}\n.slick-slide\n{\n margin-left: var(--size-125);\n}\n\n.slick-slide img {\n display: block;\n width: 100%;\n}\n.slick-arrow\n{\n\n cursor: pointer;\n background: transparent;\n border:none;\n}\n.slick-arrow::before\n{\n border: 0;\n}\n.slick-prev::before\n{\n background: url(\"arrow_prev.svg\") no-repeat center;\n margin-right: var(--size);\n}\n.slick-next::before\n{\n background: url(\"arrow_next.svg\") no-repeat center;\n}\n\n.slick-prev.slick-arrow {\n position: absolute;\nfont-size: 40px;\ncolor: red !important;\nright: 90px;\ntop: -40px;\n left: auto;\n}\n.slick-next.slick-arrow {\n position: absolute;\n font-size: 40px;\n color: red !important;\n right: 30px;\n top: -40px;\n left: auto;\n}\n</style>\n <script>\n$(document).ready(function()\n{\n $(\".carousel_content\").slick({\n arrows:true,\n slidesToShow: 3.99,\n slideToScroll: 1,\n infinite: true,\n prevArrow:\"<button type='button' class='slick-prev'> ← </button>\",\n nextArrow:\"<button type='button' class='slick-next'> → </button>\"\n });\n \n});\n\n</script>\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12917399/"
] |
74,610,777
|
<p>I have an entry field that stores my list to a text file
when i press the button to store the info, it gets stored but i have to restart the app to see it on the options menu
How do i make the app update without having to restart it?
`</p>
<pre><code>from tkinter import *
from tkinter import messagebox
root = Tk()
root.title("test tool") #App Title
root.iconbitmap("D:\\Software\\GigaPixel Frames\\Dump\\New folder\\imgs\\Logo.ico")
root.geometry("1600x800") #App Dimensions
DropDownvar = StringVar(value="Select an option")
DropDownvar.set("Select an option")
my_list = open("Characters.txt").readlines()
DropDownMenu = OptionMenu(root, DropDownvar, *my_list)
DropDownMenu.pack()
inputBox = Entry(root)
inputBox.pack()
def ButtonFun():
InputBoxEntry = inputBox.get()
with open("Characters.txt", "a") as text_file:
text_file.write(InputBoxEntry + "\n")
root.update()
inputBoxButton = Button(root, text="Input", command=ButtonFun)
inputBoxButton.pack()
root.mainloop()
</code></pre>
<p>`</p>
<p>could not find answer</p>
|
[
{
"answer_id": 74610871,
"author": "Every Screamer",
"author_id": 3863593,
"author_profile": "https://Stackoverflow.com/users/3863593",
"pm_score": 1,
"selected": false,
"text": "prevArrow: $(\"specificIDorspecificClass\")"
},
{
"answer_id": 74613317,
"author": "Jaswinder Kaur",
"author_id": 15258737,
"author_profile": "https://Stackoverflow.com/users/15258737",
"pm_score": 3,
"selected": true,
"text": "<link href=\"https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.9.0/slick.min.css\" rel=\"stylesheet\" />\n<link href=\"https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.9.0/slick-theme.css\" rel=\"stylesheet\" />\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.9.0/slick.min.js\"></script>\n\n<div class=\"carousel_wrap\">\n <div class=\"carousel_header\">\n <div class=\"carousel_title typography__headline4\">Heading</div>\n\n <div class=\"carousel_btn_arrow\">\n \n </div>\n </div>\n\n<div class=\"carousel_content\">\n\n<div class=\"product_grid_item\" data-shortId=\"${shortId}\" data-sku=\"${sku}\">\n <a href=\"${url}\">\n <div class=\"product_grid_item_img\"><img src=\"makeup.jpg\"></div>\n </a>\n <div class=\"product_grid_item_title typography__text1\">abc</div>\n <div class=\"product_grid_item_price typography__text4\">text</div>\n</div>\n\n\n<div class=\"product_grid_item\" data-shortId=\"${shortId}\" data-sku=\"${sku}\">\n <a href=\"${url}\">\n <div class=\"product_grid_item_img\"><img src=\"makeup.jpg\"></div>\n </a>\n <div class=\"product_grid_item_title typography__text1\">abc</div>\n <div class=\"product_grid_item_price typography__text4\">text</div>\n</div>\n\n\n<div class=\"product_grid_item\" data-shortId=\"${shortId}\" data-sku=\"${sku}\">\n <a href=\"${url}\">\n <div class=\"product_grid_item_img\"><img src=\"makeup.jpg\"></div>\n </a>\n <div class=\"product_grid_item_title typography__text1\">abc</div>\n <div class=\"product_grid_item_price typography__text4\">text</div>\n</div>\n\n<div class=\"product_grid_item\" data-shortId=\"${shortId}\" data-sku=\"${sku}\">\n <a href=\"${url}\">\n <div class=\"product_grid_item_img\"><img src=\"makeup.jpg\"></div>\n </a>\n <div class=\"product_grid_item_title typography__text1\">abc</div>\n <div class=\"product_grid_item_price typography__text4\">text</div>\n</div>\n\n</div>\n</div>\n <style>\n.carousel_wrap\n{\n display:flex;\n flex-direction: column;\n \n}\n.carousel_header\n{\n display:flex;\n justify-content: space-between;\n margin-bottom: var(--size-250);\n padding-bottom: 40px;\n}\n.carousel_content\n{\n display:flex;\n gap: var(--size-125);\n}\n\n.product_grid_item\n{\n display:flex;\n flex-direction:column;\n gap:var(--size-50);\n}\n.product_grid_item_img\n{\n background: var(--color-grid-item-blend);\n padding: 10px;\n}\n\n.product_grid_item_img img \n{\n mix-blend-mode: multiply;\n}\n.slick-slide\n{\n margin-left: var(--size-125);\n}\n\n.slick-slide img {\n display: block;\n width: 100%;\n}\n.slick-arrow\n{\n\n cursor: pointer;\n background: transparent;\n border:none;\n}\n.slick-arrow::before\n{\n border: 0;\n}\n.slick-prev::before\n{\n background: url(\"arrow_prev.svg\") no-repeat center;\n margin-right: var(--size);\n}\n.slick-next::before\n{\n background: url(\"arrow_next.svg\") no-repeat center;\n}\n\n.slick-prev.slick-arrow {\n position: absolute;\nfont-size: 40px;\ncolor: red !important;\nright: 90px;\ntop: -40px;\n left: auto;\n}\n.slick-next.slick-arrow {\n position: absolute;\n font-size: 40px;\n color: red !important;\n right: 30px;\n top: -40px;\n left: auto;\n}\n</style>\n <script>\n$(document).ready(function()\n{\n $(\".carousel_content\").slick({\n arrows:true,\n slidesToShow: 3.99,\n slideToScroll: 1,\n infinite: true,\n prevArrow:\"<button type='button' class='slick-prev'> ← </button>\",\n nextArrow:\"<button type='button' class='slick-next'> → </button>\"\n });\n \n});\n\n</script>\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20476093/"
] |
74,610,778
|
<p>I have a list of dicts in which one of the dict values is also a list of dicts. I want to flatten it into a list of dicts.</p>
<p>I have some working code and would like opinions on whether ot not there is a more idiomatic way of achieving this.</p>
<p>Here is my code:</p>
<pre class="lang-py prettyprint-override"><code>from pprint import pprint
transactions = [
{
"Customer": "Leia",
"Store": "Hammersmith",
"Basket": "basket1",
"items": [
{"Product": "Cheddar", "Quantity": 2, "GrossSpend": 2.50},
{"Product": "Grapes", "Quantity": 1, "GrossSpend": 3.00},
],
},
{
"Customer": "Luke",
"Store": "Ealing",
"Basket": "basket2",
"items": [
{
"Product": "Custard Creams",
"Quantity": 1,
"GrossSpend": 3.00,
}
],
},
]
flattened_transactions = []
for transaction in transactions:
flattened_transactions.extend(
{
"Customer": transaction["Customer"],
"Store": transaction["Store"],
"Basket": transaction["Basket"],
"Product": item["Product"],
"Quantity": item["Quantity"],
"GrossSpend": item["GrossSpend"],
}
for item in transaction["items"]
)
pprint(flattened_transactions)
</code></pre>
<p>it outputs:</p>
<pre class="lang-py prettyprint-override"><code>[{'Basket': 'basket1',
'Customer': 'Leia',
'GrossSpend': 2.5,
'Product': 'Cheddar',
'Quantity': 2,
'Store': 'Hammersmith'},
{'Basket': 'basket1',
'Customer': 'Leia',
'GrossSpend': 3.0,
'Product': 'Grapes',
'Quantity': 1,
'Store': 'Hammersmith'},
{'Basket': 'basket2',
'Customer': 'Luke',
'GrossSpend': 3.0,
'Product': 'Custard Creams',
'Quantity': 1,
'Store': 'Ealing'}]
</code></pre>
<p>Is there a better way of achieving this?</p>
|
[
{
"answer_id": 74610950,
"author": "Usman Arshad",
"author_id": 20582506,
"author_profile": "https://Stackoverflow.com/users/20582506",
"pm_score": 1,
"selected": false,
"text": "items flattened_transactions = []\nfor transaction in transactions:\n items = transaction.pop(\"items\", [])\n for item in items:\n for key, value in item.items():\n transaction[key] = value\n flattened_transactions.append(transaction)\n else:\n flattened_transactions.append(transaction)\npprint(flattened_transactions)\n"
},
{
"answer_id": 74610987,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 3,
"selected": true,
"text": "[{'Customer': d['Customer'], \n 'Store': d['Store'], \n 'Basket': d['Basket'], \n **d2} \n for d in transactions \n for d2 in d['items']]\n# [{'Customer': 'Leia', 'Store': 'Hammersmith', 'Basket': 'basket1', \n# 'Product': 'Cheddar', 'Quantity': 2, 'GrossSpend': 2.5}, \n# {'Customer': 'Leia', 'Store': 'Hammersmith', 'Basket': 'basket1', \n# 'Product': 'Grapes', 'Quantity': 1, 'GrossSpend': 3.0},\n# {'Customer': 'Luke', 'Store': 'Ealing', 'Basket': 'basket2', \n# 'Product': 'Custard Creams', 'Quantity': 1, 'GrossSpend': 3.0}]\n 'items' dict.get [] [{'Customer': d['Customer'], \n 'Store': d['Store'], \n 'Basket': d['Basket'], \n **d2} \n for d in transactions \n for d2 in d.get('items', [])]\n 'items' [{k: v \n for k, v in d3.items() \n if k != 'items'} \n for d in transactions \n for d2 in d.get('items', []) \n for d3 in ({**d, **d2},)]\n"
},
{
"answer_id": 74611195,
"author": "Mudassir",
"author_id": 3758912,
"author_profile": "https://Stackoverflow.com/users/3758912",
"pm_score": -1,
"selected": false,
"text": "ouput = []\n\nfor transaction in transactions:\n output = [*output, *transaction]\n\n * ..."
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/201657/"
] |
74,610,786
|
<p>Let's say I want to simplify the terms</p>
<p>[<img src="https://i.stack.imgur.com/h5CSU.png" alt="Differential of real(expression)" /></p>
<p>where <em>u</em> and <em>v</em> are (sympy) complex variables. <em>u</em> and <em>w</em> are independent from each other and the above differentials should thereby be evaluated to zero. As my code currently stands, it will not set the above differentials to zero since it does not know how to evaluate re(<em>w</em>) and im(<em>w</em>) (see reason below). Is there a way to tell Python/Sympy to reverse the order of operation between the differential and re/im operator, i.e to evaluate them as:</p>
<p><a href="https://i.stack.imgur.com/yf0BU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yf0BU.png" alt="real(Differential of expression" /></a></p>
<p>Since then Python can evaluate the differentials, and since they both are zero to begin with, it can set re(0) and im(0) to zero automatically.</p>
<p>I am basically looking for a solution to this where I don't have to decompose <em>u</em> and <em>w</em> into</p>
<p><a href="https://i.stack.imgur.com/SBGOw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SBGOw.png" alt="Decomposition" /></a></p>
<p>with <em>u_1, u_2, w_1, w_2</em> real</p>
<p><strong>Initial attempt</strong>: I noticed that one can use sympy.subs to swith the re operator to im operator by <code>[expression].subs({re: im})</code>. Maybe one could do something similiar with the differential and re/im operator to switch the order, but I do not know how to write the differential operator inside of <code>subs</code>.</p>
|
[
{
"answer_id": 74610950,
"author": "Usman Arshad",
"author_id": 20582506,
"author_profile": "https://Stackoverflow.com/users/20582506",
"pm_score": 1,
"selected": false,
"text": "items flattened_transactions = []\nfor transaction in transactions:\n items = transaction.pop(\"items\", [])\n for item in items:\n for key, value in item.items():\n transaction[key] = value\n flattened_transactions.append(transaction)\n else:\n flattened_transactions.append(transaction)\npprint(flattened_transactions)\n"
},
{
"answer_id": 74610987,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 3,
"selected": true,
"text": "[{'Customer': d['Customer'], \n 'Store': d['Store'], \n 'Basket': d['Basket'], \n **d2} \n for d in transactions \n for d2 in d['items']]\n# [{'Customer': 'Leia', 'Store': 'Hammersmith', 'Basket': 'basket1', \n# 'Product': 'Cheddar', 'Quantity': 2, 'GrossSpend': 2.5}, \n# {'Customer': 'Leia', 'Store': 'Hammersmith', 'Basket': 'basket1', \n# 'Product': 'Grapes', 'Quantity': 1, 'GrossSpend': 3.0},\n# {'Customer': 'Luke', 'Store': 'Ealing', 'Basket': 'basket2', \n# 'Product': 'Custard Creams', 'Quantity': 1, 'GrossSpend': 3.0}]\n 'items' dict.get [] [{'Customer': d['Customer'], \n 'Store': d['Store'], \n 'Basket': d['Basket'], \n **d2} \n for d in transactions \n for d2 in d.get('items', [])]\n 'items' [{k: v \n for k, v in d3.items() \n if k != 'items'} \n for d in transactions \n for d2 in d.get('items', []) \n for d3 in ({**d, **d2},)]\n"
},
{
"answer_id": 74611195,
"author": "Mudassir",
"author_id": 3758912,
"author_profile": "https://Stackoverflow.com/users/3758912",
"pm_score": -1,
"selected": false,
"text": "ouput = []\n\nfor transaction in transactions:\n output = [*output, *transaction]\n\n * ..."
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20534324/"
] |
74,610,787
|
<p>In my Oracle-database table <em>mytable</em> I have a column <em>columnx</em> with JSON-Arrays (VARCHAR2) and I would like to find all entries where the value <em>valueX</em> is inside that array.</p>
<p>In native Oracle-SQL the following query is working very well:
<code>SELECT * FROM mytable t WHERE JSON_EXISTS(columnx, '$?(@ == "valueX")');</code></p>
<p>In my Spring Boot Application I write queries in JPQL, so I have to convert it.</p>
<p>The following queries were unsuccessful:</p>
<ol>
<li><p>I found out that I have to use 'FUNCTION()' for specific SQL-Oracle-functions:
<code>@Query(value = "SELECT t FROM mytable t WHERE FUNCTION('JSON_EXISTS',t.columnx, '$?(@ == \"valueX\")')")</code>
That results in a JPQL-Parsing-Error: "QuerySyntaxException: unexpected AST node: function (JSON_EXISTS)"</p>
</li>
<li><p>I found out that JPQL needs a real boolean-comparison, so I tried this:
<code>@Query(value = "SELECT t FROM mytable t WHERE FUNCTION('JSON_EXISTS',t.columnx, '$?(@ == \"valueX\")') = TRUE")</code>
Now the JPQL-Converter can parse it to native SQL successfully, but I got an Oracle-Error while executing the query: "ORA-00933: SQL command not properly ended."
That's understandable since the parsed native <code>... WHERE JSON_EXISTS(columnx, '$?(@ == "valueX")') = 1</code> won't run either.</p>
</li>
</ol>
<p>What is the right way to solve this problem? Do you have any idea?</p>
|
[
{
"answer_id": 74616980,
"author": "psaraj12",
"author_id": 1297792,
"author_profile": "https://Stackoverflow.com/users/1297792",
"pm_score": 1,
"selected": false,
"text": "@Query(value = \"SELECT * FROM mytable t WHERE \nJSON_EXISTS(columnx, '$?(@ == \\\"valueX\\\")')\", \nnativeQuery = true)\n create or replace view my_table_json_exists as SELECT * FROM \n mytable t WHERE \n JSON_EXISTS(t.columnx, '$?(@ == \"valueX\")');\n\n @Query(value =\"select t from my_table_json_exists t\");\n"
},
{
"answer_id": 74673365,
"author": "diziaq",
"author_id": 2774914,
"author_profile": "https://Stackoverflow.com/users/2774914",
"pm_score": 0,
"selected": false,
"text": "MEMBER OF @Query(\"SELECT t FROM mytable t WHERE :valueX MEMBER OF t.columnx\")\nList<Mytable> findByValueX(@Param(\"valueX\") String valueX);\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20626780/"
] |
74,610,805
|
<p>Here's a simplified version of the script I'm trying to write:</p>
<pre><code>$i = 0
Get-ChildItem -Filter *.bat|
ForEach-Object {
Write-Host $_.Name
switch ($i) {
0 { Write-Host $_.Name}
1 { Write-Host $_.Name }
2 { Write-Host $_.Name }
Default {Write-Host "nothing here"}
}
}
</code></pre>
<p>So the first <code>Write-Host</code> command works as expected, but once I get inside the switch statement <code>Write-Host</code> prints out nothing, which is mystifying to me. I assume the problem has something to do with the scope of <code>$_</code> but I don't know. I'm a total Powershell amateur. Isn't the switch statement inside the foreach loop so the scope shouldn't be an issue?</p>
<p>If I do this then everything works like I expected, the filenames get printed from inside and outside the switch statement:</p>
<pre><code>$i = 0
Get-ChildItem -Filter *.bat |
ForEach-Object {
Write-Host $_.Name
$temp = $_.Name
switch ($i) {
0 { Write-Host $temp }
1 { Write-Host $temp }
2 { Write-Host $temp }
Default {Write-Host "nothing here"}
}
}
</code></pre>
<p>Can someone explain what is going on here?</p>
|
[
{
"answer_id": 74611326,
"author": "arco444",
"author_id": 3115685,
"author_profile": "https://Stackoverflow.com/users/3115685",
"pm_score": 3,
"selected": true,
"text": "$_ switch $i Int32 Name $temp $_ $_ Get-ChildItem -Filter *.bat |\nForEach-Object {\n Write-Host $_.gettype()\n switch ($i) {\n Default {\n Write-Host $_.gettype()\n }\n }\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20630743/"
] |
74,610,818
|
<p><img src="https://i.stack.imgur.com/Jn9Bo.png" alt="enter image description here" />
I need to add a configuration and to customize accordingly. In before versions in the startup.cs there is a class specifically for configuration. I need to know how to add configuration in program.cs</p>
<p>In before versions in the startup.cs there is a class specifically for configuration. I need to know how to add configuration in program.cs</p>
|
[
{
"answer_id": 74610846,
"author": "kosist",
"author_id": 6917446,
"author_profile": "https://Stackoverflow.com/users/6917446",
"pm_score": 0,
"selected": false,
"text": "IConfiguration Microsoft.Extensions.Configuration"
},
{
"answer_id": 74610885,
"author": "klekmek",
"author_id": 4797062,
"author_profile": "https://Stackoverflow.com/users/4797062",
"pm_score": 0,
"selected": false,
"text": "IConfiguration configuration = builder.Configuration;"
},
{
"answer_id": 74611229,
"author": "Govind",
"author_id": 5951802,
"author_profile": "https://Stackoverflow.com/users/5951802",
"pm_score": 1,
"selected": false,
"text": "var builder = WebApplication.CreateBuilder(args);\n//Get the instance of the IConfiguration service\nvar configuration = builder.Configuration;\n//We can configure configuration variables of type IConfiguration and get a value \nvar vTestValue = configuration.GetValue<string>(\"TestValue\");\n"
},
{
"answer_id": 74622479,
"author": "Gauravsa",
"author_id": 2549110,
"author_profile": "https://Stackoverflow.com/users/2549110",
"pm_score": 0,
"selected": false,
"text": "\"Employee\": {\n \"Title\": \"Mr\",\n \"Name\": \"Joe Smith\"\n }\n public class EmployeeOptions\n{\n public const string Employee = \"Employee\";\n public string Title { get; set; } = String.Empty;\n public string Name { get; set; } = String.Empty;\n}\n public class Program\n{\n public static void Main(string[] args)\n {\n var builder = WebApplication.CreateBuilder(args);\n var startup = new Startup(builder.Configuration);\n startup.RegisterServices(builder.Services);\n\n var app = builder.Build();\n startup.SetupMiddlewares(app);\n\n app.Run();\n } }\n public class Startup\n{\n public Startup(IConfiguration configuration)\n {\n Configuration = configuration;\n }\n\n public IConfiguration Configuration { get; }\n\n public void RegisterServices(IServiceCollection services)\n {\n services.Configure<EmployeeOptions>(\n Configuration.GetSection(EmployeeOptions.Employee));\n }\n\n public void SetupMiddlewares(WebApplication app)\n {\n // Configure the HTTP request pipeline.\n if (!app.Environment.IsDevelopment())\n {\n app.UseExceptionHandler(\"/Home/Error\");\n // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.\n app.UseHsts();\n }\n\n app.UseHttpsRedirection();\n app.UseStaticFiles();\n app.UseRouting();\n\n app.UseAuthentication();\n app.UseAuthorization();\n \n app.MapControllerRoute(\n name: \"default\",\n pattern: \"{controller=Home}/{action=Index}/{id?}\");\n }\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20597627/"
] |
74,610,875
|
<p>My code was supposed to</p>
<ul>
<li>check two passwords</li>
<li>check the length of the passwords</li>
<li>check the first and last letters of the passwords</li>
<li>and check the uppercase and lowercase of the passwords</li>
</ul>
<pre><code>pass1 = "secret"
pass2 = "choccie"
InputPassword = input("Write the password: ")
error = "Wrong password input"
def PasswordChecker(password):
for password in pass1 & pass2:
if len(InputPassword) != len(password) or InputPassword[0] != password[0] or InputPassword[-1] != password[-1] or InputPassword.isupper() == True:
print(error)
elif InputPassword == password:
print("Welcome!")
print(PasswordChecker)
</code></pre>
<p>I know that there's a problem regarding my 2 passwords (pass1, pass2), and def PasswordChecker(password) but I don't understand how to fix it.</p>
|
[
{
"answer_id": 74610846,
"author": "kosist",
"author_id": 6917446,
"author_profile": "https://Stackoverflow.com/users/6917446",
"pm_score": 0,
"selected": false,
"text": "IConfiguration Microsoft.Extensions.Configuration"
},
{
"answer_id": 74610885,
"author": "klekmek",
"author_id": 4797062,
"author_profile": "https://Stackoverflow.com/users/4797062",
"pm_score": 0,
"selected": false,
"text": "IConfiguration configuration = builder.Configuration;"
},
{
"answer_id": 74611229,
"author": "Govind",
"author_id": 5951802,
"author_profile": "https://Stackoverflow.com/users/5951802",
"pm_score": 1,
"selected": false,
"text": "var builder = WebApplication.CreateBuilder(args);\n//Get the instance of the IConfiguration service\nvar configuration = builder.Configuration;\n//We can configure configuration variables of type IConfiguration and get a value \nvar vTestValue = configuration.GetValue<string>(\"TestValue\");\n"
},
{
"answer_id": 74622479,
"author": "Gauravsa",
"author_id": 2549110,
"author_profile": "https://Stackoverflow.com/users/2549110",
"pm_score": 0,
"selected": false,
"text": "\"Employee\": {\n \"Title\": \"Mr\",\n \"Name\": \"Joe Smith\"\n }\n public class EmployeeOptions\n{\n public const string Employee = \"Employee\";\n public string Title { get; set; } = String.Empty;\n public string Name { get; set; } = String.Empty;\n}\n public class Program\n{\n public static void Main(string[] args)\n {\n var builder = WebApplication.CreateBuilder(args);\n var startup = new Startup(builder.Configuration);\n startup.RegisterServices(builder.Services);\n\n var app = builder.Build();\n startup.SetupMiddlewares(app);\n\n app.Run();\n } }\n public class Startup\n{\n public Startup(IConfiguration configuration)\n {\n Configuration = configuration;\n }\n\n public IConfiguration Configuration { get; }\n\n public void RegisterServices(IServiceCollection services)\n {\n services.Configure<EmployeeOptions>(\n Configuration.GetSection(EmployeeOptions.Employee));\n }\n\n public void SetupMiddlewares(WebApplication app)\n {\n // Configure the HTTP request pipeline.\n if (!app.Environment.IsDevelopment())\n {\n app.UseExceptionHandler(\"/Home/Error\");\n // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.\n app.UseHsts();\n }\n\n app.UseHttpsRedirection();\n app.UseStaticFiles();\n app.UseRouting();\n\n app.UseAuthentication();\n app.UseAuthorization();\n \n app.MapControllerRoute(\n name: \"default\",\n pattern: \"{controller=Home}/{action=Index}/{id?}\");\n }\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20625857/"
] |
74,610,876
|
<p>When tring to implement <code>std::vector</code>, I get confused with the implicit call to destructor.</p>
<p>Then element in vector maybe:</p>
<ul>
<li><code>T</code>
<ul>
<li>a Class Object,</li>
</ul>
</li>
<li><code>T*</code>, <code>shared_ptr<T></code>
<ul>
<li>a Smart/Simple Pointer to Class Object</li>
</ul>
</li>
<li><code>int</code>
<ul>
<li>built-in type</li>
</ul>
</li>
<li><code>int *</code>
<ul>
<li>pointer to built-in type</li>
</ul>
</li>
</ul>
<p>When calling <code>resize()</code>,<code>reserve()</code> ,<code>erase()</code>or <code>pop_back()</code>, the destructor might be called.</p>
<p><strong>I wonder how does <code>std::vector</code> deal with the call to destructor.</strong></p>
<p>I found, only when the type is a build-in pointer won't <code>std::vector</code> call the destructor(Of course if it have one).</p>
<p><strong>Does <code>std::vector</code> implement it by distinguishing type and determine whether or not to call the destructor?</strong></p>
<p>Below are some experiments about the question:</p>
<p><strong>Example 1</strong>, the element is Object.</p>
<pre class="lang-cpp prettyprint-override"><code>#include <vector>
#include <iostream>
using namespace std;
struct Tmp {
~Tmp() { cerr << "Destructor is called." << endl; }
};
int main (void)
{
std::vector<Tmp>arr;
Tmp tmp = Tmp();
cerr << "Capacity:" << arr.capacity() << endl;//0
arr.push_back (tmp);
cerr << "Capacity:" << arr.capacity() << endl;//1
arr.push_back (tmp);
cerr << "Capacity:" << arr.capacity() << endl;//2
cerr << "popback start------------" << std::endl;
arr.pop_back();
arr.pop_back();
cerr << "popback end--------------" << endl;
}
</code></pre>
<p>the output is:</p>
<pre class="lang-bash prettyprint-override"><code>Capacity:0
Capacity:1
Destructor is called.
Capacity:2
popback start------------
Destructor is called.
Destructor is called.
popback end--------------
Destructor is called.
</code></pre>
<p><strong>Example 2</strong>, the element is builtin-in pointer to obecjt:</p>
<pre class="lang-cpp prettyprint-override"><code>...
std::vector<Tmp>arr;
Tmp * tmp = new Tmp;
...
</code></pre>
<p>The destructor won't be called automatically:</p>
<pre class="lang-bash prettyprint-override"><code>Capacity:0
Capacity:1
Capacity:2
popback start------------
popback end--------------
</code></pre>
<p><strong>Example 3</strong>, shared_ptr</p>
<pre class="lang-cpp prettyprint-override"><code>std::vector<shared_ptr<Tmp>>arr;
auto tmp = make_shared<Tmp>();
... //after being copied, the references count should be 3.
tmp = nullptr; //References count reduced by 1
cerr << "popback start------------" << std::endl;
arr.pop_back();//References count reduced by 1
arr.pop_back();//References count reduced by 1
cerr << "popback end--------------" << endl;
</code></pre>
<p>The destructor of shared_ptr will be called. When the references reduced to 0, the destructor of Tmp will be called:</p>
<pre class="lang-bash prettyprint-override"><code>Capacity:0
Capacity:1
Capacity:2
popback start------------
Destructor is called.
popback end--------------
</code></pre>
|
[
{
"answer_id": 74610846,
"author": "kosist",
"author_id": 6917446,
"author_profile": "https://Stackoverflow.com/users/6917446",
"pm_score": 0,
"selected": false,
"text": "IConfiguration Microsoft.Extensions.Configuration"
},
{
"answer_id": 74610885,
"author": "klekmek",
"author_id": 4797062,
"author_profile": "https://Stackoverflow.com/users/4797062",
"pm_score": 0,
"selected": false,
"text": "IConfiguration configuration = builder.Configuration;"
},
{
"answer_id": 74611229,
"author": "Govind",
"author_id": 5951802,
"author_profile": "https://Stackoverflow.com/users/5951802",
"pm_score": 1,
"selected": false,
"text": "var builder = WebApplication.CreateBuilder(args);\n//Get the instance of the IConfiguration service\nvar configuration = builder.Configuration;\n//We can configure configuration variables of type IConfiguration and get a value \nvar vTestValue = configuration.GetValue<string>(\"TestValue\");\n"
},
{
"answer_id": 74622479,
"author": "Gauravsa",
"author_id": 2549110,
"author_profile": "https://Stackoverflow.com/users/2549110",
"pm_score": 0,
"selected": false,
"text": "\"Employee\": {\n \"Title\": \"Mr\",\n \"Name\": \"Joe Smith\"\n }\n public class EmployeeOptions\n{\n public const string Employee = \"Employee\";\n public string Title { get; set; } = String.Empty;\n public string Name { get; set; } = String.Empty;\n}\n public class Program\n{\n public static void Main(string[] args)\n {\n var builder = WebApplication.CreateBuilder(args);\n var startup = new Startup(builder.Configuration);\n startup.RegisterServices(builder.Services);\n\n var app = builder.Build();\n startup.SetupMiddlewares(app);\n\n app.Run();\n } }\n public class Startup\n{\n public Startup(IConfiguration configuration)\n {\n Configuration = configuration;\n }\n\n public IConfiguration Configuration { get; }\n\n public void RegisterServices(IServiceCollection services)\n {\n services.Configure<EmployeeOptions>(\n Configuration.GetSection(EmployeeOptions.Employee));\n }\n\n public void SetupMiddlewares(WebApplication app)\n {\n // Configure the HTTP request pipeline.\n if (!app.Environment.IsDevelopment())\n {\n app.UseExceptionHandler(\"/Home/Error\");\n // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.\n app.UseHsts();\n }\n\n app.UseHttpsRedirection();\n app.UseStaticFiles();\n app.UseRouting();\n\n app.UseAuthentication();\n app.UseAuthorization();\n \n app.MapControllerRoute(\n name: \"default\",\n pattern: \"{controller=Home}/{action=Index}/{id?}\");\n }\n}\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17864498/"
] |
74,610,882
|
<p>I do have a file with different length of each line. E.g.:</p>
<pre><code>a; 1; 2; 3; 4;
b; 11; 22;
c; 122; 233; 344; 45; 56;
d; 13;
e; 144; 25; 36; 47; 58; 69;
</code></pre>
<p>I try to generate a file, separated by semicolon where each line has the same amount of values. E.g.:</p>
<pre><code>a; 1; 2; 3; 4; ; ;
b; 11; 22; ; ; ; ;
c; 122; 233; 344; 45; 56; ;
d; 13; ; ; ; ; ;
e; 144; 25; 36; 47; 58; 69;
</code></pre>
<p>I tried different ways with awk but I am to newbie to get it done correctly in bulk.</p>
<pre class="lang-bash prettyprint-override"><code>awk '{if( $4 == ""){print ";"}else{print $4}}' testtest.txt
</code></pre>
<p>I hope the swarm intelligence can help me with it.</p>
|
[
{
"answer_id": 74611106,
"author": "Fravadona",
"author_id": 3387716,
"author_profile": "https://Stackoverflow.com/users/3387716",
"pm_score": 3,
"selected": true,
"text": "awk -F '; *' -v OFS='; ' '{$8 = $8} 1'\n"
},
{
"answer_id": 74611118,
"author": "RavinderSingh13",
"author_id": 5866580,
"author_profile": "https://Stackoverflow.com/users/5866580",
"pm_score": 3,
"selected": false,
"text": "awk ; awk -v FS='; ' -v OFS='; ' '\nFNR==NR{\n nf=(nf>NF?nf:NF)\n next\n}\n{\n $nf=$nf\n}\n1\n' Input_file Input_file\n"
},
{
"answer_id": 74612093,
"author": "blhsing",
"author_id": 6890912,
"author_profile": "https://Stackoverflow.com/users/6890912",
"pm_score": 2,
"selected": false,
"text": "ARGC ARGV awk '\nBEGIN{\n FS=OFS=\"; \"\n}\nNR==1{\n ARGV[ARGC++] = FILENAME\n}\nFNR==NR{\n nf=(nf>NF?nf:NF)\n next\n}\n{\n NF=nf\n}\n1\n' testtest.txt\n"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20630882/"
] |
74,610,932
|
<p>I am trying to allow some character through regular expression. I want to allow word with special character like ( - _ & spaces) in between the character. Also i am allowing number in a word along with letter.</p>
<p>Valid:</p>
<pre><code>a_B
a_b
a b
a B
a_btest_psom
a-B
a43 b
a43_c
</code></pre>
<p>Invalid:</p>
<pre><code>a_
_a
a-
a_b_
a_B_
a_b-
a_btest_psom_ (at end only special character)
43 b (starting with number)
43_c (starting with number)
434343 (only numbers)
</code></pre>
<p>Code:</p>
<pre class="lang-java prettyprint-override"><code>import javax.validation.constraints.Pattern;
public static final String PATTERN="^[a-zA-Z0-9 _-]*$";
@Pattern(regexp = PATTERN)
private String companyName;
</code></pre>
<p>Using above code, I am not able to achieve as per my expectation. Can you help me on this?</p>
|
[
{
"answer_id": 74611009,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 2,
"selected": true,
"text": "^[a-zA-Z][a-zA-Z0-9]*(?:[ _-][a-zA-Z0-9]+)*$\n ^ [a-zA-Z][a-zA-Z0-9]* (?:[ _-][a-zA-Z0-9]+)* _ - $"
},
{
"answer_id": 74611025,
"author": "Gicu Aftene",
"author_id": 18811731,
"author_profile": "https://Stackoverflow.com/users/18811731",
"pm_score": 0,
"selected": false,
"text": "[a-zA-Z] [a-zA-Z0-9] ^[a-zA-Z][a-zA-Z0-9 _-]*[a-zA-Z0-9]$ ^[a-zA-Z][a-zA-Z0-9 _-]*[a-zA-Z]$"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3925730/"
] |
74,610,948
|
<pre><code>error: unreachable statement
</code></pre>
<p>why is it not printing hello world?</p>
<pre><code>public class Main
{
public static void main(String[] args) {
final int a=10,b=20;
while(a>b){
System.out.print("Message");
}
System.out.println("Hello World");
}
}
</code></pre>
|
[
{
"answer_id": 74611042,
"author": "Mark Rotteveel",
"author_id": 466862,
"author_profile": "https://Stackoverflow.com/users/466862",
"pm_score": 1,
"selected": false,
"text": "a>b a b final false while"
},
{
"answer_id": 74611057,
"author": "Bas van der Linden",
"author_id": 11119684,
"author_profile": "https://Stackoverflow.com/users/11119684",
"pm_score": 0,
"selected": false,
"text": "a b while(a > b)\n final a b"
}
] |
2022/11/29
|
[
"https://Stackoverflow.com/questions/74610948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20631126/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.