qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,410,292 | <p>My target on daily basis is 250. For any given date, if the cum-daily_result has reached 250 then subsequent rows should have only 250 as expected results</p>
<p>In below table column 'ID' to 'cum_daily_result' are the input in data frame. The expected output is computed manually in column 'expected_daily_result'</p>
<p><a href="https://i.stack.imgur.com/xjRg5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xjRg5.png" alt="enter image description here" /></a></p>
<p>I tried the below code, but not giving the expected result,</p>
<pre><code>if df['cum_daily_result'][-1] >= 250:
expected_daily_result = df['cum_daily_result'][-1]
else:
expected_daily_result = df['cum_daily_result']
</code></pre>
| [
{
"answer_id": 74410277,
"author": "Royadma",
"author_id": 20476279,
"author_profile": "https://Stackoverflow.com/users/20476279",
"pm_score": 1,
"selected": false,
"text": "a[1,2] = \"some value\"\n"
},
{
"answer_id": 74410311,
"author": "Austin",
"author_id": 8472377,
"author_profile": "https://Stackoverflow.com/users/8472377",
"pm_score": 0,
"selected": false,
"text": ".copy()"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74410292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20482853/"
] |
74,410,315 | <p>Why doesn't the following barrier implementation work:</p>
<pre><code>void JoinQuery::barrier() {
std::unique_lock<std::mutex> lk(barrier_mutex);
barrier_count++;
if (barrier_count == NUM_THREADS) {
barrier_count = 0;
lk.unlock();
barrier_cv.notify_all();
} else {
barrier_cv.wait(lk, [this] { return barrier_count == 0; });
}
}
</code></pre>
<p>However it works if I use a second variable to track the condition of all threads arriving.</p>
<p>But I don't know why this is necessary. It should be impossible for a thread to see barrier_count == 0 before all threads have arrived.</p>
| [
{
"answer_id": 74410277,
"author": "Royadma",
"author_id": 20476279,
"author_profile": "https://Stackoverflow.com/users/20476279",
"pm_score": 1,
"selected": false,
"text": "a[1,2] = \"some value\"\n"
},
{
"answer_id": 74410311,
"author": "Austin",
"author_id": 8472377,
"author_profile": "https://Stackoverflow.com/users/8472377",
"pm_score": 0,
"selected": false,
"text": ".copy()"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74410315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3901677/"
] |
74,410,324 | <p>I have an issue which is I keep getting the error of NameError: name 'Class_Name' is not defined. Which I understand. The tricky part is that my code looks something like this:</p>
<pre><code>class FirstClass():
second_class: SecondClass
def __init__(self):
"""SOME CODE HERE"""
class SecondClass(firsClass: FirstClass):
def __init__(self):
self.first_class = firstClass
</code></pre>
<p>So the problem is that no matter how I arrange the code, I will always have one above the other so it will always say that is not defined. How can I solve this?</p>
<p>------------------------<strong>SOLUTION</strong>----------------------------</p>
<p>I found the solution to this. If you use the import</p>
<pre><code>from __future__ import annotations
</code></pre>
<p>It will read the file and you will be able to call the classes even if they are defined later in the code.</p>
| [
{
"answer_id": 74410277,
"author": "Royadma",
"author_id": 20476279,
"author_profile": "https://Stackoverflow.com/users/20476279",
"pm_score": 1,
"selected": false,
"text": "a[1,2] = \"some value\"\n"
},
{
"answer_id": 74410311,
"author": "Austin",
"author_id": 8472377,
"author_profile": "https://Stackoverflow.com/users/8472377",
"pm_score": 0,
"selected": false,
"text": ".copy()"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74410324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8011633/"
] |
74,410,330 | <pre><code><!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/static/nav.css"> <!—secondary bootstrap code—!>
<link rel="stylesheet" href="/static/bootstrap.css">
<script src="https://cdn.jsdelivr.net/npm/bootstrap/dist/js/bootstrap.bundle.min.js"></script> </head>
<body>
<header>
<nav class="navbar navbar-expand-sm bg-dark navbar-dark">
<div class="container-fluid">
<a class="navbar-brand" href="/link">Link</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#collapsibleNavbar">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="collapsibleNavbar">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="/link">Link</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">Link</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="/link">Paid Services</a></li>
<li><a class="dropdown-item" href="/link">Flash Documentation</a></li>
<li><a class="dropdown-item" href="/link">SMS Bomb</a></li>
<li><a class="dropdown-item" href="/link">MDickie Projects</a></li>
<li><a class="dropdown-item" href="/link">BxPP</a></li>
</ul>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">Link</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="/link">Link</a></li>
<li><a class="dropdown-item" href="/link">Link</a></li>
<li><a class="dropdown-item" href="/link">Link</a></li>
<li><a class="dropdown-item" href="/link">Link</a></li>
</ul>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">Link</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="/link">Link</a></li>
<li><a class="dropdown-item" href="/link">Link</a></li>
<li><a class="dropdown-item" href="/link">Link</a></li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
</header>
</body>
</html>
</code></pre>
<p>Hello community of Stackoverflow. This bootstrap header doesn't dropdown on mobile devices. I have the JS and CSS, and I really don't know what do. Can someone help? Replace the "/" with atproducts.xyz since it triggered the spam filter.</p>
| [
{
"answer_id": 74410399,
"author": "Saad1430",
"author_id": 19199222,
"author_profile": "https://Stackoverflow.com/users/19199222",
"pm_score": 0,
"selected": false,
"text": "<head>"
},
{
"answer_id": 74410413,
"author": "Tiziano Volpe",
"author_id": 13218875,
"author_profile": "https://Stackoverflow.com/users/13218875",
"pm_score": 1,
"selected": false,
"text": "<link rel=\"stylesheet\" href=\"/static/nav.css\"> <!—secondary bootstrap code—!>\n<link rel=\"stylesheet\" href=\"/static/bootstrap.css\">\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74410330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20322733/"
] |
74,410,389 | <p>I'm completely new to Java, and doing some online courses. I was doing this task when the online instructions did the task under a single Main class. I was trying to do some testing as I like to try keep my main class simple and was wondering how I could go about bringing about different arrays and method from another class over to my main class.</p>
<pre><code>import java.util.Scanner;
public class Arrays {
public static Scanner scan = new Scanner(System.in);
public static int[] getIntegers(int number) {
System.out.println("Please enter " + number + " numbers\r");
int[] entered = new int[number];
for(int i = 0; i < entered.length; i++) {
entered[i] = scan.nextInt();
}
return entered;
}
public static void printArray(int[] entered) {
for(int i = 0; i < entered.length; i++) {
System.out.println("Element " + i + ", typed value was " + entered[i]);
}
}
public static int[] sortIntegers(int[] entered) {
int[] sortedArray = new int[entered.length];
for(int i = 0; i < entered.length; i++) {
sortedArray[i] = entered[i];
}
boolean flag = true;
int temp;
while(flag) {
flag = false;
for(int i = 0; i < sortedArray.length - 1; i++) {
if(sortedArray[i] < sortedArray[i + 1]) {
temp = sortedArray[i];
sortedArray[i] = sortedArray[i + 1];
sortedArray[i + 1] = temp;
flag = true;
}
}
}
return sortedArray;
}
}
</code></pre>
<p>And my Main class.</p>
<pre><code>public class Main {
public static void main (String[] args) {
int[] myIntegers = getIntegers(5);
int[] sorted = sortIntegers(myIntegers);
printArray(myIntegers);
printArray(sorted);
}
}
</code></pre>
<p>IntelliJ allows me to just import static className over but I want to try it without a method that just imports the class over by using OOP standards.</p>
<p>as you can see I want to bring over getIntegers, printArray, and sortIntegers.</p>
| [
{
"answer_id": 74410981,
"author": "Dinuka Silva",
"author_id": 20457576,
"author_profile": "https://Stackoverflow.com/users/20457576",
"pm_score": 1,
"selected": true,
"text": "public class Main {\npublic static void main(String[] args) {\n Arrays arrays = new Arrays();\n int[] myIntegers = arrays.getIntegers(5);\n int[] sorted = arrays.sortIntegers(myIntegers);\n arrays.printArray(myIntegers);\n arrays.printArray(sorted);\n}\n"
},
{
"answer_id": 74411871,
"author": "Basil Bourque",
"author_id": 642706,
"author_profile": "https://Stackoverflow.com/users/642706",
"pm_score": 0,
"selected": false,
"text": "main"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74410389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20483051/"
] |
74,410,396 | <pre><code><div class="menu-bar">
<ul>
<li><a href="/Home/index.html"> <i class="fa fa-house"></i>Home</a> </i></li>
< ul >
</div>
<style>
.menu-bar ul li a:hover {
color: black;
transition: all 0.2s;
border-inline-end: 2px solid;
border-block-end: 2px solid;
</style>
</code></pre>
<p>I want to remove :hover effect from that cdn icon fa fa-house.</p>
| [
{
"answer_id": 74410981,
"author": "Dinuka Silva",
"author_id": 20457576,
"author_profile": "https://Stackoverflow.com/users/20457576",
"pm_score": 1,
"selected": true,
"text": "public class Main {\npublic static void main(String[] args) {\n Arrays arrays = new Arrays();\n int[] myIntegers = arrays.getIntegers(5);\n int[] sorted = arrays.sortIntegers(myIntegers);\n arrays.printArray(myIntegers);\n arrays.printArray(sorted);\n}\n"
},
{
"answer_id": 74411871,
"author": "Basil Bourque",
"author_id": 642706,
"author_profile": "https://Stackoverflow.com/users/642706",
"pm_score": 0,
"selected": false,
"text": "main"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74410396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20404911/"
] |
74,410,414 | <p>I need to generate a full month report base on some criteria. The first condition is- I am taking a anonyms <strong>Date</strong> from user and after checking all the condition it will generate full month report.</p>
<p>I tried to generate the report but this is returning a day wise report. Everything is fine except the month. Please help me to do this.</p>
<pre><code>[HttpGet("inner-join/{id}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public IActionResult GetReport(DateTime id)
{
try
{
IEnumerable<BTBPending> objBTBPendingList = _unitOfWork.BTBPending.GetAll(includeProperties: "ProformaInvoice,ContractList,SupplierList,CountryList,ItemList,BuyerList,StyleList,TradeTermList,ErpRemarksList,StatusList,LcNoList,UdAmendList");
IEnumerable<ProformaInvoice> objProformaInvoiceList = _unitOfWork.ProformaInvoice.GetAll(includeProperties: "ActualContract,ContractList,SupplierList,CountryList,ItemList,BuyerList,StyleList,TradeTermList");
var query = objBTBPendingList
.Where(x => x.LcOpenDate == id)
.Where(x => x.CountryListId == 26)
.Where(x => x.StatusListId == 12 || x.StatusListId == 13 || x.StatusListId == 14)
.Join(objProformaInvoiceList,
btbPending => btbPending.ContractListId,
pi => pi.ContractListId,
(btbPending, pi) => new
{
LcNo = btbPending.LcNoList,
Value = btbPending.PiValue,
ContractNo = pi.ContractList,
Buyer = pi.BuyerList,
PiNo = pi.PINo,
Supplier = pi.SupplierList,
Item = pi.ItemList
}).ToList();
return Ok(query);
}
catch (Exception ex)
{
return StatusCode(500, "Internal Server Error, Please Try Again Leter!");
}
}
</code></pre>
| [
{
"answer_id": 74410433,
"author": "vivek nuna",
"author_id": 6527049,
"author_profile": "https://Stackoverflow.com/users/6527049",
"pm_score": 2,
"selected": true,
"text": ".Where(x => x.LcOpenDate.Month == id.Month && x.LcOpenDate.Year == id.Year)\n"
},
{
"answer_id": 74410441,
"author": "Slack Groverglow",
"author_id": 3761097,
"author_profile": "https://Stackoverflow.com/users/3761097",
"pm_score": 0,
"selected": false,
"text": "DateTime"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74410414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20421446/"
] |
74,410,420 | <p>What's wrong with this code? I tried get marks using array and pass the array in to function parameters and calculate the average in that function.</p>
<pre><code>const marks = [100,100,80];
var summ = 0;
function calculateGrade(){
for(let i=0; i<=marks.length;i++){
summ = summ+marks[i];
var avg = (summ/marks.length);
}
if(avg<=59){
console.log('F');
}
else if(avg>=60 && avg<=69){
console.log('D');
}
else if(avg>=70 && avg<=79){
console.log('C');
}
else if(avg>=80 && avg<=89){
console.log('B');
}
else if(avg>=90 && avg<=100){
console.log('A');
}
}
console.log(calculateGrade(marks));
</code></pre>
| [
{
"answer_id": 74410451,
"author": "user2182349",
"author_id": 2182349,
"author_profile": "https://Stackoverflow.com/users/2182349",
"pm_score": 1,
"selected": false,
"text": "const marks = [100, 100, 80];\n\n\nfunction calculateGrade(marks) {\n\n let summ = 0;\n\n for (let i = 0; i < marks.length; i++) {\n summ += marks[i];\n }\n const avg = summ / marks.length;\n let grade = '';\n if (avg < 59) {\n grade = 'F';\n } else if (avg <= 69) {\n grade = 'D';\n } else if (avg <= 79) {\n grade = 'C';\n } else if (avg <= 89) {\n grade = 'B';\n } else {\n grade = 'A';\n }\n return grade;\n}\n\nconsole.log(calculateGrade(marks));"
},
{
"answer_id": 74410458,
"author": "loxxy",
"author_id": 378806,
"author_profile": "https://Stackoverflow.com/users/378806",
"pm_score": 1,
"selected": false,
"text": "i<=marks.length\n"
},
{
"answer_id": 74410491,
"author": "Javaid",
"author_id": 11674006,
"author_profile": "https://Stackoverflow.com/users/11674006",
"pm_score": 2,
"selected": true,
"text": " const marks = [100, 100, 80];\n var summ = 0;\n \n //issue one (Tmarks were missing )\n function calculateGrade(Tmarks) {\n // issues 2 ( <= should be < )\n for (let i = 0; i < Tmarks.length; i++) {\n summ += Tmarks[i];\n }\n var avg = summ / Tmarks.length;\n if (avg <= 59) {\n console.log(\"F\");\n } else if (avg >= 60 && avg <= 69) {\n console.log(\"D\");\n } else if (avg >= 70 && avg <= 79) {\n console.log(\"C\");\n } else if (avg >= 80 && avg <= 89) {\n console.log(\"B\");\n } else if (avg >= 90 && avg <= 100) {\n console.log(\"A\");\n }\n }\n\n console.log(calculateGrade(marks));\n"
},
{
"answer_id": 74410560,
"author": "Bishan",
"author_id": 1029088,
"author_profile": "https://Stackoverflow.com/users/1029088",
"pm_score": 1,
"selected": false,
"text": "for(let i=0; i<=marks.length;i++)\n"
},
{
"answer_id": 74410595,
"author": "Syful Islam",
"author_id": 10710013,
"author_profile": "https://Stackoverflow.com/users/10710013",
"pm_score": 1,
"selected": false,
"text": "` calculateGrade(){\n let marks = [100,100,80];\n let summ = 0;\n let avg = 0;\n \n for(let i = 0; i < marks.length; i++){\n summ = summ+marks[i];\n avg = (summ/marks.length);\n }\n \n if(avg<=59){\n console.log('F');\n }\n else if(avg>=60 && avg<=69){\n console.log('D');\n }\n else if(avg>=70 && avg<=79){\n console.log('C');\n }\n else if(avg>=80 && avg<=89){\n console.log('B');\n }\n else if(avg>=90 && avg<=100){\n console.log('A');\n }\n }`\n\n> array start from 0\n\n \n"
},
{
"answer_id": 74410618,
"author": "Alex",
"author_id": 19933529,
"author_profile": "https://Stackoverflow.com/users/19933529",
"pm_score": 2,
"selected": false,
"text": "const sum = marks.reduce((partialSum, a) => partialSum + a, 0);\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74410420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11974838/"
] |
74,410,429 | <p>I'm trying to write a code for linked lists using c++. Insert at begin and Insert at end are not working for some reason. Here is the code.</p>
<p>`</p>
<pre><code>#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
void insertAtBeginning(int );
void insertAtEnd(int );
void printLL();
struct Node
{
int data;
struct Node *link;
};
struct Node *head;
int main()
{
struct Node *temp, *newnode;
int ch=1, i=1, info;
head = NULL;
while(ch)
{
printf("Enter data: ");
scanf("%d", &info);
newnode = (struct Node *)malloc(sizeof(struct Node));
newnode->data = info;
newnode->link = NULL;
if(head == NULL)
{
head = newnode;
temp = newnode;
}
else
{
temp ->link = newnode;
temp = newnode;
}
printf("You wish to continue? (press 0 to terminate)\n");
scanf("%d",&ch);
if(!ch)
{
break;
}
}
temp = head;
while(temp!=NULL)
{
printf("%d -> ",temp->data);
temp = temp->link;
}
printf("\n");
insertAtBeginning(50);
insertAtEnd(150);
//printLL();
}
void insertAtBeginning(int info)
{
struct Node *newnode;
newnode->data = info;
printf("\n%d\n", newnode ->data);
newnode->link = head;
head = newnode;
}
void insertAtEnd(int info)
{
struct Node *temp, *newnode;
newnode->link = NULL;
newnode->data = info;
temp = head;
while(temp!=NULL)
{
temp = temp->link;
}
temp->link = newnode;
printf("\n%d\n", newnode -> data);
}
void printLL()
{
struct Node *temp;
temp = head;
while(temp!=NULL)
{
printf("%d -> ",temp->data);
temp = temp->link;
}
}
</code></pre>
<p>`</p>
<p>The problem is somewhere around <code>newnode->data = info</code> in the functions.</p>
<p>I created two functions, one to insert an element at beginning and one to insert an element at end. In both of them, i've created a newnode. The problem is I cannot insert data into those nodes.</p>
| [
{
"answer_id": 74410451,
"author": "user2182349",
"author_id": 2182349,
"author_profile": "https://Stackoverflow.com/users/2182349",
"pm_score": 1,
"selected": false,
"text": "const marks = [100, 100, 80];\n\n\nfunction calculateGrade(marks) {\n\n let summ = 0;\n\n for (let i = 0; i < marks.length; i++) {\n summ += marks[i];\n }\n const avg = summ / marks.length;\n let grade = '';\n if (avg < 59) {\n grade = 'F';\n } else if (avg <= 69) {\n grade = 'D';\n } else if (avg <= 79) {\n grade = 'C';\n } else if (avg <= 89) {\n grade = 'B';\n } else {\n grade = 'A';\n }\n return grade;\n}\n\nconsole.log(calculateGrade(marks));"
},
{
"answer_id": 74410458,
"author": "loxxy",
"author_id": 378806,
"author_profile": "https://Stackoverflow.com/users/378806",
"pm_score": 1,
"selected": false,
"text": "i<=marks.length\n"
},
{
"answer_id": 74410491,
"author": "Javaid",
"author_id": 11674006,
"author_profile": "https://Stackoverflow.com/users/11674006",
"pm_score": 2,
"selected": true,
"text": " const marks = [100, 100, 80];\n var summ = 0;\n \n //issue one (Tmarks were missing )\n function calculateGrade(Tmarks) {\n // issues 2 ( <= should be < )\n for (let i = 0; i < Tmarks.length; i++) {\n summ += Tmarks[i];\n }\n var avg = summ / Tmarks.length;\n if (avg <= 59) {\n console.log(\"F\");\n } else if (avg >= 60 && avg <= 69) {\n console.log(\"D\");\n } else if (avg >= 70 && avg <= 79) {\n console.log(\"C\");\n } else if (avg >= 80 && avg <= 89) {\n console.log(\"B\");\n } else if (avg >= 90 && avg <= 100) {\n console.log(\"A\");\n }\n }\n\n console.log(calculateGrade(marks));\n"
},
{
"answer_id": 74410560,
"author": "Bishan",
"author_id": 1029088,
"author_profile": "https://Stackoverflow.com/users/1029088",
"pm_score": 1,
"selected": false,
"text": "for(let i=0; i<=marks.length;i++)\n"
},
{
"answer_id": 74410595,
"author": "Syful Islam",
"author_id": 10710013,
"author_profile": "https://Stackoverflow.com/users/10710013",
"pm_score": 1,
"selected": false,
"text": "` calculateGrade(){\n let marks = [100,100,80];\n let summ = 0;\n let avg = 0;\n \n for(let i = 0; i < marks.length; i++){\n summ = summ+marks[i];\n avg = (summ/marks.length);\n }\n \n if(avg<=59){\n console.log('F');\n }\n else if(avg>=60 && avg<=69){\n console.log('D');\n }\n else if(avg>=70 && avg<=79){\n console.log('C');\n }\n else if(avg>=80 && avg<=89){\n console.log('B');\n }\n else if(avg>=90 && avg<=100){\n console.log('A');\n }\n }`\n\n> array start from 0\n\n \n"
},
{
"answer_id": 74410618,
"author": "Alex",
"author_id": 19933529,
"author_profile": "https://Stackoverflow.com/users/19933529",
"pm_score": 2,
"selected": false,
"text": "const sum = marks.reduce((partialSum, a) => partialSum + a, 0);\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74410429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19701594/"
] |
74,410,431 | <p>Given a set of X numbers less than or equal to Y, which may contain repeated numbers:</p>
<p>which algorithm gives you the maximum number of subsets whose sum of their elements is greater than or equal to Y, where none of the elements of one subset can be contained in another, and each subset cannot repeat the same element.</p>
<p>(note: if in the initial set two numbers are repeated, each counts as a distinct element)</p>
<p>subsets can group elements into duos, trios, quartets or any other number.</p>
<p>doing two for loops to search for the best combination for the highest number worked for doubles, but given that it is possible to do trios and so on, cases like "1 1 1 1 1 7 8" would be suboptimized</p>
| [
{
"answer_id": 74410451,
"author": "user2182349",
"author_id": 2182349,
"author_profile": "https://Stackoverflow.com/users/2182349",
"pm_score": 1,
"selected": false,
"text": "const marks = [100, 100, 80];\n\n\nfunction calculateGrade(marks) {\n\n let summ = 0;\n\n for (let i = 0; i < marks.length; i++) {\n summ += marks[i];\n }\n const avg = summ / marks.length;\n let grade = '';\n if (avg < 59) {\n grade = 'F';\n } else if (avg <= 69) {\n grade = 'D';\n } else if (avg <= 79) {\n grade = 'C';\n } else if (avg <= 89) {\n grade = 'B';\n } else {\n grade = 'A';\n }\n return grade;\n}\n\nconsole.log(calculateGrade(marks));"
},
{
"answer_id": 74410458,
"author": "loxxy",
"author_id": 378806,
"author_profile": "https://Stackoverflow.com/users/378806",
"pm_score": 1,
"selected": false,
"text": "i<=marks.length\n"
},
{
"answer_id": 74410491,
"author": "Javaid",
"author_id": 11674006,
"author_profile": "https://Stackoverflow.com/users/11674006",
"pm_score": 2,
"selected": true,
"text": " const marks = [100, 100, 80];\n var summ = 0;\n \n //issue one (Tmarks were missing )\n function calculateGrade(Tmarks) {\n // issues 2 ( <= should be < )\n for (let i = 0; i < Tmarks.length; i++) {\n summ += Tmarks[i];\n }\n var avg = summ / Tmarks.length;\n if (avg <= 59) {\n console.log(\"F\");\n } else if (avg >= 60 && avg <= 69) {\n console.log(\"D\");\n } else if (avg >= 70 && avg <= 79) {\n console.log(\"C\");\n } else if (avg >= 80 && avg <= 89) {\n console.log(\"B\");\n } else if (avg >= 90 && avg <= 100) {\n console.log(\"A\");\n }\n }\n\n console.log(calculateGrade(marks));\n"
},
{
"answer_id": 74410560,
"author": "Bishan",
"author_id": 1029088,
"author_profile": "https://Stackoverflow.com/users/1029088",
"pm_score": 1,
"selected": false,
"text": "for(let i=0; i<=marks.length;i++)\n"
},
{
"answer_id": 74410595,
"author": "Syful Islam",
"author_id": 10710013,
"author_profile": "https://Stackoverflow.com/users/10710013",
"pm_score": 1,
"selected": false,
"text": "` calculateGrade(){\n let marks = [100,100,80];\n let summ = 0;\n let avg = 0;\n \n for(let i = 0; i < marks.length; i++){\n summ = summ+marks[i];\n avg = (summ/marks.length);\n }\n \n if(avg<=59){\n console.log('F');\n }\n else if(avg>=60 && avg<=69){\n console.log('D');\n }\n else if(avg>=70 && avg<=79){\n console.log('C');\n }\n else if(avg>=80 && avg<=89){\n console.log('B');\n }\n else if(avg>=90 && avg<=100){\n console.log('A');\n }\n }`\n\n> array start from 0\n\n \n"
},
{
"answer_id": 74410618,
"author": "Alex",
"author_id": 19933529,
"author_profile": "https://Stackoverflow.com/users/19933529",
"pm_score": 2,
"selected": false,
"text": "const sum = marks.reduce((partialSum, a) => partialSum + a, 0);\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74410431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15457253/"
] |
74,410,506 | <pre><code>{
correct: "Warren Harding",
incorrect:
0: "Theodore Roosevelt",
1: "Andrew Jackson "
}
</code></pre>
<p>So I have this object, I want to turn it into an array containing objects like this:</p>
<pre><code>[answerOptions: [{answerText: "Warren Harding", isCorrect: true}, {answerText: "Theodore Roosevelt", isCorrect: false}, {answerText: "Andrew Jackson", isCorrect: false}]
</code></pre>
<p>How can I do this because I have been trying to figure this out for so long but I can't figure it out.</p>
| [
{
"answer_id": 74410451,
"author": "user2182349",
"author_id": 2182349,
"author_profile": "https://Stackoverflow.com/users/2182349",
"pm_score": 1,
"selected": false,
"text": "const marks = [100, 100, 80];\n\n\nfunction calculateGrade(marks) {\n\n let summ = 0;\n\n for (let i = 0; i < marks.length; i++) {\n summ += marks[i];\n }\n const avg = summ / marks.length;\n let grade = '';\n if (avg < 59) {\n grade = 'F';\n } else if (avg <= 69) {\n grade = 'D';\n } else if (avg <= 79) {\n grade = 'C';\n } else if (avg <= 89) {\n grade = 'B';\n } else {\n grade = 'A';\n }\n return grade;\n}\n\nconsole.log(calculateGrade(marks));"
},
{
"answer_id": 74410458,
"author": "loxxy",
"author_id": 378806,
"author_profile": "https://Stackoverflow.com/users/378806",
"pm_score": 1,
"selected": false,
"text": "i<=marks.length\n"
},
{
"answer_id": 74410491,
"author": "Javaid",
"author_id": 11674006,
"author_profile": "https://Stackoverflow.com/users/11674006",
"pm_score": 2,
"selected": true,
"text": " const marks = [100, 100, 80];\n var summ = 0;\n \n //issue one (Tmarks were missing )\n function calculateGrade(Tmarks) {\n // issues 2 ( <= should be < )\n for (let i = 0; i < Tmarks.length; i++) {\n summ += Tmarks[i];\n }\n var avg = summ / Tmarks.length;\n if (avg <= 59) {\n console.log(\"F\");\n } else if (avg >= 60 && avg <= 69) {\n console.log(\"D\");\n } else if (avg >= 70 && avg <= 79) {\n console.log(\"C\");\n } else if (avg >= 80 && avg <= 89) {\n console.log(\"B\");\n } else if (avg >= 90 && avg <= 100) {\n console.log(\"A\");\n }\n }\n\n console.log(calculateGrade(marks));\n"
},
{
"answer_id": 74410560,
"author": "Bishan",
"author_id": 1029088,
"author_profile": "https://Stackoverflow.com/users/1029088",
"pm_score": 1,
"selected": false,
"text": "for(let i=0; i<=marks.length;i++)\n"
},
{
"answer_id": 74410595,
"author": "Syful Islam",
"author_id": 10710013,
"author_profile": "https://Stackoverflow.com/users/10710013",
"pm_score": 1,
"selected": false,
"text": "` calculateGrade(){\n let marks = [100,100,80];\n let summ = 0;\n let avg = 0;\n \n for(let i = 0; i < marks.length; i++){\n summ = summ+marks[i];\n avg = (summ/marks.length);\n }\n \n if(avg<=59){\n console.log('F');\n }\n else if(avg>=60 && avg<=69){\n console.log('D');\n }\n else if(avg>=70 && avg<=79){\n console.log('C');\n }\n else if(avg>=80 && avg<=89){\n console.log('B');\n }\n else if(avg>=90 && avg<=100){\n console.log('A');\n }\n }`\n\n> array start from 0\n\n \n"
},
{
"answer_id": 74410618,
"author": "Alex",
"author_id": 19933529,
"author_profile": "https://Stackoverflow.com/users/19933529",
"pm_score": 2,
"selected": false,
"text": "const sum = marks.reduce((partialSum, a) => partialSum + a, 0);\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74410506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19659837/"
] |
74,410,523 | <p>We have created a feedback form and once a user submits the feedback, we want to run the function that submits it to Airtable and then show the Next button.</p>
<p>Problem: The jQuery is working, showing the button after submit, but the function in (isset($_POST['submit']) isn't saving at all.</p>
<p>I've read through many posts but can't find the answer. Any help would be great!</p>
<p>Here is our current code</p>
<pre><code> public function airtable_function() {
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#nameFrm").submit(function (e) {
e.preventDefault();
var frm = jQuery('#nameFrm');
var outPut = jQuery('#results');
var loadButton = jQuery('#loadingImage');
var comments = jQuery('#comments').val();
var reason = jQuery('#reason').val();
jQuery.ajax({
type: 'POST',
data:'action=submitForm&comments='+comments+'&reason='+reason,
url: 'requests.php',
beforeSend: function(){
loadButton.show();
},
complete: function(data){
loadButton.show();
frm.hide();
},
success: function(data) {
frm.hide();
outPut.html(data);
}
});
});
});
</script>
<div>
<form action="requests.php" id="nameFrm" name="frmName" method="POST" >
<p>Please give us feedback</p>
<select id="reason" name="reason" required>
<option value="Choose a reason">Choose a reason</option>
<option value="Reason1">Reason1</option>
<option value="Reason2">Reason2</option>
<option value="Reason3">Reason2</option>
<option value="Other">Other</option>
</select>
<input id="comments" type='text' name='comments' required />
<input type="submit" value="submit" name="subbtn" >
</form>
<div id="loadingImage" style="display:none; text-align:center;">
<a href="#" class="button-primary">Yes, Cancel Account</a>
</div>
</div>
<div id="results"></div>
</div>
<?php
if (isset($_POST['submit'])){
$reason = $_POST['reason'];
$comments = $_POST['comments'];
save($reason, $comments);
}
?>
<?php
}
</code></pre>
| [
{
"answer_id": 74410638,
"author": "Sachin Bahukhandi",
"author_id": 5192105,
"author_profile": "https://Stackoverflow.com/users/5192105",
"pm_score": 0,
"selected": false,
"text": "if (isset($_POST['submit'])){\n"
},
{
"answer_id": 74411536,
"author": "rauwitt",
"author_id": 5458987,
"author_profile": "https://Stackoverflow.com/users/5458987",
"pm_score": 3,
"selected": true,
"text": "<?php\nfunction airtable_function() {\n ?>\n <script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js\"></script>\n <script type=\"text/javascript\">\n jQuery(document).ready(function(){ \n\n jQuery(\"#nameFrm\").submit(function (e) {\n e.preventDefault();\n var frm = jQuery('#nameFrm');\n var outPut = jQuery('#results');\n var loadButton = jQuery('#loadingImage');\n\n var comments = jQuery('#comments').val();\n var reason = jQuery('#reason').val();\n\n jQuery.ajax({\n type: 'get',\n data: { 'result' : comments +'*'+reason, 'feedback' : 'true' },\n url: 'requests.php',\n beforeSend: function(){ \n loadButton.show(); \n },\n complete: function(data){ \n loadButton.show();\n frm.hide();\n },\n success: function(data) { \n frm.hide();\n outPut.html(data);\n }\n });\n });\n\n });\n </script>\n <div> \n <form action=\"requests.php\" id=\"nameFrm\" name=\"frmName\" method=\"POST\" >\n <p>Please give us feedback</p>\n <select id=\"reason\" name=\"reason\" required>\n <option value=\"Choose a reason\">Choose a reason</option>\n <option value=\"Reason1\">Reason1</option>\n <option value=\"Reason2\">Reason2</option>\n <option value=\"Reason3\">Reason3</option>\n <option value=\"Other\">Other</option>\n </select>\n <input id=\"comments\" type='text' name='comments' required />\n <input type=\"submit\" value=\"submit\" name=\"subbtn\" >\n</form>\n<div id=\"loadingImage\" style=\"display:none; text-align:center;\">\n<a href=\"#\" class=\"button-primary\">Yes, Cancel Account</a>\n</div>\n</div>\n<div id=\"results\"></div> \n</div>\n<?php\n}\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74410523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16034511/"
] |
74,410,527 | <p>I'm trying to make simple function to adding elements to my array but it doesnt work well. can you help me?</p>
<pre><code>
void insert(int &n, string name[]){
cin>>n;
for (int i = 0; i < n; i++)
{
cin>>name[i];
}
}
int main(){
int n;
string name[n];
insert(n,name);
}
</code></pre>
| [
{
"answer_id": 74410649,
"author": "Cleiton Santoia Silva",
"author_id": 5605574,
"author_profile": "https://Stackoverflow.com/users/5605574",
"pm_score": 1,
"selected": false,
"text": "std::vector<int> v; // creates a vector \nv.push_back( 10 ); // include a number in a vector \n"
},
{
"answer_id": 74410777,
"author": "shy45",
"author_id": 20313707,
"author_profile": "https://Stackoverflow.com/users/20313707",
"pm_score": 0,
"selected": false,
"text": "#include <string>\n#include <vector>\n#include <iostream>\nusing namespace std;\n\nvoid insert(int& n, vector<string>& names) {\n cin >> n;\n names.resize(n);\n for (int i = 0; i < n; i++)\n {\n cin >> names[i];\n }\n}\n\nint main() {\n int n;\n vector<string> names;\n insert(n, names);\n for (const auto& s : names) {\n cout << s << endl;\n }\n}\n"
},
{
"answer_id": 74410842,
"author": "UnKn0wn",
"author_id": 20483429,
"author_profile": "https://Stackoverflow.com/users/20483429",
"pm_score": 0,
"selected": false,
"text": "void insert(string name[]){\n for (int i = 0; i < name.size(); i++)\n {\n cin>>name[i];\n }\n}\nint main(){\n int n;\n cin >> n;\n string name[n];\n insert(name);\n}\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74410527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20483219/"
] |
74,410,531 | <p>What should I do to get any vector of the list?</p>
<p>I use following code to do it currently:</p>
<pre><code>list<vector<T>> alist;
list<vector<T>>::iterator iter = alist.begin();
vector<T> vec(*iter);
</code></pre>
<p>is there any other way by which I don't need to copy the data?</p>
| [
{
"answer_id": 74410594,
"author": "bolov",
"author_id": 2805305,
"author_profile": "https://Stackoverflow.com/users/2805305",
"pm_score": 2,
"selected": false,
"text": "vector<T> vec = alist.front();\n"
},
{
"answer_id": 74410705,
"author": "shy45",
"author_id": 20313707,
"author_profile": "https://Stackoverflow.com/users/20313707",
"pm_score": 1,
"selected": true,
"text": " for (auto& v : alist) {\n for (auto& i : v) {\n i = 13;\n }\n }\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74410531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20077120/"
] |
74,410,547 | <p><a href="https://i.stack.imgur.com/ALJ43.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ALJ43.png" alt="enter image description here" /></a></p>
<p>I have a column of hours and minutes and I would like all values in the column to be in hours. So how do I divide only the columns values in minutes by 60 to get hours? I tried splitting the column by space to separate numbers and strings but I got stuck how to achieve the desire outcome.</p>
| [
{
"answer_id": 74410594,
"author": "bolov",
"author_id": 2805305,
"author_profile": "https://Stackoverflow.com/users/2805305",
"pm_score": 2,
"selected": false,
"text": "vector<T> vec = alist.front();\n"
},
{
"answer_id": 74410705,
"author": "shy45",
"author_id": 20313707,
"author_profile": "https://Stackoverflow.com/users/20313707",
"pm_score": 1,
"selected": true,
"text": " for (auto& v : alist) {\n for (auto& i : v) {\n i = 13;\n }\n }\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74410547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13724549/"
] |
74,410,559 | <p>I am facing an issue in that I cannot send calling Intent above android version 11 below android version 11 Calling Intent working correctly.</p>
<pre><code>Intent intent = new Intent(Intent.ACTION_DIAL);
//Demo number
intent.setData(Uri.parse("tel:" +"0000000000");
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
</code></pre>
| [
{
"answer_id": 74410594,
"author": "bolov",
"author_id": 2805305,
"author_profile": "https://Stackoverflow.com/users/2805305",
"pm_score": 2,
"selected": false,
"text": "vector<T> vec = alist.front();\n"
},
{
"answer_id": 74410705,
"author": "shy45",
"author_id": 20313707,
"author_profile": "https://Stackoverflow.com/users/20313707",
"pm_score": 1,
"selected": true,
"text": " for (auto& v : alist) {\n for (auto& i : v) {\n i = 13;\n }\n }\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74410559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20483233/"
] |
74,410,563 | <p>I have few text documents in a folder and would like to convert them to PDF Format. I am able to do it individually with the below code. Is there any way to select all the text files from a folder, convert and save them with the original name (as it was for text documents)? Below is the code I used to convert each file:</p>
<pre><code>
from fpdf import FPDF
pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial", size = 8)
f = open("C:\\Users\\rc06587\\Desktop\\Text Doc\\Sample\\New folder (2)\\exp_000004593_cn23rk__09042020000000_citrixsystemsinc_92080217mr_00384.TXT", "r")
for x in f:
pdf.cell(10, 4, txt = x, ln = 1, align = 'L')
pdf.output("exp_000004593_cn23rk__09042020000000_citrixsystemsinc_92080217mr_00384.TXT.pdf")
</code></pre>
| [
{
"answer_id": 74410594,
"author": "bolov",
"author_id": 2805305,
"author_profile": "https://Stackoverflow.com/users/2805305",
"pm_score": 2,
"selected": false,
"text": "vector<T> vec = alist.front();\n"
},
{
"answer_id": 74410705,
"author": "shy45",
"author_id": 20313707,
"author_profile": "https://Stackoverflow.com/users/20313707",
"pm_score": 1,
"selected": true,
"text": " for (auto& v : alist) {\n for (auto& i : v) {\n i = 13;\n }\n }\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74410563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13313647/"
] |
74,410,669 | <p>Column value is shown in the figure and I am trying to extract the date from the datetime column.</p>
<p><img src="https://i.stack.imgur.com/cVyvW.png" alt="enter image description here" /></p>
<p>I m trying to use the following command</p>
<pre><code>=QUERY(A:B, "Select A where B is not NULL '"&SPLIT(A2:A," ")&"'",1)
</code></pre>
| [
{
"answer_id": 74410594,
"author": "bolov",
"author_id": 2805305,
"author_profile": "https://Stackoverflow.com/users/2805305",
"pm_score": 2,
"selected": false,
"text": "vector<T> vec = alist.front();\n"
},
{
"answer_id": 74410705,
"author": "shy45",
"author_id": 20313707,
"author_profile": "https://Stackoverflow.com/users/20313707",
"pm_score": 1,
"selected": true,
"text": " for (auto& v : alist) {\n for (auto& i : v) {\n i = 13;\n }\n }\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74410669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19599725/"
] |
74,410,689 | <p>I am using AWS Amplify for a ReactJS application. The only two functional areas I am using from Amplify are Authentication and Hosting. These two are working fine, and a Cognito user pool associated with the project is working as expected, providing the logged in user to the React component after successful authentication.</p>
<p>My next step is to query other AWS resources outside of Amplify configuration, starting with an S3 bucket and a DynamoDB table. I am attempting to use AWS Client SDK for these, but am unable to figure out how to use the credentials of the currently logged in user.</p>
<p>I tried to use <code>fromWebToken</code> from <code>@aws-sdk/credentials-providers</code> but I do not have an Identity pool; I am using a Cognito user pool as only authenticated users have access to the web app. So I am stumped on how to proceed. My thought was that the current user credentials would automatically be used for any client request, but apparently it's not the case.</p>
<p>Here is the code I have; please note that this is only an attempt to show what I have tried, my question is quite simple: <b>How do I get the currently authenticated user's credentials for use with S3 and other AWS Client SDK components?</b></p>
<pre><code> // user is the currently logged in user. I can see the accessToken etc. here.
console.log(user.signInUserSession.accessToken);
const client = new S3Client({
region: "us-west-2", credentials: fromWebToken({
clientConfig: {region: "us-west-2"},
roleArn: "arn:aws:iam::...", // Got these from IAM for authenticated users
webIdentityToken: user.signInUserSession.accessToken.jwtToken
})
});
</code></pre>
<p>I try to use the client for downloading a file, but get the following error:</p>
<pre><code>const command = new GetObjectCommand({
Bucket: bucket,
Key: key,
});
const response = await client.send(command);
// Throws the error: No Cognito Identity pool provided for unauthenticated access
</code></pre>
<p>Any help is appreciated.</p>
| [
{
"answer_id": 74410594,
"author": "bolov",
"author_id": 2805305,
"author_profile": "https://Stackoverflow.com/users/2805305",
"pm_score": 2,
"selected": false,
"text": "vector<T> vec = alist.front();\n"
},
{
"answer_id": 74410705,
"author": "shy45",
"author_id": 20313707,
"author_profile": "https://Stackoverflow.com/users/20313707",
"pm_score": 1,
"selected": true,
"text": " for (auto& v : alist) {\n for (auto& i : v) {\n i = 13;\n }\n }\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74410689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4332644/"
] |
74,410,711 | <p>I am working in Reactjs and i am using nextjs,Right now i am trying to clear input field after click but not successful,Here is my code</p>
<pre><code><form onSubmit={handleSubmit}>
<input
type="text"
name="name"
id="name"
placeholder="Type your email here"
value={state.name}
onChange={handleChange}
/>
<button type="submit" className='btn-remindme'>Remind me </button></form>
</code></pre>
<p>And i tried with following code for clear input text</p>
<pre><code>const [state, setState] = useState({
name: "",
job: ""
});
const handleChange = (e) => {
//alert(`So your name is `);
const value = e.target.value;
setState({
...state,
[e.target.name]: value
});
};
const handleSubmit = (e) => {
$("#name").val("")
e.preventDefault();
const data = {
name: state.name,
email: state.job
};
axios.post('https://xxxxxxxxxxx/',data).then(function(response) {
console.log(response.data);
});
</code></pre>
| [
{
"answer_id": 74410594,
"author": "bolov",
"author_id": 2805305,
"author_profile": "https://Stackoverflow.com/users/2805305",
"pm_score": 2,
"selected": false,
"text": "vector<T> vec = alist.front();\n"
},
{
"answer_id": 74410705,
"author": "shy45",
"author_id": 20313707,
"author_profile": "https://Stackoverflow.com/users/20313707",
"pm_score": 1,
"selected": true,
"text": " for (auto& v : alist) {\n for (auto& i : v) {\n i = 13;\n }\n }\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74410711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5308126/"
] |
74,410,719 | <p>I am using the following code to search and highlight accented text. The problem I am facing is that it removes accented text while highlighting. Is there anyway to keep accents?</p>
<pre><code>echo highlightTerm("Would you like a café, Mister Kàpêk?", "kape caf");
function highlightTerm($text, $keyword) {
$text = iconv('utf-8', 'ISO-8859-1//IGNORE', Normalizer::normalize($text, Normalizer::FORM_D));
$words = explode(" ", $keyword);
$p = implode('|', array_map('preg_quote', $words));
return preg_replace(
"/($p)/ui",
'<span style="background:yellow;">$1</span>',
$text
);
}
</code></pre>
| [
{
"answer_id": 74413849,
"author": "ThW",
"author_id": 497139,
"author_profile": "https://Stackoverflow.com/users/497139",
"pm_score": 1,
"selected": false,
"text": "ext/intl"
},
{
"answer_id": 74416331,
"author": "mickmackusa",
"author_id": 2943403,
"author_profile": "https://Stackoverflow.com/users/2943403",
"pm_score": 1,
"selected": false,
"text": "preg_quote()"
},
{
"answer_id": 74416616,
"author": "mickmackusa",
"author_id": 2943403,
"author_profile": "https://Stackoverflow.com/users/2943403",
"pm_score": 1,
"selected": true,
"text": "define(\n 'ACCENT_MAP',\n [\n \"A\" => \"[AАĂǍĄÀÃÁÆÂÅǺĀא]\",\n \"B\" => \"[BБבÞ]\",\n \"C\" => \"[CĈĆÇЦצĊČץ]\",\n \"D\" => \"[DДĎĐדÐ]\",\n \"E\" => \"[EÈĘÉËÊЕĒĖĚĔЄƏע]\",\n \"F\" => \"[FФƑ]\",\n \"G\" => \"[GĞĠĢĜГגҐ]\",\n \"H\" => \"[HחĦХĤה]\",\n \"I\" => \"[IIÏÎÍÌĮĬIИĨǏיЇĪІ]\",\n \"J\" => \"[JЙĴ]\",\n \"K\" => \"[KĸכĶКך]\",\n \"L\" => \"[LŁĿЛĻĹĽל]\",\n \"M\" => \"[MמМם]\",\n \"N\" => \"[NÑŃНŅןŊנʼnŇ]\",\n \"O\" => \"[OØÓÒÔÕОŐŎŌǾǑƠ]\",\n \"P\" => \"[PפףП]\",\n \"Q\" => \"[Qק]\",\n \"R\" => \"[RŔŘŖרР]\",\n \"S\" => \"[SŞŚȘŠСŜס]\",\n \"T\" => \"[TТȚטŦתŤŢ]\",\n \"U\" => \"[UÙÛÚŪУŨƯǓŲŬŮŰǕǛǙǗ]\",\n \"V\" => \"[VВו]\",\n \"Y\" => \"[YÝЫŶŸ]\",\n \"Z\" => \"(?:Z|ŹŽŻЗז\",\n \"a\" => \"[aаăǎąàãáæâåǻāא]\",\n \"b\" => \"[bбבþ]\",\n \"c\" => \"[cĉćçцצċčץ]\",\n \"ch\" => \"(?:ch|ч)\",\n \"d\" => \"[dдďđדð]\",\n \"e\" => \"[eèęéëêеēėěĕєəע]\",\n \"f\" => \"[fфƒ]\",\n \"g\" => \"[gğġģĝгגґ]\",\n \"h\" => \"[hחħхĥה]\",\n \"i\" => \"[iiïîíìįĭıиĩǐיїīі]\",\n \"j\" => \"[jйĵ]\",\n \"k\" => \"[kĸכķкך]\",\n \"l\" => \"[lłŀлļĺľל]\",\n \"m\" => \"[mמмם]\",\n \"n\" => \"[nñńнņןŋנʼnň]\",\n \"o\" => \"[oøóòôõоőŏōǿǒơ]\",\n \"p\" => \"[pפףп]\",\n \"q\" => \"[qק]\",\n \"r\" => \"[rŕřŗרр]\",\n \"s\" => \"[sşśșšсŝס]\",\n \"t\" => \"[tтțטŧתťţ]\",\n \"u\" => \"[uùûúūуũưǔųŭůűǖǜǚǘ]\",\n \"v\" => \"[vвו]\",\n \"y\" => \"[yýыŷÿ]\",\n \"z\" => \"[zźžżзזſ]\",\n \"ae\" => \"(?:ae|[ÄǼäæǽ])\",\n \"ch\" => \"(?:ch|[Чч])\",\n \"ij\" => \"(?:ij|[ijIJ])\",\n \"ja\" => \"(?:ja|[яЯ])\",\n \"je\" => \"(?:je|[Ээ])\",\n \"jo\" => \"(?:jo|[ёЁ])\",\n \"ju\" => \"(?:ju|[юЮ])\",\n \"oe\" => \"(?:oe|[œŒöÖ])\",\n \"sch\" => \"(?:sch|[щЩ])\",\n \"sh\" => \"(?:sh|[шШ])\",\n \"ss\" => \"(?:ss|[ß])\",\n \"ue\" => \"(?:ue|[Ü)\",\n \"zh\" => \"(?:zh|[Жж])\"\n ]);\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74410719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/934820/"
] |
74,410,736 | <p>What does <code>ravel</code> stand for in <code>NumPy</code>?</p>
<p>Sometimes, it is a bit harder to remember a function name that the name has nothing to do with its description.</p>
| [
{
"answer_id": 74410774,
"author": "ScottC",
"author_id": 20174226,
"author_profile": "https://Stackoverflow.com/users/20174226",
"pm_score": 2,
"selected": false,
"text": "ravel"
},
{
"answer_id": 74410784,
"author": "hpaulj",
"author_id": 901925,
"author_profile": "https://Stackoverflow.com/users/901925",
"pm_score": 2,
"selected": false,
"text": "ravel"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74410736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1082883/"
] |
74,410,744 | <p>I have data on movies and all movies have IMDB score, however some do not have a meta critic score</p>
<p>Eg:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Name</th>
<th>IMDB Score</th>
<th>Meta Score</th>
</tr>
</thead>
<tbody>
<tr>
<td>B</td>
<td>8</td>
<td>86</td>
</tr>
<tr>
<td>C</td>
<td>8</td>
<td>90</td>
</tr>
<tr>
<td>D</td>
<td>8</td>
<td>null</td>
</tr>
<tr>
<td>E</td>
<td>8</td>
<td>91</td>
</tr>
<tr>
<td>F</td>
<td>7</td>
<td>66</td>
</tr>
<tr>
<td>G</td>
<td>3</td>
<td>44</td>
</tr>
</tbody>
</table>
</div>
<p>I want to fill in the null values in the meta critic score with the mean of the values of movies that have the same IMDB score
so the null value in this table should be replaced by the mean of movies B,C,E</p>
<p>How would I achieve this with Numpy / Pandas?</p>
<p>I looked up online and the closest solution I could find was averaging all the metacritic scores and replacing the null values with that Average.</p>
| [
{
"answer_id": 74410813,
"author": "Panda Kim",
"author_id": 20430449,
"author_profile": "https://Stackoverflow.com/users/20430449",
"pm_score": 2,
"selected": true,
"text": "groupby"
},
{
"answer_id": 74411149,
"author": "shishio",
"author_id": 20483641,
"author_profile": "https://Stackoverflow.com/users/20483641",
"pm_score": 0,
"selected": false,
"text": "df['Meta Score'] = df.groupby(['Name','IMDB Score'])['Meta Score'].ffill()\n"
},
{
"answer_id": 74411953,
"author": "atena karimi",
"author_id": 17682471,
"author_profile": "https://Stackoverflow.com/users/17682471",
"pm_score": 0,
"selected": false,
"text": "df.groupby('IMDB Score')['Meta Score'].transform(lambda value: value.fillna(value.mean()))\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74410744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20483416/"
] |
74,410,768 | <p>I am struggling to figure out a way to check if a is logged-in after the first launch of the app and then sending them to the MainStack which contains every screen after the AuthStack. I'm using FireBase for auth.</p>
<p>My Auth stack contains my signin, signup, and forgot password screen:</p>
<pre><code>export default function AuthStack() {
return (
<Stack.Navigator
initialRouteName="Login"
screenOptions={{
headerShown: false
}}>
<Stack.Screen name="Login" component={LoginScreen} />
<Stack.Screen name="ForgotPassword" component={ForgotPasswordScreen} />
<Stack.Screen name="Registration" component={RegistrationScreen} />
</Stack.Navigator>
);
}
</code></pre>
<p>This is my Main Stack, which is a drawer navigator:</p>
<pre><code>export default function MainStack() {
return (
<Drawer.Navigator
drawerContent={props => <CustomDrawer {...props} />}
initialRouteName="Home"
screenOptions={{
drawerActiveBackgroundColor: '#00BFFF',
drawerActiveTintColor: '#fff',
drawerInactiveTintColor: '#333',
headerTitleAlign: 'center',
headerTintColor: '#00BFFF',
drawerLabelStyle: {
marginLeft: -25,
fontSize: 15
},
}}>
<Drawer.Screen name="Home" component={HomeScreen} options={{
drawerIcon: ({ color }) => (
<Ionicons name="home-outline" size={22} color={color} />
)
}} />
<Drawer.Screen name='Calendar' component={CalendarScreen} options={{
drawerIcon: ({ color }) => (
<Ionicons name="calendar-outline" size={22} color={color} />
)
}} />
<Drawer.Screen name='Chat' component={ChatScreen} options={{
drawerIcon: ({ color }) => (
<Ionicons name="call-outline" size={22} color={color} />
)
}} />
<Drawer.Screen name='Goals' component={GoalsScreen} options={{
drawerIcon: ({ color }) => (
<Ionicons name="checkmark-circle-outline" size={22} color={color} />
)
}} />
<Drawer.Screen name='Journal' component={JournalScreen} options={{
drawerIcon: ({ color }) => (
<Ionicons name="journal-outline" size={22} color={color} />
)
}} />
<Drawer.Screen name='Resources' component={ResourcesScreen} options={{
drawerIcon: ({ color }) => (
<Ionicons name="search-outline" size={22} color={color} />
)
}} />
<Drawer.Screen name='User Profile' component={UserProfileScreen} options={{
drawerIcon: ({ color }) => (
<Ionicons name="person-outline" size={22} color={color} />
)
}} />
</Drawer.Navigator>
</code></pre>
<p>Lastly, here lies the issue. These are my routes, but I can't figure out how to send the user to the MainStack after they initially login. The last statement works perfectly fine, but the error is in the 'else if', I can't seem to incorporate authenticating the user and verifying if it's the first app launch at the same time.</p>
<pre><code>export default function Routes() {
const { user, setUser } = useContext(AuthContext);
const [loading, setLoading] = useState(true);
const [initializing, setInitializing] = useState(true);
const [isFirstLaunch, setIsFirstLaunch] = useState(null);
function onAuthStateChanged(user) {
setUser(user);
if (initializing) {
setInitializing(false);
}
setLoading(false);
}
useEffect(() => {
const subscriber = auth.onAuthStateChanged(onAuthStateChanged);
return subscriber;
}, []);
useEffect(() => {
AsyncStorage.getItem('alreadyLaunched').then(value => {
if (value === null) {
AsyncStorage.setItem('alreadyLaunched', 'true');
setIsFirstLaunch(true);
}
else {
setIsFirstLaunch(false);
}
})
}, []);
if (isFirstLaunch === null) {
return null;
}
else if (isFirstLaunch === true) {
return (
<NavigationContainer>
<Stack.Navigator
screenOptions={{
headerShown: false
}}>
<Stack.Screen name='OnBoarding' component={OnBoardingScreen} />
<Stack.Screen name="Login" component={LoginScreen} />
<Stack.Screen name="ForgotPassword" component={ForgotPasswordScreen} />
<Stack.Screen name="Registration" component={RegistrationScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
else {
return (
<NavigationContainer>
{user ? <MainStack /> : <AuthStack />}
</NavigationContainer>
)
}
</code></pre>
<p>Below is AuthProvider with firebase</p>
<pre><code>import React, { createContext, useState } from 'react';
import { auth } from '../firebase/firebase';
export const AuthContext = createContext({});
export const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null);
return (
<AuthContext.Provider
value={{
user,
setUser,
login: async (email, password) => {
try {
await auth.signInWithEmailAndPassword(email, password);
} catch (error) {
console.log(error);
}
},
register: async (email, password) => {
try {
await auth.createUserWithEmailAndPassword(email, password);
} catch (error) {
console.log(error);
}
},
logout: async () => {
try {
await auth.signOut();
} catch (error) {
console.log(error);
}
}
}}
>
{children}
</AuthContext.Provider>
)
}
</code></pre>
| [
{
"answer_id": 74410813,
"author": "Panda Kim",
"author_id": 20430449,
"author_profile": "https://Stackoverflow.com/users/20430449",
"pm_score": 2,
"selected": true,
"text": "groupby"
},
{
"answer_id": 74411149,
"author": "shishio",
"author_id": 20483641,
"author_profile": "https://Stackoverflow.com/users/20483641",
"pm_score": 0,
"selected": false,
"text": "df['Meta Score'] = df.groupby(['Name','IMDB Score'])['Meta Score'].ffill()\n"
},
{
"answer_id": 74411953,
"author": "atena karimi",
"author_id": 17682471,
"author_profile": "https://Stackoverflow.com/users/17682471",
"pm_score": 0,
"selected": false,
"text": "df.groupby('IMDB Score')['Meta Score'].transform(lambda value: value.fillna(value.mean()))\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74410768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18788036/"
] |
74,410,826 | <p>I have a table with 5 columns.</p>
<ol>
<li>id</li>
<li>bday</li>
<li>update</li>
<li>restartDate</li>
<li>startDate</li>
</ol>
<p>I need to update each rows update column with the most recent date between restartDate and startDate</p>
<p>I've tried:</p>
<pre><code>update mytable
set update = (select MAX(v)from (values (restartDate),(startDate)) as value(v))
</code></pre>
<p>But that seems to make the update column current date(like now())</p>
<p>I should also mention that the startDate and restartDate can be null</p>
<p>For example:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>restartDate</th>
<th>startDate</th>
<th>update</th>
</tr>
</thead>
<tbody>
<tr>
<td>2022-11-11</td>
<td>null</td>
<td>null</td>
</tr>
</tbody>
</table>
</div>
<p>would set update as 2022-11-11</p>
<p>or</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>restartDate</th>
<th>startDate</th>
<th>update</th>
</tr>
</thead>
<tbody>
<tr>
<td>2022-11-01</td>
<td>2022-11-05</td>
<td>null</td>
</tr>
</tbody>
</table>
</div>
<p>would set update as 2022-11-05</p>
<p>restartDate cannot be null</p>
| [
{
"answer_id": 74410989,
"author": "Slonsoid",
"author_id": 20474992,
"author_profile": "https://Stackoverflow.com/users/20474992",
"pm_score": 0,
"selected": false,
"text": "CASE"
},
{
"answer_id": 74411042,
"author": "Jonas Metzler",
"author_id": 18794826,
"author_profile": "https://Stackoverflow.com/users/18794826",
"pm_score": 2,
"selected": false,
"text": "GREATEST"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74410826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13986714/"
] |
74,410,838 | <p>I'm writing a code with js and outputting a string to a variable. I have sampled this variable below.</p>
<p><code>var ResultX = "SefaOODQWHCDCHDAJ=SefaNSADJHDDHQKSefaUQEOFQN==";</code></p>
<p>I need to separate this string based on what's between two words and add it to an array or list.
Like this:</p>
<p><code>var ResultY = ["SefaOODQWHCDCHDAJ=","SefaNSADJHDDHQK","SefaUQEOFQN=="];</code></p>
<p>Output:</p>
<pre><code>ResultY[0]=SefaOODQWHCDCHDAJ
ResultY[1]=SefaNSADJHDDHQK
ResultY[2]=SefaUQEOFQN==
</code></pre>
<p>The reason I'm doing this is because the string I have contains a few Base64 format images. I need to separate them properly so I can process them later.</p>
<p>Can you help with this?
Thank you.</p>
<p>I tried several split and replace methods but failed.</p>
| [
{
"answer_id": 74410860,
"author": "Alexander Mills",
"author_id": 1223975,
"author_profile": "https://Stackoverflow.com/users/1223975",
"pm_score": 0,
"selected": false,
"text": "var ResultY = [s.slice(0,x),s.slice(x,y),s.slice(y)];\n"
},
{
"answer_id": 74410867,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 3,
"selected": true,
"text": "match()"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74410838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20266326/"
] |
74,410,850 | <p>A lot of the times when I code lets say I have only one cin>> I run my code it compiles but I can do infinite inputs even though in my code I have one input. What is the reason for this?</p>
<p>I checked for infinity loops found none for the specific test case I was working with.</p>
<p>Here's the code if you want to see.</p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
using namespace std;
int main()
{
long long a,b,c;
cin >> a >> b >> c;
long long mx,mn;
if(b >= a)
{
b = mx;
a = mn;
}
if(a > b)
{
a = mx;
b = mn;
}
int x;
int r = c;
for(int i = mn; i <= mx; i++)
{
x = i;
if(x - mn == mx - x)
{
for(int j = 0; j < x; j++)
{
c += r * r;
}
cout << c + (mx - mn);
return 0;
}
}
}
</code></pre>
| [
{
"answer_id": 74410860,
"author": "Alexander Mills",
"author_id": 1223975,
"author_profile": "https://Stackoverflow.com/users/1223975",
"pm_score": 0,
"selected": false,
"text": "var ResultY = [s.slice(0,x),s.slice(x,y),s.slice(y)];\n"
},
{
"answer_id": 74410867,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 3,
"selected": true,
"text": "match()"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74410850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20256879/"
] |
74,410,863 | <p>How do I convert the values of <code>Years_in_service</code> to its corresponding decimal/float values ?</p>
<p>For example, <code>'5 year(s), 7 month(s), 3 day(s)'</code> has a decimal value of <code>5.59</code></p>
<pre><code>import pandas as pd
import numpy as np
data = {'ID':['A1001','A5001','B1001','D5115','K4910'],
'Years_in_service': ['5 year(s), 7 month(s), 3 day(s)', '16 year(s), 0 month(s), 25 day(s)',
'7 year(s), 0 month(s), 2 day(s)', '0 year(s), 11 month(s), 23 day(s)','1 year(s), 0 month(s), 6 day(s)'],
'Age': [45, 59,21,18,35]}
df = pd.DataFrame(data)
df
</code></pre>
<p>Currently I'm able to extract only the year (See my attempt below)</p>
<pre><code>df['Years_in_service'].str[:2].astype(float)
</code></pre>
<p>Please show your full code, Thanks for your attempt.</p>
| [
{
"answer_id": 74410919,
"author": "Vin",
"author_id": 7955271,
"author_profile": "https://Stackoverflow.com/users/7955271",
"pm_score": 2,
"selected": false,
"text": "import pandas as pd \nimport numpy as np\n\ndata = {'ID':['A1001','A5001','B1001','D5115','K4910'],\n'Years_in_service': ['5 year(s), 7 month(s), 3 day(s)', '16 year(s), 0 month(s), 25 day(s)', \n'7 year(s), 0 month(s), 2 day(s)', '0 year(s), 11 month(s), 23 day(s)','1 year(s), 0 month(s), 6 day(s)'],\n 'Age': [45, 59,21,18,35]}\n\ndf = pd.DataFrame(data) \n"
},
{
"answer_id": 74411007,
"author": "YOLO",
"author_id": 9299259,
"author_profile": "https://Stackoverflow.com/users/9299259",
"pm_score": 3,
"selected": true,
"text": "def convert_dates(y,m,d):\n return round(int(y) + int(m)/12 + int(d)/365.25, 2)\n \n\ndf['date_float'] = df['Years_in_service'].apply(lambda x: convert_dates(*[int(i) for i in x.split(' ') if i.isnumeric()]))\n\nprint(df)\n\n ID Years_in_service Age date_float\n0 A1001 5 year(s), 7 month(s), 3 day(s) 45 5.59\n1 A5001 16 year(s), 0 month(s), 25 day(s) 59 16.07\n2 B1001 7 year(s), 0 month(s), 2 day(s) 21 7.01\n3 D5115 0 year(s), 11 month(s), 23 day(s) 18 0.98\n4 K4910 1 year(s), 0 month(s), 6 day(s) 35 1.02\n"
},
{
"answer_id": 74411538,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 1,
"selected": false,
"text": "extractall"
},
{
"answer_id": 74411909,
"author": "atena karimi",
"author_id": 17682471,
"author_profile": "https://Stackoverflow.com/users/17682471",
"pm_score": -1,
"selected": false,
"text": "i=1\nfor name in ['month','day']:\n df[name] = [date.split(',')[i].split(' ')[1] for date in df['Years_in_service']]\n df[name]=df[name].astype('float64')\n i+=1\ndf['years']=[date.split(',')[0].split(' ')[0] for date in df['Years_in_service']] \ndf['years'] = df['years'].astype('float64')\n\ni=12\nfor name in ['month','day']:\n df[name] = [x/i for x in df[name]]\n i=365.25\nl=[]\nfor i in range(len(df.index)):\n l.append(round((df.iloc[i,3]+df.iloc[i,4]+df.iloc[i,5]),2))\ndf['decimal_date'] =l \n \n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74410863",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14271017/"
] |
74,410,884 | <p>How to video streaming using customtkinter library in class method form ?
i was troubling to configure how to that, i see many examples but i dont know how to implement this on my code</p>
<pre><code># code for video streaming
def camera(self):
ret, img = cap.read()
cv2image= cv2.cvtColor(cap.read()[1],cv2.COLOR_BGR2RGB)
img = Image.fromarray(cv2image)
ImgTks = ImageTk.PhotoImage(image=img)
self.camera.imgtk = ImgTks
self.camera.configure(image=ImgTks)
self.after(20,self.camera)
if __name__ == "__main__":
app = TimeIn()
app.camera()
app.mainloop()
</code></pre>
<p>this is my whole code for this
<a href="https://github.com/Fsociety-Mrn/videostreamingCutsomkinter" rel="nofollow noreferrer">https://github.com/Fsociety-Mrn/videostreamingCutsomkinter</a></p>
<p>please do help me i am new to this</p>
| [
{
"answer_id": 74431559,
"author": "nothing",
"author_id": 17169484,
"author_profile": "https://Stackoverflow.com/users/17169484",
"pm_score": 1,
"selected": false,
"text": "import tkinter as tk\nfrom tkinter_webcam import webcam\n \nwindow = tk.Tk() # Sets up GUI\nwindow.title(\"Example\") # Titles GUI\nwindow.geometry(\"1000x1000\") # Sizes GUI\n \n# Uses Box class from webcam to create video window\nvideo = webcam.Box(window, width=450, height=450)\nvideo.show_frames() # Show the created Box\n \ntk.mainloop()\n"
},
{
"answer_id": 74440426,
"author": "acw1668",
"author_id": 5317403,
"author_profile": "https://Stackoverflow.com/users/5317403",
"pm_score": 2,
"selected": false,
"text": "camera"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74410884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18549873/"
] |
74,410,900 | <p>I am sending an object as params. But when I try to access the params in another screen. It says undefined.</p>
<p>Screen 1:</p>
<pre><code><TouchableOpacity
onPress={() => {
navigation.navigate('DraggableList', {
routes: ['A', 'B', 'C'],
name: 'ABCD',
});
}}
</TouchableOpacity>
</code></pre>
<p>Screen 2:</p>
<pre><code> console.log('Props==============>', props.route.params);
</code></pre>
<p>Output:</p>
<p><a href="https://i.stack.imgur.com/1TfAQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1TfAQ.png" alt="Output of the above image" /></a></p>
<p>But when I try to access the variables of the object:</p>
<p><code>Screen 2: </code></p>
<pre><code> console.log('Props==============>', props.route.params.name);
</code></pre>
<p>Output:
<a href="https://i.stack.imgur.com/qD18S.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qD18S.png" alt="Output of the above code" /></a></p>
| [
{
"answer_id": 74431559,
"author": "nothing",
"author_id": 17169484,
"author_profile": "https://Stackoverflow.com/users/17169484",
"pm_score": 1,
"selected": false,
"text": "import tkinter as tk\nfrom tkinter_webcam import webcam\n \nwindow = tk.Tk() # Sets up GUI\nwindow.title(\"Example\") # Titles GUI\nwindow.geometry(\"1000x1000\") # Sizes GUI\n \n# Uses Box class from webcam to create video window\nvideo = webcam.Box(window, width=450, height=450)\nvideo.show_frames() # Show the created Box\n \ntk.mainloop()\n"
},
{
"answer_id": 74440426,
"author": "acw1668",
"author_id": 5317403,
"author_profile": "https://Stackoverflow.com/users/5317403",
"pm_score": 2,
"selected": false,
"text": "camera"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74410900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19533892/"
] |
74,410,922 | <p>I'm trying to write a program for my homework:</p>
<p>Write a program to determine how much to tip the server in a restaurant. The tip should be 15% of the check, with a minimum of $2.</p>
<p>The hint said to use an if statement, but i keep running into a alot of errors.</p>
<p>I don't know how else to write it, I've been trying to figure it out for a couple of hours now and haven't found proper answers online...</p>
<pre><code>Check = 59
Tip = (Check)*(0.15)
if Tip > 2:
print(Tip)
</code></pre>
| [
{
"answer_id": 74411053,
"author": "Jamiu Shaibu",
"author_id": 19290081,
"author_profile": "https://Stackoverflow.com/users/19290081",
"pm_score": 1,
"selected": false,
"text": "if"
},
{
"answer_id": 74411088,
"author": "Vin",
"author_id": 7955271,
"author_profile": "https://Stackoverflow.com/users/7955271",
"pm_score": 1,
"selected": true,
"text": "check = 59\nif check > 2:\n tip = 0.15*check\n"
},
{
"answer_id": 74411134,
"author": "Marin Nagy",
"author_id": 14253533,
"author_profile": "https://Stackoverflow.com/users/14253533",
"pm_score": 0,
"selected": false,
"text": "tip = 2"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74410922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20482987/"
] |
74,410,974 | <p>This is the structure of my code:</p>
<pre class="lang-dart prettyprint-override"><code>class SomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Column(
Widget1(), // How to pass `FooPageState` to this widget?
Widget2(),
);
}
}
class Widget2 extends StatefulWidget {
@override
State<Widget2> createState() => _Widget2State();
}
class _Widget2State extends State<Widget2> {
final GlobalKey<FooPageState> _globalKey = GlobalKey();
@override
Widget build(BuildContext context) {
return Column(
InnerWidget1(),
FooPage(
key: _globalKey,
),
InnerWidget2(
pageState: _globalKey.currentState, // Passing `FooPageState`
),
);
}
}
</code></pre>
<p>I need to pass <code>FooPageState</code> to <code>Widget1</code>, how can I do that? <code>FooPage</code> is just a regular <code>StatefulWidget</code> whose state is <code>FooPageState</code>.</p>
<p><strong>Some workarounds:</strong></p>
<ol>
<li><p>Declare the <code>_globalKey</code> in the <code>SomePage</code> and pass it to both <code>Widget1</code> and <code>Widget2</code>.</p>
</li>
<li><p>Convert <code>SomePage</code> to <code>StatefulWidget</code>, define a callback in it, pass it to <code>Widget2</code> and then in a method like <code>SchedulerBinding.instance.addPostFrameCallback</code>, invoke the passed callback, which can in turn call the defined <code>_SomePageState</code> callback with <code>setState</code> and pass the <code>FooPageState</code> to <code>Widget1</code>. The same thing can also be done using a <code>Notification</code> and <code>NotificationListener</code>.</p>
</li>
</ol>
| [
{
"answer_id": 74442219,
"author": "张海标",
"author_id": 13832791,
"author_profile": "https://Stackoverflow.com/users/13832791",
"pm_score": 0,
"selected": false,
"text": "class SomePage extends StatelessWidget {\n final GlobalKey<FooPageState> _globalKey = GlobalKey();\n\n @override\n Widget build(BuildContext context) {\n return Column(\n Widget1(),\n Widget2(globalKey: _globalKey), // How to get `FooPageState` here?\n );\n }\n}\n\nclass Widget2 extends StatefulWidget {\n final GlobalKey<FooPageState> globalKey;\n const Widget2({Key key, this.globalKey}) : super(key: key);\n\n @override\n State<Widget2> createState() => _Widget2State();\n}\n\nclass _Widget2State extends State<Widget2> {\n @override\n Widget build(BuildContext context) {\n return Column(\n InnerWidget1(),\n FooPage(\n key: widget.globalKey,\n ),\n InnerWidget2(\n pageState: widget.globalKey.currentState, // Passing `FooPageState`\n ),\n );\n }\n}\n"
},
{
"answer_id": 74442938,
"author": "Leskeboy",
"author_id": 16896481,
"author_profile": "https://Stackoverflow.com/users/16896481",
"pm_score": 0,
"selected": false,
"text": "class your_class_name extends State<your_state_widget> {}\n"
},
{
"answer_id": 74465940,
"author": "offworldwelcome",
"author_id": 11760076,
"author_profile": "https://Stackoverflow.com/users/11760076",
"pm_score": 1,
"selected": false,
"text": "InheritedWidget"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74410974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12483095/"
] |
74,411,004 | <p>I want to call this terminal command on macOS in python <code>lsappinfo info -only name <code>lsappinfo front</code></code>. It returns the name of the <a href="https://stackoverflow.com/questions/24515436/how-to-get-current-foreground-applications-name-or-pid-in-os-x">current foreground application</a>.</p>
<p>Here is how I understand the command:</p>
<ul>
<li><p><code>lsappinfo</code> return information about running apps</p>
</li>
<li><p><code>info</code> allows to select specific data</p>
</li>
<li><p><code><code>lsappinfo front</code></code> select the foreground process</p>
</li>
<li><p><code>name</code> select
the name of the process only</p>
</li>
</ul>
<p>And here is my current code:</p>
<pre><code>import subprocess
sub = subprocess.Popen(['lsappinfo', 'info', '-only', 'name', '`lsappinfo front`'])
out, err = sub.communicate()
print(err)
print(out)
</code></pre>
<p>But I get:</p>
<pre><code>>>> None
>>> None
</code></pre>
<p>The expected output of the command is</p>
<pre><code>"LSDisplayName"="AppName"
</code></pre>
<p>I succeed using <code>os.system()</code> but I want to achieve it with <code>subprocess</code> since it's the recommended way and I want to store the output. Does someone know how to do it?</p>
| [
{
"answer_id": 74411104,
"author": "Carlos Rojas",
"author_id": 19934610,
"author_profile": "https://Stackoverflow.com/users/19934610",
"pm_score": 0,
"selected": false,
"text": "[\"./{myscript}.sh\"]"
},
{
"answer_id": 74411253,
"author": "Remzinho",
"author_id": 2484591,
"author_profile": "https://Stackoverflow.com/users/2484591",
"pm_score": 3,
"selected": true,
"text": "cmd1 = ['lsappinfo', 'front']\nname = subprocess.run(cmd1, shell=False, capture_output=True).stdout.decode('utf-8').strip(\"\\n\")\ncmd2 = ['lsappinfo', 'info', '-only', \"name\", name]\nout2 = subprocess.run(cmd2, shell=False, capture_output=True)\nprint(out2.stdout.decode('utf-8').strip(\"\\n\"))\n"
},
{
"answer_id": 74411823,
"author": "Mark Setchell",
"author_id": 2836621,
"author_profile": "https://Stackoverflow.com/users/2836621",
"pm_score": 0,
"selected": false,
"text": "lsappinfo info -only name $(lsappinfo front)\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14253533/"
] |
74,411,023 | <pre><code>print("please enter your 5 marks below")
#read 5 inputs
mark1 = int(input("enter mark 1: "))
mark2 = int(input("enter mark 2: "))
mark3 = int(input("enter mark 3: "))
mark4 = int(input("enter mark 4: "))
mark5 = int(input("enter mark 5: "))
#create array/list with five marks
marksList = [mark1, mark2, mark3, mark4, mark5]
#print the array/list
print(marksList)
#calculate the sum and average
sumOfMarks = sum(marksList)
averageOfMarks = sum(marksList)/5
#display results
print("The sum of your marks is: "+str(sumOfMarks))
print("The average of your marks is: "+str(averageOfMarks))
</code></pre>
<p>Couldn't really come up with anything</p>
<p>The assessment has the following guidelines.</p>
<p>Ask the user to input the marks for the five subjects in a list/array.</p>
<p>The program must ensure that the marks are between 0 and 100</p>
<p>Display the list/array of marks entered.</p>
<p>Find the sum of all the marks in the list (all five subjects) and display the output as:</p>
<p>The sum of your marks is: [sum]</p>
<p>Find the average of all the marks in the list (all five subjects) and display the output as:</p>
<p>The average of your marks is: [average mark]</p>
| [
{
"answer_id": 74411104,
"author": "Carlos Rojas",
"author_id": 19934610,
"author_profile": "https://Stackoverflow.com/users/19934610",
"pm_score": 0,
"selected": false,
"text": "[\"./{myscript}.sh\"]"
},
{
"answer_id": 74411253,
"author": "Remzinho",
"author_id": 2484591,
"author_profile": "https://Stackoverflow.com/users/2484591",
"pm_score": 3,
"selected": true,
"text": "cmd1 = ['lsappinfo', 'front']\nname = subprocess.run(cmd1, shell=False, capture_output=True).stdout.decode('utf-8').strip(\"\\n\")\ncmd2 = ['lsappinfo', 'info', '-only', \"name\", name]\nout2 = subprocess.run(cmd2, shell=False, capture_output=True)\nprint(out2.stdout.decode('utf-8').strip(\"\\n\"))\n"
},
{
"answer_id": 74411823,
"author": "Mark Setchell",
"author_id": 2836621,
"author_profile": "https://Stackoverflow.com/users/2836621",
"pm_score": 0,
"selected": false,
"text": "lsappinfo info -only name $(lsappinfo front)\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20336477/"
] |
74,411,037 | <p>I have a function like this</p>
<pre class="lang-rust prettyprint-override"><code>fn get_html(address: &str) -> String {
let mut response = reqwest::blocking::get(
address,
);
response = response.unwrap_or_else(|_e| {String::from("")});
response = response.text().unwrap_or_else(|_e| {String::from("")});
return response
}
</code></pre>
<p>Where I'm checking for html content. I would like to return an empty <code>String</code> if any kind of an error occurs somewhere in this function.
I'm not sure how to deal with this because <code>unwrap_or_else</code> expecting <code>Result</code> not <code>String</code>.</p>
| [
{
"answer_id": 74411103,
"author": "Mario Santini",
"author_id": 6452829,
"author_profile": "https://Stackoverflow.com/users/6452829",
"pm_score": 3,
"selected": true,
"text": "reqwest::blocking::get()"
},
{
"answer_id": 74411358,
"author": "jthulhu",
"author_id": 5956261,
"author_profile": "https://Stackoverflow.com/users/5956261",
"pm_score": 0,
"selected": false,
"text": "get_html"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19334148/"
] |
74,411,052 | <p>I have 3 textboxes in which I write numbers and last one in which is the result. If I write numbers in TextBoxA and TextBoxB instead of adding them together after I press equal button then it put them next to each other.</p>
<p>[<img src="https://i.stack.imgur.com/H8Kdv.png" alt="It look like this" />]</p>
<p>I tried this code:</p>
<pre><code> private void EqualsButton_Click(object sender, EventArgs e)
{
OutputTextBox.Text = ($"{InputTextBoxA.Text + InputTextBoxB.Text}");
}
</code></pre>
| [
{
"answer_id": 74411090,
"author": "masoud rafiee",
"author_id": 4256602,
"author_profile": "https://Stackoverflow.com/users/4256602",
"pm_score": 0,
"selected": false,
"text": "private void EqualsButton_Click(object sender, EventArgs e)\n{\n var resultA=0;\n var resultB=0;\n if(!string.IsNullOrEmpty(InputTextBoxA.Text))\n resultA=Convert.ToInt32(InputTextBoxA.Text);\n if(!string.IsNullOrEmpty(InputTextBoxB.Text))\n resultB=Convert.ToInt32(InputTextBoxB.Text);\n OutputTextBox.Text = resultA+ resultB ;\n}\n"
},
{
"answer_id": 74411096,
"author": "Slonsoid",
"author_id": 20474992,
"author_profile": "https://Stackoverflow.com/users/20474992",
"pm_score": -1,
"selected": false,
"text": "\"\""
},
{
"answer_id": 74411114,
"author": "thisisnabi",
"author_id": 2011837,
"author_profile": "https://Stackoverflow.com/users/2011837",
"pm_score": 1,
"selected": false,
"text": " private void EqualsButton2_Click(object sender, EventArgs e)\n {\n int numberA = int.Parse(textBox1.Text.Trim());\n int numberB = int.Parse(textBox2.Text.Trim());\n\n var result = numberA + numberB;\n\n textBox3.Text = result.ToString();\n }\n"
},
{
"answer_id": 74411139,
"author": "T.S.",
"author_id": 1704458,
"author_profile": "https://Stackoverflow.com/users/1704458",
"pm_score": 1,
"selected": true,
"text": "txtResult.Text = string.Empty;\n\nif (!decimal.TryParse(txt1.Text.Trim(), out decimal v1))\n{\n MessageBox.Show(\"Bad value in txt1\");\n return;\n}\nif (!decimal.TryParse(txt2.Text.Trim(), out decimal v2))\n{\n MessageBox.Show(\"Bad value in txt2\");\n return;\n}\n\ntxtResult.Text = (v1 + v2).ToString();\n\n"
},
{
"answer_id": 74411387,
"author": "Pradeep Kumar",
"author_id": 18704952,
"author_profile": "https://Stackoverflow.com/users/18704952",
"pm_score": 0,
"selected": false,
"text": " private void EqualsButton_Click(object sender, EventArgs e)\n {\n try\n {\n OutputTextBox.Text = ($\"{ Convert.ToInt32(InputTextBoxA.Text.Trim() == \"\" ? \"0\" : InputTextBoxA.Text) + Convert.ToInt32(InputTextBoxB.Text.Trim() == \"\" ? \"0\" : InputTextBoxB.Text)}\");\n }\n catch(exception ex)\n {\n MessageBox.Show(\"Enter Valid number\")'\n }\n }\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20355376/"
] |
74,411,058 | <p>I'm not precisely sure about what causes this error in my code but I guess it's the poor approach of addressing a parameter in the <strong>resualtValues</strong> function. ** thank u all in advance.**</p>
<pre><code> const calculator = {
sum:[],
subtraction:[],
multiplication:[],
division:[],
sumValues:function(num1,num2){
this.sum.push({
num1: num1,
num2: num2,
})
},
subtractionValues:function(num1,num2){
this.subtraction.push({
num1: num1,
num2: num2,
})
},
multiplyValues:function(num1,num2){
this.multiplication.push({
num1: num1,
num2: num2,
})
},
divisionValues:function(num1,num2){
this.division.push({
num1: num1,
num2: num2,
})
},
resualtValues: function(){
return this.sum.forEach(function(item){
return item.num1 + item.num2
})
}
}
calculator.sumValues(25,4)
calculator.subtractionValues(20,5)
calculator.multiplyValues(5,6)
calculator.divisionValues(45,5)
console.log(calculator.resualtValues())
</code></pre>
<p>I wanted to define some functions so when I call them they pass the given parameters to the arrays that inhabited in calculator object so that the <strong>resualtValues</strong> function use these parameters and operate four basic math operations.</p>
| [
{
"answer_id": 74411142,
"author": "Javaid",
"author_id": 11674006,
"author_profile": "https://Stackoverflow.com/users/11674006",
"pm_score": 2,
"selected": false,
"text": "const calculator = {\n sum: [],\n subtraction: [],\n multiplication: [],\n division: [],\n\n sumValues: function (num1, num2) {\n this.sum.push({\n num1: num1,\n num2: num2,\n });\n },\n subtractionValues: function (num1, num2) {\n this.subtraction.push({\n num1: num1,\n num2: num2,\n });\n },\n multiplyValues: function (num1, num2) {\n this.multiplication.push({\n num1: num1,\n num2: num2,\n });\n },\n divisionValues: function (num1, num2) {\n this.division.push({\n num1: num1,\n num2: num2,\n });\n },\n resualtValues: function () {\n let result = [];\n // **Sum Operation**\n this.sum.forEach(function (item) {\n result.push(item.num1 + item.num2);\n });\n // **Sub Operation**\n this.subtraction.forEach(function (item) {\n result.push(item.num1 - item.num2);\n });\n // **Mul Operation**\n this.multiplication.forEach(function (item) {\n result.push(item.num1 * item.num2);\n });\n // **Div Operation**\n this.division.forEach(function (item) {\n result.push(item.num1 / item.num2);\n });\n return result\n },\n };\n\n calculator.sumValues(25, 4);\n calculator.subtractionValues(20, 5);\n calculator.multiplyValues(5, 6);\n calculator.divisionValues(45, 5);\n console.log(calculator.resualtValues());\n"
},
{
"answer_id": 74411189,
"author": "Carsten Massmann",
"author_id": 2610061,
"author_profile": "https://Stackoverflow.com/users/2610061",
"pm_score": 1,
"selected": false,
"text": "console.log(\n {sum:[25+4],\n subtraction:[20-5],\n multiplication:[5*6],\n division:[45/5]}\n);"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20483554/"
] |
74,411,078 | <p>I have a problem where I want to <a href="https://www.interviewbit.com/blog/longest-common-prefix/" rel="nofollow noreferrer">find the longest common prefix of N strings given in an array</a>.</p>
<p>Below is a perfectly working code:</p>
<pre><code>def longestCommonPrefix(S) :
if (len(S) == 0):
return ""
for i in range(len(S[0])):
c = S[0][i]
for j in range(len(S)):
if (i == len(S[j]) or S[j][i] != c):
return S[0][0:i];
return S[0]
X = ["Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt anim id est laborum.",
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod td exercitation ullamcon reprehenderit int occaecat cupidatat nonmollit anim id est laborum.",
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, ccaecat cupidatat nonmollit anim id est laborum.",
"Lorem ipsum dolor sit amet, consectetur adrit int occaecat cupidatat nonmollit anim id est laborum."]
print(longestCommonPrefix(X))
>> 'Lorem ipsum dolor sit amet, consectetur ad'
</code></pre>
<p><strong>PROBLEM</strong>: When I have my text array as:</p>
<pre><code>X = [
'Class- VII-CBSE-Mathematics\\nIntegers\ne EMBIBE\nThe temperature at Srinagar \\( =-2^{\\circ} \\mathrm{C} \\)\nTherefore, the difference \\( =-2^{\\circ} \\mathrm{C}-\\left(-8^{\\circ} \\mathrm{C}\\right) \\) \\( =6^{\\circ} \\mathrm{C} \\)\n(d) The temperature of Srinagar and Shimla taken together \\( =-2^{\\circ} \\mathrm{C}+5^{\\circ} \\mathrm{C} \\) \\( =3^{\\circ} \\mathrm{C} \\)\nThe temperature at Shimla \\( =5^{\\circ} \\mathrm{C}>3^{\\circ} \\mathrm{C} \\). Therefore the temperature of Srinagar and Shimla taken together is less than that of Shimla.\n\nThe temperature at Srinagar \\( =-2^{\\circ} \\mathrm{C}<3^{\\circ} \\mathrm{C} \\). Therefore, the temperature of Srinagar and Shimla taken together is not less than that of Srinagar',
'Class- VII-CBSE-Mathematics\\nIntegers\ne EMBIBE\nSubmarine floating below the sea level \\( =1200 \\mathrm{~m} \\)\nTherefore, the vertical distance between them \\( =5000+1200 \\)\n\\[\n=6200 \\mathrm{~m}\n\\]',
'Class- VII-CBSE-Mathematics\\nIntegers\ne EMBIBE\n\\begin{tabular}{|c|c|c|}\n\\hline\\( -4 \\) & \\( -3 \\) & \\( -2 \\) \\\\\n\\hline\\( -6 \\) & 4 & \\( -7 \\) \\\\\n\\hline\n\\end{tabular}', '\n(i) Sum of the rows:\n\\[\n\\begin{array}{l}\n5+-1+-4=0 \\\\\n-5+-2+7=0 \\\\\n0+3+-3=0\n\\end{array}\n\\]\nSum of the columns:\n\\[\n\\begin{array}{l}\n5+-5+0=0 \\\\\n-1+-2+3=0 \\\\\n-4+7+-3=0\n\\end{array}\n\\]\nSum of the diagonals:\n\\[\n\\begin{array}{l}\n5+-2+-3=0 \\\\\n-4+-2+0=-6\n\\end{array}\n\\]\nThus, this is not a magic square because all the sums are not equal\n(ii) Sum of the rows:\n\\[\n\\begin{array}{l}\n1+-10+0=-9 \\\\\n-4+-3+-2=-9 \\\\\n-6+4+-7=-9\n\\end{array}\n\\]\nSum of the columns:\n\\[\n\\begin{array}{l}\n1+-4+-6=-9 \\\\\n-10+-3+4=-9 \\\\\n0+-2+-7=-9\n\\end{array}\n\\]\nSum of the diagonals:\n\\[\n\\begin{array}{l}\n1+-3+-7=0 \\\\\n0+-3+-6=-9\n\\end{array}\n\\]\nThus, this is a magic square because all the sums are equal',
'Class- VII-CBSE-Mathematics\\nIntegers\ne EMBIBE\n(ii) \\( a=118, b=125 \\)\n(iii) \\( \\mathrm{a}=75, \\mathrm{~b}=84 \\)\n(iv) \\( a=28, b=11 \\)', '\n\\[\n\\begin{array}{l}\n\\text { LHS } a-(-b)=21-(-18)=39 \\\\\n\\text { RHS } a+b=21+18=39 \\\\\n\\mathrm{LHS}=\\text { RHS }\n\\end{array}\n\\]\nThus verified\n\\[\n\\begin{array}{l}\n\\operatorname{LHS~} a-(-b)=118-(-125)=243 \\\\\n\\text { RHS a }+b=118+125=243 \\\\\n\\mathrm{LHS}=\\text { RHS }\n\\end{array}\n\\]\nThus verified\n\\[\n\\begin{array}{l}\n\\operatorname{LHS~} a-(-b)=75-(-84)=159 \\\\\n\\text { RHS } a+b=75+84=159 \\\\\n\\text { LHS }=\\text { RHS }\n\\end{array}\n\\]\nThus verified\n\\[\n\\begin{array}{l}\n\\operatorname{LHS~} a-(-b)=28-(-11)=39 \\\\\n\\text { RHS } a+b=28+11=39\n\\end{array}\n\\]\n\\[\n\\mathrm{LHS}=\\mathrm{RHS}\n\\]\nThus verified',
'Class- VII-CBSE-Mathematics\\nIntegers\ne EMBIBE\n(c) \\( -7>-29 \\)\n(d) \\( 0<20 \\)\n(e) \\( -101>-159 \\)',
]
</code></pre>
<p>I get the result as <code>''</code> EMPTY string. Can someone please help me with it.</p>
<p>given on the suggestion for the below answer, I also did:</p>
<pre><code>def replace(x):
for i in ["\\","\n","\t",'\"',"\'","\b","\f","\r"]:
x = x.replace(i,"`")
return x
X = [replace(i) for i in X]
</code></pre>
<p>I have also tried doing <code>X = [repr(i) for i in X]</code></p>
<p>But still I get the same <code>""</code> answer.</p>
| [
{
"answer_id": 74411157,
"author": "IreiterateU",
"author_id": 20483908,
"author_profile": "https://Stackoverflow.com/users/20483908",
"pm_score": 0,
"selected": false,
"text": "\\n"
},
{
"answer_id": 74411306,
"author": "Cobra",
"author_id": 17580381,
"author_profile": "https://Stackoverflow.com/users/17580381",
"pm_score": 1,
"selected": false,
"text": "X = [\n 'Class- VII-CBSE-Mathematics\\\\nIntegers\\ne EMBIBE\\nThe temperature at Srinagar \\\\( =-2^{\\\\circ} \\\\mathrm{C} \\\\)\\nTherefore, the difference \\\\( =-2^{\\\\circ} \\\\mathrm{C}-\\\\left(-8^{\\\\circ} \\\\mathrm{C}\\\\right) \\\\) \\\\( =6^{\\\\circ} \\\\mathrm{C} \\\\)\\n(d) The temperature of Srinagar and Shimla taken together \\\\( =-2^{\\\\circ} \\\\mathrm{C}+5^{\\\\circ} \\\\mathrm{C} \\\\) \\\\( =3^{\\\\circ} \\\\mathrm{C} \\\\)\\nThe temperature at Shimla \\\\( =5^{\\\\circ} \\\\mathrm{C}>3^{\\\\circ} \\\\mathrm{C} \\\\). Therefore the temperature of Srinagar and Shimla taken together is less than that of Shimla.\\n\\nThe temperature at Srinagar \\\\( =-2^{\\\\circ} \\\\mathrm{C}<3^{\\\\circ} \\\\mathrm{C} \\\\). Therefore, the temperature of Srinagar and Shimla taken together is not less than that of Srinagar',\n 'Class- VII-CBSE-Mathematics\\\\nIntegers\\ne EMBIBE\\nSubmarine floating below the sea level \\\\( =1200 \\\\mathrm{~m} \\\\)\\nTherefore, the vertical distance between them \\\\( =5000+1200 \\\\)\\n\\\\[\\n=6200 \\\\mathrm{~m}\\n\\\\]',\n 'Class- VII-CBSE-Mathematics\\\\nIntegers\\ne EMBIBE\\n\\\\begin{tabular}{|c|c|c|}\\n\\\\hline\\\\( -4 \\\\) & \\\\( -3 \\\\) & \\\\( -2 \\\\) \\\\\\\\\\n\\\\hline\\\\( -6 \\\\) & 4 & \\\\( -7 \\\\) \\\\\\\\\\n\\\\hline\\n\\\\end{tabular}\\', \\'\\n(i) Sum of the rows:\\n\\\\[\\n\\\\begin{array}{l}\\n5+-1+-4=0 \\\\\\\\\\n-5+-2+7=0 \\\\\\\\\\n0+3+-3=0\\n\\\\end{array}\\n\\\\]\\nSum of the columns:\\n\\\\[\\n\\\\begin{array}{l}\\n5+-5+0=0 \\\\\\\\\\n-1+-2+3=0 \\\\\\\\\\n-4+7+-3=0\\n\\\\end{array}\\n\\\\]\\nSum of the diagonals:\\n\\\\[\\n\\\\begin{array}{l}\\n5+-2+-3=0 \\\\\\\\\\n-4+-2+0=-6\\n\\\\end{array}\\n\\\\]\\nThus, this is not a magic square because all the sums are not equal\\n(ii) Sum of the rows:\\n\\\\[\\n\\\\begin{array}{l}\\n1+-10+0=-9 \\\\\\\\\\n-4+-3+-2=-9 \\\\\\\\\\n-6+4+-7=-9\\n\\\\end{array}\\n\\\\]\\nSum of the columns:\\n\\\\[\\n\\\\begin{array}{l}\\n1+-4+-6=-9 \\\\\\\\\\n-10+-3+4=-9 \\\\\\\\\\n0+-2+-7=-9\\n\\\\end{array}\\n\\\\]\\nSum of the diagonals:\\n\\\\[\\n\\\\begin{array}{l}\\n1+-3+-7=0 \\\\\\\\\\n0+-3+-6=-9\\n\\\\end{array}\\n\\\\]\\nThus, this is a magic square because all the sums are equal',\n 'Class- VII-CBSE-Mathematics\\\\nIntegers\\ne EMBIBE\\n(ii) \\\\( a=118, b=125 \\\\)\\n(iii) \\\\( \\\\mathrm{a}=75, \\\\mathrm{~b}=84 \\\\)\\n(iv) \\\\( a=28, b=11 \\\\)\\', \\'\\n\\\\[\\n\\\\begin{array}{l}\\n\\\\text { LHS } a-(-b)=21-(-18)=39 \\\\\\\\\\n\\\\text { RHS } a+b=21+18=39 \\\\\\\\\\n\\\\mathrm{LHS}=\\\\text { RHS }\\n\\\\end{array}\\n\\\\]\\nThus verified\\n\\\\[\\n\\\\begin{array}{l}\\n\\\\operatorname{LHS~} a-(-b)=118-(-125)=243 \\\\\\\\\\n\\\\text { RHS a }+b=118+125=243 \\\\\\\\\\n\\\\mathrm{LHS}=\\\\text { RHS }\\n\\\\end{array}\\n\\\\]\\nThus verified\\n\\\\[\\n\\\\begin{array}{l}\\n\\\\operatorname{LHS~} a-(-b)=75-(-84)=159 \\\\\\\\\\n\\\\text { RHS } a+b=75+84=159 \\\\\\\\\\n\\\\text { LHS }=\\\\text { RHS }\\n\\\\end{array}\\n\\\\]\\nThus verified\\n\\\\[\\n\\\\begin{array}{l}\\n\\\\operatorname{LHS~} a-(-b)=28-(-11)=39 \\\\\\\\\\n\\\\text { RHS } a+b=28+11=39\\n\\\\end{array}\\n\\\\]\\n\\\\[\\n\\\\mathrm{LHS}=\\\\mathrm{RHS}\\n\\\\]\\nThus verified',\n 'Class- VII-CBSE-Mathematics\\\\nIntegers\\ne EMBIBE\\n(c) \\\\( -7>-29 \\\\)\\n(d) \\\\( 0<20 \\\\)\\n(e) \\\\( -101>-159 \\\\)'\n]\n\n\ndef lcp(sa):\n assert len(sa) > 1\n k, *r = sa\n for o in range(min(map(len, sa))):\n for e in r:\n if e[o] != k[o]:\n return k[:o]\n return k\n\nprint(lcp(X))\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11725056/"
] |
74,411,123 | <p>my base <code>class</code>:</p>
<pre class="lang-js prettyprint-override"><code>import { Component, VERSION } from '@angular/core';
import { Feature } from './super.component';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent extends Feature {
name = 'Angular ' + VERSION.major;
constructor() {
super();
}
superToCall(value) {
console.log('value', value);
}
}
</code></pre>
<p>super <code>class</code>:</p>
<pre><code>export class Feature {
childCalled(value) {
console.log('child called', value);
}
}
</code></pre>
<p>how to pass the param to <code>superToCall</code> from <code>childCalled</code> method?</p>
<p><a href="https://stackblitz.com/edit/angular-ivy-zfqrye?file=src/app/super.component.ts" rel="nofollow noreferrer">Live Demo</a></p>
| [
{
"answer_id": 74411954,
"author": "3gwebtrain",
"author_id": 218349,
"author_profile": "https://Stackoverflow.com/users/218349",
"pm_score": 0,
"selected": false,
"text": "ParentClass.prototype.myMethod.call(this)\n"
},
{
"answer_id": 74412083,
"author": "Edmunds Folkmanis",
"author_id": 19886561,
"author_profile": "https://Stackoverflow.com/users/19886561",
"pm_score": 2,
"selected": false,
"text": "abstract superToCall(value: unknown):void"
},
{
"answer_id": 74412249,
"author": "TmTron",
"author_id": 1041641,
"author_profile": "https://Stackoverflow.com/users/1041641",
"pm_score": 3,
"selected": true,
"text": "Feature"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/218349/"
] |
74,411,128 | <p>I'm trying to understand exactly how this <a href="https://davidwalsh.name/javascript-once" rel="nofollow noreferrer">Once function by David Walsh</a> works:</p>
<p>`</p>
<pre><code>function once(fn, context) {
var result;
return function() {
if(fn) {
result = fn.apply(context || this, arguments);
fn = null;
}
return result;
};
}
// Usage
var canOnlyFireOnce = once(function() {
console.log('Fired!');
});
canOnlyFireOnce(); // "Fired!"
canOnlyFireOnce(); // nada
</code></pre>
<p>`</p>
<p>I understand it takes a function as a argument, and returns a function that calls the passed function only once.</p>
<p>But I'm trying to understand what each part is doing. Can anyone help explain? especially this part:</p>
<p><code>result = fn.apply(context || this, arguments);</code></p>
<p>Why the OR sign? what is "this" and how is it getting the arguments from fn? What purpose does 'context' serve?</p>
<hr />
<p>I wrote a similar once() function for school that returns the result of the passed function, and stores the result to return it again if the function attempts to get called again. It took a lot of trial and error, and I'm just trying to get a firm grasp on all the component parts of how this works.</p>
<p>`</p>
<pre><code>function add(x, y) {
return x + y;
}
function once(fn) {
let timesRan = 0;
let result;
function doOnce() {
if (timesRan === 0) {
timesRan = 1;
result = fn.apply(this, arguments); //I don't understand how this gets the arguments from AddOnce
console.log(`did it once: ${result}`)
return result;
} else {
return result;
}
}
return doOnce;
}
var addOnce = once(add);
console.log(addOnce(1, 2)); // test first call, expected value: 3
console.log(addOnce(2, 5)); // test second call, expected value: 3
console.log(addOnce(8, 22)); // test third call, expected value: 3
</code></pre>
<p>`</p>
| [
{
"answer_id": 74411954,
"author": "3gwebtrain",
"author_id": 218349,
"author_profile": "https://Stackoverflow.com/users/218349",
"pm_score": 0,
"selected": false,
"text": "ParentClass.prototype.myMethod.call(this)\n"
},
{
"answer_id": 74412083,
"author": "Edmunds Folkmanis",
"author_id": 19886561,
"author_profile": "https://Stackoverflow.com/users/19886561",
"pm_score": 2,
"selected": false,
"text": "abstract superToCall(value: unknown):void"
},
{
"answer_id": 74412249,
"author": "TmTron",
"author_id": 1041641,
"author_profile": "https://Stackoverflow.com/users/1041641",
"pm_score": 3,
"selected": true,
"text": "Feature"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4675347/"
] |
74,411,136 | <p>I hv downloaded template for bloger and i want to remove copyright area else change it to blog itself but unable to remove it anyone guide me to change it
Blog code</p>
<pre><code> <div class='copyright-area'>Created By <a href='https://propertypartner24x7.blogspot.com/' id='mycontent' rel='dofollow' style='display: inline-block!important; font-size: inherit!important; color: #ff00ba!important; visibility: visible!important;z-index:99!important; opacity: 1!important;position:relative!important;' title='Property Partner'>Property Partner</a> | Distributed By <a href='https://propertypartner24x7.blogspot.com/' rel='dofollow' style='color:#ff00ba;' target='_blank' title='Property Partner'>Property Partner</a>
</div>
</code></pre>
<p>code is showing as below on developer mode</p>
<p>Blog</p>
<p>Expecting Copyright by my blog itself</p>
| [
{
"answer_id": 74411954,
"author": "3gwebtrain",
"author_id": 218349,
"author_profile": "https://Stackoverflow.com/users/218349",
"pm_score": 0,
"selected": false,
"text": "ParentClass.prototype.myMethod.call(this)\n"
},
{
"answer_id": 74412083,
"author": "Edmunds Folkmanis",
"author_id": 19886561,
"author_profile": "https://Stackoverflow.com/users/19886561",
"pm_score": 2,
"selected": false,
"text": "abstract superToCall(value: unknown):void"
},
{
"answer_id": 74412249,
"author": "TmTron",
"author_id": 1041641,
"author_profile": "https://Stackoverflow.com/users/1041641",
"pm_score": 3,
"selected": true,
"text": "Feature"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4955856/"
] |
74,411,153 | <pre><code>url = "https://www.gumtree.com/search?search_category=all&q=ferrari"
while url:
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
name = soup.find_all("div", class_="h3-responsive")
price = soup.find_all("strong", "h3-responsive")
next_page = soup.select_one("li.pagination-page>a")
for price,name in zip(name,price):
print(name.text,price.text)
if next_page:
next_url = next_page.get("href")
url = urljoin(url,next_url)
else:
url = None
</code></pre>
<p>Nothing is printing for some reason? I've had it running for 5 minutes and still nothing. I've had no error code either so I'm geuinely confused here? If anyone would like to fix this script please do so, if you didn't realize the script is supposed to scrape the name & price as well as every other page/s name and price.</p>
<p>If someone could please re-do the script, and make it also scrape all the other pages, because I have been having a hard time figuring out how to do this.</p>
<p>I've taken some suggestions in and done some editing but the script still won't work.</p>
| [
{
"answer_id": 74411346,
"author": "Barry the Platipus",
"author_id": 19475185,
"author_profile": "https://Stackoverflow.com/users/19475185",
"pm_score": 3,
"selected": true,
"text": "next page"
},
{
"answer_id": 74418899,
"author": "Driftr95",
"author_id": 6146136,
"author_profile": "https://Stackoverflow.com/users/6146136",
"pm_score": 0,
"selected": false,
"text": "find_all"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20483330/"
] |
74,411,154 | <p>I am receiving from the web service JSON array that contains 2 types of objects - base class and class extending the base (it contains some extra attributes).
How can I process it with Jackson that will produce at the end a list of base class in Java. For example, I have a class Car and class Truck which contains attribute maxLoad (and some others) that Car does not have.
At the end I need to get List<Car> that will contain instances of both Car and Truck.
Here is the code:</p>
<pre><code>public class Car {
private String make;
private String model;
private short year;
private String bodyStyle;
private String engineType;
private int horsepower;
// setters and getters are omitted
}
public class Truck extends Car {
private double maxLoad;
private double clearance;
// setters and getters are omitted
}
</code></pre>
<p>And here is the test JSON file and code for test:</p>
<pre><code> [
{
"make": "Ford",
"model": "Focus",
"year": 2018,
"engineType": "T4",
"bodyStyle": "hatchback",
"horsepower": 225
},
{
"make": "Toyota",
"model": "Prius",
"year": 2021,
"engineType": "T4",
"bodyStyle": "hatchback",
"horsepower": 121
},
{
"make": "Toyota",
"model": "RAV4",
"year": 2020,
"engineType": "V6",
"bodyStyle": "SUV",
"horsepower": 230
},
{
"make": "Toyota",
"model": "Tacoma",
"year": 2021,
"engineType": "V6",
"bodyStyle": "pickup",
"horsepower": 278,
"maxLoad": 1050,
"clearance": 9.4
},
{
"make": "Ford",
"model": "T150",
"year": 2017,
"horsepower": 450,
"bodyStyle": "pickup",
"maxLoad": 2320,
"clearance": 8.4
}
]
public class Test {
private static final ObjectMapper mapper = new ObjectMapper();
@SuppressWarnings("CallToPrintStackTrace")
public static void main(String[] args) {
InputStream src = Test.class.getClassLoader().getResourceAsStream("cars.json");
try {
List<Car> cars = mapper.readValue(src, new TypeReference<List<Car>>() {});
for (Car car : cars) {
System.out.println(car.getClass().getName());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
</code></pre>
<p>When I run this test program, I am getting an exception:</p>
<blockquote>
<p>com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "maxLoad" (class org.garik.test.Car), not marked as ignorable (6 known properties: "horsepower", "model", "engineType", "year", "make", "bodyStyle"])
at [Source: (BufferedInputStream); line: 33, column: 24] (through reference chain: java.util.ArrayList[3]->org.garik.test.Car["maxLoad"])
at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:61)
at com.fasterxml.jackson.databind.DeserializationContext.handleUnknownProperty(DeserializationContext.java:1127)
at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:2023)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1700)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownVanilla(BeanDeserializerBase.java:1678)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:320)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:177)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer._deserializeFromArray(CollectionDeserializer.java:355)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:244)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:28)
at com.fasterxml.jackson.databind.deser.DefaultDeserializationContext.readRootValue(DefaultDeserializationContext.java:323)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4674)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3674)
at org.garik.test.Test.main(Test.java:21)</p>
</blockquote>
<p>If I replace List with List it completes without errors, but create me instances of Truck only, but I need in this list instances of both Car and Truck.</p>
| [
{
"answer_id": 74419023,
"author": "user404",
"author_id": 5332914,
"author_profile": "https://Stackoverflow.com/users/5332914",
"pm_score": 0,
"selected": false,
"text": "Car"
},
{
"answer_id": 74421355,
"author": "dariosicily",
"author_id": 11713777,
"author_profile": "https://Stackoverflow.com/users/11713777",
"pm_score": 3,
"selected": true,
"text": "Car"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2318409/"
] |
74,411,179 | <p>I have the following javascript code:</p>
<pre><code>const theJvScSet = new Set()
while (theJvScSet.size != 10) {
let iniKick = Math.floor(Math.random()*2), setElement = [iniKick]
for (let index = 0; index < 2; index++) {
const spinVal = 1 + Math.floor(Math.random()*5)
setElement.push(spinVal)
}
theJvScSet.add(setElement)
}
</code></pre>
<p>And after execution I find myself with twice the value : [0, 3, 5] in the set.
How is this possible? I expected the line of code:</p>
<pre><code>theJvScSet.add(setElement)
</code></pre>
<p>to only insert in the set values not already in there.</p>
<p>What do I need to change to make sure only different values will be accepted inside theJvScSet?</p>
| [
{
"answer_id": 74411236,
"author": "Carsten Massmann",
"author_id": 2610061,
"author_profile": "https://Stackoverflow.com/users/2610061",
"pm_score": 2,
"selected": false,
"text": "const arr=[4,5,6], unique=new Set();\n\nunique.add([1,2,3]);\nunique.add([1,2,3]);\nunique.add([1,2,3]);\n\nunique.add(arr);\nunique.add(arr);\nunique.add(arr);\n\nconsole.log([...unique]);"
},
{
"answer_id": 74411239,
"author": "rb612",
"author_id": 3813411,
"author_profile": "https://Stackoverflow.com/users/3813411",
"pm_score": 0,
"selected": false,
"text": "a === b"
},
{
"answer_id": 74411276,
"author": "Lucasbk38",
"author_id": 20480528,
"author_profile": "https://Stackoverflow.com/users/20480528",
"pm_score": 0,
"selected": false,
"text": "\nconst theJvScSet = []\n\nwhile (theJvScSet.size != 10) {\n let iniKick = Math.floor(Math.random()*2), setElement = [iniKick]\n for (let index = 0; index < 2; index++) {\n const spinVal = 1 + Math.floor(Math.random()*5)\n setElement.push(spinVal)\n }\n if (theJvScSet.findIndex(arr => arr.every((n, i) => setElement[i] === n)) === -1)\n theJvScSet.add(setElement)\n}\n\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/611201/"
] |
74,411,212 | <p>I have a table which store some datas. This is my table structure.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Course</th>
<th>Location</th>
</tr>
</thead>
<tbody>
<tr>
<td>Wolden</td>
<td>New York</td>
</tr>
<tr>
<td>Sertigo</td>
<td>Seatlle</td>
</tr>
<tr>
<td>Monad</td>
<td>Chicago</td>
</tr>
<tr>
<td>Donner</td>
<td>Texas</td>
</tr>
</tbody>
</table>
</div>
<p>I want to search from that table for example with this keyword <code>Sertigo Seattle</code> and it will return row number two as a result.</p>
<p>I have this query but doesn't work.</p>
<p><code>SELECT * FROM courses_data a WHERE CONCAT_WS(' ', a.Courses, a.Location) LIKE '%Sertigo Seattle%'</code></p>
<p>Maybe anyone knows how to make query to achieve my needs?</p>
| [
{
"answer_id": 74411236,
"author": "Carsten Massmann",
"author_id": 2610061,
"author_profile": "https://Stackoverflow.com/users/2610061",
"pm_score": 2,
"selected": false,
"text": "const arr=[4,5,6], unique=new Set();\n\nunique.add([1,2,3]);\nunique.add([1,2,3]);\nunique.add([1,2,3]);\n\nunique.add(arr);\nunique.add(arr);\nunique.add(arr);\n\nconsole.log([...unique]);"
},
{
"answer_id": 74411239,
"author": "rb612",
"author_id": 3813411,
"author_profile": "https://Stackoverflow.com/users/3813411",
"pm_score": 0,
"selected": false,
"text": "a === b"
},
{
"answer_id": 74411276,
"author": "Lucasbk38",
"author_id": 20480528,
"author_profile": "https://Stackoverflow.com/users/20480528",
"pm_score": 0,
"selected": false,
"text": "\nconst theJvScSet = []\n\nwhile (theJvScSet.size != 10) {\n let iniKick = Math.floor(Math.random()*2), setElement = [iniKick]\n for (let index = 0; index < 2; index++) {\n const spinVal = 1 + Math.floor(Math.random()*5)\n setElement.push(spinVal)\n }\n if (theJvScSet.findIndex(arr => arr.every((n, i) => setElement[i] === n)) === -1)\n theJvScSet.add(setElement)\n}\n\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7198384/"
] |
74,411,219 | <p>I'm building a landing page with some SVGs blobs that are meant to be on the edges of the webpage, half-inside, half-outside. The problem happens when adjusting the blobs for mobile dimensions, the blobs positioned on the right side are generating a lot of white space and thus right-scrolling. I'd like to 'cut' the blob right at the right edge of the screen.</p>
<p>I'm using Bootstrap 5 for this project.</p>
<p>Intended result:</p>
<p><a href="https://i.stack.imgur.com/hFuZO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hFuZO.png" alt="This is the intended result" /></a></p>
<p>Actual result:</p>
<p><a href="https://i.stack.imgur.com/GTBM7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GTBM7.png" alt="Aaand this is it's going." /></a></p>
<p>Already tried adding <code>overflow-x: hidden;</code> and <code>max-width: 100%;</code> and its variations.</p>
<p><strong>Demo:</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code> /* CSS class for the blob: */
.cssloco {
position: absolute;
opacity: 1;
left: 10%;
top: 40%;
z-index: -1;
height: 100%;
width: 200%;
}
/* CSS blob class for mobile: */
@media (max-width: 1200px) {
.cssloco {
overflow: hidden;
left: 40%;
top: 150%;
height: 600px;
width: 600px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="d-flex container mt-15 justify-content-between">
<div class="row">
<div class="col-8 col-md-6 col-sm-8 order-0 order-lg-0 order-sm-0 animacion mensaje-responsive">
<h1 class="text-start fw-bold">Estás a un mensaje de distancia.</h1>
<p class="fs-5 fw-semibold">Olvidate de volver a entrar a varios sitios web para conseguir información. <span class="fw-bold">Aerobot</span> te proporciona la forma de tener todo en un mismo lugar, haciendo que tu operación sea <span class="fw-bold">más rápida y más segura, 100% gratis. ✈️ </span></p>
</div>
<div class="d-flex col col-md-6 order-1 order-sm-1 justify-content-center">
<div class="svg-blob cssloco">
<svg viewBox="0 0 800 500" preserveAspectRatio="none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="150%" id="blobSvg">
<g transform="translate(151.32916831970215, 3.4678802490234375)">
<defs>
<linearGradient id="gradient" x1="0%" y1="0%" x2="0%" y2="100%">
<stop offset="0%" style="stop-color: rgb(76, 161, 175);"></stop>
<stop offset="100%" style="stop-color: rgb(196, 224, 229);"></stop>
</linearGradient>
</defs>
<path class="blob" d="M479.79863,286.0103Q472.04119,322.0206,452.55149,352.53089Q433.06179,383.04119,405.37643,404.81464Q377.69107,426.5881,351.37643,453.89702Q325.06179,481.20595,287.53089,468.08238Q250,454.95881,217.0103,453.44851Q184.0206,451.93821,151.9794,441.03089Q119.93821,430.12357,88.91762,409.59268Q57.89702,389.06179,52.17506,352.45881Q46.45309,315.85583,25.64417,282.92792Q4.83524,250,12.26316,212.44851Q19.69107,174.89702,53.56179,153.61327Q87.4325,132.32952,103.80893,101.78833Q120.18536,71.24714,149.05149,49.4897Q177.91762,27.73226,213.95881,30.73226Q250,33.73226,285.07208,34.14988Q320.14417,34.5675,351.69565,50.60869Q383.24714,66.64988,407.42792,92.46911Q431.60869,118.28833,436.97483,152.74714Q442.34096,187.20595,464.94851,218.60298Q487.55607,250,479.79863,286.0103Z" fill="url(#gradient)"></path>
</g>
</svg>
</div>
<img src="svg/chat1.svg" alt="" class="imagen-reporte animacion">
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74411236,
"author": "Carsten Massmann",
"author_id": 2610061,
"author_profile": "https://Stackoverflow.com/users/2610061",
"pm_score": 2,
"selected": false,
"text": "const arr=[4,5,6], unique=new Set();\n\nunique.add([1,2,3]);\nunique.add([1,2,3]);\nunique.add([1,2,3]);\n\nunique.add(arr);\nunique.add(arr);\nunique.add(arr);\n\nconsole.log([...unique]);"
},
{
"answer_id": 74411239,
"author": "rb612",
"author_id": 3813411,
"author_profile": "https://Stackoverflow.com/users/3813411",
"pm_score": 0,
"selected": false,
"text": "a === b"
},
{
"answer_id": 74411276,
"author": "Lucasbk38",
"author_id": 20480528,
"author_profile": "https://Stackoverflow.com/users/20480528",
"pm_score": 0,
"selected": false,
"text": "\nconst theJvScSet = []\n\nwhile (theJvScSet.size != 10) {\n let iniKick = Math.floor(Math.random()*2), setElement = [iniKick]\n for (let index = 0; index < 2; index++) {\n const spinVal = 1 + Math.floor(Math.random()*5)\n setElement.push(spinVal)\n }\n if (theJvScSet.findIndex(arr => arr.every((n, i) => setElement[i] === n)) === -1)\n theJvScSet.add(setElement)\n}\n\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16302284/"
] |
74,411,227 | <p>I have create a table person(id, name ,samenamecount).The samenamecount attribute can be null but for each row can store the row count for same names.I am achieving this by calling a stored procedure inside a after insert trigger.Below is my code.</p>
<pre><code>create or replace procedure automatic(s in person.name%type)
AS
BEGIN
update person set samenamecount=(select count(*) from person where name=s) where name=s;
END;
create or replace trigger inserttrigger
after insert
on person
for each row
declare
begin
automatic(:new.name);
end;
</code></pre>
<p>On inserting a row it is giving error like
table ABCD.PERSON is mutating, trigger/function may not see it.
Can somebody help me to figure out this?</p>
| [
{
"answer_id": 74412162,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 1,
"selected": false,
"text": "CREATE TABLE person (\n id NUMBER\n GENERATED ALWAYS AS IDENTITY\n CONSTRAINT person__id__pk PRIMARY KEY,\n name VARCHAR2(20)\n NOT NULL\n);\n"
},
{
"answer_id": 74413641,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 0,
"selected": false,
"text": "CREATE TRIGGER inserttrigger\nAFTER INSERT ON person\nBEGIN\n MERGE INTO person dst\n USING (\n SELECT ROWID AS rid,\n COUNT(*) OVER (PARTITION BY name) AS cnt\n FROM person\n ) src\n ON (src.rid = dst.ROWID)\n WHEN MATCHED THEN\n UPDATE SET samenamecount = src.cnt;\nEND;\n/\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19831141/"
] |
74,411,231 | <p>I found this in vue component , I didn't understand the purpose of :data-col in div , could you explain please</p>
<pre><code><template>
<div
class="vertical-layout h-100"
:class="[layoutClasses]"
:data-col="isNavMenuHidden ? '1-column' : null"
>
</code></pre>
| [
{
"answer_id": 74411329,
"author": "Remicaster",
"author_id": 18665782,
"author_profile": "https://Stackoverflow.com/users/18665782",
"pm_score": 2,
"selected": false,
"text": "data-col"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11141374/"
] |
74,411,235 | <p>How can i make the description responsive, like going to the next line? It's not going to the next line instead it extends horizontally. I can easily fix this if I use textField but I need to adjust the padding and the outline of it, is there any other way?</p>
<pre><code> <Container maxWidth="lg">
<Grid container spacing={2}>
<Grid item xs={12} md={4}>
<Box sx={{height: {xs: 150, md: 300}, width: '300px', border:1, padding: '20px', borderRadius: '10px', display: {xs: 'flex'}}}>
<Box component="img" sx={{height: '100%', width: '100%', objectFit: 'contain'}} src={singleProduct.img}/>
</Box>
</Grid>
<Grid container item xs={12} md={8}>
<Box sx={{display:'flex', flexDirection: 'column', margin:'auto'}}>
<Typography variant="h5" sx={{fontWeight: 'bold', textTransform: 'uppercase'}}> {singleProduct.title}</Typography>
<Box sx={{height: '40px', width: '100%', paddingY: '40px',paddingX: '20px', display:'flex', alignItems:'center', borderBottom: 1}}>
<Typography variant='h3' sx={{color: '#00c853', fontWeight: 800}}> ₱ {singleProduct.price}.00</Typography>
</Box>
<Grid sx={{width: 500}} container spacing={2} pt={4}>
<Grid item xs={4} sx={{lineHeight: 2}}>
<Typography variant="body1" fontWeight={600} color="#757575">Seller: </Typography>
<Typography variant="body1" fontWeight={600} color="#757575">StudentID: </Typography>
<Typography variant="body1" fontWeight={600} color="#757575">Dept: </Typography>
<Typography variant="body1" fontWeight={600} color="#757575">Desc: </Typography>
</Grid>
<Grid item xs={8}>
<Typography variant="body1" fontWeight={700} color="#212121">John Doe</Typography>
<Typography variant="body1" fontWeight={700} color="#212121">{singleProduct.seller_id?.studentId}</Typography>
<Typography variant="body1" fontWeight={700} color="#212121">{singleProduct.seller_id?.department}</Typography>
<Typography variant="body1" fontWeight={700} color="#212121">{singleProduct.description}</Typography>
</Grid>
</Grid>
</Container>
</code></pre>
<p><a href="https://i.stack.imgur.com/PI9Ib.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PI9Ib.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74411284,
"author": "Ali Sattarzadeh",
"author_id": 11434567,
"author_profile": "https://Stackoverflow.com/users/11434567",
"pm_score": 0,
"selected": false,
"text": "{\n max-width:700px;\n white-space: normal;\n}\n"
},
{
"answer_id": 74411305,
"author": "arp",
"author_id": 10841628,
"author_profile": "https://Stackoverflow.com/users/10841628",
"pm_score": 2,
"selected": true,
"text": "<Grid item xs={8} zeroMinWidth>\n <Typography variant=\"body1\" fontWeight={700} color=\"#212121\">John Doe</Typography>\n <Typography variant=\"body1\" fontWeight={700} color=\"#212121\">{singleProduct.seller_id?.studentId}</Typography>\n <Typography variant=\"body1\" fontWeight={700} color=\"#212121\">{singleProduct.seller_id?.department}</Typography>\n <Typography variant=\"body1\" fontWeight={700} color=\"#212121\" style={{overflowWrap: 'break-word'}}>{singleProduct.description}</Typography>\n</Grid>\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18478430/"
] |
74,411,266 | <p>Can I write a function in C++ to accept an array of values like this:</p>
<pre class="lang-cpp prettyprint-override"><code>void someFunction(/*the parameter for array*/){
//do something
}
someFunction({ 1, 2, 3 });
</code></pre>
| [
{
"answer_id": 74411284,
"author": "Ali Sattarzadeh",
"author_id": 11434567,
"author_profile": "https://Stackoverflow.com/users/11434567",
"pm_score": 0,
"selected": false,
"text": "{\n max-width:700px;\n white-space: normal;\n}\n"
},
{
"answer_id": 74411305,
"author": "arp",
"author_id": 10841628,
"author_profile": "https://Stackoverflow.com/users/10841628",
"pm_score": 2,
"selected": true,
"text": "<Grid item xs={8} zeroMinWidth>\n <Typography variant=\"body1\" fontWeight={700} color=\"#212121\">John Doe</Typography>\n <Typography variant=\"body1\" fontWeight={700} color=\"#212121\">{singleProduct.seller_id?.studentId}</Typography>\n <Typography variant=\"body1\" fontWeight={700} color=\"#212121\">{singleProduct.seller_id?.department}</Typography>\n <Typography variant=\"body1\" fontWeight={700} color=\"#212121\" style={{overflowWrap: 'break-word'}}>{singleProduct.description}</Typography>\n</Grid>\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19345796/"
] |
74,411,268 | <p>Digits mean numbers not places</p>
<p>I tried but the logic is wrong I know</p>
<pre><code>N=input()
L=len(N)
N=int(N)
sum_e=0
sum_o=0
for i in range(0,L+1):
if i%2==0:
sum_e=sum_e+i
else:
sum_o=sum_o+i
print(sum_e, sum_o)
</code></pre>
| [
{
"answer_id": 74411295,
"author": "KillerRebooted",
"author_id": 18554284,
"author_profile": "https://Stackoverflow.com/users/18554284",
"pm_score": 0,
"selected": false,
"text": "N=input()\n\nsum_e=0\nsum_o=0\n\nfor i in N:\n if int(i)%2==0:\n sum_e += int(i)\n else:\n sum_o += int(i)\n\nprint(sum_e, sum_o)\n"
},
{
"answer_id": 74411404,
"author": "Cobra",
"author_id": 17580381,
"author_profile": "https://Stackoverflow.com/users/17580381",
"pm_score": 1,
"selected": false,
"text": "N = abs(int(input('Enter a number: ')))\n\neo = [0, 0]\n\nwhile N != 0:\n v = N % 10\n eo[v & 1] += v\n N //= 10\n\nprint(*eo)\n"
},
{
"answer_id": 74411657,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 0,
"selected": false,
"text": "N = input()\n# N = '1234567'\n\nout = {}\nfor c in N:\n c = int(c)\n key = 'odd' if c%2 else 'even'\n out[key] = out.get(key, 0) + c\n\nprint(out['even'], out['odd'])\n# 12 16\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411268",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20484018/"
] |
74,411,285 | <p>I want to do something like this:</p>
<pre><code>const GreetingWithCounter = (props) => {
const { name, count } = props;
return (
<div>
<div>Hello {name}</div>
<button onClick={() => render({ ...props, count: count + 1 })}>
{count}
</button>
</div>
);
}
<GreetingWithCounter name="Alice" count={0} />
</code></pre>
<p>Ie. I want to re-render a component with new values for its <code>props</code>. Is there a way to do that? Looking through these three questions, I'm seeing ways to re-render a component but not with new values for props (<a href="https://stackoverflow.com/questions/30626030/can-you-force-a-react-component-to-rerender-without-calling-setstate">1</a>, <a href="https://stackoverflow.com/questions/46240647/react-how-to-force-a-function-component-to-render/53837442#53837442">2</a>, <a href="https://stackoverflow.com/questions/30626030/can-you-force-a-react-component-to-rerender-without-calling-setstate/30626072#30626072">3</a>).</p>
<p><strong>Context</strong></p>
<p>I'm thinking about a way to simplify React. I really like the mental model of React being the view layer in MVC, where UI = F(state). But things can get confusing when "state" can come from so many different places: <code>props</code>, <code>useState</code>, <code>useReducer</code>, "raw" <code>useContext</code>, Redux (which uses <code>useContext</code> I think), whatever else.</p>
<p>What if everything was just based off of props?</p>
<ul>
<li>For local state you'd do what I did in that example above. You'd initialize the local state of <code>count</code> when doing <code><GreetingWithCounter name="Alice" count={0} /></code> and then update it by re-rendering. This means less DRYness because you'd have to repeat the <code>count={0}</code> code instead of only having it once inside of <code>GreetingWithCounter</code>.</li>
<li>You'd have to do prop drilling instead of <code>useContext</code> stuff.</li>
<li>This approach would probably make React slower.</li>
<li>Still, I hypothesize 1) that the mental model of having everything coming from props is simpler and 2) that pro outweighs the cons in a non-trivial amount of apps.</li>
</ul>
| [
{
"answer_id": 74444557,
"author": "Neil Girardi",
"author_id": 1500241,
"author_profile": "https://Stackoverflow.com/users/1500241",
"pm_score": 2,
"selected": false,
"text": "const [count, setCount] = useState(initialCount)"
},
{
"answer_id": 74463446,
"author": "Erhan Yaşar",
"author_id": 6371094,
"author_profile": "https://Stackoverflow.com/users/6371094",
"pm_score": 2,
"selected": true,
"text": "props are the new state"
},
{
"answer_id": 74515654,
"author": "iAi Dev",
"author_id": 6216503,
"author_profile": "https://Stackoverflow.com/users/6216503",
"pm_score": 2,
"selected": false,
"text": "const GreetingWithCounter = (props) => {\n const { name, count, updateCount } = props;\n\n return (\n <div>\n <div>Hello {name}</div>\n <button onClick={updateCount}>{count}</button>\n </div>\n );\n};\n\nfunction App() {\n const [count, setCount] = useState(0);\n\n const updateCount = () => {\n setCount(count + 1);\n };\n\n return (\n <div className='App'>\n <h1>Greeting With Counter:</h1>\n <GreetingWithCounter\n name='Alice'\n count={count}\n updateCount={updateCount}\n />\n </div>\n );\n}\n"
},
{
"answer_id": 74517705,
"author": "Silent observer",
"author_id": 4547909,
"author_profile": "https://Stackoverflow.com/users/4547909",
"pm_score": 0,
"selected": false,
"text": "import React from 'react'\nimport ReactDOM from 'react-dom'\n\nexport default function renderComponent(Component, props, container) {\n ReactDOM.render(<Component {...props} />, container)\n}\n"
},
{
"answer_id": 74528402,
"author": "Ali Sattarzadeh",
"author_id": 11434567,
"author_profile": "https://Stackoverflow.com/users/11434567",
"pm_score": 1,
"selected": false,
"text": "const GreetingWithCounter = props => {\n const [count, setCount] = useState(props.count);\n const { name } = props;\n\n return (\n <div>\n <div>Hello {name}</div>\n <button onClick={() => setCount(prevState => prevState + 1)}>{count}</button>\n </div>\n );\n};\n\n<GreetingWithCounter name=\"Alice\" count={0} />;\n"
},
{
"answer_id": 74530242,
"author": "Rowanto",
"author_id": 1765184,
"author_profile": "https://Stackoverflow.com/users/1765184",
"pm_score": 0,
"selected": false,
"text": "const ParentStuff = () => {\n const [props, setProps] = useState({ name: \"Alice\", count: 0 });\n render = setProps;\n\n return (<GreetingWithCounter name={props.name} count={props.count} />);\n}\n\nlet render;\n\nconst GreetingWithCounter = props => {\n const { name, count } = props;\n\n return (\n <div>\n <div>Hello {name}</div>\n <button onClick={() => render({ ...props, count: count + 1 })}>{count}</button>\n </div>\n );\n};\n"
},
{
"answer_id": 74530995,
"author": "callOfCode",
"author_id": 5080069,
"author_profile": "https://Stackoverflow.com/users/5080069",
"pm_score": 0,
"selected": false,
"text": "key"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1927876/"
] |
74,411,407 | <p>I want to get the first item of each set of different entries of a columns containing IDs. It works with pandas, but not in dask, as I cannot sort with multiple columns and the <code>.head</code> aggregation is not implemented. Is there another way of getting the desired result?</p>
<p>Here is the mimimal example for pandas, where everything works fine</p>
<pre><code>import pandas as pd
t=pd.DataFrame([[1,2,"ij"],[1,2,"huHU"],[2,4],[2,9],[0,17],[0,2],[1,8],[1,-18]],columns=["particleID","distZ","someothercols"])
tz = (
t
.sort_values(["particleID","distZ"],axis=0)
.groupby(["particleID"])
.head(1)
)
print(t)
print(tz)
</code></pre>
<p>But in dask, see below, I get a <code>NotImplementedError</code>.</p>
<pre><code>import dask.dataframe as dd
t2=dd.from_pandas(t,npartitions=2)
tz2 = (
t2
.sort_values(["particleID","distZ"],axis=0)
.groupby(["particleID"])
.head(1)
)
print(t2.compute())
</code></pre>
<p>I could get the pandas result with this code, but it seems quite inefficient, since I have a needless sort first. Also, in my real application, I need more then one row per group and head does not work with dask</p>
<pre><code>tz2 = (
t2
.sort_values(["distZ"],axis=0)
.sort_values(["particleID"],axis=0)
.groupby(["particleID"])
.first()
)
print(t2.compute())
print(tz2.compute())
</code></pre>
<p>Background: I want to convince everyone to with from SAS to python and pandas. However, we have some very large datasets and this is a very common application. In SAS it is quite easy with <code>if first</code>.</p>
| [
{
"answer_id": 74444557,
"author": "Neil Girardi",
"author_id": 1500241,
"author_profile": "https://Stackoverflow.com/users/1500241",
"pm_score": 2,
"selected": false,
"text": "const [count, setCount] = useState(initialCount)"
},
{
"answer_id": 74463446,
"author": "Erhan Yaşar",
"author_id": 6371094,
"author_profile": "https://Stackoverflow.com/users/6371094",
"pm_score": 2,
"selected": true,
"text": "props are the new state"
},
{
"answer_id": 74515654,
"author": "iAi Dev",
"author_id": 6216503,
"author_profile": "https://Stackoverflow.com/users/6216503",
"pm_score": 2,
"selected": false,
"text": "const GreetingWithCounter = (props) => {\n const { name, count, updateCount } = props;\n\n return (\n <div>\n <div>Hello {name}</div>\n <button onClick={updateCount}>{count}</button>\n </div>\n );\n};\n\nfunction App() {\n const [count, setCount] = useState(0);\n\n const updateCount = () => {\n setCount(count + 1);\n };\n\n return (\n <div className='App'>\n <h1>Greeting With Counter:</h1>\n <GreetingWithCounter\n name='Alice'\n count={count}\n updateCount={updateCount}\n />\n </div>\n );\n}\n"
},
{
"answer_id": 74517705,
"author": "Silent observer",
"author_id": 4547909,
"author_profile": "https://Stackoverflow.com/users/4547909",
"pm_score": 0,
"selected": false,
"text": "import React from 'react'\nimport ReactDOM from 'react-dom'\n\nexport default function renderComponent(Component, props, container) {\n ReactDOM.render(<Component {...props} />, container)\n}\n"
},
{
"answer_id": 74528402,
"author": "Ali Sattarzadeh",
"author_id": 11434567,
"author_profile": "https://Stackoverflow.com/users/11434567",
"pm_score": 1,
"selected": false,
"text": "const GreetingWithCounter = props => {\n const [count, setCount] = useState(props.count);\n const { name } = props;\n\n return (\n <div>\n <div>Hello {name}</div>\n <button onClick={() => setCount(prevState => prevState + 1)}>{count}</button>\n </div>\n );\n};\n\n<GreetingWithCounter name=\"Alice\" count={0} />;\n"
},
{
"answer_id": 74530242,
"author": "Rowanto",
"author_id": 1765184,
"author_profile": "https://Stackoverflow.com/users/1765184",
"pm_score": 0,
"selected": false,
"text": "const ParentStuff = () => {\n const [props, setProps] = useState({ name: \"Alice\", count: 0 });\n render = setProps;\n\n return (<GreetingWithCounter name={props.name} count={props.count} />);\n}\n\nlet render;\n\nconst GreetingWithCounter = props => {\n const { name, count } = props;\n\n return (\n <div>\n <div>Hello {name}</div>\n <button onClick={() => render({ ...props, count: count + 1 })}>{count}</button>\n </div>\n );\n};\n"
},
{
"answer_id": 74530995,
"author": "callOfCode",
"author_id": 5080069,
"author_profile": "https://Stackoverflow.com/users/5080069",
"pm_score": 0,
"selected": false,
"text": "key"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19953747/"
] |
74,411,438 | <p>What I am trying to do is, whenever any cell in the range (B1:B10) is edited I want to sum up the values within the range (B1:B10) and add this to cell B11. I used the following code but it adds the formula into the cell. I want to put only the summed value, not the formula itself.</p>
<pre><code>function onEdit(e) {
var ss = e.source;
var cell = e.range;
if(cell.getA1Notation() === "B1:B10" && ss.getActiveSheet().getName() == "TEST"){
ss.getActiveSheet().getRange("B11").setFormula("=SUM(B1:B10)");
}
}
</code></pre>
<p>I tried to find an answer on Google, but I couldn't find it.</p>
| [
{
"answer_id": 74415165,
"author": "doubleunary",
"author_id": 13045193,
"author_profile": "https://Stackoverflow.com/users/13045193",
"pm_score": 3,
"selected": true,
"text": "Array.filter()"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13935956/"
] |
74,411,450 | <p>some previous questions have been asked on this topic, but they don't seem to include the case when a string contains multiple instances of the same delimiter.</p>
<p><a href="https://stackoverflow.com/questions/23518325/how-to-extract-substring-between-patterns-and-in-r">How to extract substring between patterns "_" and "." in R</a></p>
<p><a href="https://stackoverflow.com/questions/39086400/extracting-a-string-between-other-two-strings-in-r">Extracting a string between other two strings in R</a></p>
<p><a href="https://stackoverflow.com/questions/23503448/extract-a-string-between-patterns-delimiters-in-r">Extract a string between patterns/delimiters in R</a></p>
<p>The problem I am facing is the following. Say we have a vector like this:</p>
<pre><code>vec <- c("Europe/Germany/Berlin/Mitte",
"Europe/Germany/Berlin/Charlottenburg",
"Europe/Croatia/Zagreb/Gornji Grad",
"Europe/Croatia/Zagreb/Donji Grad")
</code></pre>
<p>Can you provide me with the following two functions:</p>
<p>The output of the first function should be:</p>
<pre><code>c("Germany", "Germany", "Croatia", "Croatia")
</code></pre>
<p>And the output of the second function should be:</p>
<pre><code>c("Berlin", "Berlin", "Zagreb", "Zagreb")
</code></pre>
<p>I don't understand how the answers from previous questions apply when the delimiter <code>/</code> appears more than once in the string and how can I specify which of the pieces I want.</p>
| [
{
"answer_id": 74411494,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 2,
"selected": false,
"text": "sapply()"
},
{
"answer_id": 74413195,
"author": "Tom Hoel",
"author_id": 17213355,
"author_profile": "https://Stackoverflow.com/users/17213355",
"pm_score": 3,
"selected": true,
"text": "library(tidyverse)\n\nget_name <- function(position) {\n vec %>%\n str_split(\"/\") %>%\n map_chr( ~ .x[position])\n}\n"
},
{
"answer_id": 74413652,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 1,
"selected": false,
"text": "vec <- c(\"Europe/Germany/Berlin/Mitte\", \n \"Europe/Germany/Berlin/Charlottenburg\", \n \"Europe/Croatia/Zagreb/Gornji Grad\", \n \"Europe/Croatia/Zagreb/Donji Grad\")\n\nrgx <- \"(.*)/(.*)/(.*)/(.*)\"\n\nsub(rgx, \"\\\\1\", vec)\n#> [1] \"Europe\" \"Europe\" \"Europe\" \"Europe\"\nsub(rgx, \"\\\\2\", vec)\n#> [1] \"Germany\" \"Germany\" \"Croatia\" \"Croatia\"\nsub(rgx, \"\\\\3\", vec)\n#> [1] \"Berlin\" \"Berlin\" \"Zagreb\" \"Zagreb\"\nsub(rgx, \"\\\\4\", vec)\n#> [1] \"Mitte\" \"Charlottenburg\" \"Gornji Grad\" \"Donji Grad\"\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411450",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8473437/"
] |
74,411,455 | <p>I am trying to speed up some python code using rust bindings with py03.</p>
<p>i have implemented the following function in both python and rust:</p>
<pre class="lang-py prettyprint-override"><code>def _play_action(state, action):
temp = state.copy()
i1, j1, i2, j2 = action
h1 = abs(temp[i1][j1])
h2 = abs(temp[i2][j2])
if temp[i1][j1] < 0:
temp[i2][j2] = -(h1 + h2)
else:
temp[i2][j2] = h1 + h2
temp[i1][j1] = 0
return temp
</code></pre>
<pre class="lang-rust prettyprint-override"><code>#[pyfunction]
fn play_action(state: [[i32; 9]; 9], action : [usize;4]) -> [[i32; 9]; 9] {
let mut s = state.clone();
let h1 = s[action[0]][action[1]];
let h2 = s[action[2]][action[3]];
s[action[0]][action[1]] = 0;
s[action[2]][action[3]] = h1.signum() * (h1 + h2).abs();
s
</code></pre>
<p>And to my great surprise the python version is faster... Any idea why?</p>
| [
{
"answer_id": 74411494,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 2,
"selected": false,
"text": "sapply()"
},
{
"answer_id": 74413195,
"author": "Tom Hoel",
"author_id": 17213355,
"author_profile": "https://Stackoverflow.com/users/17213355",
"pm_score": 3,
"selected": true,
"text": "library(tidyverse)\n\nget_name <- function(position) {\n vec %>%\n str_split(\"/\") %>%\n map_chr( ~ .x[position])\n}\n"
},
{
"answer_id": 74413652,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 1,
"selected": false,
"text": "vec <- c(\"Europe/Germany/Berlin/Mitte\", \n \"Europe/Germany/Berlin/Charlottenburg\", \n \"Europe/Croatia/Zagreb/Gornji Grad\", \n \"Europe/Croatia/Zagreb/Donji Grad\")\n\nrgx <- \"(.*)/(.*)/(.*)/(.*)\"\n\nsub(rgx, \"\\\\1\", vec)\n#> [1] \"Europe\" \"Europe\" \"Europe\" \"Europe\"\nsub(rgx, \"\\\\2\", vec)\n#> [1] \"Germany\" \"Germany\" \"Croatia\" \"Croatia\"\nsub(rgx, \"\\\\3\", vec)\n#> [1] \"Berlin\" \"Berlin\" \"Zagreb\" \"Zagreb\"\nsub(rgx, \"\\\\4\", vec)\n#> [1] \"Mitte\" \"Charlottenburg\" \"Gornji Grad\" \"Donji Grad\"\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20013672/"
] |
74,411,467 | <p>i have a web page with canvass and it is used to render 3D scene using threejs, however the canvas is not fullscreen so it has scroll bar since it has some HTML content. how can i prevent mouse wheel from scrolling the page and only handled the mousewheel inside the canvas?</p>
<p>I already did add the preventDefault and stopPropagation on 'wheel' event for the canvas but still the page scrolls.</p>
<pre><code> canvas.addEventListener( 'wheel', onMouseWheel, false );
</code></pre>
<pre><code> function onMouseWheel( event ) {
event.preventDefault();
event.stopPropagation();
}
</code></pre>
<p>what else am i missing here?</p>
| [
{
"answer_id": 74411494,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 2,
"selected": false,
"text": "sapply()"
},
{
"answer_id": 74413195,
"author": "Tom Hoel",
"author_id": 17213355,
"author_profile": "https://Stackoverflow.com/users/17213355",
"pm_score": 3,
"selected": true,
"text": "library(tidyverse)\n\nget_name <- function(position) {\n vec %>%\n str_split(\"/\") %>%\n map_chr( ~ .x[position])\n}\n"
},
{
"answer_id": 74413652,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 1,
"selected": false,
"text": "vec <- c(\"Europe/Germany/Berlin/Mitte\", \n \"Europe/Germany/Berlin/Charlottenburg\", \n \"Europe/Croatia/Zagreb/Gornji Grad\", \n \"Europe/Croatia/Zagreb/Donji Grad\")\n\nrgx <- \"(.*)/(.*)/(.*)/(.*)\"\n\nsub(rgx, \"\\\\1\", vec)\n#> [1] \"Europe\" \"Europe\" \"Europe\" \"Europe\"\nsub(rgx, \"\\\\2\", vec)\n#> [1] \"Germany\" \"Germany\" \"Croatia\" \"Croatia\"\nsub(rgx, \"\\\\3\", vec)\n#> [1] \"Berlin\" \"Berlin\" \"Zagreb\" \"Zagreb\"\nsub(rgx, \"\\\\4\", vec)\n#> [1] \"Mitte\" \"Charlottenburg\" \"Gornji Grad\" \"Donji Grad\"\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2300947/"
] |
74,411,512 | <p>How can I return the second max by group in R data table with the id column returned as well?</p>
<p>Reproducible example below:</p>
<pre><code>library(data.table)
sample_dt <- data.table(
myid=c("A","B","B","A","B","B","C","C","A","A"),
mycol1 =c(101,-108,140,140,-150,-140,-111,101,150,140)
)
#desired output
desired_dt <- data.table(
myid=c("A","B","C"),
mycol1_secondmax=c(140,-108,-111)
)
</code></pre>
| [
{
"answer_id": 74411774,
"author": "Waldi",
"author_id": 13513328,
"author_profile": "https://Stackoverflow.com/users/13513328",
"pm_score": 3,
"selected": false,
"text": "sample_dt[order(-mycol1),.SD[2],by=myid]\n myid mycol1\n <char> <num>\n1: A 140\n2: B -108\n3: C -111\n"
},
{
"answer_id": 74416811,
"author": "ThomasIsCoding",
"author_id": 12158757,
"author_profile": "https://Stackoverflow.com/users/12158757",
"pm_score": 2,
"selected": false,
"text": "data.table"
},
{
"answer_id": 74416937,
"author": "markus",
"author_id": 8583393,
"author_profile": "https://Stackoverflow.com/users/8583393",
"pm_score": 1,
"selected": false,
"text": "setorder"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7837376/"
] |
74,411,514 | <p>Currently doing a college assignment where we need to input and add 3 different scores.
The Scores must be not be less than 0 or greater than 10, and they can only be in multiples of 0.5. It's the latter part I'm having trouble with.</p>
<p>How do I tell the program to give an error if the input isn't a multiple of 0.5?</p>
<pre><code>score1 = float(input("Please input the first score: ")
if score1 <0 or score1 >10:
score1 = float(input("Error! Scores can only be between 0 and 10.\n Please input Score 1 again: "))
elif score1
</code></pre>
| [
{
"answer_id": 74411774,
"author": "Waldi",
"author_id": 13513328,
"author_profile": "https://Stackoverflow.com/users/13513328",
"pm_score": 3,
"selected": false,
"text": "sample_dt[order(-mycol1),.SD[2],by=myid]\n myid mycol1\n <char> <num>\n1: A 140\n2: B -108\n3: C -111\n"
},
{
"answer_id": 74416811,
"author": "ThomasIsCoding",
"author_id": 12158757,
"author_profile": "https://Stackoverflow.com/users/12158757",
"pm_score": 2,
"selected": false,
"text": "data.table"
},
{
"answer_id": 74416937,
"author": "markus",
"author_id": 8583393,
"author_profile": "https://Stackoverflow.com/users/8583393",
"pm_score": 1,
"selected": false,
"text": "setorder"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20484152/"
] |
74,411,525 | <p>I need to run a Factory <code>50</code> times, so inside the <code>DatabseSeeder</code>:</p>
<pre><code>public function run()
{
for($i=1;$i<=50;$i++){
(new CategoryQuestionFactory($i))->create();
}
}
</code></pre>
<p>So as you can see, I tried passing a variable called <code>$i</code> as parameter to <code>CategoryQuestionFactory</code> class.</p>
<p>Then at this Factory, I tried this:</p>
<pre><code>class CategoryQuestionFactory extends Factory
{
protected $counter;
public function __construct($c)
{
$this->counter = $c;
}
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition()
{
$question = Question::find($this->counter);
return [
'category_id' => $this->faker->numberBetween(1,22),
'question_id' => $question->id
];
}
}
</code></pre>
<p>But when I run <code>php artisan db:seed</code> at Terminal, I get this error:</p>
<blockquote>
<p><strong>Call to a member function pipe() on null</strong></p>
<p>at
C:\xampp\htdocs\forum\root\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Factories\Factory.php:429</p>
</blockquote>
<p>So what's going wrong here? How can I properly send a value as a parameter to the Factory Class?</p>
<p>Also, at the IDE for the <code>__construct</code> method of this Factory, I get this message:</p>
<p><a href="https://i.stack.imgur.com/jtOsu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jtOsu.png" alt="enter image description here" /></a></p>
<hr />
<h2><strong>UPDATE #1:</strong></h2>
<p>Here is the capture of error at IDE:</p>
<p><a href="https://i.stack.imgur.com/m37Pc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/m37Pc.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74598943,
"author": "xenooooo",
"author_id": 20283630,
"author_profile": "https://Stackoverflow.com/users/20283630",
"pm_score": 1,
"selected": false,
"text": "has()"
},
{
"answer_id": 74612503,
"author": "HashtagForgotName",
"author_id": 11095364,
"author_profile": "https://Stackoverflow.com/users/11095364",
"pm_score": 0,
"selected": false,
"text": "$question = Question::find($this->counter);\n\nreturn [\n 'category_id' => $this->faker->numberBetween(1,22),\n 'question_id' => $question->id\n];\n"
},
{
"answer_id": 74626282,
"author": "gaetan-hexadog",
"author_id": 20637850,
"author_profile": "https://Stackoverflow.com/users/20637850",
"pm_score": 1,
"selected": false,
"text": "parent::__construct()"
},
{
"answer_id": 74643901,
"author": "Dmitry",
"author_id": 3723707,
"author_profile": "https://Stackoverflow.com/users/3723707",
"pm_score": 0,
"selected": false,
"text": "namespace App\\Models;\n\nuse Illuminate\\Database\\Eloquent\\Factories\\Factory;\nuse Illuminate\\Support\\Collection;\n\nclass CategoryQuestionFactory extends Factory\n{\n public function __construct($count = null, ?Collection $states = null, ?Collection $has = null, ?Collection $for = null, ?Collection $afterMaking = null, ?Collection $afterCreating = null, $connection = null, ?Collection $recycle = null)\n {\n parent::__construct($count, $states, $has, $for, $afterMaking, $afterCreating, $connection, $recycle);\n }\n\n public function definition()\n {\n $question = Question::find($this->counter);\n\n return [\n 'category_id' => $this->faker->numberBetween(1,22),\n 'question_id' => $question->id\n ];\n }\n}\n"
},
{
"answer_id": 74681537,
"author": "Ant Avison",
"author_id": 2449055,
"author_profile": "https://Stackoverflow.com/users/2449055",
"pm_score": 0,
"selected": false,
"text": "$this->faker"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17119202/"
] |
74,411,537 | <p>Not sure how to run the test image script here</p>
<p><a href="https://github.com/cessen/lut_extractor" rel="nofollow noreferrer">https://github.com/cessen/lut_extractor</a></p>
<p>Does it require certain dependencies?</p>
<p>Apologies if it's black and white in the readme but I can't get it to work.</p>
| [
{
"answer_id": 74598943,
"author": "xenooooo",
"author_id": 20283630,
"author_profile": "https://Stackoverflow.com/users/20283630",
"pm_score": 1,
"selected": false,
"text": "has()"
},
{
"answer_id": 74612503,
"author": "HashtagForgotName",
"author_id": 11095364,
"author_profile": "https://Stackoverflow.com/users/11095364",
"pm_score": 0,
"selected": false,
"text": "$question = Question::find($this->counter);\n\nreturn [\n 'category_id' => $this->faker->numberBetween(1,22),\n 'question_id' => $question->id\n];\n"
},
{
"answer_id": 74626282,
"author": "gaetan-hexadog",
"author_id": 20637850,
"author_profile": "https://Stackoverflow.com/users/20637850",
"pm_score": 1,
"selected": false,
"text": "parent::__construct()"
},
{
"answer_id": 74643901,
"author": "Dmitry",
"author_id": 3723707,
"author_profile": "https://Stackoverflow.com/users/3723707",
"pm_score": 0,
"selected": false,
"text": "namespace App\\Models;\n\nuse Illuminate\\Database\\Eloquent\\Factories\\Factory;\nuse Illuminate\\Support\\Collection;\n\nclass CategoryQuestionFactory extends Factory\n{\n public function __construct($count = null, ?Collection $states = null, ?Collection $has = null, ?Collection $for = null, ?Collection $afterMaking = null, ?Collection $afterCreating = null, $connection = null, ?Collection $recycle = null)\n {\n parent::__construct($count, $states, $has, $for, $afterMaking, $afterCreating, $connection, $recycle);\n }\n\n public function definition()\n {\n $question = Question::find($this->counter);\n\n return [\n 'category_id' => $this->faker->numberBetween(1,22),\n 'question_id' => $question->id\n ];\n }\n}\n"
},
{
"answer_id": 74681537,
"author": "Ant Avison",
"author_id": 2449055,
"author_profile": "https://Stackoverflow.com/users/2449055",
"pm_score": 0,
"selected": false,
"text": "$this->faker"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15398477/"
] |
74,411,559 | <p>I have a object which is created by groupBy function.</p>
<pre><code>const productOptions = {
color: [
{ id: 1, type: "color", name: "red" },
{ id: 2, type: "color", name: "orange" },
{ id: 3, type: "color", name: "yellow" },
],
size: [
{ id: 4, type: "size", name: "sm" },
{ id: 5, type: "size", name: "md" },
{ id: 6, type: "size", name: "lg" },
{ id: 7, type: "size", name: "xl" },
],
};
</code></pre>
<p>To display product options by type, I hardcoded it like below.</p>
<pre><code><ProductOption productOptionType={"color"} productOptions={productOptions.color} />
<ProductOption productOptionType={"size"} productOptions={productOptions.size} />
</code></pre>
<p>In the future, weight, accessory, and more will be added to type.</p>
<p>I hate this static structure. Is there a way to display it dynamically using productOptions object at once??</p>
<p>I tried with .map(), But object's keys are not accessible.</p>
<p>I also tried with for-in loop, It doesn't render well.</p>
<p>How can I solve this???</p>
| [
{
"answer_id": 74598943,
"author": "xenooooo",
"author_id": 20283630,
"author_profile": "https://Stackoverflow.com/users/20283630",
"pm_score": 1,
"selected": false,
"text": "has()"
},
{
"answer_id": 74612503,
"author": "HashtagForgotName",
"author_id": 11095364,
"author_profile": "https://Stackoverflow.com/users/11095364",
"pm_score": 0,
"selected": false,
"text": "$question = Question::find($this->counter);\n\nreturn [\n 'category_id' => $this->faker->numberBetween(1,22),\n 'question_id' => $question->id\n];\n"
},
{
"answer_id": 74626282,
"author": "gaetan-hexadog",
"author_id": 20637850,
"author_profile": "https://Stackoverflow.com/users/20637850",
"pm_score": 1,
"selected": false,
"text": "parent::__construct()"
},
{
"answer_id": 74643901,
"author": "Dmitry",
"author_id": 3723707,
"author_profile": "https://Stackoverflow.com/users/3723707",
"pm_score": 0,
"selected": false,
"text": "namespace App\\Models;\n\nuse Illuminate\\Database\\Eloquent\\Factories\\Factory;\nuse Illuminate\\Support\\Collection;\n\nclass CategoryQuestionFactory extends Factory\n{\n public function __construct($count = null, ?Collection $states = null, ?Collection $has = null, ?Collection $for = null, ?Collection $afterMaking = null, ?Collection $afterCreating = null, $connection = null, ?Collection $recycle = null)\n {\n parent::__construct($count, $states, $has, $for, $afterMaking, $afterCreating, $connection, $recycle);\n }\n\n public function definition()\n {\n $question = Question::find($this->counter);\n\n return [\n 'category_id' => $this->faker->numberBetween(1,22),\n 'question_id' => $question->id\n ];\n }\n}\n"
},
{
"answer_id": 74681537,
"author": "Ant Avison",
"author_id": 2449055,
"author_profile": "https://Stackoverflow.com/users/2449055",
"pm_score": 0,
"selected": false,
"text": "$this->faker"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20164678/"
] |
74,411,597 | <p><strong>how i do use beautifulsoup get only string num "611674069.14413534248" from url ?</strong></p>
<p><code>https://shopee.co.th/Kawasaki-%E0%B8%A3%E0%B8%AD%E0%B8%87%E0%B9%80% E0%B8%97%E0%B9%89%E0%B8%B2%E0%B8%81%E0%B8%B5%E0%B8%AC%E0%B8%B2%E0%B8%A5%E0%B9%8D%E0%B8%B2%E0%B8%A5%E0%B8%AD%E0%B8%87%E0%B8%A3%E0%B8%B0%E0%B8%9A%E0%B8%9A%E0%B8%9 B%E0%B9%89%E0%B8%AD%E0%B8%87%E0%B8%81%E0%B8%B1%E0%B8%99%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%AA%E0%B8%B6%E0%B8%81%E0%B8%AB%E0%B8%A3%E0%B8%AD%E0%B9%81%E0%B8%9A%E0%B8 %9A%E0%B9%80%E0%B8%95%E0%B9%87%E0%B8%A1%E0%B8%A3%E0%B8%B9%E0%B8%9B%E0%B9%81%E0%B8%9A%E0%B8%9A-i.611674069.14413534248?sp_atk=639c49c1-a9bf-438f-9f19-26bc401be71 3&xptdk=639c49c1-a9bf-438f-9f19-26bc401be713 </code></p>
<pre><code><div class="col-xs-2-4 shopee-search-item-result__item" data-sqe="item">
<a data-sqe="link" href="/Apple-iPhone-11-by-Studio7-i.301786571.4161270915?sp_atk=cc5f3783-013f-4ed4-88cb-8675a212c9d3&amp;xptdk=cc5f3783-013f-4ed4-88cb-8675a212c9d3">
<div class="tWpFe2"><div class="VTjd7p whIxGK">
<div style="pointer-events: none;">
<div class="yvbeD6 KUUypF"><img width="invalid-value" height="invalid-value" alt="Apple iPhone 11 by Studio7" class="_7DTxhh vc8g9F" style="object-fit: contain" src="https://cf.shopee.co.th/file/sg-11134201-22110-xpzrtoej6pjv3f_tn">
<div class="aLgMTQ"><div class="YeGYFd LIaN-a" style="color: rgb(208, 1, 27);">
<div class="_0aihnk"></div></div></div>
<div class="GOgNtl"><div class="NTmuqd _3NQO+7 WVxeBE _2UunVx"><span class="percent">13%</span><span class="Th6IF+">ลด</span></div></div></div></div>
<div class="KMyn8J"><div class="dpiR4u" data-sqe="name">
<div class="FDn--+"><div class="ie3A+n bM+7UW Cve6sh">Apple iPhone 11 by Studio7</div></div>
<div class="FD2XVZ"><div class="_1PWkR nt-medium nt-foot _3nkRL" style="color: rgb(246, 145, 19);"><svg class="_2DRZW _2xFcL" viewBox="-0.5 -0.5 4 16"><path d="M4 0h-3q-1 0 -1 1a1.2 1.5 0 0 1 0 3v0.333a1.2 1.5 0 0 1 0 3v0.333a1.2 1.5 0 0 1 0 3v0.333a1.2 1.5 0 0 1 0 3q0 1 1 1h3" stroke-width="1" transform="" stroke="currentColor" fill="#f69113"></path></svg>
<div class="_1FKkT _3Ao0A" style="color: white; background-color: rgb(246, 145, 19);">โค้ดลด ฿300</div><svg class="_2DRZW _2xFcL" viewBox="-0.5 -0.5 4 16"><path d="M4 0h-3q-1 0 -1 1a1.2 1.5 0 0 1 0 3v0.333a1.2 1.5 0 0 1 0 3v0.333a1.2 1.5 0 0 1 0 3v0.333a1.2 1.5 0 0 1 0 3q0 1 1 1h3" stroke-width="1" transform="rotate(180) translate(-3 -15)" stroke="currentColor" fill="#f69113"></path></svg></div></div></div><div class="hpDKMN">
<div class="vioxXd rVLWG6"><span class="recFju">฿</span><span class="ZEgDH9">17,000</span> - <span class="recFju">฿</span><span class="ZEgDH9">21,500</span></div></div>
<div class="ZnrnMl"><div class="RS7p+X" data-sqe="rating"><div class="shopee-rating-stars"><div class="shopee-rating-stars__stars">
<div class="shopee-rating-stars__star-wrapper">
<div class="shopee-rating-stars__lit" style="width: 100%;"><svg enable-background="new 0 0 15 15" viewBox="0 0 15 15" x="0" y="0" class="shopee-svg-icon shopee-rating-stars__gold-star icon-rating-solid"><polygon points="7.5 .8 9.7 5.4 14.5 5.9 10.7 9.1 11.8 14.2 7.5 11.6 3.2 14.2 4.3 9.1 .5 5.9 5.3 5.4" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10"></polygon></svg></div><svg enable-background="new 0 0 15 15" viewBox="0 0 15 15" x="0" y="0" class="shopee-svg-icon shopee-rating-stars__dark-star icon-rating-solid"><polygon points="7.5 .8 9.7 5.4 14.5 5.9 10.7 9.1 11.8 14.2 7.5 11.6 3.2 14.2 4.3 9.1 .5 5.9 5.3 5.4" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10"></polygon></svg></div><div class="shopee-rating-stars__star-wrapper"><div class="shopee-rating-stars__lit" style="width: 100%;"><svg enable-background="new 0 0 15 15" viewBox="0 0 15 15" x="0" y="0" class="shopee-svg-icon shopee-rating-stars__gold-star icon-rating-solid"><polygon points="7.5 .8 9.7 5.4 14.5 5.9 10.7 9.1 11.8 14.2 7.5 11.6 3.2 14.2 4.3 9.1 .5 5.9 5.3 5.4" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10"></polygon></svg></div><svg enable-background="new 0 0 15 15" viewBox="0 0 15 15" x="0" y="0" class="shopee-svg-icon shopee-rating-stars__dark-star icon-rating-solid"><polygon points="7.5 .8 9.7 5.4 14.5 5.9 10.7 9.1 11.8 14.2 7.5 11.6 3.2 14.2 4.3 9.1 .5 5.9 5.3 5.4" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10"></polygon></svg></div>
<div class="shopee-rating-stars__star-wrapper">
<div class="shopee-rating-stars__lit" style="width: 100%;"><svg enable-background="new 0 0 15 15" viewBox="0 0 15 15" x="0" y="0" class="shopee-svg-icon shopee-rating-stars__gold-star icon-rating-solid"><polygon points="7.5 .8 9.7 5.4 14.5 5.9 10.7 9.1 11.8 14.2 7.5 11.6 3.2 14.2 4.3 9.1 .5 5.9 5.3 5.4" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10"></polygon></svg></div><svg enable-background="new 0 0 15 15" viewBox="0 0 15 15" x="0" y="0" class="shopee-svg-icon shopee-rating-stars__dark-star icon-rating-solid"><polygon points="7.5 .8 9.7 5.4 14.5 5.9 10.7 9.1 11.8 14.2 7.5 11.6 3.2 14.2 4.3 9.1 .5 5.9 5.3 5.4" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10"></polygon></svg></div><div class="shopee-rating-stars__star-wrapper"><div class="shopee-rating-stars__lit" style="width: 100%;"><svg enable-background="new 0 0 15 15" viewBox="0 0 15 15" x="0" y="0" class="shopee-svg-icon shopee-rating-stars__gold-star icon-rating-solid"><polygon points="7.5 .8 9.7 5.4 14.5 5.9 10.7 9.1 11.8 14.2 7.5 11.6 3.2 14.2 4.3 9.1 .5 5.9 5.3 5.4" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10"></polygon></svg></div><svg enable-background="new 0 0 15 15" viewBox="0 0 15 15" x="0" y="0" class="shopee-svg-icon shopee-rating-stars__dark-star icon-rating-solid"><polygon points="7.5 .8 9.7 5.4 14.5 5.9 10.7 9.1 11.8 14.2 7.5 11.6 3.2 14.2 4.3 9.1 .5 5.9 5.3 5.4" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10"></polygon></svg></div>
<div class="shopee-rating-stars__star-wrapper">
<div class="shopee-rating-stars__lit" style="width: 91.1562%;"><svg enable-background="new 0 0 15 15" viewBox="0 0 15 15" x="0" y="0" class="shopee-svg-icon shopee-rating-stars__gold-star icon-rating-solid"><polygon points="7.5 .8 9.7 5.4 14.5 5.9 10.7 9.1 11.8 14.2 7.5 11.6 3.2 14.2 4.3 9.1 .5 5.9 5.3 5.4" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10"></polygon></svg></div><svg enable-background="new 0 0 15 15" viewBox="0 0 15 15" x="0" y="0" class="shopee-svg-icon shopee-rating-stars__dark-star icon-rating-solid"><polygon points="7.5 .8 9.7 5.4 14.5 5.9 10.7 9.1 11.8 14.2 7.5 11.6 3.2 14.2 4.3 9.1 .5 5.9 5.3 5.4" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10"></polygon></svg></div></div></div></div>
<div class="r6HknA uEPGHT">ขายแล้ว 11.6พัน ชิ้น</div></div>
<div class="zGGwiV">จังหวัดสมุทรปราการ</div></div>
<div class="shopee-item-card__hover-footer _6o9eaa">ค้นหาสินค้าที่คล้ายกัน</div></div></div></a></div>
</code></pre>
<pre><code>get_data = data.find_all('div',class_="col-xs-2-4 shopee-search-item-result__item")
for area in get_data:
print('process data'+str(i))
name = area.find('div',class_="ie3A+n bM+7UW Cve6sh").get_text()
product_images = area.find('img')['src']
price = area.find('span',class_="ZEgDH9").get_text()
link = base_url + area.find('a')['href']
sold = area.find('div',class_="r6HknA uEPGHT")
realurl = area.find('a', text='-i.')
</code></pre>
<p>**realurl , i using find '-i.' to get "611674069.14413534248" from url , but doesn't work. **</p>
<p>[! <a href="https://i.stack.imgur.com/gYWk5.png" rel="nofollow noreferrer">pic.</a>](<a href="https://i.stack.imgur.com/gYWk5.png" rel="nofollow noreferrer">https://i.stack.imgur.com/gYWk5.png</a>)</p>
| [
{
"answer_id": 74598943,
"author": "xenooooo",
"author_id": 20283630,
"author_profile": "https://Stackoverflow.com/users/20283630",
"pm_score": 1,
"selected": false,
"text": "has()"
},
{
"answer_id": 74612503,
"author": "HashtagForgotName",
"author_id": 11095364,
"author_profile": "https://Stackoverflow.com/users/11095364",
"pm_score": 0,
"selected": false,
"text": "$question = Question::find($this->counter);\n\nreturn [\n 'category_id' => $this->faker->numberBetween(1,22),\n 'question_id' => $question->id\n];\n"
},
{
"answer_id": 74626282,
"author": "gaetan-hexadog",
"author_id": 20637850,
"author_profile": "https://Stackoverflow.com/users/20637850",
"pm_score": 1,
"selected": false,
"text": "parent::__construct()"
},
{
"answer_id": 74643901,
"author": "Dmitry",
"author_id": 3723707,
"author_profile": "https://Stackoverflow.com/users/3723707",
"pm_score": 0,
"selected": false,
"text": "namespace App\\Models;\n\nuse Illuminate\\Database\\Eloquent\\Factories\\Factory;\nuse Illuminate\\Support\\Collection;\n\nclass CategoryQuestionFactory extends Factory\n{\n public function __construct($count = null, ?Collection $states = null, ?Collection $has = null, ?Collection $for = null, ?Collection $afterMaking = null, ?Collection $afterCreating = null, $connection = null, ?Collection $recycle = null)\n {\n parent::__construct($count, $states, $has, $for, $afterMaking, $afterCreating, $connection, $recycle);\n }\n\n public function definition()\n {\n $question = Question::find($this->counter);\n\n return [\n 'category_id' => $this->faker->numberBetween(1,22),\n 'question_id' => $question->id\n ];\n }\n}\n"
},
{
"answer_id": 74681537,
"author": "Ant Avison",
"author_id": 2449055,
"author_profile": "https://Stackoverflow.com/users/2449055",
"pm_score": 0,
"selected": false,
"text": "$this->faker"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20483757/"
] |
74,411,600 | <p>I have this association in the DB -
<a href="https://i.stack.imgur.com/4WjzY.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4WjzY.jpg" alt="table structure looks like this in the DB -" /></a></p>
<p>I want the data to be persisted in the tables like this -
<a href="https://i.stack.imgur.com/MfLsz.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MfLsz.jpg" alt="records in the table" /></a></p>
<p>The corresponding JPA entities have been modeled this way (omitted getters/setters for simplicity) -</p>
<p>STUDENT Entity -</p>
<pre><code>@Entity
@Table(name = "student")
public class Student {
@Id
@SequenceGenerator(name = "student_pk_generator", sequenceName =
"student_pk_sequence", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator =
"student_pk_generator")
@Column(name = "student_id", nullable = false)
private Long studentId;
@Column(name = "name", nullable = false)
private String studentName;
@OneToMany(mappedBy = "student", cascade = CascadeType.ALL)
private Set<StudentSubscription> studentSubscription;
}
</code></pre>
<p>STUDENT_SUBSCRIPTION Entity -</p>
<pre><code>@Entity
@Table(name = "student_subscription")
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class StudentSubscription {
@Id
private Long studentId;
@ManyToOne(optional = false)
@JoinColumn(name = "student_id", referencedColumnName = "student_id")
@MapsId
private Student student;
@Column(name = "valid_from")
private Date validFrom;
@Column(name = "valid_to")
private Date validTo;
}
</code></pre>
<p>LIBRARY_SUBSCRIPTION Entity -</p>
<pre><code>@Entity
@Table(name = "library_subscription",
uniqueConstraints = {@UniqueConstraint(columnNames = {"library_code"})})
@PrimaryKeyJoinColumn(name = "student_id")
public class LibrarySubscription extends StudentSubscription {
@Column(name = "library_code", nullable = false)
private String libraryCode;
@PrePersist
private void generateLibraryCode() {
this.libraryCode = // some logic to generate unique libraryCode
}
}
</code></pre>
<p>COURSE_SUBSCRIPTION Entity -</p>
<pre><code>@Entity
@Table(name = "course_subscription",
uniqueConstraints = {@UniqueConstraint(columnNames = {"course_code"})})
@PrimaryKeyJoinColumn(name = "student_id")
public class CourseSubscription extends StudentSubscription {
@Column(name = "course_code", nullable = false)
private String courseCode;
@PrePersist
private void generateCourseCode() {
this.courseCode = // some logic to generate unique courseCode
}
}
</code></pre>
<p>Now, there is a Student entity already persisted with the id let's say - 100.
Now I want to persist this student's library subscription. For this I have created a simple test using Spring DATA JPA repositories -</p>
<pre><code>@Test
public void testLibrarySubscriptionPersist() {
Student student = studentRepository.findById(100L).get();
StudentSubscription librarySubscription = new LibrarySubscription();
librarySubscription.setValidFrom(//some date);
librarySubscription.setValidTo(//some date);
librarySubscription.setStudent(student);
studentSubscriptionRepository.save(librarySubscription);
}
</code></pre>
<p>On running this test I am getting the exception -</p>
<pre><code>org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist: com.springboot.data.jpa.entity.Student; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: com.springboot.data.jpa.entity.Student
</code></pre>
<p>To fix this I attach a @Transactional to the test. This fixed the above exception for detached entity, but the entity StudentSubscription and LibrarySubscription are not getting persisted to the DB. In fact the transaction is getting rolled back.</p>
<p>Getting this exception in the logs -</p>
<pre><code>INFO 3515 --- [ main] o.s.t.c.transaction.TransactionContext : Rolled back transaction for test: [DefaultTestContext@35390ee3 testClass = SpringDataJpaApplicationTests, testInstance = com.springboot.data.jpa.SpringDataJpaApplicationTests@48a12036, testMethod = testLibrarySubscriptionPersist@SpringDataJpaApplicationTests, testException = [null], mergedContextConfiguration = [MergedContextConfiguration@5e01a982 testClass = SpringDataJpaApplicationTests, locations = '{}', classes = '{class com.springboot.data.jpa.SpringDataJpaApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@18ece7f4, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@264f218, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@2462cb01, org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@928763c, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@7c3fdb62, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@1ad282e0], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.event.ApplicationEventsTestExecutionListener.recordApplicationEvents' -> false]]
</code></pre>
<p>Now I have couple of questions -</p>
<ol>
<li><p>Why am I getting detached entity exception. When we fetch an entity from the DB, Spring Data JPA must be using entityManager to fetch the entity. The fetched entity gets automatically attached to the persistence context right ?</p>
</li>
<li><p>On attaching @Transactional on the test, why the transaction is getting rolledback, and no entity is getting persisted. I was expecting the two entities - StudentSubscription and LibrarySubscription should've been persisted using the joined table inheritance approach.</p>
</li>
</ol>
<p>I tried many things but no luck. Seeking help from, JPA and Spring DATA experts :-)</p>
<p>Thanks in advance.</p>
| [
{
"answer_id": 74411904,
"author": "Davide D'Alto",
"author_id": 2404683,
"author_profile": "https://Stackoverflow.com/users/2404683",
"pm_score": 0,
"selected": false,
"text": "studentRepository.findById(100L).get();"
},
{
"answer_id": 74432939,
"author": "Oliver Drotbohm",
"author_id": 18122,
"author_profile": "https://Stackoverflow.com/users/18122",
"pm_score": 3,
"selected": false,
"text": "Student"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5034750/"
] |
74,411,614 | <pre><code>package main
import "fmt"
func Reverse(str string) string {
r := ""
for i := len(str) - 1; i >= 0; i-- {
r += string(str[i])
// fmt.Println(r)
}
return r
}
func Generate(str string) string {
str = Reverse(str)
// vowel := ""
for _, rne := range str {
if rne == 'a' {
str += "A"
}
if rne == 'e' {
str += "E"
}
if rne == 'i' {
str += "I"
}
if rne == 'o' {
str += "O"
}
if rne == 'u' {
str += "U"
}
}
return Reverse(str)
}
</code></pre>
<pre><code>func main() {
fmt.Println(...("haigolang123"))
}
</code></pre>
<p>This program will accept a logic from the previous function, then combine it with the next function.
I wondering how to invoke a function from the result of another function.
expect output is "321gnAlOgIAh"</p>
| [
{
"answer_id": 74411904,
"author": "Davide D'Alto",
"author_id": 2404683,
"author_profile": "https://Stackoverflow.com/users/2404683",
"pm_score": 0,
"selected": false,
"text": "studentRepository.findById(100L).get();"
},
{
"answer_id": 74432939,
"author": "Oliver Drotbohm",
"author_id": 18122,
"author_profile": "https://Stackoverflow.com/users/18122",
"pm_score": 3,
"selected": false,
"text": "Student"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20267588/"
] |
74,411,652 | <p>I'm trying to concatenate a number to the last dimension of a (None, 10, 3) tensor to make it a (None, 10, 4) tensor using a custom layer. It seems impossible, because to concatenate, all the dimensions except for the one being merged on must be equal and we can't initialize a tensor with 'None' as the first dimension.</p>
<p>For example, the code below gives me this error:</p>
<pre><code>ValueError: Shape must be rank 3 but is rank 2 for '{{node position_embedding_concat_37/concat}} = ConcatV2[N=2, T=DT_FLOAT, Tidx=DT_INT32](Placeholder, position_embedding_concat_37/concat/values_1, position_embedding_concat_37/concat/axis)' with input shapes: [?,10,3], [10,1], []
</code></pre>
<pre><code>
class PositionEmbeddingConcat(tf.keras.layers.Layer):
def __init__(self, sequence_length, **kwargs):
super(PositionEmbeddingConcat, self).__init__(**kwargs)
self.positional_embeddings_array = np.arange(sequence_length).reshape(sequence_length, 1)
def call(self, inputs):
outp = tf.concat([inputs, self.positional_embeddings_array], axis = 2)
return outp
seq_len = 10
input_layer = Input(shape = (seq_len, 3))
embedding_layer = PositionEmbeddingConcat(sequence_length = seq_len)
embeddings = embedding_layer(input_layer)
dense_layer = Dense(units = 1)
output = dense_layer(Flatten()(embeddings))
modelT = tf.keras.Model(input_layer, output)
</code></pre>
<p>Is there another way to do this?</p>
| [
{
"answer_id": 74411923,
"author": "Jirayu Kaewprateep",
"author_id": 7848579,
"author_profile": "https://Stackoverflow.com/users/7848579",
"pm_score": 0,
"selected": false,
"text": "import tensorflow as tf\n\nclass MyPositionEmbeddedLayer( tf.keras.layers.Concatenate ):\n def __init__( self, units ):\n super(MyPositionEmbeddedLayer, self).__init__( units )\n self.num_units = units\n\n def build(self, input_shape):\n self.kernel = self.add_weight(\"kernel\",\n shape=[int(input_shape[-1]),\n self.num_units])\n\n def call(self, inputs, tails):\n ### area to perform pre-calculation or custom algorithms ###\n # #\n # #\n ############################################################\n temp = tf.keras.layers.Concatenate(axis=2)([inputs, tails])\n temp = tf.matmul(temp, self.kernel)\n temp = tf.squeeze( temp )\n return temp\n\n#####################################################\n \nstart = 3\nlimit = 93\ndelta = 3\nsample = tf.range(start, limit, delta)\nsample = tf.cast( sample, dtype=tf.float32 )\nsample = tf.constant( sample, shape=( 10, 1, 3, 1 ) )\n\nstart = 3\nlimit = 33\ndelta = 3\ntails = tf.range(start, limit, delta)\ntails = tf.cast( tails, dtype=tf.float32 )\ntails = tf.constant( tails, shape=( 10, 1, 1, 1 ) )\n\nlayer = MyPositionEmbeddedLayer(10)\n\nprint( layer(sample, tails) )\n"
},
{
"answer_id": 74417060,
"author": "AloneTogether",
"author_id": 9657861,
"author_profile": "https://Stackoverflow.com/users/9657861",
"pm_score": 2,
"selected": true,
"text": "outp = tf.concat([inputs, tf.cast(tf.repeat(self.positional_embeddings_array[None, ...], repeats=tf.shape(inputs)[0], axis=0), dtype=tf.float32)], axis = 2)\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1567264/"
] |
74,411,661 | <p>I need to calculate the difference between each consecutive pairs, but all current solutions such as <code>rolling</code>, <code>diff</code>, will not jump.</p>
<p>To explain, I need to get <code>output</code> column as such</p>
<pre><code> a output
0 5 -3
1 8 -2
2 2 nan
3 4 nan
</code></pre>
<p>so (5-8) and (2-4) are my results.</p>
<p>I tried this which doesn't "jump":</p>
<pre><code>df['output'] = df['C'] - df['C'].shift(-1)
</code></pre>
| [
{
"answer_id": 74411923,
"author": "Jirayu Kaewprateep",
"author_id": 7848579,
"author_profile": "https://Stackoverflow.com/users/7848579",
"pm_score": 0,
"selected": false,
"text": "import tensorflow as tf\n\nclass MyPositionEmbeddedLayer( tf.keras.layers.Concatenate ):\n def __init__( self, units ):\n super(MyPositionEmbeddedLayer, self).__init__( units )\n self.num_units = units\n\n def build(self, input_shape):\n self.kernel = self.add_weight(\"kernel\",\n shape=[int(input_shape[-1]),\n self.num_units])\n\n def call(self, inputs, tails):\n ### area to perform pre-calculation or custom algorithms ###\n # #\n # #\n ############################################################\n temp = tf.keras.layers.Concatenate(axis=2)([inputs, tails])\n temp = tf.matmul(temp, self.kernel)\n temp = tf.squeeze( temp )\n return temp\n\n#####################################################\n \nstart = 3\nlimit = 93\ndelta = 3\nsample = tf.range(start, limit, delta)\nsample = tf.cast( sample, dtype=tf.float32 )\nsample = tf.constant( sample, shape=( 10, 1, 3, 1 ) )\n\nstart = 3\nlimit = 33\ndelta = 3\ntails = tf.range(start, limit, delta)\ntails = tf.cast( tails, dtype=tf.float32 )\ntails = tf.constant( tails, shape=( 10, 1, 1, 1 ) )\n\nlayer = MyPositionEmbeddedLayer(10)\n\nprint( layer(sample, tails) )\n"
},
{
"answer_id": 74417060,
"author": "AloneTogether",
"author_id": 9657861,
"author_profile": "https://Stackoverflow.com/users/9657861",
"pm_score": 2,
"selected": true,
"text": "outp = tf.concat([inputs, tf.cast(tf.repeat(self.positional_embeddings_array[None, ...], repeats=tf.shape(inputs)[0], axis=0), dtype=tf.float32)], axis = 2)\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18813761/"
] |
74,411,678 | <pre><code>data = [
{
'name': 'Instagram',
'follower_count': 346,
'description': 'Social media platform',
'country': 'United States'
},
{
'name': 'Cristiano Ronaldo',
'follower_count': 215,
'description': 'Footballer',
'country': 'Portugal'
}]
</code></pre>
<p>how to print follower_count of any one of tthe two given dict</p>
| [
{
"answer_id": 74411706,
"author": "Chase McDougall",
"author_id": 17985490,
"author_profile": "https://Stackoverflow.com/users/17985490",
"pm_score": 1,
"selected": false,
"text": "data[i][“follower_count”]\n"
},
{
"answer_id": 74412809,
"author": "Jethy11",
"author_id": 20440485,
"author_profile": "https://Stackoverflow.com/users/20440485",
"pm_score": 0,
"selected": false,
"text": "import random\n\ndata = [\n {\n 'name': 'Instagram',\n 'follower_count': 346,\n 'description': 'Social media platform',\n 'country': 'United States'\n },\n {\n 'name': 'Cristiano Ronaldo',\n 'follower_count': 215,\n 'description': 'Footballer',\n 'country': 'Portugal'\n }\n]\n\nx = random.randint(0,1)\nprint(data[x]['follower_count'])\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20484384/"
] |
74,411,730 | <p>I have array</p>
<pre><code> const arr = [
{id: 1, country: 'Austria'},
{id: 2, country: 'Germany'},
{id: 3, country: 'Austria'},
];
</code></pre>
<p>I tried the following the code to filter it.</p>
<pre><code>arry.map((item,idx) => (
item.country== "Austria"?(
console.log(item.id)
)
:
null
))
</code></pre>
<p>The output is</p>
<blockquote>
<p>1 3</p>
</blockquote>
<p>,
but I want to get output after whole filter like</p>
<blockquote>
<p>1,3</p>
</blockquote>
<p>I want only the IDs where country is Austria as given below.</p>
<blockquote>
<p>1,3</p>
</blockquote>
| [
{
"answer_id": 74411706,
"author": "Chase McDougall",
"author_id": 17985490,
"author_profile": "https://Stackoverflow.com/users/17985490",
"pm_score": 1,
"selected": false,
"text": "data[i][“follower_count”]\n"
},
{
"answer_id": 74412809,
"author": "Jethy11",
"author_id": 20440485,
"author_profile": "https://Stackoverflow.com/users/20440485",
"pm_score": 0,
"selected": false,
"text": "import random\n\ndata = [\n {\n 'name': 'Instagram',\n 'follower_count': 346,\n 'description': 'Social media platform',\n 'country': 'United States'\n },\n {\n 'name': 'Cristiano Ronaldo',\n 'follower_count': 215,\n 'description': 'Footballer',\n 'country': 'Portugal'\n }\n]\n\nx = random.randint(0,1)\nprint(data[x]['follower_count'])\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20424966/"
] |
74,411,746 | <p>I'm trying to check to see how many negative numbers in an arrays and check if there's any duplicate numbers in the same array.</p>
<p>Here's the code that I'm using:</p>
<pre><code>#include<stdio.h>
int main()
{
int n = 0;
int negative_count = 0;
int duplicate_count = 0;
// input lenght of the array
scanf("%d", &n);
getchar();
int arr[n];
for(int i = 0;i < n;i++){
//input elements of the array
scanf("%d", &arr[i]);
getchar();
}
int len = sizeof(arr) / sizeof(arr[0]);
for(int i=0;i<len;i++){
if(arr[i] < 0){
negative_count++;
}
for(int j= i+1;j<len;j++){
if(arr[i] == arr[j]){
duplicate_count++;
}
}
}
printf("Number of negative numbers: %d\n", negative_count);
printf("Number of duplicates: %d", duplicate_count);
return 0;
}
</code></pre>
<p>Input</p>
<pre><code>5
1 -1 2 3 -3
</code></pre>
<p>output</p>
<pre><code>Number of negative numbers: 2
Number of duplicates: 0
</code></pre>
<p>the output for the negative number is correct, but the output for the duplicate is not what I wanted. It should've output 2 because 1 and -1 boht have the number one, and so does 3 and -3. How should I go about this?</p>
| [
{
"answer_id": 74411835,
"author": "Daniel",
"author_id": 20484460,
"author_profile": "https://Stackoverflow.com/users/20484460",
"pm_score": 2,
"selected": true,
"text": "abs(-1) = 1\nabs(1) = 1\n\n\n-1 == 1 returns false\nabs(-1) == abs(1) returns true\n"
},
{
"answer_id": 74411874,
"author": "Maz Diaz",
"author_id": 17285045,
"author_profile": "https://Stackoverflow.com/users/17285045",
"pm_score": 0,
"selected": false,
"text": "#include<stdio.h>\n#include<stdlib.h>\n\nint main()\n{\nint n = 0;\nint negative_count = 0;\nint duplicate_count = 0;\n\n// input length of the array\nscanf(\"%d\", &n);\nint arr[n];\n\nfor(int i = 0;i < n;i++){\n //input elements of the array\n scanf(\"%d\", &arr[i]);\n}\n\nfor(int i=0;i<n;i++){\n if(arr[i] < 0){\n negative_count++;\n }\n for(int j= i+1;j<n;j++){\n if(abs(arr[i]) == abs(arr[j])){\n duplicate_count++;\n }\n }\n}\n\nprintf(\"Number of negative numbers: %d\\n\", error_count);\nprintf(\"Number of duplicates: %d\", duplicate_count);\n\nreturn 0;\n}\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17285045/"
] |
74,411,749 | <p>I have tried integrating in my App TTS, but there is no audio-output if I click the Button. Here is the Button code:</p>
<pre><code>struct VocabDetailView: View {
//...
var body: some View {
//...
HStack{
Button("Play") {
readOut(text: "test")
}
}
}
}
//The code from readOut is:
func readOut(text: String) {
let utterance = AVSpeechUtterance(string: text)
utterance.voice = AVSpeechSynthesisVoice(language: "en-US")
let synth = AVSpeechSynthesizer()
synth.speak(utterance)
}
</code></pre>
<p>In the Output field of Xcode is each time I click the button:</p>
<pre><code>2022-11-12 09:53:08.349877+0100 Vocab-learner[2394:64531] [plugin] AddInstanceForFactory: No factory registered for id <CFUUID 0x600000354580> F8BB1C28-BAE8-11D6-9C31-00039315CD46
2022-11-12 09:53:19.528945+0100 Vocab-learner[2394:64592] [catalog] Unable to list voice folder
2022-11-12 09:53:19.539617+0100 Vocab-learner[2394:64592] [catalog] Unable to list voice folder
2022-11-12 09:53:19.543384+0100 Vocab-learner[2394:64592] [catalog] Unable to list voice folder
2022-11-12 09:53:19.551385+0100 Vocab-learner[2394:64592] [catalog] Unable to list voice folder
2022-11-12 09:53:19.566548+0100 Vocab-learner[2394:64916] [AXTTSCommon] File file:///System/Library/PrivateFrameworks/TextToSpeechMauiSupport.framework/Resources/TTSResources/en-US/Samantha/Contents/user_rules.txt contained data that was not null terminated
2022-11-12 09:53:19.573183+0100 Vocab-learner[2394:64916] [AXTTSCommon] File file:///tmp/com.apple.mobileassetd/AssetsV2/com_apple_MobileAsset_Trial_Siri_SiriTextToSpeech/purpose_auto/253115073e2b38c109deaac3e52d26ad44a84148.asset/AssetData/vocalizer-user-dict.dat contained data that was not null terminated
</code></pre>
<p>What does that mean? What do I need to do?</p>
<p>I changed language but it does not work either.</p>
| [
{
"answer_id": 74417877,
"author": "Nerdy Bunz",
"author_id": 5717640,
"author_profile": "https://Stackoverflow.com/users/5717640",
"pm_score": 0,
"selected": false,
"text": "let tts = AVSpeechSynthesizer()\n\ntts.speak(AVSpeechUtterance(string: \"hello\"))\n"
},
{
"answer_id": 74441820,
"author": "CryptoAlgorithm",
"author_id": 13409955,
"author_profile": "https://Stackoverflow.com/users/13409955",
"pm_score": 3,
"selected": true,
"text": "AVSpeechSynthesizer"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411749",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20143530/"
] |
74,411,779 | <p>I know there are a lot Q&A regarding to this topic on SO. But in my case it is a little bit different. I have a global stylesheet <code>modal.scss</code> for restyling default bootstrap's model. I want to centre the model footer with <code>justify-content: center;</code> But it is not applying because of bootstraps folder <code>_modal.scss</code> which is setted to <code>justify-content: flex-end;</code>
<em>How can I overwrite this, or I have to make changes in <code>_modal.scss</code></em> ?</p>
<pre><code> .modal-footer {
justify-content: center;
padding: 2rem;
background-color: $color-dashboard-background;
border-top: none;
cursor: pointer;
}
</code></pre>
| [
{
"answer_id": 74417877,
"author": "Nerdy Bunz",
"author_id": 5717640,
"author_profile": "https://Stackoverflow.com/users/5717640",
"pm_score": 0,
"selected": false,
"text": "let tts = AVSpeechSynthesizer()\n\ntts.speak(AVSpeechUtterance(string: \"hello\"))\n"
},
{
"answer_id": 74441820,
"author": "CryptoAlgorithm",
"author_id": 13409955,
"author_profile": "https://Stackoverflow.com/users/13409955",
"pm_score": 3,
"selected": true,
"text": "AVSpeechSynthesizer"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15148870/"
] |
74,411,804 | <p>How to make the variable <strong><code>m_i</code></strong> have its own value for each object, and when a certain function is called, the value of <strong><code>m_i</code></strong> for all objects should be set to zero, no matter how many objects of the class <strong><code>CMyClass</code></strong> were created?</p>
<pre><code>#include <iostream>
using namespace std;
class CMyClass {
public:
static int m_i;
};
int CMyClass::m_i = 0;
CMyClass myObject1;
CMyClass myObject2;
int main() {
cout << myObject1.m_i << endl;
cout << myObject2.m_i << endl;
myObject1.m_i = 1; // set m_i to 1 for first object
cout << myObject1.m_i << endl;
cout << myObject2.m_i << endl;
myObject2.m_i = 2; // set m_i to 2 for second object
cout << myObject1.m_i << endl;
cout << myObject2.m_i << endl;
CMyClass::m_i = 0; // set m_i to zero for all objects
cout << myObject1.m_i << endl;
cout << myObject2.m_i << endl;
}
Output
0
0
1
1
2
2
0
0
</code></pre>
<p>Expected output should be:</p>
<pre><code>Output
0
0
1
0
1
2
0
0
</code></pre>
<p><strong>UPD</strong>
The solution for MCU usage was proposed by @Lasersköld and works without any additionally libraries:</p>
<pre><code>#include <iostream>
using namespace std;
class CMyClass {
public:
// The member variable should not be static because
// it is unique for each class instance.
int m_i;
};
CMyClass instances[2];
void resetInstances() {
for (auto &instance: instances) {
instance.m_i = 0;
}
}
int main() {
cout << instances[0].m_i << endl;
cout << instances[1].m_i << endl;
instances[0].m_i = 1;
cout << instances[0].m_i << endl;
cout << instances[1].m_i << endl;
instances[1].m_i = 2;
cout << instances[0].m_i << endl;
cout << instances[1].m_i << endl;
resetInstances();
cout << instances[0].m_i << endl;
cout << instances[1].m_i << endl;
}
</code></pre>
<p>Output:</p>
<pre><code>0
1
0
1
2
0
0
</code></pre>
| [
{
"answer_id": 74411876,
"author": "Lasersköld",
"author_id": 3748275,
"author_profile": "https://Stackoverflow.com/users/3748275",
"pm_score": 3,
"selected": true,
"text": "#include <iostream>\n#include <vector>\n\nusing namespace std;\nclass CMyClass {\npublic:\n\n CMyClass(int i): m_i{i} {\n instances.push_back(this);\n }\n\n // ~CMyClass() {\n // ... handle removal if nessesary. check out std::remove(...)\n // }\n\n int m_i = 0;\n\n static std::vector<CMyClass*> instances;\n\n static void reset() {\n for (auto &instance: instances) {\n instance->m_i = 0;\n }\n }\n};\n\nstd::vector<CMyClass*> CMyClass::instances;\n\nint main() {\n CMyClass myObject1{0};\n CMyClass myObject2{0};\n\n cout << myObject1.m_i << endl;\n cout << myObject2.m_i << endl;\n\n myObject1.m_i = 1;\n cout << myObject1.m_i << endl;\n cout << myObject2.m_i << endl;\n\n myObject2.m_i = 2;\n cout << myObject1.m_i << endl;\n cout << myObject2.m_i << endl;\n\n \n CMyClass::reset();\n cout << myObject1.m_i << endl;\n cout << myObject2.m_i << endl;\n}\n"
},
{
"answer_id": 74411937,
"author": "wohlstad",
"author_id": 18519921,
"author_profile": "https://Stackoverflow.com/users/18519921",
"pm_score": 0,
"selected": false,
"text": "int m_i"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13174370/"
] |
74,411,852 | <p>I want to be able to use getValue and iterate myObject keys to get the key value "f" if i input any variable.</p>
<pre><code>result = "f";
</code></pre>
<p>Or</p>
<pre><code>result = " g";
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const myObject = {
"f": [1, 2, 3, 4, 5],
"g": [6, 7, 8, 9, 10]
};
let getValueOne = 1;
function getKeyByValue() {
for (let i = 0; i < myObject[value].length; i++) {
result = myObject.key[i];
if (i === getValueOne) {
console.log(result);
}
}
}</code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74411922,
"author": "mplungjan",
"author_id": 295783,
"author_profile": "https://Stackoverflow.com/users/295783",
"pm_score": 2,
"selected": false,
"text": "const getByValue = (obj,val) => Object.entries(obj)\n .filter(([key,arr]) => arr.includes(val))\n .map(([key,arr]) => key)[0] ?? \"N/A\";\nconst myObject = {\n \"f\": [1, 2, 3, 4, 5],\n \"g\": [6, 7, 8, 9, 10]\n};\nconsole.log(getByValue(myObject,1))\nconsole.log(getByValue(myObject,99))\nconsole.log(getByValue(myObject,6))"
},
{
"answer_id": 74411984,
"author": "KooiInc",
"author_id": 58186,
"author_profile": "https://Stackoverflow.com/users/58186",
"pm_score": 0,
"selected": false,
"text": "Array.find"
},
{
"answer_id": 74417066,
"author": "vitaly-t",
"author_id": 1102051,
"author_profile": "https://Stackoverflow.com/users/1102051",
"pm_score": 0,
"selected": false,
"text": "Map"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20484321/"
] |
74,411,890 | <p>I have a state variable <code>stock_data</code> having an array of details of all stock. Structure:</p>
<pre><code> {
"scrip_code": 506235,
"short_name": "ALEMBICLTD",
"Ex_date": "12 Sep 2022",
"Purpose": "Dividend - Rs. - 1.8000",
"RD_Date": "13 Sep 2022",
"BCRD_FROM": "",
"BCRD_TO": "",
"ND_START_DATE": "06 Sep 2022",
"ND_END_DATE": "12 Sep 2022",
"payment_date": "",
"exdate": "20220912",
"long_name": "ALEMBIC LTD."
},
</code></pre>
<p>I want to filter that data out. I need to add some new key value pairs too (<code>div_or_share</code> and <code>div_amount</code>).</p>
<p>My approach was to make a new array variable <code>myNewData</code> and mapping from state variable <code>stock_data</code>:</p>
<pre><code> const [stock_data, setStockData] = useState([]);
var myNewData = [];
const makeMyNewData = () => {
console.log("in makeMyNewData with stock_data:", stock_data);
stock_data.map((item) => {
var [first, rest, end] = item.Purpose.split("-");
var newObject = {
short_name: item.short_name,
long_name: item.long_name,
div_or_share: first,
Ex_date: item.Ex_date,
div_amount: isNaN(Number(end))
? "-"
: "Rs. " + Number(end).toFixed(2)
};
console.log("newObject:", newObject);
myNewData.push(newObject);
});
}
const fetch_BSE_Data = () => {
console.log("fetching data");
return fetch(
"https://api.bseindia.com/BseIndiaAPI/api/DefaultData/w?Fdate=20220912&Purposecode=P9&TDate=20221216&ddlcategorys=E&ddlindustrys=&scripcode=&segment=0&strSearch=S"
)
.then((response) => response.json())
.then((data) => setStockData(data))
};
</code></pre>
<p>I am fetching the data and storing in <code>stock_data</code> variable using <code>fetch_BSE_Data()</code>, but the <code>console.log</code> below shows that it's empty. So, while calling <code>makeMyNewData()</code>, <code>stock_data</code> is empty:</p>
<pre><code> useEffect(() => {
fetch_BSE_Data()
console.log("after fetching stock_data:", stock_data);
makeMyNewData();
setStockData(myNewData);
}, []);
</code></pre>
<p>I want to send this updated <code>stock_data</code> to a child component:</p>
<pre><code> <DividendCalendar stock_data={stock_data} />
</code></pre>
<p>How to resolve this?</p>
<p>Also, the <code>props.stock_data</code> has the original unfiltered data when logged in console, but when I try to initialize a state variable in <code>DividendCalendar</code>, the <code>div_cal_data</code> also turns out to be empty by the console log below:</p>
<p>In <code>DividendCalendar</code> component:</p>
<pre><code> var [div_cal_data, setDivCalData] = useState(props.stock_data);
console.log("div_cal_data", div_cal_data);
</code></pre>
<p>Can someone help me with this?</p>
| [
{
"answer_id": 74412132,
"author": "Azzy",
"author_id": 2122822,
"author_profile": "https://Stackoverflow.com/users/2122822",
"pm_score": 1,
"selected": false,
"text": " useEffect(() => {\n\n const fetch_BSE_Data = async () => {\n console.log(\"fetching data\");\n return await fetch(\n \"https://api.bseindia.com/BseIndiaAPI/api/DefaultData/w?Fdate=20220912&Purposecode=P9&TDate=20221216&ddlcategorys=E&ddlindustrys=&scripcode=&segment=0&strSearch=S\"\n )\n .then((response) => response.json())\n // .then((data) => setStockData(data))\n };\n\n const async fetchData async () => {\n const response = await fetch_BSE_Data()\n const mappedItems = makeMyNewData(response);\n // this will replace the data,\n setStockData(mappedItems);\n // if you need to update/add to existing items then use map again\n setStockData(existing => {\n // logic to update existing items and insert new ones\n // [check React js new docs][1] \n });\n }\n\n fetchData();\n \n }, []);\n"
},
{
"answer_id": 74412147,
"author": "Sudhanva M",
"author_id": 13221168,
"author_profile": "https://Stackoverflow.com/users/13221168",
"pm_score": 0,
"selected": false,
"text": "fetch_BSE_Data"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13037132/"
] |
74,411,925 | <p>I have Core project where I need to do some cryptographic operations, e.g. verification of SHA256. What can I do if it's Core project, so it shouldn't depend on anything? I have to write my own cryptographic functions that are resistant to e.g. side-channel attack? This causes security problems.</p>
<p>So what to do? Can my Core project depend on a nuget package if I use Clean Architecture?</p>
| [
{
"answer_id": 74412132,
"author": "Azzy",
"author_id": 2122822,
"author_profile": "https://Stackoverflow.com/users/2122822",
"pm_score": 1,
"selected": false,
"text": " useEffect(() => {\n\n const fetch_BSE_Data = async () => {\n console.log(\"fetching data\");\n return await fetch(\n \"https://api.bseindia.com/BseIndiaAPI/api/DefaultData/w?Fdate=20220912&Purposecode=P9&TDate=20221216&ddlcategorys=E&ddlindustrys=&scripcode=&segment=0&strSearch=S\"\n )\n .then((response) => response.json())\n // .then((data) => setStockData(data))\n };\n\n const async fetchData async () => {\n const response = await fetch_BSE_Data()\n const mappedItems = makeMyNewData(response);\n // this will replace the data,\n setStockData(mappedItems);\n // if you need to update/add to existing items then use map again\n setStockData(existing => {\n // logic to update existing items and insert new ones\n // [check React js new docs][1] \n });\n }\n\n fetchData();\n \n }, []);\n"
},
{
"answer_id": 74412147,
"author": "Sudhanva M",
"author_id": 13221168,
"author_profile": "https://Stackoverflow.com/users/13221168",
"pm_score": 0,
"selected": false,
"text": "fetch_BSE_Data"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14329228/"
] |
74,411,967 | <p>I have a house icon and I want as soon as I hover over it the SVG changes to the text Home</p>
<p><strong>Demo:</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.fa-house:hover {
content: "Home";
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><li routerLink="/home"><svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="house" class="svg-inline--fa fa-house " role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512" color="#4d4d4e">
<path fill="currentColor"
d="M575.8 255.5c0 18-15 32.1-32 32.1h-32l.7 160.2c0 2.7-.2 5.4-.5 8.1V472c0 22.1-17.9 40-40 40H456c-1.1 0-2.2 0-3.3-.1c-1.4 .1-2.8 .1-4.2 .1H416 392c-22.1 0-40-17.9-40-40V448 384c0-17.7-14.3-32-32-32H256c-17.7 0-32 14.3-32 32v64 24c0 22.1-17.9 40-40 40H160 128.1c-1.5 0-3-.1-4.5-.2c-1.2 .1-2.4 .2-3.6 .2H104c-22.1 0-40-17.9-40-40V360c0-.9 0-1.9 .1-2.8V287.6H32c-18 0-32-14-32-32.1c0-9 3-17 10-24L266.4 8c7-7 15-8 22-8s15 2 21 7L564.8 231.5c8 7 12 15 11 24z">
</path>
</svg>
</li></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74412132,
"author": "Azzy",
"author_id": 2122822,
"author_profile": "https://Stackoverflow.com/users/2122822",
"pm_score": 1,
"selected": false,
"text": " useEffect(() => {\n\n const fetch_BSE_Data = async () => {\n console.log(\"fetching data\");\n return await fetch(\n \"https://api.bseindia.com/BseIndiaAPI/api/DefaultData/w?Fdate=20220912&Purposecode=P9&TDate=20221216&ddlcategorys=E&ddlindustrys=&scripcode=&segment=0&strSearch=S\"\n )\n .then((response) => response.json())\n // .then((data) => setStockData(data))\n };\n\n const async fetchData async () => {\n const response = await fetch_BSE_Data()\n const mappedItems = makeMyNewData(response);\n // this will replace the data,\n setStockData(mappedItems);\n // if you need to update/add to existing items then use map again\n setStockData(existing => {\n // logic to update existing items and insert new ones\n // [check React js new docs][1] \n });\n }\n\n fetchData();\n \n }, []);\n"
},
{
"answer_id": 74412147,
"author": "Sudhanva M",
"author_id": 13221168,
"author_profile": "https://Stackoverflow.com/users/13221168",
"pm_score": 0,
"selected": false,
"text": "fetch_BSE_Data"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19877456/"
] |
74,411,996 | <p>i was trying to set my eslint configuration up with react, typescript and astro, but seems i can't shake this error off:</p>
<p><a href="https://i.stack.imgur.com/T5VfX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/T5VfX.png" alt="enter image description here" /></a></p>
<p>Here is my <code>.eslintrc.cjs</code>, which looks like:</p>
<pre class="lang-js prettyprint-override"><code>module.exports = {
env: {
browser: true,
es2021: true
},
extends: [
'standard-with-typescript',
'plugin:astro/recommended'
],
overrides: [
{
files: ['*.astro'],
parser: 'astro-eslint-parser',
parserOptions: {
parser: '@typescript-eslint/parser',
extraFileExtensions: ['.astro']
},
rules: {
}
},
{
files: ['.jsx', '.tsx'],
extends: [
'plugin:react/recommended'
],
plugins: [
'react'
],
rules: {
'react/jsx-wrap-multilines': [2, {
declaration: 'parens-new-line',
assignment: 'parens-new-line',
return: 'parens-new-line',
arrow: 'parens-new-line',
condition: 'ignore',
logical: 'ignore',
prop: 'ignore'
}],
'react/react-in-jsx-scope': 'off',
'react/jsx-indent': [1, 2]
}
}
],
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
project: './tsconfig.json'
},
rules: {
indent: 'off',
'@typescript-eslint/indent': [1, 2],
'no-tabs': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/no-unused-vars': 'warn',
'@typescript-eslint/consistent-type-definitions': ['error', 'type'],
'@typescript-eslint/naming-convention': 'off',
'@typescript-eslint/no-floating-promises': 'off',
'@typescript-eslint/triple-slash-reference': 'off'
}
}
</code></pre>
<p>and here's my <code>tsconfig.json</code></p>
<pre class="lang-json prettyprint-override"><code>{
"extends": "astro/tsconfigs/strictest",
"compilerOptions": {
"target": "ESNext",
"useDefineForClassFields": true,
"lib": ["DOM", "DOM.Iterable", "ESNext"],
"allowJs": false,
"skipLibCheck": true,
"esModuleInterop": false,
"baseUrl": "./src/",
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "Node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": ["src"]
}
</code></pre>
<p>Any help is appreciated.</p>
<p>I tried to follow the astro-eslint setup guide this <a href="https://github.com/ota-meshi/eslint-plugin-astro" rel="nofollow noreferrer">https://github.com/ota-meshi/eslint-plugin-astro</a>, but still getting those errors.</p>
| [
{
"answer_id": 74412132,
"author": "Azzy",
"author_id": 2122822,
"author_profile": "https://Stackoverflow.com/users/2122822",
"pm_score": 1,
"selected": false,
"text": " useEffect(() => {\n\n const fetch_BSE_Data = async () => {\n console.log(\"fetching data\");\n return await fetch(\n \"https://api.bseindia.com/BseIndiaAPI/api/DefaultData/w?Fdate=20220912&Purposecode=P9&TDate=20221216&ddlcategorys=E&ddlindustrys=&scripcode=&segment=0&strSearch=S\"\n )\n .then((response) => response.json())\n // .then((data) => setStockData(data))\n };\n\n const async fetchData async () => {\n const response = await fetch_BSE_Data()\n const mappedItems = makeMyNewData(response);\n // this will replace the data,\n setStockData(mappedItems);\n // if you need to update/add to existing items then use map again\n setStockData(existing => {\n // logic to update existing items and insert new ones\n // [check React js new docs][1] \n });\n }\n\n fetchData();\n \n }, []);\n"
},
{
"answer_id": 74412147,
"author": "Sudhanva M",
"author_id": 13221168,
"author_profile": "https://Stackoverflow.com/users/13221168",
"pm_score": 0,
"selected": false,
"text": "fetch_BSE_Data"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14306019/"
] |
74,411,999 | <p>I have an appengine (Java) app with the ability to sign in via Google. For this I use
<a href="https://cloud.google.com/appengine/docs/legacy/standard/java/javadoc/com/google/appengine/api/users/UserService.html#createLoginURL-java.lang.String-" rel="nofollow noreferrer">UserServiceFactory.getUserService().createLoginURL(...)</a>.</p>
<p>This has been working fine so far, and still works well locally (using <code>mvn appengine:run</code>) but on production it consistently throws a generic 500 while on <code>/_ah/conflogin?state=~AJKiYcHHHXI45-...</code> (the 5th URL of the login process, while already being logged in with Google) and I can find nothing relevant in the Logs Explorer at <a href="https://console.cloud.google.com/logs/.." rel="nofollow noreferrer">https://console.cloud.google.com/logs/..</a>.</p>
<p>I've since even updated to the latest <a href="https://mvnrepository.com/artifact/com.google.appengine/appengine-api-1.0-sdk/2.0.10" rel="nofollow noreferrer">https://mvnrepository.com/artifact/com.google.appengine/appengine-api-1.0-sdk/2.0.10</a> but the problem remains.</p>
<p>Where should I look at to solve this issue?</p>
| [
{
"answer_id": 74412132,
"author": "Azzy",
"author_id": 2122822,
"author_profile": "https://Stackoverflow.com/users/2122822",
"pm_score": 1,
"selected": false,
"text": " useEffect(() => {\n\n const fetch_BSE_Data = async () => {\n console.log(\"fetching data\");\n return await fetch(\n \"https://api.bseindia.com/BseIndiaAPI/api/DefaultData/w?Fdate=20220912&Purposecode=P9&TDate=20221216&ddlcategorys=E&ddlindustrys=&scripcode=&segment=0&strSearch=S\"\n )\n .then((response) => response.json())\n // .then((data) => setStockData(data))\n };\n\n const async fetchData async () => {\n const response = await fetch_BSE_Data()\n const mappedItems = makeMyNewData(response);\n // this will replace the data,\n setStockData(mappedItems);\n // if you need to update/add to existing items then use map again\n setStockData(existing => {\n // logic to update existing items and insert new ones\n // [check React js new docs][1] \n });\n }\n\n fetchData();\n \n }, []);\n"
},
{
"answer_id": 74412147,
"author": "Sudhanva M",
"author_id": 13221168,
"author_profile": "https://Stackoverflow.com/users/13221168",
"pm_score": 0,
"selected": false,
"text": "fetch_BSE_Data"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74411999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/72478/"
] |
74,412,045 | <p>I run the below macro code that is capable of adding phonetic pinyin to all the selected Chinese text at once. However, that code can only add the ruby text using default settings for font and I need to modify the the font, positioning, and font size of the pinyin.</p>
<p><a href="https://github.com/wuzhuoqing/alltextphonetic/blob/master/alltext.bas" rel="nofollow noreferrer">https://github.com/wuzhuoqing/alltextphonetic/blob/master/alltext.bas</a></p>
<p>At first, I tried to toggle the field codes to change the settings, and it worked. However, when I saved, exit, and re-opened it, only positioning and font size remained changed, the font was the same before I make changes via field codes.</p>
<p>For example, the original font of the ruby text is Times New Roman. I will change it into "DengXian" by toggling field codes. Then, the ruby text's font will be changed. However, once I save and reopen the document, the ruby text's font reverts back to "Times New Roman" instead of "DengXian".</p>
<p>Is there any solutions to it? Or, is it possible to make adjustments on the macro code so that it can abandon the ruby text's default settings and adopt my own? By the way, I am tired of using only Phonetic Guide because It would cost me much of time (The document contains more than 10000 words!)</p>
<p>Thank you!</p>
| [
{
"answer_id": 74412132,
"author": "Azzy",
"author_id": 2122822,
"author_profile": "https://Stackoverflow.com/users/2122822",
"pm_score": 1,
"selected": false,
"text": " useEffect(() => {\n\n const fetch_BSE_Data = async () => {\n console.log(\"fetching data\");\n return await fetch(\n \"https://api.bseindia.com/BseIndiaAPI/api/DefaultData/w?Fdate=20220912&Purposecode=P9&TDate=20221216&ddlcategorys=E&ddlindustrys=&scripcode=&segment=0&strSearch=S\"\n )\n .then((response) => response.json())\n // .then((data) => setStockData(data))\n };\n\n const async fetchData async () => {\n const response = await fetch_BSE_Data()\n const mappedItems = makeMyNewData(response);\n // this will replace the data,\n setStockData(mappedItems);\n // if you need to update/add to existing items then use map again\n setStockData(existing => {\n // logic to update existing items and insert new ones\n // [check React js new docs][1] \n });\n }\n\n fetchData();\n \n }, []);\n"
},
{
"answer_id": 74412147,
"author": "Sudhanva M",
"author_id": 13221168,
"author_profile": "https://Stackoverflow.com/users/13221168",
"pm_score": 0,
"selected": false,
"text": "fetch_BSE_Data"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74412045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20484618/"
] |
74,412,054 | <p>I am programming an app that connects to a device via Bluetooth, but every time I want to do something with the <code>BluetoothDevice</code> I have to insert a permission check like this (Kotlin):</p>
<pre><code>if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.BLUETOOTH_CONNECT),
42
)
}
</code></pre>
<p>Is there a workaround with one single permission check in the beginning of the app?</p>
<p>Thank you!</p>
| [
{
"answer_id": 74412132,
"author": "Azzy",
"author_id": 2122822,
"author_profile": "https://Stackoverflow.com/users/2122822",
"pm_score": 1,
"selected": false,
"text": " useEffect(() => {\n\n const fetch_BSE_Data = async () => {\n console.log(\"fetching data\");\n return await fetch(\n \"https://api.bseindia.com/BseIndiaAPI/api/DefaultData/w?Fdate=20220912&Purposecode=P9&TDate=20221216&ddlcategorys=E&ddlindustrys=&scripcode=&segment=0&strSearch=S\"\n )\n .then((response) => response.json())\n // .then((data) => setStockData(data))\n };\n\n const async fetchData async () => {\n const response = await fetch_BSE_Data()\n const mappedItems = makeMyNewData(response);\n // this will replace the data,\n setStockData(mappedItems);\n // if you need to update/add to existing items then use map again\n setStockData(existing => {\n // logic to update existing items and insert new ones\n // [check React js new docs][1] \n });\n }\n\n fetchData();\n \n }, []);\n"
},
{
"answer_id": 74412147,
"author": "Sudhanva M",
"author_id": 13221168,
"author_profile": "https://Stackoverflow.com/users/13221168",
"pm_score": 0,
"selected": false,
"text": "fetch_BSE_Data"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74412054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16682019/"
] |
74,412,057 | <p>Hello and thank you for your time!</p>
<p>i have the array of objects:</p>
<pre><code>[
{ word: 'T', start: 8.87085, end: 8.88011 },
{ word: 'A', start: 8.59176, end: 8.87085 },
{ word: 'C', start: 8.39242, end: 8.59176 },
{ word: 'A', start: 8.07347, end: 8.39242 },
{ word: 'A', start: 7.87412, end: 8.07347 },
{ word: 'T', start: 7.71465, end: 7.87412 },
{ word: 'A', start: 7.51531, end: 7.71465 },
{ word: 'T', start: 7.23622, end: 7.5153 },
{ word: 'A', start: 7.11661, end: 7.23622 },
{ word: 'C', start: 6.91727, end: 7.11661 },
{ word: 'C', start: 6.63818, end: 6.91727 },
{ word: 'A', start: 6.47871, end: 6.63818 },
{ word: 'C', start: 6.39897, end: 6.47871 },
{ word: 'T', start: 5.52185, end: 6.02185 },
{ word: 'T', start: 3.76762, end: 4.26762 },
{ word: 'A', start: 3.36893, end: 3.76762 },
{ word: 'A', start: 3.04997, end: 3.36893 },
{ word: 'C', start: 2.69115, end: 3.04997 },
{ word: 'A', start: 2.57155, end: 2.69115 },
{ word: 'T', start: 2.41207, end: 2.57155 },
{ word: 'A', start: 2.21272, end: 2.29246 },
{ word: 'A', start: 1.65456, end: 2.15456 },
{ word: 'A', start: 1.45521, end: 1.65456 },
{ word: 'T', start: 1.25587, end: 1.45521 },
{ word: 'A', start: 1.01665, end: 1.25587 },
{ word: 'A', start: 0.85718, end: 1.01665 },
{ word: 'A', start: 0.61796, end: 0.85718 }
]
</code></pre>
<p>I need to cut objects in period from word == 'C' to word == 'T'.</p>
<p>Output should be like this:</p>
<pre><code>[
{ word: 'T', start: 8.87085, end: 8.88011 },
{ word: 'A', start: 8.59176, end: 8.87085 },
{ word: 'A', start: 7.51531, end: 7.71465 },
{ word: 'T', start: 7.23622, end: 7.5153 },
{ word: 'A', start: 7.11661, end: 7.23622 },
{ word: 'T', start: 3.76762, end: 4.26762 },
{ word: 'A', start: 3.36893, end: 3.76762 },
{ word: 'A', start: 3.04997, end: 3.36893 },
{ word: 'A', start: 2.21272, end: 2.29246 },
{ word: 'A', start: 1.65456, end: 2.15456 },
{ word: 'A', start: 1.45521, end: 1.65456 },
{ word: 'T', start: 1.25587, end: 1.45521 },
{ word: 'A', start: 1.01665, end: 1.25587 },
{ word: 'A', start: 0.85718, end: 1.01665 },
{ word: 'A', start: 0.61796, end: 0.85718 }
]
</code></pre>
<p>My idea is find indexes of objects 'C' and 'T' and cut this period.
But i have a problem with realization (see comments in code)</p>
<pre><code>function glue(data, t, c) {
let dataReverse = data.reverse();
for (let i = 0; i < dataReverse.length; i ++) {
let indexT = dataReverse.map(e => e.word).indexOf(c)
let indexC = dataReverse.map(e => e.word).indexOf(t)
if (indexT < indexC) { // Here the condition does not came true , but indexT = 0 and indexC = 2
dataReverse = dataReverse.splice(indexT,1) // what method better to delete the period?
} else {
dataReverse = dataReverse.splice(indexC,indexC-indexT)
}
}
</code></pre>
<p>Thanks for your idea and realization</p>
| [
{
"answer_id": 74412149,
"author": "GrafiCode",
"author_id": 5334486,
"author_profile": "https://Stackoverflow.com/users/5334486",
"pm_score": 2,
"selected": false,
"text": "Array.reduce()"
},
{
"answer_id": 74412239,
"author": "gog",
"author_id": 3494774,
"author_profile": "https://Stackoverflow.com/users/3494774",
"pm_score": 2,
"selected": false,
"text": "word-index, word-index etc"
},
{
"answer_id": 74412555,
"author": "Ben Aston",
"author_id": 38522,
"author_profile": "https://Stackoverflow.com/users/38522",
"pm_score": 0,
"selected": false,
"text": "Transform the data to remove everything between words 'C' and 'T'.\n'retrieval' is a mode that pulls items into a new array.\n'retrieve' is the action of pulling an item into a new array.\n\nInitialise `retrieval` to be turned on;\nWalk the array pulling item `curr` into a new array `result`; \n If the current word is 'C', do not retrieve `curr`, turn off `retrieval`, and continue walking;\n If current word is 'T' and retrieval is turned off, do not retrieve, but turn on retrieval;\n If retrieval is turned off, continue walking;\n Push `curr` into `result`;\nend walk\nreturn `result`\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74412057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14939936/"
] |
74,412,069 | <p>I would like to mutate a new field with a bool value if the row contains NA or not.</p>
<pre><code>mydf <- data.frame(
x = 1:5,
y = 5:1
)
mydf[4,2] <- NA
mydf[3,1] <- NA
</code></pre>
<p>I now have a data frame that looks like this:</p>
<pre><code>mydf
x y
1 1 5
2 2 4
3 NA 3
4 4 NA
5 5 1
</code></pre>
<p>I tried adding a new column to indicate if the row contains NA values:</p>
<pre><code>mydf |> mutate(has_na = complete.cases(_))
Error in mutate(mydf, has_na = complete.cases("_")) :
invalid use of pipe placeholder
</code></pre>
<p>How can I add a new column within a pipe chain that indicates whether or not the row contains an NA value?</p>
| [
{
"answer_id": 74412149,
"author": "GrafiCode",
"author_id": 5334486,
"author_profile": "https://Stackoverflow.com/users/5334486",
"pm_score": 2,
"selected": false,
"text": "Array.reduce()"
},
{
"answer_id": 74412239,
"author": "gog",
"author_id": 3494774,
"author_profile": "https://Stackoverflow.com/users/3494774",
"pm_score": 2,
"selected": false,
"text": "word-index, word-index etc"
},
{
"answer_id": 74412555,
"author": "Ben Aston",
"author_id": 38522,
"author_profile": "https://Stackoverflow.com/users/38522",
"pm_score": 0,
"selected": false,
"text": "Transform the data to remove everything between words 'C' and 'T'.\n'retrieval' is a mode that pulls items into a new array.\n'retrieve' is the action of pulling an item into a new array.\n\nInitialise `retrieval` to be turned on;\nWalk the array pulling item `curr` into a new array `result`; \n If the current word is 'C', do not retrieve `curr`, turn off `retrieval`, and continue walking;\n If current word is 'T' and retrieval is turned off, do not retrieve, but turn on retrieval;\n If retrieval is turned off, continue walking;\n Push `curr` into `result`;\nend walk\nreturn `result`\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74412069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1024586/"
] |
74,412,089 | <p>How to add special characters like <code>:</code> to array map ? I want to achieve this. <br></p>
<pre>'10': ["11/21/2022", "11/25/2022"]</pre>
<p>this is what I have so far
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const data = [{
"user_id": "10",
"dates": ["11/21/2022", "11/25/2022"]
}]
const output = data.map(({
user_id,
dates
}) => [user_id, dates]);
console.log(output);</code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74412119,
"author": "T.J. Crowder",
"author_id": 157247,
"author_profile": "https://Stackoverflow.com/users/157247",
"pm_score": 3,
"selected": true,
"text": "[\n {\n 10: [\"11/21/2022\", \"11/25/2022\"]\n },\n // ...possibly others here...\n]\n"
},
{
"answer_id": 74412174,
"author": "Daniel",
"author_id": 20484460,
"author_profile": "https://Stackoverflow.com/users/20484460",
"pm_score": 0,
"selected": false,
"text": "const data = [{\n \"user_id\": \"10\",\n \"dates\": [\"11/21/2022\", \"11/25/2022\"]\n}]\n\nconst output = data.map(({\n user_id,\n dates\n}) => [user_id, dates]);\nconsole.log(`'${output[0][0]}': [\"${output[0][1][0]}, ${output[0][1][1]}\"]`);"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74412089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17919686/"
] |
74,412,116 | <p>My Python code takes a bank statement from Excel and creates a dataframe that categorises each transaction based on description.</p>
<p>Example code:</p>
<pre><code>import pandas as pd
import openpyxl
import datetime as dt
import numpy as np
dff = pd.DataFrame({'Date': ['20221003', '20221005'],
'Tran Type': ['BOOK TRANSFER CREDIT', 'ACH DEBIT'],
'Debit Amount': [0.00, -220000.00],
'Credit Amount': [182.90, 0.0],
'Description': ['BOOK TRANSFER CREDIT FROM ACCOUNT 98754877', 'USREF2548 ACH OFFSET'],
'Amount': [-220000.00, 182.90]})
</code></pre>
<p>Then the bit that adds a column that categorises it if certain words appear in the description:</p>
<pre><code>import re
dff['Category'] = dff['Description'].str.findall('Ref|BCA|Fund|Transfer', flags=re.IGNORECASE)
</code></pre>
<p>Output:
<a href="https://i.stack.imgur.com/bilsH.png" rel="nofollow noreferrer">What it looks like</a></p>
<p>But this code will not work. Any ideas why?</p>
<pre><code>pivotf = dff
pivotf = pd.pivot_table(pivotf,
index=["Date"], columns="Category",
values=['Amount'],
margins=False, margins_name="Total")
</code></pre>
<p>The error message is TypeError: unhashable type: 'list'</p>
<p>When I change columns from "Category" to anything else, it works fine. I have tried converting the column from object to string but this doesn't actually convert it.</p>
| [
{
"answer_id": 74412119,
"author": "T.J. Crowder",
"author_id": 157247,
"author_profile": "https://Stackoverflow.com/users/157247",
"pm_score": 3,
"selected": true,
"text": "[\n {\n 10: [\"11/21/2022\", \"11/25/2022\"]\n },\n // ...possibly others here...\n]\n"
},
{
"answer_id": 74412174,
"author": "Daniel",
"author_id": 20484460,
"author_profile": "https://Stackoverflow.com/users/20484460",
"pm_score": 0,
"selected": false,
"text": "const data = [{\n \"user_id\": \"10\",\n \"dates\": [\"11/21/2022\", \"11/25/2022\"]\n}]\n\nconst output = data.map(({\n user_id,\n dates\n}) => [user_id, dates]);\nconsole.log(`'${output[0][0]}': [\"${output[0][1][0]}, ${output[0][1][1]}\"]`);"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74412116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17590718/"
] |
74,412,118 | <p>I am trying to align the name to the left side but it is not working. Always displays in the center suppose I use text-align. So, How to resolve this issue?</p>
<pre><code> Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"Name",
maxLines: 1,
overflow: TextOverflow.ellipsis,
softWrap: false,
textAlign: TextAlign.left,
style: const TextStyle(fontSize: 16,color: Colors.black,fontWeight: FontWeight.bold,),
),
const SizedBox( width: 160,
child:Text(
"mynameee@gmail.com",
maxLines: 3,
overflow: TextOverflow.ellipsis,
softWrap: true,
style: const TextStyle(
fontSize: 12,
color: Colors.black,
),
),),
],
),
</code></pre>
| [
{
"answer_id": 74412123,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 2,
"selected": false,
"text": "column"
},
{
"answer_id": 74412165,
"author": "oussama zaqouri",
"author_id": 16579236,
"author_profile": "https://Stackoverflow.com/users/16579236",
"pm_score": 3,
"selected": true,
"text": "column"
},
{
"answer_id": 74412300,
"author": "7eg",
"author_id": 13311722,
"author_profile": "https://Stackoverflow.com/users/13311722",
"pm_score": 0,
"selected": false,
"text": "alignment:Alignment.center\n"
},
{
"answer_id": 74412335,
"author": "Nasr Al-Rahbi",
"author_id": 19994059,
"author_profile": "https://Stackoverflow.com/users/19994059",
"pm_score": 0,
"selected": false,
"text": "Container(\n alignment: Alignment.centerLeft,\nchild:Text('text here')\n\n)\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74412118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19099386/"
] |
74,412,128 | <p>I have a div with an image in it and next to it some text. I want the text to fit properly into the box, which works fine with my normal screen size. Unfortunatly the text overflows the box if I look at the webiste in 1280x720 (smaller screen size).</p>
<p>This is how my website look in 1440x2560<a href="https://i.stack.imgur.com/gydct.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gydct.png" alt="enter image description here" /></a></p>
<p>This is how it looks in 1280x720 <a href="https://i.stack.imgur.com/NTSdG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NTSdG.png" alt="enter image description here" /></a></p>
<p>This is the CSS:</p>
<pre><code>.head-container {
display: flex;
flex-direction: row;
}
.container {
background-color: #F6E9DA;
position: relative;
top: 200px;
left:50px;
display: flex;
height: 450px;
width: 1200px;
justify-content: center;
align-items: center;
border-radius: 15px;
transition: 250ms;
scale: 0.9;
}
.container2 {
background-color: #F6E9DA;
position: relative;
top: 200px;
display: flex;
height: 450px;
width: 1200px;
justify-content: center;
align-items: center;
border-radius: 15px;
transition: 250ms;
scale: 0.9;
margin-left: 100px;
}
.description p {
font-family: "Poppins";
font-size: 16px;
margin-right: 20px;
color: #617569;
}
.description h2 {
font-family: "Poppins";
font-size: 26px;
text-decoration: underline;
text-decoration-thickness: 2px;
color: #617569;
}
</code></pre>
<p>HTML:</p>
<pre><code><div class="head-container">
<div class="container">
<div class="photo">
<img src="images/sampleFace.jpg" alt="">
</div>
<div class="description">
<h2>Lorem Ipsum</h2>
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr,<br>
sed diam nonumy eirmod tempor invidunt ut labore et dolore magna<br>
aliquyam erat, sed diam voluptua.<br>
At vero eos et accusam et justo duo dolores et ea rebum.<br>
Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.<br>
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod <br>
tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.<br>
At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren,<br>
no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>
</div>
</div>
<div class="container2">
<div class="photo">
<img src="images/sampleFace2.jpg" alt="">
</div>
<div class="description">
<h2>Lorem Ipsum</h2>
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr,<br>
sed diam nonumy eirmod tempor invidunt ut labore et dolore magna<br>
aliquyam erat, sed diam voluptua.<br>
At vero eos et accusam et justo duo dolores et ea rebum.<br>
Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.<br>
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod <br>
tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.<br>
At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren,<br>
no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>
</div>
</div>
</div>
</code></pre>
<p>I tried setting a fixed height for the div that the text is in but that didnt work. I'm looking for a solution which works universally on any screen size.</p>
| [
{
"answer_id": 74412213,
"author": "MAYUR SANCHETI",
"author_id": 12238257,
"author_profile": "https://Stackoverflow.com/users/12238257",
"pm_score": -1,
"selected": false,
"text": ".head-container {\n display: flex;\n flex-direction: row;\n}\n\n .container {\n background-color: #F6E9DA;\n position: relative;\n top: 200px;\n left:50px;\n height: 450px;\n width: 1200px;\n justify-content: center;\n align-items: center;\n border-radius: 15px;\n transition: 250ms;\n scale: 0.9;\n overflow: auto;\n padding: 2%;\n}\n\n.container2 {\n background-color: #F6E9DA;\n position: relative;\n top: 200px;\n height: 450px;\n width: 1200px;\n justify-content: center;\n align-items: center;\n border-radius: 15px;\n transition: 250ms;\n scale: 0.9;\n margin-left: 100px;\n overflow: auto;\n padding: 2%;\n}\n\n\n\n.description p {\n font-family: \"Poppins\";\n font-size: 16px;\n margin-right: 20px;\n color: #617569;\n}\n\n .description h2 {\n font-family: \"Poppins\";\n font-size: 26px;\n text-decoration: underline;\n text-decoration-thickness: 2px;\n color: #617569;\n }"
},
{
"answer_id": 74412259,
"author": "Sudhanva M",
"author_id": 13221168,
"author_profile": "https://Stackoverflow.com/users/13221168",
"pm_score": 0,
"selected": false,
"text": "align-items"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74412128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20407393/"
] |
74,412,130 | <p>I have this homework problem, and I'm new to python. I have this list of tuples:</p>
<p>[('the, this is me', 'the night'), ('the night', 'me'), ('me', 'the store')]</p>
<p>My code doesn't work when I'm trying to write to target_bigrams with only the tuples that have "the" in position [0]. Please help.</p>
<pre><code>target_bigrams = ()
bigrams_length = len(bigrams)
for i in range(bigrams_length):
if i[0] == target_word:
target_bigrams.append(i[0])
</code></pre>
<p></p>
| [
{
"answer_id": 74412190,
"author": "Behzad Aslani Avilaq",
"author_id": 15083206,
"author_profile": "https://Stackoverflow.com/users/15083206",
"pm_score": 0,
"selected": false,
"text": "bigrams = [('the, this is me', 'the night'), ('the night', 'me'), ('me', 'the store')]\ntarget_word = 'the'\n\ntarget_bigrams = []\nbigrams_length = len(bigrams)\n \nfor i in range(bigrams_length): \n if bigrams[i][0].startswith(target_word):\n target_bigrams.append(bigrams[i][0])\n"
},
{
"answer_id": 74412253,
"author": "S A",
"author_id": 16348606,
"author_profile": "https://Stackoverflow.com/users/16348606",
"pm_score": -1,
"selected": false,
"text": "lst = [('the, this is me', 'the night'), ('the night', 'me'), ('me', 'the store'), ('the', 'the store'),(\"the\",\"How are you\")]\n\ntarget_list = []\ntarget_word = \"the\"\nfor i in range(len(lst)):\n if target_word == lst[i][0]:\n target_list.append(lst[i])\n\nfor i in target_list:\n print(i)\n\nOutput:\n('the', 'the store')\n('the', 'How are you')\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74412130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20484604/"
] |
74,412,141 | <p>I have a .tsv file like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>sequences</th>
<th>label</th>
</tr>
</thead>
<tbody>
<tr>
<td>[[0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0],[0.0, 0.0, 1.0, 0.0],[0.0, 0.0, 1.0, 0.0],[0.0, 0.0, 1.0, 0.0],[0.0, 0.0, 1.0, 0.0]]</td>
<td>1</td>
</tr>
</tbody>
</table>
</div>
<p>I want to import the column <code>sequences</code> in pd.DataFrame as <code>np.float64</code>.</p>
<p>But it turns out like this:</p>
<pre class="lang-py prettyprint-override"><code>df = pd.read_csv('AARS.tsv', sep='\t', dtype = np.float64)
ValueError: could not convert string to float
</code></pre>
<p>I would be grateful if you can give me any suggestions!</p>
<p>Many thanks!</p>
| [
{
"answer_id": 74412190,
"author": "Behzad Aslani Avilaq",
"author_id": 15083206,
"author_profile": "https://Stackoverflow.com/users/15083206",
"pm_score": 0,
"selected": false,
"text": "bigrams = [('the, this is me', 'the night'), ('the night', 'me'), ('me', 'the store')]\ntarget_word = 'the'\n\ntarget_bigrams = []\nbigrams_length = len(bigrams)\n \nfor i in range(bigrams_length): \n if bigrams[i][0].startswith(target_word):\n target_bigrams.append(bigrams[i][0])\n"
},
{
"answer_id": 74412253,
"author": "S A",
"author_id": 16348606,
"author_profile": "https://Stackoverflow.com/users/16348606",
"pm_score": -1,
"selected": false,
"text": "lst = [('the, this is me', 'the night'), ('the night', 'me'), ('me', 'the store'), ('the', 'the store'),(\"the\",\"How are you\")]\n\ntarget_list = []\ntarget_word = \"the\"\nfor i in range(len(lst)):\n if target_word == lst[i][0]:\n target_list.append(lst[i])\n\nfor i in target_list:\n print(i)\n\nOutput:\n('the', 'the store')\n('the', 'How are you')\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74412141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16659282/"
] |
74,412,144 | <p>So i have table Project</p>
<pre><code>---------------------------------
project_id | name|
---------------------------------
1 | project 1 |
2 | project 2 |
---------------------------------
</code></pre>
<p>table 02 report</p>
<pre><code>----------------------------------------------------
report_id | report_emp | report_hours |report_project_id|
---------------------------------------------------
1 | 1 | 5 | 1 |
2 | 2 | 7 | 1 |
3 | 1 | 9 | 2 |
4 | 2 | 6 | 1 |
5 | 3 | 8 | 2 |
--------------------------------------------------
</code></pre>
<p>and table 03 emp</p>
<pre><code> ----------------------------------------------
emp_id | emp_hourly_cost | name |
-----------------------------------------------
1 | 8.5 | A |
2 | 10 | B |
3 | 12 | C |
4 | 9 | D |
5 | 7.5 | D |
-----------------------------------------------
</code></pre>
<p>as a final result i wanted to get this table</p>
<pre><code>---------------------------------------------
project | hours | total cost |
---------------------------------------------
1 | 18 | 172.5 |
2 | 17 | 172.5 |
---------------------------------------------
</code></pre>
<p>until now i only got the project with total hours but not total cost in this statement</p>
<pre><code>SELECT * from projects left join(select sum(report_hours ) as hours , daily_reports_project_id
from project_id group by report_id)x on x.report_project_id= projects.project_id;
</code></pre>
<p>total cost would be sum of all > [total hours of the project of the emp in table 2 * emp_hourly_cost in table 3 ]</p>
<p>i appreciation the help.</p>
| [
{
"answer_id": 74412190,
"author": "Behzad Aslani Avilaq",
"author_id": 15083206,
"author_profile": "https://Stackoverflow.com/users/15083206",
"pm_score": 0,
"selected": false,
"text": "bigrams = [('the, this is me', 'the night'), ('the night', 'me'), ('me', 'the store')]\ntarget_word = 'the'\n\ntarget_bigrams = []\nbigrams_length = len(bigrams)\n \nfor i in range(bigrams_length): \n if bigrams[i][0].startswith(target_word):\n target_bigrams.append(bigrams[i][0])\n"
},
{
"answer_id": 74412253,
"author": "S A",
"author_id": 16348606,
"author_profile": "https://Stackoverflow.com/users/16348606",
"pm_score": -1,
"selected": false,
"text": "lst = [('the, this is me', 'the night'), ('the night', 'me'), ('me', 'the store'), ('the', 'the store'),(\"the\",\"How are you\")]\n\ntarget_list = []\ntarget_word = \"the\"\nfor i in range(len(lst)):\n if target_word == lst[i][0]:\n target_list.append(lst[i])\n\nfor i in target_list:\n print(i)\n\nOutput:\n('the', 'the store')\n('the', 'How are you')\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74412144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9820840/"
] |
74,412,173 | <p>Why does it return <code>undefined undefined is 2 years old.</code>?</p>
<pre><code>function statement(number, name, position) {
return function(name, position){
return `${name} ${position} is ${number} years old.`;
}
}
let value = statement('two', 'ayen', 'what');
console.log(value());
</code></pre>
<p>This one returns the desirable outcome. Can somebody explain what's happening? Thanks!</p>
<pre><code>let value = statement('two');
console.log(value('ayen', 'what'));
</code></pre>
| [
{
"answer_id": 74412202,
"author": "nem035",
"author_id": 3928341,
"author_profile": "https://Stackoverflow.com/users/3928341",
"pm_score": 3,
"selected": true,
"text": "function statement(number, name, position) {\n// ^^^^ ^^^^^^^^ these are further in scope\n return function(name, position){\n // ^^^^ ^^^^^^^^ these are closer in scope\n return `${name} ${position} is ${number} years old.`;\n }\n}\n"
},
{
"answer_id": 74412357,
"author": "Larry",
"author_id": 17257136,
"author_profile": "https://Stackoverflow.com/users/17257136",
"pm_score": 1,
"selected": false,
"text": "//This is how you should write your function\n//In this example the parameters of value will not be overwriting the parameters of statement\n\nfunction statement(number, name, position) {\n return function(){\n return `${name} ${position} is ${number} years old.`;\n }\n}\n\n//Here value will equal to the inner function\nlet value = statement('two', 'ayen', 'what');\n\n//and this time value takes no parameters\n//Before when you weren't giving value parameters it was overriding ayen and what with undefined\nconsole.log(value());\n\n//This will return 'ayen what is two years old'\n\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74412173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6443564/"
] |
74,412,188 | <p>I want to change the value of "check" for particular values of "attendance"</p>
<pre><code>FirebaseFirestore.instance.collection('students').doc().set({
'doc':FirebaseFirestore.instance.collection('students').doc(),
'attendance':title,
'check':true
});
</code></pre>
<p><a href="https://i.stack.imgur.com/2dJ7o.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2dJ7o.jpg" alt="Here's the firebase database" /></a></p>
<p>What code should I use if I want to change the value of the field of that particular documents.</p>
| [
{
"answer_id": 74412202,
"author": "nem035",
"author_id": 3928341,
"author_profile": "https://Stackoverflow.com/users/3928341",
"pm_score": 3,
"selected": true,
"text": "function statement(number, name, position) {\n// ^^^^ ^^^^^^^^ these are further in scope\n return function(name, position){\n // ^^^^ ^^^^^^^^ these are closer in scope\n return `${name} ${position} is ${number} years old.`;\n }\n}\n"
},
{
"answer_id": 74412357,
"author": "Larry",
"author_id": 17257136,
"author_profile": "https://Stackoverflow.com/users/17257136",
"pm_score": 1,
"selected": false,
"text": "//This is how you should write your function\n//In this example the parameters of value will not be overwriting the parameters of statement\n\nfunction statement(number, name, position) {\n return function(){\n return `${name} ${position} is ${number} years old.`;\n }\n}\n\n//Here value will equal to the inner function\nlet value = statement('two', 'ayen', 'what');\n\n//and this time value takes no parameters\n//Before when you weren't giving value parameters it was overriding ayen and what with undefined\nconsole.log(value());\n\n//This will return 'ayen what is two years old'\n\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74412188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17022701/"
] |
74,412,199 | <p>I am creating a simple program that checks a text file for usernames and passwords. if the username and password is found a message is printed and access to granted. it returns the success message if the details are correct however when i run my code i am prompted to enter my username and password twice.</p>
<p>this is the code</p>
<pre><code>def login():
loginUsername = input("Enter Username: ")
loginPassword = input("Enter PASSWORD: ")
with open('password.txt') as data:
accounts = data.readlines()
userfound = False
for line in accounts:
splitline = line.split("\t")
if loginUsername == splitline[0] and loginPassword == splitline[1]:
userfound = True
break
return userfound
options = input("please make a choice 1 to register a new user account, 2 to login or 3 to exit to program \n")
user_found = login()
if options == "1":
register()
elif options == "2":
login()
elif options == "3":
sys.exit()
else:
print("Please make a valid choice")
if user_found:
print("LOGGED IN")
# print menu
else:
print("Login FAILED")
</code></pre>
<p>this is what happens when the program runs. in this case incorrect details were run</p>
<p>please make a choice 1 to register a new user account, 2 to login or 3 to exit to program
2
Enter Username: 22
Enter PASSWORD: ww
Enter Username: ww
Enter PASSWORD: ww
Login FAILED</p>
| [
{
"answer_id": 74412202,
"author": "nem035",
"author_id": 3928341,
"author_profile": "https://Stackoverflow.com/users/3928341",
"pm_score": 3,
"selected": true,
"text": "function statement(number, name, position) {\n// ^^^^ ^^^^^^^^ these are further in scope\n return function(name, position){\n // ^^^^ ^^^^^^^^ these are closer in scope\n return `${name} ${position} is ${number} years old.`;\n }\n}\n"
},
{
"answer_id": 74412357,
"author": "Larry",
"author_id": 17257136,
"author_profile": "https://Stackoverflow.com/users/17257136",
"pm_score": 1,
"selected": false,
"text": "//This is how you should write your function\n//In this example the parameters of value will not be overwriting the parameters of statement\n\nfunction statement(number, name, position) {\n return function(){\n return `${name} ${position} is ${number} years old.`;\n }\n}\n\n//Here value will equal to the inner function\nlet value = statement('two', 'ayen', 'what');\n\n//and this time value takes no parameters\n//Before when you weren't giving value parameters it was overriding ayen and what with undefined\nconsole.log(value());\n\n//This will return 'ayen what is two years old'\n\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74412199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18735075/"
] |
74,412,219 | <p>I have a list of 24 prices between each hour of the day and night.</p>
<p>example:</p>
<pre><code>Pricelist = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]
</code></pre>
<p>I have also imported time that returns the current time: eg. N = 13.
I want to rearrange the Pricelist so that PriceList[N] gets put at index 0 in the list, and the next price gets index N+1.</p>
<p>The goal is to get a following list if N = 13:</p>
<pre><code>Pricelist = [13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
</code></pre>
| [
{
"answer_id": 74412251,
"author": "ILS",
"author_id": 10017662,
"author_profile": "https://Stackoverflow.com/users/10017662",
"pm_score": 2,
"selected": true,
"text": "Pricelist = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]\nN = 13\n\nPricelist_new = Pricelist[N-1:] + Pricelist[:N-1]\n# [13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]\n"
},
{
"answer_id": 74412287,
"author": "A programmer ",
"author_id": 19905670,
"author_profile": "https://Stackoverflow.com/users/19905670",
"pm_score": 0,
"selected": false,
"text": "from datetime import datetime\ncurrentDateAndTime = datetime.now()\n\nN=currentDateAndTime.hour\n"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74412219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20480621/"
] |
74,412,226 | <p>I <a href="https://github.com/plasmapper/modbus-esp-cpp/issues/2" rel="nofollow noreferrer">did run into the situation</a>, that I declared two (separate) global variables with the same name in two separate files, but without using <code>static</code>, <code>volatile</code> nor <code>extern</code> on them.
One file was a .c and the other a .cpp file.</p>
<p>The compiler and build environment (GCC) was the ESP IDF and even the data types were different on these declarations.</p>
<p>mqtt_ssl.c:</p>
<pre><code>esp_mqtt_client_handle_t client;
</code></pre>
<p>mb_master.cpp:</p>
<pre><code>PL::ModbusClient client(port, PL::ModbusProtocol::rtu, 1);
</code></pre>
<p>During the runtime i experienced a lot of problems with reboots of the ESP32 until I found out, that the same name, of two actually separate variables, is causing the issue.<br />
My guess is, that the compiler used the same memory-region for both of them.</p>
<p>I expected, that it gets handled as two separate objects with its own region in the memory, which is obviously not true.<br />
After reading some questions <a href="https://stackoverflow.com/questions/63663749/redefinition-error-doesnt-happen-in-external-source-file/">here</a> and <a href="https://stackoverflow.com/questions/18991345/what-happens-if-i-declared-another-variable-with-the-same-name-in-another-file">there</a> is my understanding now is that the behavior is undefined, if a variable with the same name gets declared without <code>static</code>, <code>extern</code> or <code>volatile</code> in two separate C/C++ files.</p>
<p>It took me quite a while to figure that out.<br />
If it is not allowed to declare it like this, why didn't the compiler/linker throw an error?<br />
Is there an option for GCC to treat such a situation as error to prevent that situation in the future?</p>
<p><strong>Edit 1:</strong><br />
This is a reproducible example with xtensa-esp32-elf-gcc.exe (crosstool-NG esp-2021r2-patch3) 8.4.0.</p>
<p>app_main.c</p>
<pre><code>#include <stdio.h>
void test_sub(void);
uint16_t test1;
void app_main(void)
{
test1 = 1;
printf("app_main:test1=%d\n", test1);
test_sub();
printf("app_main:test1=%d\n", test1);
}
</code></pre>
<p>test_sub.c</p>
<pre><code>#include <stdio.h>
int16_t test1;
void test_sub(void)
{
test1 = 2;
printf("test_sub:test1=%d\n", test1);
}
</code></pre>
<p>Result:</p>
<pre><code>app_main:test1=1
test_sub:test1=2
app_main:test1=2
</code></pre>
<p><code>test1</code> in <code>app_main()</code> got overwritten by <code>test_sub()</code>, because it had the same name in both files.</p>
| [
{
"answer_id": 74413484,
"author": "Eric Postpischil",
"author_id": 298225,
"author_profile": "https://Stackoverflow.com/users/298225",
"pm_score": 2,
"selected": true,
"text": "esp_mqtt_client_handle_t client;"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74412226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6012642/"
] |
74,412,235 | <p>Tell me how to automatically connect scrolling in PySimpleGUI Multiline when the number of lines entered exceeds. For example, to enable scrolling when there are more than 5 lines</p>
<p><code>sg.Multiline(size=(42, 5))</code></p>
| [
{
"answer_id": 74420439,
"author": "RayEagle",
"author_id": 9145087,
"author_profile": "https://Stackoverflow.com/users/9145087",
"pm_score": 1,
"selected": false,
"text": "import PySimpleGUI as sg\n\n\ndef begin_window():\n layout = [[sg.Multiline(size=(42, 5), autoscroll=True)]]\n\n # Create the Window\n window = sg.Window('Title', layout)\n # window['-INDEX-'].bind(\"<Return>\", \"_Enter\")\n # Event Loop to process \"events\" and get the \"values\" of the inputs\n while True:\n event, values = window.read()\n\n if event == sg.WIN_CLOSED or event == '-CANCEL-': # if user closes window or clicks cancel\n break\n\n window.close()\n\n return\n\n\nif __name__ == '__main__':\n begin_window()\n"
},
{
"answer_id": 74421596,
"author": "Jason Yang",
"author_id": 11936135,
"author_profile": "https://Stackoverflow.com/users/11936135",
"pm_score": 1,
"selected": true,
"text": "set"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74412235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9145087/"
] |
74,412,241 | <p>im new here, i stilll dont know.. why i have to refresh first, to get the data? if i not refresh the page, data will not show up. i really struggle to solve this, please help. so many recources tell me that useeffect can cause the trouble, and i already remove it before... but the result still the same, i have to refresh first to get the data..</p>
<pre><code>const EditProfile = () => {
const [disableUsername, setDisableUsername] = useState(true);
const [disableForm, setDisableForm] = useState(true);
const [updateImage, setUpdateImage] = useState({ image: "" });
const [image, setImage] = useState("");
const userProfile = useSelector((state) => state.user);
const [form, setForm] = useState({
name: "",
username: "",
email: "",
phoneNumber: "",
gender: "",
profession: "",
nationality: "",
dateOfBirth: "",
image: "",
});
const handleTogglePhone = (e) => {
e.preventDefault();
setDisableForm(false);
};
const handleToggleUserName = (e) => {
e.preventDefault();
setDisableUsername(false);
};
const dispatch = useDispatch();
useEffect(() => {
setForm({
name: userProfile.data?.data?.name,
username: userProfile.data?.data?.username,
phoneNumber: userProfile.data?.data?.phoneNumber,
gender: userProfile.data?.data?.gender,
profession: userProfile.data?.data?.profession,
nationality: userProfile.data?.data?.nationality,
dateOfBirth: userProfile.data?.data?.dateOfBirth,
image: userProfile.data?.data?.image,
});
}, []);
const handleUpdate = (e) => {
e.preventDefault();
dispatch(updateDataUser(localStorage.getItem("idUser"), form)).then(() => {
alert(userProfile.data.message);
window.location.reload();
});
};
const handleChange = (e) => {
return setForm((prev) => {
return {
...prev,
[e.target.name]: e.target.value,
};
});
};
const handleImage = (e) => {
setUpdateImage({ image: e.target.files[0] });
setImage(URL.createObjectURL(e.target.files[0]));
};
const handleUpdateImage = (e) => {
e.preventDefault();
const formData = new FormData();
formData.append("image", updateImage.image);
dispatch(updateImageUser(localStorage.getItem("idUser"), formData))
.then((res) => {
console.log(res);
window.location.reload();
})
.catch((e) => console.log(e));
};
return (
<>
<div className="col-8 ">
<div
className="profile--section-form__container"
style={{ background: "white", borderRadius: "20px" }}
>
<h1>Profile</h1>
<form className="profile--form--input" onSubmit={handleUpdate}>
<div className="form-group d-flex">
<label htmlFor="exampleInputEmail1">Name</label>
<input
type="text"
value={form.name}
className="form-control"
placeholder="Enter name"
onChange={handleChange}
name="name"
/>
</div>
<div className="form-group d-flex">
<label htmlFor="exampleInputEmail1">Username</label>
<input
type="text"
className={`${
disableUsername ? "profile--no--border" : "form-control"
}`}
placeholder="Enter username"
name="username"
onChange={handleChange}
value={form.username}
disabled={disableUsername}
/>
{disableUsername && (
<a onClick={handleToggleUserName} href="">
Edit
</a>
)}
</div>
<div className="form-group d-flex">
<label htmlFor="exampleInputEmail1">email</label>
<input
type="email"
className="profile--no--border"
placeholder="Enter email"
name="email"
onChange={handleChange}
value={userProfile.data.data?.email}
disabled
/>
</div>
<div className="form-group d-flex">
<label htmlFor="exampleInputEmail1">Phone Number</label>
<input
disabled={disableForm}
type="text"
onChange={handleChange}
value={form.phoneNumber}
className={`${
disableForm ? "profile--no--border" : "form-control"
}`}
// placeholder="Enter phone number"
name="phoneNumber"
/>
{disableForm && (
<a onClick={handleTogglePhone} href="">
Edit
</a>
)}
</div>
<div
className="form-group d-flex gap-5"
name="gender"
onChange={handleChange}
>
<div className="form-check">
<input
className="form-check-input"
type="radio"
checked={form.gender === "Male"}
value="Male"
name="gender"
// checked={gender === "Male"}
/>{" "}
Male
</div>
<div className="form-check">
<input
className="form-check-input"
type="radio"
checked={form.gender === "Female"}
value="Female"
name="gender"
// checked={gender === "Male"}
/>{" "}
Female
</div>
</div>
<div className="form-group">
<label htmlFor="">Profession</label>
<select
className="custom-select"
name="profession"
onChange={handleChange}
defaultValue={form.profession}
>
<option selected disabled>
Open this select menu
</option>
<option
value="programmer"
selected={form.profession === "programmer"}
>
programmer
</option>
<option
value="architect"
selected={form.profession === "architect"}
>
architect
</option>
<option
value="athlete"
selected={form.profession === "athlete"}
>
athlete
</option>
<option
value="musician"
selected={form.profession === "musician"}
>
musician
</option>
</select>
</div>
<div className="form-group">
<label htmlFor="">Nationality</label>
<select
className="custom-select"
name="nationality"
onChange={handleChange}
>
<option selected>Open this select menu</option>
<option value="indonesia">Indonesia</option>
<option value="thailand">Thailand</option>
</select>
</div>
<div className="form-group">
<label htmlFor="">Birthday Date</label>
<input
type="date"
name="dateOfBirth"
value={form.dateOfBirth}
onChange={handleChange}
/>
</div>
<button type="submit" className="btn btn-primary">
Submit
</button>
</form>
</div>
</div>
<div className="col-4 ">
<form
action=""
encType="multipart/form-data"
onSubmit={updateImage.image ? handleUpdateImage : ""}
>
<div className="profile--change--user--profile__container">
<label
className="profile--change--user--profile__container--image"
htmlFor="file"
>
<i className="bi bi-camera-fill fa-2x profile--image__icon"></i>
{form.image && !image && (
<img
src={`https://res.cloudinary.com/atma-jaya-yogyakarta/image/upload/v1665891304/${userProfile.data?.data?.image}`}
alt="user image"
className="profile--container--image--user__photo"
/>
)}
{!image && !form.image ? (
<img
src={noPhoto}
alt="user image"
className="profile--container--image--user__photo"
/>
) : (
<img
src={image}
alt="user image"
className={`profile--container--image--user__photo ${
image ? "d-block" : "d-none"
}`}
/>
)}
</label>
<input
type="file"
id="file"
name="image"
className="d-none"
onChange={handleImage}
/>
{image && <img src={image} alt="view image" />}
{!updateImage.image ? (
<label
htmlFor="file"
className="btn profile--button--chose--photo__style"
>
Choose Photo
</label>
) : (
<button
htmlFor="file"
type="submit"
className="btn profile--button--chose--photo__style"
>
Save
</button>
)}
<p
style={{
color: "rgba(55, 58, 66, 0.75)",
fontSize: "0.9rem",
fontWeight: 400,
paddingTop: "2rem",
}}
>
Image size: max, 2 MB
</p>
<p
style={{
color: "rgba(55, 58, 66, 0.75)",
fontSize: "0.9rem",
fontWeight: 400,
marginTop: 0,
}}
>
Image formats: .JPG, .JPEG, .PNG
</p>
</div>
</form>
</div>
</>
);
};
```
`
</code></pre>
| [
{
"answer_id": 74420439,
"author": "RayEagle",
"author_id": 9145087,
"author_profile": "https://Stackoverflow.com/users/9145087",
"pm_score": 1,
"selected": false,
"text": "import PySimpleGUI as sg\n\n\ndef begin_window():\n layout = [[sg.Multiline(size=(42, 5), autoscroll=True)]]\n\n # Create the Window\n window = sg.Window('Title', layout)\n # window['-INDEX-'].bind(\"<Return>\", \"_Enter\")\n # Event Loop to process \"events\" and get the \"values\" of the inputs\n while True:\n event, values = window.read()\n\n if event == sg.WIN_CLOSED or event == '-CANCEL-': # if user closes window or clicks cancel\n break\n\n window.close()\n\n return\n\n\nif __name__ == '__main__':\n begin_window()\n"
},
{
"answer_id": 74421596,
"author": "Jason Yang",
"author_id": 11936135,
"author_profile": "https://Stackoverflow.com/users/11936135",
"pm_score": 1,
"selected": true,
"text": "set"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74412241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19466775/"
] |
74,412,260 | <p>I have a set of pointers to a class:</p>
<pre><code>std::set<myclass*> myset
</code></pre>
<p>In a function that gets a const myclass* ss argument, I want to search whether <strong>myset</strong> contains <strong>ss</strong>:</p>
<pre><code>bool item_in_set( const myclass *ss ) {
return myset.find( ss ) != myself.end();
}
</code></pre>
<p>This fails with an '<em>argument would lose const qualifier</em>' error.
Although it makes sense, I would expect that std::set has a way to search for items using a const qualifier but I can't find anything. To make this work I used:</p>
<pre><code>bool item_in_set( const myclass *ss ) {
return myset.find( const_cast<myclass*>( ss ) ) != myself.end();
}
</code></pre>
<p>This works but is clunky and I'm concerned that I'm missing something.</p>
<p>Is there a better way to do this, or any risks with my approach?</p>
<p>I don't want to change the signature of item_in_set() as it's pretty far in the call stack of other functions with a <em>const myclass</em>* signature (I have simplified the names in this example).</p>
<p>I'm using C++17.</p>
| [
{
"answer_id": 74412301,
"author": "HolyBlackCat",
"author_id": 2752075,
"author_profile": "https://Stackoverflow.com/users/2752075",
"pm_score": 0,
"selected": false,
"text": "std::set<myclass*, std::less<>> myset;\n"
},
{
"answer_id": 74412318,
"author": "Lasersköld",
"author_id": 3748275,
"author_profile": "https://Stackoverflow.com/users/3748275",
"pm_score": -1,
"selected": false,
"text": "std::find(...)"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74412260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1140873/"
] |
74,412,274 | <p>I am trying to define variables in a C header file. Then do work on these variables in a function and use the new values of these variables in the main function.
the code looks as follows:
C header :</p>
<pre><code>
#ifndef _myheader_h
#define _myheader_h
extern int a;
extern int b;
void get_q (int, int, char*);
#endif
</code></pre>
<p>my c source file looks like this:</p>
<pre><code>#include <stdlib.h>
#include <stdio.h>
#include "myheader.h"
#include <string.h>
int a;
int b;
void get_q (int a, int b, char* q){
if(strstr(q, "somestring1")!=NULL){
a=1;
b=0;
printf("a was chosen \n");
printf( " a= %i, b= %i \n", a, b);
return;
}else if (strstr(q, "somestring2")!=NULL){
printf("b was chosen \n");
a=0;
b=1;
return;
}else {
printf("please enter a valid q");
return;
}
}
</code></pre>
<pre><code>int main (int argc, char **argv){
get_q(a, b, argv[1]);
printf( " a = %i , b = %i \n ", a, b);
if(a){
//some function
}else if (b){
// some function
}else {
printf("no valid q was given");
}
}
</code></pre>
<p>now the problem is when I enter "somestring1" the output is:</p>
<p>//from function get_q</p>
<p>a was chosen</p>
<p>a =1 , b=0</p>
<p>//from main</p>
<p>a=0, b=0</p>
<p>no valid q was given</p>
<p>if I declared int a=0; int b=0; inside the main function. the same error happens
what am I missing here and why are the variables not visible to the main ?</p>
| [
{
"answer_id": 74412301,
"author": "HolyBlackCat",
"author_id": 2752075,
"author_profile": "https://Stackoverflow.com/users/2752075",
"pm_score": 0,
"selected": false,
"text": "std::set<myclass*, std::less<>> myset;\n"
},
{
"answer_id": 74412318,
"author": "Lasersköld",
"author_id": 3748275,
"author_profile": "https://Stackoverflow.com/users/3748275",
"pm_score": -1,
"selected": false,
"text": "std::find(...)"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74412274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13000306/"
] |
74,412,303 | <p>I tried to pass a function from the App component to another one, but it says that the function is not defined (in the child component), pretty sure I'm doing something wrong like calling the function in a wrong way but I couldn't figure it out since most answers online were using Class based components</p>
<p>App.js</p>
<pre><code>function App() {
const API_URL = "https://course-api.com/react-tours-project";
const [loading, setLoading] = useState(true);
const [data, setData] = useState([]);
async function getData() {
const response = await fetch(API_URL);
const data = await response.json();
setData(data);
setLoading(false);
}
useEffect(() => {
getData();
}, []);
const removeItemContext = React.createContext();
function removeItem(itemId) {
const newData = data.filter((object) => object.id !== itemId);
setData(newData);
}
if (loading) {
return (
<main>
<Loading />
</main>
);
}
return (
<main>
<removeItemContext.Provider value={removeItem}>
<Tours data={data} />
</removeItemContext.Provider>
</main>
);
}
export default App;
</code></pre>
<p>Tour.js (which is a grandchild)</p>
<pre><code>import React, { useContext } from "react";
import removeItemContext from "./App";
function Tour(data) {
const { id, name, info, image, price } = data;
const deleteButton = useContext(removeItemContext);
return (
<article>
<img src={image} alt={name} />
<h2>{name}</h2>
<span>{price}</span>
<p>{info}</p>
<button
onClick={() => {
removeItem(id);
}}
>
Not interested
</button>
</article>
);
}
export default Tour;
</code></pre>
| [
{
"answer_id": 74412301,
"author": "HolyBlackCat",
"author_id": 2752075,
"author_profile": "https://Stackoverflow.com/users/2752075",
"pm_score": 0,
"selected": false,
"text": "std::set<myclass*, std::less<>> myset;\n"
},
{
"answer_id": 74412318,
"author": "Lasersköld",
"author_id": 3748275,
"author_profile": "https://Stackoverflow.com/users/3748275",
"pm_score": -1,
"selected": false,
"text": "std::find(...)"
}
] | 2022/11/12 | [
"https://Stackoverflow.com/questions/74412303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20302920/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.