qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,353,924 | <p>How would one calculate a number of days in 1582. Yes, that is the year of introduction of the Georgian Calendar (in some countries). I assume October 1582 should not have 31 days as some of the dates never existed.</p>
<p>Yet when I tried Joda Time (Java/Groovy) it says 30 days:</p>
<pre class="lang-java prettyprint-override"><code>LocalDate start = new LocalDate("1582-10-01");
LocalDate end = new LocalDate("1582-10-31");
println Days.daysBetween(start, end).getDays();
</code></pre>
<p>Same for SQL</p>
<pre class="lang-sql prettyprint-override"><code>-- PostgreSQL
SELECT DATE_PART('day', '1582-10-31'::date - '1582-10-01'::timestamp);
-- MSSQL
SELECT DATEDIFF(dd, '1582-10-31', '1582-10-01');
</code></pre>
<p>So is there some agreement/specification to actually treat 1582-10-14 as if it would actually exist? Or is there some easy way to calculate correct diff for year 1582 and earlier?</p>
| [
{
"answer_id": 74402834,
"author": "Gerard Ashton",
"author_id": 4770772,
"author_profile": "https://Stackoverflow.com/users/4770772",
"pm_score": 2,
"selected": false,
"text": "LocalDate first = new LocalDate(1582, 10, 1, GJChronology.getInstance());\nLocalDate last = new LocalDate(1582, 10, 31, GJChronology.getInstance());\nint countOfDaysDiff = Days.daysBetween(first, last).getDays();\nSystem.out.println(countOfDaysDiff);\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74353924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/333296/"
] |
74,353,926 | <p>I am trying to include the Windows GNU GSL headers-only library (downloaded from <a href="https://gnuwin32.sourceforge.net/packages/gsl.htm" rel="nofollow noreferrer">https://gnuwin32.sourceforge.net/packages/gsl.htm</a>) to an example code in C++ but have lots of errors unfortunately.</p>
<p>Here is the structure of my repository:</p>
<pre><code>folder/
gsl/
gsl_sf_bessel.h
gsl_mode.h
*.h # other header files
main.cpp
CMakeLists.txt
</code></pre>
<p>main.cpp is as such:</p>
<pre><code>#include <stdio.h>
#include <gsl_sf_bessel.h>
int main (void)
{
double x = 5.0;
double y = gsl_sf_bessel_J0 (x);
printf ("J0(%g) = %.18e\n", x, y);
return 0;
}
</code></pre>
<p>and CMakeLists.txt:</p>
<pre><code>cmake_minimum_required(VERSION 3.0.0)
project(demoproject VERSION 0.1.0)
add_executable(
demoexecutable
main.cpp
)
target_include_directories(
demoexecutable
PUBLIC
gsl/
)
</code></pre>
<p>The error I get when compiling is main.cpp is:</p>
<pre><code>fatal error: gsl/gsl_mode.h: No such file or directory
[build] 26 | #include <gsl/gsl_mode.h>
</code></pre>
<p>It looks like it managed to find <code>gsl_sf_bessel.h</code> from <code>gsl/</code> but <code>gsl_sf_bessel.h</code> needs in its turn <code>gsl_mode.h</code> which the compiler cannot find. Any ideas on how to solve this issue?</p>
<p>I tried different combinations in CMakeLists.txt of functions such as <code>add_library</code>, <code>include_directories</code>, <code>target_link_libraries</code> but nothing worked unfortunately.</p>
| [
{
"answer_id": 74402834,
"author": "Gerard Ashton",
"author_id": 4770772,
"author_profile": "https://Stackoverflow.com/users/4770772",
"pm_score": 2,
"selected": false,
"text": "LocalDate first = new LocalDate(1582, 10, 1, GJChronology.getInstance());\nLocalDate last = new LocalDate(1582, 10, 31, GJChronology.getInstance());\nint countOfDaysDiff = Days.daysBetween(first, last).getDays();\nSystem.out.println(countOfDaysDiff);\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74353926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13502264/"
] |
74,353,952 | <p>Am I not seeing the forest for the trees?</p>
<p>Delphi returns <code>''</code> on <code>inifile.ReadString()</code> instead of the supplied default parameter. According to the help, it should return the default when either section, key, or value are missing.</p>
<p>I am pretty sure I have used this a number of times before without any issues before.</p>
<pre><code>unit Unit1;
interface
uses
Classes, System.SysUtils, Inifiles, Dialogs;
implementation
const
DRIVE_SECTION = 'USB_Drives';
DRIVE_LETTER = 'DriveLetter';
INI_NAME = 'c:\temp\test.ini';
//--------------------------------------------------------
procedure CreateDefaultInifile(const IniName: TFileName);
var
slist: TStringList;
begin
slist := TStringList.Create;
try
slist.Add('[' + DRIVE_SECTION + ']');
slist.Add(DRIVE_LETTER + ' = ');
//
slist.SaveToFile(IniName);
finally
slist.Free;
end;
end;
begin
if not FileExists(INI_NAME) then
CreateDefaultInifile(INI_NAME);
// now we have an inifile with a key that has no value
var ini := TIniFile.Create(INI_NAME);
Showmessage(ini.ReadString(DRIVE_SECTION, DRIVE_LETTER, 'Missing_Value'));
// according to Delphi's help, the default ('Missing_Value' in this case) should be returned if no value is assigned!
ini.Free;
end.
end.
</code></pre>
| [
{
"answer_id": 74354049,
"author": "Andreas Rejbrand",
"author_id": 282848,
"author_profile": "https://Stackoverflow.com/users/282848",
"pm_score": 3,
"selected": false,
"text": "[USB_Drives]\nDriveLetter = \n"
},
{
"answer_id": 74354166,
"author": "Remy Lebeau",
"author_id": 65863,
"author_profile": "https://Stackoverflow.com/users/65863",
"pm_score": 2,
"selected": false,
"text": "TIniFile.ReadString()"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74353952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13830610/"
] |
74,353,959 | <p>Im trying to have 3 images side by side in a flex container but the images are much too large and its stretching the page and creating a scroll bar.Tried a tip to use flex wrap but that didn't work.Should I just resize in photoshop?<a href="https://i.stack.imgur.com/tcWrP.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tcWrP.jpg" alt="enter image description here" /></a>.</p>
<pre><code><section class="main-content">
<div class="image">
<img src="img/devil-ivy-can.jpg">
</div>
<div class="image">
<img src="img/krimson-princess-can.jpg">
</div>
<div class="image">
<img src="img/spiderwort-can.jpg">
</div>
</section>
</code></pre>
<pre><code>.main-content{
display: flex;
}
div{
width:100%;
padding:10px;
margin:10px;
}
</code></pre>
| [
{
"answer_id": 74354052,
"author": "Kevon",
"author_id": 766684,
"author_profile": "https://Stackoverflow.com/users/766684",
"pm_score": 1,
"selected": true,
"text": " .container {\n display: flex;\n flex-wrap: wrap;\n background-color: grey;\n }\n\n img {\n width: 100%;\n }\n\n div {\n flex: 1;\n padding: 10px;\n margin: 10px;\n }\n\n\n <section class=\"container\">\n \n <div class=\"image\">\n <img src=\"https://atlas-content1-cdn.pixelsquid.com/assets_v2/127/1273408777629996108/jpeg-600/G13.jpg\">\n </div>\n \n <div class=\"image\">\n <img src=\"https://atlas-content1-cdn.pixelsquid.com/assets_v2/127/1273408777629996108/jpeg-600/G13.jpg\">\n </div>\n\n <div class=\"image\">\n <img src=\"https://atlas-content1-cdn.pixelsquid.com/assets_v2/127/1273408777629996108/jpeg-600/G13.jpg\">\n </div>\n </section>\n"
},
{
"answer_id": 74355034,
"author": "Ilham Nopi Hendri",
"author_id": 14158852,
"author_profile": "https://Stackoverflow.com/users/14158852",
"pm_score": 1,
"selected": false,
"text": ".main-content{\n display: flex;\n gap:10px\n}\ndiv{\n width:100%;\n gap:10px;\n\n}div.image img{\n width:100%;\n object-fit:cover;\n}"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74353959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7853503/"
] |
74,353,981 | <p>I have searched Stack Overflow for all search terms I am familiar with and have been successful creating a single row User Name/Password/Submit solution WITH two-stacked rows in-line showing an opportunity to "Remember Me" (checkbox) and a "Forgot Password?".</p>
<p><a href="https://i.stack.imgur.com/6jBZK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6jBZK.png" alt="This is what I am attempting to accomplish:" /></a></p>
<p>The code I used to build this uses a Table structure and I am wondering if this is the best method given all the HTML5 and CSS enhancements (that I may not be familiar with). Is there a better (or more modern) approach to this that would be recommended to ensure strong browser support? Here is the code I've used thus far:</p>
<pre class="lang-html prettyprint-override"><code><input type="email" name="email_address" id="email_address" tabindex="1" placeholder="Enter your EMAIL address">
<input type="password" name="password" id="password" tabindex="2" placeholder="Enter your PASSWORD">
<table style="display:inline-table;">
<tr>
<td style="line-height:0.5; padding-top:0;">
<input type="checkbox" id="remember_me" name="remember_me">
<label style="color:#fff; font-size:70%;" for="remember_me"> Remember Me</label>
</td>
</tr>
<tr>
<td style="line-height:0.5">
<label style="color:#fff; font-size:70%;" for="remember_me">Forgot Password?</label>
</td>
</tr>
</table>
<input type="submit" name="submit" id="submit" tabindex="3" value="Login" onClick="Login();">
</code></pre>
| [
{
"answer_id": 74354052,
"author": "Kevon",
"author_id": 766684,
"author_profile": "https://Stackoverflow.com/users/766684",
"pm_score": 1,
"selected": true,
"text": " .container {\n display: flex;\n flex-wrap: wrap;\n background-color: grey;\n }\n\n img {\n width: 100%;\n }\n\n div {\n flex: 1;\n padding: 10px;\n margin: 10px;\n }\n\n\n <section class=\"container\">\n \n <div class=\"image\">\n <img src=\"https://atlas-content1-cdn.pixelsquid.com/assets_v2/127/1273408777629996108/jpeg-600/G13.jpg\">\n </div>\n \n <div class=\"image\">\n <img src=\"https://atlas-content1-cdn.pixelsquid.com/assets_v2/127/1273408777629996108/jpeg-600/G13.jpg\">\n </div>\n\n <div class=\"image\">\n <img src=\"https://atlas-content1-cdn.pixelsquid.com/assets_v2/127/1273408777629996108/jpeg-600/G13.jpg\">\n </div>\n </section>\n"
},
{
"answer_id": 74355034,
"author": "Ilham Nopi Hendri",
"author_id": 14158852,
"author_profile": "https://Stackoverflow.com/users/14158852",
"pm_score": 1,
"selected": false,
"text": ".main-content{\n display: flex;\n gap:10px\n}\ndiv{\n width:100%;\n gap:10px;\n\n}div.image img{\n width:100%;\n object-fit:cover;\n}"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74353981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17326926/"
] |
74,353,995 | <p>I'm a beginner to bash scripting and been writing a script to check different log files and I'm bit stuck here.</p>
<pre><code>clientlist=/path/to/logfile/which/consists/of/client/names
#i will grep only the client name from the file which has multiple log lines
clients=$(grep --color -i 'list of client assets:' $clientlist | cut -d":" -f1 )
echo "Clients : $clients"
#For example "Clients: Apple
# Samsung
# Nokia"
#number of clients may vary from time to time
assets=("$clients".log)
echo assets: "$assets"
</code></pre>
<p>The code above greps the client name from the log file and i'm trying to use the grepped client name (each) to construct a logfile with each client name.</p>
<p>The number of clients is indefinite and may vary from time to time.</p>
<p>The code I have returns the client name as a whole</p>
<pre><code>assets: Apple
Samsung
Nokia.log
</code></pre>
<p>and I'm bit unsure of how to cut the string and pass it on one by one to return the assets which has <code>.log</code> for each client name. How can i do this ?</p>
<pre><code>Apple.log
Samsung.log
Nokia.log
</code></pre>
| [
{
"answer_id": 74354052,
"author": "Kevon",
"author_id": 766684,
"author_profile": "https://Stackoverflow.com/users/766684",
"pm_score": 1,
"selected": true,
"text": " .container {\n display: flex;\n flex-wrap: wrap;\n background-color: grey;\n }\n\n img {\n width: 100%;\n }\n\n div {\n flex: 1;\n padding: 10px;\n margin: 10px;\n }\n\n\n <section class=\"container\">\n \n <div class=\"image\">\n <img src=\"https://atlas-content1-cdn.pixelsquid.com/assets_v2/127/1273408777629996108/jpeg-600/G13.jpg\">\n </div>\n \n <div class=\"image\">\n <img src=\"https://atlas-content1-cdn.pixelsquid.com/assets_v2/127/1273408777629996108/jpeg-600/G13.jpg\">\n </div>\n\n <div class=\"image\">\n <img src=\"https://atlas-content1-cdn.pixelsquid.com/assets_v2/127/1273408777629996108/jpeg-600/G13.jpg\">\n </div>\n </section>\n"
},
{
"answer_id": 74355034,
"author": "Ilham Nopi Hendri",
"author_id": 14158852,
"author_profile": "https://Stackoverflow.com/users/14158852",
"pm_score": 1,
"selected": false,
"text": ".main-content{\n display: flex;\n gap:10px\n}\ndiv{\n width:100%;\n gap:10px;\n\n}div.image img{\n width:100%;\n object-fit:cover;\n}"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74353995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17458112/"
] |
74,354,000 | <p>How to get parameter value to javascript variable?
As an example:</p>
<p><code><a href="page.php?id=10&value='hello'">click me</a></code></p>
<p>Here, I want to get the key named <code>id</code>, and its value <code>hello</code> to assign them to a javascript variable. How to do it?</p>
| [
{
"answer_id": 74354029,
"author": "Daniel Aranda",
"author_id": 1497103,
"author_profile": "https://Stackoverflow.com/users/1497103",
"pm_score": 2,
"selected": true,
"text": "const url_params = new URLSearchParams(window.location.search);\nconst id = url_params.get('id');\nconsole.log(id);\n"
},
{
"answer_id": 74354788,
"author": "user3459487",
"author_id": 3459487,
"author_profile": "https://Stackoverflow.com/users/3459487",
"pm_score": 0,
"selected": false,
"text": "for (let name of document.querySelectorAll(\"a\")) { \nvar Reg = /page.php\\?id=(\\d+)\\&value=%27(.*?)%27/g; \nvar Array;\nwhile ((Array = Reg.exec(name.href)) != null){\nconsole.log(Array[1]);\nconsole.log(Array[2]);\n} \n} \n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74354000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19629183/"
] |
74,354,014 | <p>Sometimes, upstream DDL changes can break downstream views (it shouldn't happen, but humans make mistakes).</p>
<p>In order to detect these defects before our stakeholders do, is there a way to automatically test the validity of all views in Snowflake?</p>
| [
{
"answer_id": 74354015,
"author": "Marco Roy",
"author_id": 4406793,
"author_profile": "https://Stackoverflow.com/users/4406793",
"pm_score": 0,
"selected": false,
"text": "EXPLAIN SELECT 1 FROM database.schema.view LIMIT 1;\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74354014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4406793/"
] |
74,354,027 | <p>Is there a way in Java script to return just the substring prior to the nth occurrence of a delimiter?</p>
<p>For example:</p>
<p>If I have a string <code>"test-123-example"</code> and want to only return the substring before the second instance of <code>"-"</code>, resulting in just <code>"test-123"</code>, is there a way to do that in one line?</p>
<p>I have tried using the <code>split()</code> function using (<code>"-"</code>) and using <code>indexOf()</code> to find the second <code>"-"</code>, but having no luck.</p>
| [
{
"answer_id": 74354047,
"author": "CertainPerformance",
"author_id": 9515207,
"author_profile": "https://Stackoverflow.com/users/9515207",
"pm_score": 0,
"selected": false,
"text": "const input = \"test-123-example\";\nconst result = input.match(/[^-]+-[^-]+/)[0];\nconsole.log(result);"
},
{
"answer_id": 74354210,
"author": "Peter Seliger",
"author_id": 2627243,
"author_profile": "https://Stackoverflow.com/users/2627243",
"pm_score": 1,
"selected": false,
"text": "'test-123-example'.split('-').slice(0,2).join('-')"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74354027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20444639/"
] |
74,354,033 | <p>I'm trying to print/console.log some values I'm exporting from two separate js files. When I console.log the said values <code>price</code> and <code>info.secTableEN</code> from their individual files it prints out successfully, but when I export thses values and try printing them out in index.js as <code>priceModule</code> and <code>nameModule</code> respectfully what I get is <code>[object Object] [object Object]</code>. What am I doing wrong?</p>
<p><strong>Index.js</strong></p>
<pre><code>const priceModule = require("./price");
const nameModule = require("./name");
console.log(nameModule + priceModule);
</code></pre>
<p><strong>nameModule.js</strong></p>
<pre><code>const puppeteer = require("puppeteer");
// Url where we get and scrape the data from
const url = "https://www.sec.gov/edgar/search/#/dateRange=custom&category=custom&startdt=2017-11-05&enddt=2022-11-07&forms=4";
let browser;
(async () => {
browser = await puppeteer.launch();
const [page] = await browser.pages();
const $ = (...args) => page.waitForSelector(...args);
const text = async (...args) =>
(await $(...args)).evaluate(el => el.textContent.trim());
await page.goto(url, {waitUntil: "domcontentloaded"});
const info = {
secTableEN: await text(".table td.entity-name"),
secTableFiled: await text(".table td.filed"),
secTableLink: await text(".table td.filetype"),
};
module.exports = info.secTableEN;
})()
.catch(err => console.error(err))
.finally(() => browser?.close());
</code></pre>
<p><strong>priceModule.js</strong></p>
<pre><code>const puppeteer = require("puppeteer");
// Url where we get and scrape the data from
const url = "https://www.sec.gov/edgar/search/#/dateRange=custom&category=custom&startdt=2017-11-05&enddt=2022-11-07&forms=4";
(async () => {
browser = await puppeteer.launch();
const [page] = await browser.pages();
const ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36";
await page.setUserAgent(ua);
await page.goto(url, {waitUntil: "domcontentloaded", timeout: 0});
const responseP = page.waitForResponse(res =>
res.status() === 200 && res.url().endsWith(".xml")
);
const a = await page.waitForSelector(".filetype .preview-file");
await a.click();
const html = await (await responseP).text();
await page.evaluate(html => document.body.outerHTML = html, html);
const price = await page.$$eval(".FormText", els =>
els.find(e => e.textContent.trim() === "$")
.parentNode
.textContent
.trim()
);
module.exports = price;
})()
.catch(err => console.error(err))
.finally(() => browser?.close());
</code></pre>
| [
{
"answer_id": 74354114,
"author": "caTS",
"author_id": 18244921,
"author_profile": "https://Stackoverflow.com/users/18244921",
"pm_score": 3,
"selected": true,
"text": "console.log({} + {}); // [object Object][object Object]\n"
},
{
"answer_id": 74354163,
"author": "ray",
"author_id": 636077,
"author_profile": "https://Stackoverflow.com/users/636077",
"pm_score": 1,
"selected": false,
"text": "+"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74354033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17164833/"
] |
74,354,046 | <p>I have a Python function that receives user input with no character limitations (spaces, special chars, etc. all allowed). It then writes the input to a DynamoDB table.</p>
<p>In relational SQL, any write transaction to a database should be parameterized to avoid SQL injection. Are there any similar best practices to avoid security issues when writing user-provided data in Dynamo?</p>
| [
{
"answer_id": 74358268,
"author": "Borislav Stoilov",
"author_id": 5625696,
"author_profile": "https://Stackoverflow.com/users/5625696",
"pm_score": 3,
"selected": true,
"text": "dynamo.scan(TableName = 'my-table', Select = 'ALL_ATTRIBUTES', \n ScanFilter = {'username': {\"AttributeValueList\": [{\"S\": \"*\"}],\n \"ComparisonOperator\": \"GT\"}})\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74354046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3614277/"
] |
74,354,055 | <p>I have a list of duplicate date ranges where I need to sum all dates unique to a campaign dates, without duplicating overlapping days.</p>
<p>For example in the data below, there are days in campaign_a running between 08/07/2022 and 15/07/2022 which overlap the 11/07/2022 and 13/07/2022 which need to not duplicate when summing.</p>
<p>The summing also needs to take the campaign name as a conditional.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>campaign</th>
<th>days</th>
<th>line_start</th>
<th>line_end</th>
</tr>
</thead>
<tbody>
<tr>
<td>campaign_a</td>
<td>108</td>
<td>14/07/2022</td>
<td>30/10/2022</td>
</tr>
<tr>
<td>campaign_a</td>
<td>61</td>
<td>31/10/2022</td>
<td>31/12/2022</td>
</tr>
<tr>
<td>campaign_a</td>
<td>2</td>
<td>11/07/2022</td>
<td>13/07/2022</td>
</tr>
<tr>
<td>campaign_a</td>
<td>2</td>
<td>8/07/2022</td>
<td>15/07/2022</td>
</tr>
<tr>
<td>campaign_a</td>
<td>108</td>
<td>14/07/2022</td>
<td>30/10/2022</td>
</tr>
<tr>
<td>campaign_a</td>
<td>61</td>
<td>31/10/2022</td>
<td>31/12/2022</td>
</tr>
<tr>
<td>campaign_a</td>
<td>2</td>
<td>11/07/2022</td>
<td>13/07/2022</td>
</tr>
<tr>
<td>campaign_a</td>
<td>2</td>
<td>8/07/2022</td>
<td>10/07/2022</td>
</tr>
<tr>
<td>campaign_b</td>
<td>108</td>
<td>14/07/2022</td>
<td>30/10/2022</td>
</tr>
<tr>
<td>campaign_b</td>
<td>61</td>
<td>31/10/2022</td>
<td>31/12/2022</td>
</tr>
<tr>
<td>campaign_b</td>
<td>2</td>
<td>11/07/2022</td>
<td>13/07/2022</td>
</tr>
<tr>
<td>campaign_b</td>
<td>2</td>
<td>8/07/2022</td>
<td>10/07/2022</td>
</tr>
<tr>
<td>campaign_b</td>
<td>108</td>
<td>14/07/2022</td>
<td>30/10/2022</td>
</tr>
<tr>
<td>campaign_b</td>
<td>61</td>
<td>31/10/2022</td>
<td>31/12/2022</td>
</tr>
<tr>
<td>campaign_b</td>
<td>2</td>
<td>11/07/2022</td>
<td>13/07/2022</td>
</tr>
<tr>
<td>campaign_b</td>
<td>2</td>
<td>8/07/2022</td>
<td>10/07/2022</td>
</tr>
<tr>
<td>campaign_b</td>
<td>108</td>
<td>14/07/2022</td>
<td>30/10/2022</td>
</tr>
<tr>
<td>campaign_b</td>
<td>61</td>
<td>31/10/2022</td>
<td>31/12/2022</td>
</tr>
<tr>
<td>campaign_b</td>
<td>2</td>
<td>11/07/2022</td>
<td>13/07/2022</td>
</tr>
<tr>
<td>campaign_b</td>
<td>2</td>
<td>8/07/2022</td>
<td>10/07/2022</td>
</tr>
</tbody>
</table>
</div> | [
{
"answer_id": 74356469,
"author": "Jos Woolley",
"author_id": 17007704,
"author_profile": "https://Stackoverflow.com/users/17007704",
"pm_score": 3,
"selected": true,
"text": "G2"
},
{
"answer_id": 74369536,
"author": "David Leal",
"author_id": 6237093,
"author_profile": "https://Stackoverflow.com/users/6237093",
"pm_score": 1,
"selected": false,
"text": "13"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74354055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7471514/"
] |
74,354,084 | <p>I have a Json file that looks like the following. I want to grab the strings of names in the "actors" list and add them to a dataframe (which is empty now, the first item added to the dataframe would be the strings of actor names as rows).</p>
<pre><code>
{
"1": {
"title": "Exodus: Gods and Kings",
"url": "https://en.wikipedia.org/wiki/Exodus%3A%20Gods%20and%20Kings",
"year": "2014",
"poster": "https://upload.wikimedia.org/wikipedia/en/thumb/c/cd/Exodus2014Poster.jpg/220px-Exodus2014Poster.jpg",
"actors": [
"Christian Bale",
"Joel Edgerton",
"John Turturro",
"Aaron Paul",
"Ben Mendelsohn",
"Sigourney Weaver",
"Ben Kingsley"
]
},
...
</code></pre>
<p>I have tried using the following python code to do this but I am unsuccesful, I beleive because I am using a function wrong or not using the right function at all. Any suggestions as to what function/method to use?</p>
<pre><code># Create dataframe from json file
df_json = pd.read_json("movies_metadata.json", encoding='latin-1')
# Create new dataframe with actor names
data = [df.iloc[4]]
df = pd.DataFrame(data)
</code></pre>
<p>I strongly beleive that my code is very poor, but have had a hard time finding how to do this when googling.</p>
<p>Tried googling all around, as well as different methods from pandas to add items to dataframes</p>
| [
{
"answer_id": 74354178,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 2,
"selected": false,
"text": "data = {\n \"1\": {\n \"title\": \"Exodus: Gods and Kings\",\n \"url\": \"https://en.wikipedia.org/wiki/Exodus%3A%20Gods%20and%20Kings\",\n \"year\": \"2014\",\n \"poster\": \"https://upload.wikimedia.org/wikipedia/en/thumb/c/cd/Exodus2014Poster.jpg/220px-Exodus2014Poster.jpg\",\n \"actors\": [\n \"Christian Bale\",\n \"Joel Edgerton\",\n \"John Turturro\",\n \"Aaron Paul\",\n \"Ben Mendelsohn\",\n \"Sigourney Weaver\",\n \"Ben Kingsley\",\n ],\n }\n}\n\ndf = pd.DataFrame(\n [actor for v in data.values() for actor in v[\"actors\"]], columns=[\"Actors\"]\n)\nprint(df)\n"
},
{
"answer_id": 74354191,
"author": "Naveed",
"author_id": 3494754,
"author_profile": "https://Stackoverflow.com/users/3494754",
"pm_score": 2,
"selected": true,
"text": "# read in the json file\ndf =pd.read_json('txt.json')\n\n\n#if you have multiple json records, each will be its own columns\n# filter the actor rows and then explode \ndf.loc['actors',:].explode()\n\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74354084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20330965/"
] |
74,354,085 | <p>In Python, I am trying to split a string until an occurence of an integer, the first occurence of integer will be included, rest will not.</p>
<p>Example strings that I will have are shown below:</p>
<p><code>SOME STRING (IT WILL ALWAYS END WITH PARANTHESIS) 2 3 ---</code> <br>
<code>SOME OTHER STRING (PARANTHESIS AGAIN) 5 --- 3</code> <br>
<code>AND SOME OTHER (AGAIN) 2 1 4</code></p>
<p>And the outputs that I need for these examples are going to be:</p>
<p><code>SOME STRING (IT WILL ALWAYS END WITH PARANTHESIS) 2</code> <br>
<code>SOME OTHER STRING (PARANTHESIS AGAIN) 5</code> <br>
<code>AND SOME OTHER (AGAIN) 2</code></p>
<p>Structure of all input strings will be in this format. Any help will be appreciated. Thank you in advance.</p>
<p>I've basically tried to split it with using spaces (" "), but it of course did not work. Then, I tried to split it with using "---" occurence, but "---" may not exist in every input, so I failed again.
I also referred to this: <a href="https://stackoverflow.com/questions/69648473/how-to-split-a-string-into-a-string-and-an-integer">How to split a string into a string and an integer?</a>
However, the answer suggests to split it using spaces, so it didn't help me.</p>
| [
{
"answer_id": 74354125,
"author": "kosciej16",
"author_id": 3361462,
"author_profile": "https://Stackoverflow.com/users/3361462",
"pm_score": 3,
"selected": true,
"text": "import re\n\ns = \"SOME STRING (IT WILL ALWAYS END WITH PARANTHESIS) 2 3 ---\"\nm = re.search(r\".*?[0-9]+\", s)\nprint(m.group(0))\n"
},
{
"answer_id": 74354155,
"author": "Alberto Garcia",
"author_id": 15647384,
"author_profile": "https://Stackoverflow.com/users/15647384",
"pm_score": 0,
"selected": false,
"text": "import re\nr = re.compile('(\\D*\\d+).*')\nr.match('SOME STRING (IT WILL ALWAYS END WITH PARANTHESIS) 2 3 -').groups()[0]\n==> 'SOME STRING (IT WILL ALWAYS END WITH PARANTHESIS) 2'\n"
},
{
"answer_id": 74354164,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 1,
"selected": false,
"text": "re"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74354085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19342178/"
] |
74,354,088 | <p>I am using <code>ajv</code> node package to validate my schemas. Supposed that a field holds an object type.</p>
<p>The object can have 3 properties: <code>"A", "B", and "C"</code>.</p>
<p>How do I specify that at least one of these properties must be defined and no other properties are allowed?</p>
| [
{
"answer_id": 74364976,
"author": "Jason Desrosiers",
"author_id": 1320693,
"author_profile": "https://Stackoverflow.com/users/1320693",
"pm_score": 0,
"selected": false,
"text": "anyOf"
},
{
"answer_id": 74382852,
"author": "Byted",
"author_id": 5032258,
"author_profile": "https://Stackoverflow.com/users/5032258",
"pm_score": 2,
"selected": true,
"text": "oneOf"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74354088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5432156/"
] |
74,354,123 | <p>This seems like a really silly question, but here I am. I am able to get my product, render the form & populate the values correctly.</p>
<p>In stead of having two methods <code>create</code> and <code>update</code> I would like to just have <code>save</code>. I am trying to figure out–based on the <code>product$</code> observable what I can look for to see if I am working with an existing product or if I am creating a new one.</p>
<pre><code>// product.component.ts
public product$ = this.productService.product$;
ngOnInit(): void {
this.product$.pipe(tap((product) => console.log('product', product))).subscribe((product) => {
this.form = new FormGroup({
name: new FormControl(product?.name, [
Validators.required,
]),
description: new FormControl(product?.description, [
Validators.required,
]),
});
});
}
...
// this is the goal
save(form: FormGroup): void {
if (form.invalid) {
return;
}
if(product$) {
this.productService.update(...);
} else {
this.productService.create(...);
}
}
</code></pre>
<p>I know I could possibly subscribe (again) to <code>product$</code> but I feel like I've already got the value I need?</p>
<ul>
<li>When creating a product, my url looks like <code>example.com/products</code></li>
<li>When updating, the url will <em>always</em> be <code>example.com/products/123</code></li>
</ul>
<p>So I thought I could do something like:</p>
<pre><code>if (this.activatedRoute.params.pipe(tap((route) => console.log(route)))) {
console.log('existing');
} else {
console.log('new');
}
</code></pre>
<p>I know I'm not able to get into the <code>pipe</code> to see what I've got, so I'm not sure what to try--but I feel like I have all of the info I need for such a simple thing. How can I check for the <code>productId</code> or something so I only need a <code>save</code> method?</p>
| [
{
"answer_id": 74354272,
"author": "ukn",
"author_id": 5041973,
"author_profile": "https://Stackoverflow.com/users/5041973",
"pm_score": 3,
"selected": true,
"text": " this.form = new FormGroup({\n name: new FormControl(product?.name, [\n Validators.required,\n ]),\n description: new FormControl(product?.description, [\n Validators.required,\n ]),\n productId: new FormControl(product?.productId, []),\n });\n"
},
{
"answer_id": 74354298,
"author": "Andrew Allen",
"author_id": 4711754,
"author_profile": "https://Stackoverflow.com/users/4711754",
"pm_score": 0,
"selected": false,
"text": "\nthis.activatedRoute.params.pipe(take(1)).subscribe((route) => {\n // get the id from route\n \n if (id) {\n console.log('existing');\n } else {\n console.log('new');\n }\n}\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74354123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3357270/"
] |
74,354,150 | <p>Any one can please help me to save a Pyspark Dataframe as csv file with multicharacter delimiter using Pandas /python.</p>
<p>Did a research and found to_csv of Pypspark/Pandas can take only 1 character delimiter and there is no option to provide multicharacter delimiter as separator.</p>
<p>dataframe.to_csv(file.csv, sep="@@")
Error: delimiter must be 1-character string</p>
<p>Link - <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_csv.html" rel="nofollow noreferrer">https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_csv.html</a></p>
<p>Please let me know if any one has implemented this kind of scenario.</p>
| [
{
"answer_id": 74354272,
"author": "ukn",
"author_id": 5041973,
"author_profile": "https://Stackoverflow.com/users/5041973",
"pm_score": 3,
"selected": true,
"text": " this.form = new FormGroup({\n name: new FormControl(product?.name, [\n Validators.required,\n ]),\n description: new FormControl(product?.description, [\n Validators.required,\n ]),\n productId: new FormControl(product?.productId, []),\n });\n"
},
{
"answer_id": 74354298,
"author": "Andrew Allen",
"author_id": 4711754,
"author_profile": "https://Stackoverflow.com/users/4711754",
"pm_score": 0,
"selected": false,
"text": "\nthis.activatedRoute.params.pipe(take(1)).subscribe((route) => {\n // get the id from route\n \n if (id) {\n console.log('existing');\n } else {\n console.log('new');\n }\n}\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74354150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19699557/"
] |
74,354,162 | <p>I built a tab that a user can close using touch events and when the tab closes I want to be able to remove event listeners. This is a little bit tricky because in my actual code there is a modal and there is a part in that dynamically inserted content that the touch events are attached to.</p>
<p>So if i have the below code</p>
<pre class="lang-js prettyprint-override"><code>const tab = document.querySelector('.tab')
function handleMove(e, tab) {
e.preventDefault()
tab.style....
}
// I add the event listener like this
// but then I can't remove it
tab.addEventListener('touchmove', e => {
handleMove(e, tab)
})
</code></pre>
<p>Below is more realistic with what I am dealing with.</p>
<pre class="lang-js prettyprint-override"><code>const swipeTab = document.querySelector('.swipeable-tab')
let y1, timeStart, timeEnd
function closeStart(e) {
e.preventDefault()
let touchLocation = e.targetTouches[0]
y1 = touchLocation.clientY
console.log({ y1 })
timeStart = e.timeStamp
}
function closeMove(e, swipeTab) {
e.preventDefault()
swipeTab.style.transform = ''
let touchLocation = e.touches[0]
let yLocation = touchLocation.clientY
if (yLocation > swipeTab.clientHeight + y1) {
yLocation = swipeTab.clientHeight + y1
}
swipeTab.style.transition = ''
let marker = yLocation - y1
console.log({ marker })
if (marker < 0) {
marker = 0
}
swipeTab.style.transform = `translate3d(0, ${marker}px, 0)`
}
function closeEnd(e, swipeTab) {
e.preventDefault()
let touchLocation = e.changedTouches[0];
let y2 = touchLocation.clientY;
let yDiff = y2 - y1;
console.log({ yDiff })
timeEnd = e.timeStamp;
timeDiff = timeEnd - timeStart;
console.log({ y2 })
console.log({ timeDiff })
if (yDiff > swipeTab.clientHeight/3 || timeDiff < 50) {
closeTab(swipeTab)
} else {
openTab(swipeTab)
}
}
function openTab(swipeTab) {
swipeTab.style.transition = `all 0.2s ease-in-out`
swipeTab.style.transform = `translate3d(0, 0%, 0)`
addCloseEventListeners(swipeTab)
}
/**
* I am trying to come up with something similar to this
*/
function closeTab(swipeTab) {
swipeTab.style.transition = `all 0.2s ease-in-out`
swipeTab.style.transform = `translate3d(0, 100%, 0)`
removeCloseEventListeners(tab)
}
function removeCloseEventListeners(swipeTab) {
swipeTab.removeEventListener('touchstart', closeStart);
swipeTab.removeEventListener('touchmove', closeMove);
swipeTab.removeEventListener('touchend', closeEnd);
}
/**
* when open(swipeTab) is called
* then the event listeners are added for closing the tab
*/
function addCloseEventListeners(swipeTab) {
swipeTab.addEventListener('touchstart', e => {
closeStart(e)
})
swipeTab.addEventListener('touchmove', e => {
closeMove(e, swipeTab)
})
swipeTab.addEventListener('touchend', e => {
closeEnd(e, swipeTab)
})
}
/**
* this is where it starts
*/
open(swipeTab)
</code></pre>
| [
{
"answer_id": 74354190,
"author": "caTS",
"author_id": 18244921,
"author_profile": "https://Stackoverflow.com/users/18244921",
"pm_score": 3,
"selected": true,
"text": "function removeCloseEventListeners(swipeTab) {\n swipeTab.removeEventListener(\"touchstart\", swipeTouchStart);\n swipeTab.removeEventListener(\"touchmove\", swipeTouchMove);\n swipeTab.removeEventListener(\"touchend\", swipeTouchEnd);\n}\n\nconst swipeTouchStart = (e) => closeStart(e);\nconst swipeTouchMove = (e) => closeMove(e, swipeTab);\nconst swipeTouchEnd = (e) => closeEnd(e, swipeTab);\n\nfunction addCloseEventListeners(swipeTab) {\n swipeTab.addEventListener(\"touchstart\", swipeTouchStart);\n swipeTab.addEventListener(\"touchmove\", swipeTouchMove);\n swipeTab.addEventListener(\"touchend\", swipeTouchEnd);\n}\n"
},
{
"answer_id": 74354356,
"author": "pilchard",
"author_id": 13762301,
"author_profile": "https://Stackoverflow.com/users/13762301",
"pm_score": 1,
"selected": false,
"text": "removeEventListener()"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74354162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17422582/"
] |
74,354,193 | <p>I have an array <code>boxSize</code> that has a total count of boxes for <code>small</code> and <code>large</code> boxes. I would like to combine these 2 separate objects into one if they have the same date and warehouse name</p>
<p>For example here is the <code>boxSize</code> array:</p>
<pre><code>const boxSize = [
{
warehouse: 'NYC',
deliveryWeek: '2022-11-07',
boxSize: 'small',
total: 5
},
{
warehouse: 'NYC',
deliveryWeek: '2022-11-07',
boxSize: 'large',
total: 9
}
]
</code></pre>
<p>I attempted to loop through the array like this in the code snippet below:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const boxSize = [
{
warehouse: 'NYC',
deliveryWeek: '2022-11-07',
boxSize: 'small',
total: 5
},
{
warehouse: 'NYC',
deliveryWeek: '2022-11-07',
boxSize: 'large',
total: 9
}
]
var obj = {};
for(let i = 0; i < boxSize.length; i++){
var date = boxSize[i].deliveryWeek;
// Get previous date saved inside the result
var p_date = obj[date] || {};
// Merge the previous date with the next date
obj[date] = Object.assign(p_date, boxSize[i]);
}
// Convert to an array
var result = Object.values(obj);
console.log(result);</code></pre>
</div>
</div>
</p>
<p>I am having trouble coming up with the logic and finding up examples to meet these requirements condition.</p>
<p>How can I end up with an array that looks something similar to this when the objects have the same <code>warehouse</code> and <code>deliveryWeek</code>:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const boxSize = [
{
warehouse: 'NYC',
deliveryWeek: '2022-11-07',
boxSizeSmall: 'small',
smallTotal: 5,
boxSizeLarge: 'large',
largeTotal: 9
}
]
console.log(boxSize)</code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74354307,
"author": "caTS",
"author_id": 18244921,
"author_profile": "https://Stackoverflow.com/users/18244921",
"pm_score": 1,
"selected": false,
"text": "const boxSize = [{warehouse:'NYC',deliveryWeek:'2022-11-07',boxSize:'small',total:5},{warehouse:'NYC',deliveryWeek:'2022-11-07',boxSize:'large',total:9}];\n\nconst keyFor = (item) => `${item.warehouse}:${item.deliveryWeek}`;\n\nconst map = new Map();\n\nboxSize.forEach((box) => {\n const key = keyFor(box);\n \n if (!map.has(key)) map.set(key, []);\n \n map.get(key).push(box);\n});\n\nconst result = Array.from(map).map(([, values]) => ({\n warehouse: values[0].warehouse,\n deliveryWeek: values[0].deliveryWeek,\n ...values.reduce((obj, item) => ({\n ...obj,\n [\"boxSize\" + item.boxSize[0].toUpperCase() + item.boxSize.slice(1)]: item.boxSize,\n [item.boxSize + \"Total\"]: item.total,\n }), {}),\n}));\n\nconsole.log(result);"
},
{
"answer_id": 74354487,
"author": "Ivan",
"author_id": 3878760,
"author_profile": "https://Stackoverflow.com/users/3878760",
"pm_score": 0,
"selected": false,
"text": "let boxSize = [ \n{ \n warehouse: 'NYC',\n deliveryWeek: '2022-11-07',\n boxSize: 'small',\n total: 5\n}, \n{\n warehouse: 'NYC',\n deliveryWeek: '2022-11-07',\n boxSize: 'large',\n total: 9\n}\n]\n\nlet combinedBoxes = [];\n\n\nfor(let i = 0; i < boxSize.length; i++){\n \n let currentBox = boxSize[i];\n \n let boxes = boxSize.filter(box => box.warehouse == currentBox.warehouse && box.deliveryWeek == currentBox.deliveryWeek)\n \n let small = boxes.filter(box => box.boxSize == \"small\")[0]\n let large = boxes.filter(box => box.boxSize == \"large\")[0]\n \n combinedBoxes.push({\n warehouse: currentBox.warehouse,\n deliveryWeek: currentBox.deliveryWeek,\n smallTotal: small.total,\n largeTotal: large.total\n })\n \n boxSize = boxSize.filter(box => box.warehouse != currentBox.warehouse && box.deliveryWeek != currentBox.deliveryWeek)\n}\n\nconsole.log(combinedBoxes)"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74354193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13366922/"
] |
74,354,256 | <p><a href="https://i.stack.imgur.com/evXp8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/evXp8.png" alt="Can someone help me combining consecutive dates in different rows as shown below" /></a></p>
<p>Can someone help me combining consecutive dates in different rows as shown above.Rows in first image are input and records in 2nd image are output.</p>
| [
{
"answer_id": 74354307,
"author": "caTS",
"author_id": 18244921,
"author_profile": "https://Stackoverflow.com/users/18244921",
"pm_score": 1,
"selected": false,
"text": "const boxSize = [{warehouse:'NYC',deliveryWeek:'2022-11-07',boxSize:'small',total:5},{warehouse:'NYC',deliveryWeek:'2022-11-07',boxSize:'large',total:9}];\n\nconst keyFor = (item) => `${item.warehouse}:${item.deliveryWeek}`;\n\nconst map = new Map();\n\nboxSize.forEach((box) => {\n const key = keyFor(box);\n \n if (!map.has(key)) map.set(key, []);\n \n map.get(key).push(box);\n});\n\nconst result = Array.from(map).map(([, values]) => ({\n warehouse: values[0].warehouse,\n deliveryWeek: values[0].deliveryWeek,\n ...values.reduce((obj, item) => ({\n ...obj,\n [\"boxSize\" + item.boxSize[0].toUpperCase() + item.boxSize.slice(1)]: item.boxSize,\n [item.boxSize + \"Total\"]: item.total,\n }), {}),\n}));\n\nconsole.log(result);"
},
{
"answer_id": 74354487,
"author": "Ivan",
"author_id": 3878760,
"author_profile": "https://Stackoverflow.com/users/3878760",
"pm_score": 0,
"selected": false,
"text": "let boxSize = [ \n{ \n warehouse: 'NYC',\n deliveryWeek: '2022-11-07',\n boxSize: 'small',\n total: 5\n}, \n{\n warehouse: 'NYC',\n deliveryWeek: '2022-11-07',\n boxSize: 'large',\n total: 9\n}\n]\n\nlet combinedBoxes = [];\n\n\nfor(let i = 0; i < boxSize.length; i++){\n \n let currentBox = boxSize[i];\n \n let boxes = boxSize.filter(box => box.warehouse == currentBox.warehouse && box.deliveryWeek == currentBox.deliveryWeek)\n \n let small = boxes.filter(box => box.boxSize == \"small\")[0]\n let large = boxes.filter(box => box.boxSize == \"large\")[0]\n \n combinedBoxes.push({\n warehouse: currentBox.warehouse,\n deliveryWeek: currentBox.deliveryWeek,\n smallTotal: small.total,\n largeTotal: large.total\n })\n \n boxSize = boxSize.filter(box => box.warehouse != currentBox.warehouse && box.deliveryWeek != currentBox.deliveryWeek)\n}\n\nconsole.log(combinedBoxes)"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74354256",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6355550/"
] |
74,354,278 | <p>Have a bit of an issue attempting to get Auth0 info on the logged-in user with our current architecture.</p>
<p>We have <code>redux</code> with <code>@reduxjs/toolkit</code> & <code>react-redux</code> as our state management tool.</p>
<p>We use <code>axios</code> to make HTTP requests via redux-thunk actions.</p>
<p>And now we have a part of our application that allows users to signup/login with <code>Auth0</code>.</p>
<p>So, an example of our problem.</p>
<p>Currently our redux store is setup with some reducers</p>
<pre><code>/* eslint-disable import/no-cycle */
import { configureStore } from '@reduxjs/toolkit';
import thunk from 'redux-thunk';
const createStore = (initialState?: any) => {
return configureStore({
reducer: {
// reducers are here
},
middleware: [thunk],
preloadedState: initialState,
});
};
export default createStore;
</code></pre>
<p>Then we attached that to a <code>Provider</code> at the base of our application</p>
<pre><code>import React from 'react';
import { Provider } from 'react-redux';
import createStore from '../store/createStore';
const App = () => {
return (
<Provider store={createStore()}>
//
</Provider>
);
};
export default App;
</code></pre>
<p>We have an axios instance function that uses <code>axios</code> to make HTTP requests and handles errors.</p>
<pre><code>import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
import { getAuthSignature } from '../utils/auth';
export const API_URL = process.env.API_HOST;
const axiosInstance = async <T = any>(requestConfig: AxiosRequestConfig): Promise<AxiosResponse<T>> => {
const { token } = await getAuthSignature();
// I need to access auth0 data here
const { getAccessTokenSilently, isAuthenticated, isLoading, loginWithRedirect, user } = auth0;
if (!token) {
const tokenErr = {
title: 'Error',
message: 'Missing Authentication Token',
success: false,
};
throw tokenErr;
}
try {
let accessToken = token;
// Update authorization token if auth0 user
if(auth0) {
if(isAuthenticcation && user) accessToken = await getAccessTokenSilently({ audience });
else loginWithRedirect();
}
const result = await axios({
...requestConfig,
headers: {
...requestConfig.headers,
authorization: `Bearer ${accessToken}`,
},
});
return result;
} catch (error: any) {
if (error.response) {
if ([401, 403].includes(error.response.status)) {
window.location = '/';
}
const contentType = error?.response?.headers?.['content-type'];
const isHTMLRes = contentType && contentType.indexOf('text/html') !== -1;
const errObj = {
status: error?.response?.status,
statusText: error?.response?.statusText,
errorMessage: isHTMLRes && error?.response?.text && (await error?.response?.text()),
error,
};
throw errObj;
}
throw error;
}
};
export default axiosInstance;
</code></pre>
<p>This in an example of a thunk action, we would have something like this that uses the axios instance mentioned above to make the HTTP requests.</p>
<pre><code>import axios, { API_URL } from '../../services/axios';
import { Result } from '../../types/test';
import { AppThunk } from '../../store/store';
import { setResults, setResultsLoading, setTableLoading } from './test.slice';
type DefaultThunk = () => AppThunk<Promise<void>>;
const getResults: DefaultThunk = () => async () => {
dispatch(setTableLoading(true));
try {
const result = await axios<Result[]>(
{
method: 'GET',
url: `${API_URL}/test`,
},
);
dispatch(setResults(result.data));
} catch (err: any) {
console.log({ err });
} finally {
dispatch(setResultsLoading(false));
dispatch(setTableLoading(false));
}
};
export default getResults;
</code></pre>
<p>We then dispatch our thunk actions to make HTTP requests and update reducer states in our React components.</p>
<pre><code>import React, { useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import getResults from '../../reducers/test/test.thunk';
const TestComponent = () => {
const dispatch = useDispatch();
useEffect(() => {
dispatch(getResults());
}, []);
return (
//
);
};
export default TestComponent;
</code></pre>
<p>My problem is that I have no idea how to integrate <code>Auth0</code> gracefully into the current flow, so I do not have to make checks in every react component that uses a thunk action.</p>
<p>Basically I need access to values within the <code>useAuth0</code> hook from <code>@auth0/auth0-react</code> for example <code>getAccessTokenSilently</code>, <code>isAuthenticated</code>, <code>user</code> & <code>loginWithRedirect</code>. Just to name a few.</p>
<p>We can't use the <code>useAuth0</code> hook in the axios instance file, as it's not a react component/hook, nor is the thunk file.</p>
<p>So I'm not sure how and where the best place is to get the data so that it is accessible in the axios file, as aforementioned without having to pass it as an argument or something in every redux thunk action.</p>
<p>Perhaps we just need a different approach to the current flow of dispatch > action > axios request?</p>
<p>Is there any way to pass this data in as middleware to redux?</p>
<p>Any help would be greatly appreciated.</p>
| [
{
"answer_id": 74523558,
"author": "Drew Reese",
"author_id": 8690857,
"author_profile": "https://Stackoverflow.com/users/8690857",
"pm_score": 2,
"selected": true,
"text": "auth0"
},
{
"answer_id": 74541644,
"author": "JMParsons",
"author_id": 535810,
"author_profile": "https://Stackoverflow.com/users/535810",
"pm_score": 0,
"selected": false,
"text": "document.getElementById('call-api').addEventListener('click', async () => {\n const accessToken = await auth0.getTokenSilently();\n const result = await fetch('https://myapi.com', {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${accessToken}`\n }\n });\n const data = await result.json();\n console.log(data);\n});\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74354278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3113377/"
] |
74,354,330 | <p>I have a large dataset with multiple rows and columns. I want to change the order of the columns by the amount of missing values in the column so that the variable with the most <code>NA</code>s is the first column and the variable with the least <code>NA</code>s is the last column.</p>
<p>So far I tried to use <code>dplyr</code>'s <code>select</code> but did not get what I wanted.</p>
<pre><code>df_ordered <- df %>%
select(order(is.na(df)))
</code></pre>
| [
{
"answer_id": 74354371,
"author": "Ric Villalba",
"author_id": 6912817,
"author_profile": "https://Stackoverflow.com/users/6912817",
"pm_score": 2,
"selected": false,
"text": "df <- df[order(-colSums(apply(df, 2, is.na)))]"
},
{
"answer_id": 74354460,
"author": "AndrewGB",
"author_id": 15293191,
"author_profile": "https://Stackoverflow.com/users/15293191",
"pm_score": 2,
"selected": false,
"text": "dplyr"
},
{
"answer_id": 74354476,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 0,
"selected": false,
"text": "mean"
},
{
"answer_id": 74354607,
"author": "Dan Adams",
"author_id": 13210554,
"author_profile": "https://Stackoverflow.com/users/13210554",
"pm_score": 0,
"selected": false,
"text": "set.seed(1)\nd <- data.frame(matrix(sample(c(1:5, NA), 49, T, prob = c(rep(1, 5), 5)), ncol = 7))\n\n# base R\nd[,order(-colSums(is.na(d)))]\n#> X4 X2 X5 X1 X3 X6 X7\n#> 1 NA 4 2 NA 5 4 5\n#> 2 4 4 NA NA NA 5 3\n#> 3 NA NA NA 3 5 NA 3\n#> 4 NA NA 3 1 1 5 5\n#> 5 NA NA NA NA NA NA NA\n#> 6 NA 4 NA 2 5 2 NA\n#> 7 NA NA 2 1 1 4 5\n\n# with tidyverse\nlibrary(dplyr)\n\nd %>% \n select(order(-colSums(is.na(.))))\n#> X4 X2 X5 X1 X3 X6 X7\n#> 1 NA 4 2 NA 5 4 5\n#> 2 4 4 NA NA NA 5 3\n#> 3 NA NA NA 3 5 NA 3\n#> 4 NA NA 3 1 1 5 5\n#> 5 NA NA NA NA NA NA NA\n#> 6 NA 4 NA 2 5 2 NA\n#> 7 NA NA 2 1 1 4 5\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74354330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20444820/"
] |
74,354,344 | <p>I have this text:</p>
<pre><code>Be sure to see if the code requires firestops in
the stud walls.* These are wood strips between
the studs that will prevent flames and hot air
from moving upward within the wall. (Some
areas require that firestopping be placed no more
than one story apart. In platform-frame con-
struction, the floor platform acts as an adequate
divider and no firestopping is required.) Fire-
stopping will be required in most cases between
the joists at the places where they are supported.
These solid wooden bridges prevent the hori-
zontal movement of fire and hot gases within the
floor.
The 1970’s provided a critical turning point for
energy consumption in this country and for
other major energy-consuming countries. With
the Arab oil embargo, prices rose at an outra-
geous rate, creating a scarcity of gasoline and
heating oil. While it is still debated whether the
crisis was legitimate or created to inflate crude-
oil prices, there were lessons to be learned from
the fuel shortage. First, fuel oil is a limited and
irreplaceable resource. Second, the Western
world is burning oil at an unprecedented and
wasteful rate. The remedy is to conserve fuel as
much as possible and to explore and discover
new, regenerative sources of energy such as
solar power.
</code></pre>
<p>I would like to make a paragraph be on a single line instead of multiple lines.
So the output will be this:</p>
<pre><code>Be sure to see if the code requires firestops in the stud walls.* These are wood strips between the studs that will prevent flames and hot air from moving upward within the wall. (Some areas require that firestopping be placed no more than one story apart. In platform-frame con- struction, the floor platform acts as an adequate divider and no firestopping is required.) Fire- stopping will be required in most cases between the joists at the places where they are supported. These solid wooden bridges prevent the hori-zontal movement of fire and hot gases within the floor.
The 1970’s provided a critical turning point for energy consumption in this country and for other major energy-consuming countries. With the Arab oil embargo, prices rose at an outra-geous rate, creating a scarcity of gasoline and heating oil. While it is still debated whether the crisis was legitimate or created to inflate crude-oil prices, there were lessons to be learned from the fuel shortage. First, fuel oil is a limited and irreplaceable resource. Second, the Western world is burning oil at an unprecedented and wasteful rate. The remedy is to conserve fuel as much as possible and to explore and discover new, regenerative sources of energy such as solar power.
</code></pre>
<p>I'm seeing there's thing like sed and awk, but I'm not too sure how either one works, so far they seem alien to me.</p>
<p>Thank you for reading and helping if you can.</p>
<p>So far I only do this manually, but I honestly do not know how to make this work as I haven't found yet a solution for similar problem.</p>
| [
{
"answer_id": 74354371,
"author": "Ric Villalba",
"author_id": 6912817,
"author_profile": "https://Stackoverflow.com/users/6912817",
"pm_score": 2,
"selected": false,
"text": "df <- df[order(-colSums(apply(df, 2, is.na)))]"
},
{
"answer_id": 74354460,
"author": "AndrewGB",
"author_id": 15293191,
"author_profile": "https://Stackoverflow.com/users/15293191",
"pm_score": 2,
"selected": false,
"text": "dplyr"
},
{
"answer_id": 74354476,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 0,
"selected": false,
"text": "mean"
},
{
"answer_id": 74354607,
"author": "Dan Adams",
"author_id": 13210554,
"author_profile": "https://Stackoverflow.com/users/13210554",
"pm_score": 0,
"selected": false,
"text": "set.seed(1)\nd <- data.frame(matrix(sample(c(1:5, NA), 49, T, prob = c(rep(1, 5), 5)), ncol = 7))\n\n# base R\nd[,order(-colSums(is.na(d)))]\n#> X4 X2 X5 X1 X3 X6 X7\n#> 1 NA 4 2 NA 5 4 5\n#> 2 4 4 NA NA NA 5 3\n#> 3 NA NA NA 3 5 NA 3\n#> 4 NA NA 3 1 1 5 5\n#> 5 NA NA NA NA NA NA NA\n#> 6 NA 4 NA 2 5 2 NA\n#> 7 NA NA 2 1 1 4 5\n\n# with tidyverse\nlibrary(dplyr)\n\nd %>% \n select(order(-colSums(is.na(.))))\n#> X4 X2 X5 X1 X3 X6 X7\n#> 1 NA 4 2 NA 5 4 5\n#> 2 4 4 NA NA NA 5 3\n#> 3 NA NA NA 3 5 NA 3\n#> 4 NA NA 3 1 1 5 5\n#> 5 NA NA NA NA NA NA NA\n#> 6 NA 4 NA 2 5 2 NA\n#> 7 NA NA 2 1 1 4 5\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74354344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5212740/"
] |
74,354,376 | <p>I am using VScode on both my Macbook and my PC and my settings are synced. I use coderunner to run my python programs. My problem is that in my settings.json, the command I use to run my program on my mac is different to the one I need to use on my PC. The specific command I use is
<code>clear && python3 -u</code>. Since Vscode runs my code through the terminal, I have it clear every time I run it. When I am on my PC instead of my Mac, the command does not work. I do not want to have to change the command in the settings every time I switch beween computers. This is what the settings look like.</p>
<p><a href="https://i.stack.imgur.com/r5Sny.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/r5Sny.png" alt="enter image description here" /></a></p>
<p>I did try switching it at first to just <code>py</code> in my PC settings, since that is the command that the PC command prompt needs to activate python. But even that gave me an error and it changed the settings on my macbook. Is there something in the settings I can add or change to unsync it? Or do I just deal with it? I dont want to unsync everything else if possible.</p>
| [
{
"answer_id": 74354371,
"author": "Ric Villalba",
"author_id": 6912817,
"author_profile": "https://Stackoverflow.com/users/6912817",
"pm_score": 2,
"selected": false,
"text": "df <- df[order(-colSums(apply(df, 2, is.na)))]"
},
{
"answer_id": 74354460,
"author": "AndrewGB",
"author_id": 15293191,
"author_profile": "https://Stackoverflow.com/users/15293191",
"pm_score": 2,
"selected": false,
"text": "dplyr"
},
{
"answer_id": 74354476,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 0,
"selected": false,
"text": "mean"
},
{
"answer_id": 74354607,
"author": "Dan Adams",
"author_id": 13210554,
"author_profile": "https://Stackoverflow.com/users/13210554",
"pm_score": 0,
"selected": false,
"text": "set.seed(1)\nd <- data.frame(matrix(sample(c(1:5, NA), 49, T, prob = c(rep(1, 5), 5)), ncol = 7))\n\n# base R\nd[,order(-colSums(is.na(d)))]\n#> X4 X2 X5 X1 X3 X6 X7\n#> 1 NA 4 2 NA 5 4 5\n#> 2 4 4 NA NA NA 5 3\n#> 3 NA NA NA 3 5 NA 3\n#> 4 NA NA 3 1 1 5 5\n#> 5 NA NA NA NA NA NA NA\n#> 6 NA 4 NA 2 5 2 NA\n#> 7 NA NA 2 1 1 4 5\n\n# with tidyverse\nlibrary(dplyr)\n\nd %>% \n select(order(-colSums(is.na(.))))\n#> X4 X2 X5 X1 X3 X6 X7\n#> 1 NA 4 2 NA 5 4 5\n#> 2 4 4 NA NA NA 5 3\n#> 3 NA NA NA 3 5 NA 3\n#> 4 NA NA 3 1 1 5 5\n#> 5 NA NA NA NA NA NA NA\n#> 6 NA 4 NA 2 5 2 NA\n#> 7 NA NA 2 1 1 4 5\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74354376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20430561/"
] |
74,354,382 | <p>I am trying to get these images to be in a row side by side. I am following a tutorial for a class assignment and as far as I know the code is perfectly fine. The images are the child of Choices, within the Choice class but for some reason I cannot get the images side by side instead of vertical.</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>.choices {
margin-top: 50px 0;
text-align: center;
display: flex;
}
.choice {
display: inline-block;
border: 4px solid white;
border-radius: 50%;
margin: 0 20px;
padding: 10px;
transition: all 0.3s ease;
}
.choice:hover {
cursor: pointer;
background: #24273E;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="choices">
<div class="choice" id="r">
<img src="imgs/rock.png" alt="">
</div>
<div class="choices">
<div class="choice" id="p">
<img src="imgs/paper.png" alt="">
</div>
<div class="choices">
<div class="choice" id="s">
<img src="imgs/scissors.png" alt="">
</div>
</div></code></pre>
</div>
</div>
</p>
<p><a href="https://i.stack.imgur.com/RA5PA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RA5PA.png" alt="Screenshot of what is being currently displayed" /></a></p>
<p>I have tried other people's suggestions online but none of them seem to fix the issue.</p>
| [
{
"answer_id": 74354371,
"author": "Ric Villalba",
"author_id": 6912817,
"author_profile": "https://Stackoverflow.com/users/6912817",
"pm_score": 2,
"selected": false,
"text": "df <- df[order(-colSums(apply(df, 2, is.na)))]"
},
{
"answer_id": 74354460,
"author": "AndrewGB",
"author_id": 15293191,
"author_profile": "https://Stackoverflow.com/users/15293191",
"pm_score": 2,
"selected": false,
"text": "dplyr"
},
{
"answer_id": 74354476,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 0,
"selected": false,
"text": "mean"
},
{
"answer_id": 74354607,
"author": "Dan Adams",
"author_id": 13210554,
"author_profile": "https://Stackoverflow.com/users/13210554",
"pm_score": 0,
"selected": false,
"text": "set.seed(1)\nd <- data.frame(matrix(sample(c(1:5, NA), 49, T, prob = c(rep(1, 5), 5)), ncol = 7))\n\n# base R\nd[,order(-colSums(is.na(d)))]\n#> X4 X2 X5 X1 X3 X6 X7\n#> 1 NA 4 2 NA 5 4 5\n#> 2 4 4 NA NA NA 5 3\n#> 3 NA NA NA 3 5 NA 3\n#> 4 NA NA 3 1 1 5 5\n#> 5 NA NA NA NA NA NA NA\n#> 6 NA 4 NA 2 5 2 NA\n#> 7 NA NA 2 1 1 4 5\n\n# with tidyverse\nlibrary(dplyr)\n\nd %>% \n select(order(-colSums(is.na(.))))\n#> X4 X2 X5 X1 X3 X6 X7\n#> 1 NA 4 2 NA 5 4 5\n#> 2 4 4 NA NA NA 5 3\n#> 3 NA NA NA 3 5 NA 3\n#> 4 NA NA 3 1 1 5 5\n#> 5 NA NA NA NA NA NA NA\n#> 6 NA 4 NA 2 5 2 NA\n#> 7 NA NA 2 1 1 4 5\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74354382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18729212/"
] |
74,354,386 | <p>I am creating table, and want to remove row by id using input field. (if input field matches with id then the row must be deleted)
can not figure it out.</p>
<p>Your help is much appreciated
`</p>
<pre><code><body onload="addRow()">
<table id="myTable" style="display:none">
<tr>
<th class="borderless">ID</th>
<th>Name</th>
<th>Username</th>
<th>Gender</th>
<th>Country</th>
</tr>
<tbody id="myTableBody">
</tbody>
</table>
<button type="button" id="buttonShow" onclick="showTable()">Show Table</button>
<button type="button" id="buttonAdd" onclick="addRow()" disabled>Add a new row</button>
<br>
<label>
<input class="input1" type="text" name="todoTags"/>
<button class="dellbtn" id="buttonDell"onclick="delRow()" disabled>Delete row</button>
</label>
</code></pre>
<p>`</p>
<p>`</p>
<pre><code> function showTable(){
document.getElementById("myTable").style.display = "block";
document.getElementById("buttonAdd").disabled = false;
document.getElementById("buttonDell").disabled = false;
}
const btn = document.querySelector('.dellbtn')
const userTags = []
</code></pre>
<p>`
Here is my: <a href="https://jsfiddle.net/j2f0dsLq/" rel="nofollow noreferrer">JSfiddle</a></p>
| [
{
"answer_id": 74354371,
"author": "Ric Villalba",
"author_id": 6912817,
"author_profile": "https://Stackoverflow.com/users/6912817",
"pm_score": 2,
"selected": false,
"text": "df <- df[order(-colSums(apply(df, 2, is.na)))]"
},
{
"answer_id": 74354460,
"author": "AndrewGB",
"author_id": 15293191,
"author_profile": "https://Stackoverflow.com/users/15293191",
"pm_score": 2,
"selected": false,
"text": "dplyr"
},
{
"answer_id": 74354476,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 0,
"selected": false,
"text": "mean"
},
{
"answer_id": 74354607,
"author": "Dan Adams",
"author_id": 13210554,
"author_profile": "https://Stackoverflow.com/users/13210554",
"pm_score": 0,
"selected": false,
"text": "set.seed(1)\nd <- data.frame(matrix(sample(c(1:5, NA), 49, T, prob = c(rep(1, 5), 5)), ncol = 7))\n\n# base R\nd[,order(-colSums(is.na(d)))]\n#> X4 X2 X5 X1 X3 X6 X7\n#> 1 NA 4 2 NA 5 4 5\n#> 2 4 4 NA NA NA 5 3\n#> 3 NA NA NA 3 5 NA 3\n#> 4 NA NA 3 1 1 5 5\n#> 5 NA NA NA NA NA NA NA\n#> 6 NA 4 NA 2 5 2 NA\n#> 7 NA NA 2 1 1 4 5\n\n# with tidyverse\nlibrary(dplyr)\n\nd %>% \n select(order(-colSums(is.na(.))))\n#> X4 X2 X5 X1 X3 X6 X7\n#> 1 NA 4 2 NA 5 4 5\n#> 2 4 4 NA NA NA 5 3\n#> 3 NA NA NA 3 5 NA 3\n#> 4 NA NA 3 1 1 5 5\n#> 5 NA NA NA NA NA NA NA\n#> 6 NA 4 NA 2 5 2 NA\n#> 7 NA NA 2 1 1 4 5\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74354386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17417742/"
] |
74,354,427 | <p>I want to search the email subject from the whole outlook (all folders and archive included).
Do I change the getdefaultfolder or what should I do?</p>
<pre><code>Sub SubjectFound()
Dim oOutlook As Object
Dim oInbox As Object
Dim oFilter As Object
Dim oNS As Object
Dim sFilter As String
Dim lr As Long, r As Long
Const olFolderInbox = 6
Set oOutlook = CreateObject("outlook.application")
Set oNS = oOutlook.GetNamespace("MAPI")
Set oInbox = oNS.getdefaultfolder(olFolderInbox)
lr = Range("A" & Rows.Count).End(xlUp).Row
For r = 2 To lr
sFilter = "@SQL=""urn:schemas:httpmail:subject"" = '" & Range("A" & r).Value & "'"
sFilter = sFilter & " AND "
sFilter = sFilter & "%today(""urn:schemas:httpmail:datereceived"")%"
Set oFilter = oInbox.items.restrict(sFilter)
Range("B" & r) = IIf(oFilter.Count > 0, "Task Completed", "Task Incomplete")
DoEvents
Next
Set oOutlook = Nothing
Set oNS = Nothing
Set oInbox = Nothing
Set oFilter = Nothing
End Sub
</code></pre>
| [
{
"answer_id": 74354371,
"author": "Ric Villalba",
"author_id": 6912817,
"author_profile": "https://Stackoverflow.com/users/6912817",
"pm_score": 2,
"selected": false,
"text": "df <- df[order(-colSums(apply(df, 2, is.na)))]"
},
{
"answer_id": 74354460,
"author": "AndrewGB",
"author_id": 15293191,
"author_profile": "https://Stackoverflow.com/users/15293191",
"pm_score": 2,
"selected": false,
"text": "dplyr"
},
{
"answer_id": 74354476,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 0,
"selected": false,
"text": "mean"
},
{
"answer_id": 74354607,
"author": "Dan Adams",
"author_id": 13210554,
"author_profile": "https://Stackoverflow.com/users/13210554",
"pm_score": 0,
"selected": false,
"text": "set.seed(1)\nd <- data.frame(matrix(sample(c(1:5, NA), 49, T, prob = c(rep(1, 5), 5)), ncol = 7))\n\n# base R\nd[,order(-colSums(is.na(d)))]\n#> X4 X2 X5 X1 X3 X6 X7\n#> 1 NA 4 2 NA 5 4 5\n#> 2 4 4 NA NA NA 5 3\n#> 3 NA NA NA 3 5 NA 3\n#> 4 NA NA 3 1 1 5 5\n#> 5 NA NA NA NA NA NA NA\n#> 6 NA 4 NA 2 5 2 NA\n#> 7 NA NA 2 1 1 4 5\n\n# with tidyverse\nlibrary(dplyr)\n\nd %>% \n select(order(-colSums(is.na(.))))\n#> X4 X2 X5 X1 X3 X6 X7\n#> 1 NA 4 2 NA 5 4 5\n#> 2 4 4 NA NA NA 5 3\n#> 3 NA NA NA 3 5 NA 3\n#> 4 NA NA 3 1 1 5 5\n#> 5 NA NA NA NA NA NA NA\n#> 6 NA 4 NA 2 5 2 NA\n#> 7 NA NA 2 1 1 4 5\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74354427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16290352/"
] |
74,354,479 | <p>From this dataset:</p>
<pre class="lang-sql prettyprint-override"><code>mysql> SELECT * FROM document_signature;
+----+-------------+-------------+---------+-------+-----------+
| id | document_id | employee_id | user_id | order | status |
+----+-------------+-------------+---------+-------+-----------+
| 1 | 1 | 2 | NULL | 0 | SIGNED |
| 2 | 1 | 3 | NULL | 1 | NOTSIGNED |
| 3 | 1 | 4 | NULL | 1 | NOTSIGNED |
| 4 | 2 | 3 | NULL | 0 | NOTSIGNED |
| 5 | 3 | NULL | 1 | 0 | SIGNED |
| 6 | 3 | 1 | NULL | 0 | NOTSIGNED |
+----+-------------+-------------+---------+-------+-----------+
6 rows in set (0.00 sec)
</code></pre>
<p>I want to find the rows that have the minimun <code>order</code>, but only from those whose status is <code>NOTSIGNED</code>, even if there is more than one for each <code>document_id</code></p>
<p>Using this query:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT s.*
FROM document_signature s
WHERE `order` =
(SELECT MIN(s2.`order`)
FROM document_signature s2
WHERE s.document_id = s2.document_id
AND s2.status = 'NOTSIGNED');
</code></pre>
<p>These are the results I'm getting:</p>
<pre class="lang-sql prettyprint-override"><code>+----+-------------+-------------+---------+-------+-----------+
| id | document_id | employee_id | user_id | order | status |
+----+-------------+-------------+---------+-------+-----------+
| 2 | 1 | 3 | NULL | 1 | NOTSIGNED |
| 3 | 1 | 4 | NULL | 1 | NOTSIGNED |
| 4 | 2 | 3 | NULL | 0 | NOTSIGNED |
| 5 | 3 | NULL | 1 | 0 | SIGNED |
| 6 | 3 | 1 | NULL | 0 | NOTSIGNED |
+----+-------------+-------------+---------+-------+-----------+
5 rows in set (0.00 sec)
</code></pre>
<p>My question is: Why is there a row with <code>status</code> <code>SIGNED</code> in the resultset, what am I doing wrong here?</p>
| [
{
"answer_id": 74354371,
"author": "Ric Villalba",
"author_id": 6912817,
"author_profile": "https://Stackoverflow.com/users/6912817",
"pm_score": 2,
"selected": false,
"text": "df <- df[order(-colSums(apply(df, 2, is.na)))]"
},
{
"answer_id": 74354460,
"author": "AndrewGB",
"author_id": 15293191,
"author_profile": "https://Stackoverflow.com/users/15293191",
"pm_score": 2,
"selected": false,
"text": "dplyr"
},
{
"answer_id": 74354476,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 0,
"selected": false,
"text": "mean"
},
{
"answer_id": 74354607,
"author": "Dan Adams",
"author_id": 13210554,
"author_profile": "https://Stackoverflow.com/users/13210554",
"pm_score": 0,
"selected": false,
"text": "set.seed(1)\nd <- data.frame(matrix(sample(c(1:5, NA), 49, T, prob = c(rep(1, 5), 5)), ncol = 7))\n\n# base R\nd[,order(-colSums(is.na(d)))]\n#> X4 X2 X5 X1 X3 X6 X7\n#> 1 NA 4 2 NA 5 4 5\n#> 2 4 4 NA NA NA 5 3\n#> 3 NA NA NA 3 5 NA 3\n#> 4 NA NA 3 1 1 5 5\n#> 5 NA NA NA NA NA NA NA\n#> 6 NA 4 NA 2 5 2 NA\n#> 7 NA NA 2 1 1 4 5\n\n# with tidyverse\nlibrary(dplyr)\n\nd %>% \n select(order(-colSums(is.na(.))))\n#> X4 X2 X5 X1 X3 X6 X7\n#> 1 NA 4 2 NA 5 4 5\n#> 2 4 4 NA NA NA 5 3\n#> 3 NA NA NA 3 5 NA 3\n#> 4 NA NA 3 1 1 5 5\n#> 5 NA NA NA NA NA NA NA\n#> 6 NA 4 NA 2 5 2 NA\n#> 7 NA NA 2 1 1 4 5\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74354479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8875890/"
] |
74,354,485 | <p>I have the following pandas DF:</p>
<pre><code> val
1 10
2 20
3 30
4 40
5 30
</code></pre>
<p>I want to get two output columns: <strong>avg</strong> and <strong>avg_sep</strong></p>
<p><strong>avg</strong> should be the average calculated row by row.</p>
<p><strong>avg_sep</strong> should be the average calculated row by row until a certain condition (i.e. until row 3 I calculate one average, before row 3 I start calculating another average), my expected output is:</p>
<pre><code> val avg avg_sep
1 10 10 10
2 20 15 15
3 30 20 20
4 40 25 40
5 30 26 35
</code></pre>
<p>I know I can use <code>df.mean(axis=0)</code> to get the average of the column. But how can I get the expected output?</p>
| [
{
"answer_id": 74354583,
"author": "Chrysophylaxs",
"author_id": 9499196,
"author_profile": "https://Stackoverflow.com/users/9499196",
"pm_score": 2,
"selected": true,
"text": "import pandas as pd\nimport numpy as np\n\n# Building frame:\ndf = pd.DataFrame(\n data={\"val\": [10, 20, 30, 40, 30]},\n index=[1, 2, 3, 4, 5]\n)\n\n# Solution:\ndf[\"avg\"] = df[\"val\"].cumsum() / np.arange(1, 6) # or `/ df.index`\ndf.loc[:3, \"avg_sep\"] = df.loc[:3, \"val\"].cumsum() / np.arange(1, 4)\ndf.loc[4:, \"avg_sep\"] = df.loc[4:, \"val\"].cumsum() / np.arange(1, 3)\n"
},
{
"answer_id": 74427172,
"author": "Azhar Khan",
"author_id": 2847330,
"author_profile": "https://Stackoverflow.com/users/2847330",
"pm_score": 0,
"selected": false,
"text": "mean()"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74354485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16459035/"
] |
74,354,521 | <p>I'm making a Firefox browser extension (<strong>note: Chrome extensions and Firefox extensions have very similar APIs</strong>) that monitors screentime on certain websites that can be selected by the user. Specifically, the screen time counter <em>should</em> reset every 24 hours <strong>at midnight</strong>.</p>
<p>The code in question:</p>
<pre class="lang-js prettyprint-override"><code>let interval = setInterval(update, 1000);
let msTillMidnight = (new Date().setHours(24, 0, 0, 0) - Date.now());
function restart() {
browser.storage.local.get("totalTime").then(res => {
browser.storage.local.set({timeLeft: res["totalTime"]});
});
if (!running) {
running = true;
interval = setInterval(update, 1000);
}
}
new Promise(resolve => setTimeout(resolve, msTillMidnight)).then(() => { // I am aware this is laughably redundant, but in theory it should work exactly the same
restart();
setInterval(restart, 1000 * 60 * 60 * 24); // 1000 ms/second —> 60 s/minute —> 60 m/hour —> 24 h/day
});
</code></pre>
<p>I noticed a very odd behavior. After the first midnight after the extension began running, <code>restart</code> was not called. None of the browser storage vars were updated, nor the interval, not the <code>running</code> bool. The problem, I assumed, was that the <code>setTimeout</code> in question was <em>simply not running</em>. However, the next night, <strong>the clock had reset</strong>!</p>
<p>I don't understand. Is something wrong with my <code>msTillMidnight</code> variable? Is it because the background page shuts down and won't run any <code>setTimeout</code> scripts after a while when my computer is asleep at midnight and that the <code>restart</code> function will only call when my computer is still on or shut down recently? Or maybe, my redundant line of code that beats around the bush instead of a simple setTimeout is somehow causing a bug?</p>
<p>I would love to debug this on my own, but my testing cycles would most likely be 24 hours, which is a little slower than I would prefer...</p>
| [
{
"answer_id": 74354979,
"author": "vanowm",
"author_id": 2930038,
"author_profile": "https://Stackoverflow.com/users/2930038",
"pm_score": 2,
"selected": true,
"text": "setTimeout"
},
{
"answer_id": 74389390,
"author": "gosoccerboy5",
"author_id": 15938577,
"author_profile": "https://Stackoverflow.com/users/15938577",
"pm_score": 0,
"selected": false,
"text": "alarm"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74354521",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15938577/"
] |
74,354,585 | <p>Here is some simplified code. It's not mine, but I'm adapting it for a project of mine. It's part of a sizeable codebase I'm importing, and which I don't want to change more than absolutely necessary.</p>
<pre><code>void function (object& out_thing)
{
object thing;
#pragma omp nowait
for (int k = 0 ; k < 5 ; k++) {
object* things[2];
float scores[2];
for (i = 0; i < 2 ; i++)
scores[i] = evaluateThings(things[i], parameter1, parameter2);
if (scores[1] < scores[0]) {
scores[0] = scores[1];
things[0] = things[1];
}
thing = *(things[0]);
}
out_thing = thing;
}
</code></pre>
<p>When compiled, I get warnings that the implicitly declared thing = *(things[0]) and out_thing = thing are deprecated [-Wdeprecated-copy] because I have a user-provided copy constructor.</p>
<p>I guess the compiler wants me to write <code>object thing(*(things[1])</code> but I can't because I need to declare <code>object thing</code> before the omp pragma, and I can't write <code>object out_thing(thing)</code> at the end because out_thing is already defined as one of the arguments passed to the function.</p>
<p>Is there any way to recode this to get rid of the warnings?</p>
<p>(I can actually get rid of the first one by changing <code>object thing;</code> to <code>object* thing = NULL</code> and then later on changing <code>thing = *(things[0]);</code> to <code>thing = things[0];</code> but that requires me to change <code>out_thing = thing;</code> to <code>out_thing = *thing;</code> and I still get the warning for that deprecated copy; I'd like to get rid of both, ideally, if it's possible without extensive changes elsewhere in the code base and without being harmful to performance etc.)</p>
| [
{
"answer_id": 74397484,
"author": "273K",
"author_id": 6752050,
"author_profile": "https://Stackoverflow.com/users/6752050",
"pm_score": 4,
"selected": true,
"text": "-Wdeprecated-copy"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74354585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19459114/"
] |
74,354,587 | <p>Im having issues iterating through the dictionary because of the quotation marks in the values, how would I calculate the average in a dicitonary like this?</p>
<p>I tried to use the map function to bypass the quotation marks but that didnt work</p>
| [
{
"answer_id": 74397484,
"author": "273K",
"author_id": 6752050,
"author_profile": "https://Stackoverflow.com/users/6752050",
"pm_score": 4,
"selected": true,
"text": "-Wdeprecated-copy"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74354587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20445046/"
] |
74,354,591 | <p>I have a string containing a list of names (authors of a book)</p>
<p><code>"John Doe, Jim Smith, Jane Elizabeth Doe"</code></p>
<p>I want to output a string:</p>
<p><code>'"Doe, John", "Smith, Jim", "Doe, Jane Elizabeth"'</code></p>
<p>I managed to work it out for a single author.</p>
<pre><code>let fullName = "John Doe";
let pieces = fullName.split(" ");
var lastName, firstName;
if (pieces.length >= 2) {
firstName = pieces[0];
lastName = pieces[pieces.length - 1];
} else {
firstName = pieces[0];
lastName = "";
}
let lastFirst = '"' + lastName + ", " + firstName + '"';
</code></pre>
<p>I think I need to do something like this...</p>
<pre><code>let fullName = "John Doe, Jim Smith, Jane Elizabeth Doe";
if (fullName.includes(",")) {
let author = fullName.split(", ");
var arrayLength = author.length;
for (var i = 0; i < arrayLength; i++) {
let pieces = author[i].split(" ");
}
}
</code></pre>
<p>but now I'm stuck, any assistance is greatly appreciated.</p>
| [
{
"answer_id": 74397484,
"author": "273K",
"author_id": 6752050,
"author_profile": "https://Stackoverflow.com/users/6752050",
"pm_score": 4,
"selected": true,
"text": "-Wdeprecated-copy"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74354591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/268436/"
] |
74,354,665 | <p>I'm trying to transform a csv file with year, lat, long and pressure into a 3 dimensional netcdf pressure(time, lat, long).</p>
<p>However, my list is with duplicate values as below:</p>
<pre><code>year,lon,lat,pressure
1/1/00,79.4939,34.4713,11981569640
1/1/01,79.4939,34.4713,11870476671
1/1/02,79.4939,34.4713,11858633008
1/1/00,77.9513,35.5452,11254617090
1/1/01,77.9513,35.5452,11267424230
1/1/02,77.9513,35.5452,11297377976
1/1/00,77.9295,35.5188,1031160490
</code></pre>
<p>I have the same year, lon, lat for one pressure</p>
<p>My first attempt was using straight:</p>
<pre><code>import pandas as pd
import xarray as xr
csv_file = '.csv'
df = pd.read_csv(csv_file)
df = df.set_index(["year", "lon", "lat"])
xr = df.to_xarray()
nc=xr.to_netcdf('netcdf.nc')`
</code></pre>
<p>So I've tried to follow <a href="https://stackoverflow.com/questions/56271982/how-to-convert-a-csv-file-to-grid-with-xarray">How to convert a csv file to grid with Xarray?</a> but I crashed.</p>
<p>I think I need to rearrange this csv to have unique values of lat long as a function of time, varying only the values of pressure.</p>
<p>Something like this:</p>
<pre><code>longitude,latitude,1/1/2000,1/1/2001,1/1/2002....
79.4939,34.4713 11981569640 ...
77.9513,35.5452 11254617090 ...
77.9295,35.5188 1031160490 ...
</code></pre>
<p>I can use "pd.melt" to create my netcdf:</p>
<pre><code>df = pd.melt(df, id_vars=["year","lon", "lat"], var_name="year", value_name="PRESSURE")
</code></pre>
<p>Just a example of my file with two years:</p>
<p><a href="https://1drv.ms/u/s!AhZf0QH5jEVSjWQ7WNCwJsrKBwor?e=UndUkV" rel="nofollow noreferrer">https://1drv.ms/u/s!AhZf0QH5jEVSjWQ7WNCwJsrKBwor?e=UndUkV</a></p>
<p>Using this code below its where I wanna get:</p>
<pre><code>filename = '13.csv'
colnames = ['year','lon','lat','pressure']
df = pd.read_csv(filename, names = colnames)
df["year"]= pd.to_datetime(df["year"], errors='coerce')
xr = df.set_index(['year','lon','lat']).to_xarray()
#xr['time'].attrs={'units':'hours since 2018-01-01'}
xr['lat'].attrs={'units':'degrees', 'long_name':'Latitude'}
xr['lon'].attrs={'units':'degrees', 'long_name':'Longitude'}
xr['pressure'].attrs={'units':'pa', 'long_name':'Pressure'}
xr.to_netcdf('my_netcdf.nc')
</code></pre>
| [
{
"answer_id": 74397484,
"author": "273K",
"author_id": 6752050,
"author_profile": "https://Stackoverflow.com/users/6752050",
"pm_score": 4,
"selected": true,
"text": "-Wdeprecated-copy"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74354665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20445054/"
] |
74,354,666 | <p>If I have a list of 10K elements, and I want to randomly iterate through all of them, is there an algorithm that lets me access each element randomly, without just sorting them randomly first?</p>
<p>In other words, this would not be ideal:</p>
<pre class="lang-js prettyprint-override"><code>const sorted = list
.map(v => [math.random(), v])
.sort((a,b) => a[0]- b[0]);
</code></pre>
<p>It would be nice to avoid the sort call and the mapping call.
My only idea would be to store everything in a hashmap and access the hash keys randomly somehow? Although that's just coming back to the same problem, <em>afaict</em>.</p>
| [
{
"answer_id": 74397484,
"author": "273K",
"author_id": 6752050,
"author_profile": "https://Stackoverflow.com/users/6752050",
"pm_score": 4,
"selected": true,
"text": "-Wdeprecated-copy"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74354666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1223975/"
] |
74,354,751 | <p>I see a bunch of confusing solutions around, and I'm convinced there's a more simple, elegant way.</p>
<p>Right now, "date" would print 11/07. I simply want it to print 11/06.</p>
<p>I've tried subtracting one all over, I understand it's a string now, but I thought I could subtract before I converted it?</p>
<p>Ultimately, I want to hide tabs that contain yesterday's date. The rest of my script works perfectly, just can't figure this part out.</p>
<pre><code>function HideOldTabs(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var allsheets = ss.getSheets();
var date = Utilities.formatDate(new Date(),"EST", "MM/dd")
var data = []
for(var s in allsheets){
var sheet = allsheets[s];
if(
// (sheet.getName() == "Summary") ||
// (sheet.getName() == "Data") ||
// (sheet.getName() == "Sheet1") ||
(sheet.getName().includes(date))
){
sheet.hideSheet();
}
}
return data;
// console.log(date)
}
</code></pre>
| [
{
"answer_id": 74354879,
"author": "Cooper",
"author_id": 7215091,
"author_profile": "https://Stackoverflow.com/users/7215091",
"pm_score": 0,
"selected": false,
"text": "let dt = new Date();\nlet minusone = new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()-1)\n"
},
{
"answer_id": 74355375,
"author": "TheAddonDepot",
"author_id": 6586255,
"author_profile": "https://Stackoverflow.com/users/6586255",
"pm_score": 2,
"selected": false,
"text": "Date"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74354751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19425874/"
] |
74,354,755 | <p>I'm currently trying to merge sort an array of objects using the <code>compareTo</code> method in the <code>Box</code> class. I think I have it down but I'm getting this logical error.
Sorting the array using <em>merge sort</em>.
The array after merge sort:</p>
<pre class="lang-none prettyprint-override"><code>Width: 67.8 height: 41.5 length: 56.1 Volume: 157848.57
Width: 67.8 height: 41.5 length: 56.1 Volume: 157848.57
Width: 67.8 height: 41.5 length: 56.1 Volume: 157848.57
Width: 67.8 height: 41.5 length: 56.1 Volume: 157848.57
Width: 67.8 height: 41.5 length: 56.1 Volume: 157848.57
Width: 67.8 height: 41.5 length: 56.1 Volume: 157848.57
Width: 67.8 height: 41.5 length: 56.1 Volume: 157848.57
Width: 67.8 height: 41.5 length: 56.1 Volume: 157848.57
Width: 67.8 height: 41.5 length: 56.1 Volume: 157848.57
Width: 67.8 height: 41.5 length: 56.1 Volume: 157848.57
</code></pre>
<p>It seems to only copy that one object. I do not know where I went wrong. I've tried changing the <code>compareTo</code> method logic but it seems to stay the same no matter what. Here is my merge sort method:</p>
<pre class="lang-java prettyprint-override"><code>static void mergeSort(Box[] theBoxes) {
if(theBoxes.length > 1 ){
Box [] firstHalf = new Box[theBoxes.length/2];
System.arraycopy(theBoxes, 0 , firstHalf, 0 ,theBoxes.length /2);
mergeSort(firstHalf);
//Merge sort the second half
int secondHalfLength = theBoxes.length - theBoxes.length / 2 ;
Box [] secondHalf = new Box [secondHalfLength];
System.arraycopy(theBoxes, 0 , secondHalf, 0 ,secondHalfLength);
mergeSort(secondHalf);
merge(firstHalf, secondHalf , theBoxes);
}
}
static void merge(Box [] list1, Box [] list2 , Box [] temp ){
int current1 = 0;
int current2 = 0;
int current3 = 0;
while (current1 < list1.length && current2 < list2.length){
if(list1[current1].compareTo(list2[current2])> 0){
temp[current3++] = list1[current1++];
}else{
temp[current3++] = list2[current2++];
}
while(current1 < list1.length){
temp[current3++] = list1[current1++];
}
while(current2 < list2.length){
temp[current3++] = list2[current2++];
}
}
}
</code></pre>
<p>Here is the <code>Box</code> class:</p>
<pre class="lang-java prettyprint-override"><code>public class Box {
private double width, height, length;
Box(double w, double h, double l){
width=w;
height=h;
length=l;
}
private double getVolume(){
return width*height*length;
}
public int compareTo(Box o){
double myVol = this.getVolume();
double thatVol = o.getVolume();
if (myVol>thatVol)
return 1;
else if (myVol<thatVol)
return -1;
else
return 0;
}
public String toString(){
return "Width: "+width+
"\theight: "+height+
"\tlength: "+length+
"\tVolume: "+getVolume();
}
}
</code></pre>
<p>I am not allowed to change the <code>Box</code> class.</p>
| [
{
"answer_id": 74354879,
"author": "Cooper",
"author_id": 7215091,
"author_profile": "https://Stackoverflow.com/users/7215091",
"pm_score": 0,
"selected": false,
"text": "let dt = new Date();\nlet minusone = new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()-1)\n"
},
{
"answer_id": 74355375,
"author": "TheAddonDepot",
"author_id": 6586255,
"author_profile": "https://Stackoverflow.com/users/6586255",
"pm_score": 2,
"selected": false,
"text": "Date"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74354755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20200634/"
] |
74,354,760 | <pre><code>var employees = [
{ name: "Josh", title: "receptionist" },
{ name: "Naila", title: "receptionist" },
{ name: "Tom", title: "doctor" },
{ name: "Becky", title: "doctor" }
];
</code></pre>
<br>
For example on this one I would like to return
<br>
<pre><code>{
'doctor':2,
'receptionist':2
}
</code></pre>
<p>This is what I have tried:</p>
<pre><code>const convert = (employees) => {
const res = {};
employees.forEach((employee) => {
const key = `${employee.title}${employee["doctor-receptionist"]}`;
if (!res[key]) {
res[key] = {...employee, count: 0 };
};
res[key].count += 1;
});
return Object.values(res);
};
console.log(convert(employees));
</code></pre>
<p>It returns the name of the employees, which I did not want.
I also thought about creating arrays for each kind of job title and filtering each employee from the employee array, and pushing them to their respective arrays. But I feel like there must be an easier way.</p>
| [
{
"answer_id": 74354805,
"author": "flyingfox",
"author_id": 3176419,
"author_profile": "https://Stackoverflow.com/users/3176419",
"pm_score": 1,
"selected": true,
"text": "reduce()"
},
{
"answer_id": 74354807,
"author": "Kinglish",
"author_id": 1772933,
"author_profile": "https://Stackoverflow.com/users/1772933",
"pm_score": 0,
"selected": false,
"text": "reduce"
},
{
"answer_id": 74354852,
"author": "aknadif",
"author_id": 13542016,
"author_profile": "https://Stackoverflow.com/users/13542016",
"pm_score": 0,
"selected": false,
"text": "const employees = [\n { name: \"Josh\", title: \"receptionist\" },\n { name: \"Naila\", title: \"receptionist\" },\n { name: \"Tom\", title: \"doctor\" },\n { name: \"Becky\", title: \"doctor\" }\n] \n\n\nconst sumReceptionist = employees.filter((item)=>{\n return item.title === 'receptionist'\n}).length\nconst sumDoctor = employees.filter((item)=>{\n return item.title === 'doctor'\n}).length\n\nlet total =\n {\n receptionist: sumReceptionist,\n doctor: sumDoctor\n }\n\nconsole.log(total)"
},
{
"answer_id": 74354859,
"author": "vnetkc",
"author_id": 3421628,
"author_profile": "https://Stackoverflow.com/users/3421628",
"pm_score": 0,
"selected": false,
"text": "const Employees = [{\n name: \"Josh\",\n title: \"receptionist\"\n },\n {\n name: \"Naila\",\n title: \"receptionist\"\n },\n {\n name: \"Tom\",\n title: \"doctor\"\n },\n {\n name: \"Becky\",\n title: \"doctor\"\n },\n {\n name: \"Chad\",\n title: \"doctor\"\n },\n {\n name: \"Cindy\",\n title: \"nurse\"\n }\n];\n\n// A forEach won't return an object or array, so we create one to modify within it\nconst PositionTotals = {};\nEmployees.forEach(employee => {\n // Check if property exists. If not, create it and add one to it before continuing loop\n if (!PositionTotals.hasOwnProperty(employee.title))\n return PositionTotals[employee.title] = 1;\n PositionTotals[employee.title]++;\n})\n\nconsole.log(PositionTotals);\n$('#PositionTotals').html(JSON.stringify(PositionTotals, null, '\\t'));"
},
{
"answer_id": 74355266,
"author": "PeterKA",
"author_id": 3558931,
"author_profile": "https://Stackoverflow.com/users/3558931",
"pm_score": 1,
"selected": false,
"text": "Array#reduce"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74354760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20445025/"
] |
74,354,779 | <p>I am looking to mutate the same variables with two or more dataframes. What is the best way to implement to reduce redundant code?</p>
<pre><code>library(dplyr)
df1 <- tibble(a = 0.125068, b = 0.144623)
df2 <- tibble(a = 0.226018, b = 0.423600)
df1 <- df1 %>%
mutate(a = round(a, 1),
b = round(b, 2))
df2 <- df2 %>%
mutate(a = round(a, 1),
b = round(b, 2))
</code></pre>
| [
{
"answer_id": 74354805,
"author": "flyingfox",
"author_id": 3176419,
"author_profile": "https://Stackoverflow.com/users/3176419",
"pm_score": 1,
"selected": true,
"text": "reduce()"
},
{
"answer_id": 74354807,
"author": "Kinglish",
"author_id": 1772933,
"author_profile": "https://Stackoverflow.com/users/1772933",
"pm_score": 0,
"selected": false,
"text": "reduce"
},
{
"answer_id": 74354852,
"author": "aknadif",
"author_id": 13542016,
"author_profile": "https://Stackoverflow.com/users/13542016",
"pm_score": 0,
"selected": false,
"text": "const employees = [\n { name: \"Josh\", title: \"receptionist\" },\n { name: \"Naila\", title: \"receptionist\" },\n { name: \"Tom\", title: \"doctor\" },\n { name: \"Becky\", title: \"doctor\" }\n] \n\n\nconst sumReceptionist = employees.filter((item)=>{\n return item.title === 'receptionist'\n}).length\nconst sumDoctor = employees.filter((item)=>{\n return item.title === 'doctor'\n}).length\n\nlet total =\n {\n receptionist: sumReceptionist,\n doctor: sumDoctor\n }\n\nconsole.log(total)"
},
{
"answer_id": 74354859,
"author": "vnetkc",
"author_id": 3421628,
"author_profile": "https://Stackoverflow.com/users/3421628",
"pm_score": 0,
"selected": false,
"text": "const Employees = [{\n name: \"Josh\",\n title: \"receptionist\"\n },\n {\n name: \"Naila\",\n title: \"receptionist\"\n },\n {\n name: \"Tom\",\n title: \"doctor\"\n },\n {\n name: \"Becky\",\n title: \"doctor\"\n },\n {\n name: \"Chad\",\n title: \"doctor\"\n },\n {\n name: \"Cindy\",\n title: \"nurse\"\n }\n];\n\n// A forEach won't return an object or array, so we create one to modify within it\nconst PositionTotals = {};\nEmployees.forEach(employee => {\n // Check if property exists. If not, create it and add one to it before continuing loop\n if (!PositionTotals.hasOwnProperty(employee.title))\n return PositionTotals[employee.title] = 1;\n PositionTotals[employee.title]++;\n})\n\nconsole.log(PositionTotals);\n$('#PositionTotals').html(JSON.stringify(PositionTotals, null, '\\t'));"
},
{
"answer_id": 74355266,
"author": "PeterKA",
"author_id": 3558931,
"author_profile": "https://Stackoverflow.com/users/3558931",
"pm_score": 1,
"selected": false,
"text": "Array#reduce"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74354779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14007231/"
] |
74,354,797 | <p>I try to call fun bind declared in the inner class LaunchesViewHolder from onBindViewHolder() but I got error "Unresolved resource bind"
I was trying with an other variable x, just to see, same problem</p>
<pre><code>class LaunchesAdapter(private val dataSet: List<LaunchItem>) :
RecyclerView.Adapter<RecyclerView.ViewHolder>() {
inner class LaunchesViewHolder( val binding: LaunchesItemLayoutBinding) :
RecyclerView.ViewHolder(binding.root) {
val x = 0
public fun bind(currentLaunch: LaunchItem) {
//do something
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return LaunchesViewHolder(
LaunchesItemLayoutBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
holder.bind(dataSet[position]) => error unresolved resource bind
holder.x =1 => error unresolved resource x
}
override fun getItemCount(): Int {
return dataSet.size
}
}````
</code></pre>
| [
{
"answer_id": 74354805,
"author": "flyingfox",
"author_id": 3176419,
"author_profile": "https://Stackoverflow.com/users/3176419",
"pm_score": 1,
"selected": true,
"text": "reduce()"
},
{
"answer_id": 74354807,
"author": "Kinglish",
"author_id": 1772933,
"author_profile": "https://Stackoverflow.com/users/1772933",
"pm_score": 0,
"selected": false,
"text": "reduce"
},
{
"answer_id": 74354852,
"author": "aknadif",
"author_id": 13542016,
"author_profile": "https://Stackoverflow.com/users/13542016",
"pm_score": 0,
"selected": false,
"text": "const employees = [\n { name: \"Josh\", title: \"receptionist\" },\n { name: \"Naila\", title: \"receptionist\" },\n { name: \"Tom\", title: \"doctor\" },\n { name: \"Becky\", title: \"doctor\" }\n] \n\n\nconst sumReceptionist = employees.filter((item)=>{\n return item.title === 'receptionist'\n}).length\nconst sumDoctor = employees.filter((item)=>{\n return item.title === 'doctor'\n}).length\n\nlet total =\n {\n receptionist: sumReceptionist,\n doctor: sumDoctor\n }\n\nconsole.log(total)"
},
{
"answer_id": 74354859,
"author": "vnetkc",
"author_id": 3421628,
"author_profile": "https://Stackoverflow.com/users/3421628",
"pm_score": 0,
"selected": false,
"text": "const Employees = [{\n name: \"Josh\",\n title: \"receptionist\"\n },\n {\n name: \"Naila\",\n title: \"receptionist\"\n },\n {\n name: \"Tom\",\n title: \"doctor\"\n },\n {\n name: \"Becky\",\n title: \"doctor\"\n },\n {\n name: \"Chad\",\n title: \"doctor\"\n },\n {\n name: \"Cindy\",\n title: \"nurse\"\n }\n];\n\n// A forEach won't return an object or array, so we create one to modify within it\nconst PositionTotals = {};\nEmployees.forEach(employee => {\n // Check if property exists. If not, create it and add one to it before continuing loop\n if (!PositionTotals.hasOwnProperty(employee.title))\n return PositionTotals[employee.title] = 1;\n PositionTotals[employee.title]++;\n})\n\nconsole.log(PositionTotals);\n$('#PositionTotals').html(JSON.stringify(PositionTotals, null, '\\t'));"
},
{
"answer_id": 74355266,
"author": "PeterKA",
"author_id": 3558931,
"author_profile": "https://Stackoverflow.com/users/3558931",
"pm_score": 1,
"selected": false,
"text": "Array#reduce"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74354797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20445122/"
] |
74,354,810 | <p>I'm attempting to have get a data output for the amount of orders per shoe color. Each shoe sold has only 2 sizes that can be sold. I would like to get the total amount of each size sold into 1 object per order date.</p>
<p>I've attempted to push into a new array that gets the total of sizes per order Date into a new object</p>
<p>I've attempted to do this my looping through and applying a filter but my return is breaking due to orders being undefined. I believe the issue is due to my additional filters with</p>
<pre><code>let sizeNine = sales.filter(sale => sale.size == "9")[0]
let sizeEleven = sales.filter(sale => sale.size == "11")[0]
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const data = [
{
color: 'red',
order_date: '2022-11-01',
size: '9',
orders: 4
},
{
color: 'red',
order_date: '2022-11-01',
size: '11',
orders: 8
},
{
color: 'yellow',
order_date: '2022-11-04',
size: '9',
orders: 1
},
{
color: 'yellow',
order_date: '2022-11-04',
size: '11',
orders: 4
},
]
let combinedSales = []
for (let i = 0; i < data.length; i++) {
let currentSale = data[i]
let sales = data.filter(sale => sale.size == currentSale.size && sale.order_date == currentSale.order_date)
let sizeNine = sales.filter(sale => sale.size == "9")[0]
let sizeEleven = sales.filter(sale => sale.size == "11")[0]
combinedSales.push({
orderDate: currentSale.order_date,
sizeNineTotal: sizeNine.orders,
sizeElevenTotal: sizeEleven.orders,
totalOrders: sizeNine.orders + sizeEleven.orders
})
}
console.log(combinedSales)</code></pre>
</div>
</div>
</p>
<p>I am having trouble thinking of the correct logic to execute this, how can I achieve this output?</p>
<pre><code>const data = [
{
orderDate: '2022-11-01',
sizeNineTotal: 9,
sizeElevenTotal: 8,
totalOrder: 17
},
{
orderDate: '2022-11-04',
sizeNineTotal: 1,
sizeElevenTotal: 4,
totalOrder: 5
},
]
</code></pre>
| [
{
"answer_id": 74354901,
"author": "flyingfox",
"author_id": 3176419,
"author_profile": "https://Stackoverflow.com/users/3176419",
"pm_score": 3,
"selected": true,
"text": "reduce()"
},
{
"answer_id": 74355036,
"author": "Benjamin Penney",
"author_id": 6545526,
"author_profile": "https://Stackoverflow.com/users/6545526",
"pm_score": 0,
"selected": false,
"text": "let sizeList = [...new Set(data.map(i => i.size))];\n\n// OK, now we have a list of sizes [\"9\", \"11\"]\n\nlet dateList = [...new Set(data.map(i => i.order_date))];\n\n// Now we have a list of dates\n\nlet combinedSales = dateList.reduce((carry, date) =>\n{\n let salesOnDay = data.filter(i => i.order_date === date);\n \n // Now we have a list of orders for this day\n \n let sizeNineTotal = salesOnDay.filter(i => i.size === '9').map(i => i.orders).reduce((carry, item) => carry + item, 0); \n let sizeElevenTotal = salesOnDay.filter(i => i.size === '11').map(i => i.orders).reduce((carry, item) => carry + item, 0);\n\n // Producing our totals is a simple matter of filtering the per-day array by size, mapping to the orders property and reducing it to a total value\n \n carry.push(\n {\n orderDate: date,\n sizeNineTotal: sizeNineTotal,\n sizeElevenTotal: sizeElevenTotal,\n totalOrder: sizeNineTotal + sizeElevenTotal\n });\n\n return(carry);\n}, []);\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74354810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13501289/"
] |
74,354,840 | <p>I have a pandas dataframe like:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>one</th>
<th>two</th>
<th>three</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>2</td>
<td>4</td>
<td>6</td>
</tr>
<tr>
<td>1</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>10</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>2</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>0</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>-10</td>
<td>3</td>
<td>4</td>
</tr>
</tbody>
</table>
</div>
<p>Now observing the first column (labeled 'one') I would like to find the rows where the value is bigger than say 9. (in this case it would be the fourth )</p>
<p>Ideally, I also would like to find the rows where the absolute value of the value is bigger than say 9 (so that would be fourth and seventh)</p>
<p>How can I do this? (So far I only covert the columns into series and even into series of truths and false but my problem is that my dataframe is huge and I cannot visually inspect it. I need to get the row numbers automatically</p>
| [
{
"answer_id": 74354986,
"author": "eshirvana",
"author_id": 1367454,
"author_profile": "https://Stackoverflow.com/users/1367454",
"pm_score": 2,
"selected": true,
"text": "abs"
},
{
"answer_id": 74354992,
"author": "Sunny",
"author_id": 996565,
"author_profile": "https://Stackoverflow.com/users/996565",
"pm_score": 1,
"selected": false,
"text": "df = pd.DataFrame({\n'a': [1, 4, -6, 3, 7],\n'b': [2, 3, 5, 3, 1],\n'c': [4, 2, 7, 1, 3]\n})\n\ndf[df.a.abs() > 5]\n"
},
{
"answer_id": 74354994,
"author": "Marya",
"author_id": 16458798,
"author_profile": "https://Stackoverflow.com/users/16458798",
"pm_score": 0,
"selected": false,
"text": "row = {} \nfor column in df:\n row_temp = {}\n index = df.loc[df[column].abs()>=9].index\n row.update({column:list(index)})\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74354840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4451521/"
] |
74,354,869 | <p>I'm working with boost::asio library for serial communications, and got some problems using it. Below is my code with the problem.</p>
<pre><code>std::unique_ptr<asio::serial_port> port_;
asio::io_service io_;
// Connect serial port 'COM8'
port_ = std::make_unique<asio::serial_port>(asio::serial_port(io_, "COM8"));
std::cout << port_->is_open() << std::endl; // True
Sleep(5000);
/// **Now I unplug the device connected to the COM8 port of my PC.**
std::cout << port_->is_open() << std::endl;
/// Still printed true.
/// I think the reason @asio::serial_port::is_open() returns true
/// is because I didn't called @asio::serial_port::close() before.
/// Then how can I check the physical disconnection?
</code></pre>
<p>After I unplugged the device, how can I know whether the device is still available in programmatically?</p>
| [
{
"answer_id": 74354986,
"author": "eshirvana",
"author_id": 1367454,
"author_profile": "https://Stackoverflow.com/users/1367454",
"pm_score": 2,
"selected": true,
"text": "abs"
},
{
"answer_id": 74354992,
"author": "Sunny",
"author_id": 996565,
"author_profile": "https://Stackoverflow.com/users/996565",
"pm_score": 1,
"selected": false,
"text": "df = pd.DataFrame({\n'a': [1, 4, -6, 3, 7],\n'b': [2, 3, 5, 3, 1],\n'c': [4, 2, 7, 1, 3]\n})\n\ndf[df.a.abs() > 5]\n"
},
{
"answer_id": 74354994,
"author": "Marya",
"author_id": 16458798,
"author_profile": "https://Stackoverflow.com/users/16458798",
"pm_score": 0,
"selected": false,
"text": "row = {} \nfor column in df:\n row_temp = {}\n index = df.loc[df[column].abs()>=9].index\n row.update({column:list(index)})\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74354869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13050727/"
] |
74,354,883 | <p>I have created a new angular project but i don't known it run.</p>
<p>Please help me.</p>
<p>I have created a new angular project but i don't known it run.</p>
<p>Please help me.</p>
| [
{
"answer_id": 74354922,
"author": "Christian Joseph Dalisay",
"author_id": 20049174,
"author_profile": "https://Stackoverflow.com/users/20049174",
"pm_score": 1,
"selected": false,
"text": "ng serve"
},
{
"answer_id": 74355814,
"author": "Jinu Joseph",
"author_id": 11138933,
"author_profile": "https://Stackoverflow.com/users/11138933",
"pm_score": 0,
"selected": false,
"text": "ng serve"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74354883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16554482/"
] |
74,354,897 | <p>I want to change order of the key and value in an array to specified order in javascript</p>
<p>From this</p>
<pre><code>{
[
"id" : 1,
"name" : "John",
"address" : "Britain"
]
}
</code></pre>
<p>to this</p>
<pre><code>{
[
"id" : 1,
"address" : "Britain",
"name" : "John",
]
}
</code></pre>
<p>I have research the solution but not any work</p>
| [
{
"answer_id": 74355129,
"author": "Alip Setiawan",
"author_id": 20444577,
"author_profile": "https://Stackoverflow.com/users/20444577",
"pm_score": 2,
"selected": false,
"text": "const arr = [{\"id\" : 1, \"name\": \"John\", \"address\": \"Britain\" }]\n\nconst sortOrder = {'id': 1, 'address': 2, 'name': 3}\n\nconst res = arr.map(o => Object.assign({}, ...Object.keys(o).sort((a, b) => sortOrder[a] - sortOrder[b]).map(x => { return { [x]: o[x]}})))\n\nconsole.log(JSON.stringify(res, null, 2))\n"
},
{
"answer_id": 74355183,
"author": "Benjamin Penney",
"author_id": 6545526,
"author_profile": "https://Stackoverflow.com/users/6545526",
"pm_score": 1,
"selected": false,
"text": "let x = { \n \"id\" : 1,\n \"name\" : \"John\",\n \"address\" : \"Britain\"\n};\n\nconst reorderObject = function(source, ...keyList)\n{\n let result = [];\n\n // Ensure the list of keys are only those present in the source object\n\n let sourceKeyList = Object.keys(source);\n keyList = keyList.filter(i => sourceKeyList.includes(i));\n \n // Copy the properties you want in the order you want them to a new object\n \n keyList.forEach(i => result[i] = source[i]);\n \n // Copy any remaining properties\n \n sourceKeyList.filter(i => !keyList.includes(i)).forEach(i => result[i] = source[i]);\n\n return(result);\n}\n\n// USAGE:\n\nconsole.log(reorderObject(x, \"id\", \"address\", \"name\"));\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74354897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19869169/"
] |
74,354,913 | <p>My main.tf is like this, I wanted to assign "google_project_iam_binding" -> "members" with "instance-sink" -> "unique_writer_identity"
but I'm already using the for each to set the role in google_project_iam_binding but iam unable to think of a way to use for each twice to assign to members of unique_writer_identity.</p>
<pre><code>resource "google_logging_project_bucket_config" "custom_log_bucket" {
for_each = var.cross_project_logsink_service
bucket_id = format("bkt-%s-%s-%s-%s-%s", local.monitored_resource_project[each.key])
location = "global"
project = var.monitoring_project
retention_days = 30
}
resource "google_logging_project_sink" "instance-sink" {
for_each = var.cross_project_logsink_service
name = format("%s_logsink_%s", var.domain, each.key)
description = "log sink from ${local.monitored_resource_project[each.key]}"
destination = "logging.googleapis.com/${google_logging_project_bucket_config.custom_log_bucket[0].id}"
filter = "resource.type=cloud_composer_environment"
project = local.monitored_resource_project[each.key]
unique_writer_identity = true
}
resource "google_project_iam_binding" "log-writer" {
for_each = toset([
"roles/storage.objectCreator",
"roles/logging.bucketWriter"
])
project = var.monitoring_project
role = each.key
members = [
google_logging_project_sink.instance-sink.writer_identity #how to assign it to the above resource
]
}
</code></pre>
<p>Currently error looks like this</p>
<pre><code>$ terraform plan
╷
│ Error: Missing resource instance key
│
│ on logsink.tf line 71, in resource "google_project_iam_binding" "log-writer":
│ 71: google_logging_project_sink.instance-sink.writer_identity
│
│ Because google_logging_project_sink.instance-sink has "for_each" set, its
│ attributes must be accessed on specific instances.
│
│ For example, to correlate with indices of a referring resource, use:
│ google_logging_project_sink.instance-sink[each.key]
</code></pre>
<p>The problem is I can't assign the above because it is using for_each of roles
tfvars looks like this</p>
<pre><code>cross_project_logsink_service = ["cloud_function"]
</code></pre>
| [
{
"answer_id": 74355096,
"author": "Naveen Kulkarni",
"author_id": 9714060,
"author_profile": "https://Stackoverflow.com/users/9714060",
"pm_score": 0,
"selected": false,
"text": "resource \"google_project_iam_binding\" \"log-writer\" {\n \n\n for_each = toset([\n \"roles/storage.objectCreator\",\n \"roles/logging.bucketWriter\"\n ])\n project = var.monitoring_project\n role = each.key\n\n members = [\n google_logging_project_sink.instance-sink[*].writer_identity\n ]\n}\n"
},
{
"answer_id": 74355140,
"author": "Marcin",
"author_id": 248823,
"author_profile": "https://Stackoverflow.com/users/248823",
"pm_score": 1,
"selected": false,
"text": "google_logging_project_sink.instance-sink"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74354913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19840332/"
] |
74,354,918 | <p>I have a tricky problem, as per the title I want to run a tcp server on the host machine that communicates to clients inside docker containers. I know you can do this with the server in a container, using the -p option to expose ports in the container and match them to the host. Or you could even setup a custom network and connect to the containers by name. My issue though is that I need the sever to be running on the host machine. This is because in our workflow we have various different containers that run different tools and we want to be able to coordinate them.</p>
<p>My grand plan therefore is to have a manager container that reads an input file that list all the tools needed for the workflow. The manger then sends a request to a tcp server to spawn various containers (which thus needs to be running on the host). The server then spawns the requested containers and sends the ip and port of the new container to the manger. The manger and container then communicate what needs to be done between themselves.</p>
<p>Now I already have this working in Apptainer and now we plan to use docker for wider support (mostly mac/windows versions). However docker's network isolation is causing issues.</p>
<p>If I start the server with ip "0.0.0.0" (i.e. listening on all ip's) bond to port 9000 then docker run -p 9000:9000 manger_container (i.e. start the manager container and expose port 9000 in the container to the host). Docker throws an error saying the port is in use. If i try the other way round (i.e. start the container then start server, i get the same issue only this time the server complains the port is "in use". I've also had no joy with --network=host (which incidentally wouldn't help if it did work because as far as i know it's Linux only). So at this stage I just have no idea how to set this up or if it's even possible with docker.</p>
| [
{
"answer_id": 74355096,
"author": "Naveen Kulkarni",
"author_id": 9714060,
"author_profile": "https://Stackoverflow.com/users/9714060",
"pm_score": 0,
"selected": false,
"text": "resource \"google_project_iam_binding\" \"log-writer\" {\n \n\n for_each = toset([\n \"roles/storage.objectCreator\",\n \"roles/logging.bucketWriter\"\n ])\n project = var.monitoring_project\n role = each.key\n\n members = [\n google_logging_project_sink.instance-sink[*].writer_identity\n ]\n}\n"
},
{
"answer_id": 74355140,
"author": "Marcin",
"author_id": 248823,
"author_profile": "https://Stackoverflow.com/users/248823",
"pm_score": 1,
"selected": false,
"text": "google_logging_project_sink.instance-sink"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74354918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20445137/"
] |
74,354,924 | <p>I am trying to convert spatial data from a CDC/HHS data on hospital strain, as downloadable from here:</p>
<p><a href="https://healthdata.gov/Hospital/COVID-19-Reported-Patient-Impact-and-Hospital-Capa/anag-cw7u" rel="nofollow noreferrer">https://healthdata.gov/Hospital/COVID-19-Reported-Patient-Impact-and-Hospital-Capa/anag-cw7u</a></p>
<p>Here's a snippet of the data:</p>
<pre><code>hospital_name hospital_pk geocoded_hospital_address
TRIHEALTH EVENDALE HOSPITAL 360362 POINT (-84.420098 39.253934)
KANE COUNTY HOSPITAL 461309 POINT (-112.52859 37.054324)
CRAIG HOSPITAL 062011 POINT (-104.978247 39.654008)
</code></pre>
<p>For entry:</p>
<pre><code>structure(list(hospital_name = c("TRIHEALTH EVENDALE HOSPITAL",
"KANE COUNTY HOSPITAL", "CRAIG HOSPITAL", "JAY HOSPITAL", "HARRISON COUNTY COMMUNITY HOSPITAL"
), geocoded_hospital_address = c("POINT (-84.420098 39.253934)",
"POINT (-112.52859 37.054324)", "POINT (-104.978247 39.654008)",
"POINT (-87.151673 30.950024)", "POINT (-94.025425 40.26528)"
)), row.names = c(NA, -5L), class = c("tbl_df", "tbl", "data.frame"
))
</code></pre>
<p>I'm trying to import it as an CSV, transform it, and then turn it into a shapefile. The file has a field, termed geocoded_hospital_address, that I am trying to use to convert the dataset. It is in POINT(longitude, latitude) format e.g., "POINT (-100.01382, 37.441504)".
I am used to using two variables (longitude/latitude) under the coords option, and I cannot get the "sf_column_name" option to work for me or decompose the field into two parts:</p>
<pre><code>test_sf<-COVID_19_Reported_Patient_Impact_and_Hospital_Capacity_by_Facility%>%
+ st_as_sf(sf_column_name="geocoded_hospital_address", crs=4326)
Error in st_sf(x, ..., agr = agr, sf_column_name = sf_column_name) :
no simple features geometry column present
</code></pre>
<p>Any ideas?</p>
| [
{
"answer_id": 74355256,
"author": "Zhiqiang Wang",
"author_id": 11741943,
"author_profile": "https://Stackoverflow.com/users/11741943",
"pm_score": 3,
"selected": true,
"text": "geocoded_hospital_address"
},
{
"answer_id": 74355280,
"author": "mrhellmann",
"author_id": 7547327,
"author_profile": "https://Stackoverflow.com/users/7547327",
"pm_score": 1,
"selected": false,
"text": "\nlibrary(tidyverse)\nlibrary(sf)\n\nx <- read_csv('COVID-19_Reported_Patient_Impact_and_Hospital_Capacity_by_Facility.csv')\n\n# alter geometry column to get just coordinates\n# remove 'POINT', parentheses, and whitespace\nx$coords <- x$geocoded_hospital_address %>%\n str_remove('POINT') %>%\n str_remove('\\\\(') %>%\n str_remove('\\\\)') %>%\n str_trim()\n\n# remove NA coords, then separate 'coords' into x & y, transform to an 'sf' object\n\nx_sf <- x %>%\n filter(!is.na(coords)) %>%\n separate(coords, into = c('x','y'), sep = ' ') %>%\n st_as_sf(coords = c('x','y'))\n\nhead(x_sf)\n\n#> Simple feature collection with 6 features and 128 fields\n#> Geometry type: POINT\n#> Dimension: XY\n#> Bounding box: xmin: -108.616 ymin: 24.71104 xmax: -80.21099 ymax: 39.10636\n#> CRS: NA\n#> # A tibble: 6 × 129\n#> hospital_pk collecti…¹ state ccn hospi…² address city zip hospi…³ fips_…⁴\n#> <chr> <date> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> \n#> 1 060054 2020-06-05 CO 0600… COMMUN… 2351 '… GRAN… 81505 Short … 08077 \n#> 2 100156 2020-06-19 FL 1001… HCA FL… 340 NW… LAKE… 32055 Short … 12023 \n#> 3 101312 2020-05-15 FL 1013… FISHER… 3301 O… MARA… 33050 Critic… 12087 \n#> 4 102001 2020-06-12 FL 1020… SELECT… 955 NW… MIAMI 33128 Long T… 12086 \n#> 5 102013 2020-06-26 FL 1020… KINDRE… 4801 N… TAMPA 33603 Long T… 12057 \n#> 6 102028 2020-05-01 FL 1020… SELECT… 5050 C… OXFO… 34484 Long T… 12119 \n#> # … with 119 more variables: is_metro_micro <lgl>, total_beds_7_day_avg <dbl>,\n#> # all_adult_hospital_beds_7_day_avg <dbl>,\n#> # all_adult_hospital_inpatient_beds_7_day_avg <dbl>,\n#> # inpatient_beds_used_7_day_avg <dbl>,\n#> # all_adult_hospital_inpatient_bed_occupied_7_day_avg <dbl>,\n#> # inpatient_beds_used_covid_7_day_avg <dbl>,\n#> # total_adult_patients_hospitalized_confirmed_and_suspected_covid_7_day_avg <dbl>, …\n\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74354924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7422442/"
] |
74,354,927 | <p>I have a social media webapp with posts. I am trying to allow users to upload an image to Cloudinary from a React front end. There is sometimes an image attached to a post and sometimes not.</p>
<p>If there is an image, I want to wait for the image to be uploaded to Cloudinary and then, once the image URL has been returned by the API, then proceed to upload that <code>imageURL</code> to my Mongo db along with the other post data for permanent storage.</p>
<p>The issue I have is that I need to wait for the <code>imageURL</code> to be returned from the API before posting the data to my db. Currently I have a function <code>uploadImage()</code> that is attached to a <code>handlesubmit()</code> function attached to a form the user fills in to set the image and post content.</p>
<p>My attempt is to have a <code>useState</code> hook <code>setImgURL</code> that is updated when the API returns with the image URL and then use this variable in another <code>fetch()</code> post request to my mongodb db for storage.</p>
<p>However I have since learned that <code>useState</code> hooks are asynchronous. This causes my post image URL to be added to the mongodb with a blank value before the API actually returns with the actual image URL and hence it is lost (especially true if the user submits the form quickly before Cloudinary has given me the image URL).</p>
<p>How can I wait for the image to be uploaded to Cloudinary, get the URL, before posting the final location of it to my db?</p>
<p>I don't think I can use a <code>useEffect()</code> hook which is the standard advice to solve this, since I only get one shot to upload the <code>imageURL</code> to the backend db. I need to wait until I have that value before uploading the post details to mongo. I guess I could get the new post ID and then do a <code>useEffect</code> to do a put update request to the backend with the Cloudinary image URL when it comes through but this seems like the wrong way to do it.</p>
<p>Code:</p>
<pre><code> const [imgURL, setImgURL] = useState(null);
const uploadImage = async (image) => {
console.log('uploading image');
const formData = new FormData();
formData.append('file', image);
formData.append("upload_preset", presetValue);
try{
const response = await fetch(APIendPointURL,
{
method: 'POST',
body: formData
});
const data = await response.json();
console.log(data);
setImgURL(data.secure_url);
console.log(imgURL)
} catch(err){
console.log(err);
setErrors(err);
}
}
</code></pre>
<p>I am calling <code>uploadImage()</code> in a form <code>handleSubmit()</code> function:</p>
<pre><code>const handleSubmit = async (e) => {
if (image){
await UploadImage(image);
}
//send post data to mongodb
try{
const response = await fetch('http://localhost:3000/api/v1/post/create',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': localStorage.getItem('token')
},
body: JSON.stringify({
content: e.target.content.value,
imgURL: imgURL
})
});
const data = await response.json();
console.log(data);
} catch(err){
console.log(err);
setErrors(err);
}
}
</code></pre>
| [
{
"answer_id": 74354963,
"author": "Bikas Lin",
"author_id": 17582798,
"author_profile": "https://Stackoverflow.com/users/17582798",
"pm_score": 3,
"selected": true,
"text": "imgURL"
},
{
"answer_id": 74354988,
"author": "Mohammed Shahed",
"author_id": 19067773,
"author_profile": "https://Stackoverflow.com/users/19067773",
"pm_score": 0,
"selected": false,
"text": "flushSync"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74354927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2270903/"
] |
74,354,968 | <p>I have the following code</p>
<pre><code>visited = [[false]*4] * 3
</code></pre>
<p>which shows me the 2-D array</p>
<pre><code>[[false, false, false, false], [false, false, false, false], [false, false, false, false]]
</code></pre>
<p>now I wish to change the element at row 1, column 2 as shown:</p>
<pre><code>[[false, false, false, false], [false, false, false, false], [false, false, false, false]]
^
</code></pre>
<p>so I did the following:</p>
<pre><code>visited[1][2] = 1
</code></pre>
<p>but now when I inspect the 2-D array, I get the following output:</p>
<pre><code>puts visited.inspect
> [[false, false, 1, false], [false, false, 1, false], [false, false, 1, false]]
</code></pre>
<p>I can't seem to figure out why all the rows at the same column index get populated by 1?</p>
<p><strong>Edit:</strong>
I tried initializing my array <code>visited</code> by typing out all the elements manually (without multiplying the arrays) and it worked fine. I wonder why this is the case? Apologies if this is not the proper convention for doing so, I come from a Python background.</p>
| [
{
"answer_id": 74355016,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 3,
"selected": true,
"text": "#object_id"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74354968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14255458/"
] |
74,355,060 | <p>I am trying to get the list of company names from : <a href="https://www.ces.tech/Exhibits/Exhibitor-Directory.aspx" rel="nofollow noreferrer">https://www.ces.tech/Exhibits/Exhibitor-Directory.aspx</a></p>
<p>How can I fix this error?
<a href="https://i.stack.imgur.com/RDhxE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RDhxE.png" alt="enter image description here" /></a></p>
<p>Thank you in advance.</p>
<p>I tried
SELECTOR
XPATH
and TAG_NAME('a') Print('company-name')</p>
<p><a href="https://i.stack.imgur.com/lpgkd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lpgkd.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74355016,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 3,
"selected": true,
"text": "#object_id"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20445432/"
] |
74,355,067 | <p>I plan to calculate distance between categorical data (Distance From First Dataset to Second Dataset)</p>
<p>Here's my dataset</p>
<p>First Dataset</p>
<pre><code>Id City Phone
A1 Jakarta Samsung
A2 Surabaya Apple
A3 Singapore Sony
</code></pre>
<p>Second Dataset (as Input)</p>
<pre><code>Id City Phone
1 Jakarta Samsung
2 Singapore Xiaomi
3 Surabaya Sony
</code></pre>
<p>Reference table for <code>City</code></p>
<pre><code> Jakarta Surabaya Singapore
Jakarta 0 1 2
Surabaya 1 0 1
Singapore 2 1 0
</code></pre>
<p>Reference table for <code>Phone</code></p>
<pre><code> Apple Samsung Sony Xiaomi
Apple 0 1 2 3
Samsung 1 0 1 2
Sony 2 1 0 1
Xiaomi 3 2 1 0
</code></pre>
<p>Second Dataset (as Output)
Calculation</p>
<pre><code>Id City Phone A1 A2 A3
1 Jakarta Samsung 0+0 1+1 2+1
2 Singapore Xiaomi 1+2 2+3 0+1
3 Surabaya Sony 1+1 0+2 2+0
</code></pre>
<p>As I try to calculate distance between every single rows on first dataset and second dataset Final Output</p>
<pre><code>Id City Phone A1 A2 A3
1 Jakarta Samsung 0 2 3
2 Singapore Xiaomi 3 5 1
3 Surabaya Sony 2 2 2
</code></pre>
<p>Notes:
<code>A1, A2, A3</code> is rows in first dataset</p>
<p>What I did is using a lot of joins, but the amount of code is too much</p>
| [
{
"answer_id": 74356994,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 2,
"selected": false,
"text": "DataFrame.join"
},
{
"answer_id": 74357149,
"author": "Azhar Khan",
"author_id": 2847330,
"author_profile": "https://Stackoverflow.com/users/2847330",
"pm_score": 2,
"selected": true,
"text": "df1 = pd.DataFrame(data=[ [\"A1\",\"Jakarta\",\"Samsung\"], [\"A2\",\"Surabaya\",\"Apple\"], [\"A3\",\"Singapore\",\"Sony\"] ], columns=[\"Id\",\"City\",\"Phone\"])\ndf2 = pd.DataFrame(data=[ [1,\"Jakarta\",\"Samsung\"], [2,\"Singapore\",\"Xiaomi\"], [3,\"Surabaya\",\"Sony\"] ], columns=[\"Id\",\"City\",\"Phone\"])\ncity_df = pd.DataFrame(data=[ [\"Jakarta\",0,1,2], [\"Surabaya\",1,0,1], [\"Singapore\",2,1,0] ], columns=[\"city\",\"Jakarta\",\"Surabaya\",\"Singapore\"]).set_index(\"city\")\nphone_df = pd.DataFrame(data=[ [\"Apple\",0,1,2,3], [\"Samsung\",1,0,1,2], [\"Sony\",2,1,0,1], [\"Xiaomi\",3,2,1,0] ], columns=[\"phone\",\"Apple\",\"Samsung\",\"Sony\",\"Xiaomi\"]).set_index(\"phone\")\n\ndf1[\"dummy_key\"] = 0\ndf2[\"dummy_key\"] = 0\nfinal_df = df2.merge(df1, on=\"dummy_key\", how=\"outer\")\n\nfinal_df[\"dist\"] = final_df.apply(lambda row: city_df.loc[row[\"City_x\"], row[\"City_y\"]] + phone_df.loc[row[\"Phone_x\"], row[\"Phone_y\"]], axis=1)\nfinal_df = final_df.drop([\"City_y\", \"Phone_y\", \"dummy_key\"], axis=1)\nfinal_df = final_df.rename(columns={\"Id_x\": \"Id\", \"City_x\": \"City\", \"Phone_x\": \"Phone\"})\nfinal_df = final_df.pivot(index=[\"Id\", \"City\", \"Phone\"], columns=\"Id_y\", values=\"dist\").rename_axis(None, axis=1).reset_index()\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7585973/"
] |
74,355,068 | <p>What's the best way to produce a struct result with 2 or more models combined in Gorm?</p>
<p>Given these example models:</p>
<pre><code>type Book struct {
gorm.Model
Title string
Description string
AuthorID uint
}
</code></pre>
<pre><code>type Author struct {
gorm.Model
FirstName string
LastName string
Books []Book
}
</code></pre>
<p>I want to create a query to find books by Title</p>
<pre><code>db.Where("title=?", "foo").Find(&books)
</code></pre>
<p>So far no problem, but I would also like to include Author.FirstName and Author.LastName in the result. This does not work with any method I tried, since Book struct does not include those fields. The desired result should include all fields from a matching Book plus all fields from Author related to that Book.</p>
<p>Tried to use Select() and Join() functions to specify all the desired fields, which produced the correct SQL statement, but the resulting Book struct still does not contain any Author fields.</p>
| [
{
"answer_id": 74356973,
"author": "S H A S H A N K",
"author_id": 12489086,
"author_profile": "https://Stackoverflow.com/users/12489086",
"pm_score": 0,
"selected": false,
"text": "type Driver struct {\n gorm.Model\n \n Name string\n \n License string\n \n Cars []Car\n }\n \ntype Car struct {\n gorm.Model\n \n Year int\n \n Make string\n \n ModelName string\n \n DriverID int\n }\n \n var (\n drivers = []Driver{\n \n {Name: \"Shashank\", License: \"India123\"},\n \n {Name: \"Tom\", License: \"India321\"},\n }\n \n cars = []Car{\n \n {Year: 2000, Make: \"Toyota\", ModelName: \"Tundra\", DriverID: 1},\n \n {Year: 2001, Make: \"Honda\", ModelName: \"Accord\", DriverID: 1},\n }\n )\n \nfunc GetCars(w http.ResponseWriter, r *http.Request) {\n \n var cars []Car\n \n db.Find(&cars)\n \n json.NewEncoder(w).Encode(&cars)\n\n}\n\n// Getting cars with the id, where it will include name of driver & license\n\nfunc GetCar(w http.ResponseWriter, r *http.Request) {\nparams := mux.Vars(r)\n\n var car Car\n\n db.First(&car, params[\"id\"])\n\n json.NewEncoder(w).Encode(&car) \n}\n"
},
{
"answer_id": 74357737,
"author": "Ivan Pesenti",
"author_id": 14394371,
"author_profile": "https://Stackoverflow.com/users/14394371",
"pm_score": 2,
"selected": true,
"text": "Author Author"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20445392/"
] |
74,355,076 | <p>So this is my code for a homework</p>
<pre><code>CREATE TABLE workorders
(
wo# NUMBER(5) PRIMARY KEY,
proj# VARCHAR(10) NOT NULL FOREIGN KEY REFERENCES project(proj#),
wo_desc VARCHAR(30) NOT NULL UNIQUE,
wo_assigned VARCHAR(30),
wo_hours NUMBER(5) NOT NULL CHECK(wo_hours>0),
wo_start DATE,
wo_due DATE,
wo_complete CHAR(1),
CONSTRAINT workorders_wo_complete_chk CHECK(wo_complete in('Y','N'))
);
</code></pre>
<p>I could not figure out why oracle apex won't let me create this table, it says</p>
<blockquote>
<p>ORA-00907: missing right parenthesis</p>
</blockquote>
<p>But I double-checked so many times and I think I do have all the parenthesis? What did I do wrong here?</p>
<p>Thanks in advance</p>
<p>I just want to create this table under these constreaints but I could find any errors that I know of.</p>
| [
{
"answer_id": 74356973,
"author": "S H A S H A N K",
"author_id": 12489086,
"author_profile": "https://Stackoverflow.com/users/12489086",
"pm_score": 0,
"selected": false,
"text": "type Driver struct {\n gorm.Model\n \n Name string\n \n License string\n \n Cars []Car\n }\n \ntype Car struct {\n gorm.Model\n \n Year int\n \n Make string\n \n ModelName string\n \n DriverID int\n }\n \n var (\n drivers = []Driver{\n \n {Name: \"Shashank\", License: \"India123\"},\n \n {Name: \"Tom\", License: \"India321\"},\n }\n \n cars = []Car{\n \n {Year: 2000, Make: \"Toyota\", ModelName: \"Tundra\", DriverID: 1},\n \n {Year: 2001, Make: \"Honda\", ModelName: \"Accord\", DriverID: 1},\n }\n )\n \nfunc GetCars(w http.ResponseWriter, r *http.Request) {\n \n var cars []Car\n \n db.Find(&cars)\n \n json.NewEncoder(w).Encode(&cars)\n\n}\n\n// Getting cars with the id, where it will include name of driver & license\n\nfunc GetCar(w http.ResponseWriter, r *http.Request) {\nparams := mux.Vars(r)\n\n var car Car\n\n db.First(&car, params[\"id\"])\n\n json.NewEncoder(w).Encode(&car) \n}\n"
},
{
"answer_id": 74357737,
"author": "Ivan Pesenti",
"author_id": 14394371,
"author_profile": "https://Stackoverflow.com/users/14394371",
"pm_score": 2,
"selected": true,
"text": "Author Author"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19996278/"
] |
74,355,081 | <p>I try to install R packages by using devtools (for specific version) but got some errors.
I have to install packages that's specific version and use specific R version (4.1.*) plz.</p>
<h3>R, devtools version</h3>
<ul>
<li>R version : 4.1.3</li>
<li>devtools: 2.4.4
<a href="https://i.stack.imgur.com/AGuV2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AGuV2.png" alt="enter image description here" /></a></li>
</ul>
<h3>Install packages</h3>
<ul>
<li>forecast : 8.13</li>
<li>kernlab : 0.9-29</li>
</ul>
<h3>Install commands</h3>
<p><code>install_version("forecast", version = "8.13")</code>
<code>install_version("kernlab", version = "0.9-29")</code></p>
<p>or add option <code>dependencies=TRUE</code></p>
<h3>Error list</h3>
<pre><code>cc -I"/usr/share/R/include" -DNDEBUG -I'/usr/local/lib/R/site-library/Rcpp/include' -I
'/usr/local/lib/R/site-library/RcppArmadillo/include' -fpic -g -O2 -fdebug-prefix-ma
p=/build/r-base-NlA7dw/r-base-4.1.3=. -fstack-protector-strong -Wformat -Werror=format-s
ecurity -Wdate-time -D_FORTIFY_SOURCE=2 -g -c registerDynamicSymbol.c -o registerDynami
cSymbol.o
g++ -std=gnu++14 -I"/usr/share/R/include" -DNDEBUG -I'/usr/local/lib/R/site-library/Rcp
p/include' -I'/usr/local/lib/R/site-library/RcppArmadillo/include' -fpic -g -O2 -fde
bug-prefix-map=/build/r-base-NlA7dw/r-base-4.1.3=. -fstack-protector-strong -Wformat -We
rror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -g -c updateMatrices.cpp -o update
Matrices.o
g++ -std=gnu++14 -I"/usr/share/R/include" -DNDEBUG -I'/usr/local/lib/R/site-library/Rcp
p/include' -I'/usr/local/lib/R/site-library/RcppArmadillo/include' -fpic -g -O2 -fde
bug-prefix-map=/build/r-base-NlA7dw/r-base-4.1.3=. -fstack-protector-strong -Wformat -We
rror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -g -c updateTBATSMatrices.cpp -o u
pdateTBATSMatrices.o
g++ -std=gnu++14 -shared -L/usr/lib/R/lib -Wl,-Bsymbolic-functions -Wl,-z,relro -o forec
ast.so calcBATS.o calcTBATS.o etsTargetFunction.o etsTargetFunctionWrapper.o etscalc.o e
tspolyroot.o makeBATSMatrices.o makeTBATSMatrices.o registerDynamicSymbol.o updateMatric
es.o updateTBATSMatrices.o -llapack -lblas -lgfortran -lm -lquadmath -L/usr/lib/R/lib -l
R
/usr/bin/ld: cannot find -llapack
/usr/bin/ld: cannot find -lblas
collect2: error: ld returned 1 exit status
/usr/share/R/share/make/shlib.mk:10: recipe for target 'forecast.so' failed
make: *** [forecast.so] Error 1
ERROR: compilation failed for package ‘forecast’
* removing ‘/usr/local/lib/R/site-library/forecast’
경고메시지(들):
i.p(...)에서:
installation of package ‘/tmp/RtmpGgApec/remotes25555374bfb7/forecast’ had non-zero ex
it status
</code></pre>
<h3>Commands I've tried</h3>
<pre class="lang-bash prettyprint-override"><code>
sudo apt-get install g++
sudo apt install gfortran
sudo apt install libcurl4-gnutls-dev
R version upgrade 4.1.0 -> 4.1.3
R version downgrade 4.1.3 -> 4.1.0
install.packages('forecast')
install.packages('kernlab')
</code></pre>
| [
{
"answer_id": 74355268,
"author": "neilfws",
"author_id": 89482,
"author_profile": "https://Stackoverflow.com/users/89482",
"pm_score": 0,
"selected": false,
"text": "apt-cache search libXXX"
},
{
"answer_id": 74355319,
"author": "Dirk Eddelbuettel",
"author_id": 143305,
"author_profile": "https://Stackoverflow.com/users/143305",
"pm_score": 1,
"selected": false,
"text": "sudo apt-get install r-base-dev"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14932689/"
] |
74,355,101 | <p>Im working with fpdf that display two images every page, but it only display one picture every page.
Here is my code:</p>
<pre><code>$id = $_GET['id'];
$stmti = $database->prepare("SELECT * FROM inv_images WHERE id = :id");
$stmti->bindParam(':id',$id);
$stmti->execute();
$imageList = $stmti->fetchAll();
foreach ($imageList as $image) {
$pdf->AddPage();
$pdf->Image('dealers_picture/'.$image['name'],30,30,160,110);
}
</code></pre>
| [
{
"answer_id": 74355268,
"author": "neilfws",
"author_id": 89482,
"author_profile": "https://Stackoverflow.com/users/89482",
"pm_score": 0,
"selected": false,
"text": "apt-cache search libXXX"
},
{
"answer_id": 74355319,
"author": "Dirk Eddelbuettel",
"author_id": 143305,
"author_profile": "https://Stackoverflow.com/users/143305",
"pm_score": 1,
"selected": false,
"text": "sudo apt-get install r-base-dev"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19303061/"
] |
74,355,103 | <p>I am able to print the updated value of dataset but the new added row did not reflecting the updated data from the table component display.</p>
<p>I temporarily put the event on keypress to trigger for adding new row on the table, here the simple code that I playing.</p>
<pre><code>function createData(hardware, cost, status) {
return { hardware, cost, status };
}
const tblData = [];
class Main extends React.Component {
constructor(props) {
super(props);
this.state = {
tblData: [],
};
}
render() {
return (
<><><Box
sx={{
width: 500,
maxWidth: '100%',
}}
>
<TextField
fullWidth
label="Scan Here"
id="fullWidth"
onKeyPress={(e) => {
if (e.key === 'Enter') {
//*****--------------------------------------------------
// - Here is the part where I was able to get the updated data but not reflecting on the table display
console.log('Enter key pressed');
tblData.push(createData('blah', 356, 'Yes'));
console.log(tblData);
//
//--------------------------------------------------*****
}
} } />
</Box><TableContainer component={Paper}>
<Table sx={{ minWidth: 650, marginTop: '10px' }} aria-label="simple table">
<TableHead>
<TableRow>
<TableCell>Hardware</TableCell>
<TableCell align="right">Cost</TableCell>
<TableCell align="right">status</TableCell>
</TableRow>
</TableHead>
<TableBody>
{tblData.map((row) => (
<TableRow
key={row.name}
sx={{ '&:last-child td, &:last-child th': { border: 0 } }}
>
<TableCell component="th" scope="row">
{row.hardware}
</TableCell>
<TableCell align="right">{row.cost}</TableCell>
<TableCell align="right">{row.status}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer></>
)
}
}
export default Main;
</code></pre>
<p>Any suggestion or comments how to refresh the updated data. TIA</p>
| [
{
"answer_id": 74355268,
"author": "neilfws",
"author_id": 89482,
"author_profile": "https://Stackoverflow.com/users/89482",
"pm_score": 0,
"selected": false,
"text": "apt-cache search libXXX"
},
{
"answer_id": 74355319,
"author": "Dirk Eddelbuettel",
"author_id": 143305,
"author_profile": "https://Stackoverflow.com/users/143305",
"pm_score": 1,
"selected": false,
"text": "sudo apt-get install r-base-dev"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5191640/"
] |
74,355,188 | <p>I am in college and I have this assigment for data structures and algorithms, this is the project:
"Develop a program that asks the user to enter a capital for a U.S. state. Upon receiving the user input, the program reports whether the user input is correct. For this application, the 50 states and their capitals are stored in a two-dimensional array in order by state name. Display the current contents of the array then use a bubble sort to sort the content by capital. Next, prompt the user to enter answers for all the state capitals and then display the total correct count. The user's answer is not case-sensitive."</p>
<p>This is what I have done so far</p>
<pre><code>import java.util.Scanner;
import java.util.Arrays;
import java.lang.String;
public class Assignment {
// It begins with the creation of the two dimension array that includes state and capital.
public static void main (String[] args) {
String[][] StateAndCapital = {
{"Alabama", "Montgomery"},
{"Alaska", "Juneau"},
{"Arizona", "Phoenix"},
{"Arkansas", "Little Rock"},
{"California", "Sacramento"},
{"Colorado", "Denver"},
{"Connecticut", "Hartford"},
{"Delaware", "Dover"},
{"Florida", "Tallahassee"},
{"Georgia", "Atlanta"},
{"Hawaii", "Honolulu"},
{"Idaho", "Boise"},
{"Illinois", "Springfield"},
{"Indiana", "Indianapolis"},
{"Iowa", "Des Moines"},
{"Kansas", "Topeka"},
{"Kentucky", "Frankfort"},
{"Louisiana", "Baton Rouge"},
{"Maine", "Augusta"},
{"Maryland", "Annapolis"},
{"Massachusetts", "Boston"},
{"Michigan", "Lansing"},
{"Minnesota", "Saint Paul"},
{"Mississippi", "Jackson"},
{"Missouri", "Jefferson City"},
{"Montana", "Helena"},
{"Nebraska", "Lincoln"},
{"Nevada", "Carson City"},
{"New Hampshire", "Concord"},
{"New Jersey", "Trenton"},
{"New Mexico", "Santa Fe"},
{"New York", "Albany"},
{"North Carolina", "Raleigh"},
{"North Dakota", "Bismarck"},
{"Ohio", "Columbus"},
{"Oklahoma", "Oklahoma City"},
{"Oregon", "Salem"},
{"Pennsylvania", "Harrisburg"},
{"Rhode Island", "Providence"},
{"South Carolina", "Columbia"},
{"South Dakota", "Pierre"},
{"Tennessee", "Nashville"},
{"Texas", "Austin"},
{"Utah", "Salt Lake City"},
{"Vermont", "Montpelier"},
{"Virginia", "Richmond"},
{"Washington", "Olympia"},
{"West Virginia", "Charleston"},
{"Wisconsin", "Madison"},
{"Wyoming", "Cheyenne"}
};
</code></pre>
<p>So far I have created the 2d array, I need to have a for loop so the system goes through the array. But I am not sure on how to create a for loop for a two dimension array, I have watched videos for bubble sorting (required for the assignment) and what my lessons mention but they mainly show how to do it on a single dimension array.</p>
<pre><code> for (int i = 1; i < array.length; i++) {
for (int j = i; j > 0; j--) {
if (array[j] < array [j - 1]) {
temp = array[j];
array[j] = array[j - 1];
array[j - 1] = temp;
</code></pre>
<p>That is from a lesson, using a single array, but not sure how to do it with a two dimension array.</p>
<p>I also looked into how to convert string to boolean so whenever the user answered, the system would say either "correct answer" or "incorrect answer". If I could get some advice please, I am starting and this may be a dumb question.</p>
<p>I tried changing string value to boolean values so whenever I replied to the system I would get a "correct" or "wrong" answer according to the true/false values assigned to an array of only states, but all answers seemed to say true regardless of my input, which is odd. I am still looking for a way to validate string values.
I have used the scanner to scan the answer given by the user, looked at boolean programs to see if I can see something that I could use but try to make it string-based.</p>
| [
{
"answer_id": 74355268,
"author": "neilfws",
"author_id": 89482,
"author_profile": "https://Stackoverflow.com/users/89482",
"pm_score": 0,
"selected": false,
"text": "apt-cache search libXXX"
},
{
"answer_id": 74355319,
"author": "Dirk Eddelbuettel",
"author_id": 143305,
"author_profile": "https://Stackoverflow.com/users/143305",
"pm_score": 1,
"selected": false,
"text": "sudo apt-get install r-base-dev"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20433523/"
] |
74,355,201 | <p>I have a game-level map image like this and I code by manual HTML - CSS - JS. I want to attach
the level number <strong>based on the coordinates of the image</strong> but it moves to another position for another screen. I have used relative position for the parent element and absolute position for child elements. (I tried using px, em, rem, in, cm unit, but it hasn't worked well)
<a href="https://i.stack.imgur.com/oH2bD.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oH2bD.jpg" alt="enter image description here" /></a></p>
<p>I just want an idea for this problem. Thank you!</p>
| [
{
"answer_id": 74355235,
"author": "LeFede",
"author_id": 19694564,
"author_profile": "https://Stackoverflow.com/users/19694564",
"pm_score": 0,
"selected": false,
"text": "<div class=\"image\">\n <span id=\"span-1\">1</span>\n <span id=\"span-2\">2</span>\n</div>\n"
},
{
"answer_id": 74355323,
"author": "cbenitez",
"author_id": 16525519,
"author_profile": "https://Stackoverflow.com/users/16525519",
"pm_score": 2,
"selected": true,
"text": "(I tried using px, em, rem, in, cm unit, but it hasn't worked well)"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20024455/"
] |
74,355,219 | <p>I am trying to conncect MSSQL DB to python, and the DB's password has included a character '#'.</p>
<p>Is there any way to use '#' in string, not changing the password?</p>
| [
{
"answer_id": 74355235,
"author": "LeFede",
"author_id": 19694564,
"author_profile": "https://Stackoverflow.com/users/19694564",
"pm_score": 0,
"selected": false,
"text": "<div class=\"image\">\n <span id=\"span-1\">1</span>\n <span id=\"span-2\">2</span>\n</div>\n"
},
{
"answer_id": 74355323,
"author": "cbenitez",
"author_id": 16525519,
"author_profile": "https://Stackoverflow.com/users/16525519",
"pm_score": 2,
"selected": true,
"text": "(I tried using px, em, rem, in, cm unit, but it hasn't worked well)"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20335745/"
] |
74,355,223 | <p>I am trying to extract from URL str "/used/Mercedes-Benz/2021-Mercedes-Benz-Sprinte..."
the entire Make name, i.e. "Mercedes-Benz"
BUT my pattern only returns the first letter, i.e. "M"</p>
<p>Please help me come up with the correct pattern to use on pandas df.</p>
<p>Thank you</p>
<p>CODE:
<code>URLS_by_City['Make'] = URLS_by_City['Page'].str.extract('.+([A-Z])\w+(?=[\/])+', expand=True) Clean_Make = URLS_by_City.dropna(subset=["Make"]) Clean_Make # WENT FROM 5K rows --> to 2688 rows</code></p>
<pre><code> Page City Pageviews Unique Pageviews Avg. Time on Page Entrances Bounce Rate % Exit **Make**
71 /used/Mercedes-Benz/2021-Mercedes-Benz-Sprinte... San Jose 310 149 00:00:27 149 2.00% 47.74% **B**
103 /used/Audi/2015-Audi-SQ5-286f67180a0e09a872992... Menlo Park 250 87 00:02:36 82 0.00% 32.40% **A**
158 /used/Mercedes-Benz/2021-Mercedes-Benz-Sprinte... San Francisco 202 98 00:00:18 98 2.04% 48.02% **B**
165 /used/Audi/2020-Audi-S8-c6df09610a0e09af26b5cf... San Francisco 194 93 00:00:42 44 2.22% 29.38% **A**
168 /used/Mercedes-Benz/2021-Mercedes-Benz-Sprinte... (not set) 192 91 00:00:11 91 2.20% 47.40% **B**
... ... ... ... ... ... ... ... ... ...
4995 /used/Subaru/2019-Subaru-Crosstrek-5717b3040a0... Union City 10 3 00:02:02 0 0.00% 30.00% **S**
4996 /used/Tesla/2017-Tesla-Model+S-15605a190a0e087... San Jose 10 5 00:01:29 5 0.00% 50.00% **T**
4997 /used/Tesla/2018-Tesla-Model+3-0f3ea14d0a0e09a... Las Vegas 10 4 00:00:09 2 0.00% 40.00% **T**
4998 /used/Tesla/2018-Tesla-Model+3-0f3ea14d0a0e09a... Austin 10 4 00:03:29 2 0.00% 40.00% **T**
4999 /used/Tesla/2018-Tesla-Model+3-5f29cdc70a0e09a... Orinda 10 4 00:04:00 1 0.00% 0.00% **T**
</code></pre>
<p>TRIED:
`example_url = "/used/Mercedes-Benz/2021-Mercedes-Benz-Sprinter+2500-9f3d32130a0e09af63592c3c48ac5c24.htm?store_code=AudiOakland&ads_adgroup=139456079219&ads_adid=611973748445&ads_digadprovider=adpearance&adpdevice=m&campaign_id=17820707224&adpprov=1"
pattern = ".+([a-zA-Z0-9()])\w+(?=[/])+"</p>
<pre><code>wanted_make = URLS_by_City['Page'].str.extract(pattern)
wanted_make
</code></pre>
<p>`
0
0 r
1 r
2 NaN
3 NaN
4 r
... ...
4995 r
4996 l
4997 l
4998 l
4999 l</p>
<p>It worked in regex online tool.</p>
<p>but unfortunately not in my jupyter notebook</p>
<p>EXAMPLE PATTERNS - I bolded what should match:
/used/<strong>Mercedes-Benz</strong>/2021-Mercedes-Benz-Sprinter+2500-9f3d32130a0e09af63592c3c48ac5c24.htm?store_code=AudiOakland&ads_adgroup=139456079219&ads_adid=611973748445&ads_digadprovider=adpearance&adpdevice=m&campaign_id=17820707224&adpprov=1
/used/<strong>Audi</strong>/2020-Audi-S8-c6df09610a0e09af26b5cff998e0f96e.htm
/used/<strong>Mercedes-Benz</strong>/2021-Mercedes-Benz-Sprinter+2500-9f3d32130a0e09af63592c3c48ac5c24.htm?store_code=AudiOakland&ads_adgroup=139456079219&ads_adid=611973748445&ads_digadprovider=adpearance&adpdevice=m&campaign_id=17820707224&adpprov=1
/used/<strong>Audi</strong>/2021-Audi-RS+5-b92922bd0a0e09a91b4e6e9a29f63e8f.htm
/used/<strong>LEXUS</strong>/2018-LEXUS-GS+350-dffb145e0a0e09716bd5de4955662450.htm
/used/<strong>Porsche</strong>/2014-Porsche-Boxster-0423401a0a0e09a9358a179195e076a9.htm
/used/<strong>Audi</strong>/2014-Audi-A6-1792929d0a0e09b11bc7e218a1fa7563.htm
/used/<strong>Honda</strong>/2018-Honda-Civic-8e664dd50a0e0a9a43aacb6d1ab64d28.htm
/new-inventory/index.htm?normalFuelType=Hybrid&normalFuelType=Electric
/used-inventory/index.htm
/new-inventory/index.htm
/new-inventory/index.htm?normalFuelType=Hybrid&normalFuelType=Electric
/</p>
| [
{
"answer_id": 74355253,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 0,
"selected": false,
"text": "URLS_by_City[\"Make\"] = URLS_by_City[\"Page\"].str.extract(r'([^/]+)/\\d{4}\\b')\n"
},
{
"answer_id": 74369855,
"author": "Sachin Nayak",
"author_id": 8191861,
"author_profile": "https://Stackoverflow.com/users/8191861",
"pm_score": 0,
"selected": false,
"text": "pattern2 = '^/used/[a-zA-Z\\-]*/([0-9]{4}[a-zA-Z0-9\\-+]*)-[a-z0-9]*.htm'\npattern3 = '^/used/[a-zA-Z\\-]*/[0-9]{4}[a-zA-Z0-9\\-+]*-([a-z0-9]*).htm'\n\ndata_df['Model'] = data_df['urls'].str.extract(pattern2)\ndata_df['VIN'] = data_df['urls'].str.extract(pattern3)\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20445487/"
] |
74,355,230 | <p>I want to remove JSON properties by a specific "key" but it is not working as I expected. My code hasn't changed a thing.</p>
<p>I did the following</p>
<pre><code>void Start()
{
var foodlist = new List<Food>()
{
new() { name = "Banana", price = 3000 },
new() { name = "Apple", price = 1000}
};
// SerializeObject()
string jasonString = JsonConvert.SerializeObject(foodlist);
JArray jArray = JArray.Parse(jasonString);
// Jarray => String Serialize
string jarrayString2 = JsonConvert.SerializeObject(jArray);
foreach (var jObject in jArray.Children<JObject>())
{
int indexNum = 0;
foreach (var jProperty in jObject.Properties())
{
if(jProperty.Name == "name")
{
jArray.Remove(jArray[indexNum][jProperty.Name]);
indexNum++;
}
}
}
// Check
string jarrayString = JsonConvert.SerializeObject(jArray);
print(jarrayString);
}
public class Food
{
public string name;
public int price;
}
</code></pre>
<p>**The result hasn't changed **
Output
<code>[{"name":"Banana","price":3000},{"name":"Apple","price":1000}]</code></p>
<p>Result that I want
<code>[{"price":3000},{"price":1000}]</code></p>
| [
{
"answer_id": 74355253,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 0,
"selected": false,
"text": "URLS_by_City[\"Make\"] = URLS_by_City[\"Page\"].str.extract(r'([^/]+)/\\d{4}\\b')\n"
},
{
"answer_id": 74369855,
"author": "Sachin Nayak",
"author_id": 8191861,
"author_profile": "https://Stackoverflow.com/users/8191861",
"pm_score": 0,
"selected": false,
"text": "pattern2 = '^/used/[a-zA-Z\\-]*/([0-9]{4}[a-zA-Z0-9\\-+]*)-[a-z0-9]*.htm'\npattern3 = '^/used/[a-zA-Z\\-]*/[0-9]{4}[a-zA-Z0-9\\-+]*-([a-z0-9]*).htm'\n\ndata_df['Model'] = data_df['urls'].str.extract(pattern2)\ndata_df['VIN'] = data_df['urls'].str.extract(pattern3)\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20445491/"
] |
74,355,231 | <p>I am working on a pipeline to dynamically dump all columns from the salesforce object to the S3 bucket.
I get all columns for a salesforce object using describe object API. I store all columns into a variable and then create a big SOQL query out of it and submit a bulk query job v2.</p>
<p>Now, this is the main problem. The Column name I am getting from the salesforce connector is in camelCase</p>
<pre><code> [{
"Id": 123,
"FirstName": "Manual",
"MasterRecordId__c" :"abc"
},
{
"Id": 456,
"FirstName": "John",
"MasterRecordId__c" :"def"
}]
</code></pre>
<p>But I want column names to be in snake case</p>
<pre><code>[{
"Id": 123,
"first_name": "Manual",
"master_record_id__c":"abc"
},
{
"Id": 456,
"first_name": "john",
"master_record_id__c":"def"
}]
</code></pre>
<p>I understand mulesoft has an <strong>underscore</strong> function to do the same thing, but I am not able to apply any function at "key" level.</p>
<p>Any lead would be really helpful. Please let me know for any questions.</p>
| [
{
"answer_id": 74356082,
"author": "Harshank Bansal",
"author_id": 10946202,
"author_profile": "https://Stackoverflow.com/users/10946202",
"pm_score": 3,
"selected": true,
"text": "mapObject"
},
{
"answer_id": 74356110,
"author": "StackOverflowed",
"author_id": 7255897,
"author_profile": "https://Stackoverflow.com/users/7255897",
"pm_score": 1,
"selected": false,
"text": "%dw 2.0\nimport * from dw::core::Strings\noutput application/json \n---\npayload map ($ mapObject ((value, key, index) -> if (capitalize(key as String) == key as String)\n {\n (key): value\n }\n else\n {\n (underscore(key)): value\n }))\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17967163/"
] |
74,355,233 | <p>I would like to stack my dataset so all observations relate to all other observations but itself.
Suppose I have the following dataset:</p>
<pre><code>df <- data.frame(id = c("a", "b", "c", "d" ),
x1 = c(1,2,3,4))
df
id x1
1 a 1
2 b 2
3 c 3
4 d 4
</code></pre>
<p>I would like observation a to be related to b, c, and d. And the same for every other observation. The result should look like something like this:</p>
<pre><code> id x1 id2 x2
1 a 1 b 2
2 a 1 c 3
3 a 1 d 4
4 b 2 a 1
5 b 2 c 3
6 b 2 d 4
7 c 3 a 1
8 c 3 b 2
9 c 3 d 4
10 d 4 a 1
11 d 4 b 2
12 d 4 c 3
</code></pre>
<p>So observation a is related to b,c,d. Observation b is related to a, c,d. And so on. Any ideas?</p>
| [
{
"answer_id": 74355281,
"author": "Ritchie Sacramento",
"author_id": 2835261,
"author_profile": "https://Stackoverflow.com/users/2835261",
"pm_score": 2,
"selected": false,
"text": "tidyr::expand_grid()"
},
{
"answer_id": 74355312,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 2,
"selected": false,
"text": "combn()"
},
{
"answer_id": 74355447,
"author": "Jon Spring",
"author_id": 6851825,
"author_profile": "https://Stackoverflow.com/users/6851825",
"pm_score": 3,
"selected": true,
"text": "library(dplyr)\nleft_join(df, df, by = character()) %>%\n filter(id.x != id.y) \n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19991656/"
] |
74,355,269 | <p>I have a dataframe like:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>header1</th>
<th>header2</th>
<th>header3</th>
<th>header4</th>
</tr>
</thead>
<tbody>
<tr>
<td>NA</td>
<td>NA</td>
<td>x</td>
<td>y</td>
</tr>
<tr>
<td>a</td>
<td>NA</td>
<td>d</td>
<td>b</td>
</tr>
<tr>
<td>NA</td>
<td>b</td>
<td>y</td>
<td>NA</td>
</tr>
<tr>
<td>c</td>
<td>x</td>
<td>NA</td>
<td>a</td>
</tr>
</tbody>
</table>
</div>
<p>I would like to replace all non-NA cells (i.e. that have value: a, b, c, d, x, y, z) with the header names:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>header1</th>
<th>header2</th>
<th>header3</th>
<th>header4</th>
</tr>
</thead>
<tbody>
<tr>
<td>NA</td>
<td>NA</td>
<td>header3</td>
<td>header4</td>
</tr>
<tr>
<td>header1</td>
<td>NA</td>
<td>header3</td>
<td>header4</td>
</tr>
<tr>
<td>NA</td>
<td>header2</td>
<td>header3</td>
<td>NA</td>
</tr>
<tr>
<td>header1</td>
<td>header2</td>
<td>NA</td>
<td>header4</td>
</tr>
</tbody>
</table>
</div>
<p>Thanks!</p>
| [
{
"answer_id": 74355318,
"author": "Ricardo Semião e Castro",
"author_id": 13048728,
"author_profile": "https://Stackoverflow.com/users/13048728",
"pm_score": 2,
"selected": false,
"text": "cur_column()"
},
{
"answer_id": 74355584,
"author": "Dan Kennedy",
"author_id": 14460409,
"author_profile": "https://Stackoverflow.com/users/14460409",
"pm_score": 2,
"selected": false,
"text": "tidyverse"
},
{
"answer_id": 74355667,
"author": "thelatemail",
"author_id": 496803,
"author_profile": "https://Stackoverflow.com/users/496803",
"pm_score": 2,
"selected": false,
"text": "df[!is.na(df)] <- names(df)[col(df)[!is.na(df)]]\n"
},
{
"answer_id": 74355965,
"author": "AndrewGB",
"author_id": 15293191,
"author_profile": "https://Stackoverflow.com/users/15293191",
"pm_score": 1,
"selected": false,
"text": "ifelse"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19489286/"
] |
74,355,273 | <p>I'm setting up a pipeline that provisions resources in AWS. Each time I run the pipeline, I get get a module already exist error. I know the resources I want I already provisioned but my understanding of Terraform is that if it already exists it just skips it and provisions the rest that don't already exist. How do I make it skip existing modules and not result into a pipeline build error.</p>
| [
{
"answer_id": 74355318,
"author": "Ricardo Semião e Castro",
"author_id": 13048728,
"author_profile": "https://Stackoverflow.com/users/13048728",
"pm_score": 2,
"selected": false,
"text": "cur_column()"
},
{
"answer_id": 74355584,
"author": "Dan Kennedy",
"author_id": 14460409,
"author_profile": "https://Stackoverflow.com/users/14460409",
"pm_score": 2,
"selected": false,
"text": "tidyverse"
},
{
"answer_id": 74355667,
"author": "thelatemail",
"author_id": 496803,
"author_profile": "https://Stackoverflow.com/users/496803",
"pm_score": 2,
"selected": false,
"text": "df[!is.na(df)] <- names(df)[col(df)[!is.na(df)]]\n"
},
{
"answer_id": 74355965,
"author": "AndrewGB",
"author_id": 15293191,
"author_profile": "https://Stackoverflow.com/users/15293191",
"pm_score": 1,
"selected": false,
"text": "ifelse"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11734835/"
] |
74,355,274 | <pre><code>Listening on port 3000
/backend/node_modules/ioredis/built/Command.js:43
this.args = args.flat();
^
TypeError: args.flat is not a function
at new Command (/Users/apple/Desktop/bbs-backend/node_modules/ioredis/built/Command.js:43:26)
at EventEmitter.info (/Users/apple/Desktop/bbs-backend/node_modules/ioredis/built/utils/Commander.js:92:13)
at EventEmitter._readyCheck (/Users/apple/Desktop/bbs-backend/node_modules/ioredis/built/Redis.js:623:14)
at Socket.<anonymous> (/Users/apple/Desktop/bbs-backend/node_modules/ioredis/built/redis/event_handler.js:58:18)
at Object.onceWrapper (events.js:273:13)
at Socket.emit (events.js:187:15)
at Socket.EventEmitter.emit (domain.js:442:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1099:10)
</code></pre>
<ol>
<li>reinstall npm packages & restart redis server - not working</li>
</ol>
| [
{
"answer_id": 74355318,
"author": "Ricardo Semião e Castro",
"author_id": 13048728,
"author_profile": "https://Stackoverflow.com/users/13048728",
"pm_score": 2,
"selected": false,
"text": "cur_column()"
},
{
"answer_id": 74355584,
"author": "Dan Kennedy",
"author_id": 14460409,
"author_profile": "https://Stackoverflow.com/users/14460409",
"pm_score": 2,
"selected": false,
"text": "tidyverse"
},
{
"answer_id": 74355667,
"author": "thelatemail",
"author_id": 496803,
"author_profile": "https://Stackoverflow.com/users/496803",
"pm_score": 2,
"selected": false,
"text": "df[!is.na(df)] <- names(df)[col(df)[!is.na(df)]]\n"
},
{
"answer_id": 74355965,
"author": "AndrewGB",
"author_id": 15293191,
"author_profile": "https://Stackoverflow.com/users/15293191",
"pm_score": 1,
"selected": false,
"text": "ifelse"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8764571/"
] |
74,355,282 | <p>I have a txt file and I want to add or change its contents based on the characters on each line,</p>
<p>let's say i wanted to add string "--" on each line but break the iteration when found string "*******" and continue add string "--" after found "#######"</p>
<p><strong>Input file</strong></p>
<pre><code>aaaaaaa
bbbbbbb
*******
1234567
7654321
#######
ddddddd
eeeeeee
</code></pre>
<p><strong>Desired Output</strong></p>
<pre><code>-- aaaaaaa
-- bbbbbbb
*******
1234567
7654321
#######
-- ddddddd
-- eeeeeee
</code></pre>
<p><strong>My Code</strong></p>
<pre><code>file_name = 'abc.txt'
for line in fileinput.FileInput(file_name,inplace=1):
line = line.replace(line,'--' + line)
if '*******' in line:
break
print(line)
elif '#######' in line:
continue
print(line)
</code></pre>
<p><strong>But Give me this Result</strong></p>
<pre><code>-- aaaaaaa
-- bbbbbbb
-- *******
</code></pre>
| [
{
"answer_id": 74355318,
"author": "Ricardo Semião e Castro",
"author_id": 13048728,
"author_profile": "https://Stackoverflow.com/users/13048728",
"pm_score": 2,
"selected": false,
"text": "cur_column()"
},
{
"answer_id": 74355584,
"author": "Dan Kennedy",
"author_id": 14460409,
"author_profile": "https://Stackoverflow.com/users/14460409",
"pm_score": 2,
"selected": false,
"text": "tidyverse"
},
{
"answer_id": 74355667,
"author": "thelatemail",
"author_id": 496803,
"author_profile": "https://Stackoverflow.com/users/496803",
"pm_score": 2,
"selected": false,
"text": "df[!is.na(df)] <- names(df)[col(df)[!is.na(df)]]\n"
},
{
"answer_id": 74355965,
"author": "AndrewGB",
"author_id": 15293191,
"author_profile": "https://Stackoverflow.com/users/15293191",
"pm_score": 1,
"selected": false,
"text": "ifelse"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20445538/"
] |
74,355,302 | <p>I am trying to build an app to replicate a video streamer.
I have encountered an issue that can't seem to solve.</p>
<p>The app is working fine when run in an emulator (tried a few emulated devices) but it is crashing 99% of the time in my Samsung android tablet running android 12L.</p>
<p>I have noticed that the app works 100% of the time, when commenting out the</p>
<pre><code>bannerMoviesViewPager.setAdapter(bannerMoviesPagerAdapter);
</code></pre>
<p>I was hoping someone has some insight of why this could happen, and also, why does it not crash when running in an emulator.
Here are segments of code that I think might be important to share, but please let me know if more is needed (i am quite new at stack overflow)</p>
<pre><code>private void setBannerMoviesPagerAdapter(List<BannerMovies> bannerMoviesList){
bannerMoviesViewPager = (ViewPager) findViewById(R.id.banner_viewPager);
bannerMoviesPagerAdapter = new BannerMoviesPagerAdapter(this, bannerMoviesList);
bannerMoviesViewPager.setAdapter(bannerMoviesPagerAdapter); // COMMENT THIS LINE AND IT WORKS
//tabLayout.setupWithViewPager(bannerMoviesViewPager);
Timer sliderTimer = new Timer();
sliderTimer.scheduleAtFixedRate(new AutoSlider(), 4000, 6000);
tabLayout.setupWithViewPager(bannerMoviesViewPager, true);
}
</code></pre>
<pre><code>public void fetch_json_banner_list(){
System.out.println("Attempting to fetch JSON");
final String url = "http://*serverIP*:80/api/movie";
Request request = new Request.Builder().url(url).build();
OkHttpClient client = new OkHttpClient();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
System.out.println("Failed to execute request");
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
bannerMoviesList = new ArrayList<>();
String body = response.body().string();
Gson gson = new GsonBuilder().create();
Type allFilmsType = new TypeToken<ArrayList<Film>>(){}.getType();
List<Film> allFilms = gson.fromJson(body, allFilmsType);
for(Film film : allFilms){
System.out.println(film.getArtwork());
System.out.println(film.getArtwork().equals("https://media.movieassets.com/static/images/items/movies/posters/216767680a8a72fff4a12c484c6ac589.jpg"));
bannerMoviesList.add(new BannerMovies(film.getMovieId(), film.getTitle(), film.getSynopsis(), film.getArtwork().trim(), "https://ia800306.us.archive.org/35/items/PopeyeAliBaba/PopeyeAliBaba_512kb.mp4"));
}
setBannerMoviesPagerAdapter(bannerMoviesList);
}
});
}
</code></pre>
<pre><code>public class BannerMoviesPagerAdapter extends PagerAdapter {
Context context;
List<BannerMovies> bannerMoviesList;
public BannerMoviesPagerAdapter(Context context, List<BannerMovies> bannerMoviesList) {
this.context = context;
this.bannerMoviesList = bannerMoviesList;
System.out.println("GETS HERE....");
}
@Override
public int getCount() {
return bannerMoviesList.size();
}
</code></pre>
<p>Also, here is the last part of the logcat for the process..</p>
<p><a href="https://i.stack.imgur.com/qUo38.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>I would very much appreciate any help
Thanks</p>
<p>I double checked if I was reading / using the response body more than once.</p>
| [
{
"answer_id": 74355338,
"author": "zaitsman",
"author_id": 2057955,
"author_profile": "https://Stackoverflow.com/users/2057955",
"pm_score": 1,
"selected": true,
"text": "setBannerMoviesPagerAdapter(bannerMoviesList);\n"
},
{
"answer_id": 74355459,
"author": "Ian Nemo",
"author_id": 20200526,
"author_profile": "https://Stackoverflow.com/users/20200526",
"pm_score": 1,
"selected": false,
"text": "setBannerMoviesPagerAdapter(bannerMoviesList);\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20200526/"
] |
74,355,304 | <p>I get a website (<a href="https://www.diabetesdaily.com/forum/threads/had-a-friend-with-type-one.136015/" rel="nofollow noreferrer">https://www.diabetesdaily.com/forum/threads/had-a-friend-with-type-one.136015/</a>)</p>
<p>And I found there are many forum pages
<a href="https://i.stack.imgur.com/3TZpC.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3TZpC.jpg" alt="enter image description here" /></a></p>
<p>Want to use the for loop for web scrapping, therefore could I ask, how I get the maximum number of forum pages on this page by BeaurifulSoup?
Many thanks.</p>
| [
{
"answer_id": 74355338,
"author": "zaitsman",
"author_id": 2057955,
"author_profile": "https://Stackoverflow.com/users/2057955",
"pm_score": 1,
"selected": true,
"text": "setBannerMoviesPagerAdapter(bannerMoviesList);\n"
},
{
"answer_id": 74355459,
"author": "Ian Nemo",
"author_id": 20200526,
"author_profile": "https://Stackoverflow.com/users/20200526",
"pm_score": 1,
"selected": false,
"text": "setBannerMoviesPagerAdapter(bannerMoviesList);\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17429194/"
] |
74,355,309 | <p>The code is shown below.</p>
<pre class="lang-html prettyprint-override"><code><v-container fluid>
<!-- page title -->
<v-row>
…
</v-row>
<!-- body -->
<v-row justify="center" no-gutters>
<!-- input -->
<v-col cols="5">
<v-card outlined height="80vh" max-height="80vh" class="pa-8">
<!-- image upload -->
<v-row>
<v-col>
<v-file-input
accept="image/png, image/jpeg"
chips
label="Choose an image(JPG or PNG)"
outlined
prepend-icon="image"
show-size
v-model="image"
@change="previewImage"
@click:clear="clearAll"
></v-file-input>
</v-col>
</v-row>
<!-- image preview -->
<v-row>
<v-col>
<p v-if="no_image" class="text-center text-h4 grey--text">
Image Preview
</p>
<v-img v-else :src="imageUrl" contain max-height="55vh"></v-img>
</v-col>
</v-row>
</v-card>
</v-col>
<!-- button -->
<v-col align-self="center" cols="2">
…
</v-col>
<!-- output -->
<v-col cols="5" align-self="center">
…
</v-col>
</v-row>
</v-container>
</code></pre>
<p>Current style is <a href="https://i.stack.imgur.com/pk6m7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pk6m7.png" alt="Current Style" /></a></p>
<p>but the p element "Image Preview" is expected to be centered vertically in the v-card.<br />
I have tried to add some properties like <code>align="center"</code>, <code>class="align-center"</code>, <code>align-self="center"</code> and more to some relative elements but none of them work.<br />
How can I do this?</p>
| [
{
"answer_id": 74355382,
"author": "Zillion Dev",
"author_id": 18552333,
"author_profile": "https://Stackoverflow.com/users/18552333",
"pm_score": -1,
"selected": false,
"text": "display: flex;\nalign-items: center;\n"
},
{
"answer_id": 74355461,
"author": "kissu",
"author_id": 8816585,
"author_profile": "https://Stackoverflow.com/users/8816585",
"pm_score": 1,
"selected": true,
"text": "<template>\n <v-container fluid>\n <v-row>\n </v-row>\n <v-row justify=\"center\" no-gutters>\n <v-col cols=\"5\">\n <v-card outlined height=\"80vh\" max-height=\"80vh\" class=\"pa-8 d-flex flex-column\">\n <v-row class=\"flex-grow-0\">\n <v-col>\n <v-file-input accept=\"image/png, image/jpeg\" chips label=\"Choose an image(JPG or PNG)\" outlined\n prepend-icon=\"image\">\n </v-file-input>\n </v-col>\n </v-row>\n <v-row>\n <v-col class=\"d-flex flex-column justify-center\">\n <p class=\"text-center text-h4 grey--text\">\n Image Preview\n </p>\n </v-col>\n </v-row>\n </v-card>\n </v-col>\n <v-col align-self=\"center\" cols=\"2\">\n </v-col>\n <v-col cols=\"5\" align-self=\"center\">\n </v-col>\n </v-row>\n </v-container>\n</template>\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20051128/"
] |
74,355,327 | <p>Is there a way to add text labels to the points on a scatterplot? Each point has a string associated with it as its label. I like to label only as many points as it can be done withour overlapping?</p>
<pre><code>df = DataFrame(x=rand(100), y=rand(100), z=randstring.(fill(5,100)))
scatter(df.x, df.y)
annotate!(df.x, df.y, text.(df.z))
</code></pre>
| [
{
"answer_id": 74366069,
"author": "Bill",
"author_id": 4282847,
"author_profile": "https://Stackoverflow.com/users/4282847",
"pm_score": 0,
"selected": false,
"text": "series_annotations"
},
{
"answer_id": 74368256,
"author": "giantmoa",
"author_id": 20258205,
"author_profile": "https://Stackoverflow.com/users/20258205",
"pm_score": 3,
"selected": true,
"text": "StatisticalGraphics"
},
{
"answer_id": 74368731,
"author": "cbsteh",
"author_id": 7051064,
"author_profile": "https://Stackoverflow.com/users/7051064",
"pm_score": 1,
"selected": false,
"text": "Makie.jl"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355327",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17988569/"
] |
74,355,350 | <p>So I need to go through a loop and apply conditional statement in every element inside the matrices' rows.
conditions need to be checked:</p>
<ol>
<li>whether the elements is alphabet or not, if yes append it if not go for next conditional checking</li>
<li>next checking should be checking if its symbol/non-alphabet AND its next element(i used <code>j+1</code> for indexing) is also symbol/non-alphabet, if this is true then append a ' '(one blank space). but when I run this, it will stumbles on 'list index out of range' error due to last elements of every row cant access <code>j+1</code> index. then, i created another pre-loop to check if the elements is last element or not. if its the last element go for next loop for simple checkup.</li>
</ol>
<pre><code> clinput2=[['T', 'h', 'i', 's', '$', '#', 'i'],
['s', '%', ' ', 'S', 'p', 'a', 'r'],
['t', 'a', '#', ' ', ' ', '%', '!']]
for j in range(len(clinput2[0])):
# print (clinput2[i][j])
if (clinput2[i][j].isalpha()):
cara.append(clinput2[i][j])
elif (not clinput2[i][j].isalpha() ):
if j+1<len(clinput2[i]):
if (not clinput2[i][j+1].isalpha() or clinput2[i][j+1]==' '):
cara.append(' ')
j+=1
elif (not clinput2[i][j].isalpha() or clinput2[i][j]==' '):
pass
</code></pre>
<p>desired output: <code>This is Sparta</code></p>
<p>so how do i do this without if statement?, for now I'm able to do it with if statement, but the requirement is not to use if statement.</p>
<p>i tried this way of conditional statement but cant find a way to nest the condition, passing a function in the paremeter would be too dirty and too long:</p>
<pre><code>['pass', cara.append(clinput2[i][j])][clinput2[i][j].isalpha()]
</code></pre>
<p>the original method:</p>
<pre><code>print ["no", "yes"][x > y]
</code></pre>
<p>How do I do this without if statement?</p>
| [
{
"answer_id": 74366069,
"author": "Bill",
"author_id": 4282847,
"author_profile": "https://Stackoverflow.com/users/4282847",
"pm_score": 0,
"selected": false,
"text": "series_annotations"
},
{
"answer_id": 74368256,
"author": "giantmoa",
"author_id": 20258205,
"author_profile": "https://Stackoverflow.com/users/20258205",
"pm_score": 3,
"selected": true,
"text": "StatisticalGraphics"
},
{
"answer_id": 74368731,
"author": "cbsteh",
"author_id": 7051064,
"author_profile": "https://Stackoverflow.com/users/7051064",
"pm_score": 1,
"selected": false,
"text": "Makie.jl"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18489452/"
] |
74,355,352 | <p>In my website there is, 6 digit random numbers known as <code>refno</code> Example <code>20221234</code>and there is fileupload. Right now, it saves the photos with its own name on to the another filepath example<code>cat.png</code>. Currently, I tried to add that <code>refno</code>in front of the picture while saving like<code>20221234cat.png</code>. Is that possible to do?</p>
<pre><code><?php
$refno = isset ($_GET['refno'])? $_GET['refno']:'';
$file = isset($_FILES["file"]["tmp_name"])? $_FILES["file"]["tmp_name"] : "";
$file_size = isset($_FILES["file"]["size"])? $_FILES["file"]["size"] : "";
$file_name = isset($_FILES["file"]["name"])? $_FILES["file"]["name"] : "";
if(isset($_POST['submit']))
{
$dataDir = "//sgewsnant21.amk.st.com/ews/web/webspool/temp/visualdefectreport/";
if ($file_size <= 0)
{
echo "<script language=\"javascript\" type=\"text/javascript\">";
echo " alert('No picture attached!')";
//echo $refno;
echo "</script>";
}
else
{
if(stristr($file_name, ".png")){
$connection = mysqli_connect($apews_db_apews2, $apews_db_usr, $apews_db_pwd) or die ("Unableeeee to connect!");
$dest = $dataDir.$file_name;
if(move_uploaded_file($file,$dest))
{
echo "<script language=\"javascript\" type=\"text/javascript\">";
echo " alert('Visual Defect Report and pictures are successfully submitted!')";
//echo $refno;
echo "</script>";
}
}
else if(stristr($file_name, ".jpg")){
$connection = mysqli_connect($apews_db_apews2, $apews_db_usr, $apews_db_pwd) or die ("Unableeeee to connect!");
$dest = $dataDir.$file_name;
if(move_uploaded_file($file,$dest))
{
echo "<script language=\"javascript\" type=\"text/javascript\">";
echo " alert('Visual Defect Report and pictures are successfully submitted!')";
//echo $refno;
echo "</script>";
}
}
else if(stristr($file_name, ".jpeg")){
$connection = mysqli_connect($apews_db_apews2, $apews_db_usr, $apews_db_pwd) or die ("Unableeeee to connect!");
$dest = $dataDir.$file_name;
if(move_uploaded_file($file,$dest))
{
echo "<script language=\"javascript\" type=\"text/javascript\">";
echo " alert('Visual Defect Report and pictures are successfully submitted!')";
//echo $refno;
echo "</script>";
}
}
}
}
$file_name= "//sgewsnant21.amk.st.com/ews/web/webspool/temp/visualdefectreport/" . $refno.$file_name;
flush();
mysqli_close($conn);
?>
</code></pre>
<p>Below is how I get the <code>refno</code>.</p>
<pre><code><script type="text/javascript">
const now = new Date();
let randomNum = '';
randomNum += Math.round(Math.random() * 9);
randomNum += Math.round(Math.random() * 9);
randomNum += now.getTime().toString().slice(-2);
window.onload = function () {
document.getElementById("refno").value = `${new Date().getFullYear()}${randomNum}`;
}
</script>
<label class="control-label col-sm-4" for="refno">REF nos :</label>
<div class="col-sm-4">
<p class="form-control-static" style="margin-top: -6px;">
<input type="text" class="form-control" id="refno" name="refno" value="<?php echo $refno;?>" disabled>
</p>
</div>
</code></pre>
| [
{
"answer_id": 74355473,
"author": "manju nath",
"author_id": 20439964,
"author_profile": "https://Stackoverflow.com/users/20439964",
"pm_score": -1,
"selected": false,
"text": "<?php\nif(isset($_POST['saveimage']))\n{\n $directory=\"images/\";\n $filename =$_FILES['file']['name'];\n $filename_temp =$_FILES['file']['tmp_name'];\n $new_filename = $directory.date(\"YmdHis\").\"_\".$filename;\n \n if(move_uploaded_file($filename_temp,$new_filename))\n {\n echo \"File Uploaded \";\n }\n else\n {\n echo \"File Upload Error.\";\n }\n}\necho \"<hr/>\";\n?>\n <form method=\"post\" action=\"<?php $_SERVER['PHP_SELF']?>\" enctype=\"multipart/form-data\">\n <input type=\"file\" name=\"file\" />\n <input type=\"submit\" name=\"saveimage\" value=\"save\" />\n </form>\n"
},
{
"answer_id": 74365655,
"author": "manju nath",
"author_id": 20439964,
"author_profile": "https://Stackoverflow.com/users/20439964",
"pm_score": 0,
"selected": false,
"text": "<?php \n if(isset($_POST['submit']))\n {\n \n $refno = isset ($_GET['refno'])? $_GET['refno']:'';\n $file_tmp = isset($_FILES[\"file\"][\"tmp_name\"])? $_FILES[\"file\"][\"tmp_name\"] : \"\";\n $file_size = isset($_FILES[\"file\"][\"size\"])? $_FILES[\"file\"][\"size\"] : \"\";\n $file_name = isset($_FILES[\"file\"][\"name\"])? $_FILES[\"file\"][\"name\"] : \"\";\n \n //Images Directory\n $dataDir = \"//sgewsnant21.amk.st.com/ews/web/webspool/temp/visualdefectreport/\";\n \n //New Filename\n $new_filename = $dataDir.$refno.$file_name;\n \n //File formats\n $file_formats=array(\"jpeg\",\"jpg\",\"png\");\n \n //echo $file_size;\n if($file_size>0){\n //echo \"Good\";\n $file_info = pathinfo($file_name);\n $file_ext= $file_info['extension'];\n \n //check the extension\n if(in_array($file_ext,$file_formats))\n {\n //Database Connection \n //$connection = mysqli_connect($apews_db_apews2, $apews_db_usr, $apews_db_pwd, $database) or die (\"Unableeeee to connect!\");\n if(move_uploaded_file($file_tmp, $new_filename))\n {\n $message=\"alert('Visual Defect Report and pictures are successfully submitted!')\";\n }\n else\n {\n $message= \" alert('Error Uploading File!')\";\n } \n \n }\n else\n {\n $message= \" alert('Invalid Picture Format!')\";\n }\n }\n else\n {\n $message= \" alert('No picture attached!')\";\n }\n \n echo \"<script language=\\\"javascript\\\" type=\\\"text/javascript\\\">\";\n echo $message;\n //echo $refno;\n echo \"</script>\";\n }\n\n?> \n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19928120/"
] |
74,355,357 | <p>I have a 2 dimensional list of list but I would like the list inside the list to be dictionary</p>
<pre><code>list1 = [["ab","cd"],["ef","gh"]]
#code here,
print(output_list_of_dict)
#output should be ...
#[{"name": "ab", "phone":"cd"},{"name": "ef", "phone":"gh"}]
</code></pre>
| [
{
"answer_id": 74355373,
"author": "Leon",
"author_id": 15319257,
"author_profile": "https://Stackoverflow.com/users/15319257",
"pm_score": 1,
"selected": false,
"text": "list1 = [[\"ab\",\"cd\"],[\"ef\",\"gh\"]]\n\nres = []\nfor item in list1:\n res.append({\"name\": item[0], \"phone\": item[1]})\nprint(res)\n"
},
{
"answer_id": 74355374,
"author": "Amirhossein Sefati",
"author_id": 11856099,
"author_profile": "https://Stackoverflow.com/users/11856099",
"pm_score": 1,
"selected": false,
"text": "list1 = [[\"ab\",\"cd\"],[\"ef\",\"gh\"]] \n\noutput = []\n\nfor item in list1:\n dic = {}\n dic[\"name\"] = item[0]\n dic[\"phone\"] = item[1]\n\n output.append(dic)\n\n\nprint(output)\n"
},
{
"answer_id": 74355391,
"author": "assume_irrational_is_rational",
"author_id": 11622508,
"author_profile": "https://Stackoverflow.com/users/11622508",
"pm_score": 1,
"selected": false,
"text": "dict"
},
{
"answer_id": 74355395,
"author": "joanis",
"author_id": 3216427,
"author_profile": "https://Stackoverflow.com/users/3216427",
"pm_score": 3,
"selected": true,
"text": "list1 = [[\"ab\",\"cd\"],[\"ef\",\"gh\"]]\noutput_list_of_dict = [{\"name\": x, \"phone\": y} for x, y in list1]\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13742058/"
] |
74,355,390 | <pre><code>from functools import reduce
orders = [ [1, ("5464", 4, 9.99), ("8274",18,12.99), ("9744", 9, 44.95)]],
[2, ("5464", 9, 9.99), ("9744", 9, 44.95)],
[3, ("5464", 9, 9.99), ("88112", 11, 24.99)],
[4, ("8732", 7, 11.99), ("7733",11,18.99), ("88112", 5, 39.95)] ]
print(list(map(lambda x: [x[0]] + list(map(lambda y: (y[0], y[1]*y[2]), x[1:])), orders)))
</code></pre>
<p>I have been trying to figure out lambda, filter, and map. I came to a halt where I wanted to try and multiply the integers in the second element i.e (4 & 9.99), (18 & 12.99), (9 & 44.95) etc. Then find the minimum value for each element and have the output accordingly.</p>
<p>I know I can use min(), but I have no idea how to implement it, also my current output is a 2d-list where expected out is tuples inside a list. I understand I need to use a for loop to iteratitate through the tuples elements once I multiply them.</p>
<p>Current output:</p>
<pre><code>[[1, ('5464', 39.96), ('8274', 233.82), ('9744', 404.55)], [2, ('5464', 89.91), ('9744', 404.55)], [3, ('5464', 89.91), ('88112', 274.89)], [4, ('8732', 83.93), ('7733', 208.89), ('88112', 199.75)]]
</code></pre>
<p>Wanted output:</p>
<pre><code>[(1,"5464"), (2,"5464"), (3,"5464"), (4,"8732")]
</code></pre>
<p>So the question would be, how do I implement the min() function to filter out the minimum product of index[1] & index[2] in the tuples of a nested list.</p>
<p>(Sorry for bad english, I tried my best).</p>
| [
{
"answer_id": 74355547,
"author": "Raibek",
"author_id": 11040577,
"author_profile": "https://Stackoverflow.com/users/11040577",
"pm_score": 0,
"selected": false,
"text": "orders = [[1, (\"5464\", 4, 9.99), (\"8274\",18,12.99), (\"9744\", 9, 44.95)], \n [2, (\"5464\", 9, 9.99), (\"9744\", 9, 44.95)],\n [3, (\"5464\", 9, 9.99), (\"88112\", 11, 24.99)],\n [4, (\"8732\", 7, 11.99), (\"7733\",11,18.99), (\"88112\", 5, 39.95)]]\n\nproducts = [[_order[1]*_order[2] for _order in _order_list[1:]] for _order_list in orders]\n\nmin_product_address = [(i, _product.index(min(_product)) + 1) for i, _product in enumerate(products)]\n\noutput = [(orders[i][0], orders[i][j][0]) for i, j in min_product_address]\n\n[(1, '5464'), (2, '5464'), (3, '5464'), (4, '8732')]\n"
},
{
"answer_id": 74358220,
"author": "Timus",
"author_id": 14311263,
"author_profile": "https://Stackoverflow.com/users/14311263",
"pm_score": 1,
"selected": false,
"text": "result = list(map(lambda order: (order[0], min(order[1:], key=lambda o: o[1] * o[2])[0]), orders))\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15583888/"
] |
74,355,414 | <p>i am trying to have a code to give me a list of meals and put the day i will be having this. but when i run it it put its out the same item for the week and repeats that with the next meal. not sure how to fix this.</p>
<pre><code>monday: random meal
tuesday: random meal
wednesday: random meal
thursday: random meal
friday: random meal
saturday: random meal
sunday: random meal
</code></pre>
<pre><code>import pandas as pd
import random
def main():
# I want to do for this code is to random meals per week and put in my done Excel file to go shopping.
# grab list of meals to make.
db = pd.read_excel("meals.xlsx")
week_days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
for i in db.index:
random_item = [db["meals"].loc[i]]
random_item = random.choice(random_item)
for i in week_days:
print(f"{i}: {random_item}")
if __name__ == "__main__":
main()
</code></pre>
<p>but it double and if i add more to the list it just adds more to the list.</p>
<pre><code>monday: Chicken & Veggie Stir-fry
tuesday: Chicken & Veggie Stir-fry
wednesday: Chicken & Veggie Stir-fry
thursday: Chicken & Veggie Stir-fry
friday: Chicken & Veggie Stir-fry
saturday: Chicken & Veggie Stir-fry
sunday: Chicken & Veggie Stir-fry
monday: Easy Butter Chicken
tuesday: Easy Butter Chicken
wednesday: Easy Butter Chicken
thursday: Easy Butter Chicken
friday: Easy Butter Chicken
saturday: Easy Butter Chicken
sunday: Easy Butter Chicken
</code></pre>
<p>not really sure know how to fix this.</p>
| [
{
"answer_id": 74355456,
"author": "Amirhossein Sefati",
"author_id": 11856099,
"author_profile": "https://Stackoverflow.com/users/11856099",
"pm_score": 2,
"selected": false,
"text": "random_item"
},
{
"answer_id": 74355623,
"author": "charles rushin",
"author_id": 17775089,
"author_profile": "https://Stackoverflow.com/users/17775089",
"pm_score": 0,
"selected": false,
"text": "import pandas as pd\nimport random\n\n\ndef main():\n # I want to do for this code is to random meals per week and put in my done Excel file to go shopping.\n # grab list of meals to make.\n\n db = pd.read_excel(\"meals.xlsx\")\n week_days = [\"monday\", \"tuesday\", \"wednesday\", \"thursday\", \"friday\", \"saturday\", \"sunday\"]\n\n for i in week_days:\n df_percent = db.sample(frac=0.7)\n df_rest = db[\"meals\"].loc[~db.index.isin(df_percent.index)]\n df_rest = df_rest.values\n print(f\"{i}: {df_rest[0]}\")\n\nif __name__ == \"__main__\":\n main()\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17775089/"
] |
74,355,423 | <pre><code>class Mytextlist extends StatelessWidget {
final Function adddata;
Mytextlist(this.adddata);
TextEditingController titleController = TextEditingController();
TextEditingController valueController = TextEditingController();
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
border: Border.all(
color: Colors.black,
)),
child: Column(
children: [
Card(
child: Column(children: <Widget>[
TextField(
decoration: const InputDecoration(
labelText: "title",
),
controller: titleController,
),
])),
Card(
child: Column(children: <Widget>[
TextField(
decoration: const InputDecoration(labelText: "expenses"),
controller: valueController,
),
])),
ElevatedButton(
onPressed: adddata(
titleController.text,
double.parse(
(valueController.text),
)),
child: const Text("ADD Transaction")),
],
));
</code></pre>
<p>}
}</p>
<p>//here i want to pass the value that was entered in the Textfield , my function adddata which will invoked while pressing button,which accepts string and double value, titlecontroller.text coverts value to string but double.parse is not converting the data into double , and the application is throwing error at format exception</p>
| [
{
"answer_id": 74355456,
"author": "Amirhossein Sefati",
"author_id": 11856099,
"author_profile": "https://Stackoverflow.com/users/11856099",
"pm_score": 2,
"selected": false,
"text": "random_item"
},
{
"answer_id": 74355623,
"author": "charles rushin",
"author_id": 17775089,
"author_profile": "https://Stackoverflow.com/users/17775089",
"pm_score": 0,
"selected": false,
"text": "import pandas as pd\nimport random\n\n\ndef main():\n # I want to do for this code is to random meals per week and put in my done Excel file to go shopping.\n # grab list of meals to make.\n\n db = pd.read_excel(\"meals.xlsx\")\n week_days = [\"monday\", \"tuesday\", \"wednesday\", \"thursday\", \"friday\", \"saturday\", \"sunday\"]\n\n for i in week_days:\n df_percent = db.sample(frac=0.7)\n df_rest = db[\"meals\"].loc[~db.index.isin(df_percent.index)]\n df_rest = df_rest.values\n print(f\"{i}: {df_rest[0]}\")\n\nif __name__ == \"__main__\":\n main()\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12933247/"
] |
74,355,437 | <p>How can I ask the user the capitals of each state and tell them if they are correct or incorrect? If they are wrong can python reply with the correct answer and tally up their score at the end. I will post what I have below and what I wish for it to show once I run it.</p>
<pre><code>statesAndCapitals={ "Alabama": "Montgomery",
"Georgia": "Atlanta",
"Arizona": "Phoenix",
"Arkansas": "Little Rock",
"California": "Sacramento",
"Ohio": "Columbus",
"Connecticut": "Hartford" }
</code></pre>
<p>I was expecting:</p>
<pre><code>>>>
What is the capital of Arizona? Phoenix
Correct!
What is the capital of Connecticut? Hartford
Correct!
What is the capital of Colorado? Denver
Correct!
What is the capital of California? Sacramento
Correct!
What is the capital of Alaska? I forget
Incorrect. The answer was Juneau
What is the capital of Arkansas? Little Rock
Correct!
What is the capital of Alabama? abc
Incorrect. The answer was Montgomery
.......
***Your score is : 5 out of 10
</code></pre>
| [
{
"answer_id": 74355456,
"author": "Amirhossein Sefati",
"author_id": 11856099,
"author_profile": "https://Stackoverflow.com/users/11856099",
"pm_score": 2,
"selected": false,
"text": "random_item"
},
{
"answer_id": 74355623,
"author": "charles rushin",
"author_id": 17775089,
"author_profile": "https://Stackoverflow.com/users/17775089",
"pm_score": 0,
"selected": false,
"text": "import pandas as pd\nimport random\n\n\ndef main():\n # I want to do for this code is to random meals per week and put in my done Excel file to go shopping.\n # grab list of meals to make.\n\n db = pd.read_excel(\"meals.xlsx\")\n week_days = [\"monday\", \"tuesday\", \"wednesday\", \"thursday\", \"friday\", \"saturday\", \"sunday\"]\n\n for i in week_days:\n df_percent = db.sample(frac=0.7)\n df_rest = db[\"meals\"].loc[~db.index.isin(df_percent.index)]\n df_rest = df_rest.values\n print(f\"{i}: {df_rest[0]}\")\n\nif __name__ == \"__main__\":\n main()\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20162747/"
] |
74,355,454 | <p>I tried to retrieve data from the API to display in the dropdown but an error occurred, I've tried according to what I was looking for on google and also the forum but the problem still appears.
is there something wrong in writing in my code,
Thank you</p>
<blockquote>
<p>this is the function that is executed when calling the api and the
response is 200.</p>
</blockquote>
<pre><code>class UtilFunction {
String? _valMenu;
var _dataMenu = [];
Future getSemester() async {
String url = Constant.baseURL;
String token = await UtilSharedPreferences.getToken();
final respose = await http.get(
Uri.parse(
'$url/auth/semester/get_smt',
),
headers: {
'Authorization': 'Bearer $token',
},
);
await http
.get(
Uri.parse(
'$url/auth/semester/get_smt',
),
)
.then((value) => (() {
// respose = value; //untuk melakukan request ke webservice
var listData =
jsonDecode(respose.body); //lalu kita decode hasil datanya
_dataMenu = listData['data'];
_valMenu = _dataMenu[0]['data'];
}));
print(respose.statusCode);
print(respose.body);
return _dataMenu;
}
}
</code></pre>
<blockquote>
<p>and I take the above function here.</p>
</blockquote>
<pre><code>Container(
child: FutureBuilder(
future: UtilFunction().getSemester(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
DropdownButtonFormField(
value: _valMenu,
onChanged: (value) {},
items: snapshot.data
.map<DropdownMenuItem>(
(project) => DropdownMenuItem(
value: project['smt'],
child: Text(project['smt']),
))
.toList,
), ...
</code></pre>
<blockquote>
<p>this response json</p>
</blockquote>
<pre><code>{
"status": "success",
"code": "200",
"data": [
{
"id": "254dd6e9-791e-4a2b-959e-6ec5929f3104",
"id_ta": "2b4d2dd1-ef8e-461b-b7c3-48409a13969e",
"ta": "2022-2023",
"smt": "GANJIL",
"semester": "2022-2023 GANJIL",
"periode_awal": "Senin, 01 Agustus 2022",
"periode_akhir": "Minggu, 22 Januari 2023",
"p_awal": "2022-08-01",
"p_akhir": "2023-01-22",
"period_smt": "Senin, 01 Agustus 2022 - Minggu, 22 Januari 2023",
"created_at": "2022-08-10 05:02:18",
"updated_at": "2022-09-06 03:57:00",
"created_by": "Superadmin",
"updated_by": "Dasep",
"sts_hapus": 1
}
]
}
</code></pre>
| [
{
"answer_id": 74355672,
"author": "Mohan Sai Manthri",
"author_id": 10711216,
"author_profile": "https://Stackoverflow.com/users/10711216",
"pm_score": 0,
"selected": false,
"text": "List<DropdownMenuItem>"
},
{
"answer_id": 74359878,
"author": "Emre Faruk KOLAÇ",
"author_id": 12040178,
"author_profile": "https://Stackoverflow.com/users/12040178",
"pm_score": 2,
"selected": true,
"text": "class UtilFunction {\n String? _valMenu;\n List<String> _dataMenu = [];\n\n Future getSemester() async {\n await http.get(Uri.parse(\"http://universities.hipolabs.com/search?country=United+States\")).then((value) {\n // respose = value; //untuk melakukan request ke webservice\n var listData = jsonDecode(value.body); //lalu kita decode hasil datanya\n for (var i = 0; i < 10; i++) {\n _dataMenu.add(listData[i][\"domains\"][0]);\n }\n _valMenu = _dataMenu[0];\n });\n return _dataMenu;\n }\n}\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19132574/"
] |
74,355,462 | <p>I have the following data-frame, <code>df</code>, that is population with 1000+ rows of data. Here is what it would look like:</p>
<pre><code> date mkt bid ask
0 01/07/22 LWAPO 0.6451 0.6460
1 01/07/22 HUYNE 0.6452 0.6458
2 01/07/22 VERAS 0.6447 0.6457
3 02/07/22 HUYNE 0.6432 0.6435
4 03/07/22 LWAPO 0.6440 0.6442
5 03/07/22 VERAS 0.6441 0.6444
6 03/07/22 PLAIN 0.6440 0.6445
7 03/07/22 ALCOT 0.6445 0.6449
8 04/07/22 HUYNE 0.6431 0.6444
9 04/07/22 LWAPO 0.6439 0.6441
...
</code></pre>
<p>My goal is to aggregate this date by the date, and perform some analysis using the mean bid/ask prices by each of the market makers, that is <code>'mkt'</code> column, and finally visualise this data using plotly.</p>
<p>However, I am wanting the <code>'mkt'</code> column (or it can be a new column if easier) to populate the names of the two market makers with the best bid price (max) and the best ask price (min), as a concatenated string.</p>
<p>As such, it would be something that looks like below:</p>
<pre><code> date mkt
0 01/07/22 HUYNE, VERAS
1 02/07/22 HUYNE, HUYNE
2 03/07/22 ALCOT, VERAS
3 04/07/22 LWAPO, LWAPO
...
</code></pre>
<p>With the other two columns just being simple averages for the day. I can achieve this through the following code:</p>
<p><code>new_df = df.groupby('date').mean()</code></p>
<p>But unsure how to properly apply <code>df.loc[BOOLEAN</code>]` to alter my data-frame and achieve my desired result. I have a vague idea in mind on how I can do it, but I feel like there is a simple solution that I am missing. I have also tried the following to no avail:</p>
<pre><code>for date in df['date'].unique():
test = df.loc[df['date']==date]['bid'].max()
</code></pre>
<p>Apologies for the convoluted nature of my question, but I would appreciate any help :)</p>
| [
{
"answer_id": 74355538,
"author": "Panda Kim",
"author_id": 20430449,
"author_profile": "https://Stackoverflow.com/users/20430449",
"pm_score": 3,
"selected": true,
"text": "bid"
},
{
"answer_id": 74355810,
"author": "Python16367225",
"author_id": 16367225,
"author_profile": "https://Stackoverflow.com/users/16367225",
"pm_score": 0,
"selected": false,
"text": "bids = df[['date', 'mkt', 'bid']]\nasks = df[['date', 'mkt', 'ask']]\nbest_bid_mkt = bids.groupby('date').max().mkt\nbest_ask_mkt = asks.groupby('date').min().mkt\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19764896/"
] |
74,355,478 | <p>I have a string that looks like:</p>
<pre class="lang-js prettyprint-override"><code>const msg = " [['robot_arm', 'bc1', 'p_09_04_00'], ['operator', 'lc1', 'p_09_15_00'], ['robot_arm', 'oc1', 'p_08_17_00']]"
</code></pre>
<p>And I want to split it into an array of arrays of strings, I have tried to split this string as follows:</p>
<pre><code>const msg_obj = new Array(JSON.parse(msg).split("["));
console.log(msg_obj);
for (let act_id in msg_obj) {
console.log(msg_obj[act_id]);
}
</code></pre>
<p>The problem is that I get unwanted characters/strings inside:</p>
<ol>
<li>Empty strings <code>""</code>.</li>
<li>commas <code>,</code>.</li>
<li>square bracket <code>]</code>.</li>
</ol>
<p>Can you please tell me if there is a better way to split this string into an array of arrays of strings without the unwanted output? thanks in advance.</p>
| [
{
"answer_id": 74355488,
"author": "Benjamin Penney",
"author_id": 6545526,
"author_profile": "https://Stackoverflow.com/users/6545526",
"pm_score": 3,
"selected": true,
"text": "const msg = \" [['robot_arm', 'bc1', 'p_09_04_00'], ['operator', 'lc1', 'p_09_15_00'], ['robot_arm', 'oc1', 'p_08_17_00']]\"\n\nconst msg_obj = JSON.parse(msg.trim().replace(new RegExp(\"'\", \"g\"), \"\\\"\"));\n\nconsole.log(msg_obj);\nfor (let act_id of msg_obj) {\n console.log(act_id);\n}"
},
{
"answer_id": 74355585,
"author": "hiwangyt",
"author_id": 20445721,
"author_profile": "https://Stackoverflow.com/users/20445721",
"pm_score": 0,
"selected": false,
"text": "msg"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8618242/"
] |
74,355,481 | <p>I'm trying to position the green box in the center of the page but totally unsuccessfully.</p>
<p>I set the body as flex..this should allow me to align the inside container to the center but it doesn't work. Why?</p>
<p><a href="https://i.stack.imgur.com/DvFN3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DvFN3.png" alt="page" /></a></p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sign Up</title>
<link rel="stylesheet" href="signup.css">
<link rel="stylesheet" href="css/bootstrap.css">
<script src="https://kit.fontawesome.com/5ab317586b.js" crossorigin="anonymous"></script>
</head>
<body class="body">
<div class="container">
<div class="box-1">
<h2>Box1</h2>
<p>This is the box 1</p>
</div>
<div class="box-2">
<h2>Box2</h2>
<p>This is the box 2</p>
</div>
<div class="box-3">
<h2>Box3</h2>
<p>This is the box 3</p>
</div>
</div>
<script src="js/bootstrap.bundle.js"></script>
</body>
</html>
</code></pre>
<p>CSS</p>
<pre><code>.body{
background-color: black;
display: flex;
width: 100%;
height: 100%;
flex-direction: column;
align-items: center;
}
.container div {
border: solid red;
padding: 0;
}
.container{
background-color: green;
display: flex;
justify-content: space-around;
}
</code></pre>
<p>I want the green box in the middle, what I'm doing wrong?</p>
<p>thanks</p>
| [
{
"answer_id": 74355511,
"author": "Anis",
"author_id": 6316804,
"author_profile": "https://Stackoverflow.com/users/6316804",
"pm_score": 3,
"selected": true,
"text": "vh"
},
{
"answer_id": 74355552,
"author": "John Li",
"author_id": 20436957,
"author_profile": "https://Stackoverflow.com/users/20436957",
"pm_score": 0,
"selected": false,
"text": "body{\n background-color: black;\n display: flex;\n min-height: 100vh;\n flex-direction: column;\n justify-content: center;\n align-items: center;\n}\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9962676/"
] |
74,355,566 | <p>I'm trying to apply reactI18next on a project, normally you to toggle the language change you would create a button that would call the "changelanguage" function like this:</p>
<pre><code> const changeLanguage = (lng) => {
i18n.changeLanguage(lng);
}
<button onClick={() => changeLanguage('en')}>en</button>
</code></pre>
<p>However, I was wondering if it's possible to make something similar but In a dropdown fashion.</p>
<p>Is there a way to trigger an onClick via select or other means?</p>
<p>Thanks and I hope to hear you guys soon!</p>
| [
{
"answer_id": 74355593,
"author": "Anis",
"author_id": 6316804,
"author_profile": "https://Stackoverflow.com/users/6316804",
"pm_score": 2,
"selected": false,
"text": "onChange"
},
{
"answer_id": 74355605,
"author": "Arjun Solanki",
"author_id": 6904092,
"author_profile": "https://Stackoverflow.com/users/6904092",
"pm_score": 0,
"selected": false,
"text": "const [value, setValue] = React.useState('');\nconst changeLanguage = (event) => {\n i18n.changeLanguage(event.target.value);\n}\n<select value={value} onChange={changeLanguage}>\n <option value=\"en\">English</option>\n</select>\n"
},
{
"answer_id": 74355659,
"author": "C.Tale",
"author_id": 8622733,
"author_profile": "https://Stackoverflow.com/users/8622733",
"pm_score": 1,
"selected": false,
"text": "onChange"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13312817/"
] |
74,355,571 | <p>I have the following data set:</p>
<pre><code>df <- data.frame(identifier = c("a","b","b","c"),
disease = c("heart, lung","lung, heart,,","lung, heart, heart, liver", "kidney, brain "))
</code></pre>
<p>which gives:</p>
<pre><code> identifier disease
1 a heart, lung
2 b lung, heart,,
3 b lung, heart, heart, liver
4 c kidney, brain
</code></pre>
<p>I want to be able to then go through the diseases, and for every condition create a new column. If the disease is present for a specific identifier, I want to then put a "yes" in that column. So the ideal output would be:</p>
<pre><code> identifier heart lung liver kidney brain
1 a Yes Yes No No No
2 b Yes Yes No No No
3 b Yes Yes Yes No No
4 c No No No Yes Yes
</code></pre>
<p>Would greatly appreciate any help with this as it has stumped me for a couple of hours now :)</p>
| [
{
"answer_id": 74355712,
"author": "Just James",
"author_id": 19730031,
"author_profile": "https://Stackoverflow.com/users/19730031",
"pm_score": 0,
"selected": false,
"text": "%in%"
},
{
"answer_id": 74355719,
"author": "M.Viking",
"author_id": 10276092,
"author_profile": "https://Stackoverflow.com/users/10276092",
"pm_score": 1,
"selected": false,
"text": "separate_rows"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15250406/"
] |
74,355,601 | <p>I'm trying to implement a simple Huffman coding algorithm. I take my input string (ddddbbcccaeeeee) and use it to create 2 arrays, those being a char array called <code>usedCharacters</code> and an int array called <code>characterCounts</code>. However these arrays need to be sorted by the number of times the character appears in the input string so the Huffman tree can be constructed. I tried using LINQ's OrderByDescending() method like I had seen online:</p>
<pre><code>usedCharacters = usedCharacters.OrderByDescending(i => characterCounts).ToArray();
characterCounts = characterCounts.OrderByDescending(i => i).ToArray();
</code></pre>
<p>The program runs but when I check the results the characters are very obviously still in order as they appear in the input string, meaning no sorting is actually done. On the other hand, <code>characterCounts</code> does succesfully sort. I also tried the more commonly seen online solution of <code>usedCharacters.OrderByDescending(i => characterCounts.IndexOf(i)).ToArray()</code> but that just causes an index out of bounds exception for reasons I don't fully understand. If anybody could give me some insight into what I'm missing that would be greatly appreciated. Thank you!</p>
| [
{
"answer_id": 74355712,
"author": "Just James",
"author_id": 19730031,
"author_profile": "https://Stackoverflow.com/users/19730031",
"pm_score": 0,
"selected": false,
"text": "%in%"
},
{
"answer_id": 74355719,
"author": "M.Viking",
"author_id": 10276092,
"author_profile": "https://Stackoverflow.com/users/10276092",
"pm_score": 1,
"selected": false,
"text": "separate_rows"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17266557/"
] |
74,355,616 | <p>i have this <strong>csv file</strong> i successfully convert to html with the script below.</p>
<pre><code>name,age
mike,109
sarah,25
</code></pre>
<p><strong>Conversion Script</strong></p>
<pre><code>#!/bin/bash
awk 'BEGIN {
h[1] = "name"
h[2] = "age"
FS=","
print "<!DOCTYPE html>" \
"<html>" \
"<head>" \
"<style>" \
"th { color:#f2f2f2; background-color: #73BD00;}th, td { text-align: left; padding: 8px; font-family: Arial;} {background-color: #f2f2f2;}" \
"th, td { text-align: left; padding: 8px; }" \
"tr { background-color: #f2f2f2;}" \
"</style>" \
"</head>" \
"<body>" \
"<h2> DATA TITLE </h2>" \
"<table border-collapse=collapse width=50%;> " \
}
#insert rows into table from file
{
print "<tr>"
#NF is a number of fields in each records
for (i=1;i<=NF;i++)
{
#insert first row of file as header
if (NR==1){
print "<th>" h[i] "</th>"
} else
print "<td>" $i "</td>"
}
print "</tr>"
}
END {
print "</table>"
"</body>" \
"</html>"
}' file.csv > filex.html;
</code></pre>
<p>Now i'm trying to figure out how to use either Sed or Awk to change the font color if the age is greater than 100.</p>
<p><strong>What i've tried with SED:</strong></p>
<p>I could have easily used Sed after the conversion like this if the value was just a generic number but the value changes depending on the file. What i'm trying to do is to have the value change color to RED only IF its greater than 100 which i'm not sure on how to do or if it's even possible</p>
<pre><code>sed 's/109/<font color="red">9<\/font>/g' finalx.html > filey.html
</code></pre>
<p><strong>What i've tried with AWK:</strong>
i've tried to input this lines of codes into the conversion script in so many different ways but nothing seems to work.</p>
<pre><code>NR>1 {
# Data rows
print "<tr>"
if( $i > 100 ) {
color="#FF0000" #color code for RED
}
print "</tr>"
}
</code></pre>
<p>i even tried editing the csv file before converting hoping that if i put the html font tag in the csv file with my condition, the conversion will pick it up and come out the way i intend but even my use of awk is wrong, so i didn't get that far to even test it out</p>
<pre><code>awk -F "[, ]+" '$2>100{for(i=2; i<=NF; i++)$i="<font color="red">$i</font>"}1'
</code></pre>
<p>Any help is appreciated. Thanks</p>
<hr />
<p>EDIT: here's the original code above formatted to be readable by <code>gawk -o-</code>:</p>
<pre><code>BEGIN {
h[1] = "name"
h[2] = "age"
FS = ","
print "<!DOCTYPE html>" "<html>" "<head>" "<style>" "th { color:#f2f2f2; background-color: #73BD00;}th, td { text-align: left; padding: 8px; font-family: Arial;} {background-color: #f2f2f2;}" "th, td { text-align: left; padding: 8px; }" "tr { background-color: #f2f2f2;}" "</style>" "</head>" "<body>" "<h2> DATA TITLE </h2>" "<table border-collapse=collapse width=50%;> "
}
{
print "<tr>"
#NF is a number of fields in each records
for (i = 1; i <= NF; i++) {
#insert first row of file as header
if (NR == 1) {
print "<th>" h[i] "</th>"
} else {
print "<td>" $i "</td>"
}
}
print "</tr>"
}
#insert rows into table from file
END {
print "</table>"
"</body>" "</html>"
}
</code></pre>
| [
{
"answer_id": 74357596,
"author": "MyICQ",
"author_id": 1818059,
"author_profile": "https://Stackoverflow.com/users/1818059",
"pm_score": 1,
"selected": false,
"text": "\nfor (i=1;i<=NF;i++)\n{\n#insert first row of file as header\nif (NR==1){\n print \"<th>\" h[i] \"</th>\"\n } else\n # -- data field 1 should just print\n if (i == 1) {\n print \"<td>\" $i \"</td>\"\n }\n # -- next field should have special td tag if condition is met\n if (i == 2) {\n TDTAG = \"<td>\"\n if (h[i] > MAXVALUE) {\n TDTAG = \"<td class='max'>\"\n }\n print TDTAG $i \"</td>\"\n }\n}\nprint \"</tr>\"\n}\n"
},
{
"answer_id": 74357814,
"author": "Daweo",
"author_id": 10785975,
"author_profile": "https://Stackoverflow.com/users/10785975",
"pm_score": 3,
"selected": true,
"text": "awk -F \"[, ]+\" '$2>100{for(i=2; i<=NF; i++)$i=\"<font color=\"red\">$i</font>\"}1'\n"
},
{
"answer_id": 74362420,
"author": "Dave Pritlove",
"author_id": 2005666,
"author_profile": "https://Stackoverflow.com/users/2005666",
"pm_score": 1,
"selected": false,
"text": "awk"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19452526/"
] |
74,355,640 | <p>I have an asp.net framework api endpoint that throws an error on IIS. it is a post method as thus:</p>
<pre><code> [HttpPost]
[Route("api/ebonyiproxy/validateexpectedpaymentref")]
public async Task<IHttpActionResult> GetResult(CustomerRequest request)
{
...
catch (Exception ex)
{
_logger.Report(ex.StackTrace, DateTime.Now);
if (ex.InnerException != null)
_logger.Report(ex.InnerException.StackTrace, DateTime.Now);
return InternalServerError(ex);
}
}
</code></pre>
<p>Using postman to test; In the local, it returns valid response. In host, it throws the error bellow. Please help.</p>
<pre><code>{"Message":"The requested resource does not support http method 'GET'."}
</code></pre>
| [
{
"answer_id": 74357596,
"author": "MyICQ",
"author_id": 1818059,
"author_profile": "https://Stackoverflow.com/users/1818059",
"pm_score": 1,
"selected": false,
"text": "\nfor (i=1;i<=NF;i++)\n{\n#insert first row of file as header\nif (NR==1){\n print \"<th>\" h[i] \"</th>\"\n } else\n # -- data field 1 should just print\n if (i == 1) {\n print \"<td>\" $i \"</td>\"\n }\n # -- next field should have special td tag if condition is met\n if (i == 2) {\n TDTAG = \"<td>\"\n if (h[i] > MAXVALUE) {\n TDTAG = \"<td class='max'>\"\n }\n print TDTAG $i \"</td>\"\n }\n}\nprint \"</tr>\"\n}\n"
},
{
"answer_id": 74357814,
"author": "Daweo",
"author_id": 10785975,
"author_profile": "https://Stackoverflow.com/users/10785975",
"pm_score": 3,
"selected": true,
"text": "awk -F \"[, ]+\" '$2>100{for(i=2; i<=NF; i++)$i=\"<font color=\"red\">$i</font>\"}1'\n"
},
{
"answer_id": 74362420,
"author": "Dave Pritlove",
"author_id": 2005666,
"author_profile": "https://Stackoverflow.com/users/2005666",
"pm_score": 1,
"selected": false,
"text": "awk"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9337608/"
] |
74,355,652 | <p>I have installed "laravel/jetstream": "^2.9" on "laravel/framework": "^8.75". When I accessed Profile Information page, it doesn't load necessary information into relevant form fields.Please help me with this isses.<a href="https://i.stack.imgur.com/Tlg5u.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Tlg5u.png" alt="Profile Information page" /></a></p>
<p>Even I have tried reinstalling Jetstream separately. Problem still exists.</p>
| [
{
"answer_id": 74357596,
"author": "MyICQ",
"author_id": 1818059,
"author_profile": "https://Stackoverflow.com/users/1818059",
"pm_score": 1,
"selected": false,
"text": "\nfor (i=1;i<=NF;i++)\n{\n#insert first row of file as header\nif (NR==1){\n print \"<th>\" h[i] \"</th>\"\n } else\n # -- data field 1 should just print\n if (i == 1) {\n print \"<td>\" $i \"</td>\"\n }\n # -- next field should have special td tag if condition is met\n if (i == 2) {\n TDTAG = \"<td>\"\n if (h[i] > MAXVALUE) {\n TDTAG = \"<td class='max'>\"\n }\n print TDTAG $i \"</td>\"\n }\n}\nprint \"</tr>\"\n}\n"
},
{
"answer_id": 74357814,
"author": "Daweo",
"author_id": 10785975,
"author_profile": "https://Stackoverflow.com/users/10785975",
"pm_score": 3,
"selected": true,
"text": "awk -F \"[, ]+\" '$2>100{for(i=2; i<=NF; i++)$i=\"<font color=\"red\">$i</font>\"}1'\n"
},
{
"answer_id": 74362420,
"author": "Dave Pritlove",
"author_id": 2005666,
"author_profile": "https://Stackoverflow.com/users/2005666",
"pm_score": 1,
"selected": false,
"text": "awk"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13775355/"
] |
74,355,653 | <p>I have this dataset, where I will use to fill missing values.</p>
<pre><code>In [1]: sex_class = ['female','male']
pclass = [1,2,3]
fill_values = [34,40,29,18,24,25]
In [2]: for i in pclass:
for j in sex_class:
print(i,j)
Out[2]: 1 female
1 male
2 female
2 male
3 female
3 male
</code></pre>
<p>How can I make it so that the output will appear as:</p>
<pre><code>1 female 34
1 male 40
2 female 29
2 male 18
3 female 24
3 male 25
</code></pre>
| [
{
"answer_id": 74355709,
"author": "J V S Krishna",
"author_id": 20355000,
"author_profile": "https://Stackoverflow.com/users/20355000",
"pm_score": 0,
"selected": false,
"text": "count = 0\nfor i in pclass:\n for j in sex_class:\n print(i,j,fill_values[count])\n count += 1\n"
},
{
"answer_id": 74355710,
"author": "BENY",
"author_id": 7964527,
"author_profile": "https://Stackoverflow.com/users/7964527",
"pm_score": 2,
"selected": true,
"text": "pop"
},
{
"answer_id": 74355731,
"author": "Ben Grossmann",
"author_id": 2476977,
"author_profile": "https://Stackoverflow.com/users/2476977",
"pm_score": 2,
"selected": false,
"text": "from itertools import product\n\nsex_class = ['female','male']\npclass = [1,2,3]\nfill_values = [34,40,29,18,24,25]\n\nfor (p,sex),val in zip(product(pclass,sex_class),fill_values):\n print(f\"{p} {sex:<6} {val}\")\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18193889/"
] |
74,355,669 | <p>When looping an array, people often use a simple method like below.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const array = [1,2,3,4,5];
for (let i = 0; i < array.length; i++) {
console.log(array[i]);
}</code></pre>
</div>
</div>
</p>
<p>My question is if <code>array[i]</code> is O(1) operation or not.</p>
<p>For example, when <code>i</code> is 3, does javascript get the number immediately OR count from 0 to 3 again?</p>
| [
{
"answer_id": 74355687,
"author": "Elliott Frisch",
"author_id": 2970947,
"author_profile": "https://Stackoverflow.com/users/2970947",
"pm_score": 2,
"selected": false,
"text": "array[i]"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11873634/"
] |
74,355,680 | <p>I have made the sidebar sticky by using fixed sidebar plugin but the sidebar disappear when scroll back to top I have tried many other plugin but they're not working. This
<a href="https://willowdaleequity.com/blog/acquire-69-unit-georgia-apartment-complex-press-release/" rel="nofollow noreferrer">https://willowdaleequity.com/blog/acquire-69-unit-georgia-apartment-complex-press-release/</a>
is the url of the website on which I'm facing the issue.</p>
<p>Please help me with this problem. I'm using Hub theme by Liquid Themes on my website.</p>
<p>I've also tried following custom css code instead of any plugin but it's also not working.
<code>position: sticky; top:100px; bottom: 100px;</code></p>
| [
{
"answer_id": 74355687,
"author": "Elliott Frisch",
"author_id": 2970947,
"author_profile": "https://Stackoverflow.com/users/2970947",
"pm_score": 2,
"selected": false,
"text": "array[i]"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19480288/"
] |
74,355,707 | <p>Here is a column in df which contains integer and string both combine together.
(even here's numbers type are string)</p>
<p>I want split the df['symbol'] into df['num'] and df['name'],how can I do this question by re.</p>
<p>QUESTION:</p>
<pre><code>df = pd.DataFrame({'symbol': ['12345abc', '2234bcd', '323456cde'],'date':[5, 6, 7]})
</code></pre>
<p>ideal:</p>
<pre><code>df1 = pd.DataFrame({'symbol': ['12345', '2234', '323456'],
'name':['abc','bcd','cde'],
'date':[5, 6, 7]})
</code></pre>
<p>Thanks to instructor.</p>
| [
{
"answer_id": 74355687,
"author": "Elliott Frisch",
"author_id": 2970947,
"author_profile": "https://Stackoverflow.com/users/2970947",
"pm_score": 2,
"selected": false,
"text": "array[i]"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19546365/"
] |
74,355,713 | <p>I have a total of 10 items and I am <em>mapping</em> through them to render each one. I want least opacity for last element and highest for first element. I am aware of <code>:first</code> and <code>:last</code> in <code>tailwind-css</code>, but I was wondering if there is way so that I can target lets say <em>my 8th or 9th</em> in <code>tailwind-css</code></p>
<p>here is my return statement from a component:</p>
<pre><code> {[0,1,2,3,4,5,6,7,8,9].map((item) => (
<section
key={item}
className='last:opacity-20 flex justify-between items-center text-slate-600 bg-white shadow-sm p-5 rounded-xl my-4 cursor-pointer dark:bg-black dark:text-slate-400'
>
<div className='flex gap-3 items-center'>
<div className='rounded-full w-8 h-8 bg-slate-200'></div>
<p className='w-44 h-4 bg-slate-100'></p>
</div>
<p className='w-16 h-4 bg-slate-100'></p>
</section>
))}
</code></pre>
<p>I want to decrease <code>opacity</code> going downwards i.e, from first item to last item.</p>
| [
{
"answer_id": 74356122,
"author": "John Li",
"author_id": 20436957,
"author_profile": "https://Stackoverflow.com/users/20436957",
"pm_score": 0,
"selected": false,
"text": "nth-child"
},
{
"answer_id": 74358116,
"author": "Ihar Aliakseyenka",
"author_id": 14305076,
"author_profile": "https://Stackoverflow.com/users/14305076",
"pm_score": 1,
"selected": false,
"text": "nth-child"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15759228/"
] |
74,355,714 | <p>The following C++ template <a href="https://stackoverflow.com/a/1815371/3410351">detects overflows</a> from multiplying two unsigned integers.</p>
<pre><code>template<typename UInt> UInt safe_multiply(UInt a, UInt b) {
UInt x = a * b; // x := ab mod n, for n := 2^#bits > 0
if (a != 0 && x / a != b)
cerr << "Overflow for " << a << " * " << b << "." << endl;
return x;
}
</code></pre>
<p>Can you give a proof that this algorithm detects every potential overflow, regardless of how many bits <code>UInt</code> uses?</p>
<p>The case<br/>
<a href="https://latex.codecogs.com/png.image?%5Cdpi%7B110%7D%5Cbg%7Bwhite%7Da=0%5Clor&space;b=0" rel="nofollow noreferrer"><img src="https://latex.codecogs.com/png.image?%5Cdpi%7B110%7D%5Cbg%7Bwhite%7Da=0%5Clor&space;b=0" alt="a=0\lor b=0" /></a></p>
<p>cannot result in overflows, so we can consider<br/>
<a href="https://latex.codecogs.com/png.image?%5Cdpi%7B110%7D%5Cbg%7Bwhite%7Da,b,n%5Cin%5Cmathbb%7BN%7D_%7B%3E0%7D" rel="nofollow noreferrer"><img src="https://latex.codecogs.com/png.image?%5Cdpi%7B110%7D%5Cbg%7Bwhite%7Da,b,n%5Cin%5Cmathbb%7BN%7D_%7B%3E0%7D" alt="a,b,n\in\mathbb{N}_{>0}" /></a> .</p>
<p>It seems that the correctness proof boils down to leading<br/>
<a href="https://latex.codecogs.com/png.image?%5Cdpi%7B110%7D%5Cbg%7Bwhite%7D%5Cleft%5Clfloor%5Cfrac%7Bab&space;%5Cmod&space;n%7D%7Ba%7D%5Cright%5Crfloor=b%7E%5Cland%7Eab%5Cge&space;n" rel="nofollow noreferrer"><img src="https://latex.codecogs.com/png.image?%5Cdpi%7B110%7D%5Cbg%7Bwhite%7D%5Cleft%5Clfloor%5Cfrac%7Bab&space;%5Cmod&space;n%7D%7Ba%7D%5Cright%5Crfloor=b%7E%5Cland%7Eab%5Cge&space;n" alt="\left\lfloor\frac{ab \mod n}{a}\right\rfloor=b~\land~ab\ge n" /></a></p>
<p>to a contradiction, since <code>x / a</code> actually means <a href="https://latex.codecogs.com/png.image?%5Cdpi%7B110%7D%5Cbg%7Bwhite%7D%5Cleft%5Clfloor%5Cfrac%7Bx%7D%7Ba%7D%5Cright%5Crfloor" rel="nofollow noreferrer"><img src="https://latex.codecogs.com/png.image?%5Cdpi%7B110%7D%5Cbg%7Bwhite%7D%5Cleft%5Clfloor%5Cfrac%7Bx%7D%7Ba%7D%5Cright%5Crfloor" alt="\left\lfloor\frac{x}{a}\right\rfloor" /></a>.</p>
<p>When assuming<br/>
<a href="https://latex.codecogs.com/png.image?%5Cdpi%7B110%7D%5Cbg%7Bwhite%7D%5Cleft%5Clfloor%5Cfrac%7Bx%7D%7Ba%7D%5Cright%5Crfloor=%5Cfrac%7Bx%7D%7Ba%7D" rel="nofollow noreferrer"><img src="https://latex.codecogs.com/png.image?%5Cdpi%7B110%7D%5Cbg%7Bwhite%7D%5Cleft%5Clfloor%5Cfrac%7Bx%7D%7Ba%7D%5Cright%5Crfloor=%5Cfrac%7Bx%7D%7Ba%7D" alt="\left\lfloor\frac{x}{a}\right\rfloor=\frac{x}{a}" /></a></p>
<p>, this leads to the straightforward consequence<br/>
<a href="https://latex.codecogs.com/png.image?%5Cdpi%7B110%7D%5Cbg%7Bwhite%7D%5Cleft%5Clfloor%5Cfrac%7Bx%7D%7Ba%7D%5Cright%5Crfloor=b%5CLeftrightarrow%5Cfrac%7Bx%7D%7Ba%7D=b%5CLeftrightarrow&space;ab&space;%5Cmod&space;n=ab" rel="nofollow noreferrer"><img src="https://latex.codecogs.com/png.image?%5Cdpi%7B110%7D%5Cbg%7Bwhite%7D%5Cleft%5Clfloor%5Cfrac%7Bx%7D%7Ba%7D%5Cright%5Crfloor=b%5CLeftrightarrow%5Cfrac%7Bx%7D%7Ba%7D=b%5CLeftrightarrow&space;ab&space;%5Cmod&space;n=ab" alt="\left\lfloor\frac{x}{a}\right\rfloor=b\Leftrightarrow\frac{x}{a}=b\Leftrightarrow ab \mod n=ab" /></a></p>
<p>thus<br/>
<a href="https://latex.codecogs.com/png.image?%5Cdpi%7B110%7D%5Cbg%7Bwhite%7Dab%5Cmod&space;n=ab%5Cge&space;n" rel="nofollow noreferrer"><img src="https://latex.codecogs.com/png.image?%5Cdpi%7B110%7D%5Cbg%7Bwhite%7Dab%5Cmod&space;n=ab%5Cge&space;n" alt="ab\mod n=ab\ge n" /></a></p>
<p>which contradicts n > 0.</p>
<p>So it remains to show<br/>
<a href="https://latex.codecogs.com/png.image?%5Cdpi%7B110%7D%5Cbg%7Bwhite%7D%5Cleft%5Clfloor%5Cfrac%7Bab&space;%5Cmod&space;n%7D%7Ba%7D%5Cright%5Crfloor=%5Cfrac%7Bab&space;%5Cmod&space;n%7D%7Ba%7D" rel="nofollow noreferrer"><img src="https://latex.codecogs.com/png.image?%5Cdpi%7B110%7D%5Cbg%7Bwhite%7D%5Cleft%5Clfloor%5Cfrac%7Bab&space;%5Cmod&space;n%7D%7Ba%7D%5Cright%5Crfloor=%5Cfrac%7Bab&space;%5Cmod&space;n%7D%7Ba%7D" alt="\left\lfloor\frac{ab \mod n}{a}\right\rfloor=\frac{ab \mod n}{a}" /></a></p>
<p>or there must be another way.</p>
<p>If the last equation is true, WolframAlpha <a href="https://www.wolframalpha.com/input?i=floor%28%28a*b+mod+n%29%2Fa%29%3D%28a*b+mod+n%29%2Fa+for+a+%3E+0+and+b+%3E+0+and+n+%3E+0" rel="nofollow noreferrer">fails to confirm that</a> (also <a href="https://www.wolframalpha.com/input?i=floor%28%28a*b+mod+2%5Ek%29%2Fa%29%3D%28a*b+mod+2%5Ek%29%2Fa+for+a+%3E+0+and+b+%3E+0+and+k+%3E%3D+0" rel="nofollow noreferrer">with exponents</a>).<br/>
<em>However</em>, it asserts that the <a href="https://www.wolframalpha.com/input?i=solve+floor%28%28a*b+mod+n%29%2Fa%29%3Db+and+ab%3E%3Dn+for+a+%3E+0+and+b+%3E+0+and+n+%3E+0" rel="nofollow noreferrer">original assumptions</a> have no integer solutions, so the algorithms seems to be correct indeed.<br/>
But it doesn't provide an explanation. So <em>why</em> is it correct?</p>
<p>I am looking for the smallest possible explanation that is still mathematically profound, ideally that it fits in a single-line comment. Maybe I am missing something trivial, or the problem is not as easy as it looks.</p>
<p>On a side note, I used <a href="https://codecogs.com/latex/eqneditor.php" rel="nofollow noreferrer">Codecogs Equation Editor</a> for the LaTeX markup images, which apparently looks bad in dark mode, so consider <a href="https://stackoverflow.com/users/preferences/">switching to light mode</a> or, if you know, please tell me how to use different images depending on the client settings. It is just <code>\bg{white}</code> vs. <code>\bg{black}</code> as part of the image URLs.</p>
| [
{
"answer_id": 74355874,
"author": "Elliott",
"author_id": 8658157,
"author_profile": "https://Stackoverflow.com/users/8658157",
"pm_score": 2,
"selected": true,
"text": "*"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3410351/"
] |
74,355,715 | <p>I have the df:</p>
<pre><code>lst_1 = ['November-2022', 'October-2022', 'September-2022', 'November-2022']
lst_2 = ['', '', '', '', '']
lst_3 = ['', '', '', '', '']
lst_4 = ['', '', '', '', '']
df1 = pd.DataFrame(list(zip(lst_1 , lst_2, lst_3, lst_4)),
columns =['Date_updated', 'November-2022', 'October-2022', 'September-2022'])
</code></pre>
<p>I want to write a function to have df2 like this:</p>
<pre><code>lst_1 = ['November-2022', 'October-2022', 'September-2022', 'November-2022']
lst_2 = ['x', '', '', 'x', '']
lst_3 = ['', 'x', '', '', '']
lst_4 = ['', '', 'x', '', '']
df2 = pd.DataFrame(list(zip(lst_1 , lst_2, lst_3, lst_4)),
columns =['Date_updated', 'November-2022', 'October-2022', 'September-2022'])
</code></pre>
<p>When row['Date_updated'] == column names of df1, it will tick 'x' to that columns with the same name.
I tried this, but not work:</p>
<pre><code>df1['Date_Updated'] = df1['Date_Updated'].astype(str)
lst_date = list(df1['Date_Updated'].tolist())
def add_tick(r):
for i in lst_date:
if r['Date_Updated'] == r[i]:
return 'X'
continue
for i in lst_date:
df1[i] = df1.apply(add_tick, axis = 1)
</code></pre>
| [
{
"answer_id": 74355874,
"author": "Elliott",
"author_id": 8658157,
"author_profile": "https://Stackoverflow.com/users/8658157",
"pm_score": 2,
"selected": true,
"text": "*"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14342004/"
] |
74,355,726 | <p>I have created a doubly linked list, that appends new nodes to the doubly linked list. I am currently trying to work on deleting a node at a specific index.
This is my node class, which initializes three variables, next, previous, and it imports objects from a student class that I have. Shouldn't the <code>for</code> loop iterate up to the value of the index entered and then redirect the next value?</p>
<p><code>Node</code> Class:</p>
<pre class="lang-java prettyprint-override"><code>public class Node {
Student student;
Node next;
Node previous;
public Node(Student student) {
this.student = student;
this.next = null;
this.previous = null;
}
@Override
public String toString() {
return student.toString();
}
}
</code></pre>
<hr />
<p><code>DoublyLinkedList</code> Class:</p>
<pre class="lang-java prettyprint-override"><code>public class DoublyLinkedList <T extends Comparable<T>> {
protected Node head;
protected Node tail;
int size=0;
public DoublyLinkedList() {
this.head = null;
this.tail = null;
}
public Node append(Student student) {
Node append = new Node(student);
if (head == null) {
head = append;
tail = append;
}
else {
append.previous = tail;
tail.next = append;
tail = tail.next;
}
size++;
return append;
}
public void delete(int location) throws IllegalArgumentException {
Node current = head;
int counter = 1;
int i;
// Exception error for cases in which there are no nodes
if (head == null || location < 0)
throw new IllegalArgumentException("Sorry but the DLL is NULL, please add nodes");
// Cases in which the person wants to delete the head at index 0
if (location == 0) {
/* If the node that is next is not null we make that the head
*/
if (head.next != null) {
head.next.previous = head;
}
}
for (i = 1; head != null && i < location; i++) {
head = head.next;
}
if (head == null)
head = head.next.previous;
}
}
</code></pre>
<p>I believe the cases that I made for situations where the head is null, a negative value is entered, and the head node is being deleted are correct. I believe the problem is iterating up the given parameter (index of node being deleted). I did a <code>for</code> loop that iterates up to the given index. What I was trying to do is once the value of head reaches the parameter entered, it would redirect the next of the <code>Node</code> it iterated up to. Is this logic correct and the syntax wrong or is there another logic for a case like this?</p>
| [
{
"answer_id": 74355874,
"author": "Elliott",
"author_id": 8658157,
"author_profile": "https://Stackoverflow.com/users/8658157",
"pm_score": 2,
"selected": true,
"text": "*"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,355,735 | <p>I have these 2 tables:</p>
<p>Table one(parties):</p>
<pre><code>public function up()
{
Schema::create('parties', function (Blueprint $table) {
$table->id();
$table->string('full_name');
$table->string('ic_passport');
$table->string('nationality');
$table->string('income_tax_no');
$table->string('income_Tax_filing_branch');
$table->string('phone_no');
$table->string('email');
$table->timestamps();
});
}
</code></pre>
<p>Table two(corraddresses):</p>
<pre><code>public function up()
{
Schema::create('corraddresses', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('party_id');
$table->foreign('party_id')->references('id')->on('parties');
$table->string('address_1');
$table->string('address_2');
$table->string('city');
$table->string('poscode');
$table->timestamps();
});
}
</code></pre>
<p>Model one(Party):</p>
<pre><code>class Party extends Model
{
use HasFactory;
protected $fillable = ['full_name','ic_passport','nationality','income_tax_no',
'income_Tax_filing_branch','phone_no','email'];
}
</code></pre>
<p>Model two(Corraddress):</p>
<pre><code>class Corraddress extends Model
{
use HasFactory;
protected $fillable = ['address_1','address_2','city','poscode','party_id'];
public function partyId()
{
return $this->belongsTo(Party::class, 'party_id', 'id');
}
}
</code></pre>
<p>Controller one(PartyController - store function):</p>
<pre><code>public function store(Request $request)
{
$party = Party::create($request->post());
return response()->json([
'message'=>'Party Created Successfully!!',
'party'=>$party
]);
}
</code></pre>
<p>Controller two(CorraddressController - store function):</p>
<pre><code>public function store(Request $request)
{
$corraddress = Corraddress::create($request->post());
return response()->json([
'message'=>'Corraddress Created Successfully!!',
'corraddress'=>$corraddress
]);
}
</code></pre>
<p>The view below is submitting all data from one form:</p>
<p>Form view - Script:</p>
<pre><code>data() {
return {
full_name: '',
ic_passport: '',
nationality: '',
income_tax_no: '',
income_Tax_filing_branch: '',
phone_no: '',
email: '',
address_1: '',
address_2: '',
city: '',
poscode: '',
party_id: '',
};
},
methods: {
addNewPost(){
axios.post('/api/auth/party',{
full_name: this.full_name,
ic_passport: this.ic_passport,
nationality: this.nationality,
income_tax_no: this.income_tax_no,
income_Tax_filing_branch: this.income_Tax_filing_branch,
phone_no: this.phone_no,
email: this.email,
})
axios.post('/api/auth/corraddress',{
address_1: this.address_1,
address_2: this.address_2,
city: this.city,
poscode: this.poscode,
party_id: response.party.id,
// party_id: this.party_id,
})
},
},
</code></pre>
<p>when i submit the above the data will be stored in "parties" table only</p>
<p>but when i try to "un-comment" this-> <code>// party_id: this.party_id,</code> and submit i get this meesage:</p>
<pre><code>message "SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'party_id' cannot be null (SQL: insert into `corraddresses` (`address_1`, `address_2`, `city`, `poscode`, `party_id`, `updated_at`, `created_at`) values (awgawg, awgawg, gawg, awgaw, ?, 2022-11-08 04:31:58, 2022-11-08 04:31:58))"
</code></pre>
<p>what i am trying to do is when i submit the form i want the primary key of the record in "parties" to be saved as a foreign key in "corraddresses" tables under "party_id" column i have been stuck in this issue for a few days now, i can't find answer for it so far..</p>
<p>am i doing anything wrong? is there a problem with my migrations or models or is there anything missing from controllers or the view?</p>
<p>Note: when i try to submit the form without any relationship between the two tables both records will be saved in "parties" table and "corraddresses" table</p>
| [
{
"answer_id": 74355874,
"author": "Elliott",
"author_id": 8658157,
"author_profile": "https://Stackoverflow.com/users/8658157",
"pm_score": 2,
"selected": true,
"text": "*"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19663907/"
] |
74,355,742 | <p>I am having trouble attaching a video in my html file. I used a youtube video for this one but whenever I open it on my browser it says the video is unavailable because youtube refused to connect. I also tried attaching a video from my computer that ended with .mov and that didnt work either. here is what i wrote in html for the youtube one.</p>
<pre><code><iframe width="560" height="315" src="https://youtu.be/u9fftcQGSa0"
frameborder="0" allow="accelerometer; autoplay; encrypted-media;
gyroscope; picture-in-picture" allowfullscreen></iframe>
</code></pre>
| [
{
"answer_id": 74355874,
"author": "Elliott",
"author_id": 8658157,
"author_profile": "https://Stackoverflow.com/users/8658157",
"pm_score": 2,
"selected": true,
"text": "*"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19884517/"
] |
74,355,748 | <p>Does anyone know how to modify this code so that it will sort dictionaries{} and lists[]?</p>
<p>Example sort:</p>
<pre><code>Input: {'a': 1, 'c': 3, 'b': {'b2': 2, 'b1': [1, 7, 4, 2]}}
Output: {'a': 1, 'b': {'b1': [1, 2, 4, 7], 'b2': 2}, 'c': 3}
</code></pre>
<p>Original code:</p>
<pre><code>def sort_dict(item: dict):
return {k: sort_dict(v) if isinstance(v, dict) else v for k, v in sorted(item.items())}
</code></pre>
<blockquote>
<p>Acknowledgement to @gyli for that wonderful code
<a href="https://gist.github.com/gyli/f60f0374defc383aa098d44cfbd318eb" rel="nofollow noreferrer">https://gist.github.com/gyli/f60f0374defc383aa098d44cfbd318eb</a></p>
</blockquote>
<p>These are my two best attempts, but they both fail. In this attempt, I can see v[] getting sorted but the sorted lists aren't making it to the next line where the return is evaluated.</p>
<pre><code>def sort_dict(item: dict):
for k, v in sorted(item.items()):
v = sorted(v) if isinstance(v, list) else v
return {k: sort_dict(v) if isinstance(v, dict) else v for k, v in sorted(item.items())}
</code></pre>
<p>The same problem is occurring here, but at least in this attempt I understand why the sorted lists aren't making it to the return statement.</p>
<pre><code>def sort_dict(item: dict):
return {k: sort_dict(v) if isinstance(v, dict) else sort_list(v) for k, v in sorted(item.items())}
def sort_list(item):
item = sorted(item) if isinstance(item, list) else item
</code></pre>
| [
{
"answer_id": 74355816,
"author": "asdfasdf",
"author_id": 20354959,
"author_profile": "https://Stackoverflow.com/users/20354959",
"pm_score": 1,
"selected": false,
"text": "def sort_dict(item: dict):\n for k, v in sorted(item.items()):\n item[k] = sorted(v) if isinstance(v, list) else v\n return {k: sort_dict(v) if isinstance(v, dict) else v for k, v in sorted(item.items())}\n"
},
{
"answer_id": 74355919,
"author": "Yangtian Sun",
"author_id": 20336874,
"author_profile": "https://Stackoverflow.com/users/20336874",
"pm_score": 3,
"selected": true,
"text": "sort_list"
},
{
"answer_id": 74356040,
"author": "Shamshirsaz.Navid",
"author_id": 2227070,
"author_profile": "https://Stackoverflow.com/users/2227070",
"pm_score": 1,
"selected": false,
"text": "def full_sort(d):\n if type(d) == type({}):\n return {k: full_sort(v) for (k, v) in sorted(d.items())}\n elif type(d) == type([]):\n return sorted(d)\n return d\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20354959/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.