qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,215,623 | <p>New to R functions, I have a dataframe which looks like this except about 10,000 rows long:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Gene.name</th>
<th>Ortho.name</th>
</tr>
</thead>
<tbody>
<tr>
<td>abc</td>
<td>DEF</td>
</tr>
<tr>
<td>qrs</td>
<td>TUV</td>
</tr>
<tr>
<td>wx</td>
<td>YZ</td>
</tr>
</tbody>
</table>
</div>
<p>I'm trying to create a really simple function in r which when I input qrs, returns TUV. If someone could help I would really appreciate it.</p>
| [
{
"answer_id": 74215649,
"author": "r2evans - GO NAVY BEAT ARMY",
"author_id": 3358272,
"author_profile": "https://Stackoverflow.com/users/3358272",
"pm_score": 3,
"selected": true,
"text": "fun <- function(vec, data) data$Ortho.name[ match(vec, data$Gene.name) ]\nZ <- structure(list(Gen... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74215623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19447090/"
] |
74,215,652 | <p>So I have two-dimensional arrays of N * M like below,</p>
<pre><code>$arys = [
[0] => [0, 0 , 0 , 0],
[1] => [0, 1 , 0 , 0],
[2] => [0, 0 , 1 , 0],
[3] => [0, 0 , 0 , 0],
</code></pre>
<p>and need to detect '1' and if there's '1', i need to get values vertically and horizontally, and change them to '1', which is like below,</p>
<pre><code>$arys = [
[0] => [0, 1 , 1 , 0],
[1] => [1, 1 , 1 , 1],
[2] => [1, 1 , 1, 1],
[3] => [0, 1 , 1 , 0],
</code></pre>
<p>I kind found out that I need to use 'for' inside 'for', but can't do that.
Guess this is a very basic PHP code but appreciate if someone would help with it.</p>
| [
{
"answer_id": 74215649,
"author": "r2evans - GO NAVY BEAT ARMY",
"author_id": 3358272,
"author_profile": "https://Stackoverflow.com/users/3358272",
"pm_score": 3,
"selected": true,
"text": "fun <- function(vec, data) data$Ortho.name[ match(vec, data$Gene.name) ]\nZ <- structure(list(Gen... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74215652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20337087/"
] |
74,215,678 | <p>I have a web application that uses Azure AD B2C, with custom policies, for security. When I look at the user accounts in the Azure AD B2C portal, I can see an editable <code>Employee Id</code> field. This field would be very handy to store an internal company employee Id, but I would like to include this field as an output claim in the auth token.</p>
<p><a href="https://i.stack.imgur.com/BHIkH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BHIkH.png" alt="enter image description here" /></a></p>
<p>I've read the various documentation about the user profile attributes that are available through the portal, etc (<a href="https://learn.microsoft.com/en-us/azure/active-directory-b2c/user-profile-attributes" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/azure/active-directory-b2c/user-profile-attributes</a>), but EmployeeId is not listed there.</p>
<p>Based on the documentation, I'm assuming EmployeeId is not available to custom policies, but I thought I would ask the question, anyway, to see if anyone has worked out a way to include the property as an output claim in the JWT auth token?</p>
| [
{
"answer_id": 74222635,
"author": "Kartik Bhiwapurkar",
"author_id": 16526895,
"author_profile": "https://Stackoverflow.com/users/16526895",
"pm_score": 1,
"selected": false,
"text": "read data from the user profile within the respective Active Directory technical profiles as above. The... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74215678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7485272/"
] |
74,215,695 | <p>its me....again. I am currently trying to have a Macro trigger whenever a specific cell increases on a specific sheet.</p>
<p>After many attempts I have been able to get the Macro to trigger when the cell is changed (increasing or decreasing) but I cannot figure out a way to have this Macro trigger only when the specified cell increases in value.</p>
<p>I have tried to use simple Worksheet_Change with an If Then statement that calls the Macro when the cell value is changed. Again I can't get this to trigger only when the cell increases. Not sure it is possible or if I am even thinking about this is in the right way.</p>
<pre><code>Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address "Range" Then
Call MyMacro
End If
End Sub
</code></pre>
<p>Thank you for any help in advance. This would be really neat and save alot of manual clicking around.</p>
<hr />
<p>Here is the functioning Macro that I want to trigger when certain text is entered into a range.</p>
<pre><code>Sub Auto_Print_Yellow_Caution()
Application.ScreenUpdating = False
Sheets("Saver").Shapes("Group 6").Copy
Sheets("Main").Select
ActiveCell.Offset(-1, 0).Select
ActiveSheet.Paste
ActiveCell.Select
Application.ScreenUpdating = True
End Sub
</code></pre>
<p>I already have my Workbook set up to track these words/phrases and return either a TRUE or FALSE value. If TRUE the associated Order Number is Printed into a Cell and a COUNTIFS formula is used to keep track of how many orders meet the TRUE condition. That number is then used to keep track of how many total of those orders there are. That works using the following</p>
<p>=IF(ISNUMBER(SEARCH("Completed",Main!G7)),TRUE)
-<strong>looks for specific word and returns TRUE</strong></p>
<p>=IF(T3=TRUE,Main!A7,"")
-<strong>Returns order number</strong></p>
<p>=IF(COUNTIF($U3:$U$200,"?*")<ROW(U3)-2,"",INDEX(U:U,SMALL(IF(U$2:U$200<>"",ROW(U$2:U$200)),ROWS(U$2:U3))))
-<strong>Sorts order numbers into list</strong></p>
<p>=COUNTIF(T2:T135,TRUE)
-<strong>Counts number of orders</strong></p>
<p>Hopefully this adds context to what I am trying to accomplish.</p>
| [
{
"answer_id": 74216349,
"author": "Zen",
"author_id": 2190573,
"author_profile": "https://Stackoverflow.com/users/2190573",
"pm_score": -1,
"selected": false,
"text": "Private Sub Worksheet_Change(ByVal Target As Range)\n Dim KCells As Range\n Set KCells = Sheet10.Range(\"A1\... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74215695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20335190/"
] |
74,215,710 | <p>I have multiselect dropdown items with checkboxes in my react app, what I am trying to achieve is if I checked any three items, then dropdown should display maximum items selected and if I unchecked anyone of them, it should display back the drop down box with items.
Somehow it doesn't work, could someone please advise.</p>
<p><strong>CodeSanbox link</strong></p>
<p><a href="https://codesandbox.io/s/musing-sun-swvj6y?file=/src/App.js" rel="nofollow noreferrer">https://codesandbox.io/s/musing-sun-swvj6y?file=/src/App.js</a></p>
<pre><code>import { useState } from "react";
import Multiselect from "multiselect-react-dropdown";
import "./styles.css";
export default function App() {
const options = [
{ key: "Apple", email: "apple@test.com", id: 1 },
{ key: "Orange", email: "oranges@test.com", id: 2 },
{ key: "Mango", email: "mango@test.com", id: 3 },
{ key: "Grapes", email: "grapes@test.com", id: 4 }
];
const [option, setOption] = useState([]);
const [selectedOption, setSelectedOption] = useState([]);
const [maxOptions, setMaxOptions] = useState(0);
const handleTypeSelect = (e, i) => {
const copy = [...selectedOption];
copy.push(e[3 - maxOptions]);
setSelectedOption(copy);
setMaxOptions((prevState) => prevState - 1);
};
const handleTypeRemove = (e) => {
const copy = [...selectedOption];
let index = copy.indexOf(e);
copy.splice(index, 1);
setSelectedOption(copy);
setMaxOptions((prevState) => prevState + 1);
};
options.forEach((option) => {
option.displayValue = option.key + "\t" + option.email;
});
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<Multiselect
onSelect={(e) => handleTypeSelect(e, selectedOption.length)}
onRemove={handleTypeRemove}
options={selectedOption.length + 1 === maxOptions ? [] : options}
// options={!showOptions ? [] : option}
displayValue="displayValue"
showCheckbox={true}
emptyRecordMsg={"Maximum fruits selected !"}
/>
</div>
);
}
</code></pre>
| [
{
"answer_id": 74216349,
"author": "Zen",
"author_id": 2190573,
"author_profile": "https://Stackoverflow.com/users/2190573",
"pm_score": -1,
"selected": false,
"text": "Private Sub Worksheet_Change(ByVal Target As Range)\n Dim KCells As Range\n Set KCells = Sheet10.Range(\"A1\... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74215710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4826215/"
] |
74,215,735 | <p>I have scanned images like this where the background color is not necessarily consistent. When I use an ImageMagick command like this, it will apply a fixed threshold, which is not good for images without a consistent background.</p>
<pre><code>convert in.jpg -threshold 35% -type bilevel -monochrome -compress LZW out.pdf
</code></pre>
<p>Can anybody provide a robust way to generate the corresponding monochrome image maintaining all the texts?</p>
<p>I think the best method probably should be based on deep learning. But DL may take too many resources to run. Non-DL methods are also welcome if it can render reasonably good results.</p>
<p><a href="https://i.stack.imgur.com/oD58a.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oD58a.jpg" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74216174,
"author": "fmw42",
"author_id": 7355741,
"author_profile": "https://Stackoverflow.com/users/7355741",
"pm_score": 2,
"selected": false,
"text": "convert coahuila.jpg -colorspace gray -negate -lat 50x50+10% -negate result.jpg\n"
},
{
"answer_id": 74227012,... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74215735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1424739/"
] |
74,215,770 | <p>I'm trying to filter a table based on the queried result from another table.</p>
<pre><code>create temporary table test_table (id number, col_a varchar);
insert into test_table values
(1, 'a'),
(2, 'b'),
(3, 'aa'),
(4, 'a'),
(6, 'bb'),
(7, 'a'),
(8, 'c');
create temporary table test_table_2 (id number, col varchar);
insert into test_table_2 values
(1, 'aa'),
(2, 'bb'),
(3, 'cc'),
(4, 'dd'),
(6, 'ee'),
(7, 'ff'),
(8, 'gg');
</code></pre>
<p>Here I want to find out all the id's in <code>test_table</code> with value "a" in <code>col_a</code>, and then I want to filter for rows with one of these id's in <code>test_table_2</code>. I've tried this below way, but got an error: <code>SQL compilation error: syntax error line 6 at position 39 unexpected 'cte'.</code></p>
<pre><code>with cte as
(
select id from test_table
where col_a = 'a'
)
select * from test_table_2 where id in cte;
</code></pre>
<p>This approach below does work, but with large tables, it tends to be very slow. Is there a better more efficient way to scale to very large tables?</p>
<pre><code>with cte as
(
select id from test_table
where col_a = 'a'
)
select t2.* from test_table_2 t2 join cte on t2.id=cte.id;
</code></pre>
| [
{
"answer_id": 74216174,
"author": "fmw42",
"author_id": 7355741,
"author_profile": "https://Stackoverflow.com/users/7355741",
"pm_score": 2,
"selected": false,
"text": "convert coahuila.jpg -colorspace gray -negate -lat 50x50+10% -negate result.jpg\n"
},
{
"answer_id": 74227012,... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74215770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4896087/"
] |
74,215,857 | <p>I am able to create quarterly and monthly PeriodIndex like so:</p>
<pre><code>idx = pd.PeriodIndex(year=[2000, 2001], quarter=[1,2], freq="Q") # quarterly
idx = pd.PeriodIndex(year=[2000, 2001], month=[1,2], freq="M") # monthly
</code></pre>
<p>I would expect to be able to create a yearly PeriodIndex like so:</p>
<pre><code>idx = pd.PeriodIndex(year=[2000, 2001], freq="Y")
</code></pre>
<p>Instead this throws the following error:</p>
<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
File ".../script.py", line 3, in <module>
idx = pd.PeriodIndex(year=[2000, 2001], freq="Y")
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/core/indexes/period.py", line 250, in __new__
data, freq2 = PeriodArray._generate_range(None, None, None, freq, fields)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/core/arrays/period.py", line 316, in _generate_range
subarr, freq = _range_from_fields(freq=freq, **fields)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/core/arrays/period.py", line 1160, in _range_from_fields
ordinals.append(libperiod.period_ordinal(y, mth, d, h, mn, s, 0, 0, base))
File "pandas/_libs/tslibs/period.pyx", line 1109, in pandas._libs.tslibs.period.period_ordinal
TypeError: an integer is required
</code></pre>
<p>It seems like something that should be very easy to do but yet I cannot understand what is going wrong. Can anybody help?</p>
| [
{
"answer_id": 74216032,
"author": "Henry Ecker",
"author_id": 15497888,
"author_profile": "https://Stackoverflow.com/users/15497888",
"pm_score": 3,
"selected": true,
"text": "month"
},
{
"answer_id": 74216053,
"author": "Raibek",
"author_id": 11040577,
"author_profi... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74215857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7254514/"
] |
74,215,881 | <p>I have a working setup with Visual Studio 2022 17.3.6 on a Windows laptop and Mac M1 running macOS 12.6.1. When I run an Uno project or a Xamarin project it connects as expected to the Mac. I just upgraded the Mac to Ventura and am no longer able to connect. I understand the only thing that has changed is moving to Ventura, but am stuck on how to proceed.</p>
<p>The exact error is:</p>
<blockquote>
<p>An error occurred while trying to establish an SSH connection with SSH keys to 'ip:22'</p>
</blockquote>
<p>I have tried the following:</p>
<ul>
<li>SSH from my laptop in Ubuntu for Windows- worked</li>
<li>SSH from another computer- worked</li>
<li>Verified Remote Login settings on Mac</li>
<li>Ran ssh username@macip 'ls' and it worked</li>
<li>Deleted %LOCALAPPDATA%\Xamarin\Monotouch - no change</li>
<li>Reviewed Visual Studio log- no additional information</li>
<li>Reviewed log on Mac and no additional information</li>
</ul>
| [
{
"answer_id": 74216924,
"author": "monagano",
"author_id": 20345412,
"author_profile": "https://Stackoverflow.com/users/20345412",
"pm_score": 6,
"selected": true,
"text": "HostkeyAlgorithms +ssh-rsa\nPubkeyAcceptedAlgorithms +ssh-rsa\n"
},
{
"answer_id": 74445668,
"author":... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74215881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12628951/"
] |
74,215,915 | <p>I have a button that does something when clicking on it with mouse. I want the same method to also be triggered when pressing on your keyboard's up arrow key.</p>
<pre><code><button @click="doSomething()"> PRESS ME </button>
doSomething(){
console.log('clicked')
}
</code></pre>
<p>So in this example I want to <code>console.log('clicked')</code> when pressing on keyboard's up arrow. How can I do that?</p>
| [
{
"answer_id": 74216147,
"author": "DengSihan",
"author_id": 10519069,
"author_profile": "https://Stackoverflow.com/users/10519069",
"pm_score": 2,
"selected": true,
"text": "onkeystroke"
},
{
"answer_id": 74216677,
"author": "Đỗ văn Thắng",
"author_id": 11303128,
"au... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74215915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9605705/"
] |
74,215,950 | <p>I am trying to scraping the web from there I am getting all the data and I am trying out different formats to represent data. Here is the code:</p>
<pre><code>import requests
import pandas as pd
from bs4 import BeautifulSoup
url = "https://99petshops.com.au/Search?brandName=Ziwi%20Peak&animalCode=DOG&storeId=89%2F&page=1"
soup = BeautifulSoup(requests.get(url).content, "html.parser")
all_info = []
for item in soup.select(".pd-info"):
title = item.h2.get_text(strip=True)
price = item.select_one('span:-soup-contains("Price")').span.text
try:
store_name = item.select_one('span.hilighted').find_next('img')['alt']
shipping = item.select_one('span.shipping').text.strip()
price_per_100_g = item.select_one('p.unit-price').text.strip()
except:
store_name = ''
shipping = ''
price_per_100_g = ''
d = {"Title": title, "Price": price, "Store": store_name, "Shipping": shipping, "Price_Per_100_g": price_per_100_g}
for i, p in enumerate(item.select(".sp-price"), 1):
try:
store_name = p.find_next("img")["alt"]
except:
store_name = ''
d[f"store_{i:>02}"] = store_name
for i, p in enumerate(item.select(".sp-price"), 1):
d[f"price_{i:>02}"] = p.get_text(strip=True)
for i, p in enumerate(item.select(".shipping"), 1):
d[f"shipping_{i:>02}"] = p.get_text(strip=True)
all_info.append(d)
df = pd.DataFrame(all_info).fillna("")
print(df.head())
df.to_csv("data_2.csv", index=False)
</code></pre>
<p>and I have a csv data set from the above scraper consisting of 30 columns and 31 rows Here is a small example:</p>
<pre><code>Title,Price,Store,Shipping,Price_Per_100_g,store_01,store_02,store_03,store_04,store_05,store_06,store_07,store_08,store_09,store_10,store_11,store_12,store_13,store_14,store_15,store_16,store_17,store_18,store_19,store_20,store_21,store_22,store_23,store_24,store_25,price_01,price_02,price_03,price_04,price_05,price_06,price_07,price_08,price_09,price_10,price_11,price_12,price_13,price_14,price_15,price_16,price_17,price_18,price_19,price_20,price_21,price_22,price_23,price_24,price_25,shipping_01,shipping_02,shipping_03,shipping_04,shipping_05,shipping_06,shipping_07,shipping_08,shipping_09,shipping_10,shipping_11,shipping_12,shipping_13,shipping_14,shipping_15,shipping_16,shipping_17,shipping_18,shipping_19,shipping_20,shipping_21,shipping_22,shipping_23,shipping_24,shipping_25,shipping_26,store_26,price_26,shipping_27,store_27,store_28,price_27,price_28,shipping_28,shipping_29,store_29,price_29,shipping_30
Ziwi Peak Dog Air-Dried Free Range Chicken Recipe 1Kg,$57.75,Woofers World,+$7.95 shipping,$5.78 per 100g,VetShopAustralia,Vet Products Direct,Pet Shop Direct,Petso,PetPost,Pet Chemist,Your PetPA,Pet Circle,Petbarn,World for Pets,Lucky Pet,Stefmar,Budget Pet Products,Best Friends Pets,Kellyville Pets,iPetStore,My Pet Warehouse,Pet City,Pets Unleashed,PetO,PETstock,Pet House,Habitat Pets,Pet Culture,Peticular,$64.60,$64.60,$64.95,$64.95,$64.99,$66.29,$67.32,$69.69,$69.69,$69.95,$70.19,$71.99,$72.99,$73.39,$75.15,$75.95,$76.99,$77.99,$77.99,$79.99,$81.54,$81.99,$83.49,$83.49,$83.50,+$9.95 shipping,+$7.95 shipping,+$7.95 shipping,+$4.95 to $9.95 shipping,+$10.00 to $12.70 shipping,free shipping,+$9.33 to $14.81 shipping,+$4.00 to $11.16 shipping,free to $7.95 shipping,free shipping,+$9.00 shipping,+$6.95 to $10.51 shipping,+$7.99 to $13.87 shipping,free to $14.35 shipping,+$9.99 shipping,free to $15.95 shipping,free to $6.95 shipping,free shipping,free to $7.28 shipping,+$8.95 shipping,free to $11.00 shipping,free shipping,free shipping,free to $9.99 shipping,free to $20.00 shipping,+$7.95 shipping,,,,,,,,,,,,
</code></pre>
<p>Which I like to change the data frame to have the different stores for the same product in the rows not columns? the product name would be repeated by the store name would be the different names and then price and shipping.Here is the screenshot and Expected Output:</p>
<pre><code>Title,Price,Store,Shipping,Price_Per_100_g
Ziwi Peak Dog Air-Dried Free Range Chicken Recipe 1Kg,$57.75,Woofers World,+$7.95 shipping,$5.78 per 100g
Ziwi Peak Dog Air-Dried Free Range Chicken Recipe 1Kg,$64.60,VetShopAustralia,+$9.95 shipping,
Ziwi Peak Dog Air-Dried Free Range Chicken Recipe 1Kg,$64.60,Vet Products Direct,+$7.95 shipping,
Ziwi Peak Dog Air-Dried Free Range Chicken Recipe 1Kg,$64.95,Pet Shop Direct,+$7.95 shipping,
Ziwi Peak Dog Air-Dried Free Range Chicken Recipe 1Kg,$64.95,Petso,+$4.95 to $9.95 shipping,
Ziwi Peak Dog Air-Dried Free Range Chicken Recipe 1Kg,$64.99,PetPost,+$10.00 to $12.70 shipping,
Ziwi Peak Dog Air-Dried Free Range Chicken Recipe 1Kg,$66.29,Pet Chemist,free shipping,
Ziwi Peak Dog Air-Dried Free Range Chicken Recipe 1Kg,$67.32,Your PetPA,+$9.33 to $14.81 shipping,
Ziwi Peak Dog Air-Dried Free Range Chicken Recipe 1Kg,$69.69,Pet Circle,+$4.00 to $11.16 shipping,
Ziwi Peak Dog Air-Dried Free Range Chicken Recipe 1Kg,$69.69,Petbarn,free to $7.95 shipping,
Ziwi Peak Dog Air-Dried Free Range Chicken Recipe 1Kg,$69.95,World for Pets,free shipping,
Ziwi Peak Dog Air-Dried Free Range Chicken Recipe 1Kg,$70.19,Lucky Pet,+$9.00 shipping,
Ziwi Peak Dog Air-Dried Free Range Chicken Recipe 1Kg,$71.99,Stefmar,+$6.95 to $10.51 shipping,
Ziwi Peak Dog Air-Dried Free Range Chicken Recipe 1Kg,$72.99,Budget Pet Products,+$7.99 to $13.87 shipping,
Ziwi Peak Dog Air-Dried Free Range Chicken Recipe 1Kg,$73.39,Best Friends Pets,free to $14.35 shipping,
Ziwi Peak Dog Air-Dried Free Range Chicken Recipe 1Kg,$75.15,Kellyville Pets,+$9.99 shipping,
Ziwi Peak Dog Air-Dried Free Range Chicken Recipe 1Kg,$75.95,iPetStore,free to $15.95 shipping,
Ziwi Peak Dog Air-Dried Free Range Chicken Recipe 1Kg,$76.99,My Pet Warehouse,free to $6.95 shipping,
Ziwi Peak Dog Air-Dried Free Range Chicken Recipe 1Kg,$77.99,Pet City,free shipping,
Ziwi Peak Dog Air-Dried Free Range Chicken Recipe 1Kg,$77.99,Pets Unleashed,free to $7.28 shipping,
Ziwi Peak Dog Air-Dried Free Range Chicken Recipe 1Kg,$79.99,PetO,+$8.95 shipping,
Ziwi Peak Dog Air-Dried Free Range Chicken Recipe 1Kg,$81.54,PETstock,free to $11.00 shipping,
Ziwi Peak Dog Air-Dried Free Range Chicken Recipe 1Kg,$81.99,Pet House,free shipping,
Ziwi Peak Dog Air-Dried Free Range Chicken Recipe 1Kg,$83.49,Habitat Pets,free shipping,
Ziwi Peak Dog Air-Dried Free Range Chicken Recipe 1Kg,$83.49,Pet Culture,free to $9.99 shipping,
Ziwi Peak Dog Air-Dried Free Range Chicken Recipe 1Kg,$83.50,Peticular,free to $20.00 shipping,
</code></pre>
<p>Can anyone help me figure out the best way to reach the expected output? Thanks!</p>
| [
{
"answer_id": 74216460,
"author": "sammywemmy",
"author_id": 7175713,
"author_profile": "https://Stackoverflow.com/users/7175713",
"pm_score": 1,
"selected": false,
"text": "# pip install pyjanitor\nimport pandas as pd\nimport janitor\n\ndf = pd.read_excel('data_2.xlsx')\ndf.columns = d... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74215950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18183763/"
] |
74,215,951 | <p>I have a pyspark dataframe column with values like this:</p>
<pre class="lang-none prettyprint-override"><code>+----------------------------+
| date_string|
+----------------------------+
| 22JUL2020:20:35:36.009269|
| 22JUL2020:20:41:45.483747|
</code></pre>
<p>I want to cast this string column into a timestamp so I'm using the follow code:</p>
<pre class="lang-py prettyprint-override"><code>df.withColumn('date_timestamp', to_timestamp('date_string', 'ddMMMyyyy:HH:mm:ss'))
</code></pre>
<pre class="lang-none prettyprint-override"><code>+----------------------------+----------------------------+
| date_string| date_timestamp|
+----------------------------+----------------------------+
| 22JUL2020:20:35:36.009269| 22JUL2020:20:35:36|
| 22JUL2020:20:41:45.483747| 22JUL2020:20:41:45|
</code></pre>
<p>What format should I use to not lose the numbers after the seconds? I've tried the following formats but always get null:</p>
<pre class="lang-py prettyprint-override"><code>df.withColumn('date_timestamp', to_timestamp('date_string', 'ddMMMyyyy:HH:mm:ss.nnnnnn'))
df.withColumn('date_timestamp', to_timestamp('date_string', 'ddMMMyyyy:HH:mm:ss.SSSSSS'))
df.withColumn('date_timestamp', to_timestamp('date_string', 'ddMMMyyyy:HH:mm:ss.SSS'))
</code></pre>
<pre class="lang-none prettyprint-override"><code>+----------------------------+-------------------------+
| date_string| date_timestamp|
+----------------------------+-------------------------+
| 22JUL2020:20:35:36.009269| null|
| 22JUL2020:20:41:45.483747| null|
</code></pre>
| [
{
"answer_id": 74216460,
"author": "sammywemmy",
"author_id": 7175713,
"author_profile": "https://Stackoverflow.com/users/7175713",
"pm_score": 1,
"selected": false,
"text": "# pip install pyjanitor\nimport pandas as pd\nimport janitor\n\ndf = pd.read_excel('data_2.xlsx')\ndf.columns = d... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74215951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19376880/"
] |
74,215,954 | <pre><code>def get_txt(path):
with open(path, 'r', encoding='utf-8') as file:
while file.readline():
print(file.readline())
if __name__ == '__main__':
path = 'data/data.html'
get_txt(path)
</code></pre>
<p>This is my code, which prints the data of the source file line by line, and prints it on the console, but when I use Ctrl+F to search in the console, I don't find the data I want. It has read the data, but I don't know from which part it started reading, the data is missing</p>
<p>My file is an html file with a size of 13MB. The first line of data printed on the console is not:</p>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
</code></pre>
<p>, but the data on the first line of my source file is this. The last line prints:</p>
<pre class="lang-html prettyprint-override"><code></html>
</code></pre>
<p>this is reasonable. I've tried searching with Ctrl+F, but the results are always unexpected.</p>
| [
{
"answer_id": 74215966,
"author": "John Gordon",
"author_id": 494134,
"author_profile": "https://Stackoverflow.com/users/494134",
"pm_score": 2,
"selected": false,
"text": " while file.readline():\n print(file.readline())\n"
},
{
"answer_id": 74216021,
"author": "J... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74215954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20327862/"
] |
74,215,981 | <p>I am using Android Studio to learn my flutter project. For the first run with emulator Pixel 5 API 30, it work well.</p>
<p>But If I close Android Studio IDE without terminate the running app and then re-open Android Studio to run the project again with that emulator, it start running on the background and I have no way to get it back on screen. When I open the project, I see the emulator in Device Manager blue (meaning it is still running even I close the IDE).</p>
<p>2-Options:</p>
<p>1- I may want to stop the running emulator and re run again. I have try <code>adb kill-server</code> and <code>adb start-server</code>. There is nothing work.
Also, I cannot <strong>.lock</strong> folder and file in <code>.android\avd\Pixel_5_API_30.avd</code>. It said the action can't be completed because the file is open in qemu-system-x86-64.exe</p>
<p>2- Bring back the background emulator back to display on screen. I cannot find any solution yet.</p>
<p>The only solution is to restart my PC.</p>
<p>Anyone know, please share. I search a lot around here.</p>
| [
{
"answer_id": 74283553,
"author": "K.Sopheak",
"author_id": 5241603,
"author_profile": "https://Stackoverflow.com/users/5241603",
"pm_score": 0,
"selected": false,
"text": "File"
}
] | 2022/10/27 | [
"https://Stackoverflow.com/questions/74215981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5241603/"
] |
74,216,005 | <p>i<code>m learning React and trying to display random images from https://picsum.photos/ i</code>m using their API to get a list of random images, this is a JSON file containing some info, i<code>m interested only in the images URL. it seems like my array is filled with the url</code>s but i cant access them.</p>
<p><a href="https://i.stack.imgur.com/pmGFc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pmGFc.png" alt="enter image description here" /></a></p>
<p>i have tried logging step by step some of my issues, it seems like my array is getting filled with strings, but in the end i cant get any access to them, if i fill the list manuallt , lets say</p>
<p>const array = [1,2,3]</p>
<p>it will log the values like array[0] .</p>
<p>why cant i access the strings which was pushed into the array with my JSON callback function?</p>
| [
{
"answer_id": 74216141,
"author": "Tarek Al Beb",
"author_id": 7214287,
"author_profile": "https://Stackoverflow.com/users/7214287",
"pm_score": 0,
"selected": false,
"text": "console.log(list[55])"
},
{
"answer_id": 74219860,
"author": "GDK",
"author_id": 13475837,
... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20344517/"
] |
74,216,013 | <p>I'm trying to test a react native app with the following test suite and cases:</p>
<p>Test case files:</p>
<ul>
<li>login.ts</li>
<li>doActionAfterLogin_A.ts</li>
</ul>
<p>Test suite:
[login.ts, doActionAfterLogin_A.ts]</p>
<p><strong>Problem:</strong>
For login.ts I want to set the desired capability appium:noReset = false because I want to test the flow of the fresh install. However, I want to test doActionAfterLogin_A.ts with appium:noReset = true because I don't want to go through the whole fresh installation flow again.</p>
<p>The problem is that in between test cases in the suite, Appium will close the browser/driver and launch again with the same desired capabilities, which in this case appium:noReset will always be false. Is there a way to either:</p>
<ol>
<li>Stop the browser/driver from closing in between test cases</li>
<li>Change the desired capabilites in between test cases</li>
<li>Is the way I'm structuring my test cases wrong?</li>
</ol>
<p>Further info: Using Appium, Webdriverio, Mocha, Typescript</p>
<p>Thank you!</p>
| [
{
"answer_id": 74216141,
"author": "Tarek Al Beb",
"author_id": 7214287,
"author_profile": "https://Stackoverflow.com/users/7214287",
"pm_score": 0,
"selected": false,
"text": "console.log(list[55])"
},
{
"answer_id": 74219860,
"author": "GDK",
"author_id": 13475837,
... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1172908/"
] |
74,216,040 | <p>I need to run a simple script on a large amount of fasta files. It is very simple: I just need to add some information to the header of the files.</p>
<pre class="lang-py prettyprint-override"><code>import os
from pathlib import Path
from Bio import SeqIO
import time
import multiprocessing as mp
def header(dirname):
with open('output.fasta', 'w') as output:
for file in os.listdir(dirname):
if file == "output.fasta":
continue
seq = SeqIO.parse(file, 'fasta')
ortog = Path(file).stem
for record in seq:
record.description = ortog
SeqIO.write(record, output, 'fasta')
</code></pre>
<p>I am trying to parallelize the script in python to optimize the time since I will have to do this a few times, but I am having some difficulties with how to use the multiprocessing package. Can anyone give me directions on how to make this parallelization work?</p>
<p>I'm getting the error "TypeError: map() got an unexpected keyword argument 'args'"</p>
<pre class="lang-py prettyprint-override"><code>if __name__ == "__main__":
start_time = time.perf_counter()
with mp.Pool(4) as pool:
pool.map(header, args=(dirname))
finish_time = time.perf_counter()
print("Program finished in {} seconds - using multiprocessing".format(finish_time-start_time))
</code></pre>
| [
{
"answer_id": 74221681,
"author": "j23",
"author_id": 10911932,
"author_profile": "https://Stackoverflow.com/users/10911932",
"pm_score": 1,
"selected": false,
"text": " pool.map(header, dirname)\n"
},
{
"answer_id": 74234486,
"author": "pippo1980",
"author_id": 98770... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20344520/"
] |
74,216,041 | <p>I am trying to write an admin panel where videos can be edited, deleted and reviewed using Django. While the loop I have set up runs smoothly, it only accepts the first value as the id value in the video deletion function. I'm pretty sure I closed the for loop in the right place, I guess there's nothing wrong with it.</p>
<pre><code>
**This is my template page.**
{% extends 'dashboard/main.html' %}
{% load static %}
{% block content %}
<div class="col-sm-12">
<div class="card">
<div class="card-header">
<h5>Edit / Show Videos</h5>
</div>
<div class="card-block">
<form method="get" action="{% url 'videos' %}">
<div id="zero-configuration_filter" class="dataTables_filter">
<label>Search:<input type="search" class="form-control form-control-sm" placeholder="Type video ID or Title" name="q" aria-controls="zero-configuration"></label>
</div>
<div class="table-responsive">
<table id="responsive-table-model" class="display table dt-responsive nowrap" style="width:100%">
<thead>
<tr>
<th>Video ID</th>
<th>Video Title</th>
<th>Video Create Date</th>
<th>Video Status</th>
<th>Video From</th>
<th>Video IMG</th>
<th>Video Duration</th>
<th>Video Slug</th>
<th> Action </th>
</tr>
</thead>
<tbody>
{% autoescape off %}
{% for video in videos reversed %}
<tr>
<td class="tabledit-view-mode" style="cursor: pointer;"><span class="tabledit-span">
{{ video.id }}</span></td>
<td>{{ video.video_title|truncatechars:25 }}</td>
<td>{{ video.video_create_date }}</td>
<td>{{ video.video_status }}</td>
<td>{{ video.video_from }}</td>
<td> <div class="col-lg-8 col-md-6 col-sm-6">
<img src="{{ video.video_img}}" alt="img" class="img-fluid animation-toggle animated" data-animate="jackInTheBox">
</div></td>
<td>{{ video.video_duration }}</td>
<td>{{ video.video_slug|truncatechars:25 }}</td>
<td>
<ul class="list-inline-item">
<li class="list-inline-item">
<a class="material-icons" href="{% url 'video' video.video_slug %}">
remove_red_eye
</a>
</li>
<li class="list-inline-item">
<a class="material-icons" href="{% url 'videosupdate' video.id %}">
edit
</a>
</li>
<li class="list-inline-item">
<div class="text-center">
<!-- Button HTML (to Trigger Modal) -->
<a href="#myModal" class="trigger-btn" data-toggle="modal"><span class="material-icons">
delete
</span></a>
</div>
<div id="myModal" class="modal fade">
<div class="modal-dialog modal-confirm">
<div class="modal-content">
<div class="modal-header flex-column">
<div class="icon-box">
<i class="material-icons">&#xE5CD;</i>
</div>
<h4 class="modal-title w-100">Are you sure?</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
</div>
<div class="modal-body">
<p>Do you really want to delete these records? This process cannot be undone. {% url 'videosdelete' video.id %}</p>
</div>
<div class="modal-footer justify-content-center">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<a href="{% url 'videosdelete' video.id %}"><button type="button" class="btn btn-danger">Delete </button></a>
</div>
</div>
</div>
</div>
</li>
</ul>
</td>
</tr>
</form>
{% endfor %}
{% endautoescape %}
</tbody>
</table>
</div>
**This is my urls.py**
path ('videos-delete/<int:pk>/',VideosDelete.as_view(),name="videosdelete")
**And delete view.**
class VideosDelete(View):
model = Video
def get (self, request, pk):
videos = Video.objects.get(id=pk)
#if request.GET.get('act') == 'delete':
videos.delete()
return redirect ('/dashboard/videos/')
</code></pre>
<p><a href="https://i.stack.imgur.com/vVJ4n.png" rel="nofollow noreferrer">YOU CAN SEE ADMIN DASHBOARD CLICK HERE</a></p>
<p>When I click the delete button to delete any video <a href="http://127.0.0.1:8000/dashboard/videos-delete/4009/" rel="nofollow noreferrer">http://127.0.0.1:8000/dashboard/videos-delete/4009/</a></p>
<p>redirects to address. 4009 is the id of the first video. My english not good, sorry for mistakes.</p>
<p>I tried setting up the loop in different ways, but with no results. I tried changing the URL structure and doing href="/dashboard/videos-delete/{{video.id}}", same result.</p>
| [
{
"answer_id": 74221681,
"author": "j23",
"author_id": 10911932,
"author_profile": "https://Stackoverflow.com/users/10911932",
"pm_score": 1,
"selected": false,
"text": " pool.map(header, dirname)\n"
},
{
"answer_id": 74234486,
"author": "pippo1980",
"author_id": 98770... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20344526/"
] |
74,216,060 | <p>Write a function that takes two arguments to determine length of interval used to determine if arrivals are close or not. Should return true is close and false if not</p>
<p>Idk I can’t figure it out.</p>
| [
{
"answer_id": 74221681,
"author": "j23",
"author_id": 10911932,
"author_profile": "https://Stackoverflow.com/users/10911932",
"pm_score": 1,
"selected": false,
"text": " pool.map(header, dirname)\n"
},
{
"answer_id": 74234486,
"author": "pippo1980",
"author_id": 98770... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20344610/"
] |
74,216,069 | <p>I have the following table which stores historical prices for stocks</p>
<pre><code> stock_id | open | close | high | low | timestamp
----------+--------+--------+--------+--------+---------------------
2 | 338 | 330 | 338 | 330 | 2022-10-21 05:30:00
2 | 341 | 338 | 341 | 338 | 2022-10-20 05:30:00
2 | 340.05 | 340 | 341 | 340 | 2022-10-19 05:30:00
2 | 357 | 340 | 357 | 340 | 2022-10-18 05:30:00
2 | 358 | 358 | 358 | 358 | 2022-10-12 05:30:00
</code></pre>
<p>I want to get the 1 day change from the previous day by using values of last 2 record and window function <code>LAG()</code> so I came up with the following query</p>
<pre><code>SELECT stock_id,
close as last_price,
timestamp::DATE,
LAG(close) OVER (PARTITION BY stock_id
ORDER BY timestamp desc) AS one_day_change
FROM historical_prices WHERE stock_id = 2;
</code></pre>
<p>But this me all the change not just the latest record</p>
<pre><code>stock_id | last_price | timestamp | one_day_change
----------+------------+------------+----------------
2 | 330 | 2022-10-21 |
2 | 338 | 2022-10-20 | 330
2 | 340 | 2022-10-19 | 338
</code></pre>
<p>What I want instead is this</p>
<pre><code>stock_id | last_price | timestamp | one_day_change
----------+------------+------------+----------------
2 | 330 | 2022-10-21 | 338
</code></pre>
<p>What would be the best way to accomplish this? Maybe <code>LAG()</code> is not suitable for this usecase?</p>
| [
{
"answer_id": 74216980,
"author": "Marc",
"author_id": 1024832,
"author_profile": "https://Stackoverflow.com/users/1024832",
"pm_score": 0,
"selected": false,
"text": "SELECT stock_id,\n close as last_price,\n timestamp::DATE,\n LAG(close) OVER (PARTITION BY stock_id\n... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2725838/"
] |
74,216,085 | <p>My code can't run. Always pop up success but compiler error.
Below is the code</p>
<pre><code>CREATE PROCEDURE sp_register (personID VARCHAR(5), fullname VARCHAR(50), password VARCHAR(10), username VARCHAR(50), address VARCHAR(100), phoneno NUMBER(10), cardNo NUMBER (16))
BEGIN
DECLARE s VARCHAR(20);
IF EXISTS(SELECT person_id FROM Person WHERE Username = username)
THEN SET s = 'User already exists';
ELSE
INSERT INTO Person ('Person_ID', 'Name', 'Password', 'Username', 'Address', 'Phone_numbers', 'Card_Card_number')
VALUES(personID, name, password, username,address,phoneno,cardNo)
SET s = "User Registered";
END IF;
END
</code></pre>
<p>what is the error and the solution code to solve it.</p>
| [
{
"answer_id": 74216980,
"author": "Marc",
"author_id": 1024832,
"author_profile": "https://Stackoverflow.com/users/1024832",
"pm_score": 0,
"selected": false,
"text": "SELECT stock_id,\n close as last_price,\n timestamp::DATE,\n LAG(close) OVER (PARTITION BY stock_id\n... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18544755/"
] |
74,216,102 | <p>Hi I'm developing simple test app in MAUI for windows.</p>
<p>The problem is that label in view page doesn't change when PropertyChanged called.</p>
<p>And I found that when i change [PortErrorMsg] Property, i can see PropertyChanged func called but</p>
<p>'get' in [PortErrorMsg] Property is not called.</p>
<p>(Debug.WriteLine("Message for checking whether get is working properly"); <-- this is not called.)</p>
<p>Here is my code below</p>
<p>Xaml :</p>
<pre><code><ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:vm="clr-namespace:NxJig.ViewModels"
x:DataType="vm:JigViewModel"
x:Class="NxJig.Views.JigPage"
Title="JigPage">
<ContentPage.BindingContext>
<vm:JigViewModel/>
</ContentPage.BindingContext>
<VerticalStackLayout>
<HorizontalStackLayout Margin="30">
<Picker Title="Select Port" x:Name="picker1" SelectedIndexChanged="picker1_SelectedIndexChanged" FontSize="Large">
<Picker.Items>
<x:String>COM1</x:String>
<x:String>COM2</x:String>
<x:String>COM3</x:String>
<x:String>COM4</x:String>
<x:String>COM5</x:String>
<x:String>COM6</x:String>
<x:String>COM7</x:String>
<x:String>COM8</x:String>
<x:String>COM9</x:String>
<x:String>COM10</x:String>
<x:String>COM11</x:String>
<x:String>COM12</x:String>
<x:String>COM13</x:String>
<x:String>COM14</x:String>
<x:String>COM15</x:String>
<x:String>COM16</x:String>
<x:String>COM17</x:String>
<x:String>COM18</x:String>
<x:String>COM19</x:String>
<x:String>COM20</x:String>
</Picker.Items>
</Picker>
</HorizontalStackLayout>
<Label Text="{Binding PortErrorMsg, Mode=TwoWay}" IsEnabled="True" FontSize="Large"/>
</VerticalStackLayout>
</ContentPage>
</code></pre>
<p>Xaml behind code :</p>
<pre><code>public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
private void picker1_SelectedIndexChanged(object sender, EventArgs e)
{
ViewModel vm = new ViewModel();
vm.SerialPortName = picker1.SelectedItem as string;
}
}
</code></pre>
<p>ViewModel :</p>
<pre><code>namespace NxJig.ViewModels
{
public class JigViewModel : INotifyPropertyChanged
{
private SerialPort serialPort;
private string serialPortName = "";
private string defaultStr = "init text";
private string successStr = "complete";
private string failStr = "check the port again";
public string portErrorMsg = defaultStr;
public event PropertyChangedEventHandler PropertyChanged;
public JigViewModel()
{
serialPort = new SerialPort();
serialPort.BaudRate = 9600;
serialPort.Parity = Parity.None;
serialPort.StopBits = StopBits.One;
serialPort.DataBits = 8;
}
public string SerialPortName
{
get => serialPortName;
set
{
if (serialPortName != value)
{
serialPortName = value;
Debug.WriteLine($"{serialPortName} is selected.");
OnPropertyChanged(nameof(SerialPortName));
serialPort.PortName = value;
if (!serialPort.IsOpen)
{
try
{
serialPort.Open();
if(serialPort.IsOpen)
{
this.PortErrorMsg = successStr;
}
}
catch
{
this.PortErrorMsg = failStr;
}
}
}
}
}
public string PortErrorMsg
{
set
{
if (portErrorMsg != value)
{
portErrorMsg = value;
Debug.WriteLine($"{portErrorMsg} is selected.");
OnPropertyChanged(nameof(PortErrorMsg));
}
}
get
{
Debug.WriteLine("Message for checking whether get is working properly");
return portErrorMsg;
}
}
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
Debug.WriteLine($"propertyName is {propertyName}");
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
else
{
Debug.WriteLine("PropertyChanged is null !");
}
}
}
}
</code></pre>
<p>I expected the label in xaml is changed when PropertyChanged called.</p>
| [
{
"answer_id": 74216980,
"author": "Marc",
"author_id": 1024832,
"author_profile": "https://Stackoverflow.com/users/1024832",
"pm_score": 0,
"selected": false,
"text": "SELECT stock_id,\n close as last_price,\n timestamp::DATE,\n LAG(close) OVER (PARTITION BY stock_id\n... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20344623/"
] |
74,216,108 | <p>Why my weakRef.Target is still alive on the second shot?</p>
<p>Could it be a bug? If not, where is the error?</p>
<p>Result:</p>
<pre><code>weakRef.Target is alive = True, expected true because inst keep a hold on SomeClass.
weakRef.Target is alive = True, expected false, because there is no more ref on SomeClass.
</code></pre>
<p>Code:</p>
<pre><code>public static class DelegateKeeper
{
private static ConditionalWeakTable<object, Action> cwtAction = new ConditionalWeakTable<object, Action>();
public static void KeepAlive(Action action) => cwtAction.Add(action.Target, action);
}
public class SomeClass
{
public void DoSomething() { }
}
public static class GcHelper
{
public static void Collect()
{
// OK surely overkill but just to make sure. I will reduce it when everyting will be understood.
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true);
GC.WaitForPendingFinalizers();
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true);
GC.WaitForPendingFinalizers();
}
}
SomeClass instanceSomeClass;
WeakReference<Action> weakRef;
[TestMethod]
public void TestLifeOfObject()
{
Init();
GcHelper.Collect();
Debug.WriteLine($"weakRef.Target is alive = {weakRef.TryGetTarget(out _)}, expected true because inst keep a hold on SomeClass.");
RemoveLastReferenceOnSomeClass();
GcHelper.Collect();
Debug.WriteLine($"weakRef.Target is alive = {weakRef.TryGetTarget(out _)}, expected false, because there is no more ref on SomeClass.");
}
private void Init()
{
instanceSomeClass = new SomeClass();
var action = instanceSomeClass.DoSomething;
weakRef = new WeakReference<Action>(action);
DelegateKeeper.KeepAlive(action);
}
private void RemoveLastReferenceOnSomeClass()
{
instanceSomeClass = null;
}
</code></pre>
| [
{
"answer_id": 74223435,
"author": "Charlieface",
"author_id": 14868997,
"author_profile": "https://Stackoverflow.com/users/14868997",
"pm_score": 2,
"selected": false,
"text": "ConditionalWeakTable"
}
] | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/452845/"
] |
74,216,138 | <p>I have tried researching this but can't find anything like what I am looking for.</p>
<p>I am trying to find a specific phrase in a list. Here is a test list:</p>
<pre><code>data = {"text":["Map:","Internet",
"Subscriptions","","Map:",
"Adult","Literacy","and",
"Numeracy","|","8"]}
</code></pre>
<p>I want to get the index position of the first word in a phrase I am looking for like: <code>Map: Adult Literacy and Numeracy</code>. The answer for this would be <code>4</code> since the first word of the phrase is <code>Map:</code>. However, there are 2 <code>Maps:</code> in the list and I only need to find the one that is apart of the whole phrase <code>Map: Adult Literacy and Numeracy</code>.</p>
<p>Here is what I tried:</p>
<pre><code>teststring = "Map: Adult Literacy and Numeracy"
teststring_split = teststring.split(" ")
data = {"text":["Map:","Internet",
"Subscriptions","","Map:",
"Adult","Literacy","and",
"Numeracy","|","8"]}
if teststring in " ".join(data["text"]):
idx = data["text"].index(teststring.split(' ')[0])
print(idx)
</code></pre>
<p>However it comes out it with <code>0</code> which makes sense because I am not sure how to get the specific <code>Maps:</code> that is apart of the phrase.</p>
<p><strong>EDIT</strong> I am close because of @Alexander 's answer. I would have accepted his answer as correct but his answer only checks the first two index values in the phrase's split string. I would need to check the value as the list and phrases are dynamic and some phrases are very similar in wording.</p>
<p>Here is the code I have so far now:</p>
<pre><code>for i in range(len(data['text'])):
if data['text'][i] == teststring_split[0]:
for m in range(len(teststring_split)):
if data['text'][i + m] == teststring_split[m]:
print(teststring_split[m])
</code></pre>
<p>This will output:</p>
<pre><code>Map:
Map:
Adult
Literacy
and
Numeracy
</code></pre>
<p>So I can get a confirmation on the phrase as it prints out but I am not sure how to get the index of 4 after confirming the last word <code>Numeracy</code></p>
| [
{
"answer_id": 74216192,
"author": "AlienMeepers",
"author_id": 14165415,
"author_profile": "https://Stackoverflow.com/users/14165415",
"pm_score": 0,
"selected": false,
"text": "teststring"
},
{
"answer_id": 74216194,
"author": "Alexander",
"author_id": 17829451,
"au... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18192997/"
] |
74,216,140 | <p>I was trying to calculate the mean value by group for several variables. I wrote a loop to do that but it didn't give me what I want. Ideally, in the returned dataset, I'd want to have something like this:</p>
<pre><code># varA var1_mean var2_mean var3_mean
# 1 xx xx xx
# 2 xx xx xx
# 3 xx xx xx
# 4 xx xx xx
</code></pre>
<p>Here is my example code.</p>
<pre><code>varA<-rep(c(1:4),times=30)
df1<-data.frame(varA)
df1$var1 <- sample(500:1000, length(df1$varA))
df1$var2 <- sample(500:1000, length(df1$varA))
df1$var3 <- sample(500:1000, length(df1$varA))
varlist<-c("var1", "var2", "var3")
for( varname in varlist) {
mean_var<-paste0(varname, "_mean")
df1_mean<- df1 %>%
group_by(varA) %>%
dplyr::summarise(mean_var=mean(.[[varname]], na.rm = TRUE))
}
</code></pre>
<p>Thanks in advance for the help!</p>
| [
{
"answer_id": 74216192,
"author": "AlienMeepers",
"author_id": 14165415,
"author_profile": "https://Stackoverflow.com/users/14165415",
"pm_score": 0,
"selected": false,
"text": "teststring"
},
{
"answer_id": 74216194,
"author": "Alexander",
"author_id": 17829451,
"au... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17608782/"
] |
74,216,143 | <p>is there any way to delete or replace text with (...) if the text is inside the .class p tag is greater than 100 characters?</p>
<p>Example I have this long text inside on the p tag:</p>
<pre><code><div class='classname'>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis nibh velit, suscipit bibendum sagittis non, consequat vestibulum ante. Praesent in fermentum turpis. Nam nec erat vulputate, imperdiet mi ac, porttitor diam. Quisque posuere odio vel nulla varius dictum. Vestibulum malesuada tellus id cursus pretium. Cras volutpat, diam vel molestie bibendum, neque risus ullamcorper augue, vel convallis odio purus hendrerit quam. Mauris convallis dolor vel ex placerat, non imperdiet dolor lacinia. </p>
</code></pre>
<p>Expected Result:</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis nibh velit, suscipit bibendum sagittis non, consequat ...</p>
| [
{
"answer_id": 74216176,
"author": "Ammar Ahmed",
"author_id": 14538687,
"author_profile": "https://Stackoverflow.com/users/14538687",
"pm_score": 1,
"selected": false,
"text": "// Gets all p elements inside element with class: classname\nconst paras = document.querySelectorAll(\".classn... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12510016/"
] |
74,216,151 | <p>I am doing a google clone (mini project) for that I need to import <code>useHistory</code> from <code>react-router-dom</code>.</p>
<p>I have followed the below steps:</p>
<p>step 1: <code>npm install --save react-router-dom</code> (I used this command in terminal)
step 2: <code>import { useHistory } from "react-router-dom"</code> (use this in the top of my file)
step 3: <code>const history = useHistory()</code> (use this in my code)</p>
<p>after following this steps I am getting the below error:</p>
<blockquote>
<p>export 'useHistory' (imported as 'useHistory') was not found in
'react-router-dom' (possible exports: AbortedDeferredError, Await,
BrowserRouter, Form, HashRouter, Link, MemoryRouter, NavLink,
Navigate, NavigationType, Outlet, Route, Router, RouterProvider,
Routes, ScrollRestoration, UNSAFE_DataRouterContext,
UNSAFE_DataRouterStateContext, UNSAFE_DataStaticRouterContext,
UNSAFE_LocationContext, UNSAFE_NavigationContext, UNSAFE_RouteContext,
UNSAFE_enhanceManualRouteObjects, createBrowserRouter,
createHashRouter, createMemoryRouter, createPath,
createRoutesFromChildren, createRoutesFromElements,
createSearchParams, defer, generatePath, isRouteErrorResponse, json,
matchPath, matchRoutes, parsePath, redirect, renderMatches,
resolvePath, unstable_HistoryRouter, useActionData, useAsyncError,
useAsyncValue, useFetcher, useFetchers, useFormAction, useHref,
useInRouterContext, useLinkClickHandler, useLoaderData, useLocation,
useMatch, useMatches, useNavigate, useNavigation, useNavigationType,
useOutlet, useOutletContext, useParams, useResolvedPath,
useRevalidator, useRouteError, useRouteLoaderData, useRoutes,
useSearchParams, useSubmit)</p>
</blockquote>
<p>It seems like <code>useHistory</code> is not a part of <code>react-router-dom</code>.</p>
<p>Unable to import the <code>useHistory</code> in the react app.</p>
| [
{
"answer_id": 74216176,
"author": "Ammar Ahmed",
"author_id": 14538687,
"author_profile": "https://Stackoverflow.com/users/14538687",
"pm_score": 1,
"selected": false,
"text": "// Gets all p elements inside element with class: classname\nconst paras = document.querySelectorAll(\".classn... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15181085/"
] |
74,216,171 | <p>I was searching a thing in command pallet such as CTRL+Sift+P in VSCode.
Next, I needed to write programs in editors in VSCode. While wirting codes in a editor, I found a typo.</p>
<p>So I wanted to delete a charactor by using Back space. But, I could not delte the charactor in only the VSCode Editers. I can remove any charactors or numbers, while using any other editors such as pycharm, and, other editors. If I hit the Back space, the cursor moves to command pallet.
I checked short cut of the preferece of VSCode. But, I could not find any short cut of the Back space.</p>
<p>I use Win10, and VSCode version is V1.70.</p>
<p>I searched google. But, I have not found any answers.</p>
<p>Please help</p>
<p>I googled in relation to VSCode of the problems.
But, I have not found any hint or any solution.</p>
<p>I would like to use Back space of my key board.</p>
| [
{
"answer_id": 74216176,
"author": "Ammar Ahmed",
"author_id": 14538687,
"author_profile": "https://Stackoverflow.com/users/14538687",
"pm_score": 1,
"selected": false,
"text": "// Gets all p elements inside element with class: classname\nconst paras = document.querySelectorAll(\".classn... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10258829/"
] |
74,216,173 | <pre><code>import random
n=random.randint(1, 5)
i=int(input("Guess a number from one to ten"))
if i!=1 and i!=2 and i!=3 and i!=4 and i!=5:
print("ERROR")
elif i<n:
print("SMALL")
elif n<i:
print
("BIG")
else:
print("You're right!")
</code></pre>
<p>Tried to get a num from 1-5 and 3 tries but only got one</p>
| [
{
"answer_id": 74216247,
"author": "Wolric",
"author_id": 20163209,
"author_profile": "https://Stackoverflow.com/users/20163209",
"pm_score": 1,
"selected": false,
"text": "for"
},
{
"answer_id": 74216289,
"author": "Shub",
"author_id": 20285541,
"author_profile": "ht... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16838060/"
] |
74,216,211 | <p>So I have a <code>Dropdown Box</code> which contains data 'Dog', 'Lion', and 'Cat' so once I select the Dog it will not show in the Dropdown List how to achieve that, is it possible?</p>
<p>HTML:</p>
<pre class="lang-html prettyprint-override"><code><mat-form-field class="full-width" floatLabel="always" appearance="outline">
<mat-label>Choose Animal</mat-label>
<mat-select formControlName="animal">
<mat-option *ngFor="let items of animal" [value]="items.id">
{{items.animal}}
</mat-option>
</mat-select>
</mat-form-field>
</code></pre>
<p>TS:</p>
<pre class="lang-js prettyprint-override"><code>ngOninit() {
this.getList()
}
getList() {
this.animalSVC.getListOfAnimal().subscribe((response: AnimalDTO) => {
this.animalObj = response;
this.animalDS = this.animalObj.items
})
}
</code></pre>
<p>For example, I select the lion in the list once I selected it will not show in the selected box again</p>
| [
{
"answer_id": 74216247,
"author": "Wolric",
"author_id": 20163209,
"author_profile": "https://Stackoverflow.com/users/20163209",
"pm_score": 1,
"selected": false,
"text": "for"
},
{
"answer_id": 74216289,
"author": "Shub",
"author_id": 20285541,
"author_profile": "ht... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20209848/"
] |
74,216,223 | <p>I want to bring out the results of a function that is within another function. When I try to print or return results it only brings out the result of the function "Sum".</p>
<pre><code>let readlineSync = require("readline-sync");
let a = readlineSync.question(
"Choose an operation: Sum or Substraction: "
);
let param1 = parseInt(readlineSync.question("Value 1: "));
let param2 = parseInt(readlineSync.question("Value 2: "));
chosenFunction();
function Sum() {
return param1 + param2;
}
function Substraction() {
return param1 - param2;
}
function chosenFunction() {
let result;
if (a = 'Sum') {
result = console.log (Sum());
} else if (a = 'Substraction') {
result = console.log ( Substraction());
}
return result
}
</code></pre>
| [
{
"answer_id": 74216234,
"author": "flyingfox",
"author_id": 3176419,
"author_profile": "https://Stackoverflow.com/users/3176419",
"pm_score": 2,
"selected": false,
"text": "console.log"
},
{
"answer_id": 74216246,
"author": "Steven Spungin",
"author_id": 5093961,
"au... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15614533/"
] |
74,216,235 | <p>I'm new to React JS and just start working on a project with React JS as frontend and Python Flask 2.2.2 as the backend. In Flask I'm trying to return a JSON in a function:</p>
<pre><code>@app.route('/profile')
def test():
response_body = {
"test123": "123",
"name": "Owen!",
"about": "about!"
}
print(f"response is {response_body}")
return Response(response_body, status=200, mimetype='application/json')
</code></pre>
<p>Basically, it will just return a JSON object(Flask will automatically convert it to JSON as I learned). And then in JS I used axios to call the backend and get the response like this:</p>
<pre><code>axios
.get("/profile")
.then(response =>
console.log(response.data.about)
)
.catch(error => {});
</code></pre>
<p>I also did some research that axios and JS will automatically convert the JSON to Javascript object so "response.data.about" should give me the result in JSON returned from Flask. But I'm actually getting undefined in console.
Could anyone please point me to where it is wrong? Many thanks in advance!</p>
| [
{
"answer_id": 74216234,
"author": "flyingfox",
"author_id": 3176419,
"author_profile": "https://Stackoverflow.com/users/3176419",
"pm_score": 2,
"selected": false,
"text": "console.log"
},
{
"answer_id": 74216246,
"author": "Steven Spungin",
"author_id": 5093961,
"au... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10841577/"
] |
74,216,238 | <p>Im trying to convert a time that i have in secconds that is stored on a JSON value, and it gives me error of No matching signature for function TIMESTAMP_SECONDS, or in the query results:</p>
<p>Invalid timestamp: '1646985600'</p>
<p>This is the query:</p>
<pre><code> SELECT DATE(TIMESTAMP_SECONDS(JSON_EXTRACT_SCALAR(JSON_EXTRACT(data , '$.fechaCierre'), '$._seconds'))) AS fechaCierre
FROM db Limit 10
</code></pre>
<p>When Im querying without the DATE(TIMESTAMP_SECONDS()), like this:</p>
<pre><code> SELECT JSON_EXTRACT_SCALAR(JSON_EXTRACT(data , '$.fechaCierre'), '$._seconds') AS fechaCierre
FROM db Limit 10
</code></pre>
<p>Im getting correct the seconds like this: 1646985600</p>
| [
{
"answer_id": 74216464,
"author": "Elha",
"author_id": 5429511,
"author_profile": "https://Stackoverflow.com/users/5429511",
"pm_score": 0,
"selected": false,
"text": "SELECT date(timestamp_seconds(CAST(JSON_EXTRACT_SCALAR(JSON_EXTRACT(data , '$.fechaCierre'), '$._seconds') AS int64))) ... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5429511/"
] |
74,216,240 | <p>I'm trying to scrape the data from the table in the specifications section of this webpage:
<a href="https://www.lochinvar.com/products/commercial-water-heaters/armor-condensing-water-heater/" rel="nofollow noreferrer">Lochinvar Water Heaters</a></p>
<p>I'm using beautiful soup 4. I've tried searching for it by class - for example - (class="Table__Cell-sc-1e0v68l-0 kdksLO") but bs4 can't find the class on the webpage. I listed all the available classes that it could find and it doesn't find anything useful. Any help is appreciated.</p>
<p>Here's the code I tried to get the classes</p>
<pre><code>import requests
from bs4 import BeautifulSoup
URL = "https://www.lochinvar.com/products/commercial-water-heaters/armor-condensing-water-heater"
page = requests.get(URL)
soup = BeautifulSoup(page.content, "html.parser")
results = soup.find_all("div", class_='Table__Wrapper-sc-1e0v68l-3 iFOFNW')
classes = [value
for element in soup.find_all(class_=True)
for value in element["class"]]
classes = sorted(classes)
for cass in classes:
print(cass)
</code></pre>
| [
{
"answer_id": 74216464,
"author": "Elha",
"author_id": 5429511,
"author_profile": "https://Stackoverflow.com/users/5429511",
"pm_score": 0,
"selected": false,
"text": "SELECT date(timestamp_seconds(CAST(JSON_EXTRACT_SCALAR(JSON_EXTRACT(data , '$.fechaCierre'), '$._seconds') AS int64))) ... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7612063/"
] |
74,216,285 | <p>In SQL Server lets say you have a table like this called "Testing":</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Owner</th>
<th>State</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>Pending</td>
</tr>
<tr>
<td>John</td>
<td>Complete</td>
</tr>
<tr>
<td>Sue</td>
<td>Required</td>
</tr>
<tr>
<td>Sue</td>
<td>Required</td>
</tr>
<tr>
<td>Sue</td>
<td>Complete</td>
</tr>
<tr>
<td>Frank</td>
<td>Complete</td>
</tr>
</tbody>
</table>
</div>
<p>I want the pivot data to appear as follows:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Owner</th>
<th>Required</th>
<th>Pending</th>
<th>Complete</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>0</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>Sue</td>
<td>2</td>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td>Frank</td>
<td>0</td>
<td>0</td>
<td>1</td>
</tr>
</tbody>
</table>
</div>
<p>How do you write the SQL statement to produce that? It seems the PIVOT table would come in handy but just not sure how to include that in the statement.</p>
| [
{
"answer_id": 74216308,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 2,
"selected": false,
"text": "SELECT\n Owner,\n COUNT(CASE WHEN Genre = 'Required' THEN 1 END) AS Required,\n COUNT(CASE WHEN Gen... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4179582/"
] |
74,216,305 | <p>I am trying to save a ViewModel object from a partial view in a modal, and I get a 404 error when I try to post it. The url is being called, but the ViewModel data isn't being sent. I have been reading similar questions on here and on MSN for hours and nothing I've tried fixes the problem. I took out the repetitive days of the week code for brevity, but I can
add them back in if anyone wants a complete working example. Here is the code</p>
<p><strong>EmployeeViewModel</strong></p>
<pre><code>public class EmployeeViewModel
{
public bool Monday { get; set; } = false;
//...bool properties for Tuesday through Sunday
public Employee Employee { get; set; }
}
</code></pre>
<p><strong>Employee/ _AddEmployeeModalPartial</strong></p>
<pre><code>@model JSarad_C868_Capstone.ViewModels.EmployeeViewModel
@Html.AntiForgeryToken()
<div class="modal modal-fade" id="addEmployee">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="addEmpoyeeLabel">Add Employee</h4>
<button type=button class="close" data-bs-dismiss="modal">
<span>x</span>
</button>
</div>
<div class="modal-body">
<form action="Add">
<div class="form-group">
<input asp-for="Employee.Id" class="form-control" />
<input asp-for="Employee.Availability" class="form-control" />
<label asp-for="Employee.Role"></label>
<select asp-for="Employee.Role" class="form-control">
<option value="Bartender">Bartender</option>
<option value="Server">Server</option>
</select>
<span asp-validation-for="Employee.Role" class="text-danger"></span>
</div>
@*<div class="mb-3">*@
<div class="form-group">
<label asp-for="Employee.Name"></label>
<input asp-for="Employee.Name" class="form-control" />
<span asp-validation-for="Employee.Name" class="text-danger"></span>
</div>
@* <div class="mb-3">*@
<div class="form-group">
<label asp-for="Employee.Phone"></label>
<input asp-for="Employee.Phone" class="form-control" />
<span asp-validation-for="Employee.Phone" class="text-danger">
</span>
</div>
@*<div class="mb-3">*@
<div class="form-group">
<label asp-for="Employee.Email"></label>
<input asp-for="Employee.Email" class="form-control" />
<span asp-validation-for="Employee.Email" class="text-danger">
</span>
</div>
@*<div class="mb-3">*@
<div class="form-group">
<label asp-for="Employee.Address"></label>
<input asp-for="Employee.Address" class="form-control" />
<span asp-validation-for="Employee.Address" class="text-danger">
</span>
</div>
@* <div class="mb-3">*@
<div class="form-group">
<label>Availabiliy</label>
</div>
<div class="row pb-4">
<div class="col">
<div class="form-check">
<input asp-for="Monday" class="form-check-input"
type="checkbox" />
<label asp-for="Monday" class="form-check-label"></label>
</div>
<!--...//form check boxes for Tuesday trough Sunday -->
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary"
data-bs-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary"
data-bs-save="modal">Save</button>
</div>
</div>
</div>
</div>
</code></pre>
<p><strong>EmployeeController.cs</strong></p>
<pre><code>[HttpGet]
public IActionResult Add()
{
EmployeeViewModel viewModel = new EmployeeViewModel();
return PartialView("_AddEmployeeModalPartial", viewModel); ;
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Add(EmployeeViewModel viewModel) //code never reaches this Action
{
viewModel.Employee.Availability = ConvertDaysToChar(viewModel.Employee.Availability)
if (ModelState.IsValid)
{
_db.Employees.Add(viewModel.Employee);
_db.SaveChanges();
return RedirectToAction("Index");
}
else
{
return PartialView("_AddEmployeeModelPartial", viewModel);
}
}
</code></pre>
<p>site.js</p>
<pre><code>$(function () {
var PlaceHolderElement = $('#PlaceHolderHere');
$('button[data-bs-toggle="ajax-modal"]').click(function (event) {
/* event.preventDefault();*/
var url = $(this).data('url');
console.log(url)
$.get(url).done(function (data) {
PlaceHolderElement.html(data);
PlaceHolderElement.find('.modal').modal('show');
})
})
PlaceHolderElement.on('click', '[data-bs-save="modal"]', function (event) {
event.preventDefault();
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
console.log(actionUrl);
var sendViewModel = form.serialize();
console.log(sendViewModel);
//$.post(actionUrl, sendViewModel).done(function (data) {
// PlaceHolderElement.find('.modal').modal('hide');
/*above is the code from a tutorial for modals. It also doesn't send the object to
post action*/
$.ajax({
type: 'POST',
url: actionUrl,
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(sendViewModel),
success: function (result) {
console.log('Data received: ');
console.log(result);
}
})
})
})
</code></pre>
<p>When I click the save button on the model, the <strong>console.log(sendViewModel)</strong> returns the correct Serialization with all of the properties and their correct names. And the properties change correctly when there is input.</p>
<pre><code>
Employee.Id=&Employee.Availability=&Employee.Role=Bartender&Employee.Name=&Employee.Phone=&Employee.Email=&Employee.Address=&Monday=false&Tuesday=false&Wednesday=false&Thursday=false&Friday=false&Saturday=false&Sunday=false
</code></pre>
<p>But I get an error "Failed to load resource: the server responded with a status of 404 ()"
and when I check it the page says "No webpage was found for the web address: https://localhost:44313/Add HTTP ERROR 404" as if it's trying to get a post. It is also missing the controller, but if I change my form action to "Employee/Add" in the _Partial view it still doesn't send the data along with the url, which is causing an entirely different problem. I would greatly appreciate any help or guess or input of any kind. I'm about five seconds away from throwing my laptop out the window on this one. Thanks.</p>
| [
{
"answer_id": 74217779,
"author": "Qing Guo",
"author_id": 17124525,
"author_profile": "https://Stackoverflow.com/users/17124525",
"pm_score": 2,
"selected": true,
"text": "@Html.AntiForgeryToken()"
}
] | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17195990/"
] |
74,216,307 | <p>I have this array of object:</p>
<pre><code>let obj = [
{ "id_feed": 114, "date_upd": 1666808102 },
{ "id_feed": 115, "date_upd": 1666808102 },
{ "id_feed": 116, "date_upd": 1666808102 },
] ;
</code></pre>
<p>I want to get all the <strong>keys</strong> and <strong>value</strong>. Note: this keys can dynamic, it could be anything.</p>
<p>So to get this I am trying :</p>
<pre><code>Object.keys( obj ).forEach( ( item ) => {
console.log( obj[item] )
})
</code></pre>
<p>But seems like doing wrong :(</p>
<p><strong>Expected Output:</strong></p>
<pre><code>id_feed = 114
date_upd = 1666808102
id_feed = 115
date_upd = 1666808102
id_feed = 116
date_upd = 1666808102
</code></pre>
| [
{
"answer_id": 74216324,
"author": "Amila Senadheera",
"author_id": 8510405,
"author_profile": "https://Stackoverflow.com/users/8510405",
"pm_score": 1,
"selected": false,
"text": "let obj = [ \n { \"id_feed\": 114, \"date_upd\": 1666808102 },\n { \"id_feed\": 115, \"date_upd\": 1... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1091439/"
] |
74,216,309 | <p>I am having elements inside a list from where I want to remove all elements except the certain index values, is there a way?</p>
<pre><code>list = ['Radar', 'completed 2022-10-23T08:18:26', 'PASS: 11FAIL: 0SKIP: 0', '0:14:55', 'completed', '2022-10-23T08:18:26']
indexes = (0, 1, -2, -1) # these are the index values i want to keep in the same list sorted in same indexes format
</code></pre>
<p>expected,</p>
<pre><code>list = ['Radar', 'completed 2022-10-23T08:18:26', 'completed', '2022-10-23T08:18:26']
</code></pre>
| [
{
"answer_id": 74216324,
"author": "Amila Senadheera",
"author_id": 8510405,
"author_profile": "https://Stackoverflow.com/users/8510405",
"pm_score": 1,
"selected": false,
"text": "let obj = [ \n { \"id_feed\": 114, \"date_upd\": 1666808102 },\n { \"id_feed\": 115, \"date_upd\": 1... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8484230/"
] |
74,216,315 | <p>The dataset or say the given dictionary is:</p>
<pre><code># A list of video reviews
# - Each review has the name of the video, the numer of views
# and a list of user reviews.
# - Each user review has the user's name and the review they gave
# to the video.
video_reviews = [
{
"name": "Cats doing nothing",
"number_of_views": 450743,
"reviews": [
{"name": "Jeb", "review": 5},
{"name": "Samantha", "review": 2},
{"name": "Crystal", "review": 3},
]
},
{
"name": "All Fail",
"number_of_views": 1239734,
"reviews": [
{"name": "Crystal", "review": 5},
{"name": "Frank", "review": 3},
{"name": "Jeb", "review": 3},
]
},
{
"name": "Runaway Nintendo",
"number_of_views": 48343,
"reviews": [
{"name": "Samantha", "review": 4},
{"name": "Bill", "review": 3},
{"name": "Sarah", "review": 4},
]
},
]
</code></pre>
<p>heres my problem: I want to define a function and create a user summary - a dictionary - where the keys are the name of the user and the value is a list of the videos that they have reviewed. The result is expected to be like this:</p>
<pre><code>{
"Jeb": ["Cats doing nothing", "All Fail"],
"Samantha": ["Cats doing nothing","Runaway Nintendo"],
"Crystal": ["Cats doing nothing", "All Fail"],
"Frank": ["All Fail"],
"Bill": ["Runaway Nintendo"],
"Sarah": ["Runaway Nintendo"],
}
</code></pre>
<p>Currently, my code is:</p>
<pre><code>def create_user_summary(video_reviews):
summary = {}
for video in video_reviews:
for person in video["reviews"]:
user = person["name"]
video_name = []
if person["name"] == user:
video_name.append(video["name"])
summary[user] = video_name
return summary
</code></pre>
<pre><code>AssertionError:
You returned:
{'Jeb': ['All Fail'], 'Samantha': ['Runaway Nintendo'], 'Crystal': ['All Fail'], 'Frank': ['All Fail'], 'Bill': ['Runaway Nintendo'], 'Sarah': ['Runaway Nintendo']}
instead of:
{'Jeb': ['Cats doing nothing', 'All Fail'], 'Samantha': ['Cats doing nothing', 'Runaway Nintendo'], 'Crystal': ['Cats doing nothing', 'All Fail'], 'Frank': ['All Fail'], 'Bill': ['Runaway Nintendo'], 'Sarah': ['Runaway Nintendo']}
</code></pre>
<p>How do I revise my code and let the output match the expected one?</p>
| [
{
"answer_id": 74216394,
"author": "CryptoFool",
"author_id": 7631480,
"author_profile": "https://Stackoverflow.com/users/7631480",
"pm_score": 1,
"selected": false,
"text": "def create_user_summary(video_reviews):\n summary = {}\n for video in video_reviews:\n for person in... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18743679/"
] |
74,216,334 | <p>I have a date in this format "Wed, 26 Oct 2022 16:11:30 -1100", need to convert it to UTC time and in a format so it can be inserted into a MySQL database.</p>
<p>The date was pulled from an email using "$headerInfo->date;". I don't see any way to receive the date any different.</p>
<p>Every way I try to do the conversion is painful and brute force.</p>
<p>Is there an elegant, or not painful way to do this?</p>
<p>TIA.</p>
<p>Been trying regex but it doesn't handle converting the month into digits, then you have the UTC offset (time zone) to work with.</p>
| [
{
"answer_id": 74216394,
"author": "CryptoFool",
"author_id": 7631480,
"author_profile": "https://Stackoverflow.com/users/7631480",
"pm_score": 1,
"selected": false,
"text": "def create_user_summary(video_reviews):\n summary = {}\n for video in video_reviews:\n for person in... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20344825/"
] |
74,216,383 | <p>Are there any locations where I can see all pod's configuration scheduled on that workernode?</p>
<p>I would like to run some static checks on each worker nodes using Ansible to check if the pod's have been given enough resources (CPU/MEM), I have to explicitly run this job on worker node only and not through kubectl API call.</p>
<p>Thanks!</p>
| [
{
"answer_id": 74216394,
"author": "CryptoFool",
"author_id": 7631480,
"author_profile": "https://Stackoverflow.com/users/7631480",
"pm_score": 1,
"selected": false,
"text": "def create_user_summary(video_reviews):\n summary = {}\n for video in video_reviews:\n for person in... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6760912/"
] |
74,216,387 | <p>I have a dataset that looks something like this:</p>
<pre><code> name status
1 john sick
2 john sick
3 john healthy
4 john sick
5 john healthy
6 alex sick
7 alex sick
8 tim healthy
9 tim healthy
10 tim sick
11 tim sick
</code></pre>
<p>For this dataset, I want to find out the number of times people went from:</p>
<ul>
<li>sick to sick</li>
<li>sick to healthy</li>
<li>healthy to healthy</li>
<li>healthy to sick</li>
</ul>
<p>For example:</p>
<ul>
<li>Sick to Sick: John (sick, sick), Alex (sick, sick), Tim (Sick, Sick) = Occurs in the dataset 3 Times</li>
<li>Sick to Healthy: John (sick, healthy), John (sick, healthy) = Occurs in the dataset 2 Times</li>
<li>Healthy to Healthy: Tim (healthy, healthy) = Occurs in the dataset 1 Time</li>
<li>Healthy to Sick: John (healthy, sick), Tim (healthy, sick) = Occurs in the dataset 2 Times</li>
</ul>
<p>I am not sure how to approach this problem in R - can someone please suggest how to do this?</p>
<p>Thank you!</p>
| [
{
"answer_id": 74216394,
"author": "CryptoFool",
"author_id": 7631480,
"author_profile": "https://Stackoverflow.com/users/7631480",
"pm_score": 1,
"selected": false,
"text": "def create_user_summary(video_reviews):\n summary = {}\n for video in video_reviews:\n for person in... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13203841/"
] |
74,216,407 | <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>// stores books
let myLibrary = [];
// the constructor...
function Book(title, author, pages, read, imageURL) {
this.title = title;
this.author = author;
this.pages = pages;
this.read = read;
this.imageURL = imageURL;
}
//Function to add new books to the array
function addBookToLibrary(title, author, pages, read, imageURL) {
let book = new Book(title, author, pages, read, imageURL);
myLibrary.push(book);
console.log(myLibrary[0]);
displayBooksOnPage();
}
//function to display cards in the array
function displayBooksOnPage() {
const books = document.querySelector(".cards");
//counter used in the content loop
let counter = 0;
//removes previous card before reiteration
//Create the card for each book in array
myLibrary.forEach((myLibrary) => {
const card = document.createElement("div");
card.classList.add("card");
books.append(card);
//Adds all the content into the card
for (let key in myLibrary) {
console.log("a");
if (counter <= 0) {
const titleHeader = document.createElement("h5");
titleHeader.textContent = `${myLibrary[key]}`;
titleHeader.classList.add("card-title");
card.appendChild(titleHeader);
counter = 1;
} else if (counter < 2) {
const cardAuthor = document.createElement("p");
cardAuthor.textContent = `${myLibrary[key]}`;
cardAuthor.classList.add("card-author");
card.appendChild(cardAuthor);
counter = 2;
} else if (counter < 3) {
const cardPages = document.createElement("p");
cardPages.textContent = `${myLibrary[key]}`;
cardPages.classList.add("card-pages");
card.appendChild(cardPages);
counter = 3;
} else if (counter < 4) {
const readContainer = document.createElement("div");
readContainer.classList.add("read");
card.appendChild(readContainer);
const readElement = document.createElement("p");
readElement.textContent = `${myLibrary[key]}`;
readElement.classList.add("card-read");
readContainer.append(readElement);
counter = 4;
} else if (counter < 5) {
const imageContainer = document.createElement("div");
imageContainer.classList.add("book-image-container");
card.appendChild(imageContainer);
const bookImage = document.createElement("img");
bookImage.src = `${myLibrary[key]}`;
bookImage.classList.add("book-image");
imageContainer.append(bookImage);
const editContainer = document.createElement("div");
editContainer.classList.add("edit-container");
card.appendChild(editContainer);
const editBtn = document.createElement("button");
editBtn.innerText = "Edit";
editBtn.classList.add("edit");
editContainer.append(editBtn);
const deleteContainer = document.createElement("div");
deleteContainer.classList.add("delete-container");
card.appendChild(deleteContainer);
const deleteBtn = document.createElement("button");
deleteBtn.innerText = "Delete";
deleteBtn.classList.add("delete");
deleteContainer.append(deleteBtn);
}
}
function resetCounter() {
counter = 0;
}
resetCounter();
});
}
//New book button
const newBookBtn = document.getElementById("newBookBtn");
newBookBtn.addEventListener("click", displayForm);
//Displays the new book form
function displayForm() {
document.getElementById("formContainer").style.display = "";
}
//eventlistener on form to submit data
const submitBtn = document.querySelector(".submit-button");
submitBtn.addEventListener("click", intakeFormData);
//transform form data to variables
function intakeFormData() {
let title = document.getElementById("Title").value;
let author = document.getElementById("Author").value;
let pages = document.getElementById("Pages").value;
let read = document.getElementById("Read").value;
let imageURL = document.getElementById("imageURL").value;
addBookToLibrary(title, author, pages, read, imageURL);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script type="text/javascript" src="script.js" defer></script>
<link rel="stylesheet" href="styles.css" />
<link rel="stylesheet" href="resetcss.css" />
<title>Sign-Up Form</title>
</head>
<body id="body">
<div class="sideBar">
<div class="menuItem">
<img class="white dashIcon" src="./images/view-dashboard-variant-outline.png" alt="" />
<h1>Dashboard</h1>
</div>
<div class="menuItem">
<img class="white" src="./images/home.png" alt="" />
<h1>Home</h1>
</div>
<div class="menuItem">
<img class="white" src="./images/account.png" alt="" />
<h1>Profile</h1>
</div>
<div class="menuItem">
<img class="white" src="./images/message.png" alt="" />
<h1>Messages</h1>
</div>
<div class="menuItem">
<img class="white" src="./images/clock.png" alt="" />
<h1>History</h1>
</div>
<div class="menuItem">
<img class="white" src="./images/note-multiple.png" alt="" />
<h1>Tasks</h1>
</div>
<div class="menuItem">
<img class="white" src="./images/account-group.png" alt="" />
<h1>Communities</h1>
</div>
<!--Needs extra spacing-->
<div class="menuItem">
<img class="white" src="./images/cog.png" alt="" />
<h1>Settings</h1>
</div>
<div class="menuItem">
<img class="white" src="./images/help-circle.png" alt="" />
<h1>Support</h1>
</div>
<div class="menuItem">
<img class="white" src="./images/shield-check-outline.png" alt="" />
<h1>Privacy</h1>
</div>
</div>
<div class="header">
<!--Top section-->
<div class="topHeader">
<div class="search">
<div class="menuItem">
<img src="./images/magnify.png" alt="" />
</div>
<input type="text" name="search" />
</div>
<div class="account">
<div class="menuIcon">
<img src="./images/bell.png" alt="" />
</div>
<img class="avatar" src="./images/avatar.jpg" alt="" />
<p class="name">Benjamin Gill</p>
</div>
</div>
<!--Bottom section-->
<div class="bottomHeader">
<div class="profile">
<img class="avatar" src="./images/avatar.jpg" alt="" />
<div class="profile-name">
<p class="greeting">Hi there,</p>
<p class="name">
Benjamin Gill <span class="username">(@Bgill)</span>
</p>
</div>
</div>
<div class="buttons">
<button id="newBookBtn" class="btn">New Book</button>
</div>
</div>
</div>
<div class="content">
<div class="projects">
<h3>Your Books:</h3>
<div class="cards">
<div class="card">
<h5 class="card-title">The Hobbit</h5>
<p class="card-author">by: J.R.R. Tolken</p>
<p class="card-pages">345 pages</p>
<div class="read">
<p class="card-read">Not yet read</p>
</div>
<div class="book-image-container">
<img src="https://upload.wikimedia.org/wikipedia/en/thumb/a/a9/The_Hobbit_trilogy_dvd_cover.jpg/220px-The_Hobbit_trilogy_dvd_cover.jpg" alt="" class="book-image" />
</div>
<div class="edit-container">
<button class="edit">Edit</button>
</div>
<div class="delete-container">
<button class="delete">Delete</button>
</div>
</div>
<div id="formContainer" class="cards" style="display: none">
<form id="newBookForm" class="card">
<input type="text" name="Title" id="Title" class="card-title" placeholder="Book Title..." />
<input type="text" name="Author" id="Author" placeholder="Author Name..." class="card-author" />
<input type="number" name="Pages" id="Pages" placeholder="Amount of Pages..." class="card-pages" />
<input type="text" name="Read" id="Read" placeholder="Have you read this?" class="read" />
<input type="text" name="imageURL" id="imageURL" placeholder="Enter image URL..." class="book-image-container" />
<div class="edit-container">
<button type="reset" class="reset-button edit">
Reset Form
</button>
</div>
<div class="delete-container">
<button type="submit" class="submit-button delete">
Sumbit to Library
</button>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
<p>My main issue is in Javascript. It takes the intakeFormData and then goes through the add newBookToLibrary. Once there it runs the displayBooksOnPage and creates the new card by adding elements to the dom. Once all the elements are added, it finishes at the intakeFormData and then calls the myLibrary. Once it calls the myLibrary it just removes all the newly added elements.</p>
<p>I've looked at chrome dev tools and followed it through. It completed everything correctly. But once it is towards the end it calls the first two variables as when the page loads and it clears everything that was added.</p>
| [
{
"answer_id": 74216394,
"author": "CryptoFool",
"author_id": 7631480,
"author_profile": "https://Stackoverflow.com/users/7631480",
"pm_score": 1,
"selected": false,
"text": "def create_user_summary(video_reviews):\n summary = {}\n for video in video_reviews:\n for person in... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19841495/"
] |
74,216,413 | <p>I want to delete conditional access policy from Microsoft Graph Powershell.</p>
<p>I found this to do from Graph api</p>
<blockquote>
<p>DELETE
<a href="https://graph.microsoft.com/v1.0/identity/conditionalAccess/policies/%7Bid%7D" rel="nofollow noreferrer">https://graph.microsoft.com/v1.0/identity/conditionalAccess/policies/{id}</a></p>
</blockquote>
<p>But how to find the command for this in Microsoft Graph Powershell.</p>
<p>PS: I connected to Graph from Powershell with <code>Connect-MgGraph</code></p>
<p>TIA</p>
| [
{
"answer_id": 74217088,
"author": "VenkateshDodda-MSFT",
"author_id": 15968720,
"author_profile": "https://Stackoverflow.com/users/15968720",
"pm_score": 0,
"selected": false,
"text": "Remove-MgIdentityConditionalAccessPolicy"
},
{
"answer_id": 74217127,
"author": "Venkatesa... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20236016/"
] |
74,216,418 | <p>I use UIMenuController when presenting my custom menu for the selected text on my WKWebview. But it is now deprecated on iOS 16, and get the following error</p>
<pre><code>[Text] Using UIMenuController to add items into text menus is deprecated. Please implement the UITextInput API editMenuForTextRange:suggestedActions: instead.
[EditMenuInteraction] The edit menu ... did not have performable commands and/or actions; ignoring present.
</code></pre>
<p>And now I cant find any documentation on how to customize the menu on wkwebview.</p>
<p>This is what I am trying to present on the menu.</p>
<p><a href="https://i.stack.imgur.com/BTPZz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BTPZz.png" alt="enter image description here" /></a></p>
<p>How can you customize the menu on the selected text on wkwebview?</p>
<p>I tried adding UITextInput, but it requires to conform to a bunch of protocols.</p>
| [
{
"answer_id": 74217088,
"author": "VenkateshDodda-MSFT",
"author_id": 15968720,
"author_profile": "https://Stackoverflow.com/users/15968720",
"pm_score": 0,
"selected": false,
"text": "Remove-MgIdentityConditionalAccessPolicy"
},
{
"answer_id": 74217127,
"author": "Venkatesa... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5051164/"
] |
74,216,432 | <p>I have 2 files that I needed to grep in a separate file.</p>
<p>The two files are in this directory /var/list</p>
<pre><code>TB.1234.txt
TB.135325.txt
</code></pre>
<p>I have to grep them in another file in another directory which is in <code>/var/sup/</code>. I used the command below:</p>
<pre><code>for i in TB.*; do grep "$i" /var/sup/logs.txt; done
</code></pre>
<p>what I want to do is, if the result of the grep command contains the word "ERROR" the files which is found in /var/list will be moved to another directory <code>/var/last</code>.</p>
<p>for example I grep this file TB.1234.txt to /var/sup/logs.txt then the result is like this:</p>
<p><strong>ERROR: TB.1234.txt</strong></p>
<p>TB.1234.txt will be move to /var/last.</p>
<p>please help. I don't know how to construct the logic on how to move the files, I'm stuck in that I provided, I am also trying to use two greps in a for loop but I am encountering an error.</p>
<p>I am new in coding and really appreciates any help and suggestions. Thank you so much.</p>
| [
{
"answer_id": 74218559,
"author": "Dominique",
"author_id": 4279155,
"author_profile": "https://Stackoverflow.com/users/4279155",
"pm_score": 0,
"selected": false,
"text": "grep"
},
{
"answer_id": 74218679,
"author": "tripleee",
"author_id": 874188,
"author_profile":... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20249814/"
] |
74,216,446 | <p>Hello Experts is there any way to remove existing p tags inside the class? if it is more than 1 using JavaScript.</p>
<p>Example:</p>
<pre><code> <div class='classname'>
<p>Lorem ip purus hendrerit quam. Mauris convallis dolor vel ex placerat, non imperdiet dolor lacinia. </p>
<p>Lorem ipsum m ip purus hendrerit quam. Mauris convallis dolor v </p>
<p>Lorem ipsum m ip purus hendrerit quam. Mauris convallis dolor v </p>
<p>Lorem ipsum m ip purus hendrerit quam. Mauris convallis dolor v </p>
</div>`
</code></pre>
<p>Expected Result:</p>
<pre><code><div class='classname'>
<p>Lorem ip purus hendrerit quam. Mauris convallis dolor vel ex placerat, non imperdiet dolor lacinia. </p>
</code></pre>
| [
{
"answer_id": 74218559,
"author": "Dominique",
"author_id": 4279155,
"author_profile": "https://Stackoverflow.com/users/4279155",
"pm_score": 0,
"selected": false,
"text": "grep"
},
{
"answer_id": 74218679,
"author": "tripleee",
"author_id": 874188,
"author_profile":... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20344781/"
] |
74,216,452 | <p>(Java). Currently trying to reach a 'next' button that is located at the bottom of the page, the JavaScript script "executeScript("arguments[0].scrollIntoView(true);" properly takes me to the element but I want to reach it gradually. For example, scroll 500 pixels at a time until the element is scrolled into view.</p>
<p>I have tried getting the y location of the element and then using the scrollTo element inside a loop to reach every 1% of the y value but I face some issues with the pixels so this approach doesn't work.
This is something I have so far that takes me to the element, but it does it instantly</p>
<pre><code>WebElement next = driver.findElement(By.xpath("..."));
jas.executeScript("arguments[0].scrollIntoView(true);", next)
</code></pre>
| [
{
"answer_id": 74218559,
"author": "Dominique",
"author_id": 4279155,
"author_profile": "https://Stackoverflow.com/users/4279155",
"pm_score": 0,
"selected": false,
"text": "grep"
},
{
"answer_id": 74218679,
"author": "tripleee",
"author_id": 874188,
"author_profile":... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12606141/"
] |
74,216,466 | <p><a href="https://i.stack.imgur.com/j4vtl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/j4vtl.png" alt="Layout Target" /></a></p>
<p>How can I achieve something like this in Flutter? Is it possible in</p>
<p>I have tried these codes and it gave me an error which said no DefaultTabController. I was confused where I should put it in. Example in internet wrote I have to put it in Scaffold body. But my code required some widgets to display image using Stack before using TabBar.</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>import 'package:felix_idn/library/widget/components/enums.dart';
import 'package:felix_idn/library/widget/components/path.dart';
import 'package:felix_idn/library/widget/ui/button.dart';
import 'package:felix_idn/library/widget/ui/text.dart';
import 'package:felix_idn/menu/music/music_therapy.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
class MusicAmbient extends StatelessWidget {
const MusicAmbient({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
bottom: const TabBar(
tabs: [
Tab(icon: Icon(Icons.directions_car)),
Tab(icon: Icon(Icons.directions_transit)),
],
),
title: Text('Flutter Tabs Example'),
),
body: Container(
color: Colors.black,
child: SafeArea(
child: Container(
color: const Color.fromARGB(115, 55, 55, 55),
child: Stack(
children: [
//Icon back
Align(
alignment: Alignment.topLeft,
child: IconButton(
icon: const Icon(Icons.arrow_back_sharp),
iconSize: 32.0,
constraints: const BoxConstraints(),
padding: const EdgeInsets.all(3.0),
onPressed: () => Get.off(() => const MusicTherapy()),
color: Colors.white,
),
),
//Piano Background & Tabs
Align(
alignment: Alignment.topCenter,
child: Column(
children: [
const SizedBox(height: 40.0),
ImageButton(path: bgamb, callback: () => Get.back(), type: IconType.NONE),
const TabBarView(
children: [
MusicTherapy(),
MusicTherapy(),
],
),
],
),
),
//Title
Align(
alignment: Alignment.topCenter,
child: Column(
children: const [
SizedBox(height: 6.0),
Titles("Ambient", color: Colors.white, size: 20.0),
],
),
),
],
),
),
),
),
);
}
}</code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74222432,
"author": "Yeasin Sheikh",
"author_id": 10157127,
"author_profile": "https://Stackoverflow.com/users/10157127",
"pm_score": 2,
"selected": true,
"text": "TabController"
}
] | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13890662/"
] |
74,216,472 | <p>I have learned the definitions of functor and monad, But I am still unable to figure out the difference between them except for the definitions. I have read some answers to this problem, In <a href="https://stackoverflow.com/q/45252709/15315834">What is the difference between a Functor and a Monad?</a> one comment say</p>
<blockquote>
<p>A functor takes a pure function (and a functorial value) whereas a monad takes a Kleisli arrow, i.e. a function that returns a monad (and a monadic value). Hence you can chain two monads and the second monad can depend on the result of the previous one. You cannot do this with functors.</p>
</blockquote>
<p>This comment is interesting and gives me a read of their difference. But I still have some questions.</p>
<ol>
<li>why functor cannot use the result of previous one? since <code>fmap :: (a -> b) -> f a -> f b</code>, when I currying <code>fmap</code> with a pure function, I can get a <code>f a -> f b</code> function,<code>f b</code> depends on <code>f a</code>, Does the <strong>result</strong> mean data inside the functor?</li>
<li>In category theory I can understand the comment since I cannot get the element in category theory, but In Haskell I find out that I can use the <strong>result</strong> of functor since Haskell can remember the data constructor, Does Haskell prevent me from understanding this comment? Should I understand this in pure category theory?</li>
</ol>
| [
{
"answer_id": 74216875,
"author": "Ben",
"author_id": 450128,
"author_profile": "https://Stackoverflow.com/users/450128",
"pm_score": 4,
"selected": true,
"text": "fmap :: Functor f => (a -> b) -> f a -> f b"
},
{
"answer_id": 74222908,
"author": "chepner",
"author_id": ... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216472",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15315834/"
] |
74,216,565 | <p>I want to create a macro that adds a prefix to the argument and calls it as a function. Something like this:</p>
<pre><code>#define FUNC(name) /* some code */
FUNC(add) // => __some_function_name_prefix__add()
FUNC(subtract) // => __some_function_name_prefix__subtract()
FUNC(multiply) // => __some_function_name_prefix__multiply()
FUNC(divide) // => __some_function_name_prefix__divide()
</code></pre>
<p>This is what I have tried:</p>
<pre><code>#define FUNC(name) __some_function_name_prefix__name()
FUNC(add) // => __some_function_name_prefix__name()
FUNC(subtract) // => __some_function_name_prefix__name()
FUNC(multiply) // => __some_function_name_prefix__name()
FUNC(divide) // => __some_function_name_prefix__name()
</code></pre>
<p>But, he problem is that it will always expand to <code>__some_function_name_prefix__name()</code> and won't use the argument. How can I fix this?</p>
| [
{
"answer_id": 74216619,
"author": "robthebloke",
"author_id": 8185995,
"author_profile": "https://Stackoverflow.com/users/8185995",
"pm_score": 2,
"selected": false,
"text": "#define FUNC(name) __some_function_name_prefix__##name()\n"
}
] | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13376511/"
] |
74,216,578 | <p>I am trying to do a lookup from multiple references</p>
<p>Here is a <a href="https://mongoplayground.net/p/dTT0W3Xyd_Y" rel="nofollow noreferrer">Mongo Playground</a></p>
<p>Here is my data</p>
<p><strong>Insp</strong></p>
<p>The <strong>Insp</strong> document contains an array of references to Users (by user ID)</p>
<pre><code>[
{
"_id": {
"$oid": "6359a12fb9450da3d8d8cdd2"
},
"REF_Users": [
{
"$oid": "6359a0f1b9450da3d8d8cdc7"
},
{
"$oid": "6359a070f1e84209e0c78fc2"
}
],
"name": "Once"
}
]
</code></pre>
<p><strong>Users</strong></p>
<p>The <strong>Users</strong> document contains information about a user and it has a reference to the UserType (by userType ID)</p>
<pre><code>[
{
"_id": {
"$oid": "6359a070f1e84209e0c78fc2"
},
"REF_UserType": {
"$oid": "63596323b679475de490500a"
},
"fName": "Billy"
},
{
"_id": {
"$oid": "6359a0f1b9450da3d8d8cdc7"
},
"REF_UserType": {
"$oid": "63596323b679475de4905007"
},
"fName": "Mike"
}
]
</code></pre>
<p><strong>UserType</strong></p>
<p>The <strong>UserType</strong> document holds type information</p>
<pre><code>[
{
"_id": {
"$oid": "63596323b679475de4905007"
},
"value": 100,
"name": "INS"
},
{
"_id": {
"$oid": "63596323b679475de490500a"
},
"value": 200,
"name": "CLS"
}
]
</code></pre>
<p><strong>Expected output</strong></p>
<p>I want the <code>userType</code> for each user to be with the respective user</p>
<pre><code>{
"_id": "6359a12fb9450da3d8d8cdd2",
"people": [
{
"_id": "6359a070f1e84209e0c78fc2",
"userType": {
"_id": "63596323b679475de490500a",
"value": 200,
"name": "CLS"
},
"fName": "Billy"
},
{
"_id": "6359a0f1b9450da3d8d8cdc7",
"userType": {
"_id": "63596323b679475de4905007",
"value": 100,
"name": "INS"
},
"fName": "Mike"
}
]
}
</code></pre>
<p><strong>TRY 1</strong></p>
<p>This is my pipeline so far</p>
<pre><code>[
{
"$match": {}
},
{
"$lookup": {
"from": "users",
"localField": "REF_Users",
"foreignField": "_id",
"as": "people"
}
},
{
"$lookup": {
"from": "usertypes",
"localField": "people.REF_UserType",
"foreignField": "_id",
"as": "userType"
}
},
{
"$project": {
"REF_Users": 0,
"people.REF_UserType": 0
}
}
]
</code></pre>
<p><strong>Result of TRY 1</strong></p>
<pre><code>{
"_id": "6359a12fb9450da3d8d8cdd2",
"people": [
{
"_id": "6359a070f1e84209e0c78fc2",
"fName": "Billy"
},
{
"_id": "6359a0f1b9450da3d8d8cdc7",
"fName": "Mike"
}
],
"userType": [
{
"_id": "63596323b679475de4905007",
"value": 100,
"name": "INS"
},
{
"_id": "63596323b679475de490500a",
"value": 200,
"name": "CLS"
}
]
}
</code></pre>
<p>It works in Compass...</p>
<p><a href="https://i.stack.imgur.com/OIN5W.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OIN5W.png" alt="enter image description here" /></a></p>
<p>It works in the playground</p>
<p><a href="https://i.stack.imgur.com/XETzY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XETzY.png" alt="enter image description here" /></a></p>
<p>When I put the code into NodeJS and run it from my server:</p>
<p><strong>TRY 2</strong></p>
<pre><code> const agg_project_try = {
people: {
$map: {
input: '$people',
as: 'people',
in: {
$mergeObjects: [
'$$people',
{
userType: {
$first: {
$filter: {
input: '$userType',
cond: {
$eq: ['$$people.REF_UserType', '$$this._id'],
},
},
},
},
},
],
},
},
},
};
</code></pre>
<p>I get this error</p>
<pre><code>Arguments must be aggregate pipeline operators
</code></pre>
<p><strong>TRY 3</strong></p>
<p>I exported from Compass as NODE</p>
<pre><code>[
{
'$lookup': {
'from': 'users',
'localField': 'REF_Users',
'foreignField': '_id',
'as': 'people'
}
}, {
'$lookup': {
'from': 'usertypes',
'localField': 'people.REF_UserType',
'foreignField': '_id',
'as': 'userType'
}
}, {
'$project': {
'people': {
'$map': {
'input': '$people',
'as': 'people',
'in': {
'$mergeObjects': [
'$$people', {
'userType': {
'$first': {
'$filter': {
'input': '$userType',
'cond': {
'$eq': [
'$$people.REF_UserType', '$$this._id'
]
}
}
}
}
}
]
}
}
}
}
}, {
'$unset': 'people.REF_UserType'
}
]
</code></pre>
<p>Then tried the 'project' portion in my server</p>
<pre><code> const agg_project_try = {
'people': {
'$map': {
'input': '$people',
'as': 'people',
'in': {
'$mergeObjects': [
'$$people', {
'userType': {
'$first': {
'$filter': {
'input': '$userType',
'cond': {
'$eq': [
'$$people.REF_UserType', '$$this._id'
]
}
}
}
}
}
]
}
}
}
};
</code></pre>
<p>I get this error</p>
<pre><code>Arguments must be aggregate pipeline operators
</code></pre>
<p>Here is my node JS pipeline ( <em>that causes the error</em> )</p>
<pre><code>[
{ "$match": {} },
{ "$lookup": { "from": "users", "localField": "REF_Users", "foreignField": "_id", "as": "people" } },
{ "$lookup": { "from": "usertypes", "localField": "people.REF_UserType", "foreignField": "_id", "as": "userType" } },
{
"people": {
"$map": {
"input": "$people",
"as": "people",
"in": {
"$mergeObjects": [
"$$people",
{
"userType": {
"$first": {
"$filter": { "input": "$userType", "cond": { "$eq": ["$$people.REF_UserType", "$$this._id"] } }
}
}
}
]
}
}
}
},
{ "$project": { "REF_Users": 0 } }
]
</code></pre>
<p><strong>ANSWER</strong></p>
<p>Up too late last night working on this stuff, actually need the "project" statement to do a projection - doh !</p>
<pre><code> $project:{
'people': {
$map: {
input: '$peopleLookup',
as: 'tempPeople',
in: {
$mergeObjects: [
'$$tempPeople',
{
'userType': {
$first: {
$filter: {
input: '$userTypeLookup',
cond: {
$eq: ['$$tempPeople.REF_UserType', '$$this._id'],
},
},
},
},
},
],
},
},
},
}
</code></pre>
<p>Thank you!</p>
| [
{
"answer_id": 74217844,
"author": "Yong Shun",
"author_id": 8017690,
"author_profile": "https://Stackoverflow.com/users/8017690",
"pm_score": 3,
"selected": true,
"text": "$project"
},
{
"answer_id": 74219092,
"author": "Naveen",
"author_id": 20306839,
"author_profil... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3174075/"
] |
74,216,584 | <p>when I try to create a local WordPress development environment using docker, it throws an error</p>
<blockquote>
<p>(root) Additional property MySQL is not allowed</p>
</blockquote>
<p>Docker compose file</p>
<pre><code>web:
image: wordpress
links:
- mysql
environment:
- WORDPRESS_DB_PASSWORD=password
ports:
- "127.0.0.3:8080:80"
mysql:
image: mysql:5.7
environment:
- MYSQL_ROOT_PASSWORD=password
- MYSQL_DATABASE=my-wpdb
</code></pre>
<p>command i used : Docker compose up -d</p>
| [
{
"answer_id": 74216672,
"author": "ioeshu",
"author_id": 15406658,
"author_profile": "https://Stackoverflow.com/users/15406658",
"pm_score": 0,
"selected": false,
"text": " services:\n db:\n # We use a mariadb image which supports both amd64 & arm64 architecture\n image: maria... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15406658/"
] |
74,216,587 | <p>I have a list containing 640 items (all floats). I have a list of tuples (two items in the tuple) containing 640 items. Both lists are ordered and line up with each other. I want to take the two items from the tuple and put them at the top of their corresponding list of floats. For example, both of these are at index[0] of their corresponding lists.</p>
<pre><code>[[37.0,
40.1,
'27.2',
'58.3',
'.467',
'20.9',
'40.2',
'.519',
'6.3',
'18.1',
'.349',
'13.4',
'19.2',
'.698',
'12.4',
'19.5',
'31.9',
'15.2',
'9.1',
'6.9',
'10.5',
'15.5',
'74.1']
</code></pre>
<pre><code> ('syracuse', 2012)
</code></pre>
<p>I want it to be one list ['syracuse', 2012, 37.0, 40.1, 27.2, etc] and do that to all 640 items.</p>
<p>Here's what I've tried so far.</p>
<pre><code>empty_list = []
team_year = [list(x) for x in team_year]
for i,v in enumerate (cbb_team_sites):
y = pd.read_html(v)[1]
y = list((y.loc[0].T)[1:]) --> this is what produces the list of floats
empty_list.append(y)
combined = list(zip(team_year,empty_list))
</code></pre>
<p>I've also tried:</p>
<p>`</p>
<pre><code>for x in cbb_team_sites:
y = pd.read_html(x)[1]
y = list((y.iloc[0]).T)[1:]
team_stats_list.append(y)
for x in (range(640)):
team_stats_list.append(team_year[x])
</code></pre>
<p>`</p>
<p>I'm sure there's an easy way to do this and I'm just missing it. But after about 4+ hours of trying, I figure it's time to ask for help.</p>
<p>Thank you</p>
| [
{
"answer_id": 74216672,
"author": "ioeshu",
"author_id": 15406658,
"author_profile": "https://Stackoverflow.com/users/15406658",
"pm_score": 0,
"selected": false,
"text": " services:\n db:\n # We use a mariadb image which supports both amd64 & arm64 architecture\n image: maria... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17825177/"
] |
74,216,594 | <p>I am trying to extract words where vowel sign is used consecutively twice (or more than 2 times) next to each other.</p>
<pre><code>texts = ['ane', 'mood', 'xao', 'pqr', 'aa']
signs = ['a', 'e', 'i', 'o', 'u']
for i in texts:
for x in i:
if x in signs:
print ("double vowel sign exists in", i)
</code></pre>
<p>This will print:</p>
<pre><code>double vowel sign exists in ane
double vowel sign exists in ane
double vowel sign exists in mood
double vowel sign exists in mood
double vowel sign exists in xao
double vowel sign exists in xao
double vowel sign exists in aa
double vowel sign exists in aa
</code></pre>
<p>The expected output is:</p>
<pre><code>double vowel sign exists in mood
double vowel sign exists in mood
double vowel sign exists in xao
double vowel sign exists in xao
double vowel sign exists in aa
double vowel sign exists in aa
</code></pre>
<p>(better if not repeated)</p>
| [
{
"answer_id": 74216703,
"author": "Raibek",
"author_id": 11040577,
"author_profile": "https://Stackoverflow.com/users/11040577",
"pm_score": 0,
"selected": false,
"text": "import re \npattern = \".*[\" + ''.join(signs) + \"]{2,}\"\nfor _text in texts:\n if re.search(patte... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/139150/"
] |
74,216,620 | <p>I'm having a larger foreach loop code but need to get below code executed without casesensitive.</p>
<p>Below code snippet returns false, how can I ignore the casesensitive .contains() and the condition as true?</p>
<pre><code>$a='aa0855'
$b='AA0855 Sample'
$b.Contains($a)
</code></pre>
<p>Expected value is true. Above code is tried with 2 variables and it returns false.</p>
| [
{
"answer_id": 74216683,
"author": "mklement0",
"author_id": 45375,
"author_profile": "https://Stackoverflow.com/users/45375",
"pm_score": 3,
"selected": true,
"text": ".Contains()"
},
{
"answer_id": 74224205,
"author": "js2010",
"author_id": 6654942,
"author_profile"... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20211962/"
] |
74,216,632 | <blockquote>
<p>the result i want to achieve</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/eE0mQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eE0mQ.png" alt="enter image description here" /></a></p>
<p>how can i make a progress indicator using flutter?</p>
<p>I've tried using Flutter's built-in progress indicator but it's not what I want</p>
<p><a href="https://api.flutter.dev/flutter/material/CircularProgressIndicator-class.html" rel="nofollow noreferrer">https://api.flutter.dev/flutter/material/CircularProgressIndicator-class.html</a></p>
<p>I've used it before, something went wrong. when I move pages (from home to settings) and back again to the home page. home page doesn't reload when I delete ProgressIndicator home page works fine</p>
| [
{
"answer_id": 74216683,
"author": "mklement0",
"author_id": 45375,
"author_profile": "https://Stackoverflow.com/users/45375",
"pm_score": 3,
"selected": true,
"text": ".Contains()"
},
{
"answer_id": 74224205,
"author": "js2010",
"author_id": 6654942,
"author_profile"... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19646043/"
] |
74,216,662 | <p>I installed Electron's template following <a href="https://www.electronforge.io/templates/typescript-+-webpack-template" rel="noreferrer">Electron Forge page</a>.</p>
<pre><code>npx create-electron-app my-new-app --template=typescript-webpack
</code></pre>
<p>After that, I run</p>
<pre><code>npm run start
</code></pre>
<p>insides <code>my-new-app</code> folder and the following error message were popped up in command window</p>
<pre><code>$ npm run start
> my-new-app@1.0.0 start
> electron-forge start
✔ Checking your system
✔ Locating Application
An unhandled rejection has occurred inside Forge:
Error: Expected plugin to either be a plugin instance or a { name, config } object but found @electron-forge/plugin-webpack,[object Object]
Electron Forge was terminated. Location:
{}
</code></pre>
<p>I Google it, but no one encoutered same error.
I could use above template without error message before a week ago. So, I copy the project that were made a week ago and run. It was success. However, I run the following command</p>
<pre><code>npm audit
</code></pre>
<p>There are 22 vulnerabilities (3 moderate, 19 high).
Errors are</p>
<pre><code>got <11.8.5
Severity: moderate
</code></pre>
<p>and</p>
<pre><code>minimatch <3.0.5
Severity: high
</code></pre>
<p>It could not fix by <code>npm audit fix</code> and <code>npm audit fix --force</code>. So, I fixed this error by rewriting <code>package.json</code> and <code>package-lock.json</code>. Then I deleate <code>node_modules</code> folder and run <code>npm install</code>.
These vulnerabilities are gone, but above my problem were again after I run <code>npm run start</code>.</p>
<p>I think problem is involved in <code>@electron-forge/plugin-webpack</code>.
However, I dont know how to fix it.</p>
<p>Thanks in advance.</p>
| [
{
"answer_id": 74222266,
"author": "Vinicius Bazanella",
"author_id": 10930717,
"author_profile": "https://Stackoverflow.com/users/10930717",
"pm_score": 4,
"selected": true,
"text": "config.forge"
},
{
"answer_id": 74248904,
"author": "Shanavas P S",
"author_id": 6727767... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20344837/"
] |
74,216,695 | <p>I need to ask the user for a number of dice to roll, (at least 1) and then loop if necessary to return a positive integer. Simple question, but I'm new to Java and don't understand how to do this using a while loop and bringing my variable back into scope.</p>
<p>Here's what I have so far, as anyone can see my variable 'numOfDice' is never pulled back into scope, as I need it later in my program to establish a variable array length.</p>
<pre><code>while (true) {
System.out.println("Hello! How many dice would you like to roll");
int numOfDice = scan.nextInt();
if (numOfDice<=0) {
System.out.println("Please enter a positive integer and try again");
}else {
break;
}
}
</code></pre>
<p>So as you can see my variable is never pulled back into scope, and I've tried initializing it before the while loop, with no luck. I've also tried</p>
<pre><code>
System.out.println("Hello! How many dice would you like to roll");
int numOfDice = scan.nextInt();
while (true) {
if (numOfDice<=0) {
System.out.println("Please enter a positive integer and try again");
}else {
break;
}
}
</code></pre>
<p>But this results in an infinite loop if a negative number is an input, as my if will repeat forever.
Anyways, I'm very new to Java (my 6th week learning) and any veteran help would be much appreciated. I'm willing to learn new ways to create these loops or tricks to pull variables back into scope (if possible).</p>
<p>Solved. Thanks to tgdavies telling me to split the declaration and assignment I was able to finish this problem. Here's the solution for anyone who stumbles upon this.</p>
<pre><code> System.out.println("Hello! How many dice would you like to roll");
int numOfDice;
numOfDice = scan.nextInt();
while (true) {
if (numOfDice <= 0) {
System.out.println("Please enter a positive integer and try again");
numOfDice = scan.nextInt();
} else {
break;
}
}
</code></pre>
| [
{
"answer_id": 74222266,
"author": "Vinicius Bazanella",
"author_id": 10930717,
"author_profile": "https://Stackoverflow.com/users/10930717",
"pm_score": 4,
"selected": true,
"text": "config.forge"
},
{
"answer_id": 74248904,
"author": "Shanavas P S",
"author_id": 6727767... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20345087/"
] |
74,216,747 | <p>How do I add my 3 reducers item in persistedReducers? So basically I follow this guide but I don't know what kind of <code>rootReducers</code> is talking about here in the <a href="https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data" rel="nofollow noreferrer">LINK</a>.. I am working with non-serializable-data but I really don't much care what it means I just want to ignore it because I have a non-serializable data...since persistReducer can ignore it so I use it but I don't know how to add 3 reducers..here is the code</p>
<pre><code>...
import {
persistStore,
persistReducer,
FLUSH,
REHYDRATE,
PAUSE,
PERSIST,
PURGE,
REGISTER,
} from 'redux-persist'
import storage from 'redux-persist/lib/storage'
import { PersistGate } from 'redux-persist/integration/react'
const persistConfig = {
key: 'root',
version: 1,
storage,
}
const persistedReducer = persistReducer(persistConfig,accountSlice,createItems,oderCardData)
// import ordersData
const store = configureStore({
reducer:persistedReducer,
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware({
serializableCheck: {
ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
},
}),
})
let persistor = persistStore(store)
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.Fragment>
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<App />
</PersistGate>
</Provider>
</React.Fragment>
);
</code></pre>
<p>As you see in the line <code>const persistedReducer = persistReducer(persistConfig,accountSlice,createItems,oderCardData) </code>
I am imagining something like this also since It has certain data name like this</p>
<pre><code>const persistedReducer = persistReducer(persistConfig,{
account: accountSlice,
itemData: createItems,
ordersData: oderCardData
})
</code></pre>
<p>but it is not working out..without persistReducer I can do the reducer simple as this</p>
<pre><code>const store = configureStore({
reducer: {
{
account: accountSlice,
itemData: createItems,
ordersData: oderCardData
}
}
})
</code></pre>
<p>and it is working but the thing is I want to ignore the non-serializable error in my console can anyone help me with this?</p>
<p><strong>UPDATE</strong>
Based in answer of below I have now this</p>
<pre><code>const persistConfig = {
key: 'root',
storage,
}
const itemsPersistConfig = {
key:'items',
storage:storage,
blacklist:["temporary"]
}
const rootReducer = combineReducers({
itemData: persistReducer(itemsPersistConfig, createItems),
account: accountSlice,
ordersData:oderCardData
})
const persistedReducer = persistReducer(persistConfig, rootReducer)
// import ordersData
const store = configureStore({
reducer:persistedReducer,
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware({
serializableCheck: {
ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
},
}),
})
let persistor = persistStore(store)
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.Fragment>
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<App />
</PersistGate>
</Provider>
</React.Fragment>
</code></pre>
<p>it is working but the error of non-serializable data is still there and still wasn't remove though...Why I can't still remove it did I follow wrong things here?</p>
| [
{
"answer_id": 74222266,
"author": "Vinicius Bazanella",
"author_id": 10930717,
"author_profile": "https://Stackoverflow.com/users/10930717",
"pm_score": 4,
"selected": true,
"text": "config.forge"
},
{
"answer_id": 74248904,
"author": "Shanavas P S",
"author_id": 6727767... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19188610/"
] |
74,216,761 | <p>I have some log files which contain mixed of JSON and non-JSON logs, I'd like to separate them into two files, one contains JSON logs only and the other contains non-JSON logs, I get some ideas from <a href="https://github.com/stedolan/jq/issues/884#issuecomment-128439361" rel="nofollow noreferrer">this</a> to extract JSON logs with <code>jq</code>, here are what I have tried using <code>tee</code> to split log into two files (usage from <a href="https://unix.stackexchange.com/questions/28503/how-can-i-send-stdout-to-multiple-commands">here</a> & <a href="https://unix.stackexchange.com/questions/41246/how-to-redirect-output-to-multiple-log-files">here</a>) and <code>jq</code> to extract logs:</p>
<pre><code>cat $logfile | tee >(jq -R -c 'fromjson? | select(type == "object") | not') > $plain_log_file) >(jq -R -c 'fromjson? | select(type == "object")' > $json_log_file)
</code></pre>
<p>This extracts JSON logs correctly but returns <code>false</code> for each non-JSON log instead of the log content itself.</p>
<pre><code>cat $logfile | tee >(jq -R -c 'try fromjson catch .') > $plain_log_file) >(jq -R -c 'fromjson? | select(type == "object")' > $json_log_file)
</code></pre>
<p>this gets jq syntax error "catch ."</p>
<p>I do this so I can view the logs in <a href="https://github.com/tstack/lnav" rel="nofollow noreferrer">lnav</a> (an excellent log view/navigation tool).</p>
<p>Any suggestion on how to achieve this? Appreciate your help!</p>
<p>sample input:</p>
<pre><code>{ "name": "joe"}
text line, this can be multi-line too
{ "xyz": 123 }
</code></pre>
| [
{
"answer_id": 74222266,
"author": "Vinicius Bazanella",
"author_id": 10930717,
"author_profile": "https://Stackoverflow.com/users/10930717",
"pm_score": 4,
"selected": true,
"text": "config.forge"
},
{
"answer_id": 74248904,
"author": "Shanavas P S",
"author_id": 6727767... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8781330/"
] |
74,216,774 | <p>I'm trying to solve a problem where multiple concurrent HTTP requests are coming in and the server will read and increment the value stored in Hazelcast by 1. For example there are 3 incoming requests, the previous number value from 0 will increase to 1, keep increasing to 2 when processing request 2 and increasing to 3 when processing request 3. I am afraid that if I don't sync it, HTTP requests may read and write the old value causing problem of data inconsistency. I researched and found the method using "vertx.executeBlocking(future{});".</p>
<pre><code>vertx.executeBlocking(future -> {
}, res -> {
});
</code></pre>
<p>However, I don't know if using this method will synchronize the problem of reading and writing HTTP requests simultaneously or not? Or is there any solution for me to solve the above problem? I would be very grateful and appreciative of that. Thank</p>
| [
{
"answer_id": 74222266,
"author": "Vinicius Bazanella",
"author_id": 10930717,
"author_profile": "https://Stackoverflow.com/users/10930717",
"pm_score": 4,
"selected": true,
"text": "config.forge"
},
{
"answer_id": 74248904,
"author": "Shanavas P S",
"author_id": 6727767... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19280246/"
] |
74,216,778 | <p>How to print following sequence of number by while loop in python?</p>
<pre><code>5
54
543
5432
54321
</code></pre>
<p>Below I show my code:</p>
<pre><code>while (i <= n):
j = 1
while (j <= 1):
print(j,end='')
j+=1
print()
i += 1
</code></pre>
| [
{
"answer_id": 74222266,
"author": "Vinicius Bazanella",
"author_id": 10930717,
"author_profile": "https://Stackoverflow.com/users/10930717",
"pm_score": 4,
"selected": true,
"text": "config.forge"
},
{
"answer_id": 74248904,
"author": "Shanavas P S",
"author_id": 6727767... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20244999/"
] |
74,216,797 | <p>I'm currently working on an Android UI entirely Compose based.
I need to put a Divider component between 2 lists implemented as LazyColumn (vertical) and LazyRow (horizontal).</p>
<p>When I try to use the component, IntelliJ cannot suggest any dependency reference for Divider:</p>
<p><a href="https://i.stack.imgur.com/lJmbJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lJmbJ.png" alt="enter image description here" /></a></p>
<p>I already use the "androidx.compose.material" for other components in the UI and these are correctly imported:</p>
<p><a href="https://i.stack.imgur.com/WXGEc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WXGEc.png" alt="enter image description here" /></a></p>
<p>I even tried to add the reference manually using the import but nothing is found:</p>
<p><a href="https://i.stack.imgur.com/cONsS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cONsS.png" alt="enter image description here" /></a></p>
<p>Just for completeness, this are all the gradle app dependencies I actually use in the project:</p>
<p>`</p>
<pre><code>implementation 'androidx.core:core-ktx:1.7.0'
implementation "androidx.compose.ui:ui:$compose_version"
implementation 'androidx.compose.material3:material3:1.0.0-alpha01'
implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.3.1'
implementation 'androidx.activity:activity-compose:1.3.1'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
debugImplementation "androidx.compose.ui:ui-tooling:$compose_version"
debugImplementation "androidx.compose.ui:ui-test-manifest:$compose_version"
</code></pre>
<p>`</p>
<p>Any suggestion how to solve ?</p>
| [
{
"answer_id": 74216970,
"author": "Himanshu Bansal",
"author_id": 11953017,
"author_profile": "https://Stackoverflow.com/users/11953017",
"pm_score": 3,
"selected": true,
"text": "implementation \"androidx.compose.material:material:$compose_version\"\n"
},
{
"answer_id": 7421717... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15199900/"
] |
74,216,801 | <p>I have a pandas dataframe with monthly date index till the current month. I would like to impute NA values n periods into the future (in my case 1 year). I tried adding future dates into the existing index in the following manner:</p>
<pre><code>recentDate = inputFileDf.index[-1]
outputFileDf.index = outputFileDf.index.append(pd.date_range(recentDate , periods=12, freq="M"))
</code></pre>
<p>This throws <code>ValueError: Length mismatch: Expected axis has 396 elements, new values have 408 elements</code>.</p>
<p>Would appreciate any help to "extend" the dataframe by adding the dates and NA values.</p>
| [
{
"answer_id": 74216970,
"author": "Himanshu Bansal",
"author_id": 11953017,
"author_profile": "https://Stackoverflow.com/users/11953017",
"pm_score": 3,
"selected": true,
"text": "implementation \"androidx.compose.material:material:$compose_version\"\n"
},
{
"answer_id": 7421717... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16630042/"
] |
74,216,847 | <p>So I'm refreshing what little I knew of Python before and playing around with some beginner projects. I'm toying arond with it now, and I'm just trying to learn and see what I can do. I made a "Guessing Game" and turned it into a function. I want to store these reults in a list each time it is used. I want the results to automatically go to the list when the game is completed and then to be able to print the list when desired.</p>
<p>I'm not sure if I need to create a new function for this, or if I should be creating this within my current "guessing_game" function. I've tried to create a list previously, but I'm not sure how to create and store the variable of the game result in order to add it into the list. I feel like this is probably a fairly simple problem, so I apologize if this is a dumb question.</p>
<pre><code>def guessing_game():
import random
number = random.randint(1, 1000)
player_name = input("Enter name ")
number_of_guesses = 0
print('Howdy' + player_name + "Guess a number between 1 and 1000: ")
while number_of_guesses < 10:
guess = int(input())
number_of_guesses += 1
if guess < number:
print("Too Low, Joe")
if guess > number:
print("Too high, Sly")
if guess == number:
break
if guess == number:
print("You got it, Bobbit, in " + str(number_of_guesses) + " tries")
else:
print(" Well, yer were close, Stofe. Shoulda guessed " + str(number))
print(guessing_game())
</code></pre>
| [
{
"answer_id": 74216930,
"author": "Nathan Jiang",
"author_id": 16192057,
"author_profile": "https://Stackoverflow.com/users/16192057",
"pm_score": 1,
"selected": false,
"text": "def guessing_game():\n import random\n\n number = random.randint(1, 1000)\n player_name = input(\"En... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14588031/"
] |
74,216,856 | <p>I understand __class__ can be used to get the class of an object, it also can be used to get current class in a class definition. My question is, in a python class definition, is it safe just use __class__, rather than self.__class__?</p>
<pre><code>#!/usr/bin/python3
class foo:
def show_class():
print(__class__)
def show_class_self(self):
print(self.__class__)
if __name__ == '__main__':
x = foo()
x.show_class_self()
foo.show_class()
</code></pre>
<pre><code>./foo.py
<class '__main__.foo'>
<class '__main__.foo'>
</code></pre>
<p>As the codes above demonstrated, at least in Python3, __class__ can be used to get the current class, in the method show_class, without the present of "self". Is it safe? Will it cause problems in some special situations? (I can think none of it right now).</p>
| [
{
"answer_id": 74216930,
"author": "Nathan Jiang",
"author_id": 16192057,
"author_profile": "https://Stackoverflow.com/users/16192057",
"pm_score": 1,
"selected": false,
"text": "def guessing_game():\n import random\n\n number = random.randint(1, 1000)\n player_name = input(\"En... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1890745/"
] |
74,216,867 | <p>Hey would anyone be able to help me create a function in OCaml that would take in a string and recursively return the string with less and letters. I am trying to use the sub string and recursion to accomplish this, any ideas that could point me in the right direction?</p>
<pre class="lang-none prettyprint-override"><code>String
Strin
Stri
Str
St
S
</code></pre>
<p>I have used LISP and created a <code>car</code> and <code>cdr</code> function</p>
<pre><code>let car = function
| [] -> raise Not_found
| first :: _ -> first
and cdr = function
| [] -> raise Not_found
| _ :: rest -> rest
</code></pre>
| [
{
"answer_id": 74217030,
"author": "Jeffrey Scofield",
"author_id": 821679,
"author_profile": "https://Stackoverflow.com/users/821679",
"pm_score": 0,
"selected": false,
"text": "# let s = \"example\" in String.sub s 0 (String.length s - 1);;\n- : string = \"exampl\"\n"
},
{
"ans... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20345337/"
] |
74,216,873 | <p>This is My current output for a Grocery list Code. The list is setup to find the sum of all of the items below. The structure of the list is</p>
<pre><code>["Name", "Item Name", Item Amount, item Cost]
[['Emerie', 'keyboard', '29', '199'], ['Bodie', 'keyboard', '9', '199'], ['Emerie', 'bed', '1', '199'], ['Brecken', 'smartwatch', '9', '199'], ['Brecken', 'SSD', '9', '199']]
</code></pre>
<p>How can I get my output to look like this:</p>
<pre><code>[['Emerie', 'keyboard', 29, 199], ['Bodie', 'keyboard', 9, 199], ['Emerie', 'bed', 1, 199], ['Brecken', 'smartwatch', 9, 199], ['Brecken', 'SSD', 9, 199]]
</code></pre>
<p>So The strings are strings and the ints are ints</p>
<p><em><strong><strong>This list is a dynamic list that is subject to change.</strong></strong></em></p>
<p>I tried many methods but none seem to work</p>
| [
{
"answer_id": 74216897,
"author": "Rahul K P",
"author_id": 4407666,
"author_profile": "https://Stackoverflow.com/users/4407666",
"pm_score": 0,
"selected": false,
"text": "In [1]: [[int(j) if j.isdigit() else j for j in i] for i in l]\nOut[1]: \n[['Emerie', 'keyboard', 29, 199],\n ['Bo... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20345345/"
] |
74,216,887 | <p>I have the following problem:<br />
I need to add the 4 columns <code>F2:I2</code> I have tried with this formula <code>=ARRAYFORMULA(SUM(SPLIT(F2:I2," + ")))</code> but I don't know what the error is, it only adds me what is in cell <code>F2</code> Thank you in advance if you can give me a hand...</p>
<p>I took a screenshot of what I have done but I can't find what to modify in the formula, if you can help me I know that it is missing some function so that it can add the four cells.</p>
<p>Thank you</p>
<p><a href="https://i.stack.imgur.com/W7iNu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/W7iNu.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74217009,
"author": "CodeCamper",
"author_id": 2446698,
"author_profile": "https://Stackoverflow.com/users/2446698",
"pm_score": 0,
"selected": false,
"text": "=sum(map(f2:I2, lambda(fox,sum(split(fox,\" + \")))))\n"
},
{
"answer_id": 74219428,
"author": "JvdV"... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20345194/"
] |
74,216,888 | <p>Im using an achor to click a button to navigate to other page. However, it doesnt work and return a 404 error not found.</p>
<p>My destination blade is : <a href="https://i.stack.imgur.com/WYPVW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WYPVW.png" alt="enter image description here" /></a></p>
<p>inventory.blade.php:</p>
<pre><code><a class="d-xl-flex align-items-xl-center" href="{{ url('inventory/add')}}" style="padding-right: 0px;margin-right: 15px;"><button class="btn btn-primary d-xl-flex align-items-xl-center" type="button" style="margin-right: -16px;margin-bottom: 13px;margin-top: 7px;border-color: rgb(162,138,138);background: rgb(0,0,0);padding-bottom: 0px;padding-top: 1px;margin-left: -26px;">ADD PRODUCT</button></a>
</code></pre>
<p>controller: NavBar.php:</p>
<pre><code>public function inv(){
return view('inventory');
}
public function invadd(){
return view('inventory-add');
}
</code></pre>
<p>web.php:
<a href="https://i.stack.imgur.com/SPps9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SPps9.png" alt="enter image description here" /></a></p>
<p>I tried moving the inv() in another controller page and it's not already viewable or accessible by the routing. Is it because of referencing thing? I think my controller cannot access the blades in the resources/views folder.</p>
| [
{
"answer_id": 74217009,
"author": "CodeCamper",
"author_id": 2446698,
"author_profile": "https://Stackoverflow.com/users/2446698",
"pm_score": 0,
"selected": false,
"text": "=sum(map(f2:I2, lambda(fox,sum(split(fox,\" + \")))))\n"
},
{
"answer_id": 74219428,
"author": "JvdV"... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20252963/"
] |
74,216,901 | <p>I have a field called Name that I am breaking out into first, last, and middle initial. My query is separating it into first and last, but first name contains the middle initial. Some names have a middle initial, some have it and a period, some have neither, some have an entire word, & others are the name of a group where this would not apply. Here's my query.</p>
<pre><code>SELECT Name,
CASE WHEN Name LIKE '%,%' THEN REPLACE(SUBSTRING(Name, 1, (CHARINDEX(',', Name))), ',', '') ELSE Name END AS LastName,
CASE WHEN Name LIKE '%,%' THEN SUBSTRING(Name, (CHARINDEX(',', Name) + 2), LEN(Name)) ELSE Name END AS FirstName
FROM Customer
</code></pre>
<p>How could I:</p>
<ol>
<li>change my substring on the first name column to only go up to the space in that field</li>
<li>only put the first letter of the midddle name into MI field</li>
</ol>
<p>Current result</p>
<p><a href="https://i.stack.imgur.com/NaawN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NaawN.png" alt="enter image description here" /></a></p>
<p>Desired result</p>
<p><a href="https://i.stack.imgur.com/Wj9DX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Wj9DX.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74217009,
"author": "CodeCamper",
"author_id": 2446698,
"author_profile": "https://Stackoverflow.com/users/2446698",
"pm_score": 0,
"selected": false,
"text": "=sum(map(f2:I2, lambda(fox,sum(split(fox,\" + \")))))\n"
},
{
"answer_id": 74219428,
"author": "JvdV"... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3691608/"
] |
74,216,912 | <p>I am looking for a way to get out of the dictionary one key and its value if it is not 0 and if all other values are 0. How is it possible to expand the below code and return <code>'is': 1</code>?</p>
<pre><code>test_dict = {'gfg': 0, 'is': 1, 'best': 0}
res = all(x == 0 for x in test_dict.values())
print("Does all keys have 0 value ? : " + str(res))
#Output
#Does all keys have 0 value ? : False
</code></pre>
| [
{
"answer_id": 74217023,
"author": "Raibek",
"author_id": 11040577,
"author_profile": "https://Stackoverflow.com/users/11040577",
"pm_score": 0,
"selected": false,
"text": "key = None\nvalue = None\nfor k, v in test_dict.items():\n if v != 0:\n if key is None:\n key ... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3523406/"
] |
74,216,936 | <p><em><strong>UPDATE</strong></em>
After spending several days and dozens of hours on potential fixes, nothing works and I have given up on using Noesis. StackOverflow will not let me delete this as it has been "answered" but I assure you, I have tried these solutions and they do not work either.</p>
<hr />
<p>I recently downloaded Unity and Visual Studio and are attempting to integrate the NoesisGUI framework into my project. It requires the System.Windows.RoutedEventArgs class, but the only class I can see in System.Windows is Input. I've googled around and it looks like RoutedEventArgs should be in the 4.8 .net framework and I've verified my Visual Studio .net version is 4.8.3928.0.</p>
<p>It is worth noting that in my References section of the Solutions tab, it has a hundred different System .dll references listed (including System.Windows), but not System.Windows.RoutedEventArgs.</p>
<p>Here's some of the reference code, although I've removed anything that isn't important.</p>
<pre><code>using System;
using System.Windows.Controls;
namespace Dummy_Project
{
public partial class Dummy_ProjectMainView : UserControl
{
private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
{
}
}
}
</code></pre>
<p>I tried downloading the .net 4.8 framework and installing that, but it was still missing. I also tried unloading the project multiple times as per <a href="https://learn.microsoft.com/en-us/cpp/build/how-to-modify-the-target-framework-and-platform-toolset?view=msvc-170" rel="nofollow noreferrer">these</a> instructions, but the .vcxproj was not generated so it stopped there. I even uninstalled and reinstalled Visual Studio, but that didn't change a thing.</p>
<p><strong>I also found where PresentationCore.dll and moved it to the same folder as some of the other refences my project uses, rebuilt my project, but it still didn't pick it up. I've tried to add it to the references list as per <a href="https://learn.microsoft.com/en-us/visualstudio/ide/managing-references-in-a-project?view=vs-2022" rel="nofollow noreferrer">these</a> instructions, but when I right click the "Add Project Reference" option doesn't even show up</strong></p>
<p>Any advice would be greatly appreciated.</p>
| [
{
"answer_id": 74217320,
"author": "Milan Egon Votrubec",
"author_id": 8051819,
"author_profile": "https://Stackoverflow.com/users/8051819",
"pm_score": 0,
"selected": false,
"text": "Plugins"
}
] | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17705071/"
] |
74,216,958 | <p>I have this data in the following format:</p>
<pre><code>my_data = structure(list(name = c("john", "john", "john", "john", "john",
"alex", "alex", "alex", "alex", "alex", "tim", "tim", "tim",
"tim", "tim", "jason", "jason", "jason", "jason", "jason", "peter",
"peter", "peter", "peter", "peter", "nancy", "nancy", "nancy",
"nancy", "sarah", "sarah", "sarah", "sarah", "luke", "luke",
"luke", "luke", "steve", "steve", "steve", "steve", "matt", "matt",
"matt", "mark", "mark", "mark", "jim", "jim", "jim", "derek",
"derek", "lucy", "lucy", "anne", "kevin", "dave"), year = c(2010,
2011, 2013, 2014, 2019, 2010, 2011, 2012, 2013, 2014, 2008, 2010,
2014, 2018, 2019, 2005, 2006, 2009, 2010, 2011, 2012, 2013, 2014,
2015, 2016, 2009, 2010, 2011, 2013, 2014, 2015, 2019, 2020, 2007,
2008, 2009, 2010, 2009, 2015, 2016, 2016, 2010, 2011, 2012, 2009,
2015, 2016, 2020, 2021, 2022, 2010, 2011, 2012, 2013, 2005, 2012,
2011), grade = c("PASS", "PASS", "PASS", "FAIL", "FAIL", "FAIL",
"PASS", "FAIL", "FAIL", "PASS", "PASS", "PASS", "PASS", "PASS",
"PASS", "PASS", "FAIL", "FAIL", "FAIL", "PASS", "FAIL", "PASS",
"FAIL", "FAIL", "PASS", "FAIL", "FAIL", "PASS", "FAIL", "PASS",
"FAIL", "PASS", "FAIL", "PASS", "PASS", "FAIL", "FAIL", "PASS",
"PASS", "PASS", "PASS", "PASS", "PASS", "FAIL", "PASS", "PASS",
"PASS", "PASS", "FAIL", "PASS", "PASS", "FAIL", "FAIL", "FAIL",
"PASS", "PASS", "FAIL")), row.names = c(NA, -57L), class = "data.frame")
</code></pre>
<p>This data shows for each student:</p>
<ul>
<li>The year they were enrolled in school</li>
<li>If they passed or failed for that year</li>
</ul>
<p>In this dataset, students have been attended school for different periods of time. Sometimes, students take a leave of absence and then return to the school.</p>
<p>I would like to make a "Sankey Diagram" (e.g. <a href="https://d2mvzyuse3lwjc.cloudfront.net/doc/en/UserGuide/images/Sankey_Diagrams/Sankey_Diagrams_01.png?v=83374" rel="nofollow noreferrer">https://d2mvzyuse3lwjc.cloudfront.net/doc/en/UserGuide/images/Sankey_Diagrams/Sankey_Diagrams_01.png?v=83374</a>) that looks at the academic history of the different students in such a way:</p>
<p><a href="https://i.stack.imgur.com/5Wo2u.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5Wo2u.png" alt="enter image description here" /></a></p>
<p>I found this link in R that shows how to do something similar : <a href="https://rpubs.com/techanswers88/sankey-with-own-data-in-ggplot" rel="nofollow noreferrer">https://rpubs.com/techanswers88/sankey-with-own-data-in-ggplot</a></p>
<p>But I am not sure as to how I can restructure the data to make such a diagram.</p>
<p>Can someone please suggest how I can restructure this data so that I can make this diagram? <strong>Possibly in plotly?</strong> <a href="https://plotly.com/r/sankey-diagram/" rel="nofollow noreferrer">https://plotly.com/r/sankey-diagram/</a></p>
<p>Thank you!</p>
| [
{
"answer_id": 74217320,
"author": "Milan Egon Votrubec",
"author_id": 8051819,
"author_profile": "https://Stackoverflow.com/users/8051819",
"pm_score": 0,
"selected": false,
"text": "Plugins"
}
] | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13203841/"
] |
74,216,963 | <p>How can I return values filtering from this list?</p>
<p>I used contains, but it displays all the values.</p>
<p>I want to retrieve items from the list that have the word "abc" like this -> <code>abc Item</code>. The ones that have other words grouped like this
-> <code>abcde Item</code>, should be ignored.</p>
<p>I tried adding spaces to match the items in the list, but it didn't work:</p>
<p>.contains(' ${text} '.toUpperCase())</p>
<p>.contains('\n${text}\n'.toUpperCase())</p>
<pre class="lang-dart prettyprint-override"><code>List data = [{"Label": "abc Item", "Value": 10}, {"Label": "abcde Item", "Value": 20},{"Label": "edabc Item", "Value": 20}, {"Label": "item abc", "Value": 20}];
List match = [];
String text ="abc";
match.addAll(
data.where(
(oldValue) => oldValue['Label']
.toString()
.toUpperCase()
.contains(text.toUpperCase()),
),
);
print(match);
</code></pre>
<p><strong>expected values of the list search:</strong></p>
<pre><code>[{"Label": "abc Item", "Value": 10}, {"Label": "item abc", "Value": 20}]
</code></pre>
| [
{
"answer_id": 74217320,
"author": "Milan Egon Votrubec",
"author_id": 8051819,
"author_profile": "https://Stackoverflow.com/users/8051819",
"pm_score": 0,
"selected": false,
"text": "Plugins"
}
] | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18900734/"
] |
74,216,995 | <p>I have heavy request which takes more than 5 minutes to execute. In my logs I see that NestJS throws every 5 min new request by itself, but I don't see request from browser. As it was recommended I set</p>
<pre><code>const app = await app.listen();
app.setTimeout(1800000);
</code></pre>
<p>and in my rout</p>
<pre><code> @Get('/foo')
async foo(@Req() req) {
req.setTimeout(1800000);
//...
}
</code></pre>
<p>but it doesn't work, I see every 5 minutes new request in my logs.
I know, the best solution is making a queue and handle it asynchronously but for this moment I need just increase timeout somehow. Is it possible?</p>
| [
{
"answer_id": 74219558,
"author": "Andrey Bessonov",
"author_id": 4546382,
"author_profile": "https://Stackoverflow.com/users/4546382",
"pm_score": 1,
"selected": false,
"text": " proxy_read_timeout 5;\n proxy_connect_timeout 5;\n proxy_send_timeout 5;\n"
},
{
"answer_id":... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10127906/"
] |
74,216,998 | <p>What happens when one adds a before and an after psuedo selector to a button element?</p>
<p>I tried it already but couldn't really make anything out of it. New to web dev.</p>
| [
{
"answer_id": 74219558,
"author": "Andrey Bessonov",
"author_id": 4546382,
"author_profile": "https://Stackoverflow.com/users/4546382",
"pm_score": 1,
"selected": false,
"text": " proxy_read_timeout 5;\n proxy_connect_timeout 5;\n proxy_send_timeout 5;\n"
},
{
"answer_id":... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74216998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20345438/"
] |
74,217,000 | <p>I have a if statement where I have multiple && operators.</p>
<pre><code>if (firstname.value !=="" && lastname.value !=="" && phone.value !=="" && emailverified.value ==="1" && personcheck.checked === false){
//something//
}else{
//something else//
}
</code></pre>
<p>How can I put these into a single line and insert it in if statement so I can avoid multiple operators? Like this?</p>
<pre><code>
if (condition){
//something//
} else{
//something else//
}```
</code></pre>
| [
{
"answer_id": 74217012,
"author": "Indraraj26",
"author_id": 10842900,
"author_profile": "https://Stackoverflow.com/users/10842900",
"pm_score": 3,
"selected": true,
"text": "isValid"
},
{
"answer_id": 74217013,
"author": "Nikita Aplin",
"author_id": 11922126,
"autho... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74217000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12408884/"
] |
74,217,007 | <p>In the following code from <a href="https://doc.rust-lang.org/1.4.0/book/dining-philosophers.html" rel="nofollow noreferrer">Rust documentation</a> it talks about concurrent threading in Rust.</p>
<pre><code> use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..10 {
let counter = Arc::clone(&counter);
let handle = thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Result: {}", *counter.lock().unwrap());
}
</code></pre>
<p>I still couldn't grasp the idea of the for loop for the handles</p>
<p>i.e</p>
<pre><code>for handle in handles {
handle.join().unwrap();
}
</code></pre>
<p>The documentation says <em>"we call join on each handle to make sure all the threads finish. "</em>
For an experiment I commented out the handle for loop and I got an out put of 8 instead of 10. When I changed the loop to 1000, I got 999 when the handle loop is commented. What is happening here ? How does 8 & 999 become the output ?</p>
<p><strong>EDIT:</strong> I found <a href="https://doc.rust-lang.org/1.4.0/book/dining-philosophers.html" rel="nofollow noreferrer">this documentation</a> to touch on handle and general concept of threading.</p>
<pre><code> [1]: https://doc.rust-lang.org/book/ch16-03-shared-state.html
</code></pre>
| [
{
"answer_id": 74217267,
"author": "maxy",
"author_id": 235548,
"author_profile": "https://Stackoverflow.com/users/235548",
"pm_score": 1,
"selected": false,
"text": "join()"
},
{
"answer_id": 74218558,
"author": "Masklinn",
"author_id": 8182118,
"author_profile": "ht... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74217007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1017111/"
] |
74,217,010 | <p>I have such code example:</p>
<pre><code> <div style="width: 500px; height: 520px; position: sticky; z-index: 10;">
<div style="position: fixed; width: 100px; height: 100px; z-index: 50;"></div>
</div>
</code></pre>
<p>also I have a Shadow DOM, with <code>element A</code>, which I want to set between child and parent div</p>
<p>when I set z-index: 11 to this <code>element A</code> (between z-index of parent and child) the <code>element A</code> is above parent and child div
when I set it z-index: 9, the <code>element A</code> is under parent and child div</p>
<p>How I can set <code>element A</code> between child and parent div?</p>
| [
{
"answer_id": 74217267,
"author": "maxy",
"author_id": 235548,
"author_profile": "https://Stackoverflow.com/users/235548",
"pm_score": 1,
"selected": false,
"text": "join()"
},
{
"answer_id": 74218558,
"author": "Masklinn",
"author_id": 8182118,
"author_profile": "ht... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74217010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20329077/"
] |
74,217,036 | <p>I want to run multiple python scripts with passing arguments to the python script, how I can do that? Is it possible in Kubernetes?</p>
<p>Like I have multiple python scripts with different inputs: <code>"./main.py", "1" , "./main2.py", "2", "./main3.py", "3"</code> I can not put all of them in one file to run need to run them separately here, is there any way to do that?</p>
<pre><code>kind: Pod
metadata:
name: hello-world
spec: # specification of the pod’s contents
restartPolicy: Never
containers:
- name: hello
image: "ubuntu:14.04"
env:
- name: MESSAGE
value: "hello world"
command: [ "python" ]
args: [ "./main.py", "1" ]
</code></pre>
| [
{
"answer_id": 74217106,
"author": "P Ekambaram",
"author_id": 3270785,
"author_profile": "https://Stackoverflow.com/users/3270785",
"pm_score": 1,
"selected": false,
"text": "kind: Pod\nmetadata:\n name: hello-world-1\nspec: # specification of the pod’s contents\n restartPolicy: Neve... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74217036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5203459/"
] |
74,217,040 | <p>ahi, everyone. sorry to bother you.</p>
<p>I have this task that I have a list of hash codings stored in a list with 30 positions with value 0 and 1. In total, I have over 10000 such 30 size (0/1) hash codes and I would like to find all pairs of such hash codes which have the difference lower than a given threshold (say 0, 1, 5), in which case this pair would be considered as "similar" hash codings.</p>
<p>I have realised this using double "for loop" in python3 (see code below), but I do not feel it is efficient enough, as this seems to be a O(N^2), and it is indeed slow when N = 10000 or even larger.</p>
<p><strong>My question would be is there better way we could speed this finding similar hash pairs up ? Ideally, in O(N) I suppose ?</strong></p>
<p>Note by efficiency I mean finding similar pairs given thershold rather than generating hash codings (this is only for demonstration).</p>
<p>I have digged in this problem a little bit, all the answers I have found is talking about using some sort of collection tools to find identical pairs, but here I have a more general case that the pairs could also be similiar given a threshold.</p>
<p>I have provided the code that generates sample hashing codings and the current low efficient program I am using. I hope you may find this problem interesting and hopefully some better/smarter/senior programmer could lend me a hand on this one. Thanks in advance.</p>
<pre><code>import random
import numpy as np
# HashCodingSize = 10
# Just use this to test the program
HashCodingSize = 100
# HashCodingSize = 1000
# What can we do when we have the list over 10000, 100000 size ?
# This is where the problem is
# HashCodingSize = 10000
# HashCodingSize = 100000
#Generating "HashCodingSize" of list with each element has size of 30
outputCodingAllPy = []
for seed in range(HashCodingSize):
random.seed(seed)
listLength = 30
numZero = random.randint(1, listLength)
numOne = listLength - numZero
my_list = [0] * numZero + [1] * numOne
random.shuffle(my_list)
# print(my_list)
outputCodingAllPy.append(my_list)
#Covert to np array which is better than python3 list I suppose?
outputCodingAll = np.asarray(outputCodingAllPy)
print(outputCodingAll)
print("The N is", len(outputCodingAll))
hashDiffThreshold = 0
#hashDiffThreshold = 1
#hashDiffThreshold = 5
loopRange = range(outputCodingAll.shape[0])
samePairList = []
#This is O(n^2) I suppose, is there better way ?
for i in loopRange:
for j in loopRange:
if j > i:
if (sum(abs(outputCodingAll[i,] - outputCodingAll[j,])) <= hashDiffThreshold):
print("The pair (", str(i), ", ", str(j), ") ")
samePairList.append([i, j])
print("Following pairs are considered the same given the threshold ", hashDiffThreshold)
print(samePairList)
</code></pre>
<p><strong>Update2</strong> RAM problem
when list size goes up to 100000, the current speed solution still has the problem of RAM (numpy.core._exceptions._ArrayMemoryError: Unable to allocate 74.5 GiB for an array with shape (100000, 100000) and data type int64). In this case, anyone who are interested in the speed but without large RAM may consider parallel programming the original method **</p>
<p><strong>Update with current answers and benchmarking tests:</strong></p>
<p>I have briefly tested the answer provided by @Raibek, and it is indeed much faster than the for loop and has incoporated most of suggestions provided by others (many thanks to them as well). For now my problem is resolved, for anyone who are further interested in this problem, you could refer to @Raibek in accepted answer or to see my own test program below:</p>
<p><strong>Hint</strong>: For people who are absolutely in short of time on their project, what you need to do is to take function "bits_to_int" and "find_pairs_by_threshold_fast" to home, and first convert 0/1 bits to integers, and using XOR to find all the pairs that smaller than a threshold. Hope this helps faster.</p>
<pre><code>from logging import raiseExceptions
import random
import numpy as np
#check elapsed time
import time
# HashCodingSize = 10
# HashCodingSize = 100
HashCodingSize = 1000
# What can we do when we have the list over 10000, 100000 size ?
# HashCodingSize = 10000
# HashCodingSize = 100000
#Generating "HashCodingSize" of list with each element has 30 size
outputCodingAllPy = []
for seed in range(HashCodingSize):
random.seed(seed)
listLength = 30
numZero = random.randint(1, listLength)
numOne = listLength - numZero
my_list = [0] * numZero + [1] * numOne
random.shuffle(my_list)
# print(my_list)
outputCodingAllPy.append(my_list)
#Covert to np array which is better than python3 list
#Study how to convert bytes to integers
outputCodingAll = np.asarray(outputCodingAllPy)
print(outputCodingAll)
print("The N is", len(outputCodingAll))
hashDiffThreshold = 0
def myWay():
loopRange = range(outputCodingAll.shape[0])
samePairList = []
#This is O(n!) I suppose, is there better way ?
for i in loopRange:
for j in loopRange:
if j > i:
if (sum(abs(outputCodingAll[i,] - outputCodingAll[j,])) <= hashDiffThreshold):
print("The pair (", str(i), ", ", str(j), ") ")
samePairList.append([i, j])
return(np.array(samePairList))
#Thanks to Raibek
def bits_to_int(bits: np.ndarray) -> np.ndarray:
"""
https://stackoverflow.com/a/59273656/11040577
:param bits:
:return:
"""
assert len(bits.shape) == 2
# number of columns is needed, not bits.size
m, n = bits.shape
# -1 reverses array of powers of 2 of same length as bits
a = 2**np.arange(n)[::-1]
# this matmult is the key line of code
return bits @ a
#Thanks to Raibek
def find_pairs_by_threshold_fast(
coding_all_bits: np.ndarray,
listLength=30,
hashDiffThreshold=0
) -> np.ndarray:
xor_outer_matrix = np.bitwise_xor.outer(coding_all_bits, coding_all_bits)
# counting number of differences
diff_count_matrix = np.bitwise_and(xor_outer_matrix, 1)
for i in range(1, listLength):
diff_count_matrix += np.right_shift(np.bitwise_and(xor_outer_matrix, 2**i), i)
same_pairs = np.transpose(np.where(diff_count_matrix <= hashDiffThreshold))
# filtering out diagonal values
same_pairs = same_pairs[same_pairs[:, 0] != same_pairs[:, 1]]
# filtering out duplicates above diagonal
same_pairs.sort(axis=1)
same_pairs = np.unique(same_pairs, axis=0)
return same_pairs
start = time.time()
outResult1 = myWay()
print("My way")
print("Following pairs are considered the same given the threshold ", hashDiffThreshold)
print(outResult1)
end = time.time()
timeUsedOld = end - start
print(timeUsedOld)
start = time.time()
print('Helper Way updated')
print("Following pairs are considered the same given the threshold ", hashDiffThreshold)
outputCodingAll_bits = bits_to_int(outputCodingAll)
same_pairs_fast = find_pairs_by_threshold_fast(outputCodingAll_bits, 30, hashDiffThreshold)
print(same_pairs_fast)
end = time.time()
timeUsedNew = end - start
print(timeUsedNew)
print(type(outResult1))
print(type(same_pairs_fast))
if ((outResult1 == same_pairs_fast).all()) & (timeUsedNew < timeUsedOld):
print("The two methods have returned the same results, I have been outsmarted !")
print("The faster method used ", timeUsedNew, " while the old method takes ", timeUsedOld)
else:
raiseExceptions("Error, two methods do not return the same results, something must be wrong")
#Thanks to Raibek
#note this suffers from out of memoery problem
# def Helper1Way():
# outer_not_equal = np.not_equal.outer(outputCodingAll, outputCodingAll)
# diff_count_matrix = outer_not_equal.sum((1, 3)) // outputCodingAll.shape[1]
# samePairNumpy = np.transpose(np.where(diff_count_matrix <= hashDiffThreshold))
# # filtering out diagonal values
# samePairNumpy = samePairNumpy[samePairNumpy[:, 0] != samePairNumpy[:, 1]]
# # filtering out duplicates above diagonal
# samePairNumpy.sort(axis=1)
# samePairNumpy = np.unique(samePairNumpy, axis=0)
# return(np.array(samePairNumpy))
# start = time.time()
# outResult2 = Helper1Way()
# print('Helper Way')
# print("Following pairs are considered the same given the threshold ", hashDiffThreshold)
# print(outResult2)
# end = time.time()
# print(end - start)
</code></pre>
| [
{
"answer_id": 74217106,
"author": "P Ekambaram",
"author_id": 3270785,
"author_profile": "https://Stackoverflow.com/users/3270785",
"pm_score": 1,
"selected": false,
"text": "kind: Pod\nmetadata:\n name: hello-world-1\nspec: # specification of the pod’s contents\n restartPolicy: Neve... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74217040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8956723/"
] |
74,217,057 | <p>Reading <a href="https://en.cppreference.com/w/cpp/language/reinterpret_cast" rel="noreferrer">https://en.cppreference.com/w/cpp/language/reinterpret_cast</a> I wonder what are use-cases of <code>reinterpret_cast</code> that are not UB and are used in practice?</p>
<p>The above description contains many cases where it is legal to convert a pointer to some other type an then back, which is legal. But that seems of less practical use. Accessing an object through a <code>reinterpret_cast</code> pointer is mostly UB due to violations of strict-aliasing (and/or alignment), except accessing through a <code>char*</code>/<code>byte*</code>-pointer.</p>
<p>One helpful exception is casting a integer-constant to a pointer and accessing the target object, which is useful for manipulation of HW-registers (in µC).</p>
<p>Can anyone tell some real use-cases of relevance of reinterpret_cast that are used in practice?</p>
| [
{
"answer_id": 74217878,
"author": "user17732522",
"author_id": 17732522,
"author_profile": "https://Stackoverflow.com/users/17732522",
"pm_score": 6,
"selected": true,
"text": "// T must be trivially-copyable object type!\nT obj;\n\n//...\n\nstd::ofstream file(/*...*/);\nfile.write(rein... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74217057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3359751/"
] |
74,217,059 | <p>I have a table like this
<a href="https://i.stack.imgur.com/OVSx7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OVSx7.png" alt="enter image description here" /></a></p>
<p>and the output what I want
<a href="https://i.stack.imgur.com/W2Zn3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/W2Zn3.png" alt="enter image description here" /></a></p>
<p>Where NETT2 is sum of value of TRX_NUMBER, and i only want to use SUM, no matter what i use CASE</p>
<p>Can is possible ?</p>
<p>I tried like this</p>
<pre class="lang-sql prettyprint-override"><code>select segment1
,jenis_rcv
,gl_date
,trx_number
,nett
,sum(nett) nett2
from SEMUA
group by segment1
,jenis_rcv
,gl_date
,trx_number
,nett
</code></pre>
| [
{
"answer_id": 74217878,
"author": "user17732522",
"author_id": 17732522,
"author_profile": "https://Stackoverflow.com/users/17732522",
"pm_score": 6,
"selected": true,
"text": "// T must be trivially-copyable object type!\nT obj;\n\n//...\n\nstd::ofstream file(/*...*/);\nfile.write(rein... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74217059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20328169/"
] |
74,217,079 | <pre><code>const A = 0;
const LOOKUP = { A : "A"};
console.log(LOOKUP[A]);
console.log(LOOKUP[0]);
</code></pre>
<p>Result:</p>
<pre><code>undefined
undefined
</code></pre>
<p>Second try:</p>
<pre><code>var A = 0;
const LOOKUP = { A : "A"};
console.log(LOOKUP[A]);
console.log(LOOKUP[0]);
</code></pre>
<p>Result:</p>
<pre><code>undefined
undefined
</code></pre>
<p>How am I supposed to do this then? And can somebody explain why this doesn't work in JavaScript the way one would expect it to work coming from other languages?</p>
| [
{
"answer_id": 74217099,
"author": "mroman",
"author_id": 3967945,
"author_profile": "https://Stackoverflow.com/users/3967945",
"pm_score": 1,
"selected": false,
"text": "const A = 0;\nconst LOOKUP = {};\n\nLOOKUP[A] = 'A';\n\nconsole.log(LOOKUP[A]);\nconsole.log(LOOKUP[0]);\n"
},
{
... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74217079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3967945/"
] |
74,217,082 | <p>Dataflow streaming job reads messages from PubSub and processes it somehow.
But sometimes, for example because of very long processing time, this message is not acked on time and PubSub redelivers this message.
We can see it in dataflow logs where two in fact the same messages (the same <code>message_id</code>) are processed at the same time.</p>
<p>My question is: what will happen to this "old" (first) PubSub message, that is still processed but in fact is expired because new deliver just arrived.
If this first message finishes finally the process before second (redelivered one) message, will it go further to next step or will be dropped (because is expired)?</p>
| [
{
"answer_id": 74217099,
"author": "mroman",
"author_id": 3967945,
"author_profile": "https://Stackoverflow.com/users/3967945",
"pm_score": 1,
"selected": false,
"text": "const A = 0;\nconst LOOKUP = {};\n\nLOOKUP[A] = 'A';\n\nconsole.log(LOOKUP[A]);\nconsole.log(LOOKUP[0]);\n"
},
{
... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74217082",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12135668/"
] |
74,217,083 | <p>in reactive form hasValidator functions does not work when use with Validators.compose</p>
<p>I want to display "*" if the formcontroller is required</p>
<pre><code>import { Component, VERSION } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
constructor(private fb: FormBuilder) {}
profileForm = this.fb.group({
firstName: [
'',
Validators.compose([Validators.required, Validators.max(3)]),
],
lastName: [''],
});
isFieldMandatory(name: string) {
return (
this.profileForm.get(name)?.hasValidator(Validators.required) ?? false
);
}
}
</code></pre>
<pre><code><fieldset>
<form [formGroup]="profileForm">
<label for="first-name"
>First Name: <span *ngIf="isFieldMandatory('firstName')">*</span></label
>
<input id="first-name" type="text" formControlName="firstName" />
<span>
{{ profileForm.get('firstName').errors | json }}
</span>
<br />
<label for="last-name"
>Last Name: <span *ngIf="isFieldMandatory('lastName')">*</span>
</label>
<input id="last-name" type="text" formControlName="lastName" />
<span>
{{ profileForm.get('lastName').errors | json }}
</span>
</form>
</fieldset>
<p>Form Status: {{ profileForm.status }}</p>
</code></pre>
<pre><code></code></pre>
| [
{
"answer_id": 74219376,
"author": "Meet",
"author_id": 7517648,
"author_profile": "https://Stackoverflow.com/users/7517648",
"pm_score": 1,
"selected": false,
"text": " isFieldMandatory(name: string) {\n return this.profileForm.get(name)?.errors?.required ?? false; <--- Cha... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74217083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1371714/"
] |
74,217,100 | <p>I am trying to load options into a select box from a Google Sheet. My code currently almost works, however, the initial select option is not loading the corresponding value into the text input box when the page first displays. When the select box option is changed, the value is properly loaded into the text box. How can I load both the option and value on the initial page load?</p>
<p>Code.gs</p>
<pre><code>function onOpen(e) {
SpreadsheetApp.getUi()
.createMenu("Sidebar")
.addItem("Show sidebar", "showSidebar")
.addToUi();
}
function showSidebar() {
var htmlWidget = HtmlService.createHtmlOutputFromFile('Test')
SpreadsheetApp.getUi().showSidebar(htmlWidget);
}
function getList() {
var items = SpreadsheetApp.getActive().getRange("Sheet1!A1:B3").getValues();
return items;
}
</code></pre>
<p>Test.html</p>
<pre><code><!DOCTYPE html>
<html>
<script>
function loadSelectBox() {
google.script.run.withSuccessHandler(function(ar)
{
var itemList = document.getElementById("itemSelectBox");
ar.forEach(function(item, index)
{
var option = document.createElement("option");
option.value = item[1];
option.text = item[0];
itemList.appendChild(option);
});
}).getList();
getPath();
}
function getPath()
{
var path = document.getElementById("itemSelectBox").value;
document.getElementById("itemPath").value = path;
}
</script>
<head>
<base target="_top">
</head>
<body>
<select id="itemSelectBox" onchange="getPath()" style="width: 60%"></select>
<br>
<input type="text" id="itemPath" style="width: 60%">
<script>
loadSelectBox();
</script>
</body>
</html>
</code></pre>
| [
{
"answer_id": 74217173,
"author": "Tanaike",
"author_id": 7108653,
"author_profile": "https://Stackoverflow.com/users/7108653",
"pm_score": 3,
"selected": true,
"text": "loadSelectBox()"
}
] | 2022/10/27 | [
"https://Stackoverflow.com/questions/74217100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19286901/"
] |
74,217,120 | <p>Database settings</p>
<pre><code>
DATABASES = {
'default': {
'ENGINE': os.environ.get('DB_ENGINE', "mysql"),
'NAME': os.environ.get('DB_NAME', "django_db"),
'USER': os.environ.get('DB_USER', "root"),
'PASSWORD': os.environ.get('DB_PASS', "123456798"),
'HOST': os.environ.get('DB_HOST', "localhost"),
'PORT': os.environ.get('DB_PORT'),
}
}
</code></pre>
<p>error</p>
<pre><code>django.core.exceptions.ImproperlyConfigured: 'mysql' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of:
'mysql', 'oracle', 'postgresql', 'sqlite3'
</code></pre>
<p>Connecting with mysql to generate migration but facing issue
Its my first time and facing following above issue please guide.</p>
| [
{
"answer_id": 74217173,
"author": "Tanaike",
"author_id": 7108653,
"author_profile": "https://Stackoverflow.com/users/7108653",
"pm_score": 3,
"selected": true,
"text": "loadSelectBox()"
}
] | 2022/10/27 | [
"https://Stackoverflow.com/questions/74217120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19442360/"
] |
74,217,132 | <p>In the flutter database example code: <a href="https://docs.flutter.dev/cookbook/persistence/sqlite" rel="nofollow noreferrer">https://docs.flutter.dev/cookbook/persistence/sqlite</a></p>
<p>This block of code throws 3 errors:</p>
<pre><code> // Convert the List<Map<String, dynamic> into a List<Dog>.
return List.generate(maps.length, (i) {
return Dog(
id: maps[i]['id'],
name: maps[i]['name'],
age: maps[i]['age'],
);
});
</code></pre>
<p>}</p>
<p>The errors are:</p>
<ul>
<li>The argument type 'dynamic' can't be assigned to the parameter type 'int'.</li>
<li>The argument type 'dynamic' can't be assigned to the parameter type 'String'.</li>
<li>The argument type 'dynamic' can't be assigned to the parameter type 'int'.</li>
</ul>
<p>and vscode highlights the "maps" section of the line (maps[i])</p>
<p>I dont know what version of flutter the guide was targeting, but my guess is that it's a problem maybe in newer flutter versions? I'm trying to learn flutter and how to use sqlite, so this has me stuck. Thanks in advance for any input!</p>
<p>For reference, here's the whole code block:</p>
<pre><code>import 'dart:async';
import 'package:flutter/widgets.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
void main() async {
// Avoid errors caused by flutter upgrade.
// Importing 'package:flutter/widgets.dart' is required.
WidgetsFlutterBinding.ensureInitialized();
// Open the database and store the reference.
final database = openDatabase(
// Set the path to the database. Note: Using the `join` function from the
// `path` package is best practice to ensure the path is correctly
// constructed for each platform.
join(await getDatabasesPath(), 'doggie_database.db'),
// When the database is first created, create a table to store dogs.
onCreate: (db, version) {
// Run the CREATE TABLE statement on the database.
return db.execute(
'CREATE TABLE dogs(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)',
);
},
// Set the version. This executes the onCreate function and provides a
// path to perform database upgrades and downgrades.
version: 1,
);
// Define a function that inserts dogs into the database
Future<void> insertDog(Dog dog) async {
// Get a reference to the database.
final db = await database;
// Insert the Dog into the correct table. You might also specify the
// `conflictAlgorithm` to use in case the same dog is inserted twice.
//
// In this case, replace any previous data.
await db.insert(
'dogs',
dog.toMap(),
conflictAlgorithm: ConflictAlgorithm.replace,
);
}
// A method that retrieves all the dogs from the dogs table.
Future<List<Dog>> dogs() async {
// Get a reference to the database.
final db = await database;
// Query the table for all The Dogs.
final List<Map<String, dynamic>> maps = await db.query('dogs');
// Convert the List<Map<String, dynamic> into a List<Dog>.
return List.generate(maps.length, (i) {
return Dog(
id: maps[i]['id'],
name: maps[i]['name'],
age: maps[i]['age'],
);
});
}
Future<void> updateDog(Dog dog) async {
// Get a reference to the database.
final db = await database;
// Update the given Dog.
await db.update(
'dogs',
dog.toMap(),
// Ensure that the Dog has a matching id.
where: 'id = ?',
// Pass the Dog's id as a whereArg to prevent SQL injection.
whereArgs: [dog.id],
);
}
Future<void> deleteDog(int id) async {
// Get a reference to the database.
final db = await database;
// Remove the Dog from the database.
await db.delete(
'dogs',
// Use a `where` clause to delete a specific dog.
where: 'id = ?',
// Pass the Dog's id as a whereArg to prevent SQL injection.
whereArgs: [id],
);
}
// Create a Dog and add it to the dogs table
var fido = const Dog(
id: 0,
name: 'Fido',
age: 35,
);
await insertDog(fido);
// Now, use the method above to retrieve all the dogs.
print(await dogs()); // Prints a list that include Fido.
// Update Fido's age and save it to the database.
fido = Dog(
id: fido.id,
name: fido.name,
age: fido.age + 7,
);
await updateDog(fido);
// Print the updated results.
print(await dogs()); // Prints Fido with age 42.
// Delete Fido from the database.
await deleteDog(fido.id);
// Print the list of dogs (empty).
print(await dogs());
}
class Dog {
const Dog({
required this.id,
required this.name,
required this.age,
});
final int id;
final String name;
final int age;
// Convert a Dog into a Map. The keys must correspond to the names of the
// columns in the database.
Map<String, dynamic> toMap() {
return {
'id': id,
'name': name,
'age': age,
};
}
// Implement toString to make it easier to see information about
// each dog when using the print statement.
@override
String toString() {
return 'Dog{id: $id, name: $name, age: $age}';
}
}
</code></pre>
| [
{
"answer_id": 74217202,
"author": "Sapinder Singh",
"author_id": 14299072,
"author_profile": "https://Stackoverflow.com/users/14299072",
"pm_score": 3,
"selected": true,
"text": "return List.generate(maps.length, (i) {\n return Dog(\n id: maps[i]['id'] as int,\n name:... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74217132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/965372/"
] |
74,217,150 | <p>I'm confused about making a connection from nginx alpine to nginx alpine</p>
<p>both use laravel 9</p>
<p>on the host I can access both using http://localhost:8080
and http://localhost:5001</p>
<p>but when I try to use guzzle in frontend like this</p>
<pre><code>$response = $http->get('http://dashboard:5001');
</code></pre>
<p>result is</p>
<pre><code>cURL error 7: Failed to connect to dashboard_service port 5001 after 0 ms:
Connection refused
</code></pre>
<p>and I try to curl from frontend container to dashboard container the result is connection refused.I can ping it, but curl not work</p>
<p>this is my docker-compose.yml</p>
<pre><code>version: "3.8"
networks:
networkname:
services:
frontend:
build:
context: .
dockerfile: ./file/Dockerfile
container_name: frontend
ports:
- 8080:80
volumes:
- ./frontend:/code
- ./.docker/php-fpm.conf:/etc/php8/php-fpm.conf
- ./.docker/php.ini-production:/etc/php8/php.ini
- ./.docker/nginx.conf:/etc/nginx/nginx.conf
- ./.docker/nginx-laravel.conf:/etc/nginx/modules/nginx-laravel.conf
networks:
- networkname
dashboard:
build:
context: .
dockerfile: ./file/Dockerfile
container_name: dashboard
ports:
- 5001:80
volumes:
- ./dashboard:/code
- ./.docker/php-fpm.conf:/etc/php8/php-fpm.conf
- ./.docker/php.ini-production:/etc/php8/php.ini
- ./.docker/nginx.conf:/etc/nginx/nginx.conf
- ./.docker/nginx-laravel.conf:/etc/nginx/modules/nginx-laravel.conf
networks:
- networkname
</code></pre>
<p>this is my dockerfile</p>
<pre><code>FROM alpine:latest
WORKDIR /var/www/html/
# Essentials
RUN echo "UTC" > /etc/timezone
RUN apk add --no-cache zip unzip curl sqlite nginx supervisor
# Installing PHP
RUN apk add --no-cache php8 \
php8-common \
php8-fpm \
# Installing composer
RUN curl -sS https://getcomposer.org/installer -o composer-setup.php
RUN php composer-setup.php --install-dir=/usr/local/bin --filename=composer
RUN rm -rf composer-setup.php
# Configure supervisor
RUN mkdir -p /etc/supervisor.d/
COPY .docker/supervisord.ini /etc/supervisor.d/supervisord.ini
# Configure PHP
RUN mkdir -p /run/php/
RUN mkdir -p /test
RUN touch /run/php/php8.0-fpm.pid
CMD ["supervisord", "-c", "/etc/supervisor.d/supervisord.ini"]
</code></pre>
<p>this is my nginx conf</p>
<pre><code>server {
listen 80;
server_name localhost;
root /code/public;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
index index.php;
charset utf-8;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt { access_log off; log_not_found off; }
error_page 404 /index.php;
location ~ \.php$ {
fastcgi_pass localhost:9000;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /\.(?!well-known).* {
deny all;
}
}
</code></pre>
<p>I'm confused about having to set it up in docker, nginx or alpine linux</p>
<p>Thanks.</p>
| [
{
"answer_id": 74217202,
"author": "Sapinder Singh",
"author_id": 14299072,
"author_profile": "https://Stackoverflow.com/users/14299072",
"pm_score": 3,
"selected": true,
"text": "return List.generate(maps.length, (i) {\n return Dog(\n id: maps[i]['id'] as int,\n name:... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74217150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11915596/"
] |
74,217,160 | <p>I was reading about structs in C that there are 2 ways to define a struct variable (which initializes it and creates memory for it).</p>
<p><strong>EDIT:</strong> I found the answer. The reason it was not working was because the <code>game_struct</code> variable got destroyed as soon as the <code>game_create</code> function exited and then I was left with an address to a place in memory that I was not allowed to access anymore. And the reason that the <code>malloc</code> version worked was because it allocated memory for the struct and I passed back the value of the address.</p>
<ol>
<li>First way is to simply define it as a normal variable like this</li>
</ol>
<pre><code>struct Person {
char name[50];
int age;
float salary;
};
int main() {
struct Person person1, person2;
strcpy(person1.name, "Joey Gladstone");
person1.age = 13;
}
</code></pre>
<ol start="2">
<li>The second way is to use <code>malloc</code> like this.</li>
</ol>
<pre><code>struct game * game_create()
{
struct game * game;
game = malloc(sizeof(struct game));
return game;
}
</code></pre>
<p>But when I tried to use the first way in my game it showed me this error:</p>
<blockquote>
<p>[1] 2640483 segmentation fault (core dumped) ./game</p>
</blockquote>
<p>Here is my struct defined in <code>game.h</code></p>
<pre><code>#ifndef __GAME_H__
#define __GAME_H__
#include <SDL2/SDL.h>
#include <stdbool.h>
// Struct for displaying text on screen
typedef struct {
SDL_Rect rect;
SDL_Texture * texture;
} text;
// Ship orientation
typedef enum {
HORIZONTAL,
VERTICAL
} orientation;
typedef struct {
SDL_Rect rect;
bool is_placed;
orientation orientation;
} ship;
typedef struct {
SDL_Rect rect;
bool is_hit;
} shot;
struct game {
text title;
SDL_Window * window;
SDL_Renderer * renderer;
SDL_Rect player_aim;
shot player_shots[100];
shot opponent_shots[100];
ship player_ships[10];
ship opponent_ships[10];
bool is_running;
int cell_size;
int grid_width;
int grid_height;
int grid_offset_y;
int placing_ship_index;
int player_grid_offset_x;
int opponent_grid_offset_x;
int placed_ships;
int player_hits;
int opponent_hits;
int player_shots_count;
int opponent_shots_count;
bool is_shooting;
};
struct game * game_create();
void game_run(struct game * game);
void game_init(struct game * game);
int game_terminate(struct game * game);
void game_quit(struct game * game);
text game_get_title(struct game * game);
#endif
</code></pre>
<p>And this is how I try to create the struct variable:</p>
<pre><code>#include "include/game.h"
struct game * game_create()
{
struct game game_struct;
return &game_struct;
}
</code></pre>
<p>And I get <code>segmentation fault</code> error and I don't understand why, I think it should have worked. What am I doing wrong? It works with <code>malloc</code> but does not work like this.</p>
| [
{
"answer_id": 74217354,
"author": "Özgür Murat Sağdıçoğlu",
"author_id": 5106317,
"author_profile": "https://Stackoverflow.com/users/5106317",
"pm_score": 3,
"selected": true,
"text": "struct game * game_create()\n{\n struct game game_struct;\n return &game_struct; // wrong!\n}\n"... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74217160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9008233/"
] |
74,217,165 | <p>Assume that I'm on page-A now. I navigate to page-B. When I pop the page-B and come back to page-A, currently nothing happens. How can I reload page-A and load the new API data from the init state of page-A? Any Ideas?</p>
| [
{
"answer_id": 74217354,
"author": "Özgür Murat Sağdıçoğlu",
"author_id": 5106317,
"author_profile": "https://Stackoverflow.com/users/5106317",
"pm_score": 3,
"selected": true,
"text": "struct game * game_create()\n{\n struct game game_struct;\n return &game_struct; // wrong!\n}\n"... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74217165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14761493/"
] |
74,217,198 | <p>I am using bash and trying to do pass quoted arguments to a function using a string variable and it fails.</p>
<pre><code> myfunc() {
for myarg in "${@}"
do
echo ">$myarg<"
done
}
echo "prints three things"
myfunc foo bar "blah blah"
echo "uugh this prints four... why?!?!?"
myvar="foo bar \"blah blah\""
myfunc $myvar
</code></pre>
<p>produces this:</p>
<pre><code>prints three things
>foo<
>bar<
>blah blah<
uugh this prints four... why?!?!?
>foo<
>bar<
>"blah<
>blah"<
</code></pre>
<p>I am building the list of arguments so that is why I need a string. Also, I am stuck with bash 4.2 version. Is there a way to have the second call to the function behave the same way as the first call?</p>
<p>Note: <code>myvar</code> is being read from a text file so I need that as a string.</p>
| [
{
"answer_id": 74217354,
"author": "Özgür Murat Sağdıçoğlu",
"author_id": 5106317,
"author_profile": "https://Stackoverflow.com/users/5106317",
"pm_score": 3,
"selected": true,
"text": "struct game * game_create()\n{\n struct game game_struct;\n return &game_struct; // wrong!\n}\n"... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74217198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1241540/"
] |
74,217,229 | <p>I have the following list:</p>
<pre><code>order = [['S', ['PINEAPPLE']], ['M', ['PINEAPPLE']], ['L', ['PINEAPPLE']]]
</code></pre>
<p>I want to split this list into seperate lists so that it will look like this</p>
<pre><code>order1 = ['S', ['PINEAPPLE']]
order2 = ['M', ['PINEAPPLE']]
order3 = ['L', ['PINEAPPLE']]
</code></pre>
<p>I would also like to know if its possible to make "order 1-3" into tuples instead of lists</p>
<p>I tried:</p>
<pre><code>orders = order_str.split(",")
</code></pre>
<p>but that only works for strings</p>
| [
{
"answer_id": 74217247,
"author": "bn_ln",
"author_id": 10535824,
"author_profile": "https://Stackoverflow.com/users/10535824",
"pm_score": 1,
"selected": false,
"text": "order = [['S', ['PINEAPPLE']], ['M', ['PINEAPPLE']], ['L', ['PINEAPPLE']]]\norder1, order2, order3 = order\n\nprint(... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74217229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20067566/"
] |
74,217,239 | <p>Seems we all run into this issue at some point during our learning path. Perhaps I need to strengthen my vanilla JS skills- anyways to the point--</p>
<p><em>this is my stack trace:</em></p>
<p>Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:371:5)
at ServerResponse.setHeader (node:_http_outgoing:576:11)</p>
<p><em>this is my code:</em></p>
<pre><code>router.post("/login", async (req, res) => {
try {
const user = await User.findOne({ username: req.body.username });
!user && res.status(400).json("Wrong credentials.");
const validated = await bcrypt.compare(req.body.password, user.password);
!validated && res.status(400).json("Wrong credentials.");
res.status(200).json(user);
} catch(err) {
res.status(500).json(err);
}
});
</code></pre>
<p>I'm getting my response back when I incorrectly guess either my userName, or password, but it appears it's also trying to fire another error and thus is crashing my express server. Once a response is sent, why is it sending another response?</p>
<p>(sorry if this is a duplicate question, I've read quite a few posts of others with this issue.)</p>
| [
{
"answer_id": 74217247,
"author": "bn_ln",
"author_id": 10535824,
"author_profile": "https://Stackoverflow.com/users/10535824",
"pm_score": 1,
"selected": false,
"text": "order = [['S', ['PINEAPPLE']], ['M', ['PINEAPPLE']], ['L', ['PINEAPPLE']]]\norder1, order2, order3 = order\n\nprint(... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74217239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16743322/"
] |
74,217,256 | <p>I'm trying to DECODE the email of employees to the Company's name of that email type by combining DECODE with SUBSTRING. For some odd reason, the result keeps giving me an error of invalid number but I've used the SUBSTR's position with non-numeric values(symbols such as @ before) but it is not working now.</p>
<p>Is there a way around this?</p>
<p><a href="https://i.stack.imgur.com/WujTn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WujTn.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74217350,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 1,
"selected": false,
"text": "substr"
},
{
"answer_id": 74217403,
"author": "Koen Lostrie",
"author_id": 4189814,
"author_p... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74217256",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18210595/"
] |
74,217,308 | <pre><code>def main():
data = ("Robin", 10, "chocolates")
format_string = None
print(format_string %data)
print("Hello %d.You are currently left with %s %d" %(data))
return 0
if __name__ == '__main__':
main()
</code></pre>
<p>i got runtime error .how to solve this?.Actually i want to print " Hello Robin. Yo are currenty left with 10 chocolates</p>
| [
{
"answer_id": 74217350,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 1,
"selected": false,
"text": "substr"
},
{
"answer_id": 74217403,
"author": "Koen Lostrie",
"author_id": 4189814,
"author_p... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74217308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19059972/"
] |
74,217,317 | <p>Is there a way to get list of numbers in python without using numpy.
Example,</p>
<pre><code>asd = ['926', '927', '928', '929', '930', '931']
</code></pre>
<p>I have a list above which are typed manually.. but can not put a range like (926 to 931) and get the list?</p>
<p>Any help?</p>
| [
{
"answer_id": 74217343,
"author": "Talpa",
"author_id": 17493215,
"author_profile": "https://Stackoverflow.com/users/17493215",
"pm_score": 1,
"selected": false,
"text": "asd = [str(i) for i in range(926, 932)]"
},
{
"answer_id": 74217361,
"author": "Rahul K P",
"author_... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74217317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16176890/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.