qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,355,749 | <p>I am writing a salt state that will check the value of a registry key. This is returning 'NULL'. I suspect that my 'getregvalue' variable is not resolving with the variables i have passed to cmd.run. This works as expected when the -Path and -Name values are hardcoded. How do i pass the -Path and -Name variables dynamically correctly?</p>
<pre><code>
{% for regconfig in registryconfig.settings %}
{% set getregvalue = salt['cmd.run']('Get-ItemPropertyValue -Path regconfig.hive ~ ":\" ~ regconfig.path -Name regconfig.vname',shell='powershell') %}
{% endfor %}
c:\temp\debug.txt:
file.managed:
- contents: |
{{ getregvalue |yaml(False) |indent(8) }}
</code></pre>
<p>This is the config file</p>
<pre><code>{%- load_yaml as registrysettings %}
dev:
settings:
- hive: 'HKLM'
path: 'SOFTWARE\Database Settings\dbstate'
vname: ConnectionString
{%- endload %}
{%- set registryconfig = salt['grains.filter_by'](registrysettings,
grain='env') %}
</code></pre>
| [
{
"answer_id": 74355816,
"author": "asdfasdf",
"author_id": 20354959,
"author_profile": "https://Stackoverflow.com/users/20354959",
"pm_score": 1,
"selected": false,
"text": "def sort_dict(item: dict):\n for k, v in sorted(item.items()):\n item[k] = sorted(v) if isinstance(v, list) else v\n return {k: sort_dict(v) if isinstance(v, dict) else v for k, v in sorted(item.items())}\n"
},
{
"answer_id": 74355919,
"author": "Yangtian Sun",
"author_id": 20336874,
"author_profile": "https://Stackoverflow.com/users/20336874",
"pm_score": 3,
"selected": true,
"text": "sort_list"
},
{
"answer_id": 74356040,
"author": "Shamshirsaz.Navid",
"author_id": 2227070,
"author_profile": "https://Stackoverflow.com/users/2227070",
"pm_score": 1,
"selected": false,
"text": "def full_sort(d):\n if type(d) == type({}):\n return {k: full_sort(v) for (k, v) in sorted(d.items())}\n elif type(d) == type([]):\n return sorted(d)\n return d\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355749",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12031497/"
] |
74,355,756 | <p>Sorry this topic has been covered many times. However, I just created a new rails 7 app using esbuild, added font-awesome-sass to the gem file, created application.css.scss (already had application.bootstrap.scss) and put "@import 'font-awesome';" in there.</p>
<p>I then added the following to a view page:</p>
<pre><code> <i class="fa-sharp fa-solid fa-house"></i>
<%= icon 'fa-brands', 'font-awesome' %>
</code></pre>
<p>No page errors, no console errors---but, the icons are not visible on the page (code is in the source). I've been mindlessly trying to figure this out---but, can not figure out why this is not working.</p>
<p>Have I missed any step?</p>
<p>I've verified installation instructions for the gem, I also tried skipping the gem and installing fontawesome via yarn. Nothing has gotten icons to show up in the view.</p>
| [
{
"answer_id": 74356920,
"author": "Lee Drum",
"author_id": 17457026,
"author_profile": "https://Stackoverflow.com/users/17457026",
"pm_score": 1,
"selected": false,
"text": "rails _7.0.4_ new demo-rails-with-react-frontend -j esbuild"
},
{
"answer_id": 74360023,
"author": "Bouaik Lhoussaine",
"author_id": 14887562,
"author_profile": "https://Stackoverflow.com/users/14887562",
"pm_score": 0,
"selected": false,
"text": "yarn add @fortawesome/fontawesome-free\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1156973/"
] |
74,355,782 | <p>can you please check my code? I think something is wrong somewhere.</p>
<pre><code>
import datetime
this_year = datetime.datetime.today().year
def age_in_minutes(b_year: int):
d1 = datetime.datetime.strptime(f'{this_year}', '%Y')
d2 = datetime.datetime.strptime(f'{b_year}', '%Y')
age = (d1-d2).days * 24 * 60
return f"{age:,}"
while True:
birth_year = input("Enter you birth year: ")
try:
if int(birth_year) == this_year:
print("Please enter year less than this year...")
elif int(birth_year) > this_year:
print("Please enter year less than this year...")
elif len(birth_year) < 4 or len(birth_year) > 5:
print("PLease enter a valid year...")
elif int(birth_year) <= 1900:
print("Please enter a year after 1900...")
else:
minutes_old = age_in_minutes(int(birth_year))
print(f"You are {minutes_old} minutes old.")
break
except ValueError:
print("Please enter in a year format: ")
</code></pre>
<p>I'm tackling a challenge. It said if I enter 1930, I should get "<strong>48,355,200</strong>". But I'm getting "<strong>48,388,320</strong>". I'm new to Python.</p>
| [
{
"answer_id": 74356920,
"author": "Lee Drum",
"author_id": 17457026,
"author_profile": "https://Stackoverflow.com/users/17457026",
"pm_score": 1,
"selected": false,
"text": "rails _7.0.4_ new demo-rails-with-react-frontend -j esbuild"
},
{
"answer_id": 74360023,
"author": "Bouaik Lhoussaine",
"author_id": 14887562,
"author_profile": "https://Stackoverflow.com/users/14887562",
"pm_score": 0,
"selected": false,
"text": "yarn add @fortawesome/fontawesome-free\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20446052/"
] |
74,355,812 | <p>I'm getting a token from Azure KeyVault. I setup the keyvault in Program.cs file. It works as long as the Azure account in Visual Studio got access. obviously once that account doesn't have access, an error is thrown.</p>
<p>How do I skip setting up the key vault in case it's development env AND get token value from appsettings.json? I don't want the app to fail because the account is not authorized and also get token value provided by the user in appsettings.json.</p>
<pre><code> public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.ConfigureAppConfiguration((context, config) =>
{
var builtConfig = config.Build();
var vaultConfigSection = builtConfig.GetSection("AzureOne");
var vaultUri = vaultConfigSection.GetValue<string>("KeyVaultUri");
var secretClient = new SecretClient(new Uri(vaultUri), new DefaultAzureCredential());
config.AddAzureKeyVault(secretClient, new KeyVaultSecretManager());
});
}
</code></pre>
<p>my appsettings.json look like this</p>
<pre><code>{
"EndPoints": {
"EndpointOne": "https://awesome.net"
},
"AzureOne": {
"TokenToBeUsedInDev": "4234-fake-234234-fake",
"KeyVaultUri": "https://myKeyVaultName.vault.azure.net/"
},
}
</code></pre>
<p>I'm using .NET 5</p>
| [
{
"answer_id": 74356920,
"author": "Lee Drum",
"author_id": 17457026,
"author_profile": "https://Stackoverflow.com/users/17457026",
"pm_score": 1,
"selected": false,
"text": "rails _7.0.4_ new demo-rails-with-react-frontend -j esbuild"
},
{
"answer_id": 74360023,
"author": "Bouaik Lhoussaine",
"author_id": 14887562,
"author_profile": "https://Stackoverflow.com/users/14887562",
"pm_score": 0,
"selected": false,
"text": "yarn add @fortawesome/fontawesome-free\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17460932/"
] |
74,355,834 | <p>I want to get the locator of this element (5,126,
601) but seem cant get it normally.</p>
<p>I think it will have to hover the mouse to the element and try to get the xpath but still I cant hover my mouse into it because it an SVG element . Any one know a way to get the locator properly?<br />
here is the link to the website: <a href="https://fundingsocieties.com/progress" rel="nofollow noreferrer">https://fundingsocieties.com/progress</a></p>
<p><a href="https://i.stack.imgur.com/7m69H.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7m69H.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74357280,
"author": "Prophet",
"author_id": 3485434,
"author_profile": "https://Stackoverflow.com/users/3485434",
"pm_score": 2,
"selected": false,
"text": "\"//*[name()='text']//*[name()='tspan' and(contains(@style,'bold'))]\"\n"
},
{
"answer_id": 74361003,
"author": "Easty77",
"author_id": 2070127,
"author_profile": "https://Stackoverflow.com/users/2070127",
"pm_score": 2,
"selected": true,
"text": "url=\"https://fundingsocieties.com/progress\"\ndriver.get(url)\nchart = WebDriverWait(driver, 10).until(\n EC.presence_of_element_located((By.XPATH, \"//div[@data-highcharts-chart='0']\"))\n )\nmarkers = chart.find_elements(By.XPATH, \"//*[local-name()='g'][contains(@class,'highcharts-markers')]/*[local-name()='path']\")\nfor m in markers:\n m.click()\n try:\n element = WebDriverWait(driver, 2).until(\n EC.presence_of_element_located((By.XPATH, \"//*[local-name()='g'][contains(@class,'highcharts-label')]/*[local-name()='text']\"))\n )\n tspans = element.find_elements(By.XPATH, \"./*[local-name()='tspan']\")\n if len(tspans) > 3: \n print (\"%s = %s\" % (tspans[0].text, tspans[3].text))\n except TimeoutException:\n pass \n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13973541/"
] |
74,355,847 | <p>How can I approach sorting with an Optional?</p>
<p>Both <code>mainProducts</code> or <code>productSublist</code> in the code below maybe <code>null</code>. The resulting list <code>productSubList</code> should be sorted by Date.</p>
<pre><code>List<ProductSubList> productSubList = Optional.of(mainProducts)
.map(MainProducts::getProductSubList)
.ifPresent(list -> list.stream().sorted(Comparator.comparing(ProductSubList::getProductDate))
.collect(Collectors.toList()));
</code></pre>
<p>The code shown above produces a <strong>compilation error</strong>:</p>
<blockquote>
<p>Required type: ProductSubList ; Provided:void</p>
</blockquote>
<p><strong>Part Answer which seems too long, is there a way to make this shorter?</strong></p>
<pre><code> if (Optional.of(mainProducts).map(MainProducts::getProductSubList).isPresent()) {
productSublist = mainProducts.getProductSubList().stream()
.sorted(Comparator.comparing(ProductSubList::getProductDate))
.collect(Collectors.toList());
}
</code></pre>
<p><strong>Resource</strong>: <a href="https://stackoverflow.com/questions/49380052/how-to-avoid-checking-for-null-values-in-method-chaining">How to avoid checking for null values in method chaining?</a></p>
| [
{
"answer_id": 74357280,
"author": "Prophet",
"author_id": 3485434,
"author_profile": "https://Stackoverflow.com/users/3485434",
"pm_score": 2,
"selected": false,
"text": "\"//*[name()='text']//*[name()='tspan' and(contains(@style,'bold'))]\"\n"
},
{
"answer_id": 74361003,
"author": "Easty77",
"author_id": 2070127,
"author_profile": "https://Stackoverflow.com/users/2070127",
"pm_score": 2,
"selected": true,
"text": "url=\"https://fundingsocieties.com/progress\"\ndriver.get(url)\nchart = WebDriverWait(driver, 10).until(\n EC.presence_of_element_located((By.XPATH, \"//div[@data-highcharts-chart='0']\"))\n )\nmarkers = chart.find_elements(By.XPATH, \"//*[local-name()='g'][contains(@class,'highcharts-markers')]/*[local-name()='path']\")\nfor m in markers:\n m.click()\n try:\n element = WebDriverWait(driver, 2).until(\n EC.presence_of_element_located((By.XPATH, \"//*[local-name()='g'][contains(@class,'highcharts-label')]/*[local-name()='text']\"))\n )\n tspans = element.find_elements(By.XPATH, \"./*[local-name()='tspan']\")\n if len(tspans) > 3: \n print (\"%s = %s\" % (tspans[0].text, tspans[3].text))\n except TimeoutException:\n pass \n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15435022/"
] |
74,355,848 | <p><a href="https://i.stack.imgur.com/S19Rb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/S19Rb.png" alt="open a file in python tkinter app" /></a></p>
<pre><code>import sys
sys. argv[1]
</code></pre>
<p>is the code equivalent of the above image. Please reply me</p>
| [
{
"answer_id": 74357280,
"author": "Prophet",
"author_id": 3485434,
"author_profile": "https://Stackoverflow.com/users/3485434",
"pm_score": 2,
"selected": false,
"text": "\"//*[name()='text']//*[name()='tspan' and(contains(@style,'bold'))]\"\n"
},
{
"answer_id": 74361003,
"author": "Easty77",
"author_id": 2070127,
"author_profile": "https://Stackoverflow.com/users/2070127",
"pm_score": 2,
"selected": true,
"text": "url=\"https://fundingsocieties.com/progress\"\ndriver.get(url)\nchart = WebDriverWait(driver, 10).until(\n EC.presence_of_element_located((By.XPATH, \"//div[@data-highcharts-chart='0']\"))\n )\nmarkers = chart.find_elements(By.XPATH, \"//*[local-name()='g'][contains(@class,'highcharts-markers')]/*[local-name()='path']\")\nfor m in markers:\n m.click()\n try:\n element = WebDriverWait(driver, 2).until(\n EC.presence_of_element_located((By.XPATH, \"//*[local-name()='g'][contains(@class,'highcharts-label')]/*[local-name()='text']\"))\n )\n tspans = element.find_elements(By.XPATH, \"./*[local-name()='tspan']\")\n if len(tspans) > 3: \n print (\"%s = %s\" % (tspans[0].text, tspans[3].text))\n except TimeoutException:\n pass \n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15585008/"
] |
74,355,864 | <p>I'm getting a axios code 404 error on my front end part, here is the code</p>
<pre><code> const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const submitHandler = async (e) => {
e.preventDefault();
try {
console.log(username, password)
const { data } = await axios.post('/api/users/signin', {
username,
password,
});
console.log(data);
} catch (error) {
console.log(error);
}
}
</code></pre>
<p>i'm getting POST http://localhost:3000/api/users/signin 404 (Not Found), axios request failed with status 404. Though I used that api using the rest client in VScode and i'm getting the response that I expect but somehow when i tried to use it on my frontend part im getting the error.</p>
<p>I also used a
"proxy": "http://localhost:5000",
in my package.json file</p>
| [
{
"answer_id": 74357280,
"author": "Prophet",
"author_id": 3485434,
"author_profile": "https://Stackoverflow.com/users/3485434",
"pm_score": 2,
"selected": false,
"text": "\"//*[name()='text']//*[name()='tspan' and(contains(@style,'bold'))]\"\n"
},
{
"answer_id": 74361003,
"author": "Easty77",
"author_id": 2070127,
"author_profile": "https://Stackoverflow.com/users/2070127",
"pm_score": 2,
"selected": true,
"text": "url=\"https://fundingsocieties.com/progress\"\ndriver.get(url)\nchart = WebDriverWait(driver, 10).until(\n EC.presence_of_element_located((By.XPATH, \"//div[@data-highcharts-chart='0']\"))\n )\nmarkers = chart.find_elements(By.XPATH, \"//*[local-name()='g'][contains(@class,'highcharts-markers')]/*[local-name()='path']\")\nfor m in markers:\n m.click()\n try:\n element = WebDriverWait(driver, 2).until(\n EC.presence_of_element_located((By.XPATH, \"//*[local-name()='g'][contains(@class,'highcharts-label')]/*[local-name()='text']\"))\n )\n tspans = element.find_elements(By.XPATH, \"./*[local-name()='tspan']\")\n if len(tspans) > 3: \n print (\"%s = %s\" % (tspans[0].text, tspans[3].text))\n except TimeoutException:\n pass \n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18150722/"
] |
74,355,872 | <p>I've got a pandas DataFrame that looks like this:</p>
<pre><code> molecule species
0 a dog
1 b horse
2 c []
3 d pig
4 e []
</code></pre>
<p>I want to replace the <code>[]</code> value with <code>NaN</code> using python. How can I achieve this?</p>
<p>For testing:</p>
<pre><code>df = pd.DataFrame({
'molecule': ['a','b','c','d','e'],
'species' : ['horse','cat','[]','frog','lion']})
</code></pre>
| [
{
"answer_id": 74355908,
"author": "assume_irrational_is_rational",
"author_id": 11622508,
"author_profile": "https://Stackoverflow.com/users/11622508",
"pm_score": 1,
"selected": false,
"text": "import numpy as np\ndf = pd.DataFrame({'molecule': ['a','b','c','d','e'], 'species' : ['horse','cat','[]','frog','lion']})\ndf[\"species\"].replace({\"[]\":np.nan})\n"
},
{
"answer_id": 74355968,
"author": "Mehmaam",
"author_id": 19350100,
"author_profile": "https://Stackoverflow.com/users/19350100",
"pm_score": 0,
"selected": false,
"text": "DataFrame.mask()"
},
{
"answer_id": 74356178,
"author": "Алексей Р",
"author_id": 15035314,
"author_profile": "https://Stackoverflow.com/users/15035314",
"pm_score": 0,
"selected": false,
"text": "df.loc[df.species.eq('[]'), 'species'] = np.nan\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13536375/"
] |
74,355,880 | <p>I try to get the row where email is as in the session variable using the following code in my controller.</p>
<pre><code> $usermodel = new \App\Models\UserModel();
$user=$usermodel->where('email', $session->get('email'))->find();
</code></pre>
<p>I do not get the proper result. Instead of getting the row containing the email in session variable, I get an empty array as result. However when i try to get all the content using findAll without filtering using email, I get the result showing all content. How can I get a filtered result with the row containing the specified email in session variable.
I checked if the session variable contains value and it was found to have the correct value.</p>
<p>My model</p>
<pre><code><?php namespace App\Models;
use CodeIgniter\Database\ConnectionInterface;
use CodeIgniter\Model;
class UserModel extends Model
{
protected $table = 'tbl_user';
protected $allowedFields = ['name','email','password','image','role_id','isActive','date_created'];
}
</code></pre>
<p>Please help</p>
<p>I tried to get the row containing the email
But I get an empty array</p>
| [
{
"answer_id": 74355908,
"author": "assume_irrational_is_rational",
"author_id": 11622508,
"author_profile": "https://Stackoverflow.com/users/11622508",
"pm_score": 1,
"selected": false,
"text": "import numpy as np\ndf = pd.DataFrame({'molecule': ['a','b','c','d','e'], 'species' : ['horse','cat','[]','frog','lion']})\ndf[\"species\"].replace({\"[]\":np.nan})\n"
},
{
"answer_id": 74355968,
"author": "Mehmaam",
"author_id": 19350100,
"author_profile": "https://Stackoverflow.com/users/19350100",
"pm_score": 0,
"selected": false,
"text": "DataFrame.mask()"
},
{
"answer_id": 74356178,
"author": "Алексей Р",
"author_id": 15035314,
"author_profile": "https://Stackoverflow.com/users/15035314",
"pm_score": 0,
"selected": false,
"text": "df.loc[df.species.eq('[]'), 'species'] = np.nan\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20439651/"
] |
74,355,891 | <p>I am trying to make a typing effect, and its a very simple logic,,,but still i am not able to understand that why the 'e' in hello is always missing everything else is working fine. have not made the blinking cursor yet !!!!</p>
<p><strong>CODE:</strong></p>
<pre><code>import { useState } from "react";
export function Type() {
let str = "hello my name is prateek"
const [char, setChar] = useState("");
function type() {
let i = 0;
let id = setInterval(() => {
setChar(prev => prev + str[i]);
//console.log(i,"i")
// console.log(str[i])
i++;
if (i === str.length - 1) {
//console.log("hello")
clearInterval(id)
}
}, 1000);
}
return (<div>
<h1>{char}</h1>
<button onClick={type}>Type</button>
</div>)
}
</code></pre>
<p><strong>OUTPUT</strong></p>
<pre><code>hllo my name is prateek
</code></pre>
| [
{
"answer_id": 74356545,
"author": "Anh Le Hoang",
"author_id": 16315750,
"author_profile": "https://Stackoverflow.com/users/16315750",
"pm_score": 1,
"selected": false,
"text": "Type function"
},
{
"answer_id": 74356634,
"author": "stealththeninja",
"author_id": 3294944,
"author_profile": "https://Stackoverflow.com/users/3294944",
"pm_score": 3,
"selected": false,
"text": "dispatcher"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20446115/"
] |
74,355,904 | <p>I have very large scale dataframe with 100,000 rows and 300 columns</p>
<p>and I'm trying to fill out Nan rows in one columns by extracting the values from the other columns</p>
<p>here is the example,</p>
<p>let's say we have a sample dataframe such as:</p>
<pre><code> NAME RRN_FRONT RRN_BACK EVENT_DTL
1 JOHN 891105 1067714 Nan
2 SHOWN 791134 1156543 Nan
3 BROWN 581104 1668314 Nan
4 MIKE 984564 0153422 1. Name : MIKE
2. BIRTHDAY : 984564
3. SSN : 0153422
5 LARRY 796515 0168165 1. Name : LARRY
2. BIRTHDAY : 796515
3. SSN : 0168165
</code></pre>
<p>and I want to fill out Nan values with the NAME, RRN_FRONT, RRN_BACK</p>
<p>Here is the input that I tried:</p>
<pre><code>df.loc[df.EVENT_DTL.isnull(), 'EVENT_DTL'] = df.apply(lambda x: ('1. NAME : ' + str(x['NAME']) + '\n2. BIRTHDAY : ' + str(x['RRN_FRONT']) + '\n3. SSN : ' + str(x['RRN_BACK']),axis=1)
</code></pre>
<p>and the output is(which is not what I intended):</p>
<pre><code>1. NAME : JOHN2. \nBIRTHDAY : 8911053. \nSSN : 1067714
2. ...
.
.
5. ...
</code></pre>
<p>Here is the desired output of <code>df['EVENT_DTL']</code>:</p>
<pre><code>1 1. NAME : JOHN
2. BIRTHDAY : 8911053
3. SSN : 1156543
2 1. NAME : SHOWN
2. BIRTHDAY : 791134
3. SSN : 1156543
3 ‥
4 ‥
5 ‥
</code></pre>
| [
{
"answer_id": 74356545,
"author": "Anh Le Hoang",
"author_id": 16315750,
"author_profile": "https://Stackoverflow.com/users/16315750",
"pm_score": 1,
"selected": false,
"text": "Type function"
},
{
"answer_id": 74356634,
"author": "stealththeninja",
"author_id": 3294944,
"author_profile": "https://Stackoverflow.com/users/3294944",
"pm_score": 3,
"selected": false,
"text": "dispatcher"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20376341/"
] |
74,355,906 | <p>Discord bots can have a <a href="https://support.discord.com/hc/en-us/articles/360040720412-Bot-Verification-and-Data-Whitelisting" rel="nofollow noreferrer">Verified check mark</a>. Is there a way to check if a Discord bot is verified using Discord.js?</p>
<p><a href="https://i.stack.imgur.com/qyHjG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qyHjG.png" alt="The first bot is not verified, second is" /></a></p>
<p>I'm doing this mainly to avoid raids or nuke bots</p>
<pre class="lang-js prettyprint-override"><code>client.on('guildMemberAdd', member => {
if (member.user.bot) {
// if is verified:
// member.roles.add("<BOT_ROLE_ID>")
// else:
// member.ban(...)
}
})
</code></pre>
<p>And if it can't be done using Discord.js, then is there another way using the <code>member.user.id</code> property or something else?</p>
<p>Update: <a href="https://discord.com/developers/docs/resources/user#user-object-user-flags" rel="nofollow noreferrer">user flags</a> may be the answer</p>
| [
{
"answer_id": 74357837,
"author": "Ansh Tyagi",
"author_id": 15023927,
"author_profile": "https://Stackoverflow.com/users/15023927",
"pm_score": 0,
"selected": false,
"text": "client.on('guildMemberAdd', member => {\n if (member.user.bot) {\n if is member.user.verified:\n member.roles.add(\"<BOT_ROLE_ID>\")\n else:\n member.ban(...)\n }\n})\n"
},
{
"answer_id": 74364576,
"author": "Zsolt Meszaros",
"author_id": 6126373,
"author_profile": "https://Stackoverflow.com/users/6126373",
"pm_score": 3,
"selected": true,
"text": "User#flags"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18114046/"
] |
74,355,913 | <p>I have a dropdown in Navbar at right side, when I click on it, its menus are opening far right even not visible until I scroll horizontally.</p>
<p>This is my code</p>
<pre><code><nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<div style="margin-bottom: 0px;" class="navbar-header justify-content-start">
<a class="navbar-brand" href="#">
<img width="100" src="assets/Acc_logo.png" alt="logo">
</a>
</div>
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" data-toggle="dropdown" type="button"
aria-haspopup="true" id="dropdownMenuButton" aria-expanded="false">
<div class="divIcom"></div>
<div class="divIcom"></div>
<div class="divIcom"></div>
</button>
<ul class="dropdown-menu dropdown-menu-sm-right" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<a class="dropdown-item" href="#">Something else here</a>
</ul>
</div>
</div>
</nav>
</code></pre>
<p>also some css added</p>
<pre><code>li {
list-style-type: none;
}
.divIcom {
width: 30px;
height: 3px;
background-color: gray;
margin: 6px 0;
}
.dropdown-toggle::after {
display:none;
}
</code></pre>
<p>Styles I am using in <code>angular.json</code></p>
<pre><code> "styles": [
"./node_modules/bootstrap/dist/css/bootstrap.min.css",
"./node_modules/bootstrap-icons/font/bootstrap-icons.css",
"src/styles.css"
],
"scripts": [
"./node_modules/jquery/dist/jquery.min.js",
"./node_modules/popper.js/dist/umd/popper.min.js",
"./node_modules/bootstrap/dist/js/bootstrap.min.js",
"./node_modules/bootstrap/dist/js/bootstrap.bundle.min.js",
"./node_modules/chart.js/dist/Chart.min.js"
]
},
</code></pre>
<p><a href="https://i.stack.imgur.com/quoud.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/quoud.png" alt="enter image description here" /></a></p>
<p><strong>Edit 1</strong> -</p>
<pre><code>zone.js:1711 Uncaught TypeError: i.createPopper is not a function
at Mt._createPopper (node_modules\bootstrap\dist\js\bootstrap.min.js:6:23961)
at Mt.show (node_modules\bootstrap\dist\js\bootstrap.min.js:6:22277)
at Mt.toggle (node_modules\bootstrap\dist\js\bootstrap.min.js:6:22073)
at HTMLButtonElement.<anonymous> (node_modules\bootstrap\dist\js\bootstrap.min.js:6:26705)
at HTMLDocument.s (node_modules\bootstrap\dist\js\bootstrap.min.js:6:4456)
at _ZoneDelegate.invokeTask (zone.js:406:31)
at Zone.runTask (zone.js:178:47)
at ZoneTask.invokeTask [as invoke] (zone.js:487:34)
at invokeTask (zone.js:1661:18)
at globalCallback (zone.js:1704:33)
</code></pre>
<p>How can I fix it ?</p>
| [
{
"answer_id": 74355954,
"author": "Junaid Shaikh",
"author_id": 17033432,
"author_profile": "https://Stackoverflow.com/users/17033432",
"pm_score": 0,
"selected": false,
"text": "dropdown-menu-sm-right"
},
{
"answer_id": 74358459,
"author": "traynor",
"author_id": 4321299,
"author_profile": "https://Stackoverflow.com/users/4321299",
"pm_score": 2,
"selected": true,
"text": "dropdown-menu-sm-end"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8977696/"
] |
74,355,921 | <p>I am new to pygame. Whenever I press the key "Delete". It prints "key" continuously. I only want it to print it only one time. How can I do this ?</p>
<pre><code>import pygame
import sys
sprite = "sprite_1.jpg"
position = (20,0)
canvas = pygame.display.set_mode((952, 592))
color = (255,255,255)
exit = False
back = pygame.image.load("th.jpg").convert_alpha()
back = pygame.transform.scale(back, (952,592))
Sprite = pygame.image.load(sprite)
Sprite.set_colorkey((255,255,255))
Sprite = pygame.transform.scale(Sprite, (35,35))
pygame.display.set_caption("Game")
while not exit:
canvas.fill(color)
canvas.blit(back, dest = (0,0))
canvas.blit(Sprite, dest=position)
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit = True
if (event.type == pygame.KEYDOWN):
if (event.key == pygame.K_DELETE):
print("hi")
pygame.display.update()
</code></pre>
<p>Please tell the solution. Thanks in advance</p>
| [
{
"answer_id": 74356153,
"author": "Rabbid76",
"author_id": 5577765,
"author_profile": "https://Stackoverflow.com/users/5577765",
"pm_score": 1,
"selected": false,
"text": "while not exit:\n canvas.fill(color)\n canvas.blit(back, dest = (0,0))\n canvas.blit(Sprite, dest=position)\n \n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n exit = True\n \n # INDENTATION \n #-->| \n if (event.type == pygame.KEYDOWN):\n if (event.key == pygame.K_DELETE):\n print(\"hi\")\n\n pygame.display.update()\n"
},
{
"answer_id": 74356264,
"author": "ly_jade",
"author_id": 16323291,
"author_profile": "https://Stackoverflow.com/users/16323291",
"pm_score": 0,
"selected": false,
"text": "enter code herecanvas.fill(color)\ncanvas.blit(back, dest = (0,0))\ncanvas.blit(Sprite, dest=position)\n\nfor event in pygame.event.get():\n if event.type == pygame.QUIT:\n exit = True\n \n if (event.type == pygame.KEYDOWN):\n if count<=0: \n if (event.key == pygame.K_DELETE):\n print(\"hi\")\n else:\n continue\n\npygame.display.update()\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20200872/"
] |
74,355,989 | <p>I have a problem displaying errors message in update modal form. I'm using laravel request for validation and AJAX to submit form inside a modal. I would like to see the error message for each field that are inputted incorrectly. However, I'm getting this error:</p>
<blockquote>
<p>The Given data is invalid</p>
</blockquote>
<p>I checked the network tab, and I'm seeing the errors there but I can't figure out why this is not showing in my fields.</p>
<p>Here is my script's</p>
<pre class="lang-js prettyprint-override"><code>function updatePassword(e, t)
{
e.preventDefault();
const url = BASE_URL + '/admin/organizations/operators/updatePassword/' + $(updatePasswordForm).find("input[name='id']").val();
var form_data = $(t).serialize();
// loading('show');
axios.post(url, form_data)
.then(response => {
notify(response.data.message, 'success');
$(updatePasswordModal).modal('hide');
// roleTable.ajax.reload()
})
.catch(error => {
const response = error.response;
if (response) {
if (response.status === 422)
validationForm(updatePasswordForm, response.data.errors);
else if(response.status === 404)
notify('Not found', 'error');
else
notify(response.data.message, 'error');
}
})
.finally(() => {
// loading('hide');
});
}
</code></pre>
<p>Here is my Blade file</p>
<pre class="lang-html prettyprint-override"><code><form id="updatePasswordForm" onsubmit="updatePassword(event, this)">
<input type="hidden" name="id" value="">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel"> {{ __('Update Password') }}</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<div class="form-group row">
<label class="col-sm-4 col-form-label required">{{ __('New Password') }}</label>
<div class="col-sm-8">
<div class="row">
<div class="col-sm-12">
<div class="form-group @error('user.password') error @enderror">
<input type="password" class="form-control" id="password" name="user[password]" placeholder="{{ __('Password') }}" required>
</div>
</div>
</div>
@error('user.password')
<p class="error-message">{{ $message }}</p>
@enderror
</div>
</div>
<div class="form-group row">
<label class="col-sm-4 col-form-label required">{{ __('Confirm Password') }}</label>
<div class="col-sm-8">
<div class="row">
<div class="col-sm-12">
<div class="form-group @error('user.password_confirmation') error @enderror">
<input type="password" class="form-control" id="confirmPassword" name="user[password_confirmation]" placeholder="{{ __('Confirm Password') }}">
</div>
</div>
</div>
@error('user.password_confirmation')
<p class="error-message">{{ $message }}</p>
@enderror
</div>
</div>
</div>
<div class="modal-footer justify-content-center">
<button type="button" class="btn btn-secondary mr-3" data-dismiss="modal">{{ __('Close') }}</button>
<button type="submit" class="btn btn-primary">{{ __('Save') }} </button>
</div>
</div>
</form>
</code></pre>
<p>Here is My Controller:</p>
<pre class="lang-php prettyprint-override"><code><?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Organization\Operator\UpdatePasswordRequest;
use App\Models\OrganizationOperator;
use Illuminate\Http\Request;
use App\Services\Response;
use Exception;
use Illuminate\Support\Facades\Log;
class OrganizationController extends Controller
{
public function updateOperatorPassword(OrganizationOperator $operator, UpdatePasswordRequest $request)
{
try {
$data = $request->validated();
$user = $data['user'];
// dd($user['password']);
$operator->update([
'password' => bcrypt($user['password']),
]);
return Response::success(__('Successfully updated'));
} catch (Exception $e) {
Log::error($e->getMessage());
return Response::error(__('Unable to update'), [], 500);
}
}
}
</code></pre>
<p>Here is my Request Validation Class:</p>
<pre><code><?php
namespace App\Http\Requests\Admin\Organization\Operator;
use Illuminate\Foundation\Http\FormRequest;
class UpdatePasswordRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, mixed>
*/
public function rules()
{
return [
'id' => ['required', 'integer', 'exists:organization_operators,id'],
'user.password' => ['required', 'string', 'min:8', 'confirmed'],
];
}
}
</code></pre>
| [
{
"answer_id": 74356153,
"author": "Rabbid76",
"author_id": 5577765,
"author_profile": "https://Stackoverflow.com/users/5577765",
"pm_score": 1,
"selected": false,
"text": "while not exit:\n canvas.fill(color)\n canvas.blit(back, dest = (0,0))\n canvas.blit(Sprite, dest=position)\n \n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n exit = True\n \n # INDENTATION \n #-->| \n if (event.type == pygame.KEYDOWN):\n if (event.key == pygame.K_DELETE):\n print(\"hi\")\n\n pygame.display.update()\n"
},
{
"answer_id": 74356264,
"author": "ly_jade",
"author_id": 16323291,
"author_profile": "https://Stackoverflow.com/users/16323291",
"pm_score": 0,
"selected": false,
"text": "enter code herecanvas.fill(color)\ncanvas.blit(back, dest = (0,0))\ncanvas.blit(Sprite, dest=position)\n\nfor event in pygame.event.get():\n if event.type == pygame.QUIT:\n exit = True\n \n if (event.type == pygame.KEYDOWN):\n if count<=0: \n if (event.key == pygame.K_DELETE):\n print(\"hi\")\n else:\n continue\n\npygame.display.update()\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74355989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10418084/"
] |
74,356,017 | <p>might be a dumb beginner question but When I run my code:</p>
<pre><code>function love.draw()
love.graphics.print("Hello World", 400, 300)
end
function love.load()
20, 20, 60, 20
end
</code></pre>
<p>it give me the error message:Error</p>
<p>Syntax error: main.lua:5: unexpected symbol near '20'</p>
<p>Traceback</p>
<p>[love "callbacks.lua"]:228: in function 'handler'</p>
<p>[C]: at 0x7fff3e0d31d0</p>
<p>[C]: in function 'require'</p>
<p>[C]: in function 'xpcall'</p>
<p>[C]: in function 'xpcall'</p>
<p>I just wanna add values</p>
| [
{
"answer_id": 74356152,
"author": "Dan Bonachea",
"author_id": 3528321,
"author_profile": "https://Stackoverflow.com/users/3528321",
"pm_score": 2,
"selected": true,
"text": "love.load"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20446226/"
] |
74,356,020 | <p>I need some help trying to figure out a way to make an if statement taking the users input after a category is typed in. If the user types in string categories[0] in the cin statement, which in this case is "Number of drivers involved in fatal collisions per billion miles." I want it to display the first sentence from the worststate[0] array, which in this case will be North Dakota and South Carolina. I need help doing that for every category, to match up with the state listed, it goes in order.</p>
<pre><code>#include <iostream>
using namespace std;
string worstState[7] = {
{"North Dakota and South Carolina"},
{"Hawaii"},
{"Montana"},
{"District of Columbia"},
{"District of Columbia and Mississippi"},
{"New Jersey"},
{"Louisiana"},
};
void displayIntro(){
cout << "Welcome to the Car Accident Statistic Website" << endl;
cout << "Take a look at the following categories: " << endl;
}
string categories[7] = {
{"Number of drivers involved in fatal collisions per billion miles"},
{"Percentage of drivers involved in fatal collisions who were speeding"},
{"Percentage of drivers involved in fatal collisions who were Alcohol-Impaired"},
{"Percentage of drivers involved in fatal collisions who were not distracted"},
{"Percentage of drivers involved in fatal collisions who had not been involved in any previous accidents"},
{"Car Insurance Premiums"},
{"Losses incurred by insurance companies for collisions per insured driver"},
};
</code></pre>
<p>int main(){</p>
<pre><code>string Input;
displayIntro();
cout << categories[0] << endl;
cout << categories[1] << endl;
cout << categories[2] << endl;
cout << categories[3] << endl;
cout << categories[4] << endl;
cout << categories[5] << endl;
cout << categories[6] << endl;
cout << "Enter a category: ";
cin >> Input;
if (Input == categories....
return 0;
}
</code></pre>
<p>Obviously the code isn't the best organized, which I'm still gonna work on, but I just want the user to type in the category string, and for the state to match up with that specific category in the categories array, all in order based on the way they are entered.</p>
<p>Wondering what the best way to go about this situation is</p>
| [
{
"answer_id": 74356103,
"author": "chen",
"author_id": 20064859,
"author_profile": "https://Stackoverflow.com/users/20064859",
"pm_score": 0,
"selected": false,
"text": "for(int i = 0; i < size(categories); i++){\n if(Input == categories[i]){\n cout << worstState[i] << endl;\n }\n}\n"
},
{
"answer_id": 74356154,
"author": "selbie",
"author_id": 104458,
"author_profile": "https://Stackoverflow.com/users/104458",
"pm_score": 1,
"selected": false,
"text": "unordered_map<string, string> questionsToAnswers;\n\nfor (size_t i = 0; i < 7; i++) {\n questionsToAnswers[categories[i]] = worstState[i];\n}\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,356,036 | <p><strong>ProductTable.js</strong></p>
<p>import React, { useEffect, useState } from "react";</p>
<pre><code>function ProductTable() {
useEffect(() => {
fetchData();
}
const fetchData = () => {
axios
.get("http://localhost:4000/api/products/product/viewAllProduct")
.then((res) => {
const getData = res.data.data;
console.log(getData);
setData(getData);
});
};
return ( jsx..)
}
export default ProductTable;
</code></pre>
<p>**ProductModals.js
**</p>
<pre><code>``import React, { useEffect, useState } from "react";
function ProductModals(){
const handleSubmit=()=>{
.....
}
return (jsx..)
export default productModals;`
</code></pre>
<p><strong>viewProduct.js</strong></p>
<pre><code>import React, { useEffect, useState } from "react";
import ProductTable from "../../Components/Tables/Product/ProductTable";
import ProductModals from "../../Components/Modals/Product/ProductModals";
function viewProduct(){
return(
<productModals/>
<productTable/>
)
}
export default viewProduct;
</code></pre>
<p>I need to to get <strong>fetchData</strong>function from <strong>productTable.js</strong> component to <strong>productModal.js</strong> component. both components parent component is <strong>viewProduct.js</strong>. I tried many ways. but could not work. In <strong>productModal.js</strong> component has a function for form submit , when form submit done I need to call <strong>fetchData</strong> function, If anyone know the way please help me</p>
| [
{
"answer_id": 74356103,
"author": "chen",
"author_id": 20064859,
"author_profile": "https://Stackoverflow.com/users/20064859",
"pm_score": 0,
"selected": false,
"text": "for(int i = 0; i < size(categories); i++){\n if(Input == categories[i]){\n cout << worstState[i] << endl;\n }\n}\n"
},
{
"answer_id": 74356154,
"author": "selbie",
"author_id": 104458,
"author_profile": "https://Stackoverflow.com/users/104458",
"pm_score": 1,
"selected": false,
"text": "unordered_map<string, string> questionsToAnswers;\n\nfor (size_t i = 0; i < 7; i++) {\n questionsToAnswers[categories[i]] = worstState[i];\n}\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20355754/"
] |
74,356,038 | <p>This is my main urls.py:</p>
<pre><code>urlpatterns = [
path('admin/', admin.site.urls),
path('', include("shop.urls")),
]
</code></pre>
<p>I want that any url entered by user will redirect to shop.urls and find there
like if the user enters <strong>/index</strong> it will search index in shop.urls not in main urls.</p>
<p>My shop.urls:</p>
<pre><code>from django.urls import path
from . import views
urlpatterns = [
path('', views.index),
path('index', views.index),
]
</code></pre>
<p><a href="https://i.stack.imgur.com/NASYF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NASYF.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74356103,
"author": "chen",
"author_id": 20064859,
"author_profile": "https://Stackoverflow.com/users/20064859",
"pm_score": 0,
"selected": false,
"text": "for(int i = 0; i < size(categories); i++){\n if(Input == categories[i]){\n cout << worstState[i] << endl;\n }\n}\n"
},
{
"answer_id": 74356154,
"author": "selbie",
"author_id": 104458,
"author_profile": "https://Stackoverflow.com/users/104458",
"pm_score": 1,
"selected": false,
"text": "unordered_map<string, string> questionsToAnswers;\n\nfor (size_t i = 0; i < 7; i++) {\n questionsToAnswers[categories[i]] = worstState[i];\n}\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16527878/"
] |
74,356,063 | <p>this is the code</p>
<pre><code>@page "/"
@using Newtonsoft.Json
@using System.Text.Json
@using System.Text.Json.Serialization
<h1>Hello World</h1>
@code {
public class Account
{
public string Email { get; set; }
public bool Active { get; set; }
public DateTime CreatedDate { get; set; }
public IList<string> Roles { get; set; }
}
Account account = new Account
{
Email = "james@example.com",
Active = true,
CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc),
Roles = new List<string>
{
"User",
"Admin"
}
};
string json = JsonConvert.SerializeObject(account, Formatting.Indented);
}
</code></pre>
<p>this is the error:</p>
<p><code>error CS0236: A field initializer cannot reference the non-static field, method, or property 'Index.account'</code></p>
<p>I am just learning Blazor. I am expecting the project to build.</p>
| [
{
"answer_id": 74356164,
"author": "Natrium",
"author_id": 59119,
"author_profile": "https://Stackoverflow.com/users/59119",
"pm_score": 3,
"selected": true,
"text": "@code {\n\n public class Account\n {\n public string Email { get; set; }\n public bool Active { get; set; }\n public DateTime CreatedDate { get; set; }\n public IList<string> Roles { get; set; }\n }\n\n public Index()\n {\n Account account = new Account\n {\n Email = \"james@example.com\",\n Active = true,\n CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc),\n Roles = new List<string>\n {\n \"User\",\n \"Admin\"\n }\n };\n\n string json = JsonConvert.SerializeObject(account, Formatting.Indented);\n }\n\n}\n"
},
{
"answer_id": 74358214,
"author": "Marvin Klein",
"author_id": 13440841,
"author_profile": "https://Stackoverflow.com/users/13440841",
"pm_score": 1,
"selected": false,
"text": "IList"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20446282/"
] |
74,356,143 | <pre><code>int main() {
int choice;
printf("\n----------Welcome to Coffee Shop----------");
printf("\n\n\t1. Login ");
printf("\n\t2. Sign Up ");
printf("\n\nPlease enter 1 or 2: ");
scanf(" %d", &choice);
system("cls||clear");
//put while loop to check
switch (choice) {
case 1:
system("cls||clear");
login();
break;
case 2:
system("cls||clear");
user_signup();
break;
default:
printf("\nInvalid Number\n");
main();
break;
}
return 0;
}
</code></pre>
<p>How do i make user retype their input if the input is not int?
I tried to use isdigit() but it wont work, May i know what are the solutions?</p>
| [
{
"answer_id": 74356192,
"author": "sirosi",
"author_id": 20446397,
"author_profile": "https://Stackoverflow.com/users/20446397",
"pm_score": 1,
"selected": false,
"text": "int main() {\n int choice;\n char chars[100];\n printf(\"\\n----------Welcome to Coffee Shop----------\");\n printf(\"\\n\\n\\t1. Login \");\n printf(\"\\n\\t2. Sign Up \");\n printf(\"\\n\\nPlease enter 1 or 2: \");\n scanf(\" %s\", chars);\n choice = stringToInteger(chars);\n system(\"cls||clear\");\n\n //put while loop to check\n switch (choice) {\n case 1:\n system(\"cls||clear\");\n login();\n break;\n case 2:\n system(\"cls||clear\");\n user_signup();\n break;\n default:\n printf(\"\\nInvalid Number\\n\");\n main();\n break;\n }\n\n return 0;\n}\n\nint stringToInteger(char* chars)\n{\n int i = 0, number = 0;\n\n while(chars[i] >= '0' && chars[i] <= '9')\n {\n number = chars[i++] - '0' + number * 10;\n }\n\n return number;\n}\n"
},
{
"answer_id": 74356211,
"author": "Support Ukraine",
"author_id": 4386427,
"author_profile": "https://Stackoverflow.com/users/4386427",
"pm_score": 1,
"selected": false,
"text": "scanf"
},
{
"answer_id": 74356223,
"author": "Özgür Murat Sağdıçoğlu",
"author_id": 5106317,
"author_profile": "https://Stackoverflow.com/users/5106317",
"pm_score": 0,
"selected": false,
"text": "scanf()"
},
{
"answer_id": 74364695,
"author": "Anthony Kelly",
"author_id": 20410405,
"author_profile": "https://Stackoverflow.com/users/20410405",
"pm_score": 0,
"selected": false,
"text": "main()"
},
{
"answer_id": 74364884,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 1,
"selected": false,
"text": "scanf(\" %d\", &choice);"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16687807/"
] |
74,356,147 | <p>I have 3 related tables; user, movie and score:</p>
<p>*<strong>User:</strong></p>
<pre><code>id | name |
--------------
1 | Hans |
2 | Carry |
</code></pre>
<br/>
<p>*<strong>Movie:</strong></p>
<pre><code>id | name | budget |
----------------------
101 | Mov 1 | 200 |
102 | Mov 2 | 500 |
103 | Mov 2 | 300 |
</code></pre>
<br/>
<p>*<strong>Score:</strong></p>
<pre><code>user_id | movie_id | score |
--------------------------------
1 | 101 | 7 |
2 | 101 | 8 |
1 | 102 | 6 |
2 | 102 | 9 |
</code></pre>
<br/>
<p>I am trying to find the 5 movies whose average score is max and then sort these movies based on their budget. So, is that possible using Java Stream? How can I get this kind of list?</p>
<p>Or if it is not possible, should I use Query and retrieve data from projection?</p>
| [
{
"answer_id": 74356192,
"author": "sirosi",
"author_id": 20446397,
"author_profile": "https://Stackoverflow.com/users/20446397",
"pm_score": 1,
"selected": false,
"text": "int main() {\n int choice;\n char chars[100];\n printf(\"\\n----------Welcome to Coffee Shop----------\");\n printf(\"\\n\\n\\t1. Login \");\n printf(\"\\n\\t2. Sign Up \");\n printf(\"\\n\\nPlease enter 1 or 2: \");\n scanf(\" %s\", chars);\n choice = stringToInteger(chars);\n system(\"cls||clear\");\n\n //put while loop to check\n switch (choice) {\n case 1:\n system(\"cls||clear\");\n login();\n break;\n case 2:\n system(\"cls||clear\");\n user_signup();\n break;\n default:\n printf(\"\\nInvalid Number\\n\");\n main();\n break;\n }\n\n return 0;\n}\n\nint stringToInteger(char* chars)\n{\n int i = 0, number = 0;\n\n while(chars[i] >= '0' && chars[i] <= '9')\n {\n number = chars[i++] - '0' + number * 10;\n }\n\n return number;\n}\n"
},
{
"answer_id": 74356211,
"author": "Support Ukraine",
"author_id": 4386427,
"author_profile": "https://Stackoverflow.com/users/4386427",
"pm_score": 1,
"selected": false,
"text": "scanf"
},
{
"answer_id": 74356223,
"author": "Özgür Murat Sağdıçoğlu",
"author_id": 5106317,
"author_profile": "https://Stackoverflow.com/users/5106317",
"pm_score": 0,
"selected": false,
"text": "scanf()"
},
{
"answer_id": 74364695,
"author": "Anthony Kelly",
"author_id": 20410405,
"author_profile": "https://Stackoverflow.com/users/20410405",
"pm_score": 0,
"selected": false,
"text": "main()"
},
{
"answer_id": 74364884,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 1,
"selected": false,
"text": "scanf(\" %d\", &choice);"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20409000/"
] |
74,356,183 | <p>I have below code sample, if i create Cart object , im getting Items list as NULL.</p>
<pre class="lang-java prettyprint-override"><code>@Data
class Cart{
int cartId;
List<Item> items;
}
@Data
class Item{
int itemId;
String itemName;
}
public class Test {
public static void main(String[] args) {
Cart cart = new Cart();
System.out.println(cart); // Cart(cartId=0, items=null)
}
}
</code></pre>
<p>How can i create Cart object with Items as empty list {}, instead of NULL.</p>
<p>If my class has 10 no.of List Items, How can we create Cart Object with empty list.</p>
<p>Can we create with ObjectMapper or any other API ?</p>
| [
{
"answer_id": 74356192,
"author": "sirosi",
"author_id": 20446397,
"author_profile": "https://Stackoverflow.com/users/20446397",
"pm_score": 1,
"selected": false,
"text": "int main() {\n int choice;\n char chars[100];\n printf(\"\\n----------Welcome to Coffee Shop----------\");\n printf(\"\\n\\n\\t1. Login \");\n printf(\"\\n\\t2. Sign Up \");\n printf(\"\\n\\nPlease enter 1 or 2: \");\n scanf(\" %s\", chars);\n choice = stringToInteger(chars);\n system(\"cls||clear\");\n\n //put while loop to check\n switch (choice) {\n case 1:\n system(\"cls||clear\");\n login();\n break;\n case 2:\n system(\"cls||clear\");\n user_signup();\n break;\n default:\n printf(\"\\nInvalid Number\\n\");\n main();\n break;\n }\n\n return 0;\n}\n\nint stringToInteger(char* chars)\n{\n int i = 0, number = 0;\n\n while(chars[i] >= '0' && chars[i] <= '9')\n {\n number = chars[i++] - '0' + number * 10;\n }\n\n return number;\n}\n"
},
{
"answer_id": 74356211,
"author": "Support Ukraine",
"author_id": 4386427,
"author_profile": "https://Stackoverflow.com/users/4386427",
"pm_score": 1,
"selected": false,
"text": "scanf"
},
{
"answer_id": 74356223,
"author": "Özgür Murat Sağdıçoğlu",
"author_id": 5106317,
"author_profile": "https://Stackoverflow.com/users/5106317",
"pm_score": 0,
"selected": false,
"text": "scanf()"
},
{
"answer_id": 74364695,
"author": "Anthony Kelly",
"author_id": 20410405,
"author_profile": "https://Stackoverflow.com/users/20410405",
"pm_score": 0,
"selected": false,
"text": "main()"
},
{
"answer_id": 74364884,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 1,
"selected": false,
"text": "scanf(\" %d\", &choice);"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17188780/"
] |
74,356,208 | <p>Just learning how maven and spring boot works so i've been practicing a little bit by doing simple projects. But i've run into an issue of my swagger-ui.html giving me an error of 404 not found.</p>
<p>What i've added in my pom.xml for swagger-ui.</p>
<p>`</p>
<pre><code><dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.0.0-M4</version>
</dependency>
</code></pre>
<p>`</p>
<p>My entire project code is available <a href="https://github.com/aakhoja/restful-web-services" rel="nofollow noreferrer">here</a></p>
<p>Doing little bit of google search I found some solutions that haven't helped me with my project yet.</p>
<p>Things i've added :</p>
<p>@EnableMvc
@Configuration</p>
<p>in my main controller class. After adding these two annotations, my error displayed a different error. Pasting below :</p>
<p><code> Error creating bean with name 'org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration': Unsatisfied dependency expressed through method 'setConfigurers' parameter 0;</code></p>
<p>I've also tried added numerous other dependencies like</p>
<p>`</p>
<pre><code><dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>3.0.0</version>
</dependency>
</code></pre>
<p><code> </code></p>
<pre><code><dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
</code></pre>
<p>`</p>
<p>Any help would be greatly appreciated!</p>
| [
{
"answer_id": 74356943,
"author": "Jilliss",
"author_id": 12523079,
"author_profile": "https://Stackoverflow.com/users/12523079",
"pm_score": 0,
"selected": false,
"text": "pom.xml"
},
{
"answer_id": 74380656,
"author": "codelife",
"author_id": 20287877,
"author_profile": "https://Stackoverflow.com/users/20287877",
"pm_score": 0,
"selected": false,
"text": "<parent>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-parent</artifactId>\n <version>3.0.0-M4</version>\n <relativePath/> <!-- lookup parent from repository -->\n</parent>\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20287877/"
] |
74,356,221 | <p>I'm running into a weird error when trying to install pip
This is the sequence that I typed into my command line:
pip install opencv-python
What could be causing this?</p>
<p>This is what I get when I type in <code>echo %PATH%</code>:</p>
<p><code>C:\Program Files (x86)\Common Files\Intel\Shared Libraries\redist\intel64\compiler;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0;C:\Windows\System32\OpenSSH;C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\170\Tools\Binn;C:\Program Files (x86)\Microsoft SQL Server\150\Tools\Binn;C:\Program Files\Microsoft SQL Server\150\Tools\Binn;C:\Program Files\Microsoft SQL Server\150\DTS\Binn;C:\Program Files (x86)\Microsoft SQL Server\150\DTS\Binn;C:\Program Files\Java\jdk1.7.0_80\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0;C:\WINDOWS\System32\OpenSSH;C:\Program Files\dotnet;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;E:\MATLAB\R2022b\bin;D:\nodejs;:\users\“naglaa“\AppData\Programs\Python\Python310;C:\Program Files (x86)\Common Files\Intel\Shared Libraries\redist\intel64\compiler;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0;C:\Windows\System32\OpenSSH;C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\170\Tools\Binn;C:\Program Files (x86)\Microsoft SQL Server\150\Tools\Binn;C:\Program Files\Microsoft SQL Server\150\Tools\Binn;C:\Program Files\Microsoft SQL Server\150\DTS\Binn;C:\Program Files (x86)\Microsoft SQL Server\150\DTS\Binn;C:\Program Files\Java\jdk1.7.0_80\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0;C:\WINDOWS\System32\OpenSSH;C:\Program Files\dotnet;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;E:\MATLAB\R2022b\bin;D:\nodejs;:\users\“naglaa“\AppData\Programs\Python\Python310;C:\Users\naglaa\AppData\Local\Microsoft\WindowsApps;;C:\Program Files\Azure Data Studio\bin;C:\Users\naglaa</code></p>
| [
{
"answer_id": 74356308,
"author": "Mark Tolonen",
"author_id": 235698,
"author_profile": "https://Stackoverflow.com/users/235698",
"pm_score": 2,
"selected": true,
"text": "“naglaa“"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18741914/"
] |
74,356,229 | <p>I want dynamic gradients in Tailwinds, eg:</p>
<pre><code>className={`bg-gradient-to-b from-[${gradientStart}] to-[${gradientEnd}]`}
</code></pre>
<p>but I notice some colours come up invisible sometimes. If I explicitly hardcode the colours, refresh the browser, and then revert the change, the colours show up. Any idea why this is happening and how to fix?</p>
| [
{
"answer_id": 74356285,
"author": "caTS",
"author_id": 18244921,
"author_profile": "https://Stackoverflow.com/users/18244921",
"pm_score": 1,
"selected": false,
"text": "<div class=\"text-{{ error ? 'red' : 'green' }}-600\"></div>\n"
},
{
"answer_id": 74356309,
"author": "MagnusEffect",
"author_id": 10962364,
"author_profile": "https://Stackoverflow.com/users/10962364",
"pm_score": 0,
"selected": false,
"text": "`bg-gradient-to-b from-[${gradientStart}] to-[${gradientEnd}]`\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16514593/"
] |
74,356,272 | <p>The main function of this code is that when Firestore upload porocess end, then change the page to HomePage.
But my ".then" code is inactivate.</p>
<p>[Code]</p>
<pre><code> await Firestore.instance.collection('post').add(
{
'contents': textEditingController.text,
'displayName': widget.user.displayName,
'email': widget.user.email,
'photoUrl': downloadUrl,
'userPhotoUrl': widget.user.photoUrl,
});
} else {
await Firestore.instance.collection('post').add({
'contents': textEditingController.text,
'displayName': widget.user.displayName,
'email': widget.user.email,
'photoUrl': 'https://firebasestorage.googleapis.com/v0/b/woonsancommunity2-c95f8.appspot.com/o/post%2FNo%20IMG.001.png?alt=media&token=47a39955-39a0-447f-8846-d89149f40ee3',
'userPhotoUrl': widget.user.photoUrl,
}).then(() {
Navigator.push(
context, MaterialPageRoute(builder:(context) =>
HomePage(widget.user)),
);
});
}
</code></pre>
<p>In this situation, .then code is inactivate.(Gray Font Color)..
Plase help me!</p>
<p><a href="https://i.stack.imgur.com/XXAm5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XXAm5.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74356285,
"author": "caTS",
"author_id": 18244921,
"author_profile": "https://Stackoverflow.com/users/18244921",
"pm_score": 1,
"selected": false,
"text": "<div class=\"text-{{ error ? 'red' : 'green' }}-600\"></div>\n"
},
{
"answer_id": 74356309,
"author": "MagnusEffect",
"author_id": 10962364,
"author_profile": "https://Stackoverflow.com/users/10962364",
"pm_score": 0,
"selected": false,
"text": "`bg-gradient-to-b from-[${gradientStart}] to-[${gradientEnd}]`\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19711930/"
] |
74,356,294 | <p>I have an array of,</p>
<p><img src="https://i.stack.imgur.com/NWA4c.jpg" alt="enter image description here" /></p>
<p>I am trying to convert that to a JSON , so I can bind the data in a bootstrap table like this,</p>
<pre><code>import "bootstrap/dist/css/bootstrap.min.css";
import Table from "react-bootstrap/Table";
function Home() {
const customers = [
{
CustomerId: 1,
Name: "John Hammond",
Country: "United States",
},
{
CustomerId: 2,
Name: "Mudassar Khan",
Country: "India",
},
{
CustomerId: 3,
Name: "Suzanne Mathews",
Country: "France",
},
{
CustomerId: 4,
Name: "Robert Schidner",
Country: "Russia",
},
];
return (
<div className="container">
<div className="row">
<div className="col-12">
<Table striped bordered hover size="sm">
<thead>
<tr>
<th>File Name</th>
<th>Username</th>
</tr>
</thead>
<tbody>
{customers.map(customers=>
<tr>
<td>{customers.Name}</td>
<td>{customers.Country}</td>
</tr>
)}
</tbody>
</Table>
</div>
</div>
</div>
);
}
export default Home;
</code></pre>
<p>Like in this example, they are binding Name and country from customers, I want to bind path data and mode data from the array and bind to the table.</p>
<p>I tried JSON.stringify but it is not working. How to do this?</p>
<p>This is the full code</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>import "bootstrap/dist/css/bootstrap.min.css";
import Table from "react-bootstrap/Table";
import { Octokit } from "octokit";
function Home() {
getContents();
let jsonString = '';
const customers = [
{
CustomerId: 1,
Name: "John Hammond",
Country: "United States",
},
{
CustomerId: 2,
Name: "Mudassar Khan",
Country: "India",
},
{
CustomerId: 3,
Name: "Suzanne Mathews",
Country: "France",
},
{
CustomerId: 4,
Name: "Robert Schidner",
Country: "Russia",
},
];
let contentResponse = "";
let valueArray = [];
async function getContents() {
try {
return await new Promise(async (resolve, reject) => {
try {
const octokit = new Octokit({
auth: "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",
});
const response = await octokit.request(
"GET /repos/KaranS0406/React/git/trees/4c1289a6405a5d87de6f1071ce723ee8b94be276?recursive=1"
);
console.log(response.data.tree);
contentResponse = response.data.tree;
Object.entries(contentResponse).forEach((element) => {
const [key, value] = element;
valueArray.push(value);
});
resolve("success");
} catch (error) {
reject("error");
}
});
} catch (error) {
console.log(error);
}
}
return (
<div className="container">
<div className="row">
<div className="col-12">
<Table striped bordered hover size="sm">
<thead>
<tr>
<th>File Name</th>
<th>Username</th>
</tr>
</thead>
<tbody>
{customers.map(customers=>
<tr>
<td>{customers.Name}</td>
<td>{customers.Country}</td>
</tr>
)}
</tbody>
</Table>
</div>
</div>
</div>
);
}
export default Home;</code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74356418,
"author": "Meet Majevadiya",
"author_id": 16697937,
"author_profile": "https://Stackoverflow.com/users/16697937",
"pm_score": 2,
"selected": true,
"text": "const convertdata = contentResponse.map((item) =>{\n let obj={\n Name:item.path,\n Country:item.mode\n }\n})"
},
{
"answer_id": 74356459,
"author": "Javito",
"author_id": 9681386,
"author_profile": "https://Stackoverflow.com/users/9681386",
"pm_score": 0,
"selected": false,
"text": "customers"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19672461/"
] |
74,356,307 | <p>I use Visual Studio Code. I noticed that, compared to PyCharm, it has a lack in the project folder explorer on the left. The case is this:</p>
<p>I open a folder, then I open its subfolders. Then I close the parent folder, but when I reopen the parent folder there are still the subfolders open. I'm not talking about the main project folder, but about the folders inside it (with subfolders)</p>
<p>Is there a way to automatically close and scroll all open subfolders ... if I close the parent folder?</p>
| [
{
"answer_id": 74356418,
"author": "Meet Majevadiya",
"author_id": 16697937,
"author_profile": "https://Stackoverflow.com/users/16697937",
"pm_score": 2,
"selected": true,
"text": "const convertdata = contentResponse.map((item) =>{\n let obj={\n Name:item.path,\n Country:item.mode\n }\n})"
},
{
"answer_id": 74356459,
"author": "Javito",
"author_id": 9681386,
"author_profile": "https://Stackoverflow.com/users/9681386",
"pm_score": 0,
"selected": false,
"text": "customers"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18313765/"
] |
74,356,407 | <p>I need the current system date and time in 2022-10-03T19:45:47.844Z format in a java class.</p>
<p>I tried using the zoneddatetime and simple date format but couldn't get the write syntax or code from online. I'm beginner in Java, any help is appreciated.
Thanks.</p>
| [
{
"answer_id": 74356572,
"author": "bryson",
"author_id": 20423423,
"author_profile": "https://Stackoverflow.com/users/20423423",
"pm_score": 3,
"selected": true,
"text": "import java.time.ZoneId;\nimport java.time.ZonedDateTime;\nimport java.time.format.DateTimeFormatter;\n\npublic class Main {\n public static void main(String[] args) {\n ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of(\"UTC\"));\n DateTimeFormatter formatter =\n DateTimeFormatter.ofPattern(\"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'\");\n System.out.println(zdt.format(formatter));\n }\n}\n"
},
{
"answer_id": 74356822,
"author": "Basil Bourque",
"author_id": 642706,
"author_profile": "https://Stackoverflow.com/users/642706",
"pm_score": 2,
"selected": false,
"text": "Instant.now().toString()\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20446428/"
] |
74,356,463 | <p>I want to run multiple <code>HostedServices</code> that inject an <code>IAnimal</code> each. How can I make sure that 5 distinct instances of a <code>HostedService</code> run for each <code>IAnimal</code> I have?</p>
<p>At the moment I'm doing the following, but it feels dirty:</p>
<p><strong>AnimalDependencyResolver.cs</strong></p>
<pre><code>public interface IDependencyResolver<out TResolve>
{
TResolve GetDependency();
}
public class AnimalDependencyResolver : IDependencyResolver<IAnimal>
{
private int _currentIndex = 0;
private readonly int _animalCount = 0;
private readonly IEnumerable<IAnimal> _animals;
public AnimalDependencyResolver(IEnumerable<IAnimal> animals)
{
_animals = animals;
_animalCount = _animals.Count();
}
public IAnimal GetDependency()
{
if (_animalCount <= 0 || _currentIndex >= _animalCount)
throw new InvalidOperationException("Sequence contains no (more) elements");
return _animals.ElementAt(_currentIndex++);
}
}
</code></pre>
<p><strong>Program.cs</strong></p>
<pre><code>services.AddSingleton<IHostedService, AnimalService>();
services.AddSingleton<IHostedService, AnimalService>();
services.AddSingleton<IHostedService, AnimalService>();
services.AddSingleton<IHostedService, AnimalService>();
services.AddSingleton<IHostedService, AnimalService>();
services.AddScoped<IAnimal, MajesticSeaFlapFlap>();
services.AddScoped<IAnimal, TrashPanda>();
services.AddScoped<IAnimal, FartSquirrel>();
services.AddScoped<IAnimal, DangerFloof>();
services.AddScoped<IAnimal, NopeRope>();
services.AddSingleton<IDependencyResolver<IAnimal>, AnimalDependencyResolver>();
</code></pre>
<p><strong>AnimalService.cs</strong></p>
<pre><code>public AnimalService(ILogger<AnimalService> logger, IDependencyResolver<IAnimal> animalResolver)
{
_logger = logger;
_animal = animalResolver.GetDependency();
}
</code></pre>
<p>Help is appreciated.</p>
| [
{
"answer_id": 74356572,
"author": "bryson",
"author_id": 20423423,
"author_profile": "https://Stackoverflow.com/users/20423423",
"pm_score": 3,
"selected": true,
"text": "import java.time.ZoneId;\nimport java.time.ZonedDateTime;\nimport java.time.format.DateTimeFormatter;\n\npublic class Main {\n public static void main(String[] args) {\n ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of(\"UTC\"));\n DateTimeFormatter formatter =\n DateTimeFormatter.ofPattern(\"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'\");\n System.out.println(zdt.format(formatter));\n }\n}\n"
},
{
"answer_id": 74356822,
"author": "Basil Bourque",
"author_id": 642706,
"author_profile": "https://Stackoverflow.com/users/642706",
"pm_score": 2,
"selected": false,
"text": "Instant.now().toString()\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3973081/"
] |
74,356,466 | <p>I am trying to download an attachment from outlook with a specific Subject line. It shows finished, but no attachment is getting downloaded. Below attached is my code, kindly help if I am missing something.</p>
<pre><code># import libraries
import win32com.client
import re
import datetime
import pathlib2 as pathlib
# set up connection to outlook
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
message = messages.GetFirst()
today_date = str(datetime.date.today())
while True:
try:
current_sender = str(message.Sender).lower()
current_subject = str(message.Subject).lower()
# find the email from a specific sender with a specific subject
# condition
if re.search('AllSalons was executed at',current_subject) != None:
#if re.search('AllSalons was executed at',current_subject) != None and re.search(sender_name,current_sender) != None:
print(current_subject) # verify the subject
print(current_sender) # verify the sender
attachments = message.Attachments
attachment = attachments.Item(1)
attachment_name = str(attachment).lower()
attachment.SaveASFile(pathlib.path + 'C:\\Users\\UserTest\\Desktop\\Folder\\Subject Line\\Nov' + attachment_name)
else:
pass
message = messages.GetNext()
except:
message = messages.GetNext()
break
print("Finished")
</code></pre>
| [
{
"answer_id": 74356572,
"author": "bryson",
"author_id": 20423423,
"author_profile": "https://Stackoverflow.com/users/20423423",
"pm_score": 3,
"selected": true,
"text": "import java.time.ZoneId;\nimport java.time.ZonedDateTime;\nimport java.time.format.DateTimeFormatter;\n\npublic class Main {\n public static void main(String[] args) {\n ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of(\"UTC\"));\n DateTimeFormatter formatter =\n DateTimeFormatter.ofPattern(\"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'\");\n System.out.println(zdt.format(formatter));\n }\n}\n"
},
{
"answer_id": 74356822,
"author": "Basil Bourque",
"author_id": 642706,
"author_profile": "https://Stackoverflow.com/users/642706",
"pm_score": 2,
"selected": false,
"text": "Instant.now().toString()\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20087562/"
] |
74,356,525 | <p>I'm trying to figure out how to target a specific variable product in woocommerce to show this message underneath the "Add to cart" button. The current code is showing for all variable product type.</p>
<p>`</p>
<pre><code>add_action( 'woocommerce_after_add_to_cart_button', 'custom_product_message' , 10, 0 );
function custom_product_message() {
global $product;
if( ! $product->is_type( 'variable' )) return; // Only for variable products
echo '<div class="woo_variable_custom_message">Hello</div>';
}
</code></pre>
<p>`</p>
<p>This is the snippet I am working on.`</p>
<pre><code>add_action( 'woocommerce_after_add_to_cart_button', 'custom_product_message' , 10, 0 );
function custom_product_message() {
global $product;
if( ! $product->is_type( 'variable' )) return; // Only for variable products
echo '<div class="woo_variable_custom_message">Hello</div>';
}
</code></pre>
<p>`</p>
| [
{
"answer_id": 74356627,
"author": "Aj G",
"author_id": 16418782,
"author_profile": "https://Stackoverflow.com/users/16418782",
"pm_score": 2,
"selected": true,
"text": "add_action( 'woocommerce_after_add_to_cart_button', 'custom_product_message', 20 );\n \n function custom_product_message() {\n if ( is_single( '8941' )) {\n echo '<div class=\"woo_variable_custom_message\">Hello</div>';\n }\n } \n"
},
{
"answer_id": 74358224,
"author": "Kairav Thakar",
"author_id": 20447312,
"author_profile": "https://Stackoverflow.com/users/20447312",
"pm_score": 2,
"selected": false,
"text": "add_action( 'woocommerce_after_add_to_cart_button', 'custom_product_message', 20 );\n \n function custom_product_message() {\n global $product;\n\n $getcustomText = get_post_meta(post_id, 'meta_key', true);\n if ( !empty ($getcustomText)) {\n echo '<div class=\"woo_variable_custom_message\">Hello</div>';\n }\n }\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16418782/"
] |
74,356,567 | <p>I'm writing this program that reads in a fasta file to do some stuff with. The format of fasta file is like this:</p>
<pre><code>> This line with ">" is the header, want to skip/ignore this line
These lines below the header has sequence information we want
ATTGGTATGATTTACCCAATTTGGGGAAAAAATTCCCTCTCGATAGCTATCCTGATTTGCGG
ATTGGTATGATTTACCCAATTTGGGGAAAAAATTCCCTCTCGATAGCTATCCTGATTTGCGG
ATTGGTATGATTTACCCAATTTGGGGAAAAAATTCCCTCTCGATAGCTATCCTGATTTGCGG
</code></pre>
<p>Ideally the program I have should read in the fasta file skip the header line and inputting the sequence below into a string. My code does this except at the very end it leaves of the last character. In the example above everything would be added except the last G of the last line.
Here is my code and an example file:</p>
<pre><code>void reading_in_RNA_file()
{
string RNA_file = "sample_query.txt";
ifstream fin;
fin.open(RNA_file);
if (!fin.is_open())
{//if
cerr << "Error did not open file" << endl;
exit(1);
}//if
string line = "";
string RNA_seq = "";
string FASTA_heading = "";
string sequence = "";
while(getline(fin,line))
{
if( line.empty() || line[0] == '>' )
{ // Identifier marker
if(!FASTA_heading.empty() )
{ // Print out what we read from the last entry
FASTA_heading.clear();
RNA_seq += sequence;
}
if( !line.empty() )
{
FASTA_heading = line.substr(1);
}
sequence.clear();
}
else if(!FASTA_heading.empty())
{
line = line.substr(0, line.length() -1);
if(line.find(' ') != string::npos )
{ // Invalid sequence--no spaces allowed
FASTA_heading.clear();
sequence.clear();
}
else
{
sequence += line;
}
}
}
if(!FASTA_heading.empty() )
{ // Print out what we read from the last entry
RNA_seq += sequence;
}
cout << RNA_seq << endl;
}
</code></pre>
<p>sample_query.txt fasta file!</p>
<pre><code>> true positive test query
GTCTGAGAAAACAAGGCTAGAGATTCCAATATTAGAGACAACAGGGCTCTGGGAAGATTAAGGTTGAGTT
TTCTGGATCTGCAGAATAGAGTCACTGAGGACCAATTGCAAGATCAGAGGAGATGAAAGAACAAGTCAAG
GCATGCTTAGGAAAAGAGAATATCAGGGATAGGTTTTAGGCAAGAGTCACACTGAGGAAGGGCAGGTTCT
ACATACAGTTTATCTTGGTACTGCCAAGTACCATTTGGGTCAGGATTTTGTCATTTAGATCCATATTTTT
CCTATATTTTTATCTGGTTCTTCCATCAGTTACTGAGAGAGCACTATTAATTCACCAGCTATAATTTTGG
ATTGTCAATTTCCTGCTTTTGTCTGTTGTTTTTGATTCACATACTTTGAGGCTCTGTGTGTGTGTGTAAT
</code></pre>
<p>anyone know why I'm having this issue??</p>
| [
{
"answer_id": 74356627,
"author": "Aj G",
"author_id": 16418782,
"author_profile": "https://Stackoverflow.com/users/16418782",
"pm_score": 2,
"selected": true,
"text": "add_action( 'woocommerce_after_add_to_cart_button', 'custom_product_message', 20 );\n \n function custom_product_message() {\n if ( is_single( '8941' )) {\n echo '<div class=\"woo_variable_custom_message\">Hello</div>';\n }\n } \n"
},
{
"answer_id": 74358224,
"author": "Kairav Thakar",
"author_id": 20447312,
"author_profile": "https://Stackoverflow.com/users/20447312",
"pm_score": 2,
"selected": false,
"text": "add_action( 'woocommerce_after_add_to_cart_button', 'custom_product_message', 20 );\n \n function custom_product_message() {\n global $product;\n\n $getcustomText = get_post_meta(post_id, 'meta_key', true);\n if ( !empty ($getcustomText)) {\n echo '<div class=\"woo_variable_custom_message\">Hello</div>';\n }\n }\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19960466/"
] |
74,356,568 | <p>I have two values to check if it's existed in my PostgreSQL. I also have columns named <code>ref_name, ref_surname</code>
for example:</p>
<pre><code>//this is the data//
name: John
Surname: Lee
//this is some queryset from django//
Employee.objects.filter(ref_name=name & ref_surname=Surname).exists()
</code></pre>
<p>I want to check if the data is already existed in my database. I have read the Queryset documentation and I can't find an answer. I'm open to any suggestion.</p>
| [
{
"answer_id": 74356802,
"author": "Albert Wijaya",
"author_id": 19570048,
"author_profile": "https://Stackoverflow.com/users/19570048",
"pm_score": 0,
"selected": false,
"text": "Employee.objects.filter(ref_name=name & ref_surname=Surname).exists()\n"
},
{
"answer_id": 74357632,
"author": "Md.Imam Hossain Roni",
"author_id": 6342245,
"author_profile": "https://Stackoverflow.com/users/6342245",
"pm_score": 1,
"selected": false,
"text": "Employee.objects.filter(ref_name=name, ref_surname=Surname).exists()\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19894724/"
] |
74,356,600 | <p>After research on strackoverflow I have written/coppied this function with help from others questions.</p>
<pre><code>function evenOrOdd() {
var value = [];
value = document.getElementById('evenField').value;
value = parseInt(value);
if(evenField != ""){
if(value%2==1){
console.log(`${value} is an odd number next 10 digit will be`);
for (var i = 1; i <= 10; i = i + 1){
value = value + 2;
document.getElementById('console-log').innerHTML = console.log(`Number ${i} is ${value}`);
}
}else{
console.log(`${value} is an even number next 10 digit will be`);
for (var i = 1; i <= 10; i = i + 1){
value = value + 2;
document.getElementById('console-log').innerHTML = console.log(`Number ${i} is ${value}`);
}
}
}else{
document.getElementById('console-log').innerHTML = "";
}
}
evenOrOdd(10)
</code></pre>
<p>An exemple of output for it when the user types 11 ( an odd number ) is:</p>
<pre><code>11 is an odd number next 10 digit will be
array-interger.js:10 Number 1 is 13
array-interger.js:10 Number 2 is 15
array-interger.js:10 Number 3 is 17
array-interger.js:10 Number 4 is 19
array-interger.js:10 Number 5 is 21
array-interger.js:10 Number 6 is 23
array-interger.js:10 Number 7 is 25
array-interger.js:10 Number 8 is 27
array-interger.js:10 Number 9 is 29
array-interger.js:10 Number 10 is 31
</code></pre>
<p>And for a even number is:</p>
<pre><code>12 is an even number next 10 digit will be
array-interger.js:16 Number 1 is 14
array-interger.js:16 Number 2 is 16
array-interger.js:16 Number 3 is 18
array-interger.js:16 Number 4 is 20
array-interger.js:16 Number 5 is 22
array-interger.js:16 Number 6 is 24
array-interger.js:16 Number 7 is 26
array-interger.js:16 Number 8 is 28
array-interger.js:16 Number 9 is 30
array-interger.js:16 Number 10 is 32
</code></pre>
<p>My question is how can I change it to print only even number after the user types an odd number?.
Optional, how can I display the console.log on inside a HTML tag?</p>
<p>HTML code:</p>
<pre><code><div class="container">
<div class="row justify-content-center align-items-center vh-100">
<div class="col-auto">
<h1>Evens or Odds Numbers</h1>
<form onsubmit="event.preventDefault();" name="form" method="POST">
<div class="mb-3">
<label for="evenField" class="form-label">Enter a number</label>
<input type="number" class="form-control" id="evenField" name="evenField" min="1" max="99">
<small id="console-log" class="text-success"></small>
</div>
<button class="btn btn-primary col-md-12"
onclick="evenOrOdd()">
Submit</button>
</form>
</div>
</div>
</div>
</code></pre>
<p>I've tried to change the line</p>
<p><code>value = value + 2;</code>
to</p>
<p><code>value = value + 1;</code>
But it is printing both odd and even numbers</p>
| [
{
"answer_id": 74357042,
"author": "Rohìt Jíndal",
"author_id": 4116300,
"author_profile": "https://Stackoverflow.com/users/4116300",
"pm_score": 0,
"selected": false,
"text": "function evenOrOdd(val) {\n let value = parseInt(val);\n if(value%2==1){\n console.log(`${value} is an odd number next 10 digit will be`);\n printNumbers(value);\n }else{\n console.log(`${value} is an even number next 10 digit will be`);\n printNumbers(value);\n }\n}\n\nfunction printNumbers(value) {\n for (var i = 1; i <= 10; i++){\n let n = value + i;\n console.log(`Number ${i} is ${n}`);\n value = value + 1\n }\n}\n\nevenOrOdd(11);"
},
{
"answer_id": 74357071,
"author": "jessica-98",
"author_id": 20261328,
"author_profile": "https://Stackoverflow.com/users/20261328",
"pm_score": 2,
"selected": true,
"text": "const evenOrOdd = () => {\n const value = parseInt(document.getElementById('evenField').value);\n if (value) {\n document.getElementById('console-log').innerHTML = \"<br />\" + `${value} is an ${ value % 2 == 1?'odd':'even'} number next 10 digit will be`\n\n const arr = [...Array(10).keys()];\n\n const result = arr.reduce((acc, item, index) => {\n const nextNum = index > 0 ? parseInt(acc[index]) + 2 : parseInt(acc) + 2;\n\n document.getElementById('console-log').innerHTML += \"<br />\" + `Number ${index+1} is ${acc[index]}`\n return [...acc, nextNum];\n }, [value + 1])\n } else {\n document.getElementById('console-log').innerHTML = ''\n }\n\n\n\n}"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11991686/"
] |
74,356,618 | <p>I could not find a proper solution to my problem yet. I'm using Spring Security Oauth2 resource server to authenticate my requests. And that works fine. But when tested with different scenario it is found that spring security returns with 403 instead of 401 if there is no <em><strong>Authorization</strong></em> header present or if there is Authorization header present but the value doesn't begin with <em><strong>Bearer</strong></em> .</p>
<pre><code>Spring Boot Starter - 2.6.7
Spring Boot Starter Security - 2.6.7
Spring Security Config & Web - 5.6.3
Spring Security Core - 5.3.19
Spring Boot Starter OAuth2 Resource Server - 2.6.7
Spring OAuth2 Resource Server - 5.6.3
</code></pre>
<p>I was referring to <a href="https://stackoverflow.com/a/72959024">this answer</a> and added below code for <em>BearerTokenAuthenticationEntryPoint</em>. The difference is I'm using introspection url instead jwt. But it doesn't help and that part doesn't get executed. If the Bearer token is present, then only it gets executed.</p>
<p>What am I missing here?</p>
<pre><code>import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class CustomResourceServerSecurityConfiguration {
@Value("${spring.security.oauth2.resourceserver.opaque-token.introspection-uri}")
String introspectionUri;
@Value("${spring.security.oauth2.resourceserver.opaque-token.client-id}")
String clientId;
@Value("${spring.security.oauth2.resourceserver.opaque-token.client-secret}")
String clientSecret;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated())
.oauth2ResourceServer(oauth2 -> oauth2
.opaqueToken(opaque -> opaque.introspectionUri(this.introspectionUri)
.introspectionClientCredentials(this.clientId, this.clientSecret))
.authenticationEntryPoint((request, response, exception) -> {
System.out.println("Authentication failed");
BearerTokenAuthenticationEntryPoint delegate = new BearerTokenAuthenticationEntryPoint();
delegate.commence(request, response, exception);
}))
.exceptionHandling(
(exceptions) -> exceptions.authenticationEntryPoint((request, response, exception) -> {
System.out.println("Authentication is required");
BearerTokenAuthenticationEntryPoint delegate = new BearerTokenAuthenticationEntryPoint();
delegate.commence(request, response, exception);
}));
return http.build();
}
}
</code></pre>
| [
{
"answer_id": 74357042,
"author": "Rohìt Jíndal",
"author_id": 4116300,
"author_profile": "https://Stackoverflow.com/users/4116300",
"pm_score": 0,
"selected": false,
"text": "function evenOrOdd(val) {\n let value = parseInt(val);\n if(value%2==1){\n console.log(`${value} is an odd number next 10 digit will be`);\n printNumbers(value);\n }else{\n console.log(`${value} is an even number next 10 digit will be`);\n printNumbers(value);\n }\n}\n\nfunction printNumbers(value) {\n for (var i = 1; i <= 10; i++){\n let n = value + i;\n console.log(`Number ${i} is ${n}`);\n value = value + 1\n }\n}\n\nevenOrOdd(11);"
},
{
"answer_id": 74357071,
"author": "jessica-98",
"author_id": 20261328,
"author_profile": "https://Stackoverflow.com/users/20261328",
"pm_score": 2,
"selected": true,
"text": "const evenOrOdd = () => {\n const value = parseInt(document.getElementById('evenField').value);\n if (value) {\n document.getElementById('console-log').innerHTML = \"<br />\" + `${value} is an ${ value % 2 == 1?'odd':'even'} number next 10 digit will be`\n\n const arr = [...Array(10).keys()];\n\n const result = arr.reduce((acc, item, index) => {\n const nextNum = index > 0 ? parseInt(acc[index]) + 2 : parseInt(acc) + 2;\n\n document.getElementById('console-log').innerHTML += \"<br />\" + `Number ${index+1} is ${acc[index]}`\n return [...acc, nextNum];\n }, [value + 1])\n } else {\n document.getElementById('console-log').innerHTML = ''\n }\n\n\n\n}"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2189617/"
] |
74,356,623 | <p>I have a component which has the following -</p>
<pre><code>{tree[treeType].count > 0 ? tree[treeType].count : null}
</code></pre>
<p>The aim of it is to show the count only when count is greater than 0 but <strong>it should be shown inside () these brackets</strong> If the count is 0 nothing should be shown</p>
<p>I have tried to go with - <code>({tree[treeType].count > 0 ? tree[treeType].count : null})</code> but this shows brackets no matter what and also this - <code>{tree[treeType].count > 0 ? (tree[treeType].count) : null}</code> but this gives error.</p>
<p>What should I do?</p>
| [
{
"answer_id": 74357042,
"author": "Rohìt Jíndal",
"author_id": 4116300,
"author_profile": "https://Stackoverflow.com/users/4116300",
"pm_score": 0,
"selected": false,
"text": "function evenOrOdd(val) {\n let value = parseInt(val);\n if(value%2==1){\n console.log(`${value} is an odd number next 10 digit will be`);\n printNumbers(value);\n }else{\n console.log(`${value} is an even number next 10 digit will be`);\n printNumbers(value);\n }\n}\n\nfunction printNumbers(value) {\n for (var i = 1; i <= 10; i++){\n let n = value + i;\n console.log(`Number ${i} is ${n}`);\n value = value + 1\n }\n}\n\nevenOrOdd(11);"
},
{
"answer_id": 74357071,
"author": "jessica-98",
"author_id": 20261328,
"author_profile": "https://Stackoverflow.com/users/20261328",
"pm_score": 2,
"selected": true,
"text": "const evenOrOdd = () => {\n const value = parseInt(document.getElementById('evenField').value);\n if (value) {\n document.getElementById('console-log').innerHTML = \"<br />\" + `${value} is an ${ value % 2 == 1?'odd':'even'} number next 10 digit will be`\n\n const arr = [...Array(10).keys()];\n\n const result = arr.reduce((acc, item, index) => {\n const nextNum = index > 0 ? parseInt(acc[index]) + 2 : parseInt(acc) + 2;\n\n document.getElementById('console-log').innerHTML += \"<br />\" + `Number ${index+1} is ${acc[index]}`\n return [...acc, nextNum];\n }, [value + 1])\n } else {\n document.getElementById('console-log').innerHTML = ''\n }\n\n\n\n}"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13796424/"
] |
74,356,629 | <p>I am building a weather app. In this app, I am showing the temperature value to the user. In this value, I want to make the temperature value and degree sign different sizes. Because when the degree sign is the same size as the temperature value it alters the center of the view.</p>
<p>I try the NSAttributedText way like this.</p>
<pre class="lang-swift prettyprint-override"><code> let attrString = NSMutableAttributedString(string: temperature.value,
attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 36)])
attrString.append(NSMutableAttributedString(string:"°",
attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18)]))
temperature = attrString
</code></pre>
<p>I try the Unicode version "\u{00B0}" of the degree sign too. It doesn't matter by the way.</p>
<p>The result was like this.
<a href="https://i.stack.imgur.com/wkRqn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wkRqn.png" alt="enter image description here" /></a></p>
<p>However, I want a result like this.
<a href="https://i.stack.imgur.com/FtqVx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FtqVx.png" alt="enter image description here" /></a></p>
<p>How can I achive to this look?
Thanks in advance</p>
| [
{
"answer_id": 74356995,
"author": "HangarRash",
"author_id": 20287183,
"author_profile": "https://Stackoverflow.com/users/20287183",
"pm_score": 1,
"selected": false,
"text": ".baselineOffset"
},
{
"answer_id": 74357753,
"author": "Noman Umar",
"author_id": 8769693,
"author_profile": "https://Stackoverflow.com/users/8769693",
"pm_score": 3,
"selected": true,
"text": "let attrString = NSMutableAttributedString(string: temperature.value,\n attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 36)])\n\n attrString.append(NSMutableAttributedString(string:\"°\",\n attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18),.baselineOffset: NSNumber(value: 18)]))\n temperature = attrString\n \n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16696205/"
] |
74,356,646 | <p>I have been using openresty nginx for simple request forwarding purpose, it is working as expected, i am forwarding each incoming request to another URL using below code :</p>
<pre><code> location /app/ {
proxy_pass https://example.com/abc/;
proxy_read_timeout 60s;
proxy_pass_header Server;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
add_header X-Frame-Options "SAMEORIGIN" always;
</code></pre>
<p>and i am logging each POST request with below code :</p>
<pre><code>server {
log_format post_logs '[$time_local] "$request" $status '
'$body_bytes_sent "$http_referer" '
'"$http_user_agent" [$request_body]';
}
location /app/ {
access_log logs/post.log post_logs;
}
</code></pre>
<p>Now my requirement is that before forwarding each request, i want to filter post request body data for specific string/keyword , it should only forwarded to proxy URL <a href="https://example.com/abc/" rel="nofollow noreferrer">https://example.com/abc/</a> if specific string/keyword is found in post data.</p>
<p>I did some research but did not find anything that helps me achieve this, can anyone help ?</p>
| [
{
"answer_id": 74356995,
"author": "HangarRash",
"author_id": 20287183,
"author_profile": "https://Stackoverflow.com/users/20287183",
"pm_score": 1,
"selected": false,
"text": ".baselineOffset"
},
{
"answer_id": 74357753,
"author": "Noman Umar",
"author_id": 8769693,
"author_profile": "https://Stackoverflow.com/users/8769693",
"pm_score": 3,
"selected": true,
"text": "let attrString = NSMutableAttributedString(string: temperature.value,\n attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 36)])\n\n attrString.append(NSMutableAttributedString(string:\"°\",\n attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18),.baselineOffset: NSNumber(value: 18)]))\n temperature = attrString\n \n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3782114/"
] |
74,356,669 | <p>Here is my function, where I need to add properties as <code>disabed</code> and <code>value</code> how to do that? also <code>validation</code> should be added if requried.</p>
<pre><code> formBuilder(form, props) {
let { required, disabled, value } = props;
const formControl = new FormControl();//how to add?
if (required) {
formControl.setValidators([
Validators.required,
this.validate.plainText,
]);
}
form.addControl(props.controlName, formControl);
}
</code></pre>
<p>getting props as:</p>
<pre><code> {
"controlName": "userName",
"validateType": "plainText",
"elementType": "text",
"placeHolder": "User Name 0",
"value": "sample",
"required": false,
"disabled": true,
"errors": {
"required": "User Name must required"
}
}
</code></pre>
| [
{
"answer_id": 74356789,
"author": "N.F.",
"author_id": 4052858,
"author_profile": "https://Stackoverflow.com/users/4052858",
"pm_score": 0,
"selected": false,
"text": " formBuilder(form, props) {\n let { required, disabled, value } = props;\n const formControl = new FormControl(value);//how to add?\n\n if (required) {\n formControl.setValidators([\n Validators.required,\n this.validate.plainText,\n ]);\n }\n\n if (disabled) {\n formcontrol.disable();\n }\n\n form.addControl(props.controlName, formControl);\n }\n"
},
{
"answer_id": 74357543,
"author": "MGX",
"author_id": 20059754,
"author_profile": "https://Stackoverflow.com/users/20059754",
"pm_score": 2,
"selected": false,
"text": "formBuilder(form, props) {\n const { required, disabled, value } = props;\n const validators = [this.validate.plainText];\n if (required) validators.push(Validators.required);\n const formControl = new FormControl({ value, disabled }, validators);\n form.addControl(props.controlName, formControl);\n}\n"
},
{
"answer_id": 74357903,
"author": "Andrew Allen",
"author_id": 4711754,
"author_profile": "https://Stackoverflow.com/users/4711754",
"pm_score": 0,
"selected": false,
"text": "new <T = any>(\n value: T | FormControlState<T>, \n opts: FormControlOptions & { nonNullable: true; }\n): FormControl<T>\n\nnew <T = any>(\n value: T | FormControlState<T>,\n validatorOrOpts?: ValidatorFn | FormControlOptions | ValidatorFn[],\n asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[]\n): FormControl<T | null>\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/218349/"
] |
74,356,671 | <p>I am trying to implement upload mechanism for my application. However, I have a concurrency issue I couldn't resolve. I sent my requests using async/await with following code. In my application UploadService is creating every time an event is fired from some part of my code. As an example I creation of my <code>UploadService</code> in a for loop. The problem is if I do not use <code>NSLock</code> backend service is called multiple times (5 in this case because of loop). But if I use <code>NSLock</code> it never reaches the <code>.success</code> or <code>.failure</code> part because of deadlock I think. Could someone help me how to achieve without firing upload service multiple times and reaching success part of my request.</p>
<pre><code>final class UploadService {
/// If I use NSLock in the commented lines it never reaches to switch result so can't do anything in success or error part.
static let locker = NSLock()
init() {
Task {
await uploadData()
}
}
func uploadData() async {
// Self.locker.lock()
let context = PersistentContainer.shared.newBackgroundContext()
// It fetches data from core data to send it in my request
guard let uploadedThing = Upload.coreDataFetch(in: context) else {
return
}
let request = UploadService(configuration: networkConfiguration)
let result = await request.uploadList(uploadedThing)
switch result {
case .success:
print("success")
case .failure(let error as NSError):
print("error happened")
}
// Self.locker.unlock()
}
}
class UploadExtension {
func createUploadService() {
for i in 0...4 {
let uploadService = UploadService()
}
}
}
</code></pre>
| [
{
"answer_id": 74357652,
"author": "Mr.SwiftOak",
"author_id": 14559220,
"author_profile": "https://Stackoverflow.com/users/14559220",
"pm_score": -1,
"selected": false,
"text": "Task {}"
},
{
"answer_id": 74364600,
"author": "Rob",
"author_id": 1271826,
"author_profile": "https://Stackoverflow.com/users/1271826",
"pm_score": 1,
"selected": true,
"text": "func createUploadService() async {\n let uploadService = UploadService()\n\n for i in 0...4 {\n await uploadService.uploadData(…)\n }\n}\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5850840/"
] |
74,356,673 | <p>I'm having trouble aligning the text in the accordion button to the center while keeping the arrow on the right</p>
<p>Example of what i want to achieve:</p>
<p><a href="https://i.stack.imgur.com/2brrY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2brrY.png" alt="enter image description here" /></a></p>
<p>Here is an example from bootstrap 5 docs and have commented on where I wanted it to be aligned</p>
<pre><code><div class="accordion" id="accordionExample">
<div class="accordion-item">
<h2 class="accordion-header" id="headingOne">
// Trying to align Accordion Item #1 to the center instead of the left
<button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
Accordion Item #1
</button>
</h2>
<div id="collapseOne" class="accordion-collapse collapse show" aria-labelledby="headingOne" data-bs-parent="#accordionExample">
<div class="accordion-body">
<strong>This is the first item's accordion body.</strong> It is shown by default, until the collapse plugin adds the appropriate classes that we use to style each element. These classes control the overall appearance, as well as the showing and hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the <code>.accordion-body</code>, though the transition does limit overflow.
</div>
</div>
</div>
</div>
</code></pre>
<p>I have attempted</p>
<pre class="lang-css prettyprint-override"><code>.accordion-button{
display:block;
}
</code></pre>
<p>and</p>
<p><code>class="accordion-button d-block text-center" </code></p>
<p>but the solutions above will get rid of the arrow on the right of the acordion. Any help would be appreciated!</p>
| [
{
"answer_id": 74356942,
"author": "Delowar Hossen",
"author_id": 6602096,
"author_profile": "https://Stackoverflow.com/users/6602096",
"pm_score": -1,
"selected": false,
"text": "h2.accordion-header {\n display: flex;\n flex-direction: row;\n justify-content: center;\n}\n"
},
{
"answer_id": 74357653,
"author": "Cervus camelopardalis",
"author_id": 10347145,
"author_profile": "https://Stackoverflow.com/users/10347145",
"pm_score": 3,
"selected": true,
"text": "<button class=\"accordion-button\" type=\"button\" data-bs-toggle=\"collapse\" data-bs-target=\"#collapseOne\" aria-expanded=\"true\" aria-controls=\"collapseOne\">Accordion Item #1</button>\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13047507/"
] |
74,356,705 | <p>As seen in the picture, i pressed the blue button 3 times, which added 3 card widgets in myList. Also in terminal it shows 3 items are added in myList.
But when i longPress on 3rd Card to it, it infact removes from myList but does not update the UI.</p>
<p>Also, if i try removing 3rd item, again:</p>
<pre><code>======== Exception caught by gesture ===============================================================
The following RangeError was thrown while handling a gesture:
RangeError (index): Invalid value: Not in inclusive range 0..1: 2
</code></pre>
<p>My full code is: (controller.dart)</p>
<pre><code> import 'package:flutter/cupertino.dart';
class MyController extends ChangeNotifier{
var myList = [];
void addItemsInList(){
myList.add('item#${myList.length} ');
//todo: 1* forgot
notifyListeners();
}
void removeItems(index){
myList.removeAt(index) ;
}
}
</code></pre>
<p>full code of view.dart</p>
<pre><code>import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:provider_4/controller/controller_file.dart';
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Consumer<MyController>(
builder: (context, snapshot, child) {
return Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: (){
Provider . of <MyController> (context, listen: false) . addItemsInList();
print('myList.length gives: ${snapshot.myList.length}');
print(snapshot.myList);
},
child: Icon(Icons.add),
),
body: ListView.builder(
itemCount: snapshot.myList.length , // replace with something like myList.length
itemBuilder: (context, index) => Card(
child: ListTile(
onLongPress: () {
Provider . of <MyController> (context, listen: false).removeItems(index);
// snapshot.myList.removeAt(index);
print(snapshot.myList);
},
title: Text(
'Title', // replace with something like myList[index].title
style: TextStyle(
fontSize: 20,
color: Colors.black87,
fontWeight: FontWeight.bold,
),
),
subtitle: Text(
'Details of title above', // replace with something like myList[index].details
style: TextStyle(
fontSize: 20,
color: Colors.deepPurple,
fontWeight: FontWeight.bold,
),
),
trailing: Icon(Icons.check_circle, color: Colors.green,),
),
),
),
);
}
),
);
}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/1TGge.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1TGge.png" alt="UI does not update" /></a></p>
| [
{
"answer_id": 74356818,
"author": "pmatatias",
"author_id": 12838877,
"author_profile": "https://Stackoverflow.com/users/12838877",
"pm_score": 0,
"selected": false,
"text": "ValueKey"
},
{
"answer_id": 74671014,
"author": "Murodjon Jurayev",
"author_id": 14118281,
"author_profile": "https://Stackoverflow.com/users/14118281",
"pm_score": 0,
"selected": false,
"text": "void removeItems(index){\nmyList.removeAt(index) ;\nnotifyListeners(); }\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11565523/"
] |
74,356,722 | <p>I'm converting excel to Json, after the conversion is done I'm getting the below JSON output</p>
<pre><code>[
{
"GERMANY": "Berlin University of the Arts",
"FRANCE": "Berlin University of the Arts",
"UK": "Berlin University of the Arts",
"NETHERLANDS": "Berlin University of the Arts"
},
{
"GERMANY": "Dresden University of Technology",
"FRANCE": "Dresden University of Technology",
"UK": "Dresden University of Technology",
"NETHERLANDS": "Dresden University of Technology"
},
....
]
</code></pre>
<p>Now I need to modify the above to the below JSON structure.</p>
<pre><code>{
"GERMANY": [
"Berlin University of the Arts",
"Dresden University of Technology",
...
],
"FRANCE": [...],
... so on
}
</code></pre>
<p>How can this be done, Please help</p>
| [
{
"answer_id": 74356783,
"author": "Nick Vu",
"author_id": 9201587,
"author_profile": "https://Stackoverflow.com/users/9201587",
"pm_score": 1,
"selected": true,
"text": "reduce"
},
{
"answer_id": 74356787,
"author": "flyingfox",
"author_id": 3176419,
"author_profile": "https://Stackoverflow.com/users/3176419",
"pm_score": 1,
"selected": false,
"text": "reduce()"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16491376/"
] |
74,356,748 | <p>there is a xml message:</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-html lang-html prettyprint-override"><code><Data>
<aa>12345\n67890</aa>
<bb>98765\\4321<bb>
<Data></code></pre>
</div>
</div>
</p>
<p>I need to convert the xml to json:</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-html lang-html prettyprint-override"><code>String strXmlData = xmlHelper.SelectSingleNode(xml,"//Data").OuterXML
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(strJsonData);
String jsonData = JsonConvert.SerializeXmlNode(xmlDoc, Newtonsoft.Json.Formatting.None)</code></pre>
</div>
</div>
</p>
<p>The it seems that json result is added escape charactor by JsonConvert automatically.</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-html lang-html prettyprint-override"><code>{"aa":"12345\\n67890","bb":"98765\\\\4321"}</code></pre>
</div>
</div>
</p>
<p>I need to keep the value as it is(ie, \n as new line instead of "\n" string). Is there any way to prevent JsonConvert to generate escape charactor? Or is there any suggestion to remove the escape charactor?</p>
<p>Any Suggestion is appreciated, thank you!</p>
| [
{
"answer_id": 74356783,
"author": "Nick Vu",
"author_id": 9201587,
"author_profile": "https://Stackoverflow.com/users/9201587",
"pm_score": 1,
"selected": true,
"text": "reduce"
},
{
"answer_id": 74356787,
"author": "flyingfox",
"author_id": 3176419,
"author_profile": "https://Stackoverflow.com/users/3176419",
"pm_score": 1,
"selected": false,
"text": "reduce()"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11163863/"
] |
74,356,762 | <p>I have various strings that might have multiple leading spaces.</p>
<pre><code>string_1 = ' param A val A'
string_2 = 'param B val B'
....
</code></pre>
<p>I want to replace all multiple spaces with a single space IF the multiple spaces are not in the start of the string.</p>
<p>I want output of above to become</p>
<pre><code> string_1 = ' param A val A'z
string_2 = 'param B val B'
</code></pre>
<p>My current solution replaces all multiple spaces with a single space regardless.</p>
<pre><code> re.sub('\s+',' ',s)
</code></pre>
<p>How would I construct a pattern that only captures non leading multiple spaces?</p>
| [
{
"answer_id": 74356889,
"author": "S.B",
"author_id": 13944524,
"author_profile": "https://Stackoverflow.com/users/13944524",
"pm_score": 3,
"selected": false,
"text": "\\b\\s{2,}\\b"
},
{
"answer_id": 74357028,
"author": "Alberto Garcia",
"author_id": 15647384,
"author_profile": "https://Stackoverflow.com/users/15647384",
"pm_score": 0,
"selected": false,
"text": ">>> string_1 = ' param A val A'\n>>> sb = re.compile(r'^(\\s+)(.*)')\n>>> mg = sb.match(string_1).groups()\n>>> mg[0] + ' '.join(mg[1].split())\n' param A val A'\n"
},
{
"answer_id": 74357256,
"author": "JvdV",
"author_id": 9758194,
"author_profile": "https://Stackoverflow.com/users/9758194",
"pm_score": 2,
"selected": false,
"text": "(?<=\\S)\\s+(\\s\\S|$)\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7791963/"
] |
74,356,777 | <p>I'm working on a project where there is a website and i'm developing a phone application for it.
In the website the user could create his own form and this form is save to database as json and after that this json file converted to react components and shown in the page
I want to convert this json file to Flutter widgets and show it in my app,How can I do it?</p>
<p>There is some flutter package but didn't work with my json</p>
| [
{
"answer_id": 74356889,
"author": "S.B",
"author_id": 13944524,
"author_profile": "https://Stackoverflow.com/users/13944524",
"pm_score": 3,
"selected": false,
"text": "\\b\\s{2,}\\b"
},
{
"answer_id": 74357028,
"author": "Alberto Garcia",
"author_id": 15647384,
"author_profile": "https://Stackoverflow.com/users/15647384",
"pm_score": 0,
"selected": false,
"text": ">>> string_1 = ' param A val A'\n>>> sb = re.compile(r'^(\\s+)(.*)')\n>>> mg = sb.match(string_1).groups()\n>>> mg[0] + ' '.join(mg[1].split())\n' param A val A'\n"
},
{
"answer_id": 74357256,
"author": "JvdV",
"author_id": 9758194,
"author_profile": "https://Stackoverflow.com/users/9758194",
"pm_score": 2,
"selected": false,
"text": "(?<=\\S)\\s+(\\s\\S|$)\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20070273/"
] |
74,356,800 | <p>I use redux toolkit and I have my initial state like this:</p>
<pre><code>initialState: {
details: {
id: "",
base64: "",
},
},
</code></pre>
<p>I want to fetch an image base64 inside of my initial state, whenever user logged in. I decided to do such thing in my axios:</p>
<pre><code>axios.post(`${process.env.REACT_APP_API_URL_API_LOGIN}`, {
softWareOrUser: false,
userName: userName,
password: password,
})
.then((r) => {
if (r.data.resCode === 1) {
dispatch(setDetails({ ...details, id: r.data.Data.Id.toString() }));
ImageFetchingHandler(r.data);
}
})
.then((d) => {
navigate({ pathname: "/main" });
})
.catch(() => {
alert("user name or password is incorrect");
});
</code></pre>
<p>This is how I fetch image base64:</p>
<pre><code>const { details } = useSelector((state) => state.axiosdetails);
const ImageFetchingHandler = ({ token }) => {
axios({
method: "post",
url: `${process.env.REACT_APP_API_URL_API_FETCH_IMAGE}`,
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
"DotNet-Timeout": 30000,
},
data: JSON.stringify({
id: details.id,
}),
})
.then((d) => {
Cookies.set("userImage", JSON.stringify(d.data), {
path: "/",
expires: 3,
sameSite: "strict",
secure: window.top.location.protocol === "https:",
});
});
};
</code></pre>
<p>I have a problem, the <code>ImageFetchingHandler</code> sends <code>id</code> value as an empty string even though <code>redux developer tools</code> shows the actual id value.</p>
<p><a href="https://i.stack.imgur.com/vPZqy.png" rel="nofollow noreferrer">Redux developer tools shot</a></p>
<p>What is the problem?</p>
<p>Is there any way to solve it?</p>
| [
{
"answer_id": 74356889,
"author": "S.B",
"author_id": 13944524,
"author_profile": "https://Stackoverflow.com/users/13944524",
"pm_score": 3,
"selected": false,
"text": "\\b\\s{2,}\\b"
},
{
"answer_id": 74357028,
"author": "Alberto Garcia",
"author_id": 15647384,
"author_profile": "https://Stackoverflow.com/users/15647384",
"pm_score": 0,
"selected": false,
"text": ">>> string_1 = ' param A val A'\n>>> sb = re.compile(r'^(\\s+)(.*)')\n>>> mg = sb.match(string_1).groups()\n>>> mg[0] + ' '.join(mg[1].split())\n' param A val A'\n"
},
{
"answer_id": 74357256,
"author": "JvdV",
"author_id": 9758194,
"author_profile": "https://Stackoverflow.com/users/9758194",
"pm_score": 2,
"selected": false,
"text": "(?<=\\S)\\s+(\\s\\S|$)\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20395245/"
] |
74,356,814 | <p>When I save my changes, the whole app is re-rendered and not only the changes that I have made.</p>
<p>I have tried adding <strong>target: "web"</strong> to my devServer and also tried the following guides:</p>
<ul>
<li><a href="https://webpack.js.org/guides/hot-module-replacement/" rel="nofollow noreferrer">https://webpack.js.org/guides/hot-module-replacement/</a></li>
<li><a href="https://www.robinwieruch.de/minimal-react-webpack-babel-setup/" rel="nofollow noreferrer">https://www.robinwieruch.de/minimal-react-webpack-babel-setup/</a></li>
</ul>
<p>Unfortunately, none seems to be working.</p>
<p>Here is the webpack.config.js file:</p>
<pre><code>require('dotenv').config({ path: './.env' });
const path = require('path');
const DotenvWebpack = require('dotenv-webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
module.exports = (env, options) => {
const isDevMode = options.mode === 'development';
const title = process.env.APP_TITLE_OVERRIDE || 'My Cute App';
return {
devtool: isDevMode ? 'source-map' : false,
resolve: {
extensions: ['.ts', '.tsx', '.js'],
plugins: [
new TsconfigPathsPlugin({
/* options: see below */
})
],
fallback: {
path: require.resolve('path-browserify')
}
},
entry: ['./src'],
output: {
path: path.resolve(__dirname, 'dist'),
publicPath: '/',
filename: isDevMode ? 'bundle.js' : '[name].[chunkhash:10].js',
chunkFilename: isDevMode ? '[name].bundle.js' : '[name].[chunkhash:10].js'
},
optimization: {
usedExports: true,
innerGraph: true,
sideEffects: true
},
module: {
rules: [
{
test: /\.(ts|js)x?$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader'
}
]
},
{
test: /\.(sa|sc|c)ss$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
sourceMap: isDevMode
}
},
{
loader: 'sass-loader',
options: {
sourceMap: isDevMode
}
}
]
},
{
test: /\.(ttf|eot|woff|woff2)$/,
use: {
loader: 'file-loader',
options: {
name: 'fonts/[name].[ext]'
}
}
},
{
test: /\.(jpe?g|png|gif|svg|ico)$/i,
loader: 'file-loader'
}
]
},
devServer: {
historyApiFallback: true
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title,
meta: {
viewport:
'width=device-width, initial-scale=1, shrink-to-fit=no, maximum-scale=1'
}
}),
new DotenvWebpack({
path: './.env',
systemvars: !isDevMode
})
]
};
};
</code></pre>
<p>Here is the package.json file :</p>
<pre><code>{
"name": "my-cute-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"engines": {
"node": "16.18.0"
},
"scripts": {
"build": "cross-env NODE_ENV=production webpack --mode production",
"start": "concurrently \"nodemon ./server/index.tsx\" \"webpack serve --mode production\"",
"client": "webpack serve --mode development --open",
"server": "nodemon ./server",
"dev": "concurrently \"npm run server\" \"npm run client\"",
"cy-test": "npx cypress open"
},
"author": "Moty",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.19.6",
"@babel/preset-env": "^7.19.4",
"@babel/preset-react": "^7.18.6",
"@babel/preset-typescript": "^7.18.6",
"babel-loader": "^8.2.5",
"babel-plugin-styled-components": "^2.0.7",
"@types/jest": "^29.2.0",
"@types/node": "^18.11.5",
"@types/react": "^18.0.22",
"@types/react-dom": "^18.0.7",
"clean-webpack-plugin": "^4.0.0",
"cypress": "^10.11.0",
"dotenv-webpack": "^8.0.1",
"eslint": "^8.26.0",
"jest": "^29.2.1",
"favicons": "^7.0.2",
"favicons-webpack-plugin": "^6.0.0-alpha.1",
"file-loader": "^6.2.0",
"html-webpack-plugin": "^5.5.0",
"nodemon": "^2.0.20",
"ts-node": "^10.9.1",
"webpack": "^5.74.0",
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^4.11.1"
},
"dependencies": {
"@sentry/node": "^7.16.0",
"@sentry/react": "^7.16.0",
"@sentry/tracing": "^7.16.0",
"axios": "^0.21.4",
"cloudinary-core": "^2.13.0",
"concurrently": "^7.5.0",
"cross-env": "^7.0.3",
"dotenv": "^16.0.3",
"ejs": "^3.1.8",
"express": "^4.18.2",
"history": "^5.3.0",
"lodash": "^4.17.21",
"lodash-es": "^4.17.21",
"mobx": "^6.6.2",
"mobx-react-lite": "^3.4.0",
"path-browserify": "^1.0.1",
"pg": "^8.8.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.4.2",
"sanitize-html": "^2.7.3",
"styled-components": "^5.3.6",
"tsconfig-paths": "^4.1.0",
"tsconfig-paths-webpack-plugin": "^3.5.2",
"typescript": "^4.8.4",
"uuid": "^9.0.0"
}
}
</code></pre>
<p>Thanks in advance :)</p>
| [
{
"answer_id": 74356889,
"author": "S.B",
"author_id": 13944524,
"author_profile": "https://Stackoverflow.com/users/13944524",
"pm_score": 3,
"selected": false,
"text": "\\b\\s{2,}\\b"
},
{
"answer_id": 74357028,
"author": "Alberto Garcia",
"author_id": 15647384,
"author_profile": "https://Stackoverflow.com/users/15647384",
"pm_score": 0,
"selected": false,
"text": ">>> string_1 = ' param A val A'\n>>> sb = re.compile(r'^(\\s+)(.*)')\n>>> mg = sb.match(string_1).groups()\n>>> mg[0] + ' '.join(mg[1].split())\n' param A val A'\n"
},
{
"answer_id": 74357256,
"author": "JvdV",
"author_id": 9758194,
"author_profile": "https://Stackoverflow.com/users/9758194",
"pm_score": 2,
"selected": false,
"text": "(?<=\\S)\\s+(\\s\\S|$)\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16198836/"
] |
74,356,833 | <p>For the last few weeks I am trying to set up a project in VSCode to be able to build & run the windows desktop app. I understand that for WinUI 3 projects Visual Studio 2022 is recommended but most of the people in the team are using VSCode for all the projects. I was able to build & run WinUI / MAUI / UNO projects in Visual Studio 2022 but not able to do the same in VSCode.</p>
<p>None of the Microsoft documentation clearly denotes if it's possible to run these technologies in <strong>VSCode</strong>. Or <strong>only Visual Studio 2022 is required to run any type of WinUI 3 projects for developing Windows Desktop apps</strong>.</p>
<p>I would like to know if it's possible and if yes could anyone share the git repo of any WinUI projects that can run in VSCode and hope I can see the launch settings in the .vscode folder and other project config files subjected to change to get it work.</p>
<p>Just to reproduce, all I did was create a WinUI 3 / MAUI / UNO project in Visual Studio 2022 using templates available and try to run the same in VSCode. No workaround so far. Any best help is much appreciated.</p>
<p>WinUI 3 project shared in git repo,
<a href="https://github.com/to-marss/WinUI3TestRunInVSCode-" rel="nofollow noreferrer">https://github.com/to-marss/WinUI3TestRunInVSCode-</a></p>
<p>Work fine in Visual Studio 2022 but not in VS Code. This repo can be used to reproduce the issue. Please feel free to modify code changes to this repo for this trial in VSCode.</p>
<p>dotnet build / run returns error below,</p>
<p><a href="https://i.stack.imgur.com/IaTuv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IaTuv.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74609897,
"author": "to-mars",
"author_id": 20446906,
"author_profile": "https://Stackoverflow.com/users/20446906",
"pm_score": 2,
"selected": true,
"text": " - <Platform>x64</Platform> (Required for VSCode)\n - <Platforms>x86;x64;arm64</Platforms> (Required for Visual Studio)\n - <WindowsAppSDKSelfContained>true</WindowsAppSDKSelfContained>\n (Required for exe)\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20446906/"
] |
74,356,834 | <p>Let me say I have 'teacher' collection inside 'teacher' collection I have 'student' collection in Firebase, I need to display every student of every teacher in a list.
I know I can create separate student collection linking teacher id, but this is the scenario I need to work with.
Please help me how can I get every student using FirebaseFirestore query.</p>
| [
{
"answer_id": 74358894,
"author": "Sparko Sol",
"author_id": 20407048,
"author_profile": "https://Stackoverflow.com/users/20407048",
"pm_score": 1,
"selected": true,
"text": "class TeacherModel {\n TeacherModel({\n this.students,\n });\n\n factory TeacherModel.fromJson(Map<String, dynamic> json) {\n /// implement from json\n return TeacherModel(students: []);\n }\n\n /// all the properties of teacher\n List<StudentModel>? students;\n\n Map<String, dynamic> toJson() => {};\n}\n\nclass StudentModel {\n StudentModel();\n\n /// all the properties of student\n factory StudentModel.fromJson(Map<String, dynamic> json) {\n return StudentModel();\n }\n\n Map<String, dynamic> toJson() => {};\n}\n"
},
{
"answer_id": 74362807,
"author": "Frank van Puffelen",
"author_id": 209103,
"author_profile": "https://Stackoverflow.com/users/209103",
"pm_score": 1,
"selected": false,
"text": "db\n .collectionGroup(\"student\")\n .get()\n .then(\n (res) => print(\"Successfully completed\"),\n onError: (e) => print(\"Error completing: $e\"),\n );\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19494590/"
] |
74,356,837 | <p>I have 3 string slices:</p>
<pre><code>enp_slice := []string{"10.10.10.10", "10.10.10.11"}
cachedenp_slice := []string{"10.10.10.10", "10.10.10.11", "10.10.10.12"}
result := []string{}
</code></pre>
<p>I want to compare the 2 string slices and get distict elements in both of them and store them into the 3rd slice(element present in cachedenp_slice but not in enp_slice) like following:</p>
<pre><code>result = ["10.10.10.12"]
</code></pre>
| [
{
"answer_id": 74357408,
"author": "Ivan Pesenti",
"author_id": 14394371,
"author_profile": "https://Stackoverflow.com/users/14394371",
"pm_score": 0,
"selected": false,
"text": "isFound"
},
{
"answer_id": 74358011,
"author": "zangw",
"author_id": 3011380,
"author_profile": "https://Stackoverflow.com/users/3011380",
"pm_score": 1,
"selected": false,
"text": "map"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9391999/"
] |
74,356,864 | <p>I need to get the list of all the repositories and all the branches from TFS.</p>
<p>I have a react app and I wonder if there is some way to use TFS API from it.
Or maybe I should load C# DLL's in order to do that?</p>
<p>Thanks :)</p>
<p>I found this:
<a href="https://learn.microsoft.com/en-us/rest/api/azure/devops/git/repositories/list?view=azure-devops-rest-6.0&tabs=HTTP" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/rest/api/azure/devops/git/repositories/list?view=azure-devops-rest-6.0&tabs=HTTP</a>
but it is for C#.</p>
| [
{
"answer_id": 74357408,
"author": "Ivan Pesenti",
"author_id": 14394371,
"author_profile": "https://Stackoverflow.com/users/14394371",
"pm_score": 0,
"selected": false,
"text": "isFound"
},
{
"answer_id": 74358011,
"author": "zangw",
"author_id": 3011380,
"author_profile": "https://Stackoverflow.com/users/3011380",
"pm_score": 1,
"selected": false,
"text": "map"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17496976/"
] |
74,356,870 | <pre><code>using System;
using System.Collections.Generic;
using System.Linq;
namespace practice
{
class program
{
static void Main(string[] args)
{
Infoma infoma = new Infoma();
infoma.footballers("Messi", 10);
infoma.coach("Xavi Hernández", "Barcelona");
Console.ReadLine();
}
}
class Fifa
{
private Infoma infoma;
public Fifa()
{
infoma = new Infoma();
infoma.Ievent += displayevent;
}
public void displayevent()
{
Console.WriteLine("This message was generated on " + DateTime.Now.ToShortTimeString());
}
}
class Infoma
{
public delegate void Mevent();
public event Mevent Ievent;
public void footballers(string name, int no)
{
Console.WriteLine($"Player Name: {name}, Player NO: {no}");
Ievent(); Console.WriteLine();
}
public void coach (string name , string club)
{
Console.WriteLine($"Coach Name : {name}, Club: {club}");
Ievent();
}
}
}
</code></pre>
<p><em>I wrote this code (trying to get better using events and delegates) but when i run this code i get this error <System.NullReferenceException: 'Object reference not set to an instance of an object.'
Ievent was null.> which is not suppose to be. Actually, I do not know what I am doing wrong. If anyone can help or advise why my event is returning null . Thanks y'all</em></p>
| [
{
"answer_id": 74357310,
"author": "jmcilhinney",
"author_id": 584183,
"author_profile": "https://Stackoverflow.com/users/584183",
"pm_score": 1,
"selected": false,
"text": "Fifa"
},
{
"answer_id": 74357336,
"author": "Enigmativity",
"author_id": 259769,
"author_profile": "https://Stackoverflow.com/users/259769",
"pm_score": 1,
"selected": true,
"text": "fifa"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19072364/"
] |
74,356,875 | <p>I can't delete a category because it is a foreign key in the items table. How can I do it? How can I make a deletion in category and make $category_id null in the items table?</p>
<p>I tried making a delete function but it sends an error saying it can't because it is a foreign key.</p>
| [
{
"answer_id": 74356912,
"author": "Ashutosh Jha",
"author_id": 13004581,
"author_profile": "https://Stackoverflow.com/users/13004581",
"pm_score": -1,
"selected": false,
"text": "DB::statement('SET FOREIGN_KEY_CHECKS=0;');\n// write your delete code here\nDB::statement('SET FOREIGN_KEY_CHECKS=1;');\n"
},
{
"answer_id": 74357124,
"author": "Khayam Khan",
"author_id": 10739750,
"author_profile": "https://Stackoverflow.com/users/10739750",
"pm_score": 1,
"selected": false,
"text": "category_id"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17040377/"
] |
74,356,879 | <p><a href="https://i.stack.imgur.com/cd8ow.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cd8ow.png" alt="enter image description here" /></a>i try to render a component of all the products that are in the cart with window alert but i get just 'object object ' even when the component is empty.
<a href="https://i.stack.imgur.com/6ZGIe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6ZGIe.png" alt="enter image description here" /></a><a href="https://i.stack.imgur.com/HBVQw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HBVQw.png" alt="enter image description here" /></a></p>
<p>i tried to pass it to a function but the result remains the same</p>
| [
{
"answer_id": 74356912,
"author": "Ashutosh Jha",
"author_id": 13004581,
"author_profile": "https://Stackoverflow.com/users/13004581",
"pm_score": -1,
"selected": false,
"text": "DB::statement('SET FOREIGN_KEY_CHECKS=0;');\n// write your delete code here\nDB::statement('SET FOREIGN_KEY_CHECKS=1;');\n"
},
{
"answer_id": 74357124,
"author": "Khayam Khan",
"author_id": 10739750,
"author_profile": "https://Stackoverflow.com/users/10739750",
"pm_score": 1,
"selected": false,
"text": "category_id"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20396675/"
] |
74,356,886 | <p>I'm looking for a way to present notifications on even (2,4,6,8,10,12...) & odd (1,3,5,7,9,11...) days.</p>
<p>I did something similar in reminders:</p>
<pre><code>/// Creates a reminder
func create(_ title: String, isOddDays: Bool, hour: Int, minute: Int) {
let dueDate = Date()
let gregorian = Calendar(identifier: .gregorian)
let daysOfTheMonth: [NSNumber]
if isOddDays {
daysOfTheMonth = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31]
} else {
daysOfTheMonth = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30]
}
let rule = EKRecurrenceRule(
recurrenceWith: .monthly,
interval: 1,
daysOfTheWeek: nil,
daysOfTheMonth: daysOfTheMonth,
monthsOfTheYear: nil,
weeksOfTheYear: nil,
daysOfTheYear: nil,
setPositions: nil,
end: nil
)
guard let reminder: EKReminder = self.setUpReminder(with: title, priority: 0) else {
return
}
reminder.dueDateComponents = gregorian.dateComponents([.day, .month, .year, .hour, .minute, .second], from: dueDate)
reminder.addRecurrenceRule(rule)
let todayDateComponents = gregorian.dateComponents([.day, .month, .year], from: Date())
let day: Int = isOddDays ? 1 : 2
let month: Int = todayDateComponents.month!
let year: Int = todayDateComponents.year!
let absoluteDate = Date.create(day: day, month: month, year: year, hour: hour, minute: minute, second: 0)
let alarm = EKAlarm(absoluteDate: absoluteDate)
reminder.addAlarm(alarm)
UserDefaults.standard.set(reminder.calendarItemIdentifier, forKey: ReminderStoreManager.reminderDefaultsKey)
self.saveReminder(reminder)
}
</code></pre>
<p>I want to do something similar with local notifications in order to send an acknowledgment back to the server.</p>
<p>EDIT:
Screenshot added.
<a href="https://i.stack.imgur.com/esTEe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/esTEe.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74389569,
"author": "Allan Garcia",
"author_id": 1636456,
"author_profile": "https://Stackoverflow.com/users/1636456",
"pm_score": 0,
"selected": false,
"text": "import Foundation\n\nfunc isThisAnEvenDay() -> Bool {\n Calendar.current.component(.day, from: Date()) % 2 == 0\n}\n\nprint(isThisAnEvenDay())\n"
},
{
"answer_id": 74432743,
"author": "Idan Moshe",
"author_id": 1673632,
"author_profile": "https://Stackoverflow.com/users/1673632",
"pm_score": 3,
"selected": true,
"text": "DateComponents"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1673632/"
] |
74,356,899 | <p>I have ListView as below in my flutter application:</p>
<pre><code>widgetToReturn = ListView.builder(
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
itemBuilder: (context, innerIndex) {
return Text("Test");
},
itemCount: widget.objEvent!.details![index].items!.length);
})
</code></pre>
<p>It works perfectly fine with Vertical scroll direction.
But, When I am trying to make it Horizontal as below:</p>
<p>Using:</p>
<pre><code>scrollDirection: Axis.horizontal,
</code></pre>
<p>As below:</p>
<pre><code>widgetToReturn = ListView.builder(
scrollDirection: Axis.horizontal,
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
itemBuilder: (context, innerIndex) {
return Text("Test");
},
itemCount: widget.objEvent!.details![index].items!.length);
})
</code></pre>
<p>Issue with Horizontal direction is that nothing displaying on screen and it gives me below error :</p>
<blockquote>
<blockquote>
<p>The following assertion was thrown during performLayout(): 'package:flutter/src/rendering/viewport.dart': Failed assertion: line
1874 pos 16: 'constraints.hasBoundedHeight': is not true.</p>
</blockquote>
<p>Either the assertion indicates an error in the framework itself, or we
should provide substantially more information in this error message to
help you determine and fix the underlying cause. In either case,
please report this assertion by filing a bug on GitHub:<br />
<a href="https://github.com/flutter/flutter/issues/new?template=2_bug.md" rel="nofollow noreferrer">https://github.com/flutter/flutter/issues/new?template=2_bug.md</a></p>
</blockquote>
<p>What I am doing wrong here?</p>
| [
{
"answer_id": 74356988,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 3,
"selected": true,
"text": "listview"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4827817/"
] |
74,356,901 | <p>im trying to work out how to specify a local variable from a specific timeframe so i can use it later to trigger and alert</p>
<p>If possible without using request security</p>
<p>The normal macd and signal variables are working fine</p>
<p>here is what i have tried but they are not working ( im new to pinescript and have no idea what to do )</p>
<pre><code>//@version=5
indicator(title="", shorttitle="", overlay=false ,format=format.price, precision=4)
macd = slowMA - fastMA
signal = ta.ema(macd, signalMACDlen)
macd15 = slowMA - fastMA, timeframe.period ('15')
signal15 = (timeframe.period ='15'), ta.ema(macd, signalMACDlen)
macd5(timeframe.period ='5') = slowMA - fastMA
</code></pre>
<p>Thanks for any help</p>
| [
{
"answer_id": 74356988,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 3,
"selected": true,
"text": "listview"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20415374/"
] |
74,356,934 | <p>I tried to compare with strlen(string) with -1 but different methods gave different results:</p>
<pre><code>char string[] = {"1234"};
int len = strlen(string);
int bool;
bool = -1 < strlen(string);
printf("%d",bool); //bool=0
bool = -1 < len;
printf("%d",bool); //bool=1
</code></pre>
<p>Assigning values to len and then comparing them gives the correct result, but I don't understand why directly comparing with strlen doesn't work.</p>
| [
{
"answer_id": 74357033,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 2,
"selected": false,
"text": "strlen"
},
{
"answer_id": 74357083,
"author": "AR7CORE",
"author_id": 12945333,
"author_profile": "https://Stackoverflow.com/users/12945333",
"pm_score": 1,
"selected": true,
"text": "strlen"
},
{
"answer_id": 74364243,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 0,
"selected": false,
"text": "//int size_t\n -1 < strlen(string);\n//int int\n -1 < len;\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19689684/"
] |
74,356,946 | <p>I have a useState set as:</p>
<pre><code>const [status, setStatus] = useState([{}])
</code></pre>
<p>I am using a useState for an onChange where the data is returning:</p>
<pre><code>[
{id: 'abc', statuses: ['created', 'finished'],
{id: 'def', statuses: ['created', 'started', 'finished']
]
</code></pre>
<p>The items in the statuses array can change with the onChange (e.g., statuses: ['created', 'finished'] can become statuses: ['created', 'in progress', 'finished']).
I am wondering how I can initially set a key-value pair for each dictionary if the id does not already exist in the useState or update the statuses key-value pair if the id does exist.</p>
<p>I have tried to initialize the useState, but I get an error of "expected 1 argument, but got 2" and I am not sure if I did the spread operator correctly:</p>
<pre><code>useEffect(() => {
setTransitionKeys(prev => [...prev], {id: newData.id, statuses: newData.statuses})
</code></pre>
<p>I have tried to update the useState with:</p>
<pre><code>setStatus(
status.map((value, index) => {
if (value.id === onChangeData.id){
return {
...value, statuses: onChangeData.statuses
}
}
}
)
</code></pre>
<p>If there is a better way to solve this, please let me know.</p>
| [
{
"answer_id": 74357033,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 2,
"selected": false,
"text": "strlen"
},
{
"answer_id": 74357083,
"author": "AR7CORE",
"author_id": 12945333,
"author_profile": "https://Stackoverflow.com/users/12945333",
"pm_score": 1,
"selected": true,
"text": "strlen"
},
{
"answer_id": 74364243,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 0,
"selected": false,
"text": "//int size_t\n -1 < strlen(string);\n//int int\n -1 < len;\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16149582/"
] |
74,356,964 | <p>I have nested set of lists that looks like</p>
<pre><code>Example_List = list(Object=list(list(name="A",value=0.1),list(name="B",value=0.5),list(name="C",value=2)))
> Example_List
$Object
$Object[[1]]
$Object[[1]]$name
[1] "A"
$Object[[1]]$value
[1] 0.1
$Object[[2]]
$Object[[2]]$name
[1] "B"
$Object[[2]]$value
[1] 0.5
$Object[[3]]
$Object[[3]]$name
[1] "C"
$Object[[3]]$value
[1] 2
</code></pre>
<p>I would like to retrieve the value in the list of lists that corresponds to a given name. For example, if it was <code>name="B"</code>, the value to retrieve would be <code>0.5</code>. One way to do this is to search for the name index by using multiple <code>lapply</code> functions, then use that index (<code>2</code>) to retrieve the value.</p>
<p>Is there a more elegant solution in R?</p>
| [
{
"answer_id": 74357033,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 2,
"selected": false,
"text": "strlen"
},
{
"answer_id": 74357083,
"author": "AR7CORE",
"author_id": 12945333,
"author_profile": "https://Stackoverflow.com/users/12945333",
"pm_score": 1,
"selected": true,
"text": "strlen"
},
{
"answer_id": 74364243,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 0,
"selected": false,
"text": "//int size_t\n -1 < strlen(string);\n//int int\n -1 < len;\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74356964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7498328/"
] |
74,357,011 | <p>I have created an Azure Budget which is mapped to an Action group.
I have created a Logic App to send different emails with different email structures on different budget threshold example 50% , 75% etc.
Not able to understand, How to trigger a single logic app for sending different emails as per Azure Budget Action Group conditions.</p>
| [
{
"answer_id": 74357033,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 2,
"selected": false,
"text": "strlen"
},
{
"answer_id": 74357083,
"author": "AR7CORE",
"author_id": 12945333,
"author_profile": "https://Stackoverflow.com/users/12945333",
"pm_score": 1,
"selected": true,
"text": "strlen"
},
{
"answer_id": 74364243,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 0,
"selected": false,
"text": "//int size_t\n -1 < strlen(string);\n//int int\n -1 < len;\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74357011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19554576/"
] |
74,357,014 | <p>I have a simple console application in which I just reading items from a <code>configuration.json</code> file. I am using <code>IConfigurationRoot</code> interface to save the JSON configuration object.</p>
<p>here is my configuration.json file:</p>
<pre class="lang-json prettyprint-override"><code>{
"Configuration": {
"one": "one",
"two": "two",
"three": "three"
}
}
</code></pre>
<p>My code:</p>
<pre class="lang-cs prettyprint-override"><code>public class Program
{
public IConfigurationRoot Configuration { get; set; }
public Program()
{
Configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("configuration.json", optional: true, reloadOnChange: true).Build();
}
static void Main(string[] args)
{
Program p = new Program();
string one = p.Configuration.GetValue<string>("Configuration:one");
string two = p.Configuration.GetValue<string>("Configuration:two");
string three = p.Configuration.GetValue<string>("Configuration:three");
Console.WritLine(one);
Console.WritLine(two);
Console.WritLine(three);
}
}
</code></pre>
<p>I am getting this when I am printing the values.</p>
<p>I tried GetSection as well and got null in it as well.</p>
<p>Updated:</p>
<p>The issue is file is not found but the file exists in the folder</p>
<p><img src="https://i.stack.imgur.com/blU1k.jpg" alt="Exception Screenshot" /></p>
| [
{
"answer_id": 74357362,
"author": "Roman",
"author_id": 3777113,
"author_profile": "https://Stackoverflow.com/users/3777113",
"pm_score": 2,
"selected": true,
"text": "configuration.json"
},
{
"answer_id": 74357468,
"author": "Panagiotis Kanavos",
"author_id": 134204,
"author_profile": "https://Stackoverflow.com/users/134204",
"pm_score": 0,
"selected": false,
"text": "bin\\Debug\\net..."
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74357014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20431277/"
] |
74,357,065 | <p>How can I sum values from json object with jq</p>
<p><strong>Example input JSON object</strong></p>
<pre class="lang-json prettyprint-override"><code>{
"orderNumber": 2346999,
"workStep": 110,
"good": 8,
"bad": 0,
"type": "1",
"date": "2022-11-08T07:17:09",
"time": 0,
"result": 1
}
{
"orderNumber": 2346999,
"workStep": 110,
"good": 8,
"bad": 0,
"type": "1",
"date": "2022-11-08T07:26:57",
"time": 0,
"result": 1
}
</code></pre>
<p><strong>jq condition</strong></p>
<p><code>. | select(.orderNumber==2346999 and .workStep==110) | .good</code></p>
<p><strong>result</strong></p>
<p>8
8</p>
<p><strong>and I liketo have</strong></p>
<p>16</p>
| [
{
"answer_id": 74359752,
"author": "peak",
"author_id": 997358,
"author_profile": "https://Stackoverflow.com/users/997358",
"pm_score": 0,
"selected": false,
"text": "def count(s): reduce s as $_ (0; .+1);\n"
},
{
"answer_id": 74359790,
"author": "0stone0",
"author_id": 5625547,
"author_profile": "https://Stackoverflow.com/users/5625547",
"pm_score": 1,
"selected": false,
"text": "add"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74357065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20183264/"
] |
74,357,101 | <p>I have this dataset show below</p>
<pre><code>temp = [0.1, 1, 4, 10, 15, 20, 25, 30, 35, 40]
sg =[0.999850, 0.999902, 0.999975, 0.999703, 0.999103, 0.998207, 0.997047, 0.995649, 0.99403, 0.99222]
sg_temp = pd.DataFrame({'temp' : temp,
'sg' : sg})
temp sg
0 0.1 0.999850
1 1.0 0.999902
2 4.0 0.999975
3 10.0 0.999703
4 15.0 0.999103
5 20.0 0.998207
6 25.0 0.997047
7 30.0 0.995649
8 35.0 0.994030
9 40.0 0.992220
</code></pre>
<p>I would like to interpolate all the values between 0.1 and 40 on a scale of 0.001 with a spline interpolation and have those points as in the dataframe as well. I have used resample() before but can't seem to find an equivalent for this case.</p>
<p>I have tried this based off of other questions but it doesn't work.</p>
<pre><code>scale = np.linspace(0, 40, 40*1000)
interpolation_sg = interpolate.CubicSpline(list(sg_temp.temp), list(sg_temp.sg))
</code></pre>
| [
{
"answer_id": 74359752,
"author": "peak",
"author_id": 997358,
"author_profile": "https://Stackoverflow.com/users/997358",
"pm_score": 0,
"selected": false,
"text": "def count(s): reduce s as $_ (0; .+1);\n"
},
{
"answer_id": 74359790,
"author": "0stone0",
"author_id": 5625547,
"author_profile": "https://Stackoverflow.com/users/5625547",
"pm_score": 1,
"selected": false,
"text": "add"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74357101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18216895/"
] |
74,357,139 | <p>I am making a calculator that calculates the age in years but I also want to calculate months Please help me with this Regard Thank you. I want my output like this for 22 years and 3 months. I attach my javascript code and Razor view code. In javascript code, only years are calculated and in Razor view, two text boxes in the first text box take the user's DOB and show his age in the other text box. I want to add a code to calculate months also.DOB is not hardcode .</p>
<pre><code> <html>
<body> <div class="form-group row">
<label class="control-label col-sm-2" asp-for="Dob">Birth date:</label>
<div class="col-sm-5"> <input asp-for="Dob" id="txtDOB" asp-format="{0:yyyy-MM-dd}" class="form-control" placeholder="YYYY-MM-DD" /> </div>
</div>
\<div class="form-group row"\>
\<label class="control-label col-sm-2" for="Age"\>Age:\</label\>
\<div class="col-sm-5"\>
\<input type="text" id="age" asp-for="Age" class="form-control" /\>
\</div\>
\</div\>
</body>
</html> <script src="~/Scripts/jquery-3.4.1.js"></script> <script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script>
$(document).ready(function () {
$("#txtDOB").change(function () {
var dob = $("#txtDOB").val();
if (dob == null || dob == "") {
} else {
$("#age").val(getAge(dob));
}
});
function getAge(birth) {
ageMS = Date.parse(Date()) - Date.parse(birth);
age = new Date();
age.setTime(ageMS);
ageYear = age.getFullYear() - 1970;
return ageYear;
}
});
</script>
</code></pre>
| [
{
"answer_id": 74359752,
"author": "peak",
"author_id": 997358,
"author_profile": "https://Stackoverflow.com/users/997358",
"pm_score": 0,
"selected": false,
"text": "def count(s): reduce s as $_ (0; .+1);\n"
},
{
"answer_id": 74359790,
"author": "0stone0",
"author_id": 5625547,
"author_profile": "https://Stackoverflow.com/users/5625547",
"pm_score": 1,
"selected": false,
"text": "add"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74357139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20102245/"
] |
74,357,197 | <p>This code i am trying to get current language or default language of android phone</p>
<pre><code> String language = getApplicationContext().getResources().getConfiguration().locale.getLanguage();
</code></pre>
<p>but i am getting always es which is english i have changes my phone language to Japanese language but then also i am getting es which is english. i am trying to apply language localisation so that on launch it will check device language accordingly it will set .</p>
<p>Please help me what i am doing wrong how to get current language selected of android phone .</p>
| [
{
"answer_id": 74358299,
"author": "Gaurav Bharadia",
"author_id": 11004504,
"author_profile": "https://Stackoverflow.com/users/11004504",
"pm_score": 2,
"selected": true,
"text": "Locale.getDefault().getLanguage() = en \nLocale.getDefault().getISO3Language() = eng \nLocale.getDefault().getDisplayLanguage() = English\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74357197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1788205/"
] |
74,357,209 | <p>I followed a tutorial on how to display multiple pages for my reactJS program and it partially works. I have two pages: Home and Stocks, and they both have some example text in them. When I type in /home, or /stocks at the end of my localhost URL, the pages change and the correct text displays. But after having 100% identical code to the tutorial, I don't get the links on my website.</p>
<pre><code>//index.js
ReactDOM.render(
<Router>
<Routes>
<Route exact path="/home" element={<Home/>} />
<Route exact path="/stocks" element={<Stocks/>}/>
</Routes>
</Router>,
document.getElementById('root')
);
//app.js
function App() {
return (
<div className="App">
<NavBar />
<Route exact path="/home" component={Home} />
<Route exact path="/stocks" component={Stocks} />
</div>
);
}
//NavBar.js
function NavBar()
{
return (
<ul>
<li>
<Link to="/home">Home</Link>
</li>
<li>
<Link to="/stocks">Stocks</Link>
</li>
</ul>
);
}
</code></pre>
<p>There's no errors and everything works but only when I manually type in the pages. I am trying to have it so that when I type 'npm start', the home page automatically opens with links like: Home | Stocks, and then I can click whichever I want.</p>
| [
{
"answer_id": 74357376,
"author": "ugurgunes",
"author_id": 12119237,
"author_profile": "https://Stackoverflow.com/users/12119237",
"pm_score": 0,
"selected": false,
"text": "//app.js\n....\n <Route exact path=\"/home\" element={<Home />} />\n <Route exact path=\"/stocks\" element={<Stocks/>} />\n...\n"
},
{
"answer_id": 74357598,
"author": "ugurgunes",
"author_id": 12119237,
"author_profile": "https://Stackoverflow.com/users/12119237",
"pm_score": 1,
"selected": false,
"text": "//index.js\nReactDOM.render(\n <Router>\n <Routes>\n <Route path=\"/*\" element={<App/>} />\n </Routes>\n </Router>,\n\ndocument.getElementById('root')\n);\n\n//app.js\nfunction App() {\n return (\n <div className=\"App\">\n <NavBar />\n <Routes>\n <Route index path=\"/home\" component={<Home/>} />\n <Route path=\"/stocks\" component={<Stocks/>} />\n </Routes>\n </div>\n );\n}\n"
},
{
"answer_id": 74357752,
"author": "Sujith Sandeep",
"author_id": 12467993,
"author_profile": "https://Stackoverflow.com/users/12467993",
"pm_score": 0,
"selected": false,
"text": "function App() {\n return (\n <div className=\"App\">\n <Router>\n <NavBar />\n <Routes>\n <Route exact path=\"/home\" element={<Home/>} />\n <Route exact path=\"/stocks\" element={<Stocks/>}/>\n </Routes>\n </Router>\n </div>\n );\n}\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74357209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20413330/"
] |
74,357,265 | <p>I want to get Descending order data by date on playDate Attribute, but descending condition is apply on gameName : hockey object</p>
<p><strong>Data</strong></p>
<pre><code>[
{
"gameDetails": [
{
"gameName": "hockey",
"playDate": "2014-05-05T00:00:00.000Z"
},
{
"gameName": "football",
"playDate": "2022-06-05T00:00:00.000Z"
}
]
},
{
"gameDetails": [
{
"gameName": "hockey",
"playDate": "2020-05-05T00:00:00.000Z"
},
{
"gameName": "cricket",
"playDate": "2013-06-05T00:00:00.000Z"
}
]
},
{
"gameDetails": [
{
"gameName": "cricket",
"playDate": "2013-05-05T00:00:00.000Z"
},
{
"gameName": "football",
"playDate": "2021-06-05T00:00:00.000Z"
}
]
},
{
"gameDetails": [
{
"gameName": "cricket",
"playDate": "2009-05-05T00:00:00.000Z"
},
{
"gameName": "hockey",
"playDate": "2021-06-05T00:00:00.000Z"
}
]
}
]
</code></pre>
<p>From above data we have to output gave records gameName:hockey which is present in gameDetail Array ,in descending order by playDate attribute of gameName:hockey object</p>
<p><strong>Output is</strong>:</p>
<pre><code>[
{
"gameDetails": [
{
"gameName": "cricket",
"playDate": "2009-05-05T00:00:00.000Z"
},
{
"gameName": "hockey",
"playDate": "2021-06-05T00:00:00.000Z"
}
]
},
{
"gameDetails": [
{
"gameName": "hockey",
"playDate": "2020-05-05T00:00:00.000Z"
},
{
"gameName": "cricket",
"playDate": "2013-06-05T00:00:00.000Z"
}
]
},
{
"gameDetails": [
{
"gameName": "hockey",
"playDate": "2014-05-05T00:00:00.000Z"
},
{
"gameName": "football",
"playDate": "2022-06-05T00:00:00.000Z"
}
]
}
]
</code></pre>
| [
{
"answer_id": 74357376,
"author": "ugurgunes",
"author_id": 12119237,
"author_profile": "https://Stackoverflow.com/users/12119237",
"pm_score": 0,
"selected": false,
"text": "//app.js\n....\n <Route exact path=\"/home\" element={<Home />} />\n <Route exact path=\"/stocks\" element={<Stocks/>} />\n...\n"
},
{
"answer_id": 74357598,
"author": "ugurgunes",
"author_id": 12119237,
"author_profile": "https://Stackoverflow.com/users/12119237",
"pm_score": 1,
"selected": false,
"text": "//index.js\nReactDOM.render(\n <Router>\n <Routes>\n <Route path=\"/*\" element={<App/>} />\n </Routes>\n </Router>,\n\ndocument.getElementById('root')\n);\n\n//app.js\nfunction App() {\n return (\n <div className=\"App\">\n <NavBar />\n <Routes>\n <Route index path=\"/home\" component={<Home/>} />\n <Route path=\"/stocks\" component={<Stocks/>} />\n </Routes>\n </div>\n );\n}\n"
},
{
"answer_id": 74357752,
"author": "Sujith Sandeep",
"author_id": 12467993,
"author_profile": "https://Stackoverflow.com/users/12467993",
"pm_score": 0,
"selected": false,
"text": "function App() {\n return (\n <div className=\"App\">\n <Router>\n <NavBar />\n <Routes>\n <Route exact path=\"/home\" element={<Home/>} />\n <Route exact path=\"/stocks\" element={<Stocks/>}/>\n </Routes>\n </Router>\n </div>\n );\n}\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74357265",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15225788/"
] |
74,357,274 | <p>I have a scenario where I need to execute queries on different tables using ETL tool.
I want to store all the required queries in control table.</p>
<p>As part of this, I want to include the column <em>WatermarkValue</em> as part of the value in the column <em>Source_Query</em>, so that I can dynamically use it for my execution. This is how my control table should look like.</p>
<p>Table Name: Metadata_Table</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>TableID</th>
<th>Source_Query</th>
<th>WatermarkValue</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>select * from dbo.cust_eventchanges where lastmodifieddate >{WatermarkValue}</td>
<td>2022-10-09T12:00:00</td>
</tr>
<tr>
<td>2</td>
<td>select * from dbo.cust_contacts where lastmodifieddate >{WatermarkValue}</td>
<td>2022-07-08T03:20:00</td>
</tr>
</tbody>
</table>
</div>
<p>So when I run my metadata table like this
select * from Metadata_Table where TableID=1</p>
<p>the result should be like below.<br />
select * from dbo.cust_eventchanges where lastmodifieddate >'2022-10-09T12:00:00'</p>
<p>I know we can do this by concatenating two columns. But I would like to know if this is achievable.</p>
<p>I couldn't able to figure out how to achieve this. Hence, I need help on this scenario</p>
| [
{
"answer_id": 74361374,
"author": "Piotr Rodak",
"author_id": 227606,
"author_profile": "https://Stackoverflow.com/users/227606",
"pm_score": 0,
"selected": false,
"text": "create view vMetadataQueries \nas\n select TableID, Source_Query + WatermarkValue as [ExecuteQuery] \n from Metadata_Table\n"
},
{
"answer_id": 74362586,
"author": "planetmatt",
"author_id": 12775291,
"author_profile": "https://Stackoverflow.com/users/12775291",
"pm_score": 1,
"selected": false,
"text": "DROP TABLE IF EXISTS #MetaData_Table\nGO\nCREATE TABLE #MetaData_Table\n(TableID INT,Source_Query NVARCHAR(MAX),WatermarkValue DATETIME)\n\nINSERT INTO #MetaData_Table\n(TableID,Source_Query,WatermarkValue)\nVALUES\n(1,'select * from dbo.cust_eventchanges where lastmodifieddate >@WatermarkValue','2022-10-09T12:00:00'),\n(2,'select * from dbo.cust_contacts where lastmodifieddate >@WatermarkValue','2022-07-08T03:20:00')\n\n\nSELECT * FROM #MetaData_Table\n\nDECLARE @dtVariable DATETIME; \nDECLARE @SQLString NVARCHAR(500); \nDECLARE @ParmDefinition NVARCHAR(500); \n\n-- You can put this in a cursor to loop through all your tables, this is hardcoded to one for simplicity.\nSELECT @SQLString = Source_Query, @dtVariable = WatermarkValue FROM #MetaData_Table WHERE TableID = 1\n\nSET @ParmDefinition = N'@WatermarkValue DATETIME'\nEXECUTE sp_executesql @SQLString, @ParmDefinition, \n @WatermarkValue = @dtVariable;\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74357274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19792466/"
] |
74,357,278 | <p>I was doing some experiments in a code in order to prove the theory. This is my code:</p>
<pre><code>#include <stdio.h>
int main(){
unsigned int x,y,z;
if(1){
x=-5;
y=5;
z=x+y;
printf("%i",z);
}
return 0;
}
</code></pre>
<p>But for what I know the output should have been 10, but instead it prints 0, why this is happening? why I can assign a negative value to an unsigned int data type</p>
| [
{
"answer_id": 74357367,
"author": "Lundin",
"author_id": 584518,
"author_profile": "https://Stackoverflow.com/users/584518",
"pm_score": 2,
"selected": false,
"text": "-5"
},
{
"answer_id": 74357369,
"author": "Paul Hankin",
"author_id": 1400793,
"author_profile": "https://Stackoverflow.com/users/1400793",
"pm_score": 2,
"selected": false,
"text": "x=-5"
},
{
"answer_id": 74359648,
"author": "Steve Summit",
"author_id": 3923896,
"author_profile": "https://Stackoverflow.com/users/3923896",
"pm_score": 1,
"selected": false,
"text": "unsigned"
},
{
"answer_id": 74363976,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 1,
"selected": false,
"text": "printf()"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74357278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20384406/"
] |
74,357,320 | <pre><code>extension ArticlesViewController {
func setup() {
self.navigationController?.navigationBar.prefersLargeTitles = true
newtworkManager?.getNews { [weak self] (results) in
switch results {
case .success(let data):
self?.articleListVM = ArticleListViewModel(articles: data.article!)
// For testing
print(self?.articleListVM.articles as Any)
DispatchQueue.main.async {
self?.tableView.reloadData()
}
case .failure(let error):
print(error.localizedDescription)
}
}
}
</code></pre>
<p>Now, while debugging, I am receiving data successfully and printing it out. However, I realized the cellForRowAt function is not being executed which is causing the data not showing on the table. I cannot see any issue, but the run time disagrees of course.</p>
<pre><code>extension ArticlesViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
return self.articleListVM == nil ? 0 : self.articleListVM.numberOfSections
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.articleListVM.numberOfRowsInSection(section)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "ArticleTableViewCell", for: indexPath) as? ArticleTableViewCell else {
fatalError("ArticleTableViewCell not found")
}
let articleVM = self.articleListVM.articleAtIndex(indexPath.row)
cell.titleLabel.text = articleVM.title
cell.abstractLabel.text = articleVM.abstract
return cell
}
</code></pre>
<p>}</p>
<p>Why do you think this method is not getting triggered? Note that my UITableView and UITableViewCell on the storyboard are connected respectively to my code. I see no reason why it is not loading the data.</p>
| [
{
"answer_id": 74357479,
"author": "Anish",
"author_id": 9855456,
"author_profile": "https://Stackoverflow.com/users/9855456",
"pm_score": 2,
"selected": false,
"text": "extension ArticlesViewController: UITableViewDelegate, UITableViewDataSource {\n func numberOfSections(in tableView: UITableView) -> Int {\n return self.articleListVM == nil ? 0 : self.articleListVM.numberOfSections\n }\n\n func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {\n ....\n }\n\n func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {\n ....\n }\n}\n"
},
{
"answer_id": 74357707,
"author": "Ayush S Bhatt",
"author_id": 13485070,
"author_profile": "https://Stackoverflow.com/users/13485070",
"pm_score": 0,
"selected": false,
"text": "tableView.reloadData()"
},
{
"answer_id": 74360025,
"author": "Ahmed AlFailakawi",
"author_id": 14692364,
"author_profile": "https://Stackoverflow.com/users/14692364",
"pm_score": 1,
"selected": true,
"text": "newtworkManager"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74357320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14692364/"
] |
74,357,327 | <p>I have this large dataframe, illustrated below is for simplicity purposes.</p>
<pre><code>pd.DataFrame(df.groupby(['Pclass', 'Sex'])['Age'].median())
</code></pre>
<p><strong>Groupby results:</strong>
<a href="https://i.stack.imgur.com/Qf5MC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Qf5MC.png" alt="enter image description here" /></a></p>
<br>
<p>And it have this data that needs to be imputed</p>
<p><strong>Missing Data:</strong>
<a href="https://i.stack.imgur.com/RZq5I.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RZq5I.png" alt="enter image description here" /></a></p>
<p>How can I impute these values based on the median of the grouped statistic</p>
<p>The result that I want is:</p>
<p><a href="https://i.stack.imgur.com/thPTD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/thPTD.png" alt="enter image description here" /></a></p>
<pre><code># You can use this for reference
import numpy as np
import pandas as pd
mldx_arrays = [np.array([1, 1,
2, 2,
3, 3]),
np.array(['male', 'female',
'male', 'female',
'male', 'female'])]
multiindex_df = pd.DataFrame(
[34,29,24,40,18,25], index=mldx_arrays,
columns=['Age'])
multiindex_df.index.names = ['PClass', 'Sex']
multiindex_df
d = {'PClass': [1, 1, 2, 2, 3, 3],
'Sex': ['male', 'female', 'male', 'female', 'male', 'female'],
'Age': [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan]}
df = pd.DataFrame(data=d)
</code></pre>
| [
{
"answer_id": 74357349,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 3,
"selected": true,
"text": "Age"
},
{
"answer_id": 74357460,
"author": "Celius Stingher",
"author_id": 11897007,
"author_profile": "https://Stackoverflow.com/users/11897007",
"pm_score": 0,
"selected": false,
"text": "df['Age'] = base_df.groupby(['Pclass', 'Sex'])['Age'].median()\n"
},
{
"answer_id": 74357495,
"author": "Panda Kim",
"author_id": 20430449,
"author_profile": "https://Stackoverflow.com/users/20430449",
"pm_score": 0,
"selected": false,
"text": "reset_index"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74357327",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18193889/"
] |
74,357,342 | <p>I am currently on a beginner course in C and was given an exercise requiring my program to check if the user input contains non-alphabets. I've figured to use the function <code>isalpha()</code> to check the user input and if it contains non-alphabets, the program should ask the user to enter another input.</p>
<p>Below is my current code:</p>
<pre><code>#include <stdio.h>
#include <ctype.h>
#define MAX 13
int main() {
char player1[MAX];
int k = 0;
// Ask player 1 to type a word.
printf("Player 1, enter a word of no more than 12 letters: \n");
fgets(player1, MAX, stdin);
// // Loop over the word entered by player1
for (int i = 0; i < player1[i]; i++) {
// if any chars looped through is not an alphabet, print message.
if (isalpha((unsigned char)player1[i]) == 0) {
printf("Sorry, the word must contain only English letters.");
}
}
</code></pre>
<p>However, after testing it, I've derived a few cases from its results.</p>
<p>Case 1:
Entering without any input prints <code>("Sorry, the word must contain only English letters. ")</code></p>
<p>Case 2:
An input with 1 non-alphabetic character prints the 'sorry' message twice. Additionally, an input with 2 non-alphabetic characters print the 'sorry' message thrice. This implies that case 1 is true, since no input prints the message once, then adding a non-alphabetic prints the message twice.</p>
<p>Case 3:
An input of less than 10 characters(all alphabetic) prints out the sorry message also.</p>
<p>Case 4:
An input of more than 9 characters(all alphabetic) does not print out the sorry message, which satisfies my requirements.</p>
<p>Why are these the cases? I only require the message to print once if after looping through the user input, there's found to be a non-alphabetic character!</p>
| [
{
"answer_id": 74358345,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 1,
"selected": false,
"text": "for (int i = 0; i < player1[i]; i++) {\n"
},
{
"answer_id": 74358511,
"author": "AR7CORE",
"author_id": 12945333,
"author_profile": "https://Stackoverflow.com/users/12945333",
"pm_score": 2,
"selected": true,
"text": "#include <stdio.h>\n#include <ctype.h>\n#include <string.h>\n\n#define BUFFER_SIZE 13\n\n#define MIN(a, b) (a < b ? a : b)\n\nint main(void)\n{\n char player1[BUFFER_SIZE];\n int maxIndex;\n int i;\n\n /* Ask player 1 to type a word */\n printf(\"Player 1, enter a word of no more than 12 letters: \\n\");\n fgets(player1, BUFFER_SIZE, stdin);\n\n /*\n * Max index for iteration, if string is lesser than 12 characters\n * (excluding null-terminating byte '\\0') stop on string end, otherwise\n * loop over whole array\n */\n maxIndex = MIN(strlen(player1) - 1, BUFFER_SIZE);\n\n for (i = 0; i < maxIndex; i++) {\n /* Print error if non-letters were entered */\n if (isalpha(player1[i]) == 0) {\n printf(\"Sorry, the word must contain only English letters.\");\n /* Error occured, no need to check further */\n break;\n }\n }\n\n /*\n for (i = 0; i < maxIndex; i++)\n printf(\"%d \", (int) player1[i]);\n printf(\"\\n%s\\n\", player1);*/\n\n return 0;\n}\n"
},
{
"answer_id": 74358903,
"author": "Fe2O3",
"author_id": 17592432,
"author_profile": "https://Stackoverflow.com/users/17592432",
"pm_score": 2,
"selected": false,
"text": "for()"
},
{
"answer_id": 74363878,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 1,
"selected": false,
"text": "#include <ctype.h>\n#include <stdio.h>\n\nint main(void) {\n int ch;\n int all_alpha = 1;\n\n printf(\"Player 1, enter a line\\n\");\n\n while ((ch = getchar()) != '\\n' && ch != EOF) {\n if (!isalpha(ch) {\n all_alpha = 0;\n }\n }\n\n if (!all_alpha) {\n printf(\"Sorry, the line must contain only letters.\");\n }\n}\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74357342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10179802/"
] |
74,357,351 | <p>In Apigee</p>
<p>given a variable in javascript policy, example: var value = 123;</p>
<p>how to get this variable in the assign message policy?</p>
<p>by using {a} in the payload message is not reachable</p>
| [
{
"answer_id": 74358345,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 1,
"selected": false,
"text": "for (int i = 0; i < player1[i]; i++) {\n"
},
{
"answer_id": 74358511,
"author": "AR7CORE",
"author_id": 12945333,
"author_profile": "https://Stackoverflow.com/users/12945333",
"pm_score": 2,
"selected": true,
"text": "#include <stdio.h>\n#include <ctype.h>\n#include <string.h>\n\n#define BUFFER_SIZE 13\n\n#define MIN(a, b) (a < b ? a : b)\n\nint main(void)\n{\n char player1[BUFFER_SIZE];\n int maxIndex;\n int i;\n\n /* Ask player 1 to type a word */\n printf(\"Player 1, enter a word of no more than 12 letters: \\n\");\n fgets(player1, BUFFER_SIZE, stdin);\n\n /*\n * Max index for iteration, if string is lesser than 12 characters\n * (excluding null-terminating byte '\\0') stop on string end, otherwise\n * loop over whole array\n */\n maxIndex = MIN(strlen(player1) - 1, BUFFER_SIZE);\n\n for (i = 0; i < maxIndex; i++) {\n /* Print error if non-letters were entered */\n if (isalpha(player1[i]) == 0) {\n printf(\"Sorry, the word must contain only English letters.\");\n /* Error occured, no need to check further */\n break;\n }\n }\n\n /*\n for (i = 0; i < maxIndex; i++)\n printf(\"%d \", (int) player1[i]);\n printf(\"\\n%s\\n\", player1);*/\n\n return 0;\n}\n"
},
{
"answer_id": 74358903,
"author": "Fe2O3",
"author_id": 17592432,
"author_profile": "https://Stackoverflow.com/users/17592432",
"pm_score": 2,
"selected": false,
"text": "for()"
},
{
"answer_id": 74363878,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 1,
"selected": false,
"text": "#include <ctype.h>\n#include <stdio.h>\n\nint main(void) {\n int ch;\n int all_alpha = 1;\n\n printf(\"Player 1, enter a line\\n\");\n\n while ((ch = getchar()) != '\\n' && ch != EOF) {\n if (!isalpha(ch) {\n all_alpha = 0;\n }\n }\n\n if (!all_alpha) {\n printf(\"Sorry, the line must contain only letters.\");\n }\n}\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74357351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1528153/"
] |
74,357,354 | <p>Currently using the ff. (simplified) code in <code>.gitlab-ci.yml</code> to run multiple SSH commands:</p>
<pre><code>stage: deploy
script:
- ssh 1.2.3.4 "docker login -u foo -p bar example.com"
- ssh 1.2.3.4 "docker pull my_image"
- ssh 1.2.3.4 "docker run -d -p 80:80 my_image"
- ssh 1.2.3.4 "and so on ..."
- ssh 1.2.3.4 "exit"
</code></pre>
<p>It works but is there a simpler way to do this, for e.g., without specifying <code>ssh 1.2.3.4</code> in every line?</p>
| [
{
"answer_id": 74358345,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 1,
"selected": false,
"text": "for (int i = 0; i < player1[i]; i++) {\n"
},
{
"answer_id": 74358511,
"author": "AR7CORE",
"author_id": 12945333,
"author_profile": "https://Stackoverflow.com/users/12945333",
"pm_score": 2,
"selected": true,
"text": "#include <stdio.h>\n#include <ctype.h>\n#include <string.h>\n\n#define BUFFER_SIZE 13\n\n#define MIN(a, b) (a < b ? a : b)\n\nint main(void)\n{\n char player1[BUFFER_SIZE];\n int maxIndex;\n int i;\n\n /* Ask player 1 to type a word */\n printf(\"Player 1, enter a word of no more than 12 letters: \\n\");\n fgets(player1, BUFFER_SIZE, stdin);\n\n /*\n * Max index for iteration, if string is lesser than 12 characters\n * (excluding null-terminating byte '\\0') stop on string end, otherwise\n * loop over whole array\n */\n maxIndex = MIN(strlen(player1) - 1, BUFFER_SIZE);\n\n for (i = 0; i < maxIndex; i++) {\n /* Print error if non-letters were entered */\n if (isalpha(player1[i]) == 0) {\n printf(\"Sorry, the word must contain only English letters.\");\n /* Error occured, no need to check further */\n break;\n }\n }\n\n /*\n for (i = 0; i < maxIndex; i++)\n printf(\"%d \", (int) player1[i]);\n printf(\"\\n%s\\n\", player1);*/\n\n return 0;\n}\n"
},
{
"answer_id": 74358903,
"author": "Fe2O3",
"author_id": 17592432,
"author_profile": "https://Stackoverflow.com/users/17592432",
"pm_score": 2,
"selected": false,
"text": "for()"
},
{
"answer_id": 74363878,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 1,
"selected": false,
"text": "#include <ctype.h>\n#include <stdio.h>\n\nint main(void) {\n int ch;\n int all_alpha = 1;\n\n printf(\"Player 1, enter a line\\n\");\n\n while ((ch = getchar()) != '\\n' && ch != EOF) {\n if (!isalpha(ch) {\n all_alpha = 0;\n }\n }\n\n if (!all_alpha) {\n printf(\"Sorry, the line must contain only letters.\");\n }\n}\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74357354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/748789/"
] |
74,357,360 | <p>Rookie here, I have been breaking my head all day trying to figure this one out…</p>
<p>I have tried different approaches trying to figure this out and looking all over this site for some references, but I have come short and hit a roadblock.</p>
<p>This is my code currently:</p>
<pre><code>
import fs from 'fs'
import csvjson from 'csvjson'
const path = 'cyberBackgroundChecks/importer/assets/file.csv'
if (path && fs.existsSync(path)) {
let file = fs.readFileSync(path);
file = file.toString()
const json = csvjson.toObject(file)
let dataObject = {}
for (let i = 0; i < json.length; i++) {
if (json.length > 0) {
dataObject['index'] = i
dataObject['name'] = json[i]['OWNER 1 FIRST NAME'] ? json[i]['OWNER 1 FIRST NAME'] : json[i]['OWNER 1 LAST NAME']
dataObject['streetAddress'] = json[i]['SITUS STREET ADDRESS']
dataObject['city'] = json[i]['SITUS CITY']
dataObject['state'] = json[i]['SITUS STATE']
}
console.log(dataObject)
}
} else {
console.log('The file does not exist');
}
</code></pre>
<p>I'm trying to get it to console log like this:</p>
<pre><code>[
{
index: 0,
name: 'Betsy',
streetAddress: '1452 20th Ave',
city: 'Seattle',
state: 'WA'
},
{
index: 1,
name: 'Donald',
streetAddress: '2702 NW 67th St',
city: 'Seattle',
state: 'WA'
}
]
</code></pre>
<p>However, with my code, I can only get it to console log like this:</p>
<pre><code>{
index: 0,
name: 'Betsy',
streetAddress: '1452 20th Ave',
city: 'Seattle',
state: 'WA'
}
{
index: 1,
name: 'Donald',
streetAddress: '2702 NW 67th St',
city: 'Seattle',
state: 'WA'
}
</code></pre>
| [
{
"answer_id": 74357422,
"author": "Rocky Sims",
"author_id": 4123400,
"author_profile": "https://Stackoverflow.com/users/4123400",
"pm_score": 1,
"selected": false,
"text": "dataObject"
},
{
"answer_id": 74357446,
"author": "Orbital Bombardment",
"author_id": 8558174,
"author_profile": "https://Stackoverflow.com/users/8558174",
"pm_score": 3,
"selected": true,
"text": "const dataObjectArr = [];\nfor (let i = 0; i < json.length; i++) {\n let dataObject = {};\n dataObject['index'] = i;\n dataObject['name'] = json[i]['OWNER 1 FIRST NAME'] ? json[i]['OWNER 1 FIRST NAME'] : json[i]['OWNER 1 LAST NAME'];\n dataObject['streetAddress'] = json[i]['SITUS STREET ADDRESS'];\n dataObject['city'] = json[i]['SITUS CITY'];\n dataObject['state'] = json[i]['SITUS STATE'];\n dataObjectArr.push(dataObject);\n}\nconsole.log(dataObjectArr);\n"
},
{
"answer_id": 74357570,
"author": "jacobkim",
"author_id": 11010112,
"author_profile": "https://Stackoverflow.com/users/11010112",
"pm_score": 1,
"selected": false,
"text": "push"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74357360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6769563/"
] |
74,357,397 | <p>I have multiple ERC20 tokens, deployed on <a href="https://developers.rsk.co/" rel="noreferrer">Rootstock</a>,
and I want to track their balances and allowances in a real time from my DApp.
In <a href="https://docs.ethers.io/v5/" rel="noreferrer">ethers.js</a>,
I <em>can</em> track their balances by alternately calling the functions
<code>balanceOf(address)</code> and <code>allowance(owner, spender)</code>.
However, across two tokens, that equates to about
4 JSON-RPC requests every ~30 seconds.</p>
<p>I would prefer to reduce the frequency of JSON-RPC requests made by my application,
by aggregating these particular requests.</p>
<p>Is it possible to <em>combine</em> multiple smart contract data queries
into a single JSON-RPC request via <code>ethers.js</code> or any other library?</p>
| [
{
"answer_id": 74357422,
"author": "Rocky Sims",
"author_id": 4123400,
"author_profile": "https://Stackoverflow.com/users/4123400",
"pm_score": 1,
"selected": false,
"text": "dataObject"
},
{
"answer_id": 74357446,
"author": "Orbital Bombardment",
"author_id": 8558174,
"author_profile": "https://Stackoverflow.com/users/8558174",
"pm_score": 3,
"selected": true,
"text": "const dataObjectArr = [];\nfor (let i = 0; i < json.length; i++) {\n let dataObject = {};\n dataObject['index'] = i;\n dataObject['name'] = json[i]['OWNER 1 FIRST NAME'] ? json[i]['OWNER 1 FIRST NAME'] : json[i]['OWNER 1 LAST NAME'];\n dataObject['streetAddress'] = json[i]['SITUS STREET ADDRESS'];\n dataObject['city'] = json[i]['SITUS CITY'];\n dataObject['state'] = json[i]['SITUS STATE'];\n dataObjectArr.push(dataObject);\n}\nconsole.log(dataObjectArr);\n"
},
{
"answer_id": 74357570,
"author": "jacobkim",
"author_id": 11010112,
"author_profile": "https://Stackoverflow.com/users/11010112",
"pm_score": 1,
"selected": false,
"text": "push"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74357397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194982/"
] |
74,357,420 | <p>I have a dataframe:</p>
<pre><code>> df = batch Code. time
> a 100. 2019-08-01 00:59:12.000
> a 120. 2019-08-01 00:59:32.000
> a 130. 2019-08-01 00:59:42.000
> a 120. 2019-08-01 00:59:52.000
> b 100. 2019-08-01 00:44:11.000
> b 140. 2019-08-02 00:14:11.000
> b 150. 2019-08-03 00:47:11.000
> c 150. 2019-09-01 00:44:11.000
> d 100. 2019-08-01 00:10:00.000
> d 100. 2019-08-01 00:10:05.000
> d 130. 2019-08-01 00:10:10.000
> d 130. 2019-08-01 00:10:20.000
</code></pre>
<p>I want to get the number of seconds, per group, between the time of the first '100' code to the last '130' code.
If for a group there is no code 100 with code 130 after (one of them is missing) - put nan.
So the output should be:</p>
<pre><code>df2 = batch duration
a 30
b. nan
c. nan
d. 20
</code></pre>
<p>What is the best way to do it?</p>
| [
{
"answer_id": 74357474,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 3,
"selected": true,
"text": "#convert values to datetimes\ndf['time'] = pd.to_datetime(df['time'])\n \n#get first 100 Code per batch \ns1=df[df['Code.'].eq(100)].drop_duplicates('batch').set_index('batch')['time']\n#get last 130 Code per batch \ns2=df[df['Code.'].eq(130)].drop_duplicates('batch', keep='last').set_index('batch')['time']\n\n#subtract and convert to timedeltas\ndf = (s2.sub(s1)\n .dt.total_seconds()\n .reindex(df['batch'].unique())\n .reset_index(name='duration'))\nprint (df)\n batch duration\n0 a 30.0\n1 b NaN\n2 c NaN\n3 d 20.0\n"
},
{
"answer_id": 74357907,
"author": "Bushmaster",
"author_id": 15415267,
"author_profile": "https://Stackoverflow.com/users/15415267",
"pm_score": 0,
"selected": false,
"text": "batchs = pd.DataFrame(df['batch'].unique(),columns=['batch'])\n\ndf = df[(df['code'] == 100) | (df['code']==130)]\nfinal=pd.concat([\n df.drop_duplicates(subset='code',keep='first'),\n df.drop_duplicates(subset='code',keep='last'),\n])\nfinal['duration'] = (final['time'].shift(-1) - final['time']).dt.total_seconds()\n\nfinal = final.drop_duplicates('batch',keep='first').drop(['time','code'],axis=1).merge(batchs,on='batch',how='right')\nfinal\n batch duration\n0 a 30.0\n1 b nan\n2 c nan\n3 d 15.0\n\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74357420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6057371/"
] |
74,357,426 | <p>What are the standard ways of reading and writing audio files on Android / Kotlin?</p>
<p>I am very confused. I've found plenty of posts that discuss this at some level, but they're all either giving a third party answer (someone's own implementation like <a href="https://medium.com/@rizveeredwan/working-with-wav-files-in-android-52e9500297e" rel="nofollow noreferrer">https://medium.com/@rizveeredwan/working-with-wav-files-in-android-52e9500297e</a> or <a href="https://stackoverflow.com/a/43569709/4959635">https://stackoverflow.com/a/43569709/4959635</a> or <a href="https://gist.github.com/kmark/d8b1b01fb0d2febf5770" rel="nofollow noreferrer">https://gist.github.com/kmark/d8b1b01fb0d2febf5770</a>) or using some Java class, of which I don't know how it's related to the Android SDK (<a href="https://stackoverflow.com/a/26598862/4959635">https://stackoverflow.com/a/26598862/4959635</a>, <a href="https://gist.github.com/niusounds/3e49013a8e942cdba3fbfe1c336b61fc" rel="nofollow noreferrer">https://gist.github.com/niusounds/3e49013a8e942cdba3fbfe1c336b61fc</a>, <a href="https://github.com/google/oboe/issues/548#issuecomment-502758633" rel="nofollow noreferrer">https://github.com/google/oboe/issues/548#issuecomment-502758633</a>).</p>
<p>I cannot find a standard way from the Android documentation. Some answer said to use <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/java.io.-input-stream/read-bytes.html" rel="nofollow noreferrer">https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/java.io.-input-stream/read-bytes.html</a> for reading, but I'm quite sure this doesn't parse the file header.</p>
<p>So what's the standard way of processing audio files on Android / Kotlin?</p>
<p>I'm already using dr_wav just fine on desktop, so I am actually thinking of just using that through NDK and maybe creating a wrapper to it.</p>
| [
{
"answer_id": 74360916,
"author": "dev.bmax",
"author_id": 4283005,
"author_profile": "https://Stackoverflow.com/users/4283005",
"pm_score": 2,
"selected": false,
"text": "PCM"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74357426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4959635/"
] |
74,357,445 | <p>I tried to add an external javascript file to <strong>nuxt.config.ts</strong>.
but nuxt didn't load the file.</p>
<p><strong>nuxt.config.ts</strong> file:</p>
<pre><code>
export default defineNuxtConfig({
css: [
'bootstrap/dist/css/bootstrap.min.css'
],
script: [
{
src: 'script.js',
}
],
vite: {
define: {
'process.env.DEBUG': false,
},
}
})
</code></pre>
| [
{
"answer_id": 74359058,
"author": "diyifi3030",
"author_id": 20447384,
"author_profile": "https://Stackoverflow.com/users/20447384",
"pm_score": 0,
"selected": false,
"text": "export default defineNuxtConfig({\ncss: [\n '@/css/bootstrap.rtl.min.css'\n],\napp: {\n head: {\n script: [\n {\n src: '_nuxt/js/bootstrap.bundle.min.js',\n }\n ],\n }\n}\n})\n"
},
{
"answer_id": 74388877,
"author": "Muhammad Mahmoud",
"author_id": 17700794,
"author_profile": "https://Stackoverflow.com/users/17700794",
"pm_score": 1,
"selected": false,
"text": "head"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74357445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20447384/"
] |
74,357,452 | <pre><code>emp_dict = {'Name1' : ['2','M','10',5,datetime.date(2002, 10, 10)],
'Name2' : ['3','G','5',7,datetime.date(2003, 10, 10)],
'Name3' : ['1','M','15',9,datetime.date(2004, 10, 10)],
'Name4' : ['4','G','3',3,datetime.date(2010, 10, 10)],
'Name5' : ['5','M','5',8,datetime.date(2006, 10, 10)]}
</code></pre>
<p>In my dictionary (emp_dict) values are list containing string, integer and date. Value list include</p>
<pre><code>Index 0 - ID
Index 1 - Gender
Index 2 - Department
Index 3 - Rating
Index 4 - DoJ
</code></pre>
<p>In the value list with index 3 is the rating given to the employee which is the key. I want to sort the data based on employees with highest rating and print the top 2 employees details.</p>
<p><strong>Output</strong></p>
<pre><code>Name3
ID : 1
Gender : M
Department : 15
Rating : 9
DoJ : (2004/10/10)
Name5
ID : 5
Gender : M
Department : 5
Rating : 8
DoJ : (2006/10/10)
</code></pre>
| [
{
"answer_id": 74359058,
"author": "diyifi3030",
"author_id": 20447384,
"author_profile": "https://Stackoverflow.com/users/20447384",
"pm_score": 0,
"selected": false,
"text": "export default defineNuxtConfig({\ncss: [\n '@/css/bootstrap.rtl.min.css'\n],\napp: {\n head: {\n script: [\n {\n src: '_nuxt/js/bootstrap.bundle.min.js',\n }\n ],\n }\n}\n})\n"
},
{
"answer_id": 74388877,
"author": "Muhammad Mahmoud",
"author_id": 17700794,
"author_profile": "https://Stackoverflow.com/users/17700794",
"pm_score": 1,
"selected": false,
"text": "head"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74357452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20447167/"
] |
74,357,458 | <pre><code>{path: 'user/home', component: HomeComponent},
{path: 'user/other', component: OtherComponent}
</code></pre>
<p>And</p>
<pre><code>{
path: 'user', children: [
{path: 'home', component: HomeComponent},
{path: 'other', component: OtherComponent}
]
}
</code></pre>
<p>What are child routes to angular for? What is the fundamental difference between these two records?</p>
<p>Will patchmatch work the same for both cases?
What I mean. Angular divides the url path into a tree of segments (user/list -> user, list).</p>
<p><strong>pathMatch: full</strong> tells angular that it is required to match the segment value completely without going down to the child elements if this value does not match.
Is it true that regardless of the recording option, the url segment tree will have the same structure?</p>
<p><a href="https://stackoverflow.com/questions/42992212/in-angular-what-is-pathmatch-full-and-what-effect-does-it-have">I'm a little confused about the division of URLs into segments and the correlation of these segments with child components in angular.</a></p>
| [
{
"answer_id": 74357500,
"author": "MGX",
"author_id": 20059754,
"author_profile": "https://Stackoverflow.com/users/20059754",
"pm_score": 1,
"selected": false,
"text": "{\n path: 'user', canActivateChild: [ActivateGuard], children: [\n {path: 'home', component: HomeComponent},\n {path: 'other', component: OtherComponent}\n ]\n}\n\n{path: 'user/home', canActivate: [ActivateGuard], component: HomeComponent},\n{path: 'user/other', canActivateChild: [ActivateGuard], component: OtherComponent}\n"
},
{
"answer_id": 74357541,
"author": "Fabian Strathaus",
"author_id": 17298437,
"author_profile": "https://Stackoverflow.com/users/17298437",
"pm_score": 0,
"selected": false,
"text": "parent"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74357458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15151531/"
] |
74,357,464 | <p>I have a question about binary variable.
As you can see in the photo, I have an ordinal variable consisting of 4 categories, on this variable, I need to apply classification algorithms in machine learning. <strong>How can I make this variable a binary variable, can you help me write the necessary codes in R ?</strong></p>
<p>str(belonging)
dbl+lbl [1:2993] 1, 1, 1, 4, 1, 3, 2, 2, 3, 3, 2, 2, 3, 1, 2, 2, 1, 2, 4, 1, 3, 2, 1, 2, 1, 4, 1, 2, 1, 1, 3, 1, 3,...
@ label : chr "GEN\AGREE\BELONG AT SCHOOL"
@ format.spss: chr "F1.0"
@ labels : Named num [1:5] 1 2 3 4 9
..- attr(*, "names")= chr [1:5] "Agree a lot" "Agree a little" "Disagree a little" "Disagree a lot" ...</p>
<p>Levels of the variable : "agree a lot", "agree a little", "disagree a lot", "disagree a little", I want to make these into "agree" and "disagree", and then I want to label the agree to 1 and the disagree level to 0.</p>
| [
{
"answer_id": 74357500,
"author": "MGX",
"author_id": 20059754,
"author_profile": "https://Stackoverflow.com/users/20059754",
"pm_score": 1,
"selected": false,
"text": "{\n path: 'user', canActivateChild: [ActivateGuard], children: [\n {path: 'home', component: HomeComponent},\n {path: 'other', component: OtherComponent}\n ]\n}\n\n{path: 'user/home', canActivate: [ActivateGuard], component: HomeComponent},\n{path: 'user/other', canActivateChild: [ActivateGuard], component: OtherComponent}\n"
},
{
"answer_id": 74357541,
"author": "Fabian Strathaus",
"author_id": 17298437,
"author_profile": "https://Stackoverflow.com/users/17298437",
"pm_score": 0,
"selected": false,
"text": "parent"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74357464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20447394/"
] |
74,357,465 | <p>I have dataframe which has one nan value in column <code>B</code>.</p>
<pre><code>df_stack = pd.DataFrame({'A': [2, 4, 8, 0,6],
'B': [2, 4, np.NaN, 5,7],
'C': [10, 2, 1, 8,9]},
index=['1', '2', '3', '4', '5'])
A B C
1 2 2.0 10
2 4 4.0 2
3 8 NaN 1
4 0 5.0 8
5 6 7.0 9
</code></pre>
<p>This nan value should be replaced by a value so that the new value represent the same percentage change as column C. So I used this technique and it works.</p>
<pre><code>df_stack['B'] = df_stack['B'].fillna(
(
df_stack['C'] /
df_stack['C'].shift(1)
) * df_stack['B'].shift(1)
)
A B C
1 2 2.0 10
2 4 4.0 2
3 8 2.0 1
4 0 5.0 8
5 6 7.0 9
</code></pre>
<p>But the issue arises when there are two or more consecutive nan values. It replaces only the first nan and keep the rest.</p>
<pre><code>df_stack = pd.DataFrame({'A': [2, 4, 8, 0,6],
'B': [2, 4, np.NaN, np.NaN ,7],
'C': [10, 2, 1, 8,9]},
index=['1', '2', '3', '4', '5'])
df_stack['B'] = df_stack['B'].fillna(
(
df_stack['C'] /
df_stack['C'].shift(1)
) * df_stack['B'].shift(1)
)
A B C
1 2 2.0 10
2 4 4.0 2
3 8 2.0 1
4 0 NaN 8
5 6 7.0 9
</code></pre>
<p>Is there any way without using for loop to do this operation so that the value will be changed row by row (from top to bottom)? My expected output is this:</p>
<pre><code>df_stack = pd.DataFrame({'A': [2, 4, 8, 0,6],
'B': [2, 4, np.NaN, np.NaN ,7],
'C': [10, 2, 1, 8,9]},
index=['1', '2', '3', '4', '5'])
df_stack['B'] = df_stack['B'].fillna(
(
df_stack['C'] /
df_stack['C'].shift(1)
) * df_stack['B'].shift(1)
)
A B C
1 2 2.0 10
2 4 4.0 2
3 8 2.0 1
4 0 16.0 8
5 6 7.0 9
</code></pre>
| [
{
"answer_id": 74358137,
"author": "EMT",
"author_id": 12243638,
"author_profile": "https://Stackoverflow.com/users/12243638",
"pm_score": 0,
"selected": false,
"text": "for i in range(len(df_stack[\"B\"):\n if len(df_stack[(df_stack['B'].isnull()) & (df_stack['B'].shift(i).isnull())])>0:\n continue\n else:\n break\n"
},
{
"answer_id": 74358172,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": true,
"text": "cumprod"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74357465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12243638/"
] |
74,357,518 | <p>this is the code for expanding/collapsing an item. how can I Expand all items in a recycler view with a single button click?</p>
<pre><code> private fun expandParentRow(position: Int){ \\to expand an item
val currentBoardingRow = list[position]
val services = currentBoardingRow.gameDetes
currentBoardingRow.isExpanded = true
var nextPosition = position
if(currentBoardingRow.type == Constants.PARENT) {
services?.forEach { service ->
val parentModel = IndividualReport()
parentModel.type = Constants.CHILD
val subList: ArrayList<GameDete> = ArrayList()
subList.add(service)
parentModel.gameDetes = subList
list.add(++nextPosition, parentModel)
}
notifyDataSetChanged()
}
}
private fun collapseParentRow(position: Int){ \\ to collapse an item
val currentBoardingRow = list[position]
val services = currentBoardingRow.gameDetes
list[position].isExpanded = false
if(list[position].type==Constants.PARENT){
services?.forEach { _ ->
list.removeAt(position + 1)
}
notifyDataSetChanged()
}
}
</code></pre>
| [
{
"answer_id": 74358137,
"author": "EMT",
"author_id": 12243638,
"author_profile": "https://Stackoverflow.com/users/12243638",
"pm_score": 0,
"selected": false,
"text": "for i in range(len(df_stack[\"B\"):\n if len(df_stack[(df_stack['B'].isnull()) & (df_stack['B'].shift(i).isnull())])>0:\n continue\n else:\n break\n"
},
{
"answer_id": 74358172,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": true,
"text": "cumprod"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74357518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11855624/"
] |
74,357,533 | <p>So basically I'm trying to get all the documents (as it's called in Mongodb) in a collection. I've watched some Youtube videos and they use the db.collection.find() method to do this.</p>
<p>In my case however this doesn't work for some reason. I'm using node js take a look at my code below.</p>
<pre class="lang-js prettyprint-override"><code>import { MongoClient } from 'mongodb';
const client = new MongoClient(uri);
const database = client.db(dbase);
const collection = database.collection(collec);
const getAll = async () => {
const res = await collection.find({});
await client.close();
return res;
console.log(getAll);
</code></pre>
<p>I was expecting some sort of an object or maybe an array of objects but unfortunatly I get this:</p>
<pre class="lang-bash prettyprint-override"><code><ref *1> FindCursor {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
[Symbol(kCapture)]: false,
[Symbol(client)]: MongoClient {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
</code></pre>
<p>I'm not going to show the full error message since it contains sesetive information but this is the first few lines which I think should be save to share.</p>
<p>Thanks in advance...</p>
| [
{
"answer_id": 74358137,
"author": "EMT",
"author_id": 12243638,
"author_profile": "https://Stackoverflow.com/users/12243638",
"pm_score": 0,
"selected": false,
"text": "for i in range(len(df_stack[\"B\"):\n if len(df_stack[(df_stack['B'].isnull()) & (df_stack['B'].shift(i).isnull())])>0:\n continue\n else:\n break\n"
},
{
"answer_id": 74358172,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": true,
"text": "cumprod"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74357533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20028924/"
] |
74,357,580 | <p>In my code, I have a 2 lined text. I want to move the second text (nth-child(3): 10 x apples) to the line below when the width of the screen changes. I have tried <code>display:block</code> and <code>white-space:pre</code>. But it didn't work and the sentence did not move to next line. My code and a screenshot is below. What should I do to achieve this?</p>
<pre><code>@media (min-width: breakpoint-max(sm)) {
.fruit-detail {
& :nth-child(3) {
display: block;
}
}
}
<div class="fruit-detail">
<span class="day-one ng-star-inserted">
"Yesterday"
</span>
<span class="ng-star-inserted">
Today
</span>
<span> 10 x </span>
<span>Apples</span>
</div>
</code></pre>
<p><a href="https://i.stack.imgur.com/2sxUs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2sxUs.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74357885,
"author": "Señor Lancho",
"author_id": 19871890,
"author_profile": "https://Stackoverflow.com/users/19871890",
"pm_score": 2,
"selected": false,
"text": " .parentContainer::after{\n content: \"\\a\";\n white-space: pre;\n }\n"
},
{
"answer_id": 74357888,
"author": "Cédric",
"author_id": 17684809,
"author_profile": "https://Stackoverflow.com/users/17684809",
"pm_score": 0,
"selected": false,
"text": ".fruit-detail"
},
{
"answer_id": 74373515,
"author": "Darshil Jani",
"author_id": 19232446,
"author_profile": "https://Stackoverflow.com/users/19232446",
"pm_score": 1,
"selected": false,
"text": "display:none;"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74357580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15782098/"
] |
74,357,586 | <p>I am trying to converet the list of list into a dictionary using defaultdict method.</p>
<p>I have a list of list:</p>
<pre class="lang-py prettyprint-override"><code>a= [[1,2],[2,3,4], [4,5,6], [3,7], [6,10]]
</code></pre>
<p>I want the output in this format:</p>
<pre class="lang-py prettyprint-override"><code>{1: [0], 2: [0], 2: [1], 3: [1], 4: [1], 4: [2], 5: [2], 6: [2], 3: [3], 7: [3], 6: [4], 10: [4]})
</code></pre>
<p>Here is my code:</p>
<pre class="lang-py prettyprint-override"><code>a =[[1,2],[2,3,4], [4,5,6], [3,7], [6,10]]
clusters = defaultdict(list)
cluster_sz = {}
cliques = []
cluster_idx = 0
for clique in a:
cliques.append(clique)
for v in clique:
clusters[v].append(cluster_idx)
cluster_idx+=1
print(clusters)
</code></pre>
<p>The output of this code is:</p>
<pre class="lang-py prettyprint-override"><code>{1: [0], 2: [0,1], 3: [1,3], 4: [1, 2], 5: [2], 6: [2, 4], 7: [3], 10: [4]})
</code></pre>
<p>But I need this type of output:</p>
<pre class="lang-py prettyprint-override"><code>{1: [0], 2: [0], 2: [1], 3: [1], 4: [1], 4: [2], 5: [2], 6: [2], 3: [3], 7: [3], 6: [4], 10: [4]})
</code></pre>
| [
{
"answer_id": 74357680,
"author": "CTRL ALT DELETE",
"author_id": 20445337,
"author_profile": "https://Stackoverflow.com/users/20445337",
"pm_score": 0,
"selected": false,
"text": "a = [[1,2],[2,3,4], [4,5,6], [3,7], [6,10]]\n\nd = {}\n\nfor i, sublist in enumerate(a):\n for num in sublist:\n if num not in d:\n d[num] = []\n d[num].append(i)\n\nprint(d)\n"
},
{
"answer_id": 74357745,
"author": "Piotr Żak",
"author_id": 9455902,
"author_profile": "https://Stackoverflow.com/users/9455902",
"pm_score": 0,
"selected": false,
"text": "dict = {1: [0], 2: [0,1], 3: [1,3], 4: [1, 2], 5: [2], 6: [2, 4], 7: [3], 10: [4]}\nconvertedDict = {}\n\nfor (i, j) in dict.items():\n if len(j) > 1:\n for k in j:\n convertedDict[i] = [k]\n else:\n convertedDict[i] = j\n \n \nprint (convertedDict)\n"
},
{
"answer_id": 74357768,
"author": "assume_irrational_is_rational",
"author_id": 11622508,
"author_profile": "https://Stackoverflow.com/users/11622508",
"pm_score": 1,
"selected": false,
"text": "a= [[1,2],[2,3,4], [4,5,6], [3,7], [6,10]]\nb = [{r:i} for i,k in enumerate(a) for r in k ]\n\n[{1: 0}, {2: 0}, {2: 1}, {3: 1}, {4: 1}, {4: 2}, {5: 2}, {6: 2}, {3: 3}, {7: 3}, {6: 4}, {10: 4}]\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74357586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18804177/"
] |
74,357,604 | <p>Why this <em>f value()</em> cannot access the <strong>const num = 3</strong> inside another function though it's being called there but can access the variable below it?</p>
<pre><code>function xyz() {
const num = 3
value() // <-- why this *f value()* cannot access the **num** from here
}
function value() {
console.log(num)
}
const num = 100 // <-- but it can access the **num** here even though it's below of it.
xyz()
</code></pre>
<p>the Output is num = <strong>100</strong></p>
<p>I expected the output would be the num = <strong>3</strong>.</p>
| [
{
"answer_id": 74357712,
"author": "Jaona",
"author_id": 9116854,
"author_profile": "https://Stackoverflow.com/users/9116854",
"pm_score": 0,
"selected": false,
"text": "function xyz() {\nconst num = 3\nvalue(num) // <-- call it with params *num*\n\nfunction value(num) {\n console.log(num)\n}\n\nconst num = 100 \nxyz()\n"
},
{
"answer_id": 74357773,
"author": "T.J. Crowder",
"author_id": 157247,
"author_profile": "https://Stackoverflow.com/users/157247",
"pm_score": 2,
"selected": true,
"text": "function handleInputEvents(selector) {\n function showChange(value) {\n console.log(`Value for \"${selector}\" changed to \"${value}\"`);\n }\n document.querySelector(selector).addEventListener(\"input\", (event) => {\n showChange(event.currentTarget.value);\n });\n}\n\nhandleInputEvents(\".first\");\nhandleInputEvents(\".second\");"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74357604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20447017/"
] |
74,357,631 | <p>Suppose I have the decimal number 8, and I want to conver it into a binary list of length 8.
It means if I give input as 8, I should get output as [0,0,0,0,1,0,0,0]. I am looking for an inbuilt command in python that can do that in a very short time (in nano-seconds).</p>
<p>I have tried the foolowing comman which is giving me error:</p>
<pre><code>[int(x) for x in list('{0:8b}'.format(8))]
</code></pre>
<p>The error I am getting is</p>
<pre><code>ValueError: invalid literal for int() with base 10: ' '
</code></pre>
| [
{
"answer_id": 74357698,
"author": "Abdul Niyas P M",
"author_id": 6699447,
"author_profile": "https://Stackoverflow.com/users/6699447",
"pm_score": 2,
"selected": false,
"text": ">>> [int(i) for i in bin(8)[2:].zfill(8)]\n[0, 0, 0, 0, 1, 0, 0, 0]\n"
},
{
"answer_id": 74357792,
"author": "Cobra",
"author_id": 17580381,
"author_profile": "https://Stackoverflow.com/users/17580381",
"pm_score": 0,
"selected": false,
"text": "n = 8\n\nlst = list(map(int, f'{n:08b}'))\n\nprint(lst)\n"
},
{
"answer_id": 74358004,
"author": "Jason Tsai",
"author_id": 20413091,
"author_profile": "https://Stackoverflow.com/users/20413091",
"pm_score": 0,
"selected": false,
"text": "[function(item) for item in list]\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74357631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20417383/"
] |
74,357,649 | <p>Is there a way to create a CoroutineScope that is tied to the loggedIn user?</p>
<p>Basically, the idea is to create a coroutine scope, which I can cancel when the user logouts so that all the jobs being done on that scope gets cancelled.</p>
<p>My idea is to create a singleton class that holds a map between the userId and coroutineScope then inject the class wherever I need. Then I would observe the loggedInUser and cancel the scope that doesn't belong to the loggedInUser and then delete the scope.</p>
<p>Is this a good way or is there a more elegant way to achieve this?</p>
| [
{
"answer_id": 74358167,
"author": "Gaurav Bharadia",
"author_id": 11004504,
"author_profile": "https://Stackoverflow.com/users/11004504",
"pm_score": 0,
"selected": false,
"text": "lifecycleScope.launch {\n dataStoreGetUserData().firstOrNull {\n \n callApi()\n\n true\n }\n }\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74357649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15543809/"
] |
74,357,690 | <p>According to the Serverless <a href="https://www.serverless.com/framework/docs/guides/parameters#" rel="nofollow noreferrer">documentation</a>, I should be able to define params within the dashboard/console. But when I navigate there, the inputs are disabled:
<a href="https://i.stack.imgur.com/gllCD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gllCD.png" alt="enter image description here" /></a></p>
<p>I've tried following the <a href="https://www.serverless.com/framework/docs/guides/parameters#cli-parameters" rel="nofollow noreferrer">instructions</a> to update via CLI, with: <code>serverless deploy --param="domain=myapp.com" --param="key=value"</code>. The deploy runs successfully (I get a <code>✔ Service deployed to...</code> message with no errors), but nothing appears in my dashboard. Likewise, when I run a command to check whether there are any params stored: <code>serverless param list</code>, I get</p>
<pre><code>Running "serverless" from node_modules
No parameters stored
</code></pre>
| [
{
"answer_id": 74366129,
"author": "pgrzesik",
"author_id": 3864176,
"author_profile": "https://Stackoverflow.com/users/3864176",
"pm_score": 1,
"selected": false,
"text": "param"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74357690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11664580/"
] |
74,357,696 | <p>I'm trying to get the php version in the form PHP_MAJOR_VERSION.PHP_MINOR_VERSION :</p>
<pre class="lang-bash prettyprint-override"><code>$ php -r 'print $PHP_MAJOR_VERSION.$PHP_MINOR_VERSION;'
PHP Warning: Undefined variable $PHP_MAJOR_VERSION in Command line code on line 1
PHP Warning: Undefined variable $PHP_MINOR_VERSION in Command line code on line 1
$
</code></pre>
<p><a href="https://www.php.net/manual/en/reserved.constants.php" rel="nofollow noreferrer">This doc</a> says :</p>
<blockquote>
<p>These constants are defined by the PHP core.</p>
</blockquote>
<p>How can I load them ?</p>
| [
{
"answer_id": 74357781,
"author": "fseydel",
"author_id": 948827,
"author_profile": "https://Stackoverflow.com/users/948827",
"pm_score": 1,
"selected": false,
"text": "$ php -r 'print PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION;'\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74357696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5649639/"
] |
74,357,706 | <p>I have an issue with routing in angular. I have a parent which is the shell component and it is loaded from app component. The Shell has the left menu and the dynamic content section on the right side. Once i click on a link in left menu, i need to render the list of of reports as tabs and each report is a child component.</p>
<p>Now, when i try to click on a report , the URL matches with the paths provided in reports.component.ts but it does not render the child component.</p>
<p>I am not sure if I am doing it the correct way.
Could anyone please advice me ?</p>
<blockquote>
<p><strong>app.routing.module.ts</strong></p>
<pre><code>{
path: 'app',
children: [
{ path: 'parent/:param', loadChildren: () => import('./report-list.module').then(m => m.ReportListModule) },
]
}
</code></pre>
<p><strong>app.component.html</strong></p>
</blockquote>
<pre><code><shell></shell> <!-- Renders shell.component.html -->
</code></pre>
<blockquote>
<p><strong>shell.component.html</strong></p>
</blockquote>
<pre><code><reports></reports> <!-- Renders reports.component.html -->
<othermodules></othermodules>
</code></pre>
<blockquote>
<p><strong>reports.component.html</strong></p>
</blockquote>
<pre><code><router-outlet></router-outlet>
</code></pre>
<blockquote>
<p><strong>reports.component.ts</strong></p>
</blockquote>
<pre><code> this.router.navigate(['/app/parent/report1'], { queryParams: params});
this.router.navigate(['/app/parent/report2'], { queryParams: params});
this.router.navigate(['/app/parent/report3'], { queryParams: params});
this.router.navigate(['/app/parent/report4'], { queryParams: params});
</code></pre>
<blockquote>
<p><strong>report-list.module.ts</strong></p>
</blockquote>
<pre><code>const routes: Routes = [
{ path: 'app/parent/report1', component: Report1Component },
{ path: 'app/parent/report2', component: Report2Component },
{ path: 'app/parent/report3', component: Report3Component },
{ path: 'app/parent/report4', component: Report4Component } ];
@NgModule({ declarations: [], imports: [
Report1Module,
Report2Module,
Report3Module,
Report4Module,
RouterModule.forChild(routes) ] })
</code></pre>
| [
{
"answer_id": 74357795,
"author": "Parth M. Dave",
"author_id": 12119351,
"author_profile": "https://Stackoverflow.com/users/12119351",
"pm_score": -1,
"selected": false,
"text": "const routes: Routes = [ \n{ path: 'report1', component: Report1Component }, \n{ path: 'report2', component: Report2Component },\n{ path: 'report3', component: Report3Component },\n{ path: 'report4', component: Report4Component } ];\n"
},
{
"answer_id": 74358485,
"author": "Nithin",
"author_id": 7572925,
"author_profile": "https://Stackoverflow.com/users/7572925",
"pm_score": 1,
"selected": true,
"text": "this.router.navigate(['/app/parent/reports/report1'], { queryParams: params}); \n\nconst routes: Routes = [ \n{ path: 'app/parent/reports/report1', component: Report1Component },\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74357706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7572925/"
] |
74,357,738 | <p>lets say we have two classes(these are just sample classses):</p>
<pre><code>public class Post
{
public int ID { get; set; }
public string Text { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
}
public class Tag
{
public int ID { get; set; }
[Required]
public string Label { get; set;}
public virtual ICollection<Post> Posts { get; set; }
}
</code></pre>
<p><strong>P.S after execution "PostTag" table is created in database.</strong></p>
<p>So in my current database there is the following situation: I have separate service for getting "<strong>Posts</strong>" and I am writing this data directly to database.<strong>(lets say we have 500 records in database. P.S these are max number of "Posts" I will be working around)</strong>.</p>
<p>Then I have service for "Tag". This service does the following: I am getting data of "Tags" from API**(It is about 1500 records)**, which is collection and each "Tag" contains its own "Post" collection in returned data <strong>(lets say each "Tag" has 100 records of "Posts").</strong></p>
<p>So the problem is that, after I get all the "<strong>Tags</strong>" and then write them in database, in "<strong>Post</strong>" tables, "<strong>Posts</strong>" that was returned during "Tag" service are also written in table, I mean before calling "<strong>Tag</strong>" service, <strong>If we had 500 records, now we have 15000 + 500 and that is wrong.</strong></p>
<p>I want to happen following: when I call "<strong>Tag</strong>" service, it should just write "<strong>Tags</strong>" in database table and instead of adding "<strong>Posts</strong>" in table, use already written data in "Posts" table in order to set up relationship in "<strong>PostTag</strong>" table.</p>
<p><strong>So in tables there should be this kind of situation: Post - 500 records, Tags - 1500 records and PostTag - the amount of records that are needed for relationship</strong></p>
<p>How can I accomplish that?</p>
| [
{
"answer_id": 74357795,
"author": "Parth M. Dave",
"author_id": 12119351,
"author_profile": "https://Stackoverflow.com/users/12119351",
"pm_score": -1,
"selected": false,
"text": "const routes: Routes = [ \n{ path: 'report1', component: Report1Component }, \n{ path: 'report2', component: Report2Component },\n{ path: 'report3', component: Report3Component },\n{ path: 'report4', component: Report4Component } ];\n"
},
{
"answer_id": 74358485,
"author": "Nithin",
"author_id": 7572925,
"author_profile": "https://Stackoverflow.com/users/7572925",
"pm_score": 1,
"selected": true,
"text": "this.router.navigate(['/app/parent/reports/report1'], { queryParams: params}); \n\nconst routes: Routes = [ \n{ path: 'app/parent/reports/report1', component: Report1Component },\n"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74357738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18183385/"
] |
74,357,741 | <p>I am wondering how I can add one column from a dataframe, to another based on the dates in both columns. I tried to simplify this as much as I can.</p>
<p>I have two dataframes one is filled with event types and the cost done for the event, the other being the observation from a nearby station giving how much rainfall occurred as well. But</p>
<p>Here is what the dataframes looks like:</p>
<pre><code>d1 = {'ObservationDate': ['2021-09-11', '2021-06-24', '2020-09-23', '2015-10-09'],
'EventType': ['Flood', 'Flood', 'Wind', 'Hail'],
'Closures': ['Schools', 'Schools', 'None', 'Offices'],
'Cost': [1000, 4000, 100, 8000]}
events = pd.DataFrame(data = d1)
display(events)
ObservationDate EventType Closures Cost
0 2021-09-11 Flood Schools 1000
1 2021-06-24 Flood Schools 4000
2 2020-09-23 Wind None 100
3 2015-10-09 Hail Offices 8000
</code></pre>
<p>And,</p>
<pre><code>d2 = {'ObservationDate': ['2021-09-11', '2021-06-24', '2015-10-09', '2018-07-16'],
'Rainfall': [45, 90, 32, 22]}
observation = pd.DataFrame(data = d2)
display(observation)
ObservationDate Rainfall
0 2021-09-11 45
1 2021-06-24 90
2 2015-10-09 32
3 2018-07-16 22
</code></pre>
<p>What I then did was filtered the observation DataFrame to get only the relevant event dates (in my actual code I do have the dates converted to the Pandas DateTime type).</p>
<p><code> filtered = observation[observation.ObservationDate.dt.strftime('%y%m%d').isin(events.ObservationDate.dt.strftime('%y%m%d'))]</code></p>
<p>What I am trying to do is take the Dates in the filtered dataframe and then add the "Event Type" column from the Event Dataframe, but only for those specific dates.</p>
<p>The ideal result would look like:</p>
<pre><code> ObservationDate Rainfall EventType
0 2021-09-11 45 Flood
1 2021-06-24 90 Flood
2 2015-10-09 32 Hail
</code></pre>
<p>Things I have tried but I can't seem to get it to work right is merging them, also trying to take the index of where the "isin" is true, as well as a few other mindless attempts.</p>
<p>I intuitively know how I would go about this, I would honestly just loop through each of the rows then find where the dates are equal to one another, then assign that value to the column. But I am trying to find a more "Python" way of doing this.</p>
<p>Any help is appreciated.</p>
<p>For further context, when I tried Merge on the full dataframe I have like was suggested by Clegange. The dataframe went from having 467,132 entries (taking up 110.5+ MB of memory) to having 2,317,895 entries (583.6+ MB). It seemed like when I was using merge, it was duplicating entries multiple times and not giving expected result on the full dataframe I have.</p>
| [
{
"answer_id": 74357790,
"author": "Panda Kim",
"author_id": 20430449,
"author_profile": "https://Stackoverflow.com/users/20430449",
"pm_score": 0,
"selected": false,
"text": "merge"
},
{
"answer_id": 74357844,
"author": "Celius Stingher",
"author_id": 11897007,
"author_profile": "https://Stackoverflow.com/users/11897007",
"pm_score": 2,
"selected": true,
"text": "merge()"
}
] | 2022/11/08 | [
"https://Stackoverflow.com/questions/74357741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9463725/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.