qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,193,638 | <p>I am trying to get Routes based on a list that is coming from firebase realtime db and here is my code :</p>
<pre><code>import { onValue, ref } from "firebase/database";
import React, { useEffect, useState } from "react";
import { Route, Routes } from "react-router-dom";
import "./App.css";
import Changepassword from "./Changepassword";
import Editprofile from "./Editprofile";
import Explore from "./Explore";
import { database } from "./firebase";
import ForgotPassword from "./ForgotPassword";
import Home from "./Home";
import Login from "./Login";
import NotFound from "./NotFound";
import SignUp from "./SignUp";
import ViewingProfile from "./ViewingProfile";
function App() {
const [array2, setArray2] = useState([]);
var array1 = [];
useEffect(() => {
onValue(ref(database, "/users/"), (snapshot) => {
Object.values(snapshot.val()).map((w) => {
return array1.push(w);
});
});
const newArray = array1.map((object) => object.username);
setArray2(newArray);
}, [array1]);
return (
<Routes>
<Route path="/" element={<Home />} />
<Route path="/login" element={<Login />} />
<Route path="/signup" element={<SignUp />} />
<Route path="/*" element={<NotFound />} />
<Route path="/edit-profile" element={<Editprofile />} />
<Route path="/change-password" element={<Changepassword />} />
<Route path="/explore" element={<Explore />} />
<Route path="/forgot-password" element={<ForgotPassword />} />
{array2.map((name) => {
return (
<Route path={`/${name}`} element={<ViewingProfile name={name} />} />
);
})}
</Routes>
);
}
export default App;
</code></pre>
<p>So it works fine when i run it but in the console there is a error which is repeating like per nano second and i guess that slows the app down a lot so what should i do here to resolve the error or just tell the app not to give THAT specific error?</p>
<hr />
| [
{
"answer_id": 74193740,
"author": "felixkpt",
"author_id": 7764721,
"author_profile": "https://Stackoverflow.com/users/7764721",
"pm_score": 0,
"selected": false,
"text": "useEffect(() => {\n return onValue() {\n .... \n }\n })\n"
},
{
"answer_id": 74193748,
"author":... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16814937/"
] |
74,193,655 | <p>I have a large dataset which contains a date column that covers from the year 2019. Now I do want to generate number of weeks on a separate column that are contained in those dates.</p>
<p>Here is how the date column looks like:</p>
<pre><code>import pandas as pd
data = {'date': ['2019-09-10', 'NaN', '2019-10-07', '2019-11-04', '2019-11-28',
'2019-12-02', '2020-01-24', '2020-01-29', '2020-02-05',
'2020-02-12', '2020-02-14', '2020-02-24', '2020-03-11',
'2020-03-16', '2020-03-17', '2020-03-18', '2021-09-14',
'2021-09-30', '2021-10-07', '2021-10-08', '2021-10-12',
'2021-10-14', '2021-10-15', '2021-10-19', '2021-10-21',
'2021-10-26', '2021-10-28', '2021-10-29', '2021-11-02',
'2021-11-15', '2021-11-16', '2021-12-01', '2021-12-07',
'2021-12-09', '2021-12-10', '2021-12-14', '2021-12-15',
'2022-01-13', '2022-01-14', '2022-01-21', '2022-01-24',
'2022-01-25', '2022-01-27', '2022-01-31', '2022-02-01',
'2022-02-10', '2022-02-11', '2022-02-16', '2022-02-24']}
df = pd.DataFrame(data)
</code></pre>
<p>Now as from the first day this data was collected, I want to count 7 days using the date column and create a week out it. an example if the first week contains the 7 dates, I create a column and call it week one. I want to do the same process until the last week the data was collected.</p>
<p>Maybe it will be a good idea to organize the dates in order as from the first date to current one.</p>
<p>I have tried this but its not generating weeks in order, it actually has repetitive weeks.</p>
<pre><code>pd.to_datetime(df['date'], errors='coerce').dt.week
</code></pre>
<p>My intention is, as from the first date the date was collected, count 7 days and store that as week one then continue incrementally until the last week say week number 66.</p>
<p>Here is the expected column of weeks created from the date column</p>
<pre><code>import pandas as pd
week_df = {'weeks': ['1', '2', "3", "5", '6']}
df_weeks = pd.DataFrame(week_df)
</code></pre>
| [
{
"answer_id": 74193740,
"author": "felixkpt",
"author_id": 7764721,
"author_profile": "https://Stackoverflow.com/users/7764721",
"pm_score": 0,
"selected": false,
"text": "useEffect(() => {\n return onValue() {\n .... \n }\n })\n"
},
{
"answer_id": 74193748,
"author":... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11883900/"
] |
74,193,685 | <p>I am a beginner in Django and I am working on a project which requires Custom user model as I Don't require is_staff, is_superuser, is_admin.</p>
<p>So, but searching and other ways I made my own Custom user model. But it is not working and I am stuck on it for days.</p>
<p>It will be a huge help if someone can help me with the code.</p>
<p>settings.py</p>
<pre><code>
AUTH_USER_MODEL = 'accounts.Usermanagement'
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
'accounts.backends.EmailAuthBackend',
]
</code></pre>
<p>backends.py</p>
<pre><code>#backends.py
# from django.contrib.auth.models import User
from django.contrib.auth.hashers import check_password
from django.contrib.auth import get_user_model
Usermanagement = get_user_model()
class EmailAuthBackend:
def authenticate(self,request,username=None,password=None):
print(request)
try:
user = Usermanagement.objects.get(emailid=username)
print(password)
print(user.password)
# print(check_password(password))
# print(user.check_password(password))
if user.check_password(password):
return user
return None
except user.DoesNotExist:
return None
def get_user(self,user_id):
try:
return user.objects.get(pk=user_id)
except user.DoesNotExist:
return None
</code></pre>
<p>views.py</p>
<pre><code># views.py
def loginPage(request):
# POST
if request.method == 'POST':
form = AuthenticationForm(request,data=request.POST)
# loginPage.html the html tag has attribute name = username for email ,
# name = password for password
if form.is_valid(): # Form Valid
email = request.POST['username']
password = request.POST['password']
#Check
print("EMAIL: ",email)
print("PASSWORD: ",password)
# Authentication USER
user = authenticate(request,username=email,password=password)
print("Authenticated ",user) # Check
# check
print(user)
if user is not None: # If User found
login(request,user,backend='accounts.backends.EmailAuthBackend')
messages.info(request, f"You are now logged in as {email}.")
return redirect("home")
else: # If User Not found
messages.error(request,"User not found")
return HttpResponse("User not found, not able to login")
else: # Form InValid
messages.error(request,"Invalid username or password.")
return HttpResponse("Form Invalid")
# GET
else:
form = AuthenticationForm()
context = {"form":form}
return render(request,"loginPage.html",context=context)
</code></pre>
<p>urls.py and other configurations are correct.</p>
<p>Problems:</p>
<ol>
<li>check_password : always False</li>
<li>In DB I have unencrypted password ( ex:- password=admin )</li>
<li>DB is a legacy(existing) DB , so I first made the DB and then I did "python manage.py inspectdb" , which created models for me and then I changed few things, but did not changed the field names or the db_table name.</li>
<li>I am very much ok to create user through SHELL.</li>
<li>In loginPage.html the html tag has attribute name = username for email , name = password for password</li>
</ol>
<p>if any other requirements I will edit the Questions</p>
| [
{
"answer_id": 74193740,
"author": "felixkpt",
"author_id": 7764721,
"author_profile": "https://Stackoverflow.com/users/7764721",
"pm_score": 0,
"selected": false,
"text": "useEffect(() => {\n return onValue() {\n .... \n }\n })\n"
},
{
"answer_id": 74193748,
"author":... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19818111/"
] |
74,193,723 | <p>Given this df</p>
<pre><code>from io import StringIO
import pandas as pd
data = StringIO('''gene_variant gene val1 val2 val3
b1 b 1 1 1
b2 b 2 11 1
b3 b 3 11 1
c2 c 1 1 1
t1 t 1 1 1
t2 t 12 2 2
t4 t 12 3 2
t5 t 1 4 3
d2 d 11 1 2
d4 d 11 1 1''')
df = pd.read_csv(data, sep='\t')
</code></pre>
<p>How do I get the gene_variant for each gene where; the gene_variant corresponds to the max value for val1 if the max value is not duplicated, and if it is duplicated, the gene_variant corresponds to the max value for val2 if the max value for val2 is not duplicated, or then just max for val3? I.e., any tiebreakers are decided by the next column until the third option.</p>
<p>EDIT: The column val2 is only considered if the max val in val1 is a duplicated/a tie. Same for val3. If the max val in val1/2 is duplicated/is a tie then the values in those columns are no longer considered. Only the values in 1 column at a time are compared.</p>
<p>I've been trying solutions based on:</p>
<pre><code>df.groupby('gene').agg(max)
</code></pre>
<p>and:</p>
<pre><code>df.groupby('gene').rank('max')
</code></pre>
<p>But I can't get there without dropping out into iteration...</p>
<p>The correct answer would be:</p>
<pre><code>b3 3
c2 1
t5 4
d2 2
</code></pre>
<p>Thanks in advance!</p>
| [
{
"answer_id": 74193740,
"author": "felixkpt",
"author_id": 7764721,
"author_profile": "https://Stackoverflow.com/users/7764721",
"pm_score": 0,
"selected": false,
"text": "useEffect(() => {\n return onValue() {\n .... \n }\n })\n"
},
{
"answer_id": 74193748,
"author":... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2186650/"
] |
74,193,747 | <p>so I am using MySQL as the database for my node app I can insert the date in <code>YYYY-MM-DD</code> format but when I get data from it returns it as <code>yyyy-mm-ddT00:00:00.000Z</code> so I want only the first part</p>
<pre class="lang-js prettyprint-override"><code>db.query(`SELECT agereement_date FROM mt_A1 WHERE ledger_num = 15`,(err,data)=>{
console.log(data)
})
</code></pre>
<p>the output is like this</p>
<pre class="lang-js prettyprint-override"><code>[
RowDataPacket {
agereement_date: 2021-03-07T18:30:00.000Z,
}
]
</code></pre>
<p>I Want only the <code>YYYY-MM-DD</code> the first part I am using some JavaScript to rectify it but it feels unnecessary is there a way to get the date in that format directly from MySQL</p>
| [
{
"answer_id": 74193864,
"author": "num8er",
"author_id": 3706693,
"author_profile": "https://Stackoverflow.com/users/3706693",
"pm_score": 2,
"selected": true,
"text": "Date"
},
{
"answer_id": 74193870,
"author": "Marcos Tulio",
"author_id": 17083385,
"author_profile... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16928810/"
] |
74,193,772 | <p>Hi guys I'm having challenges with extracting params from my route in nuxt 3.</p>
<p>The structure of my dynamic route looks like this exam_[id]_[applicant_id].vue and after loading my route looks like this http://localhost:3000/e-recruitment/exam_cl96q0u040000v1ocg2ffryio_3 and my to dynamic params are cl96q0u040000v1ocg2ffryio and 3, when I console log the params object I get this object <a href="https://i.stack.imgur.com/0mSXV.png" rel="nofollow noreferrer">screenshot</a>, what might be the problem</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>onMounted(async ()=>{
console.log(route.params.applicant_id)
console.log(route.params.id)
})</code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74193820,
"author": "arthurDent",
"author_id": 8842015,
"author_profile": "https://Stackoverflow.com/users/8842015",
"pm_score": 2,
"selected": false,
"text": "<script setup> \nconst route = useRoute();\nconsole.log(route.params.applicant_id)\nconsole.log(route.params.i... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11873195/"
] |
74,193,777 | <p>so I'm doing a project where I am fetching an HTML file and replacing the body content with the file I'm fetching.</p>
<p>So I have index.html and result.html. I have managed to get the content to switch based on the "matching search result in my input field". But the problem I have is that the script from the .js file only fires once.</p>
<p>I don't understand why that is. I want to be able to go back and forth between index.html and result.html</p>
<p>Here is my code for checking if the input field matches the file keyword:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const searchInput = document.getElementById("search");
document.getElementById("submit").addEventListener("click", function(e) {
e.preventDefault();
if(searchInput.value === "result") {
handleRequest("result.html");
searchInput.value = "";
}
e.preventDefault();
if(searchInput.value === "index") {
handleRequest("index.html");
searchInput.value = "";
}</code></pre>
</div>
</div>
</p>
<p>And this is my code for fetching the HTML:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function handleRequest(url) {
fetch(url)
.then(res => res.text())
.then((text) => {
const doc = new DOMParser().parseFromString(text, 'text/html');
const body = document.querySelector('body');
body.innerHTML = '';
body.append(doc.querySelector('body'));
});
}</code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74193820,
"author": "arthurDent",
"author_id": 8842015,
"author_profile": "https://Stackoverflow.com/users/8842015",
"pm_score": 2,
"selected": false,
"text": "<script setup> \nconst route = useRoute();\nconsole.log(route.params.applicant_id)\nconsole.log(route.params.i... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18553197/"
] |
74,193,780 | <p>for example i have a data like csv file:</p>
<pre><code> x(col) y(row) Value
0 0 5
3 1 10
2 2 2
1 3 6
</code></pre>
<p>output:</p>
<pre><code> [[5,0,0,0],
[0,10,0,0],
[0, 0,2,0],
[0, 0,0,6]]
</code></pre>
| [
{
"answer_id": 74193820,
"author": "arthurDent",
"author_id": 8842015,
"author_profile": "https://Stackoverflow.com/users/8842015",
"pm_score": 2,
"selected": false,
"text": "<script setup> \nconst route = useRoute();\nconsole.log(route.params.applicant_id)\nconsole.log(route.params.i... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20016854/"
] |
74,193,789 | <p>Trying to run a select statement using the below code. I'm parsing a SQL table name parameter
whose value is determined by a case statement. This then assigns the dataset to a global datasource used in another form. However, the app is returning a "Syntax error in FROM clause" dialogue.</p>
<p>I've assigned the correct datatype and during my tests, I can confirm that the parameter's value is what it needs to be i.e. "ACCOUNTS" for case 1.</p>
<p>I'm new to using ADO but ADOQUERY.SQL.GetText is returning the SQL statement with the parameter placeholder ":ATABLE" rather than the parameter value, though I am currently assuming this is normal.</p>
<pre><code>procedure TfrmDataModule.FindAllRecords(Sender: TObject; recordType: Integer);
var
ADOQuery : TADOQuery;
Param : TParameter;
begin
case recordType of
1 : currentRecordType := 'ACCOUNTS';
2 : currentRecordType := 'CONTACTS';
3 : currentRecordType := 'USERS';
end;
{ SQL Query }
SQLStr := 'SELECT * FROM :ATABLE';
{ Create the query. }
ADOQuery := TADOQuery.Create(Self);
ADOQuery.Connection := ADOConn;
ADOQuery.SQL.Add(SQLStr);
{ Update the parameter that was parsed from the SQL query. }
Param := ADOQuery.Parameters.ParamByName('ATABLE');
Param.DataType := ftString;
Param.Value := currentRecordType;
{ Set the query to Prepared--it will improve performance. }
ADOQuery.Prepared := true;
try
ADOQuery.Active := True;
except
on e: EADOError do
begin
MessageDlg('Error while doing query', mtError,
[mbOK], 0);
Exit;
end;
end;
{ Create the data source. }
DataSrc := TDataSource.Create(Self);
DataSrc.DataSet := ADOQuery;
DataSrc.Enabled := true;
end;
</code></pre>
<p>Edit: More info. The query does work if I comment out the Param lines and replace the SQLStr :ATABLE with the concatenated SQLStr and the case variable currentRecordType.</p>
| [
{
"answer_id": 74193820,
"author": "arthurDent",
"author_id": 8842015,
"author_profile": "https://Stackoverflow.com/users/8842015",
"pm_score": 2,
"selected": false,
"text": "<script setup> \nconst route = useRoute();\nconsole.log(route.params.applicant_id)\nconsole.log(route.params.i... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17481713/"
] |
74,193,831 | <p>I have a vague memory of reading about a way to convert error numbers from a format like this <code>-1073740791</code> to something meaningful. I am pretty sure it involved converting from a signed Int to something else, and that there was a way to do it in Powershell. But I can't remember enough details to get any results from a search it seems.
Am I just missing some detail, or am I misremembering completely?</p>
| [
{
"answer_id": 74194853,
"author": "Theo",
"author_id": 9898643,
"author_profile": "https://Stackoverflow.com/users/9898643",
"pm_score": 3,
"selected": true,
"text": "'0x{0:X}' -f -2147219694"
},
{
"answer_id": 74199709,
"author": "mklement0",
"author_id": 45375,
"au... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4552490/"
] |
74,193,851 | <p>So I am trying to scrape job posts from Glassdoor using Requests, Beautiful Soup and Selenium. The entire code works except that, even after scraping data from 30 pages, most entries turn out to be duplicates (almost 80% of them!). Its not a headless scraper so I know it is going to each new page. What could be the reason for so many duplicate entries? Could it be some sort of anti-scraping tool being used by Glassdoor or is something off in my code?</p>
<p>The result turns out to be 870 entries of which a whopping 690 are duplicates!</p>
<p>My code:</p>
<pre class="lang-py prettyprint-override"><code>def glassdoor_scraper(url):
driver = webdriver.Chrome()
driver.get(url)
time.sleep(10)
# Getting to the page where we want to start scraping
jobs_search_title = driver.find_element(By.ID, 'KeywordSearch')
jobs_search_title.send_keys('Data Analyst')
jobs_search_location = driver.find_element(By.ID, 'LocationSearch')
time.sleep(1)
jobs_search_location.clear()
jobs_search_location.send_keys('United States')
click_search = driver.find_element(By.ID, 'HeroSearchButton')
click_search.click()
for page_num in range(1,10):
time.sleep(10)
res = requests.get(driver.current_url)
soup = BeautifulSoup(res.text,'html.parser')
time.sleep(2)
companies = soup.select('.css-l2wjgv.e1n63ojh0.jobLink')
for company in companies:
companies_list.append(company.text)
positions = soup.select('.jobLink.css-1rd3saf.eigr9kq2')
for position in positions:
positions_list.append(position.text)
locations = soup.select('.css-l2fjlt.pr-xxsm.css-iii9i8.e1rrn5ka0')
for location in locations:
locations_list.append(location.text)
job_post = soup.select('.eigr9kq3')
for job in job_post:
salary_info = job.select('.e1wijj242')
if len(salary_info) > 0:
for salary in salary_info:
salaries_list.append(salary.text)
else:
salaries_list.append('Salary Not Found')
ratings = soup.select('.e1rrn5ka3')
for index, rating in enumerate(ratings):
if len(rating.text) > 0:
ratings_list.append(rating.text)
else:
ratings_list.append('Rating Not Found')
next_page = driver.find_elements(By.CLASS_NAME, 'e13qs2073')[1]
next_page.click()
time.sleep(5)
try:
close_jobalert_popup = driver.find_element(By.CLASS_NAME, 'modal_closeIcon')
except:
pass
else:
time.sleep(1)
close_jobalert_popup.click()
continue
#driver.close()
print(f'{len(companies_list)} jobs found for you!')
global glassdoor_dataset
glassdoor_dataset = pd.DataFrame(
{'Company Name': companies_list,
'Company Rating': ratings_list,
'Position Title': positions_list,
'Location' : locations_list,
'Est. Salary' : salaries_list
})
glassdoor_dataset.to_csv(r'glassdoor_jobs_scraped.csv')
</code></pre>
| [
{
"answer_id": 74194853,
"author": "Theo",
"author_id": 9898643,
"author_profile": "https://Stackoverflow.com/users/9898643",
"pm_score": 3,
"selected": true,
"text": "'0x{0:X}' -f -2147219694"
},
{
"answer_id": 74199709,
"author": "mklement0",
"author_id": 45375,
"au... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15606732/"
] |
74,193,872 | <p>Let's say I have a function <code>Farm (animal1, animal2, ...)</code> that takes objects as parameters. These objects are either sheep or cows, which are made by one of two factory methods:</p>
<pre><code>function Sheep(id)
{
function noise() {console.log('baa');}
return {
my_id : id,
noise
}
}
function Cow(id)
{
function noise() {console.log('moo');}
function swish_tail () {}
return {
my_id : id,
noise,
swish_tail
}
}
</code></pre>
<p>Now, imagine <code>Farm</code> needs to do something different depending on the type of object of each animal (e.g. just list the numbers of each, or perhaps make all the sheep make a noise first then the cows). What is the best thing to do?</p>
<ul>
<li>Use prototypes for each animal, and check the prototype of each in Farm?</li>
<li>Work based on the knowledge that only a <code>Cow</code> has a <code>swish_tail ()</code> function as a member?</li>
<li>Have <code>Sheep</code> and <code>Cow</code> functionally inherit from an <code>Animal</code> factory method, and add something like a <code>type</code> member to <code>Animal</code>?</li>
</ul>
<p>Ideally, <code>Farm</code> should be ignorant of the implementation of each animal as far as possible,</p>
<p>Edit: I understand there are similarities with <a href="https://stackoverflow.com/questions/572897/how-does-javascript-prototype-work">this question</a> however this does not quite address the question of how to solve the specific problem.</p>
| [
{
"answer_id": 74202829,
"author": "cherryblossom",
"author_id": 8289918,
"author_profile": "https://Stackoverflow.com/users/8289918",
"pm_score": 2,
"selected": false,
"text": "type"
},
{
"answer_id": 74203673,
"author": "vsync",
"author_id": 104380,
"author_profile"... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1528634/"
] |
74,193,893 | <p>I have a data frame:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Dept_Name</th>
<th>Placed</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>1</td>
</tr>
<tr>
<td>B</td>
<td>0</td>
</tr>
<tr>
<td>C</td>
<td>1</td>
</tr>
</tbody>
</table>
</div>
<p>Where 'Placed' column has a boolean value
I want to print the count of rows that have the value '1' in placed grouped by the Dept_Name</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Dept_Name</th>
<th>Count(Placed == 1)</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>3</td>
</tr>
<tr>
<td>B</td>
<td>4</td>
</tr>
<tr>
<td>C</td>
<td>0</td>
</tr>
</tbody>
</table>
</div> | [
{
"answer_id": 74193909,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 2,
"selected": true,
"text": "0,1"
},
{
"answer_id": 74193921,
"author": "mozway",
"author_id": 16343464,
"author_profile": "ht... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9056381/"
] |
74,193,900 | <p>I developed an E-Mailing service and there is a form which must show all Emails related to a person in a grid.</p>
<p>I have the SQL query to display the result like this:</p>
<pre><code>SELECT
FOLDERNAME,
MAILFROM,
MAILTO,
LEFT(SUBJ, 200) + IIF(LEN(SUBJECT) > 200, '...', '')
AS 'Subject',
CAST(CNT AS VARCHAR(300)) + IIF(LEN(CNT) > 300, '...', '')
AS 'Content',
STUFF(STUFF(STUFF(STUFF(MAILTIMESTAMP, 5, 0, '-'), 8, 0, '-'), 11, 0, ' '), 14, 0, ':')
AS 'Date - Time',
(SELECT COUNT(*) FROM ATTACHMENTS WHERE MESSAGEID = MESSAGES.MESSAGEID)
AS Attachments
FROM
MESSAGES, FOLDERS
WHERE
FOLDERS.FOLDERID = MESSAGES.FOLDERID AND
MESSAGES.PKEY = '4070486';
</code></pre>
<p>PKEY is the Person Key and Attachments is the number of attachments exists in database as BLOB.</p>
<p>The problem is that I cannot combine IIF function and Count function in the inner Select statement to display the Attachments like this:</p>
<pre><code>SELECT IIF(COUNT(*) > 1, 'Yes', 'No')
FROM ATTACHMENTS WHERE MESSAGEID = MESSAGES.MESSAGEID
</code></pre>
<p>Note that every Email has one XML Attachment and if there are more than one attachment, it should write Yes otherwise No.</p>
<p>I have tried other things like WHERE EXISTS or IIF((SELECT...) > 1,...) and was not successful.</p>
<p>I think there should be a better solution for that.</p>
| [
{
"answer_id": 74194492,
"author": "Delta32000",
"author_id": 12939087,
"author_profile": "https://Stackoverflow.com/users/12939087",
"pm_score": 3,
"selected": true,
"text": "SELECT\n CASE\n WHEN COUNT(*) <= 1 THEN 'No'\n ELSE 'Yes'\n END AS HAVE_MULTIPLE_VALUES\nFRO... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20288923/"
] |
74,193,905 | <p>I have the following tables:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">Teammate ID</th>
<th style="text-align: center;">Teammate name</th>
<th style="text-align: right;">Team id</th>
<th style="text-align: right;">Teams</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">1</td>
<td style="text-align: center;">Amy</td>
<td style="text-align: right;">11</td>
<td style="text-align: right;">Sales</td>
</tr>
<tr>
<td style="text-align: left;">1</td>
<td style="text-align: center;">Amy</td>
<td style="text-align: right;">12</td>
<td style="text-align: right;">Support</td>
</tr>
<tr>
<td style="text-align: left;">1</td>
<td style="text-align: center;">Amy</td>
<td style="text-align: right;">13</td>
<td style="text-align: right;">Marketing</td>
</tr>
<tr>
<td style="text-align: left;">2</td>
<td style="text-align: center;">Peter</td>
<td style="text-align: right;">12</td>
<td style="text-align: right;">Support</td>
</tr>
<tr>
<td style="text-align: left;">2</td>
<td style="text-align: center;">Peter</td>
<td style="text-align: right;">13</td>
<td style="text-align: right;">Marketing</td>
</tr>
</tbody>
</table>
</div>
<p>And I want to group my results so the Teams column appears in one single row by Teammate Id or Teammate name as per below:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">Teammate ID</th>
<th style="text-align: center;">Teammate name</th>
<th style="text-align: right;">Team id</th>
<th style="text-align: right;">Teams</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">1</td>
<td style="text-align: center;">Amy</td>
<td style="text-align: right;">11, 12, 13</td>
<td style="text-align: right;">Sales, Support, Marketing</td>
</tr>
<tr>
<td style="text-align: left;">2</td>
<td style="text-align: center;">Peter</td>
<td style="text-align: right;">12, 13</td>
<td style="text-align: right;">Support, Marketing</td>
</tr>
</tbody>
</table>
</div>
<p>Which function would be best/cleanest to use for this purpose? I tried subqueries, coalescing, some weird XML path thing but as a new SQL user I can't wrap my head around figuring this one out</p>
<p>My original query which gave me the results is;</p>
<pre><code> SELECT
tm.teammate_id AS "Teammate ID",
tm.name AS "Teammate name",
itt.team_id AS "Team IDs",
it.team AS "Teams"
FROM
intercom_teammates AS tm
LEFT JOIN intercom_teammate_teams AS itt
ON tm.teammate_id = itt.teammate_id
LEFT JOIN intercom_teams AS it
ON tm.teammate_id = itt.teammate_id
</code></pre>
| [
{
"answer_id": 74194492,
"author": "Delta32000",
"author_id": 12939087,
"author_profile": "https://Stackoverflow.com/users/12939087",
"pm_score": 3,
"selected": true,
"text": "SELECT\n CASE\n WHEN COUNT(*) <= 1 THEN 'No'\n ELSE 'Yes'\n END AS HAVE_MULTIPLE_VALUES\nFRO... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17326000/"
] |
74,193,923 | <p>I am trying to create a function to use the variable name instead of values, but at the <code>princ</code> it is showing me only the name not the value.</p>
<pre class="lang-lisp prettyprint-override"><code>(defun c:loop3 ()
(setq xp 5)
(setq count 0)
(setq zp 200)
(setq yp 5)
(setq cenPT '(count xp yp zp))
(princ cenPT)
(princ)
)
</code></pre>
<p>I am expecting to print the value <code>5 0 200</code> but it prints the name of the variables.</p>
| [
{
"answer_id": 74253591,
"author": "Lee Mac",
"author_id": 7531598,
"author_profile": "https://Stackoverflow.com/users/7531598",
"pm_score": 2,
"selected": false,
"text": "'"
}
] | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2084408/"
] |
74,193,929 | <p>Under views.py</p>
<pre><code>def addcomments(request):
comment_text = request.POST.get('comment')
user_id = request.POST.get('user_id')
name = request.POST.get('name')
email = request.POST.get('email')
comment = Comment.objects.create(user_id=user_id, body=comment_text, name=name, email=email)
comment.save()
return HttpResponseRedirect(reverse('users:detail', args=(user_id, )))
</code></pre>
<p>this one, from detail.html</p>
<pre><code>{% extends 'base.html' %}
{% block title %}
{{ user.user_fname }} {{ user.user_lname }}
{% endblock %}
{% block content %}
{% if error_message %}
<p class="alert alert-danger">
<strong>{{error_message}}</strong>
</p>
{% endif %}
<div class="row">
<div class="col-lg-6">
<div class="mb-5">
<h1>{{ user.user_fname }} {{ user.user_lname }}</h1>
<p class="text-muted">{{ user.user_email }}</p>
<p>Position: {{ user.user_position }}</p>
</div>
<div class="img-responsive">
<img src="/users/media/{{user.user_image}}" alt="profile_user" class="img-rounded" width="300">
<!-- ito yung hinahanap ng search engine-->
</div>
<div class="btn-group mt-5">
<a href="{% url 'users:delete' user.id %}" class="btn btn-sm btn-danger">Delete</a>
<a href="{% url 'users:edit' user.id %}" class="btn btn-sm btn-info">Edit</a>
<a href="{% url 'users:index'%}" class="btn btn-sm btn-success">Back</a>
</div>
</div>
<div class="col-lg-6">
<h2>Comment</h2>
<p class="text-muted"> Number of comment : {{ comments_count }}</p>
{% if comments_count > 0 %}
{% for comment in comments %}
{% if comment.active %}
<p><strong>{{comment.name}}</strong> : {{comment.body}}</p>
{% endif %}
{% endfor %}
{% endif %}
<hr>
<br><br><br><br><br><br>
<form action="{%url 'users:addcomments'%}" method="post">
{% csrf_token %}
<div class="form-group">
<label>Comment</label>
<textarea name="comment" id="comment" cols="30" rows="5" class="form-control" required placeholder="Enter your comment here ..."></textarea>
</div>
<br>
<input type="text" name="name" id="name" value="{{ user.user_lname }}">
<input type="text" name="lname" id="lname" value="{{ user.user_fname }}">
<input type="text" name="email" id="email" value="{{ user.user_email }}">
<br><br><br><br>
<button type="submit" class="btn btn-sm btn-primary">Add Comment</button>
</form>
</div>
</div>
{% endblock %}
</code></pre>
<p>this one for url.py</p>
<pre><code>path('addcomments', views.addcomments, name='addcomments'),
</code></pre>
<p>I am having the error message,</p>
<p><strong>IntegrityError at /users/addcomments
(1048, "Column 'user_id' cannot be null")</strong></p>
<p><strong>During handling of the above exception ((1048, "Column 'user_id' cannot be null")), another exception occurred:</strong></p>
<p>from 404
users\views.py, line 146, in addcomments
comment = Comment.objects.create(user_id=users_id, body=comment_text, name=name, email=email) …
Local vars
Variable Value
comment_text<br />
'wwerwr'
email<br />
'HeavyRain@gmail.com'
name<br />
'Heavy'
request
<WSGIRequest: POST '/users/addcomments'>
user_id
None</p>
<p>the heavyrain details, ignore it, was trying stuffs</p>
<p><strong>this one for detail</strong> detail is working fine properly, detail is on left side of the page, while addcomments is on the right side of the same page</p>
<pre><code>@login_required(login_url='/users/login')
def detail(request, profile_id):
try:
user = User.objects.get(pk=profile_id)
comments = Comment.objects.filter(user_id=profile_id)
comments_count = Comment.objects.filter(user_id=profile_id).count()
except User.DoesNotExist:
raise Http404("Profile does not exist")
return render(request, 'UI/detail.html', {'user': user, 'comments': comments, 'comments_count': comments_count})
</code></pre>
| [
{
"answer_id": 74253591,
"author": "Lee Mac",
"author_id": 7531598,
"author_profile": "https://Stackoverflow.com/users/7531598",
"pm_score": 2,
"selected": false,
"text": "'"
}
] | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19255079/"
] |
74,193,940 | <p>Here is a naive implementation of a function which sets every value of a numpy array with index x,y,z to zero if any of x,y, or z is not a multiple of one_per_n:</p>
<pre><code>import numpy as np
X = np.random.rand(10,10,10)
one_per_n = 4
for x in range(X.shape[0]):
for y in range(X.shape[1]):
for z in range(X.shape[2]):
if x % one_per_n != 0 or y % one_per_n != 0 or z % one_per_n != 0:
X[x,y,z] = 0
</code></pre>
<p>I am looking for a more efficient method.</p>
| [
{
"answer_id": 74201273,
"author": "w-m",
"author_id": 463796,
"author_profile": "https://Stackoverflow.com/users/463796",
"pm_score": 3,
"selected": true,
"text": "one_per_n"
},
{
"answer_id": 74204186,
"author": "user7138814",
"author_id": 7138814,
"author_profile":... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10889650/"
] |
74,193,950 | <p>I have two arrays, <code>x</code> and <code>t</code> with <code>n</code> elements (<code>t</code>'s elements are in strict ascending order, so no dividing by 0) and a formula on which the creation of my new array, <code>v</code> is based:</p>
<pre><code>v[i] = (x[i+1] - x[i]) / (t[i+1] - t[i])
</code></pre>
<p>How can I write this in NumPy? I tried using <a href="https://numpy.org/doc/stable/reference/generated/numpy.fromfunction.html" rel="nofollow noreferrer"><code>numpy.fromfunction</code></a> but didn't manage to make it work.</p>
<p>I did manage to do it using a for loop - but I feel like there's a better way of doing this:</p>
<pre><code>n = 100000
x = np.random.rand(n)
t = np.random.randint(1, 10, n)
t = t.cumsum()
def gen_v(x, t):
v = np.zeros(n - 1)
for i in range(0, n - 1):
v[i] = (x[i+1] - x[i])/(t[i+1]-t[i])
return v
v = gen_v(x, t)
%timeit gen_v(x, t)
</code></pre>
<p>Outputs</p>
<pre><code>156 ms ± 15 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
</code></pre>
| [
{
"answer_id": 74194031,
"author": "obchardon",
"author_id": 4363864,
"author_profile": "https://Stackoverflow.com/users/4363864",
"pm_score": 3,
"selected": true,
"text": "np.diff()"
},
{
"answer_id": 74194082,
"author": "Invarianz",
"author_id": 5521725,
"author_pro... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12792893/"
] |
74,193,962 | <p>I am using flutter to process a link and download it to the device using dio package.</p>
<p>But the problem is dart is replacing all '&' with '\u0026' and making the link unusable. is there a way to avoid this problem? Thanks in advance.</p>
<p>Here's the code:</p>
<pre><code> const uuid = Uuid();
final Dio dio = Dio();
// * create random id for naming downloaded file
final String randid = uuid.v4();
// * create a local instance of state all media
List<MediaModel> allMedia = state.allMedia;
// * create an instance of IGDownloader utility class from ~/lib/utilities
final IGDownloader igd = IGDownloader();
// * make a download link from provided link from the GetNewMedia event
final link = await igd.getPost(event.link);
link.replaceAll('\u0026', '&');
print(await link);
</code></pre>
<p>Output:</p>
<pre><code>// expected : "http://www.example.com/example&examples/"
// result: "http://www.example.com/example\u0026example"
</code></pre>
| [
{
"answer_id": 74194031,
"author": "obchardon",
"author_id": 4363864,
"author_profile": "https://Stackoverflow.com/users/4363864",
"pm_score": 3,
"selected": true,
"text": "np.diff()"
},
{
"answer_id": 74194082,
"author": "Invarianz",
"author_id": 5521725,
"author_pro... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18310253/"
] |
74,194,017 | <p>I have the following dataset:</p>
<p><strong>Table1</strong>
<a href="https://i.stack.imgur.com/sUeAt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sUeAt.png" alt="enter image description here" /></a></p>
<p>2021 is my base year, and I want to know which of these products that started 2021 also occurred in 2022. So only if a product has a Contract_start in 2021, I want to pull this same product with contract_start in 2022 as well.</p>
<p>My output should therefore look like this
<a href="https://i.stack.imgur.com/cFDOQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cFDOQ.png" alt="enter image description here" /></a></p>
<p>I tried below query. This approach fails to include all four instances of product C, instead it only pulls one product C for 2021 and one for 2022. How to fix this query so that all products starting in 2021 are included in the right number of rows, without causing duplication for the 2022 products?</p>
<pre><code>with values_2021 as
( select distinct
CUSTOMER_NUMBER||PRODUCT as productcust
from table1
where substr(CONTRACT_START,1,4) = '2021'
)
SELECT distinct
CUSTOMER_NUMBER,
TOTAL_DOLLARS,
PRODUCT,
CONTRACT_START,
CONTRACT_END
FROM table1
join values_2021 on (table1.CUSTOMER_NUMBER||table1.PRODUCT) = values_2021.productcust
where CONTRACT_START >= ('20210101')
</code></pre>
| [
{
"answer_id": 74194031,
"author": "obchardon",
"author_id": 4363864,
"author_profile": "https://Stackoverflow.com/users/4363864",
"pm_score": 3,
"selected": true,
"text": "np.diff()"
},
{
"answer_id": 74194082,
"author": "Invarianz",
"author_id": 5521725,
"author_pro... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16767382/"
] |
74,194,033 | <p>How to query django-viewflow for all tasks assigned to user?</p>
<p>Probably <code>viewflow.managers.TaskQuerySet inbox()</code> is right place. But how to invoke it?</p>
<p>Alternatively how to query users task from <code>viewflow.models.Process</code> object?</p>
| [
{
"answer_id": 74234514,
"author": "surge_",
"author_id": 1640574,
"author_profile": "https://Stackoverflow.com/users/1640574",
"pm_score": 0,
"selected": false,
"text": "class CoopOnboardingProcess(Process):\n user = models.ForeignKey(CustomUser, on_delete=models.RESTRICT, blank=True... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1640574/"
] |
74,194,040 | <p>I try to load to the form the values of the object when I click the form opens i got an undefined data error.</p>
<p>I got to conclusion that my error is because I don't give the value right to the mat-select.</p>
<p>in the ngOnInit() of the diaog i call the api for the data i want to put in the mat-select.</p>
<p>this is the func:</p>
<pre><code>getAuthors() {
this._authorService.getAuthors().subscribe(result => {
this.authrosDb = result;
console.log(this.authrosDb.data);
});
</code></pre>
<p>}</p>
<p>when i do the console log i do get the values but the error saying that the data is undefined,so i got to the conclusion that this is might happening because the select loads before the data is passed.
when i open the add form i can add all and see the values in the select. <a href="https://i.stack.imgur.com/k5vbv.png" rel="nofollow noreferrer">This is the add form with the values</a></p>
<p>but when i want to update all the inputs beside the select
has the values of the row</p>
<p><a href="https://i.stack.imgur.com/Vsrdc.png" rel="nofollow noreferrer">this is the udate from all have values only the selct isnt</a></p>
<p>this is the select author section in my form:</p>
<pre><code><mat-form-field class="example-full-width" appearance="fill">
<mat-label>Author</mat-label>
<mat-select formControlName="authorId" placeholder="Author">
<mat-option *ngFor="let author of authrosDb.data" value={{author.authorId}}>
{{author.authorName}}</mat-option>
</mat-select>
</mat-form-field
</code></pre>
<p>and this is how I give the values to my inputs :</p>
<pre><code>ngOnInit(): void {
this.getAuthors();
this.getGenres();
if (this.data.id != '' && this.data.id != null) {
this._bookService.getBook(this.data.id).subscribe(response => {
this.editBook = response;
console.log(this.editBook);
this.bookForm.setValue({
bookId: this.editBook.data.bookId,
bookName: this.editBook.data.bookName,
authorId: this.editBook.data.authorId,
bookPublishedYear: this.editBook.data.bookPublishedYear,
genreId: this.editBook.data.genreId,
bookLanguage: this.editBook.data.bookLanguage,
bookNumOfPages: this.editBook.data.bookNumOfPages,
bookCopys: this.editBook.data.bookCopys
});
});
}
}
</code></pre>
<p>this is bookForm:</p>
<pre><code>bookForm = this.builder.group({
bookId: this.builder.control({ value: '', disabled: true }),
bookName: this.builder.control('', Validators.required),
authorId: this.builder.control('', Validators.required),
bookPublishedYear: this.builder.control('', Validators.required),
genreId: this.builder.control('', Validators.required),
bookLanguage: this.builder.control('', Validators.required),
bookNumOfPages: this.builder.control('', Validators.required),
bookCopys: this.builder.control('', Validators.required)
});
</code></pre>
<p><a href="https://i.stack.imgur.com/ecXW2.png" rel="nofollow noreferrer">Html</a></p>
<p>tho its adding and updating the right values.
I'm new to angular so it's be helpful if anyone could explain my mistake and show me how to fix it, thx in advance!.</p>
| [
{
"answer_id": 74196427,
"author": "Avraham Weinstein",
"author_id": 8938503,
"author_profile": "https://Stackoverflow.com/users/8938503",
"pm_score": 0,
"selected": false,
"text": "formGroup"
},
{
"answer_id": 74203693,
"author": "Eliseo",
"author_id": 8558186,
"auth... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17388454/"
] |
74,194,048 | <p>I'm interested in automating Outlook to check/read mails.
I'm using the package win32com with Python to control the app, but I can't find how to open an hyperlink which is in the mail body.</p>
<p>Is there an if or for statement that can open the hyperlink automatically?</p>
<p>Thank you in advance for your help!</p>
| [
{
"answer_id": 74194785,
"author": "Eugene Astafiev",
"author_id": 1603351,
"author_profile": "https://Stackoverflow.com/users/1603351",
"pm_score": 1,
"selected": false,
"text": "Find"
},
{
"answer_id": 74223196,
"author": "chronowix",
"author_id": 20091163,
"author_... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20330071/"
] |
74,194,052 | <p>I am using ggplot2 to produce plots. The plots have subgroups with different colours. For instance, within ggplot2 I have the following code and the output (hex colour codes) is below it:</p>
<pre><code>levels(df$colour)[1:3]
[1] "#000000" "#bababa" "#e31a1c"
</code></pre>
<p>However, I would like to choose levels 1 and 3 and exclude 2 so that the output is "#000000" "#e31a1c".</p>
<p>How do I do this? I tried the below but get TRUE and FALSE rather than the actual Hex codes.</p>
<pre><code>levels(df$colour) %in% c("#000000", "#e31a1c")
[1] TRUE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
FALSE FALSE FALSE FALSE FALSE FALSE
[21] FALSE FALSE
</code></pre>
| [
{
"answer_id": 74194785,
"author": "Eugene Astafiev",
"author_id": 1603351,
"author_profile": "https://Stackoverflow.com/users/1603351",
"pm_score": 1,
"selected": false,
"text": "Find"
},
{
"answer_id": 74223196,
"author": "chronowix",
"author_id": 20091163,
"author_... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16416945/"
] |
74,194,054 | <p>I want to find out the mean of each row for column "votes" but when I try to read that column in as a numeric value instead of a character it gives me an error. After that I dont know how to get r to understand what i want !</p>
<p><img src="https://i.stack.imgur.com/QYIYG.png" alt="data set" /></p>
| [
{
"answer_id": 74194136,
"author": "r2evans - GO NAVY BEAT ARMY",
"author_id": 3358272,
"author_profile": "https://Stackoverflow.com/users/3358272",
"pm_score": 2,
"selected": false,
"text": "dat <- data.frame(Votes = c(\"4,5,3,5,1,4,4,5,6\", \"4,4,3,5,4,3,5,4\", \"5,4,6,5,3,4,1,4,6\"))\... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20330230/"
] |
74,194,075 | <p>I'm a complete beginner, I have a website in which I want to click a button through python selenium, I've tried a lot of things, but I can't get it to work.</p>
<pre><code>import time
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
chromedriver_location = executable_path=r"C:\Users\HP\Desktop\chromedriver_win32\chromedriver.exe"
driver = webdriver.Chrome(chromedriver_location)
driver.get('https://maskun.org/donate/')
donate_button = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[contains(@class, 'give-btn advance-btn')] and text()='Donate Now']")))
donate_button.click()
</code></pre>
<p>Right now, I'm getting the error:</p>
<pre><code>Traceback (most recent call last):
File "d:\pythonprojects\maskun.py", line 13, in <module>
donate_button = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[contains(@class, 'give-btn advance-btn')] and text()='Donate Now']")))
File "C:\Python\Python310\lib\site-packages\selenium\webdriver\support\wait.py", line 81, in until
value = method(self._driver)
File "C:\Python\Python310\lib\site-packages\selenium\webdriver\support\expected_conditions.py", line 312, in _predicate
target = driver.find_element(*target) # grab element at locator
File "C:\Python\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 856, in find_element
return self.execute(Command.FIND_ELEMENT, {
File "C:\Python\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 429, in execute
self.error_handler.check_response(response)
File "C:\Python\Python310\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 243, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: Unable to locate an element with the xpath expression //button[contains(@class, 'give-btn advance-btn')] and text()='Donate Now'] because of the following error:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//button[contains(@class, 'give-btn advance-btn')] and text()='Donate Now']' is not a valid XPath expression.
(Session info: chrome=106.0.5249.119)
Stacktrace:
Backtrace:
Ordinal0 [0x00B51ED3+2236115]
Ordinal0 [0x00AE92F1+1807089]
Ordinal0 [0x009F66FD+812797]
Ordinal0 [0x009F92B4+823988]
Ordinal0 [0x009F9165+823653]
Ordinal0 [0x009F9400+824320]
Ordinal0 [0x00A25352+1004370]
Ordinal0 [0x00A257CB+1005515]
Ordinal0 [0x00A57632+1209906]
Ordinal0 [0x00A41AD4+1120980]
Ordinal0 [0x00A559E2+1202658]
Ordinal0 [0x00A418A6+1120422]
Ordinal0 [0x00A1A73D+960317]
Ordinal0 [0x00A1B71F+964383]
GetHandleVerifier [0x00DFE7E2+2743074]
GetHandleVerifier [0x00DF08D4+2685972]
GetHandleVerifier [0x00BE2BAA+532202]
GetHandleVerifier [0x00BE1990+527568]
Ordinal0 [0x00AF080C+1837068]
Ordinal0 [0x00AF4CD8+1854680]
Ordinal0 [0x00AF4DC5+1854917]
Ordinal0 [0x00AFED64+1895780]
BaseThreadInitThunk [0x76046739+25]
RtlGetFullPathName_UEx [0x77858FD2+1218]
RtlGetFullPathName_UEx [0x77858F9D+1165]
</code></pre>
<p>If I inspect the button on chrome I get:</p>
<pre><code><button class="give-btn advance-btn" tabindex="1">Donate Now<i class="fas fa-chevron-right"></i></button>
</code></pre>
<p>The XPath is:</p>
<pre><code>//*[@id="give-form-746-1"]/div[1]/button
</code></pre>
| [
{
"answer_id": 74194136,
"author": "r2evans - GO NAVY BEAT ARMY",
"author_id": 3358272,
"author_profile": "https://Stackoverflow.com/users/3358272",
"pm_score": 2,
"selected": false,
"text": "dat <- data.frame(Votes = c(\"4,5,3,5,1,4,4,5,6\", \"4,4,3,5,4,3,5,4\", \"5,4,6,5,3,4,1,4,6\"))\... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20330206/"
] |
74,194,091 | <p>i have this model:</p>
<pre><code>class Person:
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
sexe = models.TextChoices('M', 'F')
arrival_date = models.DateField(max_length=30)
reason = models.CharField(max_length=30)
</code></pre>
<p>It turns out that the same person can be registered several times (only the arrival date and the reason change).
I would like to make a query that lists distinctly persons. For example, if a person is registered many times, he will be selected only once.</p>
<p>How can i do it ? Thanks.</p>
| [
{
"answer_id": 74194305,
"author": "Hashem",
"author_id": 18806558,
"author_profile": "https://Stackoverflow.com/users/18806558",
"pm_score": 1,
"selected": false,
"text": "Person.objects.values_list('first_name', 'last_name', 'sexe').distinct()\n"
},
{
"answer_id": 74195930,
... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9187265/"
] |
74,194,094 | <p>I have this code to use saved API token and use it on other test, but it doesn't work (I get this error message : Reference Error : access_token is not defined: so I need to save my generated token and use it on all my API test</p>
<pre><code>const API_STAGING_URL = Cypress.env('API_STAGING_URL')
describe('Decathlon API tests', () => {
it('Get token',function(){
cy.request({
method:'POST',
url: 'https://test.com/as/token.oauth2?grant_type=client_credentials',
headers:{
authorization : 'Basic 1aFJueHkxddsvdvsdcd3cSA=='
}}).then((response)=>{
expect(response.status).to.eq(200)
const access_token = response.body.access_token
cy.log(access_token)
cy.log(this.access_token)
})
cy.log(this.access_token)
}),
it('Create Cart',function(){
cy.request({
method:'POST',
url: `${API_STAGING_URL}`+"/api/v1/cart",
headers:{
Authorization : 'Bearer ' + access_token,
"Content-Type": 'application/json',
"Cache-Control": 'no-cache',
"User-Agent": 'PostmanRuntime/7.29.2',
"Accept": '*/*',
"Accept-Encoding": 'gzip, deflate, br',
"Connection": 'keep-alive',
"Postman-Token": '<calculated when request is sent>'
},
}}).then((response)=>{
//Get statut 200
expect(response.status).to.eq(200)
//Get property headers
})})
})
</code></pre>
| [
{
"answer_id": 74194951,
"author": "agoff",
"author_id": 11625850,
"author_profile": "https://Stackoverflow.com/users/11625850",
"pm_score": 2,
"selected": true,
"text": "access_token"
},
{
"answer_id": 74196883,
"author": "jjhelguero",
"author_id": 17917809,
"author_... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194094",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12044397/"
] |
74,194,102 | <p>In a Spring Boot application written in Kotlin it is possible to use both the <a href="https://kotlinlang.org/docs/classes.html#constructors" rel="nofollow noreferrer">init block</a> or the <a href="https://docs.spring.io/spring-framework/docs/4.2.8.RELEASE/spring-framework-reference/htmlsingle/#beans-postconstruct-and-predestroy-annotations" rel="nofollow noreferrer"><code>@PostConstruct</code> JSR-250 lifecycle annotation</a> to do something right after instantiation. What are the consequences of using one vs the other in a <code>@Component</code> ? Can there be any behavioral difference?</p>
<p>Similar question <a href="https://stackoverflow.com/questions/8519187/spring-postconstruct-vs-init-method-attribute">here</a>.</p>
| [
{
"answer_id": 74194168,
"author": "Simon Martinelli",
"author_id": 1045142,
"author_profile": "https://Stackoverflow.com/users/1045142",
"pm_score": 0,
"selected": false,
"text": "@PostConstruct"
}
] | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2408863/"
] |
74,194,115 | <p>Something that should be very simple and yet I am not able to solve it.
The indexing does not appear correctly when a character duplicates:
For example:</p>
<pre class="lang-py prettyprint-override"><code>list=[]
stringg="BAtmAn"
for i in stringg:
if i.isupper():
list.append(stringg.index(i))
print(list)
</code></pre>
<p>And the output shows <code>[0,1,1]</code> instead of <code>[0,1,4]</code>.
When the stringg variable is changed to <code>"BAtmEn"</code> it appears the way I expect it to appear in the first example.</p>
| [
{
"answer_id": 74194183,
"author": "LinFelix",
"author_id": 6754986,
"author_profile": "https://Stackoverflow.com/users/6754986",
"pm_score": 1,
"selected": false,
"text": "stringg=\"BAtmAn\"\nprint([x for x in range(len(stringg)) if stringg[x].isupper()])\nprint([i for i, c in enumerate... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19971042/"
] |
74,194,132 | <p>I am creating Flutter paraphrasing app but my app size is too big, I don't know why?</p>
<p>App is used for paraphrasing, the text user can enter text, speak or extract text from file. We translate and paraphrase the text.
I created this for my software house but i don't know why app size is too big. I am not even using static assets still app size is <strong>158MB</strong></p>
<pre><code>name: paraphrase_and_translate
description: A new Flutter project.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
version: 1.0.0+1
environment:
sdk: ">=2.17.6 <3.0.0"
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
speech_to_text: ^5.5.0
google_ml_kit: ^0.11.0
camera: ^0.9.7+1
image_picker: ^0.8.5+3
translator: ^0.1.7
clipboard: ^0.1.2+8
pdf_text: ^0.5.0
file_picker: ^4.6.1
permission_handler: ^10.0.0
flex_color_scheme: ^5.1.0
font_awesome_flutter: ^10.1.0
dio: ^4.0.6
rounded_loading_button: ^2.0.8
language_picker: ^0.4.1
google_fonts: ^3.0.1
flutter_tts: ^3.5.0
simple_speed_dial: ^0.1.7
animated_splash_screen: ^1.3.0
flutter_launcher_icons: ^0.10.0
facebook_audience_network: ^1.0.1
google_mobile_ads: ^2.0.1
dev_dependencies:
flutter_test:
sdk: flutter
flutter_icons:
android: "launcher_icon"
ios: true
image_path: "assets/images/icon.png"
flutter_lints: ^2.0.0
flutter:
uses-material-design: true
assets:
- assets/images/new.png
- assets/images/parapharse.png
- assets/images/icon.png
</code></pre>
<p><strong>This is my pubspec.yaml file.
images are only 2 mbs only</strong></p>
<pre><code>Running "flutter pub get" in paraphrase_and_translate...
Launching lib\main.dart on Redmi Note 8 in release mode...
Running Gradle task 'assembleRelease'...
√ Built build\app\outputs\flutter-apk\app-release.apk (159.1MB).
Installing build\app\outputs\flutter-apk\app.apk...
</code></pre>
| [
{
"answer_id": 74194183,
"author": "LinFelix",
"author_id": 6754986,
"author_profile": "https://Stackoverflow.com/users/6754986",
"pm_score": 1,
"selected": false,
"text": "stringg=\"BAtmAn\"\nprint([x for x in range(len(stringg)) if stringg[x].isupper()])\nprint([i for i, c in enumerate... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16453584/"
] |
74,194,139 | <p>I am writing a code in which I calculate derivatives and integrals. For that I use <code>sympy</code> and <code>scipy.integrate</code>, respectively. But the use results in a strange erroneous, behaviour. Below is a minimal code that reproduces the behaviour:</p>
<pre><code>from scipy.integrate import quadrature
import sympy
import math
def func(z):
return math.e**(2*z**2)+3*z
z = symbols('z')
f = func(z)
dlogf_dz = sympy.Lambda(z, sympy.log(f).diff(z))
print(dlogf_dz)
print(dlogf_dz(10))
def integral(z):
# WHY DO I HAVE TO USE [0] BELOW ?!?!
d_ARF=dlogf_dz(z[0])
return d_ARF
result = quadrature(integral, 0, 3)
print(result)
>>> Lambda(z, (4.0*2.71828182845905**(2*z**2)*z + 3)/(2.71828182845905**(2*z**2) + 3*z))
>>> 40.0000000000000
>>> (8.97457203290041, 0.00103422711649337)
</code></pre>
<p>The first 2 print statements deliver mathematically correct results, but the integration outcome <code>result</code> is wrong - instead of ~8.975 it should be exactly 18. I know this, because I double-checked with WolframAlpha, since <code>dlogf_dz</code> is mathematically quite simple, you can check for yourself <a href="https://www.wolframalpha.com/input?i=integrate%20%284.0*2.71828182845905**%282*z**2%29*z%20%2B%203%29%2F%282.71828182845905**%282*z**2%29%20%2B%203*z%29%20from%200%20to%203" rel="nofollow noreferrer">here</a>.</p>
<p>Strangely enough, if I just hard-code the math-expression from my first print statement into <code>integral(z)</code>, I get the right answer:</p>
<pre><code>def integral(z):
d_ARF=(4.0*2.71828182845905**(2*z**2)*z + 3)/(2.71828182845905**(2*z**2) + 3*z)
return d_ARF
result = quadrature(integral, 0, 3)
print(result)
>>> (18.000000063540558, 1.9408245677254854e-07)
</code></pre>
<p>I think the problem is that I don't provide <code>dlogf_dz</code> to <code>integral(z)</code> in a correct way, I have to somehow else define <code>dlogf_dz</code> as a function. Note, that I defined <code>d_ARF=dlogf_dz(z[0])</code> in <code>integral(z)</code>, else the function was giving errors.</p>
<p><strong>What am I doing wrong? How can I fix the code, more precisely make <code>dlogf_dz</code> compatible with <code>sympy</code> integrations?</strong> Tnx</p>
| [
{
"answer_id": 74194183,
"author": "LinFelix",
"author_id": 6754986,
"author_profile": "https://Stackoverflow.com/users/6754986",
"pm_score": 1,
"selected": false,
"text": "stringg=\"BAtmAn\"\nprint([x for x in range(len(stringg)) if stringg[x].isupper()])\nprint([i for i, c in enumerate... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5838180/"
] |
74,194,144 | <p>In my case I want to retrieve a list with all groups where the total amount of uploads by their users exceeds or is equal to X value.</p>
<pre><code>A briefly example:
Group A, 5 Users, 3 Uploads
Group B, 2 Users, 10 Uploads
Group C, 6 Users, 5 Uploads
and I want all groups with more or equal than 6 Uploads
</code></pre>
<p>So in this case List<Groups> should only contain Group B.</p>
<p><strong>The models:</strong> (Note; in this case a user is only able to be in one group)</p>
<pre><code>public class Users
{
public int UserId { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public ......
.............
public int GroupId { get; set; }
[ForeignKey("GroupId")]
public virtual Groups Group { get; set; }
}
public class Groups
{
public int GroupId { get; set; }
public string GroupName { get; set; }
public int CategoryId { get; set; }
[ForeignKey("CategoryId")]
public virtual Categories Categories { get; set; }
}
public class Uploads
{
public int UploadId { get; set; }
public int UploadedByUserId { get; set; }
[ForeignKey("UploadedByUserId")]
public virtual Users User { get; set; }
public DateTime CreatedUTC { get; set; }
public string FilePath { get; set; }
}
</code></pre>
<p>I'm currently able to retrieve all groups without a single upload by saying:</p>
<pre><code>List<Groups> groups= await _db.Groups
.GroupJoin(_db.Uploads, g => g.GroupId, u => u.User.GroupId, (g, u) => new { g, u })
.SelectMany(x => x.u.DefaultIfEmpty(), (x, u) => new { x.g, u })
.Where(x => x.u == null)
.Select(x => x.g)
.ToListAsync();
</code></pre>
<p>but I'm currently struggeling saying something like:</p>
<pre><code>.where(u => u.Count() >= X-VALUE)
</code></pre>
<p>Thanks in advance for any suggestions!</p>
| [
{
"answer_id": 74194912,
"author": "Ronan Thibaudau",
"author_id": 1196886,
"author_profile": "https://Stackoverflow.com/users/1196886",
"pm_score": 3,
"selected": true,
"text": "List<Groups> groups= await _db.Groups\n .Where(g=>g.Users.SelectMany(user=>user.Uploads).Count() >6)\n"
... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10889461/"
] |
74,194,148 | <p>I have a list of Booking and this Booking has field OfficeType as enum as follow</p>
<pre><code>@Data
@Entity
@TypeDef(name = "json", typeClass = JsonStringType.class)
public class Booking {
@Id
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2")
@Column(name = "id", nullable = false, columnDefinition = "VARCHAR(36)")
private String id;
@Column(name = "office_type")
private OfficeType officeType;
</code></pre>
<p>I get the list of Booking from db, and I need to return to client that list and grouped by <em>Office type</em> and <em>count</em> as:</p>
<pre><code>List<Booking> bookingList = bookingRepository.findByStatus(Status.APPROVED);
Map<OfficeType, Integer> officeTypeMap = new HashMap<>();
</code></pre>
<p>How can I stream that list into that map grouping by OfficeType and counts ?</p>
| [
{
"answer_id": 74194312,
"author": "birca123",
"author_id": 10231374,
"author_profile": "https://Stackoverflow.com/users/10231374",
"pm_score": 1,
"selected": false,
"text": "bookingList.stream().collect(Collectors.groupingBy(Booking::getOfficeType, Collectors.counting()));\n"
},
{
... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1261764/"
] |
74,194,149 | <p>Basically I use SweetAlert2 to fire a toast whenever there is errors, single error or success messages.</p>
<p>It seems to work fine until I do a <code>Redirect::route('auth.index')->with([...])</code>, then the success or error/errors message won't fire at all.</p>
<p>I can open the VueDevTools and confirm that the error/success is visible though.
<a href="https://i.stack.imgur.com/tdu2i.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tdu2i.png" alt="enter image description here" /></a></p>
<p>Works fine if I do redirect back to the same page with the errors/success message <code>Redirect::back()->with([...])</code>.</p>
<p>Everything works until I want to go to another view with the flash message. What am I missing or doing wrong? I've been searching and going through the Inertia docs and vue docs but can't find anything related other than the data sharing, which I've already done.</p>
<p>Thanks in advance if anyone got the time to help.</p>
<p><strong>HandleInertiaRequests.php</strong></p>
<pre><code>/**
* Defines the props that are shared by default.
*
* @see https://inertiajs.com/shared-data
* @param \Illuminate\Http\Request $request
* @return array
*/
public function share(Request $request): array
{
return array_merge(parent::share($request), [
'flash' => [
'message' => fn () => $request->session()->get('message'),
'type' => fn () => $request->session()->get('type'),
'title' => fn () => $request->session()->get('title'),
],
]);
}
</code></pre>
<p><strong>PasswordController.php</strong></p>
<pre><code>/**
* Send a reset link to the given user.
*
* @param \App\Http\Requests\Password\EmailRequest $request
* @return \Illuminate\Http\RedirectResponse
*/
public function email(EmailRequest $request)
{
# Send reset link to user
$status = Password::sendResetLink(
$request->only('email')
);
# No leak if email exists or not.
if ($status === Password::RESET_LINK_SENT || $status === Password::INVALID_USER) {
return Redirect::route('auth.index')->with([
'message' => __($status),
'type' => 'success',
'title' => 'Success',
]);
}
# Error
return Redirect::back()->withErrors([__($status)]);
}
...
</code></pre>
<p><strong>Layout.vue</strong></p>
<pre><code><template>
<Swal :swalErrors="$page.props.errors" :swalFlash="$page.props.flash" />
</template>
<script>
import Swal from '../Component/Swal.vue';
</script>
</code></pre>
<p><strong>Swal.vue</strong></p>
<pre><code><template>
</template>
<script>
export default {
props: {
swalErrors: Object,
swalFlash: Object
},
watch: {
swalErrors: {
handler: function (errors) {
if (errors) {
this.toast(Object.values(errors).join(' '));
}
},
},
swalFlash: {
handler: function (flash) {
if (flash) {
this.toast(flash.message, flash.title, flash.type);
}
},
}
},
methods: {
toast: function (html, title, icon, timer) {
title = title || 'Error';
icon = icon || 'error';
timer = timer || 4000;
this.$swal.fire({
position: 'top-end',
toast: true,
icon: icon,
title: title,
html: html,
showClass: { popup: 'animate__animated animate__fadeInDown' },
hideClass: { popup: 'animate__animated animate__fadeOutUp' },
timer: timer,
timerProgressBar: true,
showConfirmButton: false,
});
}
}
}
</script>
</code></pre>
| [
{
"answer_id": 74194312,
"author": "birca123",
"author_id": 10231374,
"author_profile": "https://Stackoverflow.com/users/10231374",
"pm_score": 1,
"selected": false,
"text": "bookingList.stream().collect(Collectors.groupingBy(Booking::getOfficeType, Collectors.counting()));\n"
},
{
... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/918323/"
] |
74,194,174 | <p>I have a select with options that have values that are populated with jQuery based on data attributes from divs.<br/> When a user select an option, the div with the data attribute that matches the value of the option is displayed.<br/> Now I'm trying to create a deep linking option, so when I have a url like <a href="https://my-site.com/page/#option-2" rel="nofollow noreferrer">https://my-site.com/page/#option-2</a> the option-2 is preselected in the select and the div with data attribute option-2 is displayed.<br/> So far I have this javascript:</p>
<pre><code>$(window).on('load', function() {
let urlHash = window.location.hash.replace('#','');
console.log(urlHash);
if ( urlHash ) {
$('.dropdown').val(urlHash);
$('body').find('.location').removeClass('is-active');
$('body').find(`.location[data-location-hash=${urlHash}]`).addClass('is-active');
}
});
</code></pre>
<p>If I enter the url <a href="https://my-site.com/page/#option-2" rel="nofollow noreferrer">https://my-site.com/page/#option-2</a> the site goes in infinite loop and never loads without displaying any error in the console.. <br/>If I refresh the page while loading, the console.log is displayed with the correct string that I'm expecting, but the .location[data-location-hash=option-2] is not displayed and the option is not selected... <br/>I'm using the same code for the change function of the dropdown and is working, but it's not working in the load function.. Is there anything I'm missing?</p>
<p>JSFiddle, if it's of any help:
<a href="https://jsfiddle.net/tsvetkokrastev/b0epz1mL/4/" rel="nofollow noreferrer">https://jsfiddle.net/tsvetkokrastev/b0epz1mL/4/</a></p>
| [
{
"answer_id": 74194312,
"author": "birca123",
"author_id": 10231374,
"author_profile": "https://Stackoverflow.com/users/10231374",
"pm_score": 1,
"selected": false,
"text": "bookingList.stream().collect(Collectors.groupingBy(Booking::getOfficeType, Collectors.counting()));\n"
},
{
... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6324615/"
] |
74,194,178 | <p>How to use pipline for checkin devops data.
How to use pipline for checkin devops data
How to use pipline for checkin devops data</p>
| [
{
"answer_id": 74194312,
"author": "birca123",
"author_id": 10231374,
"author_profile": "https://Stackoverflow.com/users/10231374",
"pm_score": 1,
"selected": false,
"text": "bookingList.stream().collect(Collectors.groupingBy(Booking::getOfficeType, Collectors.counting()));\n"
},
{
... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20294615/"
] |
74,194,181 | <p>I have searched a lot on the forums for implementing TCP server using Python. All that I could find is a multi-threaded approach to TCP Server Implementation on a single port for interacting with clients.</p>
<p>I am looking for Server sample code for creating sockets using different ports.I have clients with distinct port numbers.For example, One socket binding IP and portNo-2000 and second one binding IP and another port No. 3000 and so on. Could anybody provide pointers?</p>
| [
{
"answer_id": 74194312,
"author": "birca123",
"author_id": 10231374,
"author_profile": "https://Stackoverflow.com/users/10231374",
"pm_score": 1,
"selected": false,
"text": "bookingList.stream().collect(Collectors.groupingBy(Booking::getOfficeType, Collectors.counting()));\n"
},
{
... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11759882/"
] |
74,194,188 | <ul>
<li>Trying to achieve input type password to accept only numeric value.</li>
<li>Also toggling of eye icon should be able toggle input type to
hidden password type or non-hidden number type.</li>
<li>As of now, when it is hidden, it changes to hidden text type, want to keep it numeric in hidden/password type</li>
</ul>
<pre><code>import React from 'react';
import { IconButton, InputAdornment, Input } from '@mui/material';
import Visibility from '@mui/icons-material/Visibility';
import VisibilityOff from '@mui/icons-material/VisibilityOff';
import { useDispatch, useSelector } from 'react-redux';
import { registerPin } from '../../../redux/passwordSlice';
const SSN = () => {
const dispatch = useDispatch();
const { pin } = useSelector((state) => state.inputValue);
const [values, setValues] = React.useState({ password: '****', showPassword: false });
const handleChange = (prop) => (event) => {
dispatch(registerPin(event.target.value));
setValues({ ...values, [prop]: event.target.value })
};
const handleClickShowPassword = () => setValues({ ...values, showPassword: !values.showPassword });
return (
<>
<Input
type={values.showPassword ? 'number' : 'password'}
value={pin}
onChange={handleChange('password')}
endAdornment={(
<InputAdornment position='end'>
<IconButton
onClick={handleClickShowPassword}
edge='end'
>
{!values.showPassword ? <VisibilityOff /> : <Visibility />}
</IconButton>
</InputAdornment>
)}
/>
</>
);
};
export default SSN;
</code></pre>
| [
{
"answer_id": 74194276,
"author": "Ted's Projects",
"author_id": 15828620,
"author_profile": "https://Stackoverflow.com/users/15828620",
"pm_score": 0,
"selected": false,
"text": "pattern=\"[0-9]\""
},
{
"answer_id": 74222476,
"author": "Hamed Siaban",
"author_id": 56130... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14870101/"
] |
74,194,213 | <p>I am trying to import "And" keyword from <code>@badeball/cypress-cucumber-preprocessor</code> so I can use it in Cypress/Cucumber, but I get this error</p>
<blockquote>
<p>Module "@badeball/cypress-cucumber-preprocessor" has no exported member 'And' - ts(2305)</p>
</blockquote>
<p>and I have no idea why.</p>
<p>Other keywords like "Given", "When" and "Then" are imported just fine.</p>
| [
{
"answer_id": 74218655,
"author": "Uzair Khan",
"author_id": 17601619,
"author_profile": "https://Stackoverflow.com/users/17601619",
"pm_score": 2,
"selected": false,
"text": "AND"
},
{
"answer_id": 74219066,
"author": "Nichola Walker",
"author_id": 19939224,
"author... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20330329/"
] |
74,194,282 | <p>I'm practicing with a simple roulette program. At this moment, I have a problem with balance input(), if I put it outside the function, the function betting() doesn't recognize it. But, if I put it inside, the function, the program asks me again to input the amount of money and it overwrites the amount of money after the bet.</p>
<p>How to avoid that, so the program asks me only once for input? This is my code:</p>
<pre><code>import random
def betting():
balance = float(input("How much money do you have? $"))
your_number = int(input("Choose the number between 0 and 36, including these: "))
if your_number < 0 or your_number > 36:
print("Wrong input, try again!")
betting()
else:
bet = float(input("Place your bet: "))
while balance > 0:
if bet > balance:
print("You don't have enough money! Place your bet again!")
betting()
else:
number = random.randint(0,36)
print(f"Your number is {your_number} and roulette's number is {number}.")
if number == your_number:
balance = balance + bet*37
print(f"You won! Now you have ${balance}!")
else:
balance = balance - bet
print(f"You lost! Now you have ${balance}!")
betting()
else:
print("You don't have more money! Goodbye!")
quit()
def choice():
choice = str(input("Y/N "))
if choice.lower() == "y":
betting()
elif choice.lower() == "n":
print("Goodbye!")
quit()
else:
print("Wrong input, try again!")
choice()
print("Welcome to the Grand Casino! Do you want to play roulette?")
choice()
</code></pre>
| [
{
"answer_id": 74194310,
"author": "Marcus",
"author_id": 16528000,
"author_profile": "https://Stackoverflow.com/users/16528000",
"pm_score": 1,
"selected": false,
"text": "inp = input(\"State how much money you have and a number between 0 and 36 inclusive, separated by space: \")\nbal, ... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20285937/"
] |
74,194,290 | <p>I'm working on a script, which builds an image, combines it with another image and saves it locally as an 8-bit BMP-file.
The image is then read by a ESP32 microcontroller, but the problem is that due to memorylimitations, the allowed file size is somewhat limited.</p>
<p>As a consequence, I made a BMP decoder for the ESP32, which supports RLE. In theory, the allowed number of bytes can still be exceeded, but only text and simple icons are to be read, so it will most likely never happen.</p>
<p>It uses Pillow for image processing, which now supports RLE-compression from version 9.1.0
<a href="https://github.com/python-pillow/Pillow/blob/main/docs/handbook/image-file-formats.rst" rel="nofollow noreferrer">https://github.com/python-pillow/Pillow/blob/main/docs/handbook/image-file-formats.rst</a></p>
<blockquote>
<p>Pillow reads and writes Windows and OS/2 BMP files containing 1, L, P,
or RGB data. 16-colour images are read as P images. Support for
reading 8-bit run-length encoding was added in Pillow 9.1.0. Support
for reading 4-bit run-length encoding was added in Pillow 9.3.0.</p>
</blockquote>
<p>Here's the part of the code, that combines two existing images into a new one and saves them:</p>
<pre><code>img_buf = io.BytesIO() # Start converting from Matplotlib to PIL
# Supported: eps, jpeg, jpg, pdf, pgf, png, ps, raw, rgba, svg, svgz, tif, tiff, webp
plt.savefig(img_buf, format='png', transparent=True)
graph = Image.open(img_buf)
# Create empty, 8-bit canvas
new_image = Image.new('P',(600,448), (255,255,255)) # P = 8-bit indexed
new_image.paste(img,(0,0)) # Insert image 1 into canvas
new_image.paste(graph,(0,200)) # Insert image 2 into canvas at y:200
new_image.save("../output/priceeast.bmp", compression=1) # According to the docs, 1 = RLE
</code></pre>
<p>It saves the image, alright, but not RLE-encoded and I can't work out, how to enable it... or is RLE only supported when reading BMP, not saving?</p>
<p>UPDATE:
I added this line below:</p>
<pre><code>subprocess.call('magick ../output/priceeast.png -type palette -compress RLE ../output/priceeast.bmp ', shell=True)
</code></pre>
| [
{
"answer_id": 74200883,
"author": "tari",
"author_id": 2658436,
"author_profile": "https://Stackoverflow.com/users/2658436",
"pm_score": 2,
"selected": false,
"text": "BmpImagePlugin._write"
},
{
"answer_id": 74205109,
"author": "Mark Setchell",
"author_id": 2836621,
... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/909452/"
] |
74,194,304 | <p>Im trying to create page for giving my to customers discounts on my products, but for a short period of time. I have created a field "start date" and "end date" of this promotion. Next thing i want to do, is to validate the input of the date.</p>
<p>By "Validate" i mean, that start date cannot be greater then end date. I decided to try preventing from writing into "end date" field unless there is a value in "Start date" field, but i ran into some syntax errors... Can you help me with that? Here is the logic i want to write for my page:</p>
<pre><code>field("Starting Date"; Rec."Starting Date")
{
ApplicationArea = All;
}
field("End Date"; Rec."End Date")
{
ApplicationArea = All;
if Rec."Starting Date" = '' then
Editable = false;
}
</code></pre>
<p>Here is the full page code i have so far for better understanding:</p>
<pre><code> page 95012 "ArKe Provision Subform"
{
Caption = 'ArKe Provision Subform';
PageType = ListPart;
ApplicationArea = All;
UsageCategory = Administration;
SourceTable = ArKeProvisionLine;
SourceTableView = sorting(Status, "Line No.") order(descending);
layout
{
area(Content)
{
repeater(ProvisionLineRepeater)
{
field(Status; Rec.Status)
{
ApplicationArea = All;
trigger OnValidate()
begin
CurrPage.Update();
end;
}
field("Customer Type"; Rec."Customer Type")
{
ApplicationArea = All;
}
field("Product Type"; Rec."Product Type")
{
ApplicationArea = All;
}
field("Starting Date"; Rec."Starting Date")
{
ApplicationArea = All;
}
field("End Date"; Rec."End Date")
{
ApplicationArea = All;
if Rec."Starting Date" = '' then begin
Editable = false;
end
}
field("Provision %"; Rec."Provision %")
{
ApplicationArea = All;
}
field("Line No."; Rec."Line No.")
{
ApplicationArea = All;
Editable = false;
}
}
}
}
}
</code></pre>
| [
{
"answer_id": 74200883,
"author": "tari",
"author_id": 2658436,
"author_profile": "https://Stackoverflow.com/users/2658436",
"pm_score": 2,
"selected": false,
"text": "BmpImagePlugin._write"
},
{
"answer_id": 74205109,
"author": "Mark Setchell",
"author_id": 2836621,
... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20158030/"
] |
74,194,337 | <p>I am using a data scraper and I know just enough code to not know what I'm doing. The scraper is free and has a crawl limit. There is no option to resume the crawl from end point. I need to scrape all li's on the page. The program will only let me select 1 or all li's. I am trying to come up with a manual selector or xpath that would allow me to select from nth-child(200)on. Any help or suggestions?</p>
| [
{
"answer_id": 74194546,
"author": "ChenBr",
"author_id": 17718587,
"author_profile": "https://Stackoverflow.com/users/17718587",
"pm_score": 1,
"selected": false,
"text": ":nth-child()"
},
{
"answer_id": 74194729,
"author": "fitzgeraldda",
"author_id": 20330369,
"aut... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20330369/"
] |
74,194,362 | <p>I have a spring-boot Webflux application and I am writing some tests using Spock and Groovy.</p>
<p>My Controllers are secured with OAuth opaque token which I need to mock a response from introspection.
My test properties are:</p>
<pre><code>spring.security.oauth2.resourceserver.opaquetoken.client-id=fake_client
spring.security.oauth2.resourceserver.opaquetoken.client-secret=fake_secret
spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=http://localhost:8089/api/v1/oauth/token/introspect
</code></pre>
<p>My test uses <code>WebClient</code> as below:</p>
<pre class="lang-java prettyprint-override"><code>webClient.post()
.uri(URL.toString()))
.accept(MediaType.APPLICATION_JSON)
.headers(http -> http.setBearerAuth("bearer_token"))
.exchange()
.expectStatus()
.is2xxSuccessful()
</code></pre>
| [
{
"answer_id": 74194546,
"author": "ChenBr",
"author_id": 17718587,
"author_profile": "https://Stackoverflow.com/users/17718587",
"pm_score": 1,
"selected": false,
"text": ":nth-child()"
},
{
"answer_id": 74194729,
"author": "fitzgeraldda",
"author_id": 20330369,
"aut... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9467865/"
] |
74,194,366 | <p>Recently, Neo4j presented 5.0.1 version. Is there a corresponding APOC library available for such release?</p>
<p>Right now I'm unable to start Neo4j 5.0.1 with apoc-4.4.0.9-all.jar</p>
| [
{
"answer_id": 74194546,
"author": "ChenBr",
"author_id": 17718587,
"author_profile": "https://Stackoverflow.com/users/17718587",
"pm_score": 1,
"selected": false,
"text": ":nth-child()"
},
{
"answer_id": 74194729,
"author": "fitzgeraldda",
"author_id": 20330369,
"aut... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1219755/"
] |
74,194,389 | <p>currently i am working on my HomeLab infrastructure. Unfortunately, I ran into a problem that I can't solve.</p>
<p>The following components are affected</p>
<ul>
<li>Nginx Proxy Manager</li>
<li>Authentik</li>
<li>Dashy</li>
</ul>
<p>My goal is to have all my services in one UI with a single authentication-flow. Dashy has the ability to show different services inside the dashboard ui. That works fine as long as I set the X-Frame-Options "ALLOW-FROM URL" and Content-Security-Policy "frame-ancestors URL" in Nginx Proxy Manager.</p>
<p>Unfortunately, however, Authentik now seems to override the X-Frame options and ignore changes in the proxy manager. And because Authentik is always addressed via a redirect before the first call of a service, I can't load an application within an IFrame.</p>
<p>Now to my question:</p>
<ul>
<li>How do I give Authentik to understand that it should allow SAMEORIGIN or ALLOW FROM if it ignores the nginx configuration. Is there an Option that let me set headers for Authentik?</li>
</ul>
<p><a href="https://i.stack.imgur.com/R0YsR.png" rel="nofollow noreferrer">X-Frame Options after edit the nginx proxymanager conf.</a></p>
| [
{
"answer_id": 74194546,
"author": "ChenBr",
"author_id": 17718587,
"author_profile": "https://Stackoverflow.com/users/17718587",
"pm_score": 1,
"selected": false,
"text": ":nth-child()"
},
{
"answer_id": 74194729,
"author": "fitzgeraldda",
"author_id": 20330369,
"aut... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10288831/"
] |
74,194,423 | <p>I have the following code (works fine). I would like to set different background, font level, outline for open and closed elements.</p>
<pre><code>a.innerHTML = "We are Open now now.";
a.innerHTML = "We are Closed, arm.";
</code></pre>
<p>I would also like to have it, not here, but in this code you can display the text differently:
I could format it in css, but I can't do it with javascript. Could you help me with an example or two?</p>
<pre><code>var a = document.getElementById("hoursofoperation"); var d = new Date(); var n = d.getDay(); var now = d.getHours() + "." + d.getMinutes(); var weekdays = {
0: null,//Sunday
1: [8.30, 21.30],
2: [6.00, 11.30],
3: [8.30, 12.00],
4: [8.30, 12.00],
5: [8.30, 12.30],
6: null //Saturday
};
var dayWorkingHours = weekdays[n];//Today working hours. if null we are close
if (dayWorkingHours && (now > dayWorkingHours[0] && now < dayWorkingHours[1])) {
a.innerHTML = "We are Open now now.";
} else {
a.innerHTML = "We are Closed, kar.";
}
</code></pre>
| [
{
"answer_id": 74194481,
"author": "niorad",
"author_id": 5774727,
"author_profile": "https://Stackoverflow.com/users/5774727",
"pm_score": 0,
"selected": false,
"text": "a.style.color = \"blue\""
},
{
"answer_id": 74194694,
"author": "luckyape",
"author_id": 714768,
... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20319752/"
] |
74,194,428 | <p>I have a nested function that should be able to handle chained function calls, but the number of calls is unknown. The function has to add up numbers until we call it without parameters, in which case it should return the result of all the numbers that were passed as arguments in the chain call.</p>
<p>Description:</p>
<p>Write the <code>makeAdder</code> function, which will return the<code> adder</code> function.
The <code>adder</code> function should work on the following pattern: <code>adder(2)(3)(4)(1)(2)(3)(4)() === 19</code>. It will sum all the numbers passed in the parameters until it encounters a call without parameters. When calling without parameters, it will return the result and clear the amount.</p>
<p>Example:</p>
<pre><code>const adder = makeAdder();
adder() === 0
adder(4)(5)() === 9
adder() === 0
adder(5)(5)(5)
adder(4)
adder() === 19
adder() === 0
</code></pre>
<p>How can I write this function without knowing how many nested functions I am going to need beforehand?</p>
<pre><code>function makeInfinityAdder() {
return function adder(a = 0) {
return (b) => {
if (b) {
adder(a + b)
} else {
return a + b;
}
};
}
}
</code></pre>
<p>I tried this but I get 'adder(...)(...) is not a function'.</p>
| [
{
"answer_id": 74194641,
"author": "KooiInc",
"author_id": 58186,
"author_profile": "https://Stackoverflow.com/users/58186",
"pm_score": 2,
"selected": true,
"text": "const addAll = (a = 0) => b => +b >= 0 ? addAll(a + b) : a;\n\nlet add = addAll();\nconsole.log(`add(8)(9)(10)(15)() => $... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18126421/"
] |
74,194,441 | <p>For a sentence</p>
<ul>
<li><code>'Foo bar was open on 12.03.2022 and closed on 3.05.22.'</code>
with respective</li>
<li><code>list = [12.03.2022, 4.04.2022, 3.05.22]</code></li>
</ul>
<p>I want to get the start and end indices in the sentence as a tuple if a date in the list can be found in the sentence.</p>
<p>In this case: <code>[(20,29), (45, 51)]</code></p>
<p>I have found the dates through regex but I cannot get the indices.</p>
<pre><code>DAY = r'(?:(?:0)[1-9]|[12]\d|3[01])' # day can be from 1 to 31 with a leading zero
MONTH = r'(?:(?:0)[1-9]|1[0-2])' # month can be 1 to 12 with a leading zero
YEAR1 = r'(?:(?:20|)\d{2}|(?:19|){9}[0-9])' # Restricted the year to begin in 20th or 21st century
# Also the first two digits may be skipped if data is represented as dd.mm.yy
YEAR2 = r'(?:20\d{2}|199[0-9])'
BEGIN_LINE1 = r'(?<!\w)'
DELIM1 = r'(?:[\,\/\-\._])'
DELIM2 = r'(?:[\,\/\-\._])?'
# combined, several options
NUM_DATE = f"""(?P<date>
(?:
# DAY MONTH YEAR
(?:{BEGIN_LINE1}{DAY}{DELIM1}{MONTH}{DELIM1}{YEAR1})
|
(?:{BEGIN_LINE1}{DAY}{DELIM1}{MONTH})
|
(?:{BEGIN_LINE1}{MONTH}{DELIM1}{YEAR1})
|
(?:{BEGIN_LINE1}{DAY}{DELIM2}{MONTH}{DELIM2}{YEAR2})
|
(?:{BEGIN_LINE1}{MONTH}{DELIM2}{YEAR2})
)
)"""
myDate = re.compile(f'{NUM_DATE}', re.IGNORECASE | re.VERBOSE | re.UNICODE)
def find_date(subject):
"""_summary_
Args:
subject (_type_): _description_
Returns:
_type_: _description_
"""
if subject is None:
return subject
dates = list(set(myDate.findall(subject)))
return dates
</code></pre>
| [
{
"answer_id": 74194496,
"author": "Tim J",
"author_id": 7052830,
"author_profile": "https://Stackoverflow.com/users/7052830",
"pm_score": 2,
"selected": false,
"text": "re.search"
},
{
"answer_id": 74194734,
"author": "Ramesh",
"author_id": 18014805,
"author_profile"... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11479825/"
] |
74,194,443 | <p>I would like to group rows in a pandas dataframe based on the difference between rows. Given the following dataframe</p>
<pre><code>zz = pd.DataFrame([[1,0], [1.1, 2], [2,3], [2.19,4], [5,7], [6,0], [7,2], [8,3], [8.05, 0], [8.12,4]], columns = ['a', 'b'])
</code></pre>
<p>I would like to form groups when the difference between values in column 'a' is less than 0.2. So, the following groups (as a dataframegroup object) would emerge (indices of the rows in brackets) for this dataframe:</p>
<ul>
<li>group1: [0, 1]</li>
<li>group2: [2,3]</li>
<li>group3: [4]</li>
<li>group5: [5]</li>
<li>group6: [6]</li>
<li>group7: [7, 8, 9]</li>
</ul>
<p>I looked around but I could find an easy solution.</p>
| [
{
"answer_id": 74194479,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 0,
"selected": false,
"text": "1"
},
{
"answer_id": 74194489,
"author": "mozway",
"author_id": 16343464,
"author_profile": "htt... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11864134/"
] |
74,194,505 | <p><a href="https://i.stack.imgur.com/iWp0y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iWp0y.png" alt="code output" /></a></p>
<p>Whenever I try fetching data from a REST API, I keep getting an error <strong>"Expected a value of type 'Widget?', but got one of type 'String'".</strong> There is nothing wrong with my code yet I keep getting the error.</p>
<p><strong>This is the function for fetching items from the database.</strong></p>
<pre><code>Future<List<Map>> fetchItems() async {
List<Map> items = [];
//get data from API and assign to variable
http.Response response =
await http.get(Uri.parse("https://jsonplaceholder.typicode.com/posts"));
if (response.statusCode == 200) {
//get data from the response
String jsonString = response.body;
items = jsonDecode(jsonString).cast<Map>();
}
return items;
}
</code></pre>
<p><strong>This is my main.dart file</strong></p>
<pre><code>void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: PostList(),
);
}
}
</code></pre>
<pre><code>class PostList extends StatelessWidget {
PostList({super.key});
final Future<List<Map>> _futurePosts = HTTPHelper().fetchItems();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Posts"),
),
body: FutureBuilder(
future: _futurePosts,
builder: ((context, snapshot) {
//check for error
if (snapshot.hasError) {
return Center(
child: Text("Some error has occured ${snapshot.error}"));
}
//has data
if (snapshot.hasData) {
List<Map> _posts = snapshot.data!;
return ListView.builder(
itemCount: _posts.length,
itemBuilder: ((context, index) {
Map _thisItem = _posts[index];
return ListTile(
title: _thisItem["title"],
subtitle: _thisItem["body"],
);
}));
}
//display a loader
return Center(child: CircularProgressIndicator());
}),
),
);
}
}
</code></pre>
<p>Any solution to this error?</p>
| [
{
"answer_id": 74194631,
"author": "Rohan Jariwala",
"author_id": 13954519,
"author_profile": "https://Stackoverflow.com/users/13954519",
"pm_score": 2,
"selected": true,
"text": "ListView.builder(\n itemCount: _posts.length,\n itemBuilder: ((context, index)... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20330417/"
] |
74,194,522 | <p>I have a list of numbers ['2054', '3271', '8671', '273'] and would like to find all files in a directory that include any one of those values in the pathname in a set pattern. I am using the glob module to find all the pathnames but I have not found a good way of including the numbers from my list. This is what I have so far:</p>
<pre><code>pathPac = '/Users/noah/Data/Docs'
pathlist = Path(pathPac).glob('**/doc*.xml')
</code></pre>
<p>But instead of doc*.xml I want to find a way of looking for doc2054.xml, doc3271.xml and so on. I have looked around in the glob documentation, but have not found anything to do this.</p>
| [
{
"answer_id": 74194631,
"author": "Rohan Jariwala",
"author_id": 13954519,
"author_profile": "https://Stackoverflow.com/users/13954519",
"pm_score": 2,
"selected": true,
"text": "ListView.builder(\n itemCount: _posts.length,\n itemBuilder: ((context, index)... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17280156/"
] |
74,194,549 | <p>I have a string generated with this format :</p>
<pre><code>'fdffddf<div><br> <div><img style="max-width: 7rem;" src="folder/myimg.jpg"><div> <br></div></div><div><div> <br></div></div></div>'.
</code></pre>
<p>I want to create a regular expression .
I want a regular expression that just fetches me the content without the div tag and the source of the image in an array.</p>
<p>Example in my case:
<code>[ 'fdffddf', 'folder/myimg.jpg' ]</code></p>
<p>I tried this method :</p>
<pre><code>let str = 'fdffddf<div><br> <div><img style="max-width: 7rem;" src="folder/myimg.jpg"><div> <br></div></div><div><div> <br></div></div></div>'
console.log('only content without div tag and src image only without img tag : ',str.match(/<img [^>]*src="[^"]*"[^>]*>/gm)[0])
</code></pre>
<p>It doesn't work. I get only the img tag.</p>
<p>How can I do it please ?</p>
| [
{
"answer_id": 74196191,
"author": "Cristiano Schiaffella",
"author_id": 9395753,
"author_profile": "https://Stackoverflow.com/users/9395753",
"pm_score": -1,
"selected": false,
"text": "/^(?<!<)(\\b[^<>]+\\b)(?!>).*(?<=\")(\\b.+\\b)(?=\")/\n"
},
{
"answer_id": 74204933,
"aut... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16086275/"
] |
74,194,573 | <p>I am having difficulty testing my redux application. I am not sure if there is some kind of asynch issue, or there is something I dont quite understand about React Testing Library. Needless to say I am pretty lost with RTL. With Enzyme I had no problems with this kind of stuff.</p>
<p>I want to test a component which is basically a 'product' which has some text with a combo box for 'quantity'.</p>
<p>The component is pretty straightforward and looks like this :</p>
<pre><code>function ItemBox(props: Props) {
const dispatch = useDispatch();
let selected = ""
if (props.product.amount && props.product.amount > 0) {
selected = "selected"
}
function handleChangeQuantity(e: any) {
dispatch(createUpdateProductSelection({value: e.currentTarget.value, productid: props.product.id}));
}
return(
<div className={"item-box " + selected}>
<div className={"item-box-desc " + selected} title={props.product.name} >
{props.product.name}
</div>
<div className={"item-box-bottom"} >
<select className={"item-box-options"} id="qty" onChange={handleChangeQuantity} value={props.product.amount}>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
</div>
)
}
</code></pre>
<p>In my reducer I catch the action and update the product.</p>
<pre><code>export function productsReducer(state: ProductsState, action: AnyAction): ProductsState {
if (createUpdateProductSelection.match(action)) {
let allProducts = state.allProducts.map((item): Product => {
if (item.id === action.payload.productid) {
return {
...item,
amount: action.payload.value
}
}
return item;
})
return {
...state,
allProducts: allProducts,
};
}
return state;
}
</code></pre>
<p>In the actual application this all works fine.</p>
<p>When I get to writing the test things get weird. My test looks like this :</p>
<pre><code>let comboboxes: HTMLInputElement[] = await screen.findAllByRole("combobox");
fireEvent.change(comboboxes[0], {target: {value: "3"}})
comboboxes = await screen.findAllByRole("combobox");
expect(comboboxes[0].value).toEqual("3")
console.info("" + screen.debug(comboboxes[0]))
</code></pre>
<p>The test passes because it finds that the combobox has been set to '3'. However when I look at the HTML in the console.info I see a "select" but there is no option that is set to selected (ie. <code><option value="3" selected></code> ).</p>
<p>It looks like this :</p>
<pre><code><select class="item-box-options" id="qty">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</code></pre>
<p>Maybe this is an issue with this component being a controlled component?</p>
<p>In any case debugging through the test shows me that it is breaking correctly at the callback <strong>handleChangeQuantity</strong> . But it is NOT breaking at the reducer level.</p>
<p>Before it gets to the reducer level it breaks at this line in my test :</p>
<pre><code>comboboxes = await screen.findAllByRole("combobox");
</code></pre>
<p>Which basically means the react behaviour has not completed before it has gotten to this test line.</p>
<p>Am I 'waiting' correctly?</p>
<p>Is something async happening in the background that I am not aware of? This should all be 'sync' because it is a trivial redux scenario as far as I am concerned.</p>
| [
{
"answer_id": 74194904,
"author": "Oliver Watkins",
"author_id": 1022330,
"author_profile": "https://Stackoverflow.com/users/1022330",
"pm_score": 1,
"selected": true,
"text": "const mockStore = configureStore();\n\nlet store = mockStore(getData());\n"
},
{
"answer_id": 74202165... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1022330/"
] |
74,194,596 | <p>I've been messing around with a wp plugin that is missing some classes and stuff, and I figured I could add them myself through a custom script.
As you can see from the code I just selected a bunch of elements and I gave each one a unique classname that will later be used to add some css pseudo elements, but the best thing I could come up with is this long a55 statement lol
If some of you know a better way, your help will be greatly appreciated!</p>
<p>This is an html snippet of my area of interest:</p>
<pre><code><div class="side_by_side">
<label for="fieldname6_1_rb7">
<input
aria-label="Van"
name="fieldname6_1"
id="fieldname6_1_rb7"
class="field group required"
value="489"
vt="Van"
type="radio"
/>
<span>Van</span></label>
</div>
</code></pre>
<p>This is what my js looks like, which works as it is, but I'd like to know if there's a better way to write something like this..</p>
<pre><code>const modelInputLabel = document.querySelectorAll(".side_by_side span");
for (let i = 0; i < modelInputLabel.length; i++) {
if (i === 0) {
modelInputLabel[i].setAttribute("class", "test modelFirst");
} else if (i === 1) {
modelInputLabel[i].setAttribute("class", "test modelSecond");
} else if (i === 2) {
modelInputLabel[i].setAttribute("class", "test modelThird");
} else if (i === 3) {
modelInputLabel[i].setAttribute("class", "test modelFourth");
} else if (i === 4) {
modelInputLabel[i].setAttribute("class", "test modelFifth");
} else if (i === 5) {
modelInputLabel[i].setAttribute("class", "test modelSixth");
} else if (i === 6) {
modelInputLabel[i].setAttribute("class", "test modelSeventh");
} else if (i === 7) {
modelInputLabel[i].setAttribute("class", "test modelEight");
}
}
</code></pre>
| [
{
"answer_id": 74194699,
"author": "Ivan124",
"author_id": 20246826,
"author_profile": "https://Stackoverflow.com/users/20246826",
"pm_score": 3,
"selected": true,
"text": "forEach"
},
{
"answer_id": 74194757,
"author": "Harrison",
"author_id": 15291770,
"author_profi... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18036831/"
] |
74,194,600 | <p>So, I am building an ecommerce app in sveltekit and wanted to implement cart as a global store, so components can query that store for cart status. I pretty much know how to implement it in a single page application, but can't get my head around how to do it with SvelteKit. What will be the best approach to make a reactive cart for such application? Should I store cart at server only and reload cart on each change? or is there a way to implement a global store that works between pages?</p>
| [
{
"answer_id": 74196763,
"author": "Scott Vickrey",
"author_id": 17827032,
"author_profile": "https://Stackoverflow.com/users/17827032",
"pm_score": 0,
"selected": false,
"text": "import { motor } from '../stores.ts';\n\nconsole.log($motor.horsePower);\n"
},
{
"answer_id": 741972... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7034560/"
] |
74,194,611 | <p>I did some workarounds but none of them worked so here I am with a question on how can we split a value from a list based on a keyword and update in the same list</p>
<pre><code> here is my code,
result_list = ['48608541\ncsm_radar_main_dev-7319-userdevsigned\nLogd\nG2A0P3027145002X\nRadar\ncompleted 2022-10-25T10:43:01\nPASS: 12FAIL: 1SKIP: 1\n2:25:36']
</code></pre>
<p>what I want to remove '\n' and write something like this,</p>
<pre><code>result_list = ['48608541', 'csm_radar_main_dev-7319-userdevsigned', 'Logd', 'G2A0P3027145002X', .....]
</code></pre>
| [
{
"answer_id": 74194654,
"author": "ThePyGuy",
"author_id": 9136348,
"author_profile": "https://Stackoverflow.com/users/9136348",
"pm_score": 1,
"selected": false,
"text": "split"
},
{
"answer_id": 74194722,
"author": "Nikhil Belure",
"author_id": 14086220,
"author_pr... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8484230/"
] |
74,194,628 | <pre><code>print("this is your "+t+" warning")
</code></pre>
<p>t is supposed to be an integer.</p>
<p>this is probably a silly and stupid question but is it possible to print a variable(in the case t with an int value) and a string("this is your" & "warning") together in one print statement[print()].</p>
<p>If I remember it correctly it's possible in java, not sure though.</p>
| [
{
"answer_id": 74194644,
"author": "Omer Dagry",
"author_id": 15010874,
"author_profile": "https://Stackoverflow.com/users/15010874",
"pm_score": 1,
"selected": false,
"text": "t = 0\nprint(\"this is your\", t, \"warning\")\nprint(f\"this is your {t} warning\")\nprint(\"this is your \" +... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20015903/"
] |
74,194,630 | <p>I am very new to R. Working mostly with Seurat package to evaluate my single-cell RNAseq data.
Today I wanted to update the R version and RStudio. After that I had problems using installed packages. This is my problem:</p>
<pre><code>> install.packages("Seurat", dependencies = TRUE)
Installing package into ‘C:/Users/benne/AppData/Local/R/win-library/4.2’
(as ‘lib’ is unspecified)
Warning in install.packages :
dependencies ‘S4Vectors’, ‘SummarizedExperiment’, ‘SingleCellExperiment’, ‘MAST’, ‘DESeq2’, ‘BiocGenerics’, ‘GenomicRanges’, ‘GenomeInfoDb’, ‘IRanges’, ‘rtracklayer’, ‘monocle’, ‘Biobase’, ‘limma’ are not available
trying URL 'https://cran.rstudio.com/bin/windows/contrib/4.2/Seurat_4.2.0.zip'
Content type 'application/zip' length 2376157 bytes (2.3 MB)
downloaded 2.3 MB
package ‘Seurat’ successfully unpacked and MD5 sums checked
The downloaded binary packages are in
C:\Users\benne\AppData\Local\Temp\RtmpIlveV0\downloaded_packages
> library(Seurat)
Error: package or namespace load failed for ‘Seurat’ in loadNamespace(i, c(lib.loc, .libPaths()), versionCheck = vI[[i]]):
there is no package called ‘spatstat.data’
</code></pre>
<p>I think, there is no problem with the installation of Seurat-package but I cannot make the library-function work. I found other topics that tried to solve that problem but they did not help me.</p>
<p>What could be the problem? With the old R/RStudio version everything worked well. After the update I had to install the RTools42 because it said I have to do that. I have never done that before, why today??</p>
<p>I really hope, you guys may help me. I am totally lost!!</p>
<p>Attached my sessionInfo():</p>
<pre><code>> sessionInfo()
R version 4.2.1 (2022-06-23 ucrt)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 22000)
Matrix products: default
locale:
[1] LC_COLLATE=German_Germany.utf8 LC_CTYPE=German_Germany.utf8 LC_MONETARY=German_Germany.utf8
[4] LC_NUMERIC=C LC_TIME=German_Germany.utf8
attached base packages:
[1] stats graphics grDevices utils datasets methods base
loaded via a namespace (and not attached):
[1] httr_1.4.4 tidyr_1.2.1 viridisLite_0.4.1 jsonlite_1.8.2 splines_4.2.1
[6] leiden_0.4.3 shiny_1.7.2 sp_1.5-0 ggrepel_0.9.1 globals_0.16.1
[11] pillar_1.8.1 lattice_0.20-45 glue_1.6.2 reticulate_1.26 digest_0.6.29
[16] RColorBrewer_1.1-3 promises_1.2.0.1 colorspace_2.0-3 plyr_1.8.7 cowplot_1.1.1
[21] htmltools_0.5.3 httpuv_1.6.6 Matrix_1.5-1 pkgconfig_2.0.3 listenv_0.8.0
[26] purrr_0.3.5 xtable_1.8-4 patchwork_1.1.2 scales_1.2.1 RANN_2.6.1
[31] later_1.3.0 Rtsne_0.16 spatstat.utils_2.3-1 tibble_3.1.8 generics_0.1.3
[36] ggplot2_3.3.6 ellipsis_0.3.2 ROCR_1.0-11 pbapply_1.5-0 SeuratObject_4.1.2
[41] lazyeval_0.2.2 cli_3.4.1 survival_3.3-1 magrittr_2.0.3 mime_0.12
[46] future_1.28.0 fansi_1.0.3 parallelly_1.32.1 MASS_7.3-57 ica_1.0-3
[51] progressr_0.11.0 tools_4.2.1 fitdistrplus_1.1-8 data.table_1.14.2 lifecycle_1.0.3
[56] matrixStats_0.62.0 stringr_1.4.1 plotly_4.10.0 munsell_0.5.0 cluster_2.1.3
[61] irlba_2.3.5.1 compiler_4.2.1 rlang_1.0.6 scattermore_0.8 grid_4.2.1
[66] ggridges_0.5.4 RcppAnnoy_0.0.19 htmlwidgets_1.5.4 igraph_1.3.5 miniUI_0.1.1.1
[71] gtable_0.3.1 codetools_0.2-18 reshape2_1.4.4 R6_2.5.1 gridExtra_2.3
[76] zoo_1.8-11 dplyr_1.0.10 fastmap_1.1.0 future.apply_1.9.1 rgeos_0.5-9
[81] utf8_1.2.2 KernSmooth_2.23-20 stringi_1.7.8 parallel_4.2.1 Rcpp_1.0.9
[86] sctransform_0.3.5 vctrs_0.4.2 png_0.1-7 tidyselect_1.2.0 lmtest_0.9-40
</code></pre>
<p>Thank you so much!</p>
<p>I tried to find out what the problem could be. I had hope that the installation of RTools42 may work but that does not make it better. The error still occurs.</p>
| [
{
"answer_id": 74194644,
"author": "Omer Dagry",
"author_id": 15010874,
"author_profile": "https://Stackoverflow.com/users/15010874",
"pm_score": 1,
"selected": false,
"text": "t = 0\nprint(\"this is your\", t, \"warning\")\nprint(f\"this is your {t} warning\")\nprint(\"this is your \" +... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20330526/"
] |
74,194,667 | <p>I ran into an issue where my async functions caused the UI to freeze, even tho I was calling them in a Task, and tried many other ways of doing it (GCD, Task.detached and the combination of the both). After testing it I figured out which part causes this behaviour, and I think it's a bug in Swift/SwiftUI.</p>
<p><strong>Bug description</strong></p>
<p>I wanted to calculate something in the background every x seconds, and then update the view, by updating a @Binding/@EnvironmentObject value. For this I used a timer, and listened to it's changes, by subscribing to it in a .onReceive modifier. The action of this modifer was just a Task with the async function in it (await foo()). This works like expected, so even if the foo function pauses for seconds, the UI won't freeze <strong>BUT</strong> if I add one @EnvironmentObject to the view the UI will be unresponsive for the duration of the foo function.</p>
<p>GIF of the behaviour with <strong>no</strong> EnvironmentVariable in the view:</p>
<p><a href="https://i.stack.imgur.com/37ris.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/37ris.gif" alt="Correct, expected behaviour" /></a></p>
<p>GIF of the behaviour with EnvironmentVariable in the view:</p>
<p><a href="https://i.stack.imgur.com/mkiL4.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mkiL4.gif" alt="Incorrect, unresponsive behaviour" /></a></p>
<p><strong>Minimal, Reproducible example</strong></p>
<p>This is just a button and a scroll view to see the animations. When you press the button with the EnvironmentObject present in the code the UI freezes and stops responding to the gestures, but just by removing that one line the UI works like it should, remaining responsive and changing properties.</p>
<pre><code>import SwiftUI
class Config : ObservableObject{
@Published var color : Color = .blue
}
struct ContentView: View {
//Just by removing this, the UI freeze stops
@EnvironmentObject var config : Config
@State var c1 : Color = .blue
var body: some View {
ScrollView(showsIndicators: false) {
VStack {
HStack {
Button {
Task {
c1 = .red
await asyncWait()
c1 = .green
}
} label: {
Text("Task, async")
}
.foregroundColor(c1)
}
ForEach(0..<20) {x in
HStack {
Text("Placeholder \(x)")
Spacer()
}
.padding()
.border(.blue)
}
}
.padding()
}
}
func asyncWait() async{
let continueTime: Date = Calendar.current.date(byAdding: .second, value: 2, to: Date())!
while (Date() < continueTime) {}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
</code></pre>
<p><strong>Disclaimer</strong></p>
<p>I am fairly new to using concurrency to the level I need for this project, so I might be missing something, but I couldn't find anything related to the searchwords "Task" and "EnvironmentObject".</p>
<p><strong>Question</strong></p>
<p>Is this really a bug? Or am I missing something?</p>
| [
{
"answer_id": 74195339,
"author": "jnpdx",
"author_id": 560942,
"author_profile": "https://Stackoverflow.com/users/560942",
"pm_score": 3,
"selected": true,
"text": "@EnvrionmentObject"
},
{
"answer_id": 74200617,
"author": "Rob",
"author_id": 1271826,
"author_profil... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11259671/"
] |
74,194,679 | <p>Say you have a room with an indefinite number of light bulbs, and these are turning randomly on and off. Each time a bulb is turned on and then off, a record is entered in a table with TurnedOn and TurnedOff values.
How should the query look like if I am interested in how long (HH.mm.ss) was it visible in the room between two DateTime values?</p>
<p>e.g.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>LightBulbId</th>
<th>TurnedOn</th>
<th>TurnedOff</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2022-10-01 06:00:00</td>
<td>2022-10-01 11:00:00</td>
</tr>
<tr>
<td>2</td>
<td>2022-10-01 07:00:00</td>
<td>2022-10-01 10:00:00</td>
</tr>
<tr>
<td>3</td>
<td>2022-10-01 08:00:00</td>
<td>2022-10-01 09:00:00</td>
</tr>
<tr>
<td>4</td>
<td>2022-10-01 12:00:00</td>
<td>2022-10-01 13:00:00</td>
</tr>
<tr>
<td>5</td>
<td>2022-10-01 14:00:00</td>
<td>2022-10-01 15:00:00</td>
</tr>
</tbody>
</table>
</div>
<p>So for the example above in the time period between 2022-10-01 06:00:00 and 2022-10-01 15:00:00 - 09 hours has passed and it was visible for 07 hours.</p>
<ol>
<li>The bulb can be on for more than 24 hours.</li>
<li>One hour increments are put in the example for simplicity.</li>
<li>If at least one light bulb is on, you can see in the room.</li>
<li>If a Light is turned on, starting from that moment you can see in the room, and if a light is turned off starting from that moment you can not :-)</li>
</ol>
<p>Another example with the same logic:</p>
<p>Say you have a machine that more than one person can work on at the same time. StartTime and EndTime is added to the table each time when a person starts and then stops working on a machine. I am interested in what was machines work time for a given time period?</p>
| [
{
"answer_id": 74196387,
"author": "DannySlor",
"author_id": 19174570,
"author_profile": "https://Stackoverflow.com/users/19174570",
"pm_score": 2,
"selected": true,
"text": "select sign(on_off) as on_off\n ,sum(hour_diff) as hours\nfrom\n(\nselect *\n ,datediff(secon... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1809167/"
] |
74,194,685 | <p>I have Elasticsearch Data pods that are currently running on an AKS and are connected to Persistent Volumes that is using a Premium SSD Managed Disk Storage Class and I want to downgrade it to Standard SSD Managed Disk without losing the data I have on the currently used Persistent Volume.
I've created a new Storage Class that is defined with Standard SSD Managed Disk, but if I create a new PV from that it obviously doesn't keep the old data and I need to copy it somehow, so I was wondering what would be best practice switching PV's Storage Class.</p>
| [
{
"answer_id": 74196331,
"author": "LeoD",
"author_id": 18553882,
"author_profile": "https://Stackoverflow.com/users/18553882",
"pm_score": 3,
"selected": true,
"text": "rsync"
},
{
"answer_id": 74597591,
"author": "teamdever",
"author_id": 11817652,
"author_profile":... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11817652/"
] |
74,194,697 | <p>I'm trying to filter out questions based on the difficulty that is set to the question in the array. So when I check the box at the beginning of the quiz it will display the question based on the difficulty it has been assigned. I think I have the filter right but I don't know how to display the question. This is the code I have written.</p>
<pre><code>let questionE1 = document.getElementById("question")
let a_answer = document.getElementById("a-answer");
let b_answer = document.getElementById("b-answer");
let c_answer = document.getElementById("c-answer");
let d_answer = document.getElementById("d-answer");
let submitBtn = document.getElementById("submit");
let currentQuiz = 0;
let easyDifficulty = document.getElementById("easy-diff");
let mediumDifficulty = document.getElementById("medium-diff");
let hardDifficulty = document.getElementById("hard-diff");
let difficulty = document.querySelectorAll('[name="difficulty"]');
let difficultyLevel = "";
let questionE1 = document.getElementById("question")
let a_answer = document.getElementById("a-answer");
let b_answer = document.getElementById("b-answer");
let c_answer = document.getElementById("c-answer");
let d_answer = document.getElementById("d-answer");
let submitBtn = document.getElementById("submit");
let questions = [
{
question: `What is the biggest city in the USA`,
a: `Chicago`,
b: `Los Angeles`,
c: `Boston`,
d: `New York`,
answer: `d`,
difficulty:`hard`
},
{
question: `What is the longest river on the earth`,
a: `Amazon`,
b: `Nile`,
c: `Amur`,
d: `Mississippi`,
answer: `b`,
difficulty:`medium`
},
{
question: `What is the highest mountain on earth`,
a: `Everest`,
b: `K2`,
c: `Broad Peak`,
d: `Manaslu`,
answer: `a`,
difficulty:`easy`
},
]
let filteredQuestions = questions.filter(question => question.difficulty === difficultyLevel)
let pickDifficulty = () => {
if (easyDifficulty.checked){
difficultyLevel = "easy";
} else if (mediumDifficulty.checked){
difficultyLevel = "medium";
}else if (hardDifficulty.checked){
difficultyLevel = "hard";
}
}
function getQuestion() {
if (pickDifficulty === "easy") {
return filteredQuestions.value;
} else if (pickDifficulty === "medium"){
return filteredQuestions.value;
} else if (pickDifficulty === "hard"){
return filteredQuestions.value;
}
}
displayQuestion ()
function displayQuestion () {
let currentQuestion = questions[currentQuiz]
questionE1.innerText = currentQuestion.question
a_answer.innerText = currentQuestion.a
b_answer.innerText = currentQuestion.b
c_answer.innerText = currentQuestion.c
d_answer.innerText = currentQuestion.d
}
</code></pre>
| [
{
"answer_id": 74196331,
"author": "LeoD",
"author_id": 18553882,
"author_profile": "https://Stackoverflow.com/users/18553882",
"pm_score": 3,
"selected": true,
"text": "rsync"
},
{
"answer_id": 74597591,
"author": "teamdever",
"author_id": 11817652,
"author_profile":... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20248446/"
] |
74,194,702 | <p>I have an Eigen (3.4.0) related question that really troubles me. In this C++ code, there's a function <code>pass_by_nonconst_ref</code> which takes a <strong>non-const reference to a eigen matrix</strong>, and that does some work on the matrix.</p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include "Eigen/Eigen"
using namespace std;
// A function that takes a non const reference to a vector
void pass_by_nonconst_ref(Eigen::Matrix<float, -1, 1>& vec) {
// do some work on your matrix...
vec(0) = 1;
}
int main() {
// This works without any problem.
Eigen::Matrix<float, -1, 1> x1(3);
x1 << 0.0, 0.0, 0.0 ;
pass_by_nonconst_ref(x1);
cout << "x = " << x1 << endl ;
// But this does not !!!!
Eigen::Matrix<float, 3, 1> x2;
x2 << 0.0, 0.0, 0.0 ;
// if you uncomment this line, it won't compile...
// pass_by_nonconst_ref(x2);
cout << "x = " << x2 << endl ;
// And to check that x2 is not a temporary?
Eigen::Matrix<float, 3, 1> x3;
x3 << 0.0, 0.0, 0.0 ;
x3(0) = 1;
cout << "x = " << x3 << endl ;// this works
return 0;
}
</code></pre>
<p>This code only compiles if I pass to the function an object the type <code>Eigen::Matrix<float, -1, 1></code>. If I use instead <code>Eigen::Matrix<float, 3, 1></code>, then there is the following compilation error:</p>
<pre class="lang-bash prettyprint-override"><code>error: cannot bind non-const lvalue reference of type ‘Eigen::Matrix<float, -1, 1>&’ to an rvalue of type ‘Eigen::Matrix<float, -1, 1>’
22 | pass_by_nonconst_ref(x2);
</code></pre>
<p>The only difference (that I see) is that <code>x2</code> knows it only has 3 rows, whereas <code>x1</code> has a dynamic number of rows. I am aware that a non-const reference can't bind to a temporary, but I really don't see why <code>x2</code> can be considered as one and not <code>x1</code>.</p>
<p>I can't understand why I have to specify the dynamic type to make it work. It got me quite curious. Is there something obvious that I am missing ? I suspect it is related to type conversion.</p>
| [
{
"answer_id": 74196331,
"author": "LeoD",
"author_id": 18553882,
"author_profile": "https://Stackoverflow.com/users/18553882",
"pm_score": 3,
"selected": true,
"text": "rsync"
},
{
"answer_id": 74597591,
"author": "teamdever",
"author_id": 11817652,
"author_profile":... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13219173/"
] |
74,194,703 | <p>I made a scroll to top button that appears when the user scrolls down 25px from the top of the document (otherwise it's not visible) thanks to JavaScript following a tutorial because I still don't know anything about this programming language.</p>
<p>However, I would like it to be visible only on desktop websites and not also on mobile.</p>
<p>I tried using <strong>media queries</strong> but they <strong>don't work</strong> since <em>JavaScript</em> has <strong>control</strong> over the <strong>visibility</strong> of the button.
What function can I integrate to manage everything with JS?</p>
<p>Here is the code I'm using.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let myButton = document.getElementById("to-top-container");
window.onscroll = function() {
scrollFunction()
};
function scrollFunction() {
if (document.body.scrollTop > 25 || document.documentElement.scrollTop > 25) {
myButton.style.display = "block";
} else {
myButton.style.display = "none";
}
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>#to-top-container {
position: fixed;
bottom: 30px;
right: 3px;
}
.to-top-button {
background-color: #263238;
min-height: 40px;
min-width: 40px;
border-radius: 20px;
text-decoration: none;
display: flex;
justify-content: center;
align-items: center;
box-shadow: 2px 4px 5px rgb(0 0 0 / 30%);
/* animation: Up 2.3s infinite; */
}
#to-top-container .lni {
font-size: 14px;
font-weight: 900;
color: white;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="to-top-container">
<a href="#body-container" title="Torna su" class="to-top-button">
<i class="lni lni-chevron-up"></i>
</a>
</div></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74196331,
"author": "LeoD",
"author_id": 18553882,
"author_profile": "https://Stackoverflow.com/users/18553882",
"pm_score": 3,
"selected": true,
"text": "rsync"
},
{
"answer_id": 74597591,
"author": "teamdever",
"author_id": 11817652,
"author_profile":... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19744323/"
] |
74,194,721 | <p>Consider the following data set:</p>
<p>How can I generate the expected value, <code>ExpectedGroup</code> such that the same value exists when True, but changes and increments by 1, when we run into a False statement in <code>case_id</code>.</p>
<pre><code>df = pd.DataFrame([
['A', 'P', 'O', 2, np.nan],
['A', 'O', 'O', 5, 1],
['A', 'O', 'O', 10, 1],
['A', 'O', 'P', 4, np.nan],
['A', 'P', 'P', 300, np.nan],
['A', 'P', 'O', 2, np.nan],
['A', 'O', 'O', 5, 2],
['A', 'O', 'O', 10, 2],
['A', 'O', 'P', 4, np.nan],
['A', 'P', 'P', 300, np.nan],
['B', 'P', 'O', 2, np.nan],
['B', 'O', 'O', 5, 3],
['B', 'O', 'O', 10, 3],
['B', 'O', 'P', 4, np.nan],
['B', 'P', 'P', 300, np.nan],
],
columns = ['ID', 'FromState', 'ToState', 'Hours', 'ExpectedGroup'])
</code></pre>
<pre><code># create boolean mask
df['case_id'] = ( (df.FromState == 'O') & (df.ToState == 'O') )
0 False
1 True
2 True
3 False
4 False
5 False
6 True
7 True
8 False
9 False
10 False
11 True
12 True
13 False
14 False
Name: case_id, dtype: boo
</code></pre>
<pre><code># but how to get incrementing groups?
np.where(df['case_id'] != False, df['case_id'].cumsum(), np.nan)
</code></pre>
| [
{
"answer_id": 74194752,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 3,
"selected": true,
"text": "diff"
},
{
"answer_id": 74194836,
"author": "Shubham Sharma",
"author_id": 12833166,
"author_pro... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6534818/"
] |
74,194,793 | <p>I'm new to SQL and I am trying to filter out responses with no variation for survery collection (invalid responses) to do multi-linear regression. Do take note that there is actually more than 100 records for this table and I have simplified it for the illustration.</p>
<p>Database: MySQL 8.0.30 : TLSv1.2 (TablePlus)</p>
<ul>
<li>ID is the respondent number.</li>
<li>Variables - x1, x2, x3 is the independent variables.</li>
<li>Values - Survery response.</li>
</ul>
<p>For example this is the current table I have:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>Variables</th>
<th>Values</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>x1</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>x2</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>x3</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>x1</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
<td>x2</td>
<td>3</td>
</tr>
<tr>
<td>2</td>
<td>x3</td>
<td>4</td>
</tr>
<tr>
<td>3</td>
<td>x1</td>
<td>5</td>
</tr>
<tr>
<td>3</td>
<td>x2</td>
<td>5</td>
</tr>
<tr>
<td>3</td>
<td>x3</td>
<td>5</td>
</tr>
</tbody>
</table>
</div>
<p>Scripts used:
<em>SELECT ID, Variables, Values
FROM TableA
GROUP BY ID</em></p>
<p>I am trying to achieve the following table, where I only want to keep the records which have a variation in the responses:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>Variables</th>
<th>Values</th>
</tr>
</thead>
<tbody>
<tr>
<td>2</td>
<td>x1</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
<td>x2</td>
<td>3</td>
</tr>
<tr>
<td>2</td>
<td>x3</td>
<td>4</td>
</tr>
</tbody>
</table>
</div>
<p>I have tried to use the functions WHERE, DISTINCT, WHERE NOT, HAVING, but I can't seem to get the results that I require, or showing blank most times (like the table below). If anyone is able to help, that would be most helpful.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>Variables</th>
<th>Values</th>
</tr>
</thead>
</table>
</div>
<p>Thank you very much!</p>
| [
{
"answer_id": 74194752,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 3,
"selected": true,
"text": "diff"
},
{
"answer_id": 74194836,
"author": "Shubham Sharma",
"author_id": 12833166,
"author_pro... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20129214/"
] |
74,194,843 | <p><strong>I have this</strong></p>
<pre><code>function Toggle(){
const [toggleOn, setToggleOn] = useState(false);
return (
<div>
{toggleOn == true && <Settingson className={classes.settingson} onClick={() => setToggleOn(d => !d)} value="true" name="toggle"/>}
{toggleOn == false && <Settingsoff className={classes.settingsoff} onClick={() => setToggleOn(d => !d)} value="false" name="toggle"/>}
</div>
)
}
export default Toggle;
</code></pre>
<p><strong>And somehow I want to get the value of this</strong></p>
<pre><code><Toggle />
</code></pre>
<p><strong>I tried many things, but couldn't came up with a solution. Please help! I am new to React Next Js.</strong></p>
<p>I tried to get the value of a jsx component, but It doesn't work. Somehow I need to check if the value of the toggle is true or not.</p>
| [
{
"answer_id": 74194752,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 3,
"selected": true,
"text": "diff"
},
{
"answer_id": 74194836,
"author": "Shubham Sharma",
"author_id": 12833166,
"author_pro... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18260438/"
] |
74,194,869 | <p>I'm trying to convert a list of elements to tuples and then add the tuples to a new list but keep running into issues with how the results are presented.</p>
<p>My list is:</p>
<pre><code>list = ['(One, 1)', '(Two, 2)', '(Three, 3)', '(Four, 4)']
</code></pre>
<p>When I try to convert it to a tuple using:</p>
<pre><code>for a in list1:
list2.append(tuple([a.replace("(", "").replace(")", "")]))
</code></pre>
<p>It gives the output:</p>
<pre><code>print(list2)
[('One, 1',), ('Two, 2',), ('Three, 3',), ('Four, 4',)]
</code></pre>
<p>I want it to give the following output:</p>
<pre><code>[('One', 1), ('Two', 2), ('Three', 3), ('Four', 4)]
</code></pre>
<p>How would I go about doing this?</p>
| [
{
"answer_id": 74194992,
"author": "Aymen",
"author_id": 5165980,
"author_profile": "https://Stackoverflow.com/users/5165980",
"pm_score": 2,
"selected": true,
"text": "list1 = ['(One, 1)', '(Two, 2)', '(Three, 3)', '(Four, 4)']\nlist2 = []\n\nfor a in list1:\n str = a.replace(\"(\", ... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20280977/"
] |
74,194,876 | <p>Sharing Sample XML file. Need to convert this fie to CSV, even if extra tags are added in this file. {without using tag names}. And XML file tag names should be used as column names while converting it to CSV}</p>
<p>Example Data:</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<Food>
<Info>
<Msg>Food Store items.</Msg>
</Info>
<store slNo="1">
<foodItem>meat</foodItem>
<price>200</price>
<quantity>1kg</quantity>
<discount>7%</discount>
</store>
<store slNo="2">
<foodItem>fish</foodItem>
<price>150</price>
<quantity>1kg</quantity>
<discount>5%</discount>
</store>
<store slNo="3">
<foodItem>egg</foodItem>
<price>100</price>
<quantity>50 pieces</quantity>
<discount>5%</discount>
</store>
<store slNo="4">
<foodItem>milk</foodItem>
<price>50</price>
<quantity>1 litre</quantity>
<discount>3%</discount>
</store>
</Food>
</code></pre>
<p>Tried Below code but getting error with same.</p>
<pre class="lang-py prettyprint-override"><code>import xml.etree.ElementTree as ET
import pandas as pd
ifilepath = r'C:\DATA_DIR\feeds\test\sample.xml'
ofilepath = r'C:\DATA_DIR\feeds\test\sample.csv'
root = ET.parse(ifilepath).getroot()
print(root)
with open(ofilepath, "w") as file:
for child in root:
print(child.tag, child.attrib)
# naive example how you could save to csv line wise
file.write(child.tag+";"+child.attrib)
</code></pre>
<p>Above code is able to find root node, but unable to concatenate its attributes though</p>
<p>Tried one more code, but this works for 1 level nested XML, who about getting 3-4 nested tags in same XML file. And currently able to print values of all tags and their text. need to convert these into relational model { CSV file}</p>
<pre><code>import xml.etree.ElementTree as ET
tree = ET.parse(ifilepath)
root = tree.getroot()
for member in root.findall('*'):
print(member.tag,member.attrib)
for i in (member.findall('*')):
print(i.tag,i.text)
</code></pre>
<p>Above example works well with pandas read_xml { using lxml parser}</p>
<p>But when we try to use the similar way out for below XML data, it doesn't produce indicator ID value and Country ID value as output in CSV file</p>
<p>Example Data ::</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<du:data xmlns:du="http://www.dummytest.org" page="1" pages="200" per_page="20" total="1400" sourceid="5" sourcename="Dummy ID Test" lastupdated="2022-01-01">
<du:data>
<du:indicator id="AA.BB">various, tests</du:indicator>
<du:country id="MM">test again</du:country>
<du:date>2021</du:date>
<du:value>1234567</du:value>
<du:unit />
<du:obs_status />
<du:decimal>0</du:decimal>
</du:data>
<du:data>
<du:indicator id="XX.YY">testing, cases</du:indicator>
<du:country id="DD">coverage test</du:country>
<du:date>2020</du:date>
<du:value>3456223</du:value>
<du:unit />
<du:obs_status />
<du:decimal>0</du:decimal>
</du:data>
</du:data>
</code></pre>
<p>Solution Tried ::</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
pd.read_xml(ifilepath, xpath='.//du:data', namespaces= {"du": "http://www.dummytest.org"}).to_csv(ofilepath, sep=',', index=None, header=True)
</code></pre>
<p>Output Got ::</p>
<pre><code>indicator,country,date,value,unit,obs_status,decimal
"various, tests",test again,2021,1234567,,,0
"testing, cases",coverage test,2020,3456223,,,0
</code></pre>
<p>Expected output ::</p>
<pre><code>indicator id,indicator,country id,country,date,value,unit,obs_status,decimal
AA.BB,"various, tests",MM,test again,2021,1234567,,,0
XX.YY,"testing, cases",DD,coverage test,2020,3456223,,,0
</code></pre>
<p>Adding Example data , having usage of 2 or more xpath's.
Looking for ways to convert the same using pandas <code>to_csv()</code></p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type='text/xsl'?>
<CATALOG>
<PLANT>
<COMMON>rose</COMMON>
<BOTANICAL>canadensis</BOTANICAL>
<ZONE>4</ZONE>
<LIGHT>Shady</LIGHT>
<PRICE>202</PRICE>
<AVAILABILITY>446</AVAILABILITY>
</PLANT>
<PLANT>
<COMMON>mango</COMMON>
<BOTANICAL>sunny</BOTANICAL>
<ZONE>3</ZONE>
<LIGHT>shady</LIGHT>
<PRICE>301</PRICE>
<AVAILABILITY>569</AVAILABILITY>
</PLANT>
<PLANT>
<COMMON>Marigold</COMMON>
<BOTANICAL>palustris</BOTANICAL>
<ZONE>4</ZONE>
<LIGHT>Sunny</LIGHT>
<PRICE>500</PRICE>
<AVAILABILITY>799</AVAILABILITY>
</PLANT>
<PLANT>
<COMMON>carrot</COMMON>
<BOTANICAL>Caltha</BOTANICAL>
<ZONE>4</ZONE>
<LIGHT>sunny</LIGHT>
<PRICE>205</PRICE>
<AVAILABILITY>679</AVAILABILITY>
</PLANT>
<FOOD>
<NAME>daal fry</NAME>
<PRICE>300</PRICE>
<DESCRIPTION>
Famous daal tadka from surat
</DESCRIPTION>
<CALORIES>60</CALORIES>
</FOOD>
<FOOD>
<NAME>Dhosa</NAME>
<PRICE>350</PRICE>
<DESCRIPTION>
The famous south indian dish
</DESCRIPTION>
<CALORIES>80</CALORIES>
</FOOD>
<FOOD>
<NAME>Khichdi</NAME>
<PRICE>150</PRICE>
<DESCRIPTION>
The famous gujrati dish
</DESCRIPTION>
<CALORIES>40</CALORIES>
</FOOD>
<BOOK>
<AUTHOR>Santosh Bihari</AUTHOR>
<TITLE>PHP Core</TITLE>
<GENER>programming</GENER>
<PRICE>44.95</PRICE>
<DATE>2000-10-01</DATE>
</BOOK>
<BOOK>
<AUTHOR>Shyam N Chawla</AUTHOR>
<TITLE>.NET Begin</TITLE>
<GENER>Computer</GENER>
<PRICE>250</PRICE>
<DATE>2002-17-05</DATE>
</BOOK>
<BOOK>
<AUTHOR>Anci C</AUTHOR>
<TITLE>Dr. Ruby</TITLE>
<GENER>Computer</GENER>
<PRICE>350</PRICE>
<DATE>2001-04-11</DATE>
</BOOK>
</CATALOG>
</code></pre>
| [
{
"answer_id": 74194992,
"author": "Aymen",
"author_id": 5165980,
"author_profile": "https://Stackoverflow.com/users/5165980",
"pm_score": 2,
"selected": true,
"text": "list1 = ['(One, 1)', '(Two, 2)', '(Three, 3)', '(Four, 4)']\nlist2 = []\n\nfor a in list1:\n str = a.replace(\"(\", ... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16748727/"
] |
74,194,892 | <p>I wanted to have my dags to have first run on <code>2:00 AM on 25th</code> and then onwards Tuesday to Sat daily run at <code>2:00 am</code>.</p>
<p>following is how my scheduling look like.</p>
<pre class="lang-py prettyprint-override"><code>with DAG(
dag_id='in__xxx__agnt_brk_com',
schedule_interval='0 2 * * 2-6',
start_date=datetime(2022, 10, 24),
catchup=False,
) as dag:
</code></pre>
<p>And on Airflow UI also it shows that my first run should be on <code>25th 2:00 AM</code>. But unfortunately, dags didn't execute on time.</p>
<p><a href="https://i.stack.imgur.com/XNDzB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XNDzB.png" alt="enter image description here" /></a>
<a href="https://i.stack.imgur.com/3NHlz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3NHlz.png" alt="enter image description here" /></a></p>
<p>What I am missing here ?</p>
| [
{
"answer_id": 74194992,
"author": "Aymen",
"author_id": 5165980,
"author_profile": "https://Stackoverflow.com/users/5165980",
"pm_score": 2,
"selected": true,
"text": "list1 = ['(One, 1)', '(Two, 2)', '(Three, 3)', '(Four, 4)']\nlist2 = []\n\nfor a in list1:\n str = a.replace(\"(\", ... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2504762/"
] |
74,194,901 | <p>I have an array with date and some total.
I would like to sum all A_Total ; B_Total ; C_Total that have the same Date.</p>
<p>How can I do that ?
Thanks for the help</p>
<p>Source :</p>
<pre>
Array
(
[0] => Array
(
[Date] => 2022-10-23
[A_Total] => 547
[B_Total] => 70
[C_Total] => 83
)
[1] => Array
(
[Date] => 2022-10-24
[A_Total] => 547
[B_Total] => 70
[C_Total] => 83
)
[2] => Array
(
[Date] => 2022-10-25
[A_Total] => 552
[B_Total] => 70
[C_Total] => 83
)
[3] => Array
(
[Date] => 2022-10-23
[A_Total] => 5
[B_Total] => 1
[C_Total] => 19
)
[4] => Array
(
[Date] => 2022-10-24
[A_Total] => 5
[B_Total] => 1
[C_Total] => 19
)
[5] => Array
(
[Date] => 2022-10-25
[A_Total] => 5
[B_Total] => 1
[C_Total] => 19
)
[6] => Array
(
[Date] => 2022-10-23
[A_Total] => 557
[B_Total] => 134
[C_Total] => 51
)
[7] => Array
(
[Date] => 2022-10-24
[A_Total] => 557
[B_Total] => 134
[C_Total] => 51
)
[8] => Array
(
[Date] => 2022-10-25
[A_Total] => 557
[B_Total] => 134
[C_Total] => 51
)
)
</pre>
<p>Expected :</p>
<pre>
Array
(
[0] => Array
(
[Date] => 2022-10-23
[A_Total] => 1019
[B_Total] => 205
[C_Total] => 153
)
[1] => Array
(
[Date] => 2022-10-24
[A_Total] => 1019
[B_Total] => 205
[C_Total] => 153
)
[2] => Array
(
[Date] => 2022-10-25
[A_Total] => 1114
[B_Total] => 205
[C_Total] => 153
)
)
</pre>
| [
{
"answer_id": 74194992,
"author": "Aymen",
"author_id": 5165980,
"author_profile": "https://Stackoverflow.com/users/5165980",
"pm_score": 2,
"selected": true,
"text": "list1 = ['(One, 1)', '(Two, 2)', '(Three, 3)', '(Four, 4)']\nlist2 = []\n\nfor a in list1:\n str = a.replace(\"(\", ... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12549913/"
] |
74,194,907 | <p>I'm trying to understand proper execution order of async functions in Dart. Here is a code that puzzles me:</p>
<pre class="lang-dart prettyprint-override"><code>void main() async {
print(1);
f1();
print(3);
}
void f1() async {
print(2);
}
</code></pre>
<p>According to spec first <code>main()</code> will be executed then <code>f1()</code>. So I expect output:</p>
<pre><code>1
3
2
</code></pre>
<p>However real output is:</p>
<pre><code>1
2
3
</code></pre>
<p>Does it mean <code>f1()</code> is executed synchronously?</p>
<p>However if I add <code>await Future.delayed(Duration.zero);</code> to <code>f1()</code> before <code>print</code> the output is as I expect:</p>
<pre class="lang-dart prettyprint-override"><code>void main() async {
print(1);
f1();
print(3);
}
void f1() async {
await Future.delayed(Duration.zero);
print(2);
}
</code></pre>
<pre><code>1
3
2
</code></pre>
<p>Can anyone explain that?</p>
| [
{
"answer_id": 74195082,
"author": "Christopher Moore",
"author_id": 13250142,
"author_profile": "https://Stackoverflow.com/users/13250142",
"pm_score": 1,
"selected": true,
"text": "async"
}
] | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/200160/"
] |
74,194,952 | <p>Before in other random languages I always returned values from functions and I was so surprised now when I try do like below but got error:</p>
<pre><code>fun getChannels(): List<TblChannel> {
val stringRequest = JsonObjectRequest(
Request.Method.GET, "$baseUrl/api/json/channel_list.json",
null,
{ response ->
try{
val gson = Gson()
val token = TypeToken.getParameterized(ArrayList::class.java,TblChannel::class.java).type
val channels1:JSONArray = response.getJSONArray("groups").getJSONObject(0).getJSONArray("channels")
//got "return isn't allowed here" error
return gson.fromJson(channels1.toString(),token)
} catch (e:Exception){
Log.e(tag,"DkPrintError on getChannels: $e")
}
},
{ error ->
Log.e(tag, "DkPrintError on getChannels: $error")
})
requestQueue.add(stringRequest)
}
</code></pre>
<p>How can I convert response body to my class and return them?</p>
| [
{
"answer_id": 74232518,
"author": "Dowlpack",
"author_id": 8385912,
"author_profile": "https://Stackoverflow.com/users/8385912",
"pm_score": 0,
"selected": false,
"text": "fun getChannels(onDataReadyCallback: OnDataReadyCallBack){\n val stringRequest = JsonObjectRequest(\n ... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8385912/"
] |
74,194,987 | <p>Render Error
<a href="https://i.stack.imgur.com/xZc9a.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xZc9a.png" alt="enter image description here" /></a></p>
<p><em>Here is my code:</em></p>
<p>function Adddetails () {
set(ref(db, 'users/' + phone), {
phone: phone,
parent: parent
}).then(() => {
alert('data updated');
})
.catch((error) => {
alert(error);
});
};</p>
<p><a href="https://i.stack.imgur.com/JsPJr.png" rel="nofollow noreferrer">button design code is here</a></p>
| [
{
"answer_id": 74195149,
"author": "Azzam Michel",
"author_id": 14568922,
"author_profile": "https://Stackoverflow.com/users/14568922",
"pm_score": 3,
"selected": true,
"text": "<button/>"
},
{
"answer_id": 74195167,
"author": "Suyash Vashishtha",
"author_id": 11974466,
... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15611854/"
] |
74,194,996 | <p>I cant figure out how to do this...</p>
<pre><code>const arr1 = [{ name: 'peter' }, { name: 'sam', id: 1 }, { name: 'mark' }];
const arr2 = [{ name: 'sam' }, { name: 't' }, { name: 'george' }];
</code></pre>
<p>Desired outcome:</p>
<p><code>const arr2 = [{ name: 'sam', id: 1 }, { name: 't' }, { name: 'george' }];</code></p>
| [
{
"answer_id": 74195149,
"author": "Azzam Michel",
"author_id": 14568922,
"author_profile": "https://Stackoverflow.com/users/14568922",
"pm_score": 3,
"selected": true,
"text": "<button/>"
},
{
"answer_id": 74195167,
"author": "Suyash Vashishtha",
"author_id": 11974466,
... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20061501/"
] |
74,194,997 | <p>I am new in JS and I'm having difficulty with using a variable from another function to my new function.</p>
<p>the goal is to compute for a combination (combination calculator) but when I use this script code I don't get an output.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var i, num, num2;
function factor() {
x = 1;
y = 1;
num = document.getElementById("num").value;
for (i = 1; i <= num; i++) {
x = x * i;
}
i = i - 1;
document.getElementById("res").innerHTML = "The factorial of the number " + i + " is: " + x;
num2 = document.getElementById("num2").value;
for (i = 1; i <= num2; i++) {
y = y * i;
}
i = i - 1;
document.getElementById("res2").innerHTML = "The factorial of the number " + i + " is: " + y;
}
function partTwo() {
a = y.factor(num - num2);
b = x.factor / a;
document.getElementById("res3").innerHTML = "Answer: ";
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!--Input-->
<h2 id="one"> Please enter first value for combination calculation </h2>
<input type="number" placeholder="Number 1" id="num"> <br> <br>
<!--Input 2-->
<h2 id="two"> Please enter second value for combination calculation </h2>
<input type="number" placeholder="Number 2" id="num2"> <br> <br>
<!--button-->
<button onclick="factor()"> ENTER </button>
<h2 id="res"> </h2>
<h2 id="res2"> </h2>
<button onclick="partTwo()"> CALCULATE </button>
<h2 id="res3"> </h2></code></pre>
</div>
</div>
</p>
<p>I was supposed to get an output for a combination calculator and need help how to do the second function</p>
| [
{
"answer_id": 74195149,
"author": "Azzam Michel",
"author_id": 14568922,
"author_profile": "https://Stackoverflow.com/users/14568922",
"pm_score": 3,
"selected": true,
"text": "<button/>"
},
{
"answer_id": 74195167,
"author": "Suyash Vashishtha",
"author_id": 11974466,
... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74194997",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16025349/"
] |
74,195,017 | <p>So I am trying to think of a way to have a go back option if the user scans the wrong barcode. Some insight, my company scans in a lot of equipment and sometimes there are barcodes very close to each other and it easy to scan the wrong one.</p>
<p>The problem I am currently having with my code is that if the user scans the wrong code, there is not way to simply go back. You either have to terminate the script and start over, or insert the data into the db and change it manually in access.</p>
<p>Below is my current code:</p>
<pre><code># get serial numbers for equipment
print("------------------------")
serial_numbers = []
print("Scan barcode, type 'q' when you are done.")
# loop for user to insert multiple serial numbers.
while True:
s = input("Scan Code: ")
if s == "q":
break
serial_numbers.append(s)
print("Here is the list of serial numbers:")
print(serial_numbers)
</code></pre>
<p>Currently, as stated above, this code is not very...robust, if you will. If you don't get it right on the first try... the user has to completely start over or fix if manually in the Access DB.</p>
<p>Edit:</p>
<p>I attempted to add the .pop() method into the loop, but now the user input 'e' I am using to initiate the pop is being added to the list.</p>
<pre><code># get serial numbers for equipment
print("------------------------")
serial_numbers = []
print("Scan barcode, Type 'e' to delete last scanned item. Type 'q' when you are done.")
# loop for user to insert multiple serial numbers.
while True:
s = input("Scan Code: ")
if s == "e":
serial_numbers.pop()
print(serial_numbers)
if s == "q":
break
serial_numbers.append(s)
print("Here is the list of serial numbers:")
print(serial_numbers)
</code></pre>
<p>Output:</p>
<pre><code>Scan barcode, Type 'e' to delete last scanned item. Type 'q' when you are done.
Scan Code: 31P11JJ0019US
Scan Code: 31P11JJ0019US
Scan Code: 31P11JJ0019US
Scan Code: 31P11JJ0019US
Scan Code: e
['31P11JJ0019US', '31P11JJ0019US', '31P11JJ0019US']
Scan Code: 31P11JJ0019US
Scan Code: e
['31P11JJ0019US', '31P11JJ0019US', '31P11JJ0019US', 'e']
Scan Code:
</code></pre>
| [
{
"answer_id": 74195149,
"author": "Azzam Michel",
"author_id": 14568922,
"author_profile": "https://Stackoverflow.com/users/14568922",
"pm_score": 3,
"selected": true,
"text": "<button/>"
},
{
"answer_id": 74195167,
"author": "Suyash Vashishtha",
"author_id": 11974466,
... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20284202/"
] |
74,195,018 | <p>Every row in my schedules table has <code>start_time</code> and <code>end_time</code>.
I can get and map them by using the code below.</p>
<p>My question is how can I deliver an object with <code>moments</code> as an array of arrays, containing the intervals <code>start_time</code>, <code>end_time</code> of every row I get from my <code>schedules</code> table?</p>
<p>Below is the format I want to achieve, you can see there are two arrays inside of <code>moments</code> they are the two rows that came from my <code>schedules</code> table.</p>
<pre><code>{
moments: [
[ { hour: 6, minute: 45 }, { hour: 7, minute: 45 }, ],
[ { hour: 10, minute: 30 }, { hour: 11, minute: 30 }, ]
]
}
</code></pre>
<p>Here are my <code>schedules</code> table and sample records.</p>
<pre><code>+----------+------------------+----------------+-------------+
| id | start_time | end_time | user_id |
+----------+------------------+----------------+-------------+
| 1 | 6:45 | 7:45 | 1 |
| 2 | 10:30 | 11:30 | 1 |
+----------+------------------+----------------+-------------+
</code></pre>
<p>Code</p>
<pre><code>$user = User::find(1);
$schedules = Schedule::select('start_time', 'end_time')
->whereBelongsTo($user)
->get();
$collection = $schedules->map(function ($time) {
return [date("g:i", strtotime($time['start_time'])), date("g:i", strtotime($time['end_time']))];
});
$data = $collection->values()->all();
// result
[
[
"6:45",
"7:45",
],
[
"10:30",
"11:30",
],
]
</code></pre>
<p>Q: Why do I need that specific format?</p>
<p>A: Because I will use that on the client side's DateTimePicker to disable time intervals - <a href="https://getdatepicker.com/4/Options/#disabledtimeintervals" rel="nofollow noreferrer">https://getdatepicker.com/4/Options/#disabledtimeintervals</a></p>
<p><strong>Client side code</strong></p>
<p>Here I will access the formatted response from my backend by passing it inside <code>JSON.stringify()</code>.</p>
<pre><code>const timeIntervalsData = JSON.stringify( { moments: [
[ { hour: 6, minute: 45 }, { hour: 7, minute: 45 }, ],
[ { hour: 10, minute: 30 }, { hour: 11, minute: 30 }, ]
]
});
let options = {
format: 'hh:mm A',
disabledTimeIntervals: JSON.parse(timeIntervalsData)
.moments
.map( ([start, end]) => [ moment(start), moment(end) ] )
}
$('.datetimepicker').datetimepicker(options)
</code></pre>
| [
{
"answer_id": 74195149,
"author": "Azzam Michel",
"author_id": 14568922,
"author_profile": "https://Stackoverflow.com/users/14568922",
"pm_score": 3,
"selected": true,
"text": "<button/>"
},
{
"answer_id": 74195167,
"author": "Suyash Vashishtha",
"author_id": 11974466,
... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20147460/"
] |
74,195,022 | <p>I try to create a new column displaying 1 if another column is a missing value.</p>
<p>I have the following dataframe</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Col1</th>
<th>Col2</th>
</tr>
</thead>
<tbody>
<tr>
<td>NaN</td>
<td>5.5</td>
</tr>
<tr>
<td>2.5</td>
<td>1.6</td>
</tr>
<tr>
<td>NaN</td>
<td>2.0</td>
</tr>
</tbody>
</table>
</div>
<p>I want to get the following result :</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Col1</th>
<th>Col2</th>
<th>new_col</th>
</tr>
</thead>
<tbody>
<tr>
<td>NaN</td>
<td>5.5</td>
<td>1.0</td>
</tr>
<tr>
<td>2.5</td>
<td>1.6</td>
<td>0.0</td>
</tr>
<tr>
<td>NaN</td>
<td>2.0</td>
<td>1.0</td>
</tr>
</tbody>
</table>
</div>
<p>I tried the following code :</p>
<pre class="lang-py prettyprint-override"><code>df['new_col']=[1 if (pd.isnull(df['col1'])==True) else 0 for i in range(len(df))]
</code></pre>
<p>I got the following error :</p>
<pre><code>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
</code></pre>
| [
{
"answer_id": 74195069,
"author": "Naveed",
"author_id": 3494754,
"author_profile": "https://Stackoverflow.com/users/3494754",
"pm_score": 2,
"selected": false,
"text": "df['col3']=np.where(df['Col1'].isna(), 1, 0)\ndf\n"
},
{
"answer_id": 74195106,
"author": "mozway",
"... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15852600/"
] |
74,195,028 | <p>I have troubles with moving my character.
The Program should behave like this:</p>
<p>Read from the input two numbers separated by a space, rows and cols.
Create a 2D grid (array) of characters with dimensions of rows rows and cols columns. Initialize the characters in the grid to '.' (dot).
Place the turtle in position (0, 0) - the zero row and the zero column (top left).
Load characters sequentially from the program input. The characters will be separated by a white character (a space or a line).</p>
<p>If you hit the 'x' character, print the grid to the Program Output and exit the program.</p>
<p>If you encounter characters '<', '>', '^', 'v', Move the turtle in the corresponding direction (Left, Right, Up, Down).</p>
<p>If you encounter the character 'o', enter the character' o ' in the grid at the current position of the turtle.</p>
<p>If the turtle were to make a move that would take it out of the grid (e.g. to position (0, 0) it would receive the command to go to the left), then “teleport” the turtle to the opposite side of the grid.</p>
<p>My program (I do not why but when I press ">" or "<" it moves by two, not one):</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
int main(){
int rows, cols;
int i;
int j;
int x = 0, y = 0;
char symbol = 'o';
scanf("%d %d", &rows, &cols);
char* pole = (char*)malloc(rows * cols * sizeof(char));
for (i = 0; i < rows; i++){
for(j = 0; j < cols; j++)
pole[i * rows + j] = '.';
}
pole[x * rows + y] = 'o';
while(symbol != 'x'){
scanf("%c", &symbol);
if (symbol == '^') x--;
else if (symbol == 'v') x++;
else if (symbol == '>') y++;
else if (symbol == '<') y--;
else if (symbol == 'o') pole[x * rows + y] = 'o';
if(0 < y)
y = rows - 1;
else if(y > rows)
y = 0;
if(x < 0)
x = cols - 1;
else if(x > cols)
x = 0;
}
for (i = 0; i < rows; i++){
for(j = 0; j < cols; j++){
printf("%c", pole[i * rows + j]);
}
printf("\n");
}
return 0;
}
</code></pre>
<p>It should be like this:</p>
<pre><code>3 3
o
>
v
o
>
v
o
x
</code></pre>
<pre><code>o..
.o.
..o
</code></pre>
<p>But I have this:</p>
<pre><code>3 3
o
>
v
o
>
v
o
x
</code></pre>
<pre><code>o..
..o
..o
</code></pre>
| [
{
"answer_id": 74197266,
"author": "user20276305",
"author_id": 20276305,
"author_profile": "https://Stackoverflow.com/users/20276305",
"pm_score": 0,
"selected": false,
"text": "if (0 < y)"
},
{
"answer_id": 74203141,
"author": "Raon",
"author_id": 19535974,
"author_... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20330747/"
] |
74,195,088 | <p>Blazor has the <code>InputNumber</code> component that constrains input to digits. However that renders an <code><input type=number .../></code> which firefox does not respect (it permits any text).</p>
<p>So I tried to create a custom component that filters input:</p>
<pre class="lang-cs prettyprint-override"><code>@inherits InputNumber<int?>
<input type="number" @bind=_value @onkeypress=OnKeypress />
<p>@_value</p>
@code {
private string _value;
private void OnKeypress(KeyboardEventArgs e) {
if (Regex.IsMatch(e.Key, "[0-9]"))
_value += e.Key;
}
}
</code></pre>
<p>The <code><p></code> shows the correct value. But the input itself shows all keypresses.</p>
<p>How do I write a custom component to filter keystrokes? (In this example I'm filtering for digits, but I assume the same approach would apply for filtering any char.)</p>
| [
{
"answer_id": 74197430,
"author": "T.Trassoudaine",
"author_id": 10989407,
"author_profile": "https://Stackoverflow.com/users/10989407",
"pm_score": 2,
"selected": false,
"text": "@using Microsoft.AspNetCore.Components\n\n<input type=\"number\" value=@_value @oninput=OnInput />\n<p>@_va... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9971404/"
] |
74,195,091 | <p>I have this JSON:</p>
<pre class="lang-json prettyprint-override"><code>{
"mapTrue": "true",
"code": [
"X",
"Y",
"Z"
],
"expired": [
"true",
"false",
"true"
]
}
</code></pre>
<p>I want to use the <code>"mapTrue"</code> value in order to filter the <code>"code"</code> array.</p>
<p>If <code>"mapTrue": "true"</code>, I'll take the <code>0</code> and <code>2</code> values in "expired" array, therefore I need to output</p>
<pre class="lang-json prettyprint-override"><code>"code": ["X", "Z"].
</code></pre>
<p>Using the same logic, for <code>"mapTrue: "false"</code> I'll return <code>"code": ["Y"]</code>.</p>
<p>This specification returns the right <code>"code"</code> array but it doesn't use the <code>"mapTrue"</code> value.</p>
<pre class="lang-json prettyprint-override"><code>
[
{
"operation": "shift",
"spec": {
"expired": {
"*": {
"true": {
"@(3,code[&1])": "code"
}
}
}
}
}
]
</code></pre>
<p>That's where my problem is.</p>
| [
{
"answer_id": 74196096,
"author": "Eusebius",
"author_id": 7217030,
"author_profile": "https://Stackoverflow.com/users/7217030",
"pm_score": 1,
"selected": false,
"text": "[\n {\n \"operation\": \"shift\",\n \"spec\": {\n \"expired\": \"@(1,mapTrue)\",\n \"code\": \"cod... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7217030/"
] |
74,195,098 | <pre class="lang-c prettyprint-override"><code>#include <stdio.h>
int add(int a, int b)
{
if (a > b)
return a * b;
}
int main(void)
{
printf("%d", add(3, 7));
return 0;
}
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>3
</code></pre>
<p>In the above code, I am calling the function inside the print. In the function, the <code>if</code> condition is not true, so it won't execute. Then why I am getting 3 as output? I tried changing the first parameter to some other value, but it's printing the same when the <code>if</code> condition is not satisfied.</p>
| [
{
"answer_id": 74195234,
"author": "Jabberwocky",
"author_id": 898348,
"author_profile": "https://Stackoverflow.com/users/898348",
"pm_score": 2,
"selected": false,
"text": "(a <= b)"
},
{
"answer_id": 74195638,
"author": "Silvio Mayolo",
"author_id": 2288659,
"author... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19768178/"
] |
74,195,104 | <p>I'm facing some errors in my Maven project. My project structure is shown in the following image.
<img src="https://i.stack.imgur.com/H9J8C.png" alt=""project structure"" /></p>
<p>I define the class ProjectInfosDAO in the package <code>main.resources.utils</code> and the others are in <code>main.java.io.r2devops.jobSelector</code>.
<code>ProjectInfos</code> class is called in <code>JobSelector</code> class.
When I compile the project the following error is displayed:</p>
<pre><code>cannot find symbol
symbol: variable ProjectDAO
location: class io.r2devops.jobSelector.JobSelector
</code></pre>
<p>Also the similar error occurs for the dependency Gson despite I mentionned it in <code>pom.xml</code> and imported it in <code>ProjectInfosDAO</code>.</p>
<pre><code>cannot find symbol
symbol: variable Gson
location: class main.resources.utils.ProjectInfosDAO
</code></pre>
<p>In <code>JobSelector</code> class:</p>
<pre><code> import main.resources.ProjectInfosDAO;
public class JobSelector{
public static final void main(String[] args){
...
HashMap<String, TechnoInfos> technoInfos = ProjectInfosDAO.getTechnologiesInfos("technologies_infos.json");
...
}
}
</code></pre>
<p>In the <code>pom.xml</code>:</p>
<pre><code>...
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-bom</artifactId>
<type>pom</type>
<version>${drools-version}</version>
<scope>import</scope>
</dependency>
<!-- Gson: Java to JSON conversion -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10</version>
<scope>compile</scope>
</dependency>
</dependencies>
</dependencyManagement>
...
</code></pre>
<p>Thanks in advance for your kindly help.</p>
| [
{
"answer_id": 74195372,
"author": "Roddy of the Frozen Peas",
"author_id": 419705,
"author_profile": "https://Stackoverflow.com/users/419705",
"pm_score": 2,
"selected": false,
"text": "src/main/resources"
},
{
"answer_id": 74205573,
"author": "Esteban Aliverti",
"author... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11386831/"
] |
74,195,107 | <p>I want to update a list of type <code>SongModel</code> when I enter a value in the <code>TextField</code>. However, the list is not updating when <code>onChanged</code> is called.</p>
<pre class="lang-dart prettyprint-override"><code>List<SongModel> songs = item.data!;
List<SongModel> filterSongs = [];
//showing the songs
return Column(
mainAxisSize: MainAxisSize.max,
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: TextField(
keyboardType: TextInputType.text,
controller: searchController,
onChanged: (value) {
//pass value for the search
getSearch(filterSongs,songs);
},
decoration: InputDecoration(............
</code></pre>
<p><code>getSearch()</code> :</p>
<pre><code>getSearch(List<SongModel> filterSongs,List<SongModel> songs)
{
var text = searchController.text;
if (text.isEmpty) {
setState(() {
filterSongs = songs;
});
}
print(songs.where((SongModel item) => item.title.toLowerCase().contains(text.toLowerCase())).toList());
print(text);
setState(() {
// search = text;
filterSongs = songs.where((SongModel item) => item.title.toLowerCase().contains(text.toLowerCase())).toList();
});
print(filterSongs.length);
}
</code></pre>
<p>Here the list is not updating with set state method.</p>
| [
{
"answer_id": 74195222,
"author": "Nijat Namazzade",
"author_id": 16788073,
"author_profile": "https://Stackoverflow.com/users/16788073",
"pm_score": 0,
"selected": false,
"text": " final TextEditingController _controller = TextEditingController();\n\n \n@override\n void initState() {\... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20164446/"
] |
74,195,128 | <p>Is there any WindowsFormApp listener method that automatically monitors events from child elements?
Clicking a button, opening a list, etc... without each one having its own method?</p>
<p>I'm trying to automate the event process bound to WindowsFormApp components. Example:
There are 10 buttons and I want a single method to monitor the actions of those 10 buttons or any other contained element. I already tried the manual method said at <a href="https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-add-an-event-handler?view=netdesktop-6.0#set-the-handler" rel="nofollow noreferrer">Set the handler</a>. I want to know if there is an automated way, that is, some method of WindowsFormApp that is able to identify these events.</p>
<p>I await reply..</p>
<p>Thank you!</p>
| [
{
"answer_id": 74195304,
"author": "Marsd3q",
"author_id": 11409835,
"author_profile": "https://Stackoverflow.com/users/11409835",
"pm_score": -1,
"selected": true,
"text": "Panel p = new();\nButton a = new();\nButton b = new();\n\np.Controls.Add(a);\np.Controls.Add(b);\nforeach (Button ... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15237556/"
] |
74,195,177 | <p>I have a number of card divs that represent comments and when the user clicked the delete button on the comment I module pops up asking the user if they are sure they want to delete the comment. I would like the correct comment to be deleted based on which delete button they have clicked.</p>
<p><a href="https://i.stack.imgur.com/4vIP9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4vIP9.png" alt="comments" /></a></p>
<p><a href="https://i.stack.imgur.com/GesXu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GesXu.png" alt="module" /></a></p>
<p>Here is my card and module code</p>
<pre class="lang-html prettyprint-override"><code>
<div class="card cardReply">
<div class="row">
<div class="col-3">
<img class="youIcon" src="./images/avatars/image-juliusomo.png">
</div>
<div class="col-3">
<h1 class="cardName">juliusomo</h1>
</div>
<div class="col-2 youText">
<h2 class="you">you</h2>
</div>
<div class="col">
<h2 class="cardDate">2 days ago</h2>
</div>
</div>
<p class="cardComment"><span>@ramsesmiron</span> I couldn't agree more with this. Everything moves so fast and it always seems like everyone knows the newest library/framework. But the fundamentals are what stay constant.</p>
<div class="row">
<div class="col-3 stars">
<img class="stars_plus" src="images/icon-plus.svg" alt="">
<span class="stars_number">2</span>
<img class="stars_minus" src="images/icon-minus.svg" alt="">
</div>
<div class="col reply d-flex justify-content-end">
<img class="details_delete_reply" src="images/icon-delete.svg" alt="">
<button class="details_delete_reply_text" data-bs-toggle="modal" data-bs-target="#exampleModal">Delete</button>
<img class="details_edit_reply" src="images/icon-edit.svg" alt="">
<span class="details_edit_reply_text">Edit</span>
</div>
</div>
</div>
</code></pre>
<pre class="lang-html prettyprint-override"><code><div class="card">
<div class="row">
<div class="col-3">
<img class="youIcon" src="./images/avatars/image-amyrobson.png">
</div>
<div class="col-5">
<h1 class="cardNameText">amyrobson</h1>
</div>
<div class="col">
<h2 class="cardDate">1 month ago</h2>
</div>
</div>
<p class="cardComment">Impressive! Though it seems the drag feature could be improved. But overall it looks incredible. You've nailed the design and the responsiveness at various breakpoints works really well.</p>
<div class="row">
<div class="col-3 stars">
<img class="stars_plus" src="images/icon-plus.svg" alt="+">
<span class="stars_number">12</span>
<img class="stars_minus" src="images/icon-minus.svg" alt="-">
</div>
<div class="col reply d-flex justify-content-end">
<img class="details_edit_reply" src="images/icon-reply.svg" alt="">
<span class="details_edit_reply_text">Reply</span>
</div>
</div>
</div>
<div class="card">
<div class="row">
<div class="col-3">
<img class="youIcon" src="./images/avatars/image-maxblagun.png">
</div>
<div class="col-5">
<h1 class="cardNameText">maxblagun</h1>
</div>
<div class="col">
<h2 class="cardDate">2 weeks ago</h2>
</div>
</div>
<p class="cardComment">Woah, your project looks awesome! How long have you been coding for? I'm still new, but think I want to dive into React as well soon. Perhaps you can give me an insight on where I can learn React? Thanks!</p>
<div class="row">
<div class="col-3 stars">
<img class="stars_plus" src="images/icon-plus.svg" alt="+">
<span class="stars_number">5</span>
<img class="stars_minus" src="images/icon-minus.svg" alt="-">
</div>
<div class="col reply d-flex justify-content-end">
<img class="details_edit_reply" src="images/icon-reply.svg" alt="">
<span class="details_edit_reply_text">Reply</span>
</div>
</div>
</div>
</code></pre>
<pre class="lang-html prettyprint-override"><code><div class="card">
<div class="row">
<div class="col-3">
<img class="youIcon" src="./images/avatars/image-amyrobson.png">
</div>
<div class="col-5">
<h1 class="cardNameText">amyrobson</h1>
</div>
<div class="col">
<h2 class="cardDate">1 month ago</h2>
</div>
</div>
<p class="cardComment">Impressive! Though it seems the drag feature could be improved. But overall it looks incredible. You've nailed the design and the responsiveness at various breakpoints works really well.</p>
<div class="row">
<div class="col-3 stars">
<img class="stars_plus" src="images/icon-plus.svg" alt="+">
<span class="stars_number">12</span>
<img class="stars_minus" src="images/icon-minus.svg" alt="-">
</div>
<div class="col reply d-flex justify-content-end">
<img class="details_edit_reply" src="images/icon-reply.svg" alt="">
<span class="details_edit_reply_text">Reply</span>
</div>
</div>
</div>
<div class="card">
<div class="row">
<div class="col-3">
<img class="youIcon" src="./images/avatars/image-maxblagun.png">
</div>
<div class="col-5">
<h1 class="cardNameText">maxblagun</h1>
</div>
<div class="col">
<h2 class="cardDate">2 weeks ago</h2>
</div>
</div>
<p class="cardComment">Woah, your project looks awesome! How long have you been coding for? I'm still new, but think I want to dive into React as well soon. Perhaps you can give me an insight on where I can learn React? Thanks!</p>
<div class="row">
<div class="col-3 stars">
<img class="stars_plus" src="images/icon-plus.svg" alt="+">
<span class="stars_number">5</span>
<img class="stars_minus" src="images/icon-minus.svg" alt="-">
</div>
<div class="col reply d-flex justify-content-end">
<img class="details_edit_reply" src="images/icon-reply.svg" alt="">
<span class="details_edit_reply_text">Reply</span>
</div>
</div>
</div>
</code></pre>
<pre class="lang-html prettyprint-override"><code><div class="card cardReply">
<div class="row">
<div class="col-3">
<img class="youIcon" src="./images/avatars/image-juliusomo.png">
</div>
<div class="col-3">
<h1 class="cardName">juliusomo</h1>
</div>
<div class="col-2 youText">
<h2 class="you">you</h2>
</div>
<div class="col">
<h2 class="cardDate">a few seconds ago</h2>
</div>
</div>
<p class="cardComment">hello</p>
<div class="row">
<div class="col-3 stars">
<img class="stars_plus" src="images/icon-plus.svg" alt="">
<span class="stars_number">0</span>
<img class="stars_minus" src="images/icon-minus.svg" alt="">
</div>
<div class="col reply d-flex justify-content-end">
<img class="details_delete_reply" src="images/icon-delete.svg" alt="">
<button class="details_delete_reply_text" data-bs-toggle="modal" data-bs-target="#exampleModal">Delete</button>
<img class="details_edit_reply" src="images/icon-edit.svg" alt="">
<span class="details_edit_reply_text">Edit</span>
</div>
</div>
</div>
</code></pre>
<pre class="lang-html prettyprint-override"><code> <div class="card cardReply">
<div class="row">
<div class="col-3">
<img class="youIcon" src="./images/avatars/image-juliusomo.png">
</div>
<div class="col-3">
<h1 class="cardName">juliusomo</h1>
</div>
<div class="col-2 youText">
<h2 class="you">you</h2>
</div>
<div class="col">
<h2 class="cardDate">a few seconds ago</h2>
</div>
</div>
<p class="cardComment">hello</p>
<div class="row">
<div class="col-3 stars">
<img class="stars_plus" src="images/icon-plus.svg" alt="">
<span class="stars_number">0</span>
<img class="stars_minus" src="images/icon-minus.svg" alt="">
</div>
<div class="col reply d-flex justify-content-end">
<img class="details_delete_reply" src="images/icon-delete.svg" alt="">
<button class="details_delete_reply_text" data-bs-toggle="modal" data-bs-target="#exampleModal">Delete</button>
<img class="details_edit_reply" src="images/icon-edit.svg" alt="">
<span class="details_edit_reply_text">Edit</span>
</div>
</div>
</div>
</code></pre>
<pre class="lang-html prettyprint-override"><code>
<div class="modal fade show" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" style="display: block; padding-left: 0px;" aria-modal="true" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Delete comment</h5>
</div>
<div class="modal-body">
<p class="modal-text">Are you sure you want to delete this comment? This will remove the comment and can't be undone</p>
<div class="row">
<div class="col">
<button type="button" class="btn btn-primary btn-no text-center text-uppercase" data-bs-dismiss="modal" aria-label="Close">No, Cancel</button>
</div>
<div class="col">
<button type="button" class="btn btn-primary btn-delete text-center text-uppercase" data-bs-dismiss="modal" aria-label="Close" onclick="handleDeleteClick()">Yes, Delete</button>
</div>
</div>
</div>
</div>
</div>
</div>
</code></pre>
<p>Here is the JavaScript that I have tried</p>
<pre class="lang-js prettyprint-override"><code>const handleDeleteClick = () = \ > {
const deleteCooment = document.querySelector('.btn-delete')
const deleteButton = document.querySelector('.details_delete_reply_text');
deleteCooment.onclick = () = \ > {
// deleteCooment.target.closest('.card').parentNode.removeChild(deleteCooment.target.closest('.message'));
console.log("hello");
deleteButton.forEach(el => {
el.addEventListener('click', (e) => {
e.target.closest('.card').parentNode.removeChild(deleteCooment.target.closest('.message'));
});
});
}
}
</code></pre>
| [
{
"answer_id": 74195696,
"author": "Vayne Valerius",
"author_id": 11888674,
"author_profile": "https://Stackoverflow.com/users/11888674",
"pm_score": -1,
"selected": false,
"text": "const cardData = [{dataSet1}, {dataSet2}, ...]\n\nconst delete = (index) => {\n //Method to delete from c... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12339109/"
] |
74,195,207 | <p>remove % and keep testing using jQuery</p>
<pre><code><div id="top_content">testing %</div> == 0$
</code></pre>
<p>I've tried to use this code but it didn't work</p>
<pre><code>$('.top_content:contains("%: ")').each(function(){
$(this).html($(this).html().split("%: ").join(""));
});
</code></pre>
<p>top content is an element inside wordpress plugin</p>
<p>thanks for help</p>
| [
{
"answer_id": 74195378,
"author": "mscdeveloper",
"author_id": 8656248,
"author_profile": "https://Stackoverflow.com/users/8656248",
"pm_score": 2,
"selected": false,
"text": "$('#top_content').(...);"
},
{
"answer_id": 74195404,
"author": "David Thomas",
"author_id": 82... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20310929/"
] |
74,195,214 | <p>I want to be able to write code like this:</p>
<pre><code>ExampleStruct {
field1: "value1",
field2: "value2",
nested: ExampleNestedStruct{
field3: "value3",
},
}
</code></pre>
<p>for a struct that looks like this:</p>
<pre><code>struct ExampleStruct{
field1: String,
field2: String,
nested: ExampleNestedStruct
}
</code></pre>
<pre><code>struct ExampleNestedStruct {
field3: String,
}
</code></pre>
<p>but since ExampleStruct has to have fields of type String and not of type &str I'd have to convert every value explicitly with .to_owned() or similar fuctions, which works but isn't optimal.</p>
<p>I thought about creating an identical struct with &str fields and a conversion method utilizing serialization but that seems overcomplicated for such a simple issue, as well as having two essentially idential structs in my code.</p>
<p>Is there any way for me to convert all occuring &str to String implicitly? Or is there some syntax I might not know about? I'm quite new to rust over all.</p>
<p>I tried looking up possible Syntax of creating Strings which all seem to include some kind of explicit function call.</p>
<p>I also discovered some auto conversion syntax (if you can call it that) for function arguments like so: fn fn_name <T: Into<T'>> (s: T) but that won't work because I'm not calling a function with arguments.</p>
<p>Edit: I think I might be able to achieve this by writing a macro. I'll try that when I have time, unless theres someone out there who already created a &str_to_String macro perhaps?</p>
| [
{
"answer_id": 74195543,
"author": "ymochurad",
"author_id": 11196108,
"author_profile": "https://Stackoverflow.com/users/11196108",
"pm_score": 2,
"selected": false,
"text": "struct ExampleStruct {\n field1: String,\n field2: String,\n nested: ExampleNestedStruct,\n}\n\nstruct ... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9852934/"
] |
74,195,218 | <p>I entered date in my google spreadsheet example 25/10/2022, then I want to use fill handle to copy that date in the column but the date automatically increasing , like 26/10/2022, 27/10/2022. and i don't need that.</p>
<p>I was expecting to copy same date in the column</p>
| [
{
"answer_id": 74195329,
"author": "player0",
"author_id": 5632629,
"author_profile": "https://Stackoverflow.com/users/5632629",
"pm_score": 2,
"selected": true,
"text": "=\"25/10/2022\"\n"
}
] | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20330889/"
] |
74,195,244 | <p>I have a list of emails that match a similar pattern as such:</p>
<p>chris-repo-nonprod-red-sens@mail.com</p>
<p>ryan-prod-blue-sens@mail.com</p>
<p>The first email has 5 parts while the second one has 4 parts (marked by the hyphen) before the @mail.com</p>
<p>I need to extract the group_code that comes after the nonprod/prod portion of the group email.</p>
<p>For example for chris-repo-nonprod-red-sens@mail.com i need to extract red,</p>
<p>and for ryan-prod-blue-sens@mail.com i need to extract blue.</p>
<p>The portion before the group code will always be prod or nonprod, further more there will always be the subtring "prod-" before the group code.</p>
<p>How can I go about extracting the group code from emails that have different amount of parts to always get the group code?</p>
| [
{
"answer_id": 74195301,
"author": "Naveed",
"author_id": 3494754,
"author_profile": "https://Stackoverflow.com/users/3494754",
"pm_score": 2,
"selected": true,
"text": "re.findall('(?:prod-)(.*)-', s)\n"
},
{
"answer_id": 74195405,
"author": "Bhargav",
"author_id": 15358... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17928364/"
] |
74,195,246 | <p><a href="https://i.stack.imgur.com/u3PpX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/u3PpX.png" alt="enter image description here" /></a></p>
<p>When use text overflow and button same line, the button have problem</p>
<p>Here are my code</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>a {
float: right;
}
li {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>The ul element</h1>
<ul>
<li><span>Create a list inside a list (a nested list)</span><a href="">x</a></li>
<li><span>Create</span><a href="">x</a></li>
<li><span>Create a list inside a list (a nested list)</span><a href="">x</a></li>
</ul></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74195301,
"author": "Naveed",
"author_id": 3494754,
"author_profile": "https://Stackoverflow.com/users/3494754",
"pm_score": 2,
"selected": true,
"text": "re.findall('(?:prod-)(.*)-', s)\n"
},
{
"answer_id": 74195405,
"author": "Bhargav",
"author_id": 15358... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8888883/"
] |
74,195,253 | <p>I have the following route with a redirect for a child route but the URL path is not updated.</p>
<pre><code>RouterModule.forChild([
{
path: '',
component: MainComponent,
children: [
{ path: '', redirectTo: '/account/data', pathMatch: 'full', },
{
path: "account",
children: [
...AccountPaths,
]
},
]
},
{
path: '**',
redirectTo: '',
pathMatch: 'full'
}
])
</code></pre>
<p>As you can see I redirect the default path <strong>''</strong> to child route <strong>/account/data</strong></p>
<p>The proper view is loaded but the <strong>/account/data</strong> is missing in the url</p>
<pre><code>http://localhost:4200
</code></pre>
<p>instead (what I expect)</p>
<pre><code>http://localhost:4200/account/data
</code></pre>
<p>My question is WHY?</p>
| [
{
"answer_id": 74195301,
"author": "Naveed",
"author_id": 3494754,
"author_profile": "https://Stackoverflow.com/users/3494754",
"pm_score": 2,
"selected": true,
"text": "re.findall('(?:prod-)(.*)-', s)\n"
},
{
"answer_id": 74195405,
"author": "Bhargav",
"author_id": 15358... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1841289/"
] |
74,195,280 | <p>I tried this.$forceupdate() , v-if hack but it didn't work. I am new to Vue.</p>
<pre><code>
<template>
<div class="intro-y grid grid-cols-12 gap-3 sm:gap-6 mt-5">
<HeroCard v-for="hero in heroes" :key="hero.id" :hero="hero" />
</div>
</template>
</code></pre>
<pre><code><script>
import HeroCard from "@/components/hero/HeroCard.vue";
export default {
inject: ["heroStats"],
name: "HeroList",
components: {
HeroCard,
},
data() {
return {
heroes: this.heroStats,
};
},
methods: {
filterHeroes(heroStats, primary_attribute, attack_type, roles, name) {
if (!primary_attribute.length) {
this.heroes = heroStats;
} else {
this.heroes = heroStats.filter((hero) =>
primary_attribute.includes(hero.primary_attr)
);
...etc
}
},
},
};
</script>
</code></pre>
<p><a href="https://i.stack.imgur.com/RbOKw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RbOKw.png" alt="enter image description here" /></a></p>
<p>When Checkboxes are checked the HeroCard component should display heroes that including the primary attributes[ 'Strength', 'Intelligence' ]</p>
| [
{
"answer_id": 74195301,
"author": "Naveed",
"author_id": 3494754,
"author_profile": "https://Stackoverflow.com/users/3494754",
"pm_score": 2,
"selected": true,
"text": "re.findall('(?:prod-)(.*)-', s)\n"
},
{
"answer_id": 74195405,
"author": "Bhargav",
"author_id": 15358... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15497970/"
] |
74,195,282 | <p>Since I am not experinced Go developer, I didn't understand way of working with Ticker. I have following scenario:</p>
<p>A go web service running on specific port 8080, it is getting data from another applications and processing the data. So far so good, but I have a another <code>sendData</code> function in this web service which loop through the some files and send them to another extern service. I am trying to call the <code>sendData()</code> function every 1 minute. Here is how main function looks without Tickers:</p>
<pre><code>func main() {
http.HandleFunc("/data", headers) //line 1
log.Printf("Ready for data ...%s\n", 8080) //line 2
http.ListenAndServe(":8080", nil) //line 3
}
</code></pre>
<p>If I add the Ticker after <code>line 2</code> it's keeping loop infinitively.
If I add after <code>line 3</code>, the programm is not invoking the Ticker.
Any idea how to handle this?</p>
<p>The Ticker part</p>
<pre><code>ticker := schedule(sendData, time.Second, done)
time.Sleep(60 * time.Second)
close(done)
ticker.Stop()
</code></pre>
<p>and the <a href="https://go.dev/play/p/HogqmrdYDSk" rel="nofollow noreferrer">schedule from</a></p>
<pre><code>func schedule(f func(), interval time.Duration, done <-chan bool) *time.Ticker {
ticker := time.NewTicker(interval)
go func() {
for {
select {
case <-ticker.C:
f()
case <-done:
return
}
}
}()
return ticker
</code></pre>
<p>So basically I want to sendData evert minute or hour etc. Could someone explain how internally Ticker works?</p>
| [
{
"answer_id": 74195481,
"author": "Stephen Dunne",
"author_id": 3301685,
"author_profile": "https://Stackoverflow.com/users/3301685",
"pm_score": -1,
"selected": false,
"text": "ListenAndServe"
},
{
"answer_id": 74197659,
"author": "GGP",
"author_id": 12574067,
"auth... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16808133/"
] |
74,195,295 | <p>I want to add a feature to my while loop if they want to try again but I don't know where to put the code. If the user enters <kbd>N</kbd>, the code shall stop and if he enters <kbd>Y</kbd>, it shall re-ask for the start, end and step.</p>
<pre class="lang-java prettyprint-override"><code>import java.util.Scanner;
public class Sum3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int start, end, step;
char option;
System.out.print("Enter START value: ");
start = input.nextInt();
System.out.print("Enter END value: ");
end = input.nextInt();
System.out.print("Enter STEP value: ");
step = input.nextInt();
while (start > end)
System.out.println("Start is larger than End");
while (step == 0)
System.out.println("Step is larger than the zero");
while (true)
for (int i = start; i < end; i += step)
System.out.println(i);
/*System.out.println("Would you still want to continue? (Y/ N)");
option = input.next().charAt(0);*/
}
}
</code></pre>
| [
{
"answer_id": 74195739,
"author": "Jayant Verma",
"author_id": 20330766,
"author_profile": "https://Stackoverflow.com/users/20330766",
"pm_score": 1,
"selected": false,
"text": "for (int i = start; i < end; i = i + step)\n{\n System.out.println(i);\n System.out.println(\"Retry (... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20137415/"
] |
74,195,296 | <p>Is there a way to nest types and interfaces for better organization?</p>
<p>eg. <code>let myshark: Animals.Fish.Shark</code></p>
<p>To allow referring the nested <code>Shark</code> interface, what kind of implementation structure of the interfaces work?</p>
<p>One attempt could be =></p>
<pre><code>interface Animals{
interface Mamals{
interface Bat {
kind:string;
wings:number;
}
}
interface Fish {
interface Shark {
variant:string;
color:string;
fins:number;
}
}
}
</code></pre>
<p>To then use them as follows</p>
<pre><code>let greatwhite: Animals.Fish.Shark;
let mybat: Animals.Mamals.Bat;
</code></pre>
<p>I have also tried using classes and namespaces? Is there a proper way to do this or is it not possible to get type declarations such as <code>let myshark: Animals.Fish.Shark</code>?</p>
| [
{
"answer_id": 74195647,
"author": "Harrison",
"author_id": 15291770,
"author_profile": "https://Stackoverflow.com/users/15291770",
"pm_score": 0,
"selected": false,
"text": "namespace"
},
{
"answer_id": 74197026,
"author": "jcalz",
"author_id": 2887218,
"author_profi... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74195296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14487032/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.