qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,242,176 | <p>just want your insight on what I can do since I'm lost for 2 days now. What I'm trying to do is to move a file from 1 folder to 5 folders 1 at a time. here's what I got so far.</p>
<pre><code>import os
import shutil
#path
source = 'C:/Users/folder/Downloads/Files/test'
destination = ['C:/Users/folder/Downloads/Files/test1',
'C:/Users/folder/Downloads/Files/test2',
'C:/Users/folder/Downloads/Files/test3',
'C:/Users/folder/Downloads/Files/tes',
'C:/Users/folder/Downloads/Files/test5']
def countItems():
global totalfiles
global copiedfiles
totalfiles = 0
copiedfiles = 1
for item in os.listdir(source):
totalfiles += 1
#get total items
countItems()
#get Destination
while(totalfiles != 0):
for dst in destination:
for items in os.listdir(source):
s = os.path.join(source, items)
d = os.path.join(dst, items)
if os.path.isfile(d):
checker = 'Copy of'
filename, filext = os.path.splitext(items)
finalF = checker + filename + filext
newd = os.path.join(dst, finalF)
os.rename(s, newd)
countItems()
else:
shutil.move(s, d)
countItems()
</code></pre>
<p>I'm trying to distribute all of the files evenly throughout the 5 destination folder.</p>
| [
{
"answer_id": 74242282,
"author": "ahmed",
"author_id": 12705912,
"author_profile": "https://Stackoverflow.com/users/12705912",
"pm_score": 2,
"selected": true,
"text": "SELECT T.Customer, T.Transactionid, T.TransactionDate\nFROM Table2 T\nJOIN\n(\n SELECT Customer, MAX(TransactionDate... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18457728/"
] |
74,242,183 | <p><strong>My goal</strong>: is to set a rate limit of 600 requests per minute, which is reset at the next minute. My intend was to do this via the <code>http.client</code> setting a <code>RoundTrip</code> with a <code>limit.wait()</code>. So that I can set different limits for different <code>http.clients()</code> and have the limiting handled via <code>roundtrip</code> rather than adding complexity to my code elsewhere.</p>
<p>The issue is that the rate limit is not honoured, I still exceed the number of requests allowed and setting a timeout produces a fatal panic <code>net/http: request canceled (Client.Timeout exceeded while awaiting headers)</code></p>
<p>I have created a barebones <code>main.go</code> that replicates the issue. Note that the 64000 loop is a realistic scenario for me.</p>
<p><strong>Update</strong>: setting <code>ratelimiter: rate.NewLimiter(10, 10),</code> still exceeds the 600 rate limit somehow and produces errors <code>Context deadline exceeded</code> with the set timeout.</p>
<pre><code>package main
import (
"fmt"
"io/ioutil"
"net/http"
"sync"
"time"
"golang.org/x/time/rate"
)
var client http.Client
// ThrottledTransport Rate Limited HTTP Client
type ThrottledTransport struct {
roundTripperWrap http.RoundTripper
ratelimiter *rate.Limiter
}
func (c *ThrottledTransport) RoundTrip(r *http.Request) (*http.Response, error) {
err := c.ratelimiter.Wait(r.Context()) // This is a blocking call. Honors the rate limit
if err != nil {
return nil, err
}
return c.roundTripperWrap.RoundTrip(r)
}
// NewRateLimitedTransport wraps transportWrap with a rate limitter
func NewRateLimitedTransport(transportWrap http.RoundTripper) http.RoundTripper {
return &ThrottledTransport{
roundTripperWrap: transportWrap,
//ratelimiter: rate.NewLimiter(rate.Every(limitPeriod), requestCount),
ratelimiter: rate.NewLimiter(10, 10),
}
}
func main() {
concurrency := 20
var ch = make(chan int, concurrency)
var wg sync.WaitGroup
wg.Add(concurrency)
for i := 0; i < concurrency; i++ {
go func() {
for {
a, ok := <-ch
if !ok { // if there is nothing to do and the channel has been closed then end the goroutine
wg.Done()
return
}
resp, err := client.Get("https://api.guildwars2.com/v2/items/12452")
if err != nil {
fmt.Println(err)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println(err)
}
fmt.Println(a, ":", string(body[4:29]))
}
}()
}
client = http.Client{}
client.Timeout = time.Second * 10
// Rate limits 600 requests per 60 seconds via RoundTripper
transport := NewRateLimitedTransport(http.DefaultTransport)
client.Transport = transport
for i := 0; i < 64000; i++ {
ch <- i // add i to the queue
}
wg.Wait()
fmt.Println("done")
}
</code></pre>
| [
{
"answer_id": 74242334,
"author": "Zeke Lu",
"author_id": 1369400,
"author_profile": "https://Stackoverflow.com/users/1369400",
"pm_score": 2,
"selected": false,
"text": "rate.NewLimiter(rate.Every(60*time.Second), 600)"
},
{
"answer_id": 74295325,
"author": "LeGEC",
"au... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2936329/"
] |
74,242,187 | <p>I have strings in the below pattern:</p>
<pre><code>ab:ab:ab:1:ab
ac:ac:ac:2:ac
ad:ad:ad:3:ad
</code></pre>
<p>I have to extract the string between the <code>3rd colon</code> and the <code>4th colon</code>.</p>
<p>For the above example strings, the results would be <code>"1"</code>, <code>"2"</code> and <code>"3"</code>.</p>
<p>What is a short way in Java using string functions to extract it?</p>
| [
{
"answer_id": 74242285,
"author": "Teddy Tsai",
"author_id": 16959486,
"author_profile": "https://Stackoverflow.com/users/16959486",
"pm_score": 3,
"selected": true,
"text": "Stream.of(\"ab:ab:ab:1:ab\", \"ac:ac:ac:2:ac\", \"ad:ad:ad:3:ad\")\n .map(s -> s.split(\":\")[3])\n .f... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5414637/"
] |
74,242,190 | <p>I have a CSV with a structure as:</p>
<p>Test CSV:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Column A</th>
<th>Column B</th>
</tr>
</thead>
<tbody>
<tr>
<td>abc-dfcv</td>
<td>rebtgsergbsedrfgesrg</td>
</tr>
<tr>
<td></td>
<td>water rdfe egreg</td>
</tr>
<tr>
<td></td>
<td>oluiuilegregreg</td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td>def fefd</td>
<td>rtjtyujdtgfhndgfhjfh</td>
</tr>
<tr>
<td></td>
<td>water edgregerg</td>
</tr>
</tbody>
</table>
</div>
<p>Result needed:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Column A</th>
<th>Column B</th>
</tr>
</thead>
<tbody>
<tr>
<td>abc-dfcv</td>
<td>water rdfe egreg</td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td>def fefd</td>
<td>water edgregerg</td>
</tr>
</tbody>
</table>
</div>
<p>As can be seen, in each cell of column B there are multiple lines. I need to edit it so only the lines which start with "water" are kept within the cell, rest of the lines are omitted. This has to be done for all cells in Column B.</p>
<p>The regex statement I've made is <code>re.findall("^water'.*")</code>.</p>
<p>I tried to directly apply regex, but it halts and errors at the end of a line within a cell.</p>
<p>Thinking of something along these lines, but blanking on what the regex input should be.</p>
<pre><code>df = pd.read_csv("MyFile.csv")
for p in range(len(df.index)):
df._set_value(p, "SCHEDULES", str(re.findall("^water'.*", ??????????????? )))
df.to_csv("Nexpose_Schedules.csv", index=False)
</code></pre>
| [
{
"answer_id": 74242285,
"author": "Teddy Tsai",
"author_id": 16959486,
"author_profile": "https://Stackoverflow.com/users/16959486",
"pm_score": 3,
"selected": true,
"text": "Stream.of(\"ab:ab:ab:1:ab\", \"ac:ac:ac:2:ac\", \"ad:ad:ad:3:ad\")\n .map(s -> s.split(\":\")[3])\n .f... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20362584/"
] |
74,242,193 | <p>on a web page I'm working on, I got an input area that I'd like to show a hidden CSS element (a DIV) when the input value is set to be greater than 1.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" class="NetscapeFix CalTicketQuantity form-control" name="tix_quantity" id="tix_quantity_1842" value="0" size="4" maxlength="4" onchange="calculate(this.form);"></code></pre>
</div>
</div>
</p>
<p>above is the code snippet of the input field, also please see image attached to see how the input looks on the page. <a href="https://i.stack.imgur.com/Rvkcw.jpg" rel="nofollow noreferrer">Webpage Screenshot</a></p>
<p>So, if you see the <strong>image above</strong>, what I'm trying to achieve is to show a div HIDDEN with CSS when "<strong>Number of Individual Ticket Tickets:</strong>" input is changed to be <strong>greater than one</strong>.</p>
| [
{
"answer_id": 74242285,
"author": "Teddy Tsai",
"author_id": 16959486,
"author_profile": "https://Stackoverflow.com/users/16959486",
"pm_score": 3,
"selected": true,
"text": "Stream.of(\"ab:ab:ab:1:ab\", \"ac:ac:ac:2:ac\", \"ad:ad:ad:3:ad\")\n .map(s -> s.split(\":\")[3])\n .f... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15166105/"
] |
74,242,267 | <pre class="lang-py prettyprint-override"><code>[('key1', ['word1', 'word1', 'word2', ...]),
('key2', ['word1', 'word2', 'word2', ...]),
...
]
</code></pre>
<p>I want to remove duplicate in the list and assign them to the key.</p>
<p>First step output: removing duplicate in list</p>
<pre class="lang-py prettyprint-override"><code>[('key1', ['word1', 'word2', ...]),
('key2', ['word1', 'word2', ...]),
...
]
</code></pre>
<p>second step output</p>
<pre class="lang-py prettyprint-override"><code>[('key1', ('word1', '1'))
('key1', ('word2', '1')),
...
('key2', ('word1', '1')),
('key2', ('word2', '1')),
...
]
</code></pre>
<p>Here's my try which does not work.</p>
<pre class="lang-py prettyprint-override"><code>rdd.map(lambda x: (x[0], (x[1], 1])).collect()
</code></pre>
<p>Output:</p>
<pre class="lang-py prettyprint-override"><code>[('key1', (['word1', 'word1', 'word2', ...], 1)),
('key2', (['word1', 'word2', 'word2', ...], 1)),
...
]
</code></pre>
| [
{
"answer_id": 74242285,
"author": "Teddy Tsai",
"author_id": 16959486,
"author_profile": "https://Stackoverflow.com/users/16959486",
"pm_score": 3,
"selected": true,
"text": "Stream.of(\"ab:ab:ab:1:ab\", \"ac:ac:ac:2:ac\", \"ad:ad:ad:3:ad\")\n .map(s -> s.split(\":\")[3])\n .f... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20362677/"
] |
74,242,291 | <p>I want to match this text:</p>
<pre><code>&lt;SERIES&gt;
&lt;OWNER-CIK&gt;0000003521
&lt;SERIES-ID&gt;S000020958
&lt;SERIES-NAME&gt;Alger Small Cap Focus Fund
&lt;CLASS-CONTRACT&gt;
&lt;CLASS-CONTRACT-ID&gt;C000059340
&lt;CLASS-CONTRACT-NAME&gt;Alger Small Cap Focus Fund Class I
&lt;CLASS-CONTRACT-TICKER-SYMBOL&gt;AOFIX
&lt;/CLASS-CONTRACT&gt;
&lt;CLASS-CONTRACT&gt;
&lt;CLASS-CONTRACT-ID&gt;C000095961
&lt;CLASS-CONTRACT-NAME&gt;Alger Small Cap Focus Fund Class Z
&lt;CLASS-CONTRACT-TICKER-SYMBOL&gt;AGOZX
&lt;/CLASS-CONTRACT&gt;
&lt;CLASS-CONTRACT&gt;
&lt;CLASS-CONTRACT-ID&gt;C000179520
&lt;CLASS-CONTRACT-NAME&gt;Class Y
&lt;CLASS-CONTRACT-TICKER-SYMBOL&gt;AOFYX
&lt;/CLASS-CONTRACT&gt;
&lt;/SERIES&gt;
&lt;SERIES&gt;
</code></pre>
<p>From:</p>
<pre><code>&lt;SERIES&gt;
</code></pre>
<p>Untill</p>
<pre><code>&lt;/SERIES&gt;
</code></pre>
<p>I'm trying with:</p>
<pre><code>&lt;SERIES&gt;[^/]+
</code></pre>
<p>but it fails at the line with:</p>
<pre><code>&lt;/CLASS-CONTRACT&gt;
</code></pre>
<p><a href="https://i.stack.imgur.com/5nrOm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5nrOm.png" alt="enter image description here" /></a></p>
<p>If I add the S to the regex in finish even earlier since it ends with any of the character / or S appears. I need that both apear /S in that specific order</p>
<p><a href="https://i.stack.imgur.com/lDuMn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lDuMn.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74242285,
"author": "Teddy Tsai",
"author_id": 16959486,
"author_profile": "https://Stackoverflow.com/users/16959486",
"pm_score": 3,
"selected": true,
"text": "Stream.of(\"ab:ab:ab:1:ab\", \"ac:ac:ac:2:ac\", \"ad:ad:ad:3:ad\")\n .map(s -> s.split(\":\")[3])\n .f... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4544413/"
] |
74,242,296 | <p>I am trying to write a program to query multiple DNS servers for the IP address of a hostname. My only problem is that I can't get the actual IP address, only the server's response.</p>
<p>This is my code:</p>
<pre><code>import dns.resolver
my_resolver = dns.resolver.Resolver()
reply_list = []
dns_list = ['8.8.8.8', '8.8.4.4', '1.2.3.4']
resp = []
for server in dns_list:
try:
my_resolver.nameservers = [server]
answer = my_resolver.resolve('google.com')
print(answer.response)
except dns.resolver.LifetimeTimeout:
print('Error')
</code></pre>
<p>I don't understand how I can use the output.
I had hoped for a list, a dict or a tuple as a response.</p>
<p>But I get this on the console:</p>
<pre><code>id 54769
opcode QUERY
rcode NOERROR
flags QR RD RA
;QUESTION
google.com. IN A
;ANSWER
google.com. 233 IN A 172.217.16.206
;AUTHORITY
;ADDITIONAL
id 39642
opcode QUERY
rcode NOERROR
flags QR RD RA
;QUESTION
google.com. IN A
;ANSWER
google.com. 300 IN A 172.217.18.14
;AUTHORITY
;ADDITIONAL
Error
Process finished with exit code 0`
</code></pre>
<p>Thanks for your help! :)</p>
| [
{
"answer_id": 74242285,
"author": "Teddy Tsai",
"author_id": 16959486,
"author_profile": "https://Stackoverflow.com/users/16959486",
"pm_score": 3,
"selected": true,
"text": "Stream.of(\"ab:ab:ab:1:ab\", \"ac:ac:ac:2:ac\", \"ad:ad:ad:3:ad\")\n .map(s -> s.split(\":\")[3])\n .f... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8978772/"
] |
74,242,299 | <p>I have setup a backend and frontend service running on Kubernetes. Frontend would be <code>www.<myDomain>.com</code> and backend would be <code>api.<myDomain>.com</code></p>
<p>I need to expose and secure both services. I wish to use one ingress. I want to use free certificates from let's encrypt + cert manager. I guess a certificate for <code><myDomain>.com</code> should cover both <code>www.</code> and <code>api.</code>.</p>
<p>Pretty normal use case, right? But when these normal stuff comes together, I couldn't figure out the combined yaml. I was able to get single service, the <code>www.<myDomain>.com</code> working with https. Things doesn't work when I tried to add the <code>api.<myDomain>.com</code></p>
<p>I'm using GKE, but this doesn't seem to be a platform related question. Now creating ingress takes forever. This following events has been tried again and again</p>
<pre><code>Error syncing to GCP: error running load balancer syncing routine: loadbalancer <some id here> does not exist: googleapi: Error 404: The resource 'projects/<project>/global/sslCertificates/<some id here>' was not found, notFound
</code></pre>
<pre><code>apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: web-ingress
annotations:
kubernetes.io/ingress.class: gce
kubernetes.io/ingress.allow-http: "true"
cert-manager.io/issuer: letsencrypt-staging
spec:
tls:
- secretName: web-ssl
hosts:
- <myDomain>.com
rules:
- host: "www.<myDomain>.com"
http:
paths:
- pathType: Prefix
path: "/"
backend:
service:
name: angular-service
port:
number: 80
- host: "api.<myDomain>.com"
http:
paths:
- pathType: Prefix
path: "/"
backend:
service:
name: spring-boot-service
port:
number: 8080
</code></pre>
| [
{
"answer_id": 74242285,
"author": "Teddy Tsai",
"author_id": 16959486,
"author_profile": "https://Stackoverflow.com/users/16959486",
"pm_score": 3,
"selected": true,
"text": "Stream.of(\"ab:ab:ab:1:ab\", \"ac:ac:ac:2:ac\", \"ad:ad:ad:3:ad\")\n .map(s -> s.split(\":\")[3])\n .f... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16809133/"
] |
74,242,325 | <p>Ok, I'll try to explain this as cleanly as I can.</p>
<p>I've created a generic abstract controller class that has a method <code>hasCreatePermissions</code> that looks something like this:</p>
<pre><code>public abstract class ApplicationController<
AppEntity extends ApplicationEntity,
AppService extends ApplicationService<AppEntity>,
DTOManager extends ApplicationDTOManager
> {
// Other methods, properties, etc...
public boolean hasCreatePermissions(DTOManager.CreationRequest requestBody, Optional<UUID> requestingUser) {
return false;
}
}
</code></pre>
<p>Essentially, I want any class that overrides this method to be able to use its own DTOManager class as the parameter when it overrides this method.</p>
<p>The generic ApplicationDTOManager class looks like</p>
<pre><code>public abstract class ApplicationDTOManager {
public abstract class CreationRequest {}
public abstract class CreationResponse {}
}
</code></pre>
<p>and any class that inherits ApplicationDTOManager can add classes that extend CreationRequest and CreationResponse for their own implementation of respective DTOs.</p>
<p>However, lets say I try to extend it with a UserResource class (assume UserDTOManager exists with an implementation for CreationRequest):</p>
<pre><code>@RestController
public class UserResource extends ApplicationController<
User,
UserService<User>,
UserDTOManager
> {
@Override
public boolean hasCreatePermissions(UserDTOManager.CreationRequest requestBody, Optional<UUID> requestingUser) {
// Stuff
}
}
</code></pre>
<p>I'm told that this does not override any super class methods. Why? Is there any way to achieve this as I did not want to pass too many generics to my ApplicationController class, but also cannot have a constructor.</p>
| [
{
"answer_id": 74242729,
"author": "rzwitserloot",
"author_id": 768644,
"author_profile": "https://Stackoverflow.com/users/768644",
"pm_score": 2,
"selected": true,
"text": "class ApplicationController<\n AppEntity extends ApplicationEntity,\n"
}
] | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16050570/"
] |
74,242,338 | <p>Given an array fild with 4 bytes inside (R,G,B,A), i'm trying to translate this array full of 4 8bits numbers into its translation in 32bits.To be more clear, if i get an array such as :</p>
<pre><code>byte[] tab = {1,2,3,4};
</code></pre>
<p>with translated in binary in 8bit :</p>
<pre><code>1 = 0b00000001
2 = 0b00000010
3 = 0b00000011
4 = 0b00000100
</code></pre>
<p>Then, my method should return a byte array such as :</p>
<pre><code>newTab = {00000001_00000010_00000011_00000100};
</code></pre>
<p>For some reasons, i'm trying to do this wihtout using a String to concatenate the bytes.</p>
<p>I've already tried something with binary operators such as <<, >> or |, but without succes...</p>
<p>so far, my code look like this :</p>
<pre><code>byte[] tab = {1,2,3,4};
int tmp,tabToInt = 0;
for (int x = 0 ; x < tab.length ; ++x){
tmp = tmp << (tab.length - 1 - x)*8;
byteToInt = byteToInt | tmp;
}
return tabToInt;
</code></pre>
<p>But it didn't seems to work, even less with negatives bytes... (like -1 = 0b11111111)</p>
<p>Thanks in advance for your answers !</p>
| [
{
"answer_id": 74242729,
"author": "rzwitserloot",
"author_id": 768644,
"author_profile": "https://Stackoverflow.com/users/768644",
"pm_score": 2,
"selected": true,
"text": "class ApplicationController<\n AppEntity extends ApplicationEntity,\n"
}
] | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20362697/"
] |
74,242,340 | <p>I have this list:</p>
<pre><code>list = ['12kg','900g', '2,7kg', '801g', '15', '3,63kg', '1kg']
</code></pre>
<p>and I want to remove only letter <code>g</code> (or replace with <code>""</code>) when I have pattern <code><number>g</code>, which means:</p>
<pre><code>new_list = ['12kg', '900', '2,7kg', '801', '15', '3,63kg', '1kg]
</code></pre>
<p>I've tried to write the following but failed they all failed:</p>
<ul>
<li><code>[^kK]g</code>: for some reason gets last digit (<code>0g</code> and <code>1g</code>)</li>
<li><code>[^kK]g$</code>: nothing comes up (I expected the sign <code>$</code> would get the end of string)</li>
<li><code>[^kK](g)</code>: it does work but in a group -> How do I replace the group match with what I want?</li>
</ul>
| [
{
"answer_id": 74242729,
"author": "rzwitserloot",
"author_id": 768644,
"author_profile": "https://Stackoverflow.com/users/768644",
"pm_score": 2,
"selected": true,
"text": "class ApplicationController<\n AppEntity extends ApplicationEntity,\n"
}
] | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17835442/"
] |
74,242,345 | <p>Suppose I have the following dataframe:</p>
<pre><code> A B C D Count
0 0 0 0 0 12.0
1 0 0 0 1 2.0
2 0 0 1 0 4.0
3 0 0 1 1 0.0
4 0 1 0 0 3.0
5 0 1 1 0 0.0
6 1 0 0 0 7.0
7 1 0 0 1 9.0
8 1 0 1 0 0.0
... (truncated for readability)
</code></pre>
<p>And an array: <code>[1, 0, 0, 1]</code></p>
<p>I would like to access <code>Count</code> value given the above values of each column. In this case, this would be <code>row 7</code> with Count = 9.0</p>
<p>I can use iloc or at by deconstructing each value in the array, but that seems inefficient. Wondering if there's a way to map the values in the array to a value of a column.</p>
| [
{
"answer_id": 74242440,
"author": "Arne",
"author_id": 13014172,
"author_profile": "https://Stackoverflow.com/users/13014172",
"pm_score": 2,
"selected": false,
"text": "all()"
},
{
"answer_id": 74242522,
"author": "ScottC",
"author_id": 20174226,
"author_profile": "... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7871458/"
] |
74,242,348 | <p>I am trying to do this.</p>
<p>The circle is: 90px 90px</p>
<p><a href="https://i.stack.imgur.com/5a4jP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5a4jP.png" alt="enter image description here" /></a></p>
<p>How do I add the colored circle to the middle?</p>
<p>I am not exactly sure how this would be done.</p>
<p><a href="https://jsfiddle.net/xft3r061/" rel="nofollow noreferrer">https://jsfiddle.net/xft3r061/</a></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>.fence {
width: 640px;
height: 340px;
background:
linear-gradient(45deg,
#0000 7px,
blue 0 7.5px,
#0000 0 10px),
linear-gradient(-45deg,
#0000 7px,
blue 0 7.5px,
#0000 0 10px);
background-size: 10px 10px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="fence"></div></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74242394,
"author": "Mukundhan",
"author_id": 6769119,
"author_profile": "https://Stackoverflow.com/users/6769119",
"pm_score": 2,
"selected": false,
"text": ".fence {\n width: 640px;\n height: 340px;\n display: flex;\n justify-content: center;\n align-items: center;\... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17631451/"
] |
74,242,370 | <p>I have two models
listing model is:</p>
<pre><code>class listing(models.Model):
productTitle= models.CharField(max_length=60)
description = models.TextField()
category = models.ForeignKey(category,on_delete=models.CASCADE,null=True)
productPrice = models.FloatField(default=0.0)
def __str__(self):
return self.productTitle
</code></pre>
<p>my watchlist model is:</p>
<pre><code> item = models.ForeignKey(listing, on_delete= models.CASCADE)
watchlist = models.BooleanField(default=False)
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.item
</code></pre>
<p>In my index.html
I want to show the list item if watchlist attribute is False.</p>
<p>Now, my views.py for index.html is as follows:</p>
<pre><code>def index(request):
if request.user != "AnonymousUser":
items= listing.objects.exclude(id=watchlist.objects.filter(user=request.user))
else:
items = watchlist.objects.all()
context = {'items':items}
return render(request, "auctions/index.html", context)
</code></pre>
<p>I couldn't filter the items on listing models based on the result of watchlist model i.e if watchlist=True then I do not want to render items on index.html. Because, I want to render watchlist items in separate pages.
How to query in django if there are two models used?</p>
| [
{
"answer_id": 74242394,
"author": "Mukundhan",
"author_id": 6769119,
"author_profile": "https://Stackoverflow.com/users/6769119",
"pm_score": 2,
"selected": false,
"text": ".fence {\n width: 640px;\n height: 340px;\n display: flex;\n justify-content: center;\n align-items: center;\... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11457339/"
] |
74,242,373 | <p>This is my simple code</p>
<pre><code>function toggleDarkMode() {
let darkTheme= document.body;
darkTheme.classList.toggle("darkMode");
}
</code></pre>
<p>It works well, but I can't for the life of me think of a way to save it in local.storage since it's not true or false, it just modifies the css.</p>
<p>I'd like for it to be saved and stay on the previous choice when it opens up next time.
Anyone have any ideas?</p>
| [
{
"answer_id": 74242403,
"author": "Franco Agustín Torres",
"author_id": 20318366,
"author_profile": "https://Stackoverflow.com/users/20318366",
"pm_score": 2,
"selected": false,
"text": "window"
},
{
"answer_id": 74242405,
"author": "ActionJackson",
"author_id": 20362756... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20362795/"
] |
74,242,399 | <p>When using <code>trigger()</code> on react hook form I can't read the errors object on first attempt. I think this is because the object populates on a subsequent render.</p>
<p>Here is full working example: <a href="https://codesandbox.io/s/crimson-firefly-f8ulg7?file=/src/App.tsx" rel="nofollow noreferrer">https://codesandbox.io/s/crimson-firefly-f8ulg7?file=/src/App.tsx</a></p>
<p>You can see the first time you click submit it logs an empty object and does not set focus. If you click it again then it will work as intended.</p>
<p>Here is example form code:</p>
<pre><code>import "./styles.css";
import classNames from "classnames";
import { useForm } from "react-hook-form";
export default function App() {
const {
register,
handleSubmit,
trigger,
watch,
formState: { errors }
} = useForm();
const onSubmit = (data: any) => console.log(data);
return (
<div className="App">
<div className="form">
<form onSubmit={handleSubmit(onSubmit)}>
<div className={"row"}>
<div className="label">Name</div>
<div
className={classNames({
input: true,
error: errors?.name !== undefined
})}
>
<input {...register("name", { required: "Name is required" })} />
</div>
</div>
<div className="row">
<div className="label">Company</div>
<div
className={classNames({
input: true,
error: errors?.company !== undefined
})}
>
<input
{...register("company", { required: "Company is required" })}
/>
</div>
</div>
<div className="row">
<div className="label">Tel</div>
<div
className={classNames({
input: true,
error: errors?.tel !== undefined
})}
>
<input
{...register("tel", { required: "Telephone is required" })}
/>
</div>
</div>
<div className="row">
<div className="label">Mobile</div>
<div
className={classNames({
input: true,
error: errors?.mobile !== undefined
})}
>
<input
{...register("mobile", { required: "Mobile is required" })}
/>
</div>
</div>
<div className="row">
<div className="label">Email</div>
<div
className={classNames({
input: true,
error: errors?.email !== undefined
})}
>
<input
{...register("email", { required: "Email is required" })}
/>
</div>
</div>
</form>
</div>
<div className="button">
<a
href="#"
onClick={() => {
trigger().then((res) => {
if (res) {
handleSubmit(onSubmit)();
} else {
let elem = errors[Object.keys(errors)[0]]
?.ref as HTMLInputElement;
elem?.focus();
// setTimeout(() => {
// (errors[Object.keys(errors)[0]]?.ref as HTMLInputElement).focus();
// }, 10);
// (errors[Object.keys(errors)[0]]?.ref as HTMLInputElement).focus();
console.log(errors);
}
});
}}
>
Submit
</a>
</div>
</div>
);
}
</code></pre>
<p>I tried using a timeout but it's still empty on the first attempt.</p>
<p>How do I trigger the forms validation and run code based on the results of the validation?</p>
<p>I want to know the errored fields but also have the <code>ref</code> that is included inside the error object.</p>
| [
{
"answer_id": 74242403,
"author": "Franco Agustín Torres",
"author_id": 20318366,
"author_profile": "https://Stackoverflow.com/users/20318366",
"pm_score": 2,
"selected": false,
"text": "window"
},
{
"answer_id": 74242405,
"author": "ActionJackson",
"author_id": 20362756... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/657477/"
] |
74,242,407 | <p>I have a code that looks like:</p>
<pre><code>#!/usr/bin/env python
'''Plot multiple DOS/PDOS in a single plot
run python dplot.py -h for more usage
'''
import argparse
import sys
import matplotlib.pyplot as plt
import numpy as np
parser = argparse.ArgumentParser()
# parser.add_argument('--dos', help='Plot the dos', required=True)
parser.add_argument('--dos', nargs='*', help='Files to plot')
parser.add_argument('--label', nargs='*', help='Label of the files')
parser.add_argument('--fermi', help='Fermi Energy')
args = parser.parse_args()
</code></pre>
<p>If I run this code with <code>python foo.py -h</code>, I get the output:</p>
<pre><code>usage: foo.py [-h] [--dos [DOS ...]] [--label [LABEL ...]] [--fermi FERMI]
options:
-h, --help show this help message and exit
--dos [DOS ...] Files to plot
--label [LABEL ...] Label of the files
--fermi FERMI Fermi Energy
</code></pre>
<p>I know I can separately print the docstring using <code>print(__doc__)</code>.</p>
<p>But, I want the <code>python foo.py -h</code> to print both the docstring together with the present <code>-h</code> output. That is, <code>python foo.py -h</code> should give:</p>
<pre><code>Plot multiple DOS/PDOS in a single plot
run python dplot.py -h for more usage
usage: foo.py [-h] [--dos [DOS ...]] [--label [LABEL ...]] [--fermi FERMI]
options:
-h, --help show this help message and exit
--dos [DOS ...] Files to plot
--label [LABEL ...] Label of the files
--fermi FERMI Fermi Energy
</code></pre>
<p>Is this possible?</p>
| [
{
"answer_id": 74242403,
"author": "Franco Agustín Torres",
"author_id": 20318366,
"author_profile": "https://Stackoverflow.com/users/20318366",
"pm_score": 2,
"selected": false,
"text": "window"
},
{
"answer_id": 74242405,
"author": "ActionJackson",
"author_id": 20362756... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2005559/"
] |
74,242,442 | <p>Can't keep data in the array when adding new. This code is in a loop btw</p>
<pre><code>let placeHolder = facArray[key].filter(i => i.M == map).map(i => i.W)
mapArray[map] = [...placeHolder]
</code></pre>
<p>I am trying to store data in an array with the value of map as an index and I would like to push data to it this is in a loop btw but it keeps removing the previous data how do I keep the previous data while adding to it</p>
| [
{
"answer_id": 74242403,
"author": "Franco Agustín Torres",
"author_id": 20318366,
"author_profile": "https://Stackoverflow.com/users/20318366",
"pm_score": 2,
"selected": false,
"text": "window"
},
{
"answer_id": 74242405,
"author": "ActionJackson",
"author_id": 20362756... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2200809/"
] |
74,242,473 | <p>I have a huge 23 GB CSV file I am trying to load, and I've found that instead of converting it to insert statements which takes a while, It's possible to directly load to the DB.
So I tried the following syntax:</p>
<pre><code>LOAD DATA LOCAL INFILE client_report.csv into table client_report fields terminated by ',' optionally enclosed by '"' lines terminated by '\r\n' ignore 1 lines;
</code></pre>
<blockquote>
<p>mysql> LOAD DATA LOCAL INFILE client_report.csv into table
client_report fields terminated by ',' optionally enclosed by '"' lines
terminated by '\r\n' ignore 1 lines; ERROR 1064 (42000): You have an
error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near
'client_report.csv into table client_report fields terminated
by ',' opti' at line 1</p>
</blockquote>
<p>I am at a loss, I seem to be following documentation to the letter, and checked
<code>sHOW GLOBAL VARIABLES LIKE 'local_infile';</code> its ON.</p>
| [
{
"answer_id": 74242503,
"author": "Gerballi",
"author_id": 20358885,
"author_profile": "https://Stackoverflow.com/users/20358885",
"pm_score": -1,
"selected": false,
"text": "import pandas\nimport sqlite3\nimport time\n\nstart_time = time.process_time()\n\ndb = sqlite3.connect(\"-databa... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/373091/"
] |
74,242,478 | <p>I am making a navigation bar for my website and I am relatively new to HTML, I am trying to set the font size of the nav links to 17px but it is not working. When I try it the font size just stays the same.</p>
<p>I tried changing the font in the .nav tag, like this:</p>
<pre><code><div class="navbar">
<div class="nav-bg">
<!-- nav background container -->
</div>
<h1 class="title-text"><span class="text-gradient" >Cosmic</span> Studios</h1>
<div class="nav">
<h1 class="home">Home</h1>
<h1 class="proxies">Proxies</h1>
<h1 class="courses">Courses</h1>
</div>
</div>
</code></pre>
<pre><code>.nav {
display: flex;
gap: 25px;
color: var(--text-color);
font-size: 17px;
font-family: 'Manrope';
font-style: normal;
}
</code></pre>
<p>I also tried referencing each individual element, i.e: .home, .proxies. courses etc. but that messed with some other elements, what should I do</p>
| [
{
"answer_id": 74242503,
"author": "Gerballi",
"author_id": 20358885,
"author_profile": "https://Stackoverflow.com/users/20358885",
"pm_score": -1,
"selected": false,
"text": "import pandas\nimport sqlite3\nimport time\n\nstart_time = time.process_time()\n\ndb = sqlite3.connect(\"-databa... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20193212/"
] |
74,242,479 | <p>I have the following dataframe:</p>
<pre><code>col1
01
1
02
2
03
3
00
0
</code></pre>
<p>How can I replace values in col1 to be like the expected output below:</p>
<p>Expected Output:</p>
<pre><code>col1
1
1
2
2
3
3
0
0
</code></pre>
| [
{
"answer_id": 74242854,
"author": "Khaled DELLAL",
"author_id": 15852600,
"author_profile": "https://Stackoverflow.com/users/15852600",
"pm_score": 1,
"selected": false,
"text": "df['col1']=[int(x) for x in df['col1']]\n"
},
{
"answer_id": 74243530,
"author": "salman",
"... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9566739/"
] |
74,242,492 | <p>Suppose I have a tibble</p>
<pre><code>id year X
1 2001 False
1 2002 TRUE
1 2003 TRUE
1 2004 False
1 2005 False
1 2006 TRUE
1 2007 TRUE
1 2008 TRUE
</code></pre>
<p>How to Calculate a <strong>Continuous</strong> Cumulative Sum of variable X?</p>
<pre><code>id year X cumN
1 2001 False 0
1 2002 TRUE 1
1 2003 TRUE 2
1 2004 False 0
1 2005 False 0
1 2006 TRUE 1
1 2007 TRUE 2
1 2008 TRUE 3
</code></pre>
<p>Thanks!</p>
<pre><code>dt <- tibble(id = rep(1,8),
year = 2001:2008,
X = c(FALSE, TRUE, TRUE, FALSE, FALSE, TRUE,TRUE,TRUE))
</code></pre>
| [
{
"answer_id": 74242596,
"author": "Just James",
"author_id": 19730031,
"author_profile": "https://Stackoverflow.com/users/19730031",
"pm_score": 2,
"selected": false,
"text": "rle"
},
{
"answer_id": 74242604,
"author": "SpikyClip",
"author_id": 16745699,
"author_prof... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8756279/"
] |
74,242,504 | <p>Example json:</p>
<pre><code>{
"a": 1,
"c": {
"ca": 1.1
},
"d": {},
"e": [1,2,3],
"f": [
{
"fa": "vf1",
"fb": "vf2",
"fc": [],
"fffs232/232": {
"z": 1
}
},
{
"fa": "vf3",
"fb": "vf4",
"fc": [1.1,2.3],
"fffs232/232": {
"z": 2
}
}
]
}
</code></pre>
<p>I want a full path jq expression that gives me the values of "z". Such expression should not explicitly mention "fffs232/232" since that key is dynamic.</p>
<p>Is this possible with jq?</p>
<p>Thanks!</p>
| [
{
"answer_id": 74242596,
"author": "Just James",
"author_id": 19730031,
"author_profile": "https://Stackoverflow.com/users/19730031",
"pm_score": 2,
"selected": false,
"text": "rle"
},
{
"answer_id": 74242604,
"author": "SpikyClip",
"author_id": 16745699,
"author_prof... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/347527/"
] |
74,242,562 | <p>I'm currently in the process of learning python and having a lot of trouble with the syntax.
The problem I'm currently working on is asking me to make a simple password/input more complex. So far I'm trying to use a for loop to cycle through all the letters and see if they need to be changed, as in m -> M. I want each loop to add the resulting character onto a new variable(new_pass) and basically put the characters together to make the new password. That's the thought anyways. The sample input I'm working off is the word 'mypassword', which in turn should output 'Myp@$$word!' per the if/elif statements below.
Currently I'm getting an error at line 6 "invalid syntax". Thanks in advance if you can help me out!</p>
<pre><code>word = input()
password = ''
new_pass = ''
for letter in word:
if letter == i
letter = 1
elif letter == a:
letter = @
elif letter == m:
letter = M
elif letter == B:
letter = 8
elif letter == s:
letter = $
else:
new_pass = new_pass + letter
print(new_pass)
</code></pre>
| [
{
"answer_id": 74242596,
"author": "Just James",
"author_id": 19730031,
"author_profile": "https://Stackoverflow.com/users/19730031",
"pm_score": 2,
"selected": false,
"text": "rle"
},
{
"answer_id": 74242604,
"author": "SpikyClip",
"author_id": 16745699,
"author_prof... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20363001/"
] |
74,242,577 | <p>I have trouble with my code. i want display record sum <code>jk = P</code> and <code>jk = L</code></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const JK = ["L", "P"];
const data = [{
"name": "Faris",
"jk": "L"
}, {
"name": "Nanda",
"jk": "P"
}, {
"name": "Ani",
"jk": "P"
}]
var b = []
for (var a = 0; a < JK.length; a++) {
for (var i = 0; i < data.length; i++) {
if (data[i].jk == JK[a]) b.push(data[a] += 1)
}
}
console.log(b);</code></pre>
</div>
</div>
</p>
<p>I want <code>b = [1, 2]</code></p>
| [
{
"answer_id": 74242596,
"author": "Just James",
"author_id": 19730031,
"author_profile": "https://Stackoverflow.com/users/19730031",
"pm_score": 2,
"selected": false,
"text": "rle"
},
{
"answer_id": 74242604,
"author": "SpikyClip",
"author_id": 16745699,
"author_prof... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19492951/"
] |
74,242,608 | <p>The script shown here work in SQL Server but NOT in SNOWFLAKE SQL. What is the equivalent in SNOWFLAKE SQL?</p>
<pre><code>SELECT DISTINCT
ST2.SubjectID,
SUBSTRING((SELECT ',' + ST1.StudentName AS [text()]
FROM dbo.Students ST1
WHERE ST1.SubjectID = ST2.SubjectID
ORDER BY ST1.SubjectID
FOR XML PATH (''), TYPE).value('text()[1]', 'nvarchar(max)'), 2, 1000) [Students]
FROM
dbo.Students ST2
</code></pre>
<p>RESULTS FROM SAMPLE BELOW: IT CONCATENATES TEXT FROM ALL THE ROWS INTO A SINGLE TEXT STRING BY ID</p>
<p>I tried the above in SQL Server and it worked, however, I need to use a datawarehouse in Snowflake and snowflake doesn't use XML PATH. They have XMLGET but I can't figure out how to use it.</p>
| [
{
"answer_id": 74242806,
"author": "Rajat",
"author_id": 9947159,
"author_profile": "https://Stackoverflow.com/users/9947159",
"pm_score": 2,
"selected": false,
"text": "listagg"
},
{
"answer_id": 74258398,
"author": "Simeon Pilgrim",
"author_id": 43992,
"author_profi... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20363005/"
] |
74,242,609 | <pre><code>import sys
ok = True
count = 0
while ok == True:
try:
a = int(input("What is a? Put number pls "))
ok = False
count = count + 1
except ValueError:
print("no u")
if (count >= 3):
sys.exit()
</code></pre>
<p>What I'm trying to do here is get the user to input an integer. If the user inputted an integer or the loop has ran 3 times, the program stops. I have tried putting the if statement both in the try and except statements, it still keeps on looping.</p>
<p>I have also tried this:</p>
<pre><code>ok = True
count = 0
while ok == True:
try:
a = int(input("What is a? Put number pls "))
ok = False
count = count + 1
except ValueError:
print("no u")
if (count >= 3):
break
</code></pre>
<p>It still doesn't break out of the loop.</p>
<p>I have inputted numbers, breaks out of the loop as what I expected. I then tried to input random letters and hoped that the loop stops after 3 times, it still continues to loop until I have inputted a number. Happens to both versions.</p>
| [
{
"answer_id": 74242646,
"author": "Michael M.",
"author_id": 13376511,
"author_profile": "https://Stackoverflow.com/users/13376511",
"pm_score": 3,
"selected": true,
"text": "count = 0\nwhile count < 3:\n try:\n a = int(input(\"What is a? Put number pls \"))\n break\n ... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20184682/"
] |
74,242,620 | <p>I've created a multiplot containing an isoline plot f(x,y) and a point, (0,0) on the zero level set of the isoline plot. Unfortunately the point plot appears to create a second axis frames as shown below</p>
<pre><code>f(x,y)=2*x**2 - x + 2*y**2 - y - 2
set multiplot
set xrange [-3:3]
set yrange [-3:3]
set isosamples 250
set contour
unset surface
set view map
set key out
set cntrparam levels incremental 0,1,5
splot f(x,y)
plot "< echo '1 1'"
set nomultiplot
</code></pre>
<p>What can I do to solve this problem?</p>
<p><strong>Update</strong></p>
<p>A bit more context. In the larger problem I am using multiplot to superimpose two isoline plots, as hinted below. Both isoline plots share a common axis frame.</p>
<pre><code>...
set cntrparam levels incremental 0,1,5
splot f(x,y)
set cntrparam levels discrete 0
g(x,y)=(x - 1)**2 + y**2 - 1
splot g(x,y)
</code></pre>
<p><a href="https://i.stack.imgur.com/JOSLY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JOSLY.png" alt="isoline plot and single point" /></a></p>
| [
{
"answer_id": 74242912,
"author": "Ethan",
"author_id": 6797953,
"author_profile": "https://Stackoverflow.com/users/6797953",
"pm_score": 2,
"selected": true,
"text": "f(x,y)=2*x**2 - x + 2*y**2 - y - 2\n\nset label 1 \"\" at 1,1,0 point pt 7 lc \"blue\"\n\nset xrange [-3:3]\nset yrange... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/181783/"
] |
74,242,639 | <p>Hi I am trying to set the show the items the is only related to a specific user who is currently logged in.</p>
<p>I have made sure that the user has items under his username. I want to filter the items to be viewed only to the related user. Currently I am getting an error of <code>Not Found: /</code> I am not sure why?</p>
<p>Here is the models.py:</p>
<pre><code>class Item(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True)
</code></pre>
<p>Here is the urls.py:</p>
<pre><code>urlpatterns = [
#path('', home.as_view(), name='home'), <-- Returned not found
path('user/<str:username>/', home.as_view(), name='home'), <-- Retuned Not found as well
</code></pre>
<p>I have tried to have a queryset with the filter to the logged in user but returned back the same error.</p>
<p>Here is my views that I have tried</p>
<pre><code>class home(LoginRequiredMixin, ListView):
model = Item
template_name = 'app_name/base.html'
context_object_name = 'items'
# queryset = Item.objects.filter(user=User)
def get_queryset(self):
user = get_object_or_404(User, username=self.kwargs.get('username'))
print(user)
# return Item.objects.filter(user=user)
</code></pre>
<p>In the home.html I added:
<code>{% block head_title %} {{ view.kwargs.username }} | {% endblock %}</code></p>
<p><em><strong>My question:</strong></em></p>
<p>How can I show the list of items that is only related to the logged in user? what am I doing wrong in here?</p>
| [
{
"answer_id": 74242735,
"author": "Fernando Beckworth",
"author_id": 20353641,
"author_profile": "https://Stackoverflow.com/users/20353641",
"pm_score": -1,
"selected": false,
"text": "self.kwargs[f'username'] #f string if it is a variable which it should be.\nNot\nself.kwargs.get('use... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13176726/"
] |
74,242,650 | <p>My main.tf has following code:</p>
<pre><code>resource "aws_lb_target_group" "dev-ext-test-msvc1-pub" {
name = "dev-ext-test-msvc1-pub"
port = "14003"
protocol = "HTTP"
target_type = "instance"
vpc_id = data.aws_vpc.vpc.id
protocol_version = "HTTP1"
deregistration_delay = 10
health_check {
enabled = true
interval = 10
path = "/health"
port = "32767"
healthy_threshold = 2
unhealthy_threshold = 2
timeout = 2
protocol = "HTTP"
matcher = "200"
}
tags = {
environment = "dev"
project = "ext test 2"
Name = "dev-ext-test-msvc1-pub"
}
}
resource "aws_lb_target_group" "dev-ext-test-msvc2-pub" {
name = "dev-ext-test-msvc2-pub"
port = "14004"
protocol = "HTTP"
target_type = "instance"
vpc_id = data.aws_vpc.vpc.id
protocol_version = "HTTP1"
deregistration_delay = 10
health_check {
enabled = true
interval = 10
path = "/health"
port = "32767"
healthy_threshold = 2
unhealthy_threshold = 2
timeout = 2
protocol = "HTTP"
matcher = "200"
}
tags = {
environment = "dev"
project = "ext test 2"
Name = "dev-ext-test-msvc2-pub"
}
}
resource "aws_lb_target_group" "dev-ext-test-msvc5-pub" {
name = "dev-ext-test-msvc5-pub"
port = "14002"
protocol = "HTTP"
target_type = "instance"
vpc_id = data.aws_vpc.vpc.id
protocol_version = "HTTP1"
deregistration_delay = 10
health_check {
enabled = true
interval = 10
path = "/health"
port = "32767"
healthy_threshold = 2
unhealthy_threshold = 2
timeout = 2
protocol = "HTTP"
matcher = "200"
}
tags = {
environment = "dev"
project = "ext test 2"
Name = "dev-ext-test-msvc5-pub"
}
}
resource "aws_lb_target_group" "dev-ext-test-msvc4-pub" {
name = "dev-ext-test-msvc4-pub"
port = "14001"
protocol = "HTTP"
target_type = "instance"
vpc_id = data.aws_vpc.vpc.id
protocol_version = "HTTP1"
deregistration_delay = 10
health_check {
enabled = true
interval = 10
path = "/health"
port = "32767"
healthy_threshold = 2
unhealthy_threshold = 2
timeout = 2
protocol = "HTTP"
matcher = "200"
}
tags = {
environment = "dev"
project = "ext test 2"
Name = "dev-ext-test-msvc4-pub"
}
}
</code></pre>
<p>And output.tf is :</p>
<pre><code>output "lb_dns" {
value = module.dev-ext-test-pub-2-alb.lb_dns_name
}
output "lb_security_group" {
value = module.dev-ext-test-pub-2-alb-sg.security_group_id
}
output "lb_target_groups" {
value = aws_lb_target_group.*.name
}
output "lb_target_groups_arns" {
value = aws_lb_target_group.*.arn
}
output "worker_ami" {
value = data.aws_ami.k8s_msvcs_custom_ami.id
}
output "worker_security_group" {
value = data.aws_security_group.worker_k8s_sg.id
}
output "worker_subnet_id" {
value = data.aws_subnet.worker-subnet.id
}
</code></pre>
<p>But the <code>aws_lb_target_group.*.name</code> is unable to fetch all target groups. Though I can do something like this to fetch the values:</p>
<pre><code>output "lb_target_groups" {
value = [aws_lb_target_group.dev-ext-test-msvc1-pub.name, aws_lb_target_group.dev-ext-test-msvc4-pub.name,]
}
output "lb_target_groups_arns" {
value = [aws_lb_target_group.dev-ext-test-msvc1-pub.arn, aws_lb_target_group.dev-ext-test-msvc4-pub.arn,]
}
</code></pre>
<p>But is there a more efficient way to fetch all target groups?</p>
| [
{
"answer_id": 74243218,
"author": "Marcin",
"author_id": 248823,
"author_profile": "https://Stackoverflow.com/users/248823",
"pm_score": 3,
"selected": true,
"text": "aws_lb_target_group"
},
{
"answer_id": 74247046,
"author": "Flamarion",
"author_id": 3673929,
"autho... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2297135/"
] |
74,242,675 | <p>I have a requirement to deploy config rules conditionally based on certain parameters. Here below is one</p>
<pre><code>config.ManagedRule(self, "AccessKeysRotated",
identifier=config.ManagedRuleIdentifiers.ACCESS_KEYS_ROTATED,
input_parameters={
"max_access_key_age": 60
},
maximum_execution_frequency=config.MaximumExecutionFrequency.TWELVE_HOURS
)
</code></pre>
<p>Here below is another one</p>
<pre><code>config.ManagedRule(self, "S3BucketLogging",
identifier=config.ManagedRuleIdentifiers.S3_BUCKET_LOGGING_ENABLED,
config_rule_name="S3BucketLogging"
)
</code></pre>
<p>The managed rule identifiers are in the hundreds. I don't want to have all of these in one big file but each rule stored in a separate file. I can then read off a dynamodb where I store the account name and a csv list of rules that pertain to that account. Each item in the csv can be a single file which has a single rule. Is there a way to do this?</p>
| [
{
"answer_id": 74246205,
"author": "fedonev",
"author_id": 1103511,
"author_profile": "https://Stackoverflow.com/users/1103511",
"pm_score": 2,
"selected": true,
"text": "aws_config_stack"
},
{
"answer_id": 74253978,
"author": "lynkfox",
"author_id": 11591758,
"author... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20358/"
] |
74,242,679 | <p>I have a two-dimensional list like this:</p>
<pre><code>[[1, 6], [2, 5], [3, 7], [5, 2], [6, 1], [7, 3], [8, 9], [9, 8]]
</code></pre>
<p>I want to remove all the sublists that are duplicates but in reverse order (ie: <code>[1, 6]</code> and <code>[6, 1]</code>, <code>[3, 7]</code> and <code>[7, 3]</code>).</p>
<p>The result should be:</p>
<pre><code>[[1, 6], [2, 5], [3, 7], [8, 9]]
</code></pre>
| [
{
"answer_id": 74242687,
"author": "j1-lee",
"author_id": 11450820,
"author_profile": "https://Stackoverflow.com/users/11450820",
"pm_score": 2,
"selected": false,
"text": "set"
},
{
"answer_id": 74242693,
"author": "Michael M.",
"author_id": 13376511,
"author_profile... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11315832/"
] |
74,242,724 | <p>I'm having a problem here when I want to make dynamic color changes when the user wants to click on the menu in the sidebar.</p>
<p>So, when the user wants to move the page from /building to /street, then the user will click the "street" menu and hopefully the street menu will change color like the building menu which changes color to red when the menu is active.</p>
<p>however, when I made it not as I expected and the result is like the image below.</p>
<p>Maybe the masters can help me. Thank you very much</p>
<p><a href="https://i.stack.imgur.com/ksehi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ksehi.png" alt="enter image description here" /></a>
<a href="https://i.stack.imgur.com/bFuuO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bFuuO.png" alt="enter image description here" /></a></p>
<p><em><strong>Sidebar.jsx</strong></em></p>
<pre><code>import React from "react";
import { useState } from "react";
import { BiBuildingHouse } from "react-icons/bi";
import { FaRoad } from "react-icons/fa";
import { Link, NavLink } from "react-router-dom";
const Sidebar = () => {
const [activeMenu, setActiveMenu] = useState(false);
return (
<div className='w-[16rem] h-[72rem] bg-[#FFFFFF] px-5 py-3 md:px-8 md:py-5 drop-shadow-xl"'>
<h1 className="text-[#92929D] font-semibold ml-3">DASHBOARD</h1>
<NavLink
to="/try/building"
className={
activeMenu === "/try/building"
? "mr-6 mt-4 w-[12rem] h-[4rem] bg-red-500 text-white py-3 md:px-8 md:py-5 rounded-2xl drop-shadow-xl cursor-pointer"
: "mr-6 mt-4 text-black py-3 md:px-8 md:py-5 rounded-2xl drop-shadow-xl cursor-pointer"
}
onClick={() => {
setActiveMenu("/try/building");
}}
active={activeMenu}
>
<div className="mr-6 mt-4 w-[12rem] h-[4rem] bg-red-500 py-3 md:px-8 md:py-5 rounded-2xl drop-shadow-xl cursor-pointer">
<div className="inline-flex gap-4 items-center">
<BiBuildingHouse size={25} className="text-white" />
<h1 className="text-white">Building</h1>
</div>
</div>
</NavLink>
<Link
to="/try/street"
className={
activeMenu === "/try/street"
? "mr-6 mt-4 w-[12rem] h-[4rem] bg-red-500 text-white py-3 md:px-8 md:py-5 rounded-2xl drop-shadow-xl cursor-pointer"
: "mr-6 mt-4 text-black py-3 md:px-8 md:py-5 rounded-2xl drop-shadow-xl cursor-pointer"
}
onClick={() => {
setActiveMenu("/try/street");
}}
active={activeMenu}
>
<div className="mr-6 w-[12rem] h-[4rem] py-3 md:px-8 md:py-5 rounded-2xl drop-shadow-xl cursor-pointer">
<div className="inline-flex gap-4 items-center">
<FaRoad size={25} className="text-[#92929D]" />
<h1 className="text-black">Street</h1>
</div>
</div>
</Link>
</div>
);
};
export default Sidebar;
</code></pre>
| [
{
"answer_id": 74242826,
"author": "Elbashir Saror",
"author_id": 20033482,
"author_profile": "https://Stackoverflow.com/users/20033482",
"pm_score": 2,
"selected": true,
"text": "useState()"
},
{
"answer_id": 74254251,
"author": "Drew Reese",
"author_id": 8690857,
"a... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17680464/"
] |
74,242,776 | <p>We have AWS accounts created and managed using control tower service.</p>
<p>The requirement is to restrict internet access from lambda even it is not attached to any VPC.</p>
<p>By default lambda functions can connect to internet if it is not connected to any VPC.</p>
<p>How do we enforce restricting internet access to users using lambda functions ?</p>
| [
{
"answer_id": 74433711,
"author": "sajesh pp",
"author_id": 9013358,
"author_profile": "https://Stackoverflow.com/users/9013358",
"pm_score": 1,
"selected": true,
"text": "{\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Sid\": \"EnforceVPCFunction\",\n \"Actio... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9013358/"
] |
74,242,803 | <p>I am new to Python. I am trying to write a script which will copy values from one excel file to another and sort them based on the value in column A. My code is only copying the final value that meets the condition, not all values. What am I doing wrong?</p>
<p><a href="https://i.stack.imgur.com/i9WEi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/i9WEi.png" alt="enter image description here" /></a></p>
<pre><code>from openpyxl import load_workbook
wb = load_workbook('testData.xlsx')
wb2 = load_workbook('testTemplate.xlsx')
ws = wb['Sheet1']
ws2 = wb2['Sheet1']
mr = ws.max_row
mc = ws.max_column
mr2 = ws2.max_row
mc2 = ws2.max_column
for i in range(2, mr + 2):
for j in range(1, mc + 1):
if ws.cell(row=i,column=j).value == "A":
ws2.cell(row=mr2 + 1,column=j).value = ws.cell(row=i,column=j+1).value
elif ws.cell(row=i,column=j).value == "B":
ws2.cell(row=mr2 + 1,column=j+1).value = ws.cell(row=i,column=j+1).value
elif ws.cell(row=i,column=j).value == "C":
ws2.cell(row=mr2 + 1,column=j+2).value = ws.cell(row=i,column=j+1).value
wb2.save('testTemplate.xlsx')
</code></pre>
| [
{
"answer_id": 74433711,
"author": "sajesh pp",
"author_id": 9013358,
"author_profile": "https://Stackoverflow.com/users/9013358",
"pm_score": 1,
"selected": true,
"text": "{\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Sid\": \"EnforceVPCFunction\",\n \"Actio... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7270897/"
] |
74,242,808 | <pre class="lang-dart prettyprint-override"><code>import 'package:flutter/material.dart';
bool jov = false;
class boox extends StatelessWidget {
const boox({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
drawer: Drawer(),
body: Container(
child: Column(children: [
Row(
children: [
Text("jordn"),
Checkbox(
value: jov,
onChanged: (String val) {
setstate(() {
jov = val;
});
})
],
),
Row(
children: [Text("data")],
)
]),
),
);
}
}
</code></pre>
<p>The <code>setstate</code> cannot appear on onchanged and cant take it</p>
<p>I am difintion the variables and the problem still appear</p>
<p>and try to write the code and still appear this problem if any can fix him to me or no way</p>
| [
{
"answer_id": 74433711,
"author": "sajesh pp",
"author_id": 9013358,
"author_profile": "https://Stackoverflow.com/users/9013358",
"pm_score": 1,
"selected": true,
"text": "{\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Sid\": \"EnforceVPCFunction\",\n \"Actio... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20363251/"
] |
74,242,819 | <p>Getting the below error while trying to run the command <code>npm install</code> after the angular migration to version 9.</p>
<p>Error</p>
<pre><code>npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR!
npm ERR! While resolving: jodit-angular@1.9.4
npm ERR! Found: zone.js@0.10.3
npm ERR! node_modules/zone.js
npm ERR! peer zone.js@"~0.10.3" from @angular/core@9.1.13
npm ERR! node_modules/@angular/core
npm ERR! @angular/core@"^9.1.13" from the root project
npm ERR! peer @angular/core@"9.1.13" from @angular/animations@9.1.13
npm ERR! node_modules/@angular/animations
npm ERR! @angular/animations@"^9.1.13" from the root project
npm ERR! 2 more (@angular/platform-browser, jodit-angular)
npm ERR! 11 more (@angular/cdk, @angular/common, @angular/forms, ...)
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer zone.js@"~0.9.1" from jodit-angular@1.9.4
npm ERR! node_modules/jodit-angular
npm ERR! jodit-angular@"1.9.4" from the root project
npm ERR!
npm ERR! Conflicting peer dependency: zone.js@0.9.1
npm ERR! node_modules/zone.js
npm ERR! peer zone.js@"~0.9.1" from jodit-angular@1.9.4
npm ERR! node_modules/jodit-angular
npm ERR! jodit-angular@"1.9.4" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! A complete log of this run can be found in:
</code></pre>
<p>I have added the required <code>zone.js</code> deps version and updated the <code>jodit-angular</code> as below.</p>
<p>The current version of node.js is 16.17.1</p>
<p>Package.json</p>
<pre><code> {
"name": "Angular App",
"version": "0.0.0",
"engines": {
"node": ">=16.0.0"
},
"private": true,
"dependencies": {
"@angular/animations": "^9.1.13",
"@angular/cdk": "^9.2.4",
"@angular/common": "^9.1.13",
"@angular/compiler": "^9.1.13",
"@angular/core": "^9.1.13",
"@angular/forms": "^9.1.13",
"@angular/localize": "^9.1.13",
"@angular/platform-browser": "^9.1.13",
"@angular/platform-browser-dynamic": "^9.1.13",
"@angular/router": "^9.1.13",
"@ng-bootstrap/ng-bootstrap": "^6.2.0",
"@types/lodash": "^4.14.134",
"core-js": "^2.6.5",
"date-fns": "^1.29.0",
"decimal.js": "^10.2.0",
"rxjs": "~6.6.7",
"tslib": "^1.10.0",
"typeface-open-sans": "0.0.54",
"jodit-angular": "1.9.4",
"jsonpath": "^1.0.1",
"karma-parallel": "^0.3.1",
"ng-bullet": "^1.0.3",
"ngx-cookie": "~5.0.2",
"zone.js": "~0.10.3"
},
"devDependencies": {
"@angular-devkit/build-angular": "~0.901.15",
"@angular/cli": "^9.1.15",
"@angular/compiler-cli": "^9.1.13",
"karma-jasmine-html-reporter": "1.7.0",
"karma-junit-reporter": "2.0.1",
"protractor": "~5.4.0",
"puppeteer": "^1.17.0",
"sonar-scanner": "^3.1.0",
"ts-node": "~7.0.0",
"tslint": "~5.11.0",
"typescript": "~3.8.3",
"@angular/language-service": "^9.1.13",
"@types/date-fns": "^2.6.0",
"@types/jasmine": "3.3.0",
"@types/jasminewd2": "2.0.10",
"@types/node": "^12.11.1",
"codelyzer": "^5.1.2",
"https-proxy-agent": "^2.2.1",
"jasmine-core": "3.9.0",
"jasmine-spec-reporter": "7.0.0",
"karma": "4.4.1",
"karma-chrome-launcher": "3.1.1",
"karma-coverage-istanbul-reporter": "3.0.3",
"karma-jasmine": "3.3.0",
},
"optionalDependencies": {
"fsevents": "^2.1.2"
}
}
</code></pre>
<p>Any help is appreciated. Thanks in advance</p>
| [
{
"answer_id": 74433711,
"author": "sajesh pp",
"author_id": 9013358,
"author_profile": "https://Stackoverflow.com/users/9013358",
"pm_score": 1,
"selected": true,
"text": "{\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Sid\": \"EnforceVPCFunction\",\n \"Actio... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3210446/"
] |
74,242,856 | <p>In pyspark how to generate new rows against every month value from given start date and end date time period?
Say, I have a start date column and end date column and there are 8 months in between the dates by datediff. How can i generate 8 rows against 8 months with new column having month values respectively. Say 1 for Jan if start date month is Jan, 2 for Feb and so on till 8?</p>
<p>I tried using tried explode and array_repeat which helped me generate rows against month_between() for every row. But its not my desired result.</p>
| [
{
"answer_id": 74246911,
"author": "bramb",
"author_id": 2931774,
"author_profile": "https://Stackoverflow.com/users/2931774",
"pm_score": 0,
"selected": false,
"text": "import pyspark.sql.functions as F\n \n# Create a list of datetime objects\ndates = [..]\n\n# Transform to Spark DataFr... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20363320/"
] |
74,242,861 | <p>I am trying to make a link that's anchored to a heading appear after scrolling down 300px on my website, but my code doesn't seem to work. Does anyone know why?
<strong>NOTE-
I am using Bootstrap5 on my website.</strong>
<em>I have altered my code based on the replies I got but I'm still facing the issue. This is how my code looks now-</em></p>
<hr />
<p><strong>Here is my code -</strong></p>
<pre><code> <a href="#header-title-1" id="customID" class="bottom-0 end-0 quick-anchor-top hide"> <i
class="fa-solid fa-arrow-up"></i></a>
.quick-anchor-top {
font-size: 25px;
padding: 15px 25px 15px 25px;
border-radius: 50px;
color: rgb(0, 0, 0);
background-color: rgba(182, 20, 20, 0.800);
transition: all 0.4s ease;
margin: 20px;
position: fixed;
z-index: 1;
}
.quick-anchor-top:hover {
transition-duration: 0.4s;
color: white;
background-color: rgba(0, 0, 0, 0.800);
}
.quick-anchor-top.show {
display: block;
}
.quick-anchor-top.hide {
display: none;
}
const myID = document.getElementById("customID");
// Reset timeout after each call
const debounce = function (func, duration = 250){
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => { func.apply(this, args); }, duration);
};
}
// Call only once per duration
function throttle(func, duration = 250) {
let shouldWait = false
return function (...args) {
if (!shouldWait) {
func.apply(this, args)
shouldWait = true
setTimeout(function () {
shouldWait = false
}, duration)
}
}
}
// Handle scroll Event
const scrollHandler = function() {
const { scrollY } = window;
if ( scrollY >= 300) {
myID.classList.add('show');
myID.classList.remove('hide');
} else {
myID.classList.add('hide');
myID.classList.remove('show');
}
};
window.addEventListener("scroll", throttle(() => scrollHandler()) );
</code></pre>
| [
{
"answer_id": 74246911,
"author": "bramb",
"author_id": 2931774,
"author_profile": "https://Stackoverflow.com/users/2931774",
"pm_score": 0,
"selected": false,
"text": "import pyspark.sql.functions as F\n \n# Create a list of datetime objects\ndates = [..]\n\n# Transform to Spark DataFr... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18958838/"
] |
74,242,906 | <p><a href="https://i.stack.imgur.com/1rvM0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1rvM0.png" alt="err" /></a></p>
<p>When I try change my scripts on script setup method - I getting error like on screen. On the other hand, with export default and without <code><script setup></code> , this error has gone. In Vue docs I can't find this decision
Code:</p>
<pre><code><template>
<button class="nav-link" @click.prevent="logOut">LogOut</button>
<RouterView />
<DarkMode />
</template>
<script setup lang="ts">
import DarkMode from './components/DarkMode.vue'
const logOut = () => {
this.$store.dispatch('auth/logout')
this.$router.push('/login')
}
</script>
<style lang="scss"></style>
</code></pre>
| [
{
"answer_id": 74246911,
"author": "bramb",
"author_id": 2931774,
"author_profile": "https://Stackoverflow.com/users/2931774",
"pm_score": 0,
"selected": false,
"text": "import pyspark.sql.functions as F\n \n# Create a list of datetime objects\ndates = [..]\n\n# Transform to Spark DataFr... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15753450/"
] |
74,242,920 | <p>How do I create my DataFrame to show only French movies in the 'Language' column of my dataset where there is multiple languages in the column?</p>
<p>Example:</p>
<pre><code>Languages column:
French
English
German,French,Spanish
Spanish,English,French
French, English, Gernman
</code></pre>
<p>What I have been trying only brings back the columns that have French only as the value in the language column.
Please help!</p>
<p>I have tried:</p>
<pre><code>df.loc[df['column_name'] == some_value]
</code></pre>
<p>but it only returns movies that are in the French language only, not those that are in French but also in other languages.</p>
| [
{
"answer_id": 74242931,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": false,
"text": "str.contains"
},
{
"answer_id": 74242953,
"author": "ali",
"author_id": 11968879,
"author_profi... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20363400/"
] |
74,242,950 | <p>I need help on how to get a list of data from two different inputs, a value input and a frequency input.
I think i could do it by creating a dictionary and adding the values and frequencies to it in the form {v:f,v:f,v:f} etc., but I don't know how to do that.</p>
<p>e.g.</p>
<p>values = First, enter or paste the VALUES, separated by spaces:
frequencies = Now enter the corresponding FREQUENCIES separated by spaces:</p>
<p>It should take each number - separated by spaces - and add it in to the dictionary
so say if
values = 1 2 3 4 5
and
frequencies = 5 4 3 2 1
the dictionary should be
{1:5,2:4,3:3,4:2,5:1}
meaning 1 appears 5 times, 2 appears 4 times, 3 appears 3 times, 4 appears 2 times, and 5 appears once.
and a list from that should be
[1,1,1,1,1,2,2,2,2,3,3,3,4,4,5]</p>
<p>I tried mucking around with for loops and i think i will have to use one or two but im not sure how</p>
| [
{
"answer_id": 74242964,
"author": "Dmitriy Neledva",
"author_id": 16786350,
"author_profile": "https://Stackoverflow.com/users/16786350",
"pm_score": 0,
"selected": false,
"text": "dictionary = dict(zip(input('values = First, enter or paste the VALUES, separated by spaces: ').split(' ')... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14254684/"
] |
74,242,952 | <p>This code snippet:</p>
<pre><code>import numpy as np
from skimage.measure import label, regionprops
image = np.array([[1, 1, 0], [1, 0, 0], [0, 0, 2]])
labels = label(image, background=0, connectivity=2)
props = regionprops(labels, image, cache=True)
print(image)
print(np.argmax([p.area for p in props]))
</code></pre>
<p>will print:</p>
<pre><code>[[1 1 0]
[1 0 0]
[0 0 2]]
0
</code></pre>
<p><code>0</code> is an index of <code>props</code> element with maximum value of <code>area</code> property. Is there a more direct way of computing it without the need for creating a temporary array in <code>np.argmax([p.area for p in props])</code>? It doesn't have to use NumPy.</p>
| [
{
"answer_id": 74243012,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": false,
"text": "regionprops_table"
},
{
"answer_id": 74243185,
"author": "ILS",
"author_id": 10017662,
"author_... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/219153/"
] |
74,242,977 | <p>In C apparently strings are stored like an array with a null value or '\0' at the end. I wish to iterate over the string in a for loop and I need it to stop at '\0', not including it. I've tried many conditions for the if else and it all don't seem to work.</p>
<p>for example:</p>
<pre><code>char patternInput[TEXTSIZE];
for(int i = 0; i<strlen(patternInput);i++)
{
if(patternInput[i]==NULL)
{
printf("\nlast character");
break;
}
else
{
printf("\n%c",patternInput[i]);
}
}
</code></pre>
<p>I've tried <code>if(patternInput[i]==NULL)</code>, <code>if(patternInput[i]==NUL)</code>,<code>if(!patternInput[i])</code>,<code>if(patternInput[i]=='\0')</code> and none of them seems to work.</p>
| [
{
"answer_id": 74242988,
"author": "Jeremy Friesner",
"author_id": 131930,
"author_profile": "https://Stackoverflow.com/users/131930",
"pm_score": 2,
"selected": false,
"text": "strlen()"
},
{
"answer_id": 74243117,
"author": "ashish.g",
"author_id": 604656,
"author_p... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11270788/"
] |
74,243,038 | <p>Below is function through which I am writing data into a .txt file. This has worked several times in the past but below code is not working in a way that it doesn't throw any error as such but it doesn't write anything to the file. It just created it and after that even after running code several times, it doesn't work.</p>
<p>Have debugged as well, everything goes smoothly.</p>
<pre><code>public void GenerateReportCard()
{
string path = @"F:/StudentDetails.txt";
FileStream fs = null;
if (File.Exists(path))
{
fs = new FileStream(path, FileMode.Open, FileAccess.Write);
}
else
{
fs = new FileStream(path, FileMode.CreateNew, FileAccess.Write);
}
StreamWriter sw = new StreamWriter(fs);
foreach (var item in _Student)//_Student is a list of Student class objects
{
sw.WriteLine("{0} , {1}", item.StudentName, item.classroom);
foreach (var marks in item.Marks)
{
sw.WriteLine(", {0}", marks);
}
sw.WriteLine("\n");
}
sw.close();
Console.WriteLine("student added to .txt file");
}
</code></pre>
| [
{
"answer_id": 74243231,
"author": "Maxim",
"author_id": 6690823,
"author_profile": "https://Stackoverflow.com/users/6690823",
"pm_score": 1,
"selected": false,
"text": "// See https://aka.ms/new-console-template for more information\n\nusing System.Text;\n\nvar students = new List<Stude... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19661756/"
] |
74,243,081 | <p><strong><a href="https://i.stack.imgur.com/xIRRL.png" rel="nofollow noreferrer">Indexes table</a></strong></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">Keyname</th>
<th style="text-align: left;">Type</th>
<th style="text-align: left;">Unique</th>
<th style="text-align: left;">Packed</th>
<th style="text-align: left;">Column</th>
<th style="text-align: left;">Cardinality</th>
<th style="text-align: left;">Collation</th>
<th style="text-align: left;">Null</th>
<th style="text-align: left;">Comment</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">PRIMARY</td>
<td style="text-align: left;">BTREE</td>
<td style="text-align: left;">Yes</td>
<td style="text-align: left;">No</td>
<td style="text-align: left;">ID</td>
<td style="text-align: left;">7</td>
<td style="text-align: left;">A</td>
<td style="text-align: left;">No</td>
<td style="text-align: left;"></td>
</tr>
<tr>
<td style="text-align: left;">AD_ID</td>
<td style="text-align: left;">BTREE</td>
<td style="text-align: left;">Yes</td>
<td style="text-align: left;">No</td>
<td style="text-align: left;">AD_ID <br> USER_ID</td>
<td style="text-align: left;">1 <br> 2</td>
<td style="text-align: left;">A <br> A</td>
<td style="text-align: left;">No <br> Yes</td>
<td style="text-align: left;"></td>
</tr>
<tr>
<td style="text-align: left;">USER_ID</td>
<td style="text-align: left;">BTREE</td>
<td style="text-align: left;">No</td>
<td style="text-align: left;">No</td>
<td style="text-align: left;">USER_ID</td>
<td style="text-align: left;">2</td>
<td style="text-align: left;">A</td>
<td style="text-align: left;">Yes</td>
<td style="text-align: left;"></td>
</tr>
</tbody>
</table>
</div>
<p>How can the column of <code>USER_ID</code> be unique and at the same time not be unique as you can see in the indexes table?</p>
| [
{
"answer_id": 74243336,
"author": "WandererAboveTheSea",
"author_id": 9680817,
"author_profile": "https://Stackoverflow.com/users/9680817",
"pm_score": 3,
"selected": true,
"text": "USER_ID"
}
] | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7474282/"
] |
74,243,110 | <p>I create a dataset like that,</p>
<pre><code>Gender response
female yes
male yes
female yes
female no
male yes
female no
male yes
male no
female no
</code></pre>
<p>I like to count the yes responses and no responses genderwise. Like there are two females who said No and 2 females who said yes. There are three males said yes and one said no.</p>
<p>I tried to implement this using pandas dataframe.</p>
<p>So far I have tried to write down the query like</p>
<pre><code>df.loc[df['Gender'] == 'female' & (df['response'] == 'yes')]
</code></pre>
<p>But I got error. How could I write it down?</p>
<p>Thank you.</p>
| [
{
"answer_id": 74243167,
"author": "BehRouz",
"author_id": 2500257,
"author_profile": "https://Stackoverflow.com/users/2500257",
"pm_score": 1,
"selected": false,
"text": "counts = df.groupby(['Gender','response']).size()\n\nprint(counts['female']['yes']) # Show the number of females who... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9357484/"
] |
74,243,138 | <p>//HERE WHY IS IT CONVERTING TO LOWER CASE BUT NOT TO UPPER CASE</p>
<pre><code>public class LowerUpperCase {
public static void main(String[] args) {
String s="lowerUppercase";
for (int i = 0; i < s.length()-1; i++) {
if(s.charAt(i) >='a' && s.charAt(i)<='z'){ //OR IF DONE THIS NOT WORKING
```
if((s.charAt(i) >='a' && s.charAt(i)<='z' ) || (s.charAt(i) >='A' && s.charAt(i)<='Z')){
```
s=s.toLowerCase();//here should i go for
}
else if(s.charAt(i) >='A' && s.charAt(i)<='Z'){
s=s.toUpperCase();
}
}
System.out.println(s);
}
}
</code></pre>
<p>//I ALWAYS GET OUTPUT LIKE loweruppercase or LOWERUPPERCASE</p>
<pre><code>INPUT:LowerUpperCase
OUTPUT:lOWERuPPERcASE expected
HERE WHY IS IT CONVERTING TO LOWER CASE BUT NOT TO UPPER CASE
I ALWAYS GET OUTPUT LIKE loweruppercase or LOWERUPPERCASE
</code></pre>
| [
{
"answer_id": 74243171,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 1,
"selected": true,
"text": "String s = \"lowerUppercase\";\nStringBuilder output = new StringBuilder();\n\nfor (int i=0; i < s.length(); ... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20127653/"
] |
74,243,151 | <p>How do I implement arbitrary number of arguments in my Max(int num, ...) with ONLY arguments that needs to be compared in C? I'm using <code>va_list</code> from the C library <code>stdarg.h</code></p>
<p>I've read <a href="https://stackoverflow.com/questions/52663211/variable-number-of-arguments-in-c-programmng">Variable number of arguments in C programmng</a>, but sadly it seems that there aren't any answers that can help me. Since it is a post in 2018, I wonder if there is a solution to my problem after 4 years from then.</p>
<p>I'm using <code>va_list</code> from the C library <code>stdarg.h</code> to implement <code>Max()</code> . While looking for the maximal value, I have to use <strong>for loop</strong> to retrieve the arguments from the very first to the last. And that is where I get stuck.</p>
<p>My goal is to implement <code>Max()</code> with only arguments that needs to be compared their value. But I can't find a way to stop my <strong>for loop</strong> from executing after it reach to the last argument. The mostly seem solutions on the net for breaking the <strong>for loop</strong> are:</p>
<blockquote>
<ol>
<li>Adding an additional argument that represent <strong>the amount of arguments</strong> that you are passing in, which tells the <strong>for loop</strong> to loop for that amount of times</li>
<li>Passing in a number that the <strong>for loop</strong>'s condition part becomes <code>false</code> -> break out of the loop (In my code below, I pass the argument <code>-1</code> in as the last argument to my function. When the for loop sees that value, it knows it has arrived to the end of the argument)</li>
</ol>
</blockquote>
<p>But the above solutions both require an additional arguments, which I can't achieve my goal. So are there any solutions that can help me with my problem? Any response is appreciated :)</p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <stdarg.h> // this library is required for infinite number of arguments
int Max(int num, ...){
va_list ap;
int temp;
va_start(ap,num);
int maximum = num;
for(temp = va_arg(ap,int); temp!= -1/*put condition here */; temp = va_arg(ap, int)){
if(temp > maximum){
maximum = temp;
}
}
va_end(ap);
return maximum;
}
int main(){
int maximum;
printf("the input vals are: 1 3 4 6 3 78 100\n");
maximum = Max(1,3,4,6,3,78,100, -1);
printf("maximum val: %d\n",maximum);
}
</code></pre>
| [
{
"answer_id": 74243567,
"author": "n. m.",
"author_id": 775806,
"author_profile": "https://Stackoverflow.com/users/775806",
"pm_score": -1,
"selected": false,
"text": "Max"
},
{
"answer_id": 74244976,
"author": "Eric Postpischil",
"author_id": 298225,
"author_profile... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20293439/"
] |
74,243,169 | <p>I have these 13 columns:</p>
<p><a href="https://i.stack.imgur.com/MTBcd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MTBcd.png" alt="enter image description here" /></a></p>
<p>I want to split the 'Category' column into the testing set and the rest into the training set.
I'm using sklearn and sklearn works best with numerical values, thus I want 'Sex' column to be numeric.
I've done the following code to convert 'Sex' values (m or f) to numeric (1 and 0)</p>
<pre><code>#Convert categorical values in 'sex' column to numerical
from sklearn import preprocessing
le=preprocessing.LabelEncoder()
sex_new=sex_new.apply(le.fit_transform)
#Check the numerical values
sex_new.Sex.unique()
</code></pre>
<p>But I don't know how to proceed to the next step.
The original data seems didn't get affected by the changes from categorical to numerical.</p>
<p>Here is the full code of what I've done:</p>
<pre><code>import sys
import pandas as pd
import numpy as np
import sklearn
import matplotlib
import keras
import matplotlib.pyplot as plt
from pandas.plotting import scatter_matrix
#Data location
url='https://archive.ics.uci.edu/ml/machine-learning-databases/00571/hcvdat0.csv'
df=pd.read_csv(url)
df.head(2)
df.info()
#Drop the unnamed column
df_=df.drop("Unnamed: 0",axis=1)
df_.info()
#Assign 'sex' column into a variable
sex_new=df_.iloc[:, 2:3]
#How many unique values in 'sex_new'?
sex_new.Sex.unique()
#Convert categorical values in 'sex' column to numerical
from sklearn import preprocessing
le=preprocessing.LabelEncoder()
sex_new=sex_new.apply(le.fit_transform)
#Check the numerical values
sex_new.Sex.unique()
</code></pre>
<p>or should I just put both columns with dtype object into testing?</p>
<p>If you guys know any other best options to do training and testing to this dataset do share with me.</p>
| [
{
"answer_id": 74243567,
"author": "n. m.",
"author_id": 775806,
"author_profile": "https://Stackoverflow.com/users/775806",
"pm_score": -1,
"selected": false,
"text": "Max"
},
{
"answer_id": 74244976,
"author": "Eric Postpischil",
"author_id": 298225,
"author_profile... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14774516/"
] |
74,243,194 | <ol>
<li>Precondition: Data from a dataframe (<strong>dfold</strong>) is already saved to CSV file. The data looks like so:</li>
</ol>
<pre><code>import pandas as pd
columns = ['timestamp','base']
data = [['2022-10-14 11:47:38',100],
['2022-10-14 11:47:39',100],
['2022-10-14 11:47:40',100],
['2022-10-14 11:47:41',100],
['2022-10-14 11:47:42',200],
['2022-10-14 11:47:43',200],
['2022-10-14 11:47:44',300],
['2022-10-14 11:47:45',300]]
dfold = pd.DataFrame(data=data,columns=columns)
dfold.set_index(['timestamp'],inplace=True)
dfold['pbase'] = dfold['base'].shift(1).fillna(0)
dfold['pbase'] = dfold['pbase'].astype(int)
dfold['groupid'] = (dfold['base']!=dfold['pbase']).cumsum()
print('Print dfold\n',dfold)
</code></pre>
<pre><code>Print dfold:
base pbase groupid
timestamp
2022-10-14 11:47:38 100 0 1
2022-10-14 11:47:39 100 100 1
2022-10-14 11:47:40 100 100 1
2022-10-14 11:47:41 100 100 1
2022-10-14 11:47:42 200 100 2
2022-10-14 11:47:43 200 200 2
2022-10-14 11:47:44 300 200 3
2022-10-14 11:47:45 300 300 3
</code></pre>
<ol start="2">
<li>Data is logically grouped based on a column - groupid. Group id is created using cumsum(). The problem is that each new set of messages is again assigned groupids' starting from 1 instead of the highest no already assigned. This is illustrated by using a new dataframe (dfnew). The prior data in dataframe (dfold) is already saved to CSV file.</li>
</ol>
<pre><code>columns2 = ['timestamp','base']
data2 = [['2022-10-14 11:47:46',400],
['2022-10-14 11:47:47',400],
['2022-10-14 11:47:48',500],
['2022-10-14 11:47:49',500]]
dfnew = pd.DataFrame(data=data2,columns=columns2)
dfnew.set_index(['timestamp'],inplace=True)
dfnew['pbase'] = dfnew['base'].shift(1).fillna(0)
dfnew['pbase'] = dfnew['pbase'].astype(int)
dfnew['groupid'] = (dfnew['base']!=dfnew['pbase']).cumsum()
print('Print dfnew\n',dfnew)
</code></pre>
<pre><code>Print dfnew:
base pbase groupid
timestamp
2022-10-14 11:47:46 400 0 1
2022-10-14 11:47:47 400 400 1
2022-10-14 11:47:48 500 400 2
2022-10-14 11:47:49 500 500 2
</code></pre>
<ol start="3">
<li>The highest groupid allocated is retrieved like so:</li>
</ol>
<pre><code>maxgroupid = dfold['groupid'].max()
print('Max group id stored is: ',maxgroupid)
</code></pre>
<pre><code>Max group id stored is: 3
</code></pre>
<ol start="4">
<li>Problem: How do I reallocate unique group id - in this case starting with 4 - to the new messages in new dataframe (dfnew)? The expected result in dfnew is given below:</li>
</ol>
<pre><code>Expected result in dfnew:
base pbase groupid
timestamp
2022-10-14 11:47:46 400 0 4
2022-10-14 11:47:47 400 400 4
2022-10-14 11:47:48 500 400 5
2022-10-14 11:47:49 500 500 5
</code></pre>
<ol start="5">
<li>What I have tried to do to accomplish this but not succeeded so far:</li>
</ol>
<pre><code>grpnew = dfnew.groupby('groupid',as_index=True).max()
print('Grouped dfnew:\n',grpnew)
grpnew['newgroupid'] = range(maxgroupid + 1, maxgroupid + 1 + len(grpnew))
print('New groupid added to grouped dfnew:\n',grpnew)
dfboth = pd.merge(dfnew,grpnew,on='groupid',how='outer')
print(dfboth)
</code></pre>
<pre><code>**Grouped dfnew:**
base pbase
groupid
1 400 400
2 500 500
**New groupid added to grouped dfnew:**
base pbase newgroupid
groupid
1 400 400 4
2 500 500 5
**Merged output (unable to merge timestamp index)**
base_x pbase_x groupid base_y pbase_y newgroupid
0 400 0 1 400 400 4
1 400 400 1 400 400 4
2 500 400 2 500 500 5
3 500 500 2 500 500 5
</code></pre>
<ol start="5">
<li><strong>Issues:</strong></li>
</ol>
<p>(a) I am unable to get the timestamp index in the merged dataframe (<strong>dfboth</strong>)</p>
<p>(b) I am unsure if this is the most efficient method performance-wise</p>
<p>Please help in resolving (5) stated above. The expected result is shown in step 4 above (dfnew with new group ids - 4 and 5). Thank you.</p>
| [
{
"answer_id": 74252581,
"author": "plain",
"author_id": 20268123,
"author_profile": "https://Stackoverflow.com/users/20268123",
"pm_score": 0,
"selected": false,
"text": "import pandas as pd\ncolumns = ['timestamp','base']\ndata = [['2022-10-14 11:47:38',100],\n ['20... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20268123/"
] |
74,243,203 | <p>I can't set the size of an Elevated button in Flutter. I have tried enclosing it in a sized box but my code doesn't work. I'm not sure where the size is coming from but I can't change it.</p>
<p>Here's my code:</p>
<pre class="lang-dart prettyprint-override"><code> Widget build(BuildContext context) {
return SizedBox(
width: 60,
height: 60,
child: Padding(
padding: const EdgeInsets.only(top: 20, bottom: 20),
child: ElevatedButton(
onPressed: () {},
style: ElevatedButton.styleFrom(
elevation: 10,
backgroundColor: Colors.deepOrange,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30), // <-- Radius
),
padding: EdgeInsets.all(4),
),
child: Text(
table.tableNumber,
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.normal,
fontSize: 20,
),
overflow: TextOverflow.ellipsis,
maxLines: 1,
textAlign: TextAlign.left,
),
),
),
);
}
</code></pre>
<p>From my scaffold:</p>
<pre><code>class TablesShopView extends StatefulWidget {
const TablesShopView({super.key});
@override
State<StatefulWidget> createState() => TablesShopViewState();
}
class TablesShopViewState extends State<TablesShopView> {
@override
void initState() {
WidgetsBinding.instance.addPostFrameCallback((_) => showSnackBar(context));
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Theme.of(context).backgroundColor,
resizeToAvoidBottomInset: false,
body: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [appBackgroundColorStart, appBackgroundColorEnd],
begin: Alignment.topLeft,
end: Alignment.bottomRight),
),
child: Padding(
padding: const EdgeInsets.all(20.0),
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const SizedBox(height: 12),
const TablesShop(),
],
),
),
),
),
);
}
}
class TablesShop extends StatelessWidget {
const TablesShop({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return BaseWidget<TablesModel>(
model: TablesModel(api: Provider.of(context, listen: false)),
onModelReady: (model) => model.fetchTables(),
child: const SizedBox.shrink(),
builder: (context, model, child) => model.busy
? const Center(
child: CircularProgressIndicator(),
)
: GridView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
padding: const EdgeInsets.all(10.0),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisSpacing: 10.0,
mainAxisSpacing: 10.0,
crossAxisCount: 5,
// childAspectRatio: MediaQuery.of(context).size.width /
// (MediaQuery.of(context).size.width),
),
itemCount: model.tables.length,
itemBuilder: (context, index) => TableShopListItem(
table: model.tables[index],
),
),
);
}
}
</code></pre>
<p>edit: Because Gridview always maintains its aspect ratio as mentioned in the accepted answer below, the solution for me was to remove the sized box and elevated button dimensions completely and increase the circle radius to 300. With a grid <code>crossAxisCount</code> of 5, this maintained a perfect circle at any screen size. While the buttom size will change with the screen size that still works for me.</p>
| [
{
"answer_id": 74243237,
"author": "Yeasin Sheikh",
"author_id": 10157127,
"author_profile": "https://Stackoverflow.com/users/10157127",
"pm_score": 2,
"selected": true,
"text": "Wrap"
},
{
"answer_id": 74243525,
"author": "Siddharth Mehra",
"author_id": 16985146,
"au... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/951321/"
] |
74,243,243 | <p>I have the below data frame</p>
<p><a href="https://i.stack.imgur.com/485B2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/485B2.png" alt="enter image description here" /></a></p>
<p>Now I want to transfer the data frame like below
<a href="https://i.stack.imgur.com/UOaUO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UOaUO.png" alt="enter image description here" /></a></p>
<p>I have used the python commands to do that but none of them worked . Could anyone please help me with how to do that
df.loc[df.index.repeat(df.mas_id)].reset_index(drop=True)</p>
<p>n_df = pd.concat([df] * final_n)</p>
<p>newdf = pd.DataFrame(np.repeat(df.values, final_n, axis=0))</p>
| [
{
"answer_id": 74243285,
"author": "Vishnudev",
"author_id": 5120049,
"author_profile": "https://Stackoverflow.com/users/5120049",
"pm_score": 2,
"selected": false,
"text": "itertools"
},
{
"answer_id": 74243300,
"author": "alphaBetaGamma",
"author_id": 12959241,
"aut... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19856161/"
] |
74,243,250 | <pre><code>let obj = [
{ id : 1 },
{ id : 10 },
{ brand : 12 },
{ id : 15 },
{ id : 18 },
{ image_link : 'some link' },
{ price : 10 },
{ brand : 111 },
{ image_link : 'some link 2' }
];
</code></pre>
<p>I have this array of object. I want filter this object so that I can get an object without duplicate keys.</p>
<p><strong>I am trying this:</strong></p>
<pre><code>let uniqueIds = [];
let unique = obj.filter( (element ) => {
let key = Object.keys(element)[0];
let isDuplicate = uniqueIds.includes(element.key);
if (!isDuplicate) {
uniqueIds.push(element.key);
return true;
}
return false;
});
console.log( unique )
</code></pre>
<p>But everytime it's showing me :</p>
<pre><code>[ { id: 1 } ]
</code></pre>
<p><strong>My expected output:</strong></p>
<pre><code>[
{ id : 18 },
{ price : 10 },
{ brand : 111 },
{ image_link : 'some link 2' }
];
</code></pre>
| [
{
"answer_id": 74243275,
"author": "flyingfox",
"author_id": 3176419,
"author_profile": "https://Stackoverflow.com/users/3176419",
"pm_score": 1,
"selected": false,
"text": "key"
},
{
"answer_id": 74243281,
"author": "Nick",
"author_id": 9473764,
"author_profile": "ht... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1091439/"
] |
74,243,252 | <p>Iam using the row level security in supabase with nest.js, So how can I set runtime variables safely to the DB so that I can be sure that the variables sync with each app user (due to the http request triggered the execution)?</p>
<p>I saw that it is possible to set local variables in a transaction but I wouldn't like to wrap all the queries with transactions.</p>
<p>Thanks & Regards</p>
<p>I tried to execute this with subscribers in nestjs it working fine . but it wont have a function like beforeSelect or beforeLoad , so i drop it</p>
<pre><code>import { Inject, Injectable, Scope } from '@nestjs/common';
import { InjectDataSource } from '@nestjs/typeorm';
import { ContextService } from 'src/context/context.service';
import { DataSource, EntityManager, LoadEvent, RecoverEvent, TransactionRollbackEvent, TransactionStartEvent } from 'typeorm';
import {
EventSubscriber,
EntitySubscriberInterface,
InsertEvent,
UpdateEvent,
RemoveEvent,
} from 'typeorm';
@Injectable()
@EventSubscriber()
export class CurrentUserSubscriber implements EntitySubscriberInterface {
constructor(
@InjectDataSource() dataSource: DataSource,
private context: ContextService,
) {
dataSource.subscribers.push(this);
}
async setUserId(mng: EntityManager, userId: string) {
await mng.query(
`SELECT set_config('request.jwt.claim.sub', '${userId}', true);`,
);
}
async beforeInsert(event: InsertEvent<any>) {
try {
const userId = this.context.getRequest();
await this.setUserId(event.manager, userId);
} catch (err) {
console.log(err);
}
}
async beforeTransactionRollback(event: TransactionRollbackEvent) {
console.log('hello')
try {
const userId = this.context.getRequest();
await this.setUserId(event.manager, userId);
} catch (err) {
console.log(err);
}
}
async beforeUpdate(event: UpdateEvent<any>) {
try {
const userId = this.context.getRequest();
await this.setUserId(event.manager, userId);
} catch (err) {
console.log(err);
}
}
async beforeRemove(event: RemoveEvent<any>) {
try {
const userId = this.context.getRequest();
await this.setUserId(event.manager, userId);
} catch (err) {
console.log(err);
}
}
}
</code></pre>
<p>After i get to know that we can use query runner instead of subscriber . but its not working ,
also i need a common method to use all the queries</p>
<pre><code>import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Users } from 'src/common/entities';
import { DataSource, EntityManager, Repository } from 'typeorm';
@Injectable()
export class UsersService {
constructor(
@InjectRepository(Users) private userRepository: Repository<Users>,
private dataSource: DataSource,
private em: EntityManager,
) {}
getAllUsers(userId: string) {
const queryRunner = this.dataSource.createQueryRunner();
return new Promise(async (resolve, reject) => {
let res: any;
try {
await queryRunner.connect();
await queryRunner.manager.query(
// like this we can set the variable
`SELECT set_config('request.jwt.claim.sub', '${userId}', true);`,
);
// after setting config variable the query should return only one user by userId
res = await queryRunner.query('SELECT * FROM users');
// but it reurns every user
} catch (err) {
reject(err);
} finally {
await queryRunner.manager.query(`RESET request.jwt.claim.sub`);
await queryRunner.release();
resolve(res);
}
});
}
}
</code></pre>
<p>Thanks in advance....</p>
| [
{
"answer_id": 74244999,
"author": "Marcelo KortKamp",
"author_id": 5740546,
"author_profile": "https://Stackoverflow.com/users/5740546",
"pm_score": 1,
"selected": false,
"text": "/**\n * Note: Set current_tenant session var and executes a query on repository.\n * Usage:\n * const itens... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19120067/"
] |
74,243,267 | <p>I am getting Bad Request when trying to do POST to createCategory end point. All endpoint works but not for createCategory. Am i doing something wrong?</p>
<p>All my DTO classes using the same annotation but only this one doesn't work. Is it possible that spring doesn't accept single variable response body?</p>
<p>endpoint: http://localhost:8180/api/v1/categories</p>
<pre><code>request body in json:
{
"name": "Category 1"
}
</code></pre>
<p>CategoryController:</p>
<pre><code> @RestController
@RequiredArgsConstructor
@RequestMapping("api/v1/categories")
public class CategoryController {
private final CategoryApplicationService categoryApplicationService;
@PostMapping
public ResponseEntity<Data<CategoryIDResponse>> createCategory(@RequestBody CreateCategory createCategory){
return new ResponseEntity<>(new Data<>(categoryApplicationService.createCategory(createCategory)), HttpStatus.CREATED);
}
@PatchMapping
public ResponseEntity<Data<CategoryIDResponse>> updateCategory(@RequestBody UpdateCategory updateCategory){
return new ResponseEntity<>(new Data<>(categoryApplicationService.updateCategory(updateCategory)), HttpStatus.OK);
}
@DeleteMapping("/{categoryID}")
public ResponseEntity<Data<CategoryIDResponse>> deleteCategory(@PathVariable("categoryID") UUID categoryID){
return new ResponseEntity<>(new Data<>(categoryApplicationService.deleteCategory(categoryID)), HttpStatus.OK);
}
@GetMapping("/{categoryID}")
public ResponseEntity<Data<GetCategoryResponse>> getCategory(@PathVariable("categoryID") UUID categoryID){
return new ResponseEntity<>(new Data<>(categoryApplicationService.getCategory(categoryID)), HttpStatus.OK);
}
@GetMapping
public ResponseEntity<Data<List<GetCategoryResponse>>> getAllCategory(){
return new ResponseEntity<>(new Data<>(categoryApplicationService.getAllCategory()), HttpStatus.OK);
}
}
</code></pre>
<p>DTO:</p>
<pre><code>CreateCategory:
@Getter
@Builder
@AllArgsConstructor
public class CreateCategory {
@NotNull
private final String name;
}
</code></pre>
| [
{
"answer_id": 74244999,
"author": "Marcelo KortKamp",
"author_id": 5740546,
"author_profile": "https://Stackoverflow.com/users/5740546",
"pm_score": 1,
"selected": false,
"text": "/**\n * Note: Set current_tenant session var and executes a query on repository.\n * Usage:\n * const itens... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19467960/"
] |
74,243,291 | <pre><code>l1 = [{'_id': 0, 'type': 'int', 'name': 'one', 'des': 1},
{'_id': 1, 'type': 'int', 'name': 'two', 'des': 2},
{'_id': 2, 'type': 'int', 'name': 'one', 'des': 1},
{'_id': 3, 'type': 'int', 'name': 'five', 'des': 5}]
l2 = [{'g_id': 0, 'type': 'group1', 'name': 'first',},
{'g_id': 1, 'type': 'group2', 'name': 'second'},]
</code></pre>
<p>How do I group items like this? Referring to the previous two pieces of data, extract two items from list1 and group them with list2?</p>
<pre><code>group_result = [{'g_id': 0, 'type': 'group1', 'name': 'first',
'group':[{'_id': 0, 'type': 'int', 'name': 'one', 'des': 1},
{'_id': 1, 'type': 'int', 'name': 'two', 'des': 2}]},
{'g_id': 1, 'type': 'group1', 'name': 'first',
'group':[{'_id': 2, 'type': 'int', 'name': 'one', 'des': 1},
{'_id': 3, 'type': 'int', 'name': 'five', 'des': 5}]}]
</code></pre>
| [
{
"answer_id": 74244999,
"author": "Marcelo KortKamp",
"author_id": 5740546,
"author_profile": "https://Stackoverflow.com/users/5740546",
"pm_score": 1,
"selected": false,
"text": "/**\n * Note: Set current_tenant session var and executes a query on repository.\n * Usage:\n * const itens... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20363704/"
] |
74,243,304 | <p>Context of the problem - I want to migrate from the SQLite database to Postgres.
When I <code>makemigrations</code> with Postgres settings which are passed to the settings file with environment variables, I get KeyError; however, another variable from the same file does not cause any problems.</p>
<p>My secrets file:</p>
<pre><code>SECRET_KEY='secret key value'
DB_HOST='db host value'
DB_NAME='db name value'
DB_USER='db user value'
DB_PASS='db pass value'
DB_PORT='db port value'
</code></pre>
<p>My dev.py settings:</p>
<pre><code>from app.settings.base import *
import os
from dotenv import load_dotenv
import pprint
load_dotenv(os.environ.get('ENV_CONFIG', ''))
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
INSTALLED_APPS += [
]
MIDDLEWARE += [
]
env_var = os.environ
print("User's Environment variable:")
pprint.pprint(dict(env_var), width=1)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.environ['DB_NAME'],
'USER': os.environ['DB_USER'],
'PASSWORD': os.environ['DB_PASS'],
'HOST': os.environ['DB_HOST'],
'PORT': os.environ['DB_PORT'],
}
}
</code></pre>
<p>As you see, I import all the content from my base settings file - app.settings.base, where I use my secret key (in the same way as I read my environment variables for database):</p>
<pre><code>SECRET_KEY = os.environ.get('SECRET_KEY', '')
</code></pre>
<p>I use SQLite in my base.py settings and want to use Postgres in my dev.py.</p>
<p>However, when I try to <code>./manage.py makemigrations --settings=app.settings.dev</code>, I get the error:</p>
<pre><code> File "/Users/admin/Desktop/Programming/Python/UkranianFunds/src/app/settings/dev.py", line 39, in <module>
'NAME': os.environ['DB_NAME'],
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/os.py", line 679, in __getitem__
raise KeyError(key) from None
KeyError: 'DB_NAME'
</code></pre>
<p>But when I print all the environment variables in dev.py like this:</p>
<pre><code>env_var = os.environ
print("User's Environment variable:")
pprint.pprint(dict(env_var), width=1)
</code></pre>
<p>I see that all my database variables are being printed and the values are correct!
So on the level when I just run the app, and print being called - all the variables are there.
But when I do <code>makemigrations</code> - it couldn't find the same variable by key.</p>
<p>However, when I tried to set database settings with just plain text (copied from .env file) - everything worked.</p>
<p>What could be an issue in using environment variables when doing <code>makemigrations</code>?</p>
| [
{
"answer_id": 74244999,
"author": "Marcelo KortKamp",
"author_id": 5740546,
"author_profile": "https://Stackoverflow.com/users/5740546",
"pm_score": 1,
"selected": false,
"text": "/**\n * Note: Set current_tenant session var and executes a query on repository.\n * Usage:\n * const itens... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1512250/"
] |
74,243,306 | <p>I have the dataframe below:</p>
<pre><code>
details = {
'container_id' : [1, 2, 3, 4, 5, 6 ],
'container' : ['black box', 'orange box', 'blue box', 'black box','blue box', 'white box'],
'fruits' : ['apples, black currant', 'oranges','peaches, oranges', 'apples','apples, peaches, oranges', 'black berries, peaches, oranges, apples'],
}
# creating a Dataframe object
df = pd.DataFrame(details)
</code></pre>
<p>I want to find the frequency of each fruit separately on a list.</p>
<p>I tried this code</p>
<p><code>df['fruits'].str.split(expand=True).stack().value_counts()</code></p>
<p>but I get the black count 2 times instead of 1 for black currant and 1 for black berries.</p>
| [
{
"answer_id": 74243334,
"author": "ScottC",
"author_id": 20174226,
"author_profile": "https://Stackoverflow.com/users/20174226",
"pm_score": 0,
"selected": false,
"text": "df['fruits'].str.split(',\\s?', expand=True).stack().value_counts()"
},
{
"answer_id": 74243379,
"autho... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19965698/"
] |
74,243,322 | <p>I want to download pdf directly from api response but the format that i am getting from api response is this :</p>
<blockquote>
<p>%PDF-1.7 1 0 obj << /Type /Catalog /Outlines 2 0 R /Pages 3 0 R >>
endobj 2 0 obj << /Type /Outlines /Count 0 >> endobj 3 0 obj << /Type
/Pages /Kids [6 0 R 9 0 R ] /Count 2 /Resources << /ProcSet 4 0 R
/Font << /F1 8 0 R /F2 11 0 R</p>
<blockquote>
<blockquote>
<p>/MediaBox [0.000 0.000 595.280 841.890]
endobj 4 0 obj [/PDF /Text ] endobj 5 0 obj << /Producer (��dompdf 1.2.1 + CPDF) /CreationDate
(D:20221029062939+00'00') /ModDate (D:20221029062939+00'00')
endobj 6 0 obj << /Type /Page /MediaBox [0.000 0.000 595.280 841.890] /Parent 3 0 R /Contents 7 0 R
endobj 7 0 obj << /Filter /FlateDecode /Length 189 >> stream x�u��J�@F�<�W���3���"��N,B2w�$˾�R����;�[HB<code>���І�t�=V1)�����s�XR�v�ի�:&v�9g<>KHAa�^S����Mc�us<| ��)lef2B��m�c̸&(Y�;_R.Ѵ��Zk�ZƐ�~��ˀ�Y������n�%��|/QO�J���P� endstream endobj 8 0 obj << /Type /Font /Subtype /Type1 /Name /F1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding endobj 9 0 obj << /Type /Page /MediaBox [0.000 0.000 595.280 841.890] /Parent 3 0 R /Contents 10 0 R endobj 10 0 obj << /Filter /FlateDecode /Length 949 >> stream x��W�n�F}�WHk��K��$N�)�XA�>0��&B�I���wIi�2d]A��Μ���g�IΡ�Yߞ ����?*�p�2�1�8��7�7g$٫��3g8�</code>��+�������
�?υV/���{�\�JZ&�Dv�4�{���c�͗�YɄ h~_mʶ�ќ3��f���8ôt?
o6��ɜ��4�s�����6=�e��D<code>VP%{�m�|��XV]���c$<S�*�"g�ͤ�\�r����t.Qi��=��N �r�!��]?Q���{�bwpĻ2o��ϗ0�)i�tfI�if �1�KG@��b��ME�?���mK��cg���DMfB̸F _g�2E\��4������>=f� h:%�QU���T|���"��z�Y���ͫrP�$ӹ&�fD�j�[H/xWn+\5��q��?l�Э0m�{L��? I7��0�������N�3KBN3;*�-��}�]���MB�栄��9һF*�&Hf��$-V�r5�3�-Vk�GzÜn�=����5�訪,(��Zl�i�bӠ����<7��8]���$A�L tG��4i�S�I3 ��%�?e<�QsQ�Y�\[3V�4(-��@a/��̓>yUĬ�x۹�[Xg��w��V�����*��a���jUǦyIQs<ϓ�vU-������}��H�e�L��'<N���!˱#��^ge���۪�v�൵�:�/�E��|y.�����3|�</code>�W@r����c�ϋ���x��"�I�QIj�����j�w��t�]p�X�*/�g�e�p�\�>����%ʜ7�������w���$#��8)աk��Ep̓<em>��ŎH�N��R��+����</em>�ɕ�X�����
&I52���\�z̷�����oc��+||=��ž�� �pM�'��s���]�X�$�ԭk�d����I
endstream endobj 11 0 obj << /Type /Font /Subtype /Type1 /Name /F2
/BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding
endobj xref 0 12 0000000000 65535 f 0000000009 00000 n 0000000074 00000 n 0000000120 00000 n 0000000291 00000 n 0000000320 00000 n
0000000469 00000 n 0000000572 00000 n 0000000833 00000 n 0000000940
00000 n 0000001044 00000 n 0000002066 00000 n trailer << /Size 12
/Root 1 0 R /Info 5 0 R
/ID[<71468b7d13dde79b89173b27b85d8251><71468b7d13dde79b89173b27b85d8251>]
startxref 2179 %%EOF</p>
</blockquote>
</blockquote>
</blockquote>
<p>So any one has idea how to download this kind of file directly!</p>
<p>I tried using</p>
<pre><code>fileDownload(apiCall.data, `customer-${payload.customer_id}.pdf`);
</code></pre>
| [
{
"answer_id": 74243334,
"author": "ScottC",
"author_id": 20174226,
"author_profile": "https://Stackoverflow.com/users/20174226",
"pm_score": 0,
"selected": false,
"text": "df['fruits'].str.split(',\\s?', expand=True).stack().value_counts()"
},
{
"answer_id": 74243379,
"autho... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20363858/"
] |
74,243,360 | <p>Null check operator used on a null value in calendar! i am assigning calendar with ? mark then the this null operator error is occurring and when i am adding the late calendar LateInitializationError: Field '_calendar@94028380' has not been initialized error is getting</p>
<pre><code>class MedicationListChild extends StatefulWidget {
final String? medicationName;
final String? medicationUID;
final String? childUid;
final String? childName;
final Calendar? calendar;
const MedicationListChild({
Key? key,
this.medicationName,
this.medicationUID,
this.childUid,
this.childName,
this.calendar,
}) : super(key: key);
@override
_MedicationListChildState createState() => _MedicationListChildState();
}
class _MedicationListChildState extends State<MedicationListChild> {
Calendar? _calendar;
@override
void initState() => super.initState();
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(top: 7.0),
child: Card(
elevation: 3.0,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(7.0)),
child: InkWell(
splashColor: Colors.blue,
highlightColor: Colors.green,
onTap: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => CalendarEventPage(_calendar!),
),
);
},
</code></pre>
| [
{
"answer_id": 74243381,
"author": "My Car",
"author_id": 16124033,
"author_profile": "https://Stackoverflow.com/users/16124033",
"pm_score": 1,
"selected": false,
"text": "class MedicationListChild extends StatefulWidget {\n final String? medicationName;\n final String? medicationUID;... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20061332/"
] |
74,243,385 | <p>I am exploring cloud monitoring and unable to understand, how to show my dataset as a report on cloud monitoring.</p>
| [
{
"answer_id": 74243381,
"author": "My Car",
"author_id": 16124033,
"author_profile": "https://Stackoverflow.com/users/16124033",
"pm_score": 1,
"selected": false,
"text": "class MedicationListChild extends StatefulWidget {\n final String? medicationName;\n final String? medicationUID;... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,243,399 | <p>I am using a very extensive formula to remove all words from a string that start with lowercase letters and contains numerous special characters and other signs and symbols. The goal is to end up with only words that start with uppercase letters (if two words start with uppercase letters right after each other, then they are counted as one word).
For example</p>
<p>This is the input</p>
<blockquote>
<p>Obama Mama told: Reporters in 19. Washington-Post in That he and Netanyahu-lll
are opposed to Iran's calls for "Death To America".</p>
</blockquote>
<p>And this is the expected output</p>
<blockquote>
<p>Obama Mama, Reporters, Washington-Post, That, Netanyahu-lll, Irans, Death To
America</p>
</blockquote>
<p>And this is the formula</p>
<pre><code>=Regexreplace(REGEXREPLACE(REGEXREPLACE(REGEXREPLACE(REGEXREPLACE(INDEX(TEXTJOIN(" "; 1; LAMBDA(x;IF(REGEXMATCH(x&"";"(^[0-9a-zäüö])");"_";x))(SPLIT(G7;" "&CHAR(10)))));"(.*)\/|\|.*|\(.*\) |\.|»| - .*$| – |!|\?|\+|\„|\“|%| \& | \& |'|»|«|""";"");"(:| --)";" _");"(^[_\s]+|[\s_]+$)";"");"\s_+";",");"([,]+|,\s)";",")
</code></pre>
<p>This also works very well. I just wonder if there isn't a simpler way that just extracts all the words with capital letters.</p>
<p>Is there such a thing as a multiple REGEXEXTRACT?
This one is only extracting the first word:</p>
<pre><code>=regexextract(G7;"\b[A-Z].*?\b")
</code></pre>
| [
{
"answer_id": 74244066,
"author": "player0",
"author_id": 5632629,
"author_profile": "https://Stackoverflow.com/users/5632629",
"pm_score": -1,
"selected": false,
"text": "=INDEX(TEXTJOIN(\", \", 1, LAMBDA(x, \n IFERROR(IF(REGEXMATCH(x, \"^[a-z]\"),,x)))\n (SPLIT(REGEXREPLACE(A1, \"[\"\... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3392296/"
] |
74,243,405 | <p>I have a table like this</p>
<pre><code>userId story novel
1 a b
1 a b
1 a c
1 b c
1 b c
2 x x
2 x y
2 y y
3 m n
4 NULL NULL
</code></pre>
<p>How do I find the most story and novel count per user?</p>
<p>What I am looking for is the highest distinct count of story and novel for each user. So if a user has no story then story_count should be 0.</p>
<p>Desired output looks like this</p>
<pre><code>userId story story_count novel novel_count
1 a 3 c 3
2 x 2 y 2
3 m 1 n 1
4 NULL 0 NULL 0
</code></pre>
<p>This is my faulty current attempt</p>
<pre><code>SELECT userId, story, COUNT(story) as story_count, novel, COUNT(novel) as novel_count
FROM logs WHERE user = (SELECT DISTINCT(user)) GROUP BY story, novel;
</code></pre>
| [
{
"answer_id": 74243492,
"author": "Gerballi",
"author_id": 20358885,
"author_profile": "https://Stackoverflow.com/users/20358885",
"pm_score": 0,
"selected": false,
"text": "\nselect story.userid, story, story_count, novel, novel_count \nfrom\n (\n select userid, story, count(... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8805742/"
] |
74,243,423 | <p>In Windows environment, jmeter is used to stress test the local springboot web project. The command line input is:</p>
<p><strong>D:\software\apache-jmeter-5.5\bin>jmeter -n -t D:\software\apache-jmeter-5.5\test\test1.jmx -l D:\software\apache-jmeter-5.5\test\result.txt -e -o D:\software\apache-jmeter-5.5\test</strong></p>
<p>The execution result is:</p>
<p><strong>Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8
Unrecognized option: --add-opens
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
errorlevel=1</strong></p>
<p>Java version is 1.8.0_102. Jmeter version is 5.5. How to solve it?</p>
| [
{
"answer_id": 74243492,
"author": "Gerballi",
"author_id": 20358885,
"author_profile": "https://Stackoverflow.com/users/20358885",
"pm_score": 0,
"selected": false,
"text": "\nselect story.userid, story, story_count, novel, novel_count \nfrom\n (\n select userid, story, count(... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19958859/"
] |
74,243,428 | <p>How can i solve the TypeError</p>
<p>I tried this:</p>
<pre><code>print("Multiplication Calculator for Kids")
onenum = input("Enter a number")
twonum = input("Enter a second number")
calc = onenum * twonum
print(calc)
</code></pre>
| [
{
"answer_id": 74243492,
"author": "Gerballi",
"author_id": 20358885,
"author_profile": "https://Stackoverflow.com/users/20358885",
"pm_score": 0,
"selected": false,
"text": "\nselect story.userid, story, story_count, novel, novel_count \nfrom\n (\n select userid, story, count(... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19821405/"
] |
74,243,452 | <p>I currently have the following VBA code to automatically push the body of Outlook appointments into MySQL.
The two calendars listened to here in the example are (in reality I need many calendars and some may be created dynamically):</p>
<pre><code>Default Calendar
MYCALENDAR2
</code></pre>
<p>Whenever a new appointment is entered into either calendar or changed in either calendar, the BODY of the appointment will be pushed automatically into MySQL table called <strong>report</strong> under the column called <strong>BODY</strong>.</p>
<p>This is the code I place under Project 1 -> Microsoft Outlook Objects -> ThisOutlookSession:</p>
<pre><code>Option Explicit
Private objNS As Outlook.NameSpace
Private WithEvents objItems As Outlook.Items
Private WithEvents objItems2 As Outlook.Items
Private Sub Application_Startup()
Set objNS = Application.GetNamespace("MAPI")
'Set the folder and items to watch:
' Set objWatchFolder = objNS.GetDefaultFolder(olFolderCalendar)
' Set objItems = objWatchFolder.Items
Dim objWatchFolder As Outlook.Folder
Set objWatchFolder = objNS.GetDefaultFolder(olFolderCalendar)
Set objItems = objWatchFolder.Items
Dim objWatchFolder2 As Outlook.Folder
' Set objWatchFolder2 = objNS.Folders("MYCALENDAR2").Folders("MYCALENDAR3").Folders("MYCALENDAR4").Folders("MYCALENDAR5").Folders("MYCALENDAR6")
Set objWatchFolder2 = objNS.GetDefaultFolder(olFolderCalendar).Folders("MYCALENDAR2")
Set objItems2 = objWatchFolder2.Items
' Set objItems2 = objWatchFolder.Items
' Set objItems2 = objNS.GetDefaultFolder(olFolderCalendar).Folders("MYCALENDAR2").Items
Set objWatchFolder = Nothing
End Sub
Private Sub objItems_ItemAdd(ByVal Item As Object)
MsgBox "*** PROPERTIES of olFolderCalendar ***" & vbNewLine & _
"Subject: " & Item.Subject & vbNewLine & _
"Start: " & Item.Start & vbNewLine & _
"End: " & Item.End & vbNewLine & _
"Duration: " & Item.Duration & vbNewLine & _
"Location: " & Item.Location & vbNewLine & _
"Body: " & Item.Body & vbNewLine & _
"Global Appointment ID: " & Item.GlobalAppointmentID
send2mysql Item
Set Item = Nothing
End Sub
Private Sub objItems_ItemChange(ByVal Item As Object)
MsgBox "*** PROPERTIESS of olFolderCalendar ***" & vbNewLine & _
"Subject: " & Item.Subject & vbNewLine & _
"Start: " & Item.Start & vbNewLine & _
"End: " & Item.End & vbNewLine & _
"Duration: " & Item.Duration & vbNewLine & _
"Location: " & Item.Location & vbNewLine & _
"Body: " & Item.Body & vbNewLine & _
"Global Appointment ID: " & Item.GlobalAppointmentID
send2mysql Item
Set Item = Nothing
End Sub
Private Sub objItems2_ItemAdd(ByVal Item As Object)
MsgBox "*** PROPERTIES of olFolderCalendar ***" & vbNewLine & _
"Subject: " & Item.Subject & vbNewLine & _
"Start: " & Item.Start & vbNewLine & _
"End: " & Item.End & vbNewLine & _
"Duration: " & Item.Duration & vbNewLine & _
"Location: " & Item.Location & vbNewLine & _
"Body: " & Item.Body & vbNewLine & _
"Global Appointment ID: " & Item.GlobalAppointmentID
send2mysql Item
Set Item = Nothing
End Sub
Private Sub objItems2_ItemChange(ByVal Item As Object)
MsgBox "*** PROPERTIESS of olFolderCalendar ***" & vbNewLine & _
"Subject: " & Item.Subject & vbNewLine & _
"Start: " & Item.Start & vbNewLine & _
"End: " & Item.End & vbNewLine & _
"Duration: " & Item.Duration & vbNewLine & _
"Location: " & Item.Location & vbNewLine & _
"Body: " & Item.Body & vbNewLine & _
"Global Appointment ID: " & Item.GlobalAppointmentID
send2mysql Item
Set Item = Nothing
End Sub
Sub send2mysql(ByVal Item As Object)
Dim updSQL As String
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
Dim rs As ADODB.Recordset
Dim strConn As String
strConn = "Driver={MySQL ODBC 8.0 ANSI Driver};Server=localhost; Database=thairis; UID=root; PWD=root"
cn.Open strConn
updSQL = "INSERT INTO report (BODY) VALUES ('" & Item.Body & "')"
cn.Execute updSQL
MsgBox updSQL
MsgBox "Done"
End Sub
</code></pre>
<p>The code is rather redundant.<br />
<strong>In reality I have say 10 calendars (for example MYCALENDAR3, MYCALENDAR4 .. , MYCALENDAR9) and I may real time decide to add in new calendars</strong>.</p>
<p>How do I tidy up the code above so that it is more compact/flexible, plus can automatically cycle through <strong>all calendars</strong> and apply _ItemAdd and _ItemChange to each calendar automatically?
I do not want to hard code actual calendar names, because in practice <strong>I may decide to add new calendars from time to time</strong>. I'd like the VB code to always cycle through all available calendars and listen automatically to all.</p>
<p>How should the above code be re-written exactly please? Thank you.</p>
<p>I tried this:</p>
<pre><code>Set objWatchFolder2 = objNS.Folders("MYCALENDAR2").Folders("MYCALENDAR3").Folders("MYCALENDAR4").Folders("MYCALENDAR5").Folders("MYCALENDAR6")
</code></pre>
<p>and it did not work. Therefore I have commented it out in the code now.</p>
<p><strong>QUESTION: How to dynamically listen for _ItemAdd and ItemChange in all calendars?</strong></p>
<p>I use Outlook 2019 offline mode on Desktop.
Windows 10 (64 bit).</p>
<p>PS:
I have read some links about enumerate and Folder.DefaultItemType property, but I do not know how exactly to apply it to my code. . . (as following):</p>
<p><a href="https://learn.microsoft.com/en-us/office/vba/outlook/how-to/navigation/enumerate-active-folders-in-the-calendar-view" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/office/vba/outlook/how-to/navigation/enumerate-active-folders-in-the-calendar-view</a></p>
<p><a href="https://learn.microsoft.com/en-us/office/vba/api/outlook.folder.defaultitemtype" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/office/vba/api/outlook.folder.defaultitemtype</a></p>
<pre><code>Dim WithEvents objPane As NavigationPane
Private Sub EnumerateActiveCalendarFolders()
Dim objModule As CalendarModule
Dim objGroup As NavigationGroup
Dim objFolder As NavigationFolder
Dim intCounter As Integer
On Error GoTo ErrRoutine
' Get the NavigationPane object for the
' currently displayed Explorer object.
Set objPane = Application.ActiveExplorer.NavigationPane
' Get the CalendarModule object, if one exists,
' for the current Navigation Pane.
Set objModule = objPane.Modules.GetNavigationModule(olModuleCalendar)
' Iterate through each NavigationGroup contained
' by the CalendarModule.
For Each objGroup In objModule.NavigationGroups
' Iterate through each NavigationFolder contained
' by the NavigationGroup.
For Each objFolder In objGroup.NavigationFolders
' Check if the folder is selected.
If objFolder.IsSelected Then
intCounter = intCounter + 1
End If
Next
Next
' Display the results.
MsgBox "There are " & intCounter & " selected calendars in the Calendar module."
EndRoutine:
On Error GoTo 0
Set objFolder = Nothing
Set objGroup = Nothing
Set objModule = Nothing
Set objPane = Nothing
intCounter = 0
Exit Sub
ErrRoutine:
MsgBox Err.Number & " - " & Err.Description, _
vbOKOnly Or vbCritical, _
"EnumerateActiveCalendarFolders"
End Sub
</code></pre>
<p><strong>ADDENDUM</strong></p>
<p>I read the link provided:
<a href="https://stackoverflow.com/questions/73881358/run-code-when-new-email-comes-to-any-subfolder-in-a-shared-mailbox">Run code when new email comes to any subfolder in a Shared Mailbox</a></p>
<p>It is for Mail, not Calendar.
I tried to adopt the code from it to use for Outlook Calendar. This is the code I came up with (for Calendar):</p>
<pre><code>Dim myRecipient As Outlook.Recipient
Dim oFolder As Outlook.Folder
Dim objOwner As Outlook.Recipient
Set objOwner = objNS.CreateRecipient("my_Shared_Mailibox")
objOwner.Resolve
Set oFolder = objNS.GetSharedDefaultFolder(objOwner, olFolderCalendar)
Set colFolders = New Collection
processFolder oFolder
</code></pre>
<p>In addition I have put the following in Class Module:</p>
<pre><code>Option Explicit
Private OlFldr As Folder
Public WithEvents Items As Outlook.Items
'called to set up the object
Public Sub Init(f As Folder) ', sPath As String)
Set OlFldr = f
Set Items = f.Items
End Sub
Private Sub Items_ItemAdd(ByVal Item As Object)
If TypeOf Item Is Outlook.CalendarItem Then
Debug.Print "eMail '" & Item.Subject & "' was added to Folder '" & OlFldr.Name & _
"'. Mailbox: '" & Item.Parent.Store & "'."
'do sth with a email added...
End If
End Sub
</code></pre>
<p>However when I run , I get this error message:</p>
<blockquote>
<p>Run-time error '-2147352567(B80020009)': Outlook does not recognize
one or more names</p>
</blockquote>
<p>When I click "Debug". This following line is highlighted in yellow:</p>
<blockquote>
<p>Set oFolder = objNS.GetSharedDefaultFolder(objOwner, olFolderCalendar)</p>
</blockquote>
| [
{
"answer_id": 74243492,
"author": "Gerballi",
"author_id": 20358885,
"author_profile": "https://Stackoverflow.com/users/20358885",
"pm_score": 0,
"selected": false,
"text": "\nselect story.userid, story, story_count, novel, novel_count \nfrom\n (\n select userid, story, count(... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7734363/"
] |
74,243,458 | <p>So, I have this page where navbar/header is included in the hero section.
In the hero section the navbar/header is transparent.
When it scrolls to different sections, I want it to change background color also the navlinks should change style depending on which section it is on.</p>
<p>The navlink color change works fine however the header/navbar background color change is not working. I have used plain JS for all these effects. But can't figure out why the background color change is not working.
What have I got wrong??
Edit: I tried to console.log on my js and got this "
main.js:68 Uncaught TypeError: Cannot read properties of undefined (reading 'add')
at HTMLDocument.navbarChange"</p>
<p>Could someone please explain?</p>
<p>index.html</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta content="width=device-width, initial-scale=1.0" name="viewport" />
<title>Test</title>
<meta content="" name="description" />
<meta content="" name="keywords" />
<!-- Favicons -->
<link href="assets/img/log.ico" rel="icon" />
<!-- Google Fonts -->
<link
href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Montserrat:300,300i,400,400i,500,500i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i"
rel="stylesheet"
/>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@200;300;400;500;600;700;800;900&family=Merriweather:ital,wght@0,300;0,400;0,700;1,300;1,400;1,700;1,900&display=swap" rel="stylesheet">
<!-- Vendor CSS Files -->
<link href="assets/vendor/aos/aos.css" rel="stylesheet" />
<link
href="assets/vendor/bootstrap/css/bootstrap.min.css"
rel="stylesheet"
/>
<link
href="assets/vendor/bootstrap-icons/bootstrap-icons.css"
rel="stylesheet"
/>
<link href="assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet" />
<link
href="assets/vendor/glightbox/css/glightbox.min.css"
rel="stylesheet"
/>
<link href="assets/vendor/swiper/swiper-bundle.min.css" rel="stylesheet" />
<!-- Template Main CSS File -->
<link href="assets/css/style.css" rel="stylesheet" />
</head>
<body>
<!-- ======= Hero Section ======= -->
<section id="hero">
<!-- ======= Header ======= -->
<header id="header" class="d-flex align-items-center fixed-top">
<div class="container d-flex align-items-center justify-content-between">
<div class="logo">
<a href="index.html"><h1>Test.</h1></a>
</div>
<nav id="navbar" class="navbar">
<ul>
<li><a class="nav-link scrollto active" href="#hero">Home</a></li>
<li><a class="nav-link scrollto" href="#services">Services</a></li>
<li><a class="nav-link scrollto" href="#feature">Featured</a></li>
<li><a class="nav-link scrollto" href="#pricing">Pricing</a></li>
<li><a class="nav-link scrollto" href="#faq">FAQ</a></li>
<li><a class="nav-link scrollto" href="#contact">Contact</a></li>
<li><a href="#" class="nav-link"><button type="button" class="btn btn-outline-dark rounded-pill">Log In</button></a></li>
<li><a href="#" class="nav-link"><button type="button" class="btn btn-primary rounded-pill">Book a Demo</button></a></li>
</ul>
<i class="bi bi-list mobile-nav-toggle"></i>
</nav>
<!-- .navbar -->
</div>
</header>
<!-- End Header -->
<div class="hero-container">
</div>
</section>
<!-- End Hero -->
<main>
<section id="services" class="section services">
</section>
</main>
<footer>
<footer>
<!-- Vendor JS Files -->
<script src="assets/vendor/aos/aos.js"></script>
<script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="assets/vendor/glightbox/js/glightbox.min.js"></script>
<script src="assets/vendor/isotope-layout/isotope.pkgd.min.js"></script>
<script src="assets/vendor/ email-form/validate.js"></script>
<script src="assets/vendor/swiper/swiper-bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/typed.js/2.0.11/typed.min.js"
integrity="sha512-BdHyGtczsUoFcEma+MfXc71KJLv/cd+sUsUaYYf2mXpfG/PtBjNXsPo78+rxWjscxUYN2Qr2+DbeGGiJx81ifg=="
crossorigin="anonymous"></script>
<!-- Template Main JS File -->
<script src="assets/js/main.js"></script>
</body>
</html>
</code></pre>
<p>style.css</p>
<pre><code>#header {
height: 90px;
transition: all 0.5s;
z-index: 997;
transition: all 0.5s;
background: transparent;
box-shadow: 0 4px 10px -3px rgba(191, 191, 191, 0.5);
}
#header .colorful {
background: linear-gradient(
305deg,
#d8eae5,
#e0ece9,
#f9e9a7,
#f4f6fb,
#fdebe9,
#fff
);
background-size: 1000% 1000%;
-webkit-animation: live-gradient 17s ease infinite;
-moz-animation: live-gradient 17s ease infinite;
animation: live-gradient 17s ease infinite;
position: relative;
}
</code></pre>
<p>main.js</p>
<pre><code>(function() {
"use strict";
/**
* Easy selector helper function
*/
const select = (el, all = false) => {
el = el.trim()
if (all) {
return [...document.querySelectorAll(el)]
} else {
return document.querySelector(el)
}
}
/**
* Easy event listener function
*/
const on = (type, el, listener, all = false) => {
let selectEl = select(el, all)
if (selectEl) {
if (all) {
selectEl.forEach(e => e.addEventListener(type, listener))
} else {
selectEl.addEventListener(type, listener)
}
}
}
/**
* Easy on scroll event listener
*/
const onscroll = (el, listener) => {
el.addEventListener('scroll', listener)
}
/**
* Navbar links active state on scroll
*/
let navbarlinks = select('#navbar .scrollto', true)
const navbarlinksActive = () => {
let position = window.scrollY + 200
navbarlinks.forEach(navbarlink => {
if (!navbarlink.hash) return
let section = select(navbarlink.hash)
if (!section) return
if (position >= section.offsetTop && position <= (section.offsetTop + section.offsetHeight)) {
navbarlink.classList.add('active')
} else {
navbarlink.classList.remove('active')
}
})
}
/**
* Navbar color change after first section
*/
window.addEventListener('load', navbarlinksActive)
onscroll(document, navbarlinksActive)
let header = select('#header',true)
const navbarChange = () => {
let position = window.scrollY
if(position > window.innerHeight){
header.classList.add('colorful')
}else{
header.classList.remove('colorful')
}
}
window.addEventListener('load', navbarChange)
onscroll(document, navbarChange)
/**
* Scrolls to an element with header offset
*/
const scrollto = (el) => {
let header = select('#header')
let offset = header.offsetHeight
if (!header.classList.contains('header-scrolled')) {
offset -= 16
}
let elementPos = select(el).offsetTop
window.scrollTo({
top: elementPos - offset,
behavior: 'smooth'
})
}
/**
* Back to top button
*/
let backtotop = select('.back-to-top')
if (backtotop) {
const toggleBacktotop = () => {
if (window.scrollY > 100) {
backtotop.classList.add('active')
} else {
backtotop.classList.remove('active')
}
}
window.addEventListener('load', toggleBacktotop)
onscroll(document, toggleBacktotop)
}
/**
* Mobile nav toggle
*/
on('click', '.mobile-nav-toggle', function(e) {
select('#navbar').classList.toggle('navbar-mobile')
this.classList.toggle('bi-list')
this.classList.toggle('bi-x')
})
/**
* Mobile nav dropdowns activate
*/
on('click', '.navbar .dropdown > a', function(e) {
if (select('#navbar').classList.contains('navbar-mobile')) {
e.preventDefault()
this.nextElementSibling.classList.toggle('dropdown-active')
}
}, true)
/**
* Scroll with ofset on links with a class name .scrollto
*/
on('click', '.scrollto', function(e) {
if (select(this.hash)) {
e.preventDefault()
let navbar = select('#navbar')
if (navbar.classList.contains('navbar-mobile')) {
navbar.classList.remove('navbar-mobile')
let navbarToggle = select('.mobile-nav-toggle')
navbarToggle.classList.toggle('bi-list')
navbarToggle.classList.toggle('bi-x')
}
scrollto(this.hash)
}
}, true)
/**
* Scroll with ofset on page load with hash links in the url
*/
window.addEventListener('load', () => {
if (window.location.hash) {
if (select(window.location.hash)) {
scrollto(window.location.hash)
}
}
});
/**
* Animation on scroll
*/
window.addEventListener('load', () => {
AOS.init({
duration: 1000,
easing: 'ease-in-out',
once: true,
mirror: false
})
});
})()
</code></pre>
| [
{
"answer_id": 74243527,
"author": "Asif Jalil",
"author_id": 15974978,
"author_profile": "https://Stackoverflow.com/users/15974978",
"pm_score": -1,
"selected": false,
"text": "#header.colorful {\n background: linear-gradient(\n 305deg,\n #d8eae5,\n #e0ece9,\n #f9e9a7,\n ... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19367608/"
] |
74,243,468 | <p>Im doing unit testing and want to test my functions against each possible combinations of flags. Each flag can be either a 1 or a 0. the flags are global variables.</p>
<p>This is what I tried:</p>
<p>`</p>
<pre><code>for(flagA = 0; flagA <= 1; ++flagA){
for(flagB = 0; flagB <= 1; ++flagB){
for(flagC = 0; flabC <= 1; ++flagC){
for(flagD = 0; flagD <= 1; ++flagD){
myFunction();
}
}
}
};
</code></pre>
<p>`</p>
<p>The issue I am having is myFunction() can change a flags value, causing the other calls of myFunction() to be called with unexpected flag values rather than testing every combination.</p>
| [
{
"answer_id": 74243527,
"author": "Asif Jalil",
"author_id": 15974978,
"author_profile": "https://Stackoverflow.com/users/15974978",
"pm_score": -1,
"selected": false,
"text": "#header.colorful {\n background: linear-gradient(\n 305deg,\n #d8eae5,\n #e0ece9,\n #f9e9a7,\n ... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13277845/"
] |
74,243,499 | <p>Excel only provide below Rounding modes.
<a href="https://i.stack.imgur.com/92RDS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/92RDS.png" alt="enter image description here" /></a></p>
<p>But how can I round a value to HalfUp And HalfDown!??
<a href="https://i.stack.imgur.com/iBjlJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iBjlJ.png" alt="enter image description here" /></a>
<a href="https://www.mathsisfun.com/numbers/rounding-methods.html" rel="nofollow noreferrer">https://www.mathsisfun.com/numbers/rounding-methods.html</a></p>
| [
{
"answer_id": 74243527,
"author": "Asif Jalil",
"author_id": 15974978,
"author_profile": "https://Stackoverflow.com/users/15974978",
"pm_score": -1,
"selected": false,
"text": "#header.colorful {\n background: linear-gradient(\n 305deg,\n #d8eae5,\n #e0ece9,\n #f9e9a7,\n ... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13455451/"
] |
74,243,502 | <p>I have a class that is a descendant of TImage32. I need to use the event like OnMouseMove, so the code assigns my OnMouseMove event in Create().
But if the user installs this component in Delphi and assigns another OnMouseMove event, my event is replaced.</p>
<p>My current solution is to inherit from TCustomImage32 and do not publish the OnMouseMove property (all other properties yes), but create a new OnMouseMove2 property that can be assigned by the user, and the code calls OnMouseMove2 in my assigned OnMouseMove event if OnMouseMove2 is assigned.</p>
<p>Is there a better solution to this problem? To keep the event name for example OnMouseMove and have my own event assigned too?</p>
<pre><code>type
TAudioBezierCurvesInteractive = class (TCustomImage32)
private
FOnMouseMove2: TImgMouseMoveEvent;
procedure ImgMouseMoveEvent(Sender: TObject; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer);
public
Constructor Create(AOwner: TComponent); override;
published
property OnMouseMove2: TImgMouseMoveEvent read FOnMouseMove2 write FOnMouseMove2;
//* Original published properties
property Align;
property Anchors;
property AutoSize;
etc. ...
constructor TAudioBezierCurvesInteractive.Create(AOwner: TComponent);
begin
inherited;
OnMouseMove := ImgMouseMoveEvent;
end;
procedure TAudioBezierCurvesInteractive.ImgMouseMoveEvent(Sender: TObject; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer);
begin
...my code here...
if Assigned(FOnMouseMove2) then begin
FOnMouseMove2(Sender, Shift, X, Y, Layer);
end;
end;
</code></pre>
| [
{
"answer_id": 74243780,
"author": "Uwe Raabe",
"author_id": 26833,
"author_profile": "https://Stackoverflow.com/users/26833",
"pm_score": 3,
"selected": false,
"text": "type\n TAudioBezierCurvesInteractive = class (TCustomImage32)\n protected\n procedure MouseMove(Shift: TS... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10940712/"
] |
74,243,541 | <p>I have data like this</p>
<p><a href="https://i.stack.imgur.com/unWHK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/unWHK.png" alt="enter image description here" /></a></p>
<p>I want to pivot by year and show the total only from 2020</p>
<p><a href="https://i.stack.imgur.com/j7DcP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/j7DcP.png" alt="enter image description here" /></a></p>
<p>How do I achieve this?</p>
| [
{
"answer_id": 74243696,
"author": "Vaebhav",
"author_id": 9108912,
"author_profile": "https://Stackoverflow.com/users/9108912",
"pm_score": 3,
"selected": true,
"text": "year"
},
{
"answer_id": 74244159,
"author": "wwnde",
"author_id": 8986975,
"author_profile": "htt... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4057692/"
] |
74,243,569 | <p>Having a array values of the below need to convert another form of array using typescript or javascript.</p>
<pre><code>arrayList = {
['p1', 'm1', 0],
['p1', 'm2', 2],
['p1', 'm3', 3],
['p2', 'm2', 3],
['p2', 'm3', 5],
['p3', 'm1', 3],
['p3', 'm2', 4]}
</code></pre>
<p>new array need to check with first element of array</p>
<pre><code>array2 = { [ panel: 'p1', content: {['m1',0], ['m2', 2], ['m3', 3]}],
[ panel: 'p2', content: {['m2', 3], ['m3', 5]}],
[ panel: 'p3', content: {['m1', 3], ['m2', 4]}] }
</code></pre>
<p>Thanks in advance</p>
| [
{
"answer_id": 74243696,
"author": "Vaebhav",
"author_id": 9108912,
"author_profile": "https://Stackoverflow.com/users/9108912",
"pm_score": 3,
"selected": true,
"text": "year"
},
{
"answer_id": 74244159,
"author": "wwnde",
"author_id": 8986975,
"author_profile": "htt... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20364004/"
] |
74,243,583 | <p>I am writing a program to read and write a file at the same time. More specifically, all write operations are appending new data to the end of the file and all read operations are reading random positions of the file.</p>
<p>I am thinking of creating memory-mapped file (using <code>mmap</code>) to achieve efficient read while writing via append (mode <code>a</code> in <code>open</code>). However, I don't think this will work because the memory-mapped file cannot change in size*, unless I <code>munmap</code> and then <code>mmap</code> it.</p>
<p>While "<code>munmap</code> and then <code>mmap</code> the file again" works, it has many downsides. Not only I need to perform 2 syscalls after every write (or before every read), which hurts performance, the base address returned from the next <code>mmap</code> call after <code>munmap</code> could be different from the previous one. Since I am planning to have other in-memory data structure storing pointers to specific offset of this memory mapped file, it could be very inconvenient.</p>
<p>Are there more elegant and efficient ways of doing this? The program will be mostly running on Linux (but solutions with portability to other POSIX systems are preferred). I have read through the following posts, but none of them seems to give a definitive answer.</p>
<p><a href="https://stackoverflow.com/questions/15684771/how-to-portably-extend-a-file-accessed-using-mmap">How to portably extend a file accessed using mmap()</a></p>
<p><a href="https://stackoverflow.com/questions/72179836/can-the-os-automatically-grow-an-mmap-backed-file?noredirect=1&lq=1">Can the OS automatically grow an mmap backed file?</a></p>
<p><a href="https://stackoverflow.com/questions/8703820/fast-resize-of-a-mmap-file?rq=1">Fast resize of a mmap file</a></p>
<p>My intuition is to use <code>mmap</code> to "reserve" the file with a size that is large enough to accommodate the growth of file, say a few hundred of GiB (that is a very reasonable assumption in my use case). And then somehow reflect the change of file size in this mapped memory without invalidating it with <code>munmap</code>. However, I am aware that accessing data beyond the real file boundary could result in a bus error. And the documentation isn't clear about whether changes in file size will get reflected.</p>
<p>*I am not 100% sure about this, but I couldn't find any source of elegantly changing the size of memory-mapped file.</p>
| [
{
"answer_id": 74246126,
"author": "Useless",
"author_id": 212858,
"author_profile": "https://Stackoverflow.com/users/212858",
"pm_score": 1,
"selected": false,
"text": "ftruncate"
},
{
"answer_id": 74282782,
"author": "lewisxy",
"author_id": 9970386,
"author_profile"... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9970386/"
] |
74,243,594 | <p><a href="https://i.stack.imgur.com/r2Qrg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/r2Qrg.png" alt="enter image description here" /></a>
any formula that works on both excel and googles sheet for splitting text to their column.</p>
<p>I want a formula that split text from string to specific column.</p>
| [
{
"answer_id": 74243989,
"author": "JvdV",
"author_id": 9758194,
"author_profile": "https://Stackoverflow.com/users/9758194",
"pm_score": 2,
"selected": false,
"text": "B2"
},
{
"answer_id": 74244087,
"author": "Mayukh Bhattacharya",
"author_id": 8162520,
"author_prof... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13687076/"
] |
74,243,621 | <p>this is the function for dialing numbers.
resultTextview variable is what's displayed when someone inputs number
numbers. variable stores every action user takes and displays it</p>
<p>`</p>
<pre><code>fun numberclick(clickedView: View) {
if(clickedView is TextView) {
var text = resultTextview.text.toString()
var textN = numbers.text.toString()
var number = clickedView.text.toString()
if (text == "0" || textN == "0") {
text = ""
textN = ""
}
val result = text + number
val resultN = textN + number
resultTextview.text = result
numbers.text = resultN
}
}
</code></pre>
<p><code>this code works but when i try to do multiple operations without hitting equals it fails</code></p>
<pre><code>fun operationclick(clickedView: View) {
if(clickedView is TextView){
var numresult = numbers.text.toString() + clickedView.text.toString()
this.operant = resultTextview.text.toString().toDouble()
this.operation = clickedView.text.toString()
resultTextview.text = ""
numbers.text = numresult + resultTextview.text
}
}
fun equals(clickedView: View) {
if (clickedView is TextView){
val secondoperant = resultTextview.text.toString().toDouble()
when (operation) {
"+" -> resultTextview.text = (this.operant + secondoperant).toString()
"-" -> resultTextview.text = (this.operant - secondoperant).toString()
"/" -> resultTextview.text = (this.operant / secondoperant).toString()
"X" -> resultTextview.text = (this.operant * secondoperant).toString()
}
}
}
</code></pre>
<p>`</p>
<p>i tried to change returnTextView to Numbers variable in this.operator but the app crashes when i do that.</p>
| [
{
"answer_id": 74243989,
"author": "JvdV",
"author_id": 9758194,
"author_profile": "https://Stackoverflow.com/users/9758194",
"pm_score": 2,
"selected": false,
"text": "B2"
},
{
"answer_id": 74244087,
"author": "Mayukh Bhattacharya",
"author_id": 8162520,
"author_prof... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14938636/"
] |
74,243,647 | <pre><code>import re
def tst():
text = '''
<script>
'''
if proxi := re.findall(r"(?:<td\s[^>]*?><font\sclass\=spy14>(.*?)<script.*?\"\+(.*?)\)<\/script)", text):
for proxy, port in proxi:
yield f"{proxy}:{''.join(port)}"
if dtt := re.findall(r"<td colspan=1><font class\=spy1><font class\=spy14>(.*?)</font> (\d+[:]\d+) <font class\=spy5>([(]\d+ \w+ \w+[)])", text):
for date, time, taken in dtt:
yield f"{date} {' '.join([time, taken])}"
return None
return None
for proxy in tst():
print(proxy)
</code></pre>
<p>output that i get</p>
<pre><code>51.155.10.0:8000
178.128.96.80:7497
98.162.96.41:4145
27-oct-2022 11:05 (49 mins ago)
27-oct-2022 11:04 (50 mins ago)
27-oct-2022 11:03 (51 mins ago)
</code></pre>
<p>so i use this regex below to capture group from output</p>
<pre><code>(\w+[.]\w+[.]\w+[.]\w+[:]\w+)|(\w+.*)
</code></pre>
<p>i want the result like this, how to combine it from output?</p>
<pre><code>157.245.247.84:7497 - 27-oct-2022 11:05 (49 mins ago)
184.190.137.213:8111 - 27-oct-2022 11:04 (50 mins ago)
202.149.89.67:7999 - 27-oct-2022 11:03 (51 mins ago)
</code></pre>
| [
{
"answer_id": 74243989,
"author": "JvdV",
"author_id": 9758194,
"author_profile": "https://Stackoverflow.com/users/9758194",
"pm_score": 2,
"selected": false,
"text": "B2"
},
{
"answer_id": 74244087,
"author": "Mayukh Bhattacharya",
"author_id": 8162520,
"author_prof... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20169628/"
] |
74,243,680 | <p>I have created aks cluster with 2 services exposed using Ingress controller</p>
<p>below is the yml file for ingress controller with TLS</p>
<pre><code>apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: xyz-office-ingress02
annotations:
nginx.ingress.kubernetes.io/use-regex: "true"
nginx.ingress.kubernetes.io/rewrite-target: /
cert-manager.io/cluster-issuer: letsencrypt
kubernetes.io/ingress.class: "nginx"
spec:
tls:
- hosts:
- office01.xyz.com
secretName: tls-office-secret
rules:
- host: office01.xyz.com
- http:
paths:
- path: /(/|$)(.*)
pathType: Prefix
backend:
service:
name: office-webapp
port:
number: 80
- path: /api/
pathType: Prefix
backend:
service:
name: xyz-office-api
port:
number: 80
</code></pre>
<p>kubenctl describe ing</p>
<pre><code> Name: xyz-office-ingress02
Labels: <none>
Namespace: default
Address: <EXTERNAL Public IP>
Ingress Class: <none>
Default backend: <default>
TLS:
tls-office-secret terminates office01.xyz.com
Rules:
Host Path Backends
---- ---- --------
*
/(/|$)(.*) office-webapp:80 (10.244.1.18:80,10.244.2.16:80)
/api/ xyz-office-api:80 (10.244.0.14:8000,10.244.1.19:8000)
Annotations: cert-manager.io/cluster-issuer: letsencrypt
kubernetes.io/ingress.class: nginx
nginx.ingress.kubernetes.io/rewrite-target: /
nginx.ingress.kubernetes.io/use-regex: true
Events: <none>
</code></pre>
<p>On IP i am able to access both services, however when using the DNS it is not working and gives 404 error</p>
| [
{
"answer_id": 74243989,
"author": "JvdV",
"author_id": 9758194,
"author_profile": "https://Stackoverflow.com/users/9758194",
"pm_score": 2,
"selected": false,
"text": "B2"
},
{
"answer_id": 74244087,
"author": "Mayukh Bhattacharya",
"author_id": 8162520,
"author_prof... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6672128/"
] |
74,243,692 | <p>Flutter opened and moved to developer folder. I haven't had any luck updating the flutter path in the terniaml. It fails to open flutter</p>
<p>I enter the info posted on the flutter website and replace the path with my info on where the flutter folder is located on my computer. i run, source $HOME/.. Then a error code comes back. If i run,</p>
<pre><code> echo $PATH
</code></pre>
<p>then it comes back flutter not detected.</p>
| [
{
"answer_id": 74243989,
"author": "JvdV",
"author_id": 9758194,
"author_profile": "https://Stackoverflow.com/users/9758194",
"pm_score": 2,
"selected": false,
"text": "B2"
},
{
"answer_id": 74244087,
"author": "Mayukh Bhattacharya",
"author_id": 8162520,
"author_prof... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20364104/"
] |
74,243,719 | <p>I'm learning SvelteKit and this might be a very elementary question. But I could not figure out how to change the tab's title.</p>
<p>In my <code>src/+layout.svelte</code> I have:</p>
<pre><code> <script>
let title="My Site Homepage"
</script>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
...
<title>{title}</title>
</head>
</code></pre>
<p>Then in my <code>/src/faq/+page.svelte</code> I'd like to change the title to 'FAQ'</p>
<p>So I put</p>
<pre><code><script>
let title="FAQ"
</script>
</code></pre>
<p>But when I visit <code>http://localhost:5173/faq</code> the tab's title is not changed.
So I'm wondering how can I do that? Is there an idomatic way to do so?</p>
| [
{
"answer_id": 74243758,
"author": "01001010",
"author_id": 20333579,
"author_profile": "https://Stackoverflow.com/users/20333579",
"pm_score": -1,
"selected": false,
"text": "//../components/meta-title.svelte\n\n<svelte:head>\n <title>{title}</title>\n</svelte:head>\n\n<script>\n ex... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15363841/"
] |
74,243,737 | <p>Hi I'm trying to search for a pattern using find all and it will return list if there is a match. and I'm trying to access that list which throughs an error like (IndexError: list index out of range)
and my snippet i wrote is like below.</p>
<pre><code>return_from_findall = re.findall(regex, input)
if return_from_findall:
##trying to print the list element when list returned from finall is true##
print(return_from_finall[0])
## also trying to compare the list with another string like
if return_from_finall[0] == somestring:
print(match found)
</code></pre>
<p>Both are not working</p>
<p>can some one help to solve this problem</p>
<p>My program:</p>
<pre><code>import re
output = """
Another option is to use the name randomizer.
to randomize all the names on your list.
In this case, you arent using it as a
random name picker, but as a true name
randomizer. For example,
"""
match = 0
search_item = "Another option is to use the name randomizer"
expected_list = [
'Another option is to use the name randomizer.',
'to randomize all the names on your list.',
'In this case, you arent using it as a',
'random name picker, but as a true name',
'randomizer. For example,']
for line in output.splitlines():
line = line.strip()
print(" ################### ")
return_from_findall = re.findall(search_item, line)
print("searched line - ")
print(return_from_findall)
print("expected line - ")
print(expected_list[match])
if return_from_findall:
if return_from_findall[0] == expected_list[match]:
print("found match")
</code></pre>
| [
{
"answer_id": 74243758,
"author": "01001010",
"author_id": 20333579,
"author_profile": "https://Stackoverflow.com/users/20333579",
"pm_score": -1,
"selected": false,
"text": "//../components/meta-title.svelte\n\n<svelte:head>\n <title>{title}</title>\n</svelte:head>\n\n<script>\n ex... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16600302/"
] |
74,243,846 | <p>I want to display a variable from an extension called node temp mail
its just a temp email generator
i installed it using npm
tell me if you want some more info I am new to webdev</p>
<p>i want the variable <code>body</code> to display in the html or on the website itself</p>
<p><strong>Here‘s the code:</strong></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 TempMail = require('node-temp-mail');
function makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
var address = new TempMail(makeid(5),true);
address.fetchEmails(function(err,body){
console.log(body);
});
address.getAddress()</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<script src="javasquript.js"></script>
<title>Debit Card Design</title>
</head>
<body>
<div class="card">
<h4 class="bank">lightning <span>BANK</span></h4>
<div class="number">
<h6>4512</h6>
<h6>8963</h6>
<h6>7845</h6>
<h6>3542</h6>
</div>
<img src="img/lightning.png" alt="" class="lightning">
<img src="img/wave.png" alt="" class="wave">
<div class="ex_date">
<span>VALID<br>UPTO</span>
<h3>02 <span>/</span> 29</h3>
</div>
<div class="cvv">
<span>CVC</span>
<h1>563</h1>
</div>
<img src="img/visa.png" alt="" class="visa">
</div>
<script type="module" src="javasquript.js"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74243894,
"author": "HackerFrosch",
"author_id": 20357737,
"author_profile": "https://Stackoverflow.com/users/20357737",
"pm_score": 2,
"selected": true,
"text": "<div id=\"address\"></div>\n"
},
{
"answer_id": 74254272,
"author": "KooiInc",
"author_id": 58... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19055220/"
] |
74,243,853 | <p>Learning React, making a very simple to-do list. I am able to add items as expected. When I input something and click "add", the item shows up on the page. But I noticed that if I try to console.log the result, the array that gets consoled is always missing the last item. Eg. If I enter "bread" and click "add", it will show on the page, but in the console, I just get an empty array. If I then enter "milk" and click "add", on the page both bread and milk show up but in the console, I only see ["bread"] as the array. Why is this happening?</p>
<pre><code>import { useRef, useState } from "react";
export default function App() {
const [items, setItems] = useState([]);
const inputRef = useRef();
function onSubmit(e) {
e.preventDefault();
const value = inputRef.current.value;
setItems(prev => [...prev, value]);
console.log(items);
inputRef.current.value = "";
}
return (
<main>
<form onSubmit={onSubmit}>
<input type="text" ref={inputRef} />
<button type="submit">Add</button>
</form>
<h3>My List:</h3>
<ul>
{items.map(item => (
<li>{item}</li>
))}
</ul>
</main>
);
}
</code></pre>
| [
{
"answer_id": 74243877,
"author": "moshfiqrony",
"author_id": 9418800,
"author_profile": "https://Stackoverflow.com/users/9418800",
"pm_score": 3,
"selected": true,
"text": "setItems"
}
] | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4671257/"
] |
74,243,869 | <p>Using <a href="https://www.filehelpers.net/" rel="nofollow noreferrer">FileHelpers</a> FixedFileEngine to read in large files from customers. One customer seems to have an extra whitespace per record (perhaps lf/cf TBD).</p>
<p>BUT can I support this difference easily in the parsing record definition?</p>
<pre><code>[FixedLengthRecord()]
public class ClaimEntryDch
{
...
[IgnoreOptionalWhitespace(1)] // something like this?
string IgnoreThis { get; set; }
}
</code></pre>
| [
{
"answer_id": 74244308,
"author": "Xerillio",
"author_id": 3034273,
"author_profile": "https://Stackoverflow.com/users/3034273",
"pm_score": 1,
"selected": false,
"text": "[FieldOptional]"
},
{
"answer_id": 74246515,
"author": "kenny",
"author_id": 3225,
"author_prof... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3225/"
] |
74,243,874 | <p>I was using Selenium Python to log in to Instagram and open some pages. It worked fine, but after two days the Instagram started sending the message "CSRF token missing or incorrect". And now I can't even log in with my script or manually to any accounts and with any browsers such as Chrome or FireFox on my laptop.</p>
<p>I'm not sending any cookies with my Selenium. And most of the search results are about Django which I'm not using.</p>
<ul>
<li><p>I erased the cookies, but it it didn't work.</p>
</li>
<li><p>I tried to change my IP address to make sure if I'm banned from Instagram, but it didn't work.</p>
</li>
<li><p>I tried to check for the scrf-token in my URL with Selenium and sending it to the driver, but it didn't work.</p>
</li>
</ul>
<p>I'm not sure if the solution is within the code, because now I can't log in even manually, so maybe there must be a problem with my system settings or from Instagram side.</p>
<p>Can I fix this with Selenium? Or how can I fix this?</p>
| [
{
"answer_id": 74631486,
"author": "350D",
"author_id": 819764,
"author_profile": "https://Stackoverflow.com/users/819764",
"pm_score": 1,
"selected": false,
"text": "n=new Date;t=n.getTime();et=t+36E9;n.setTime(et);document.cookie='csrftoken='+document.body.innerHTML.split('csrf_token')... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20364259/"
] |
74,243,879 | <p>I want to use UTC dates in my Node.js backend app, however, I need to be able to set time (hours and minutes) in a local/user-specified timezone.</p>
<p>I am looking for a solution in either pure JS or using <code>dayjs</code>. I am not looking for a solution in <code>moment</code>.</p>
<p>It seemed like using <code>dayjs</code> I could solve this problem quite easily, however, I could not find a way to accomplish this.</p>
<p>I can use UTC timezone by using <a href="https://day.js.org/docs/en/plugin/utc" rel="nofollow noreferrer"><code>dayjs.utc()</code></a> or using <a href="https://day.js.org/docs/en/timezone/timezone" rel="nofollow noreferrer"><code>dayjs.tz(someDate, 'Etc/UTC')</code></a>.</p>
<p>When using <code>dayjs.utc()</code>, I cannot use/specify other timezones for <em>anything</em>, therefore I could not find a way to tell <code>dayjs</code> I want to set hours/minutes in a particular (non-UTC) timezone.</p>
<p>When using <code>dayjs.tz()</code>, I still cannot define a timezone of time I want to set to a particular date.</p>
<h3>Example in plain JS</h3>
<p>My locale timezone is <code>Europe/Slovakia</code> (CEST = UTC+02 with DST, CET = UTC+1 without DST), however, I want this to work with any timezone.</p>
<pre class="lang-js prettyprint-override"><code>// Expected outcome
// old: 2022-10-29T10:00:00.000Z
// new time: 10h 15m CEST
// new: 2022-10-29T08:15:00.000Z
// Plain JS
const now = new Date('2022-10-29T10:00:00.000Z')
const hours = 10
const minutes = 15
now.setHours(10)
now.setMinutes(15)
// As my default timezone is `Europe/Bratislava`, it seems to work as expected
console.log(now)
// Output: 2022-10-29T08:15:00.000Z
// However, it won't work with timezones other than my local timezone
</code></pre>
<h3>(Nearly) a solution</h3>
<p><em><strong>Update: I posted a working function in <a href="https://stackoverflow.com/a/74245936/3408342">this answer</a>.</strong></em></p>
<p>The following functions seems to work for most test cases, however, it fails for <strike>6</strike> 4 cases known to me (any help is greatly appreciated):</p>
<ul>
<li>[DST to ST] <code>now</code> in DST before double hour, <code>newDate</code> in ST during double hour;</li>
<li>[DST to ST] <code>now</code> in DST during double hour, <code>newDate</code> in ST during double hour;</li>
<li>[DST to ST] <code>now</code> in ST during double hour, <code>newDate</code> in DST during double hour;</li>
<li>[DST to ST] <code>now</code> in ST after double hour, <code>newDate</code> in DST during double hour;</li>
<li><strike>[ST to DST] <code>now</code> in ST before skipped hour, <code>newDate</code> in ST in skipped hour</strike>;</li>
<li><strike>[ST to DST] <code>now</code> in DST after skipped hour, <code>newDate</code> in ST in skipped hour</strike>.</li>
</ul>
<p>I think the only missing piece is to find a way to check if a particular date in a non-UTC timezone falls into double hour. By <em>double hour</em> I mean a situation caused by changint DST to ST, i.e. setting our clock back an hour (e.g. at 3am to 2am → double hour is between <code>02:00:00.000</code> and <code>02:59:59.999</code>, which occur both in DST and ST).</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>/**
* Set time provided in a timezone
*
* @param {Date} [dto.date = new Date()] Date object to work with
* @param {number} [dto.time.h = 0] Hour to set
* @param {number} [dto.time.m = 0] Minute to set
* @param {number} [dto.time.s = 0] Second to set
* @param {number} [dto.time.ms = 0] Millisecond to set
* @param {string} [dto.timezone = 'Europe/Bratislava'] Timezone of `dto.time`
*
* @return {Date} Date object
*/
function setLocalTime(dto = {
date: new Date(),
// TODO: Rename the property to `{h, m, s, ms}`.
time: {h: 0, m: 0, ms: 0, s: 0},
timezone: 'Europe/Bratislava'
}) {
const defaultTime = {h: 0, m: 0, ms: 0, s: 0}
const defaultTimeKeys = Object.keys(defaultTime)
// src: https://stackoverflow.com/a/44118363/3408342
if (!Intl || !Intl.DateTimeFormat().resolvedOptions().timeZone) {
throw new Error('`Intl` API is not available or it does not contain a list of timezone identifiers in this environment')
}
if (!(dto.date instanceof Date)) {
throw Error('`date` must be a `Date` object.')
}
try {
Intl.DateTimeFormat(undefined, {timeZone: dto.timezone})
} catch (e) {
throw Error('`timezone` must be a valid IANA timezone.')
}
if (
typeof dto.time !== 'undefined'
&& typeof dto.time !== 'object'
&& dto.time instanceof Object
&& Object.keys(dto.time).every(v => defaultTimeKeys.indexOf(v) !== -1)
) {
throw Error('`time` must be an object of `{h: number, m: number, s: number, ms: number}` format, where numbers should be valid time values.')
}
dto.time = Object.assign({}, defaultTime, dto.time)
const getTimezoneOffsetHours = ({date, localisedDate, returnNumber, timezone}) => {
let offsetString
if (localisedDate) {
offsetString = localisedDate.find(i => i.type === 'timeZoneName').value.match(/[\d+:-]+$/)?.[0]
} else {
offsetString = new Intl
.DateTimeFormat('en-GB', {timeZone: timezone, timeZoneName: 'longOffset'})
.formatToParts(date)
.find(i => i.type === 'timeZoneName').value.match(/[\d+:-]+$/)?.[0]
}
return returnNumber ? offsetString.split(':').reduce((a, c) => /^[+-]/.test(c) ? +c * 60 : a + +c, 0) : offsetString
}
const pad = (n, len) => `00${n}`.slice(-len)
let [datePart, offset] = dto.date.toLocaleDateString('sv', {
timeZone: dto.timezone,
timeZoneName: 'longOffset'
}).split(/ GMT|\//)
offset = offset.replace(String.fromCharCode(8722), '-')
const newDateWithoutOffset = `${datePart}T${pad(dto.time.h || 0, 2)}:${pad(dto.time.m || 0, 2)}:${pad(dto.time.s || 0, 2)}.${pad(dto.time.ms || 0, 3)}`
let newDate = new Date(`${newDateWithoutOffset}${offset}`)
const newDateTimezoneOffsetHours = getTimezoneOffsetHours({date: newDate, timezone: dto.timezone})
// Check if timezones of `dto.date` and `newDate` match; if not, use the new timezone to re-create `newDate`
newDate = newDateTimezoneOffsetHours === offset
? newDate
: new Date(`${newDateWithoutOffset}${newDateTimezoneOffsetHours}`)
if (dto.time.h !== +new Intl.DateTimeFormat('en-GB', {hour: 'numeric', timeZone: dto.timezone}).formatToParts(newDate)?.[0].value) {
newDate = new Date('')
}
return newDate
}
const timezoneIana = 'Europe/Bratislava'
const tests = [
{
expString: '30/10/2022, 01:55:00 GMT+02:00',
now: new Date('2022-10-29T23:56:12.006Z'),
testName: '[DST to ST] `now` in DST before double hour, `newDate` in DST before double hour',
time: {h: 1, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+02:00',
now: new Date('2022-10-29T23:56:12.006Z'),
testName: '[DST to ST] `now` in DST before double hour, `newDate` in DST during double hour',
time: {h: 2, m: 55}
},
// FIXME
{
expString: '30/10/2022, 02:55:00 GMT+01:00',
now: new Date('2022-10-29T23:56:12.006Z'),
testName: '[DST to ST] `now` in DST before double hour, `newDate` in ST during double hour',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 03:55:00 GMT+01:00',
now: new Date('2022-10-29T23:56:12.006Z'),
testName: '[DST to ST] `now` in DST before double hour, `newDate` in ST after double hour',
time: {h: 3, m: 55}
},
{
expString: '30/10/2022, 01:55:00 GMT+02:00',
now: new Date('2022-10-30T00:56:12.006Z'),
testName: '[DST to ST] `now` in DST during double hour, `newDate` in DST before double hour',
time: {h: 1, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+02:00',
now: new Date('2022-10-30T00:56:12.006Z'),
testName: '[DST to ST] `now` in DST during double hour, `newDate` in DST during double hour',
time: {h: 2, m: 55}
},
// FIXME
{
expString: '30/10/2022, 02:55:00 GMT+01:00',
now: new Date('2022-10-30T00:56:12.006Z'),
testName: '[DST to ST] `now` in DST during double hour, `newDate` in ST during double hour',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 03:55:00 GMT+01:00',
now: new Date('2022-10-30T00:56:12.006Z'),
testName: '[DST to ST] `now` in DST during double hour, `newDate` in ST after double hour',
time: {h: 3, m: 55}
},
{
expString: '30/10/2022, 01:55:00 GMT+02:00',
now: new Date('2022-10-30T01:56:12.006Z'),
testName: '[DST to ST] `now` in ST during double hour, `newDate` in DST before double hour',
time: {h: 1, m: 55}
},
// FIXME
{
expString: '30/10/2022, 02:55:00 GMT+02:00',
now: new Date('2022-10-30T01:56:12.006Z'),
testName: '[DST to ST] `now` in ST during double hour, `newDate` in DST during double hour',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+01:00',
now: new Date('2022-10-30T01:56:12.006Z'),
testName: '[DST to ST] `now` in ST during double hour, `newDate` in ST during double hour',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 03:55:00 GMT+01:00',
now: new Date('2022-10-30T01:56:12.006Z'),
testName: '[DST to ST] `now` in ST during double hour, `newDate` in ST after double hour',
time: {h: 3, m: 55}
},
{
expString: '30/10/2022, 01:55:00 GMT+02:00',
now: new Date('2022-10-30T02:56:12.006Z'),
testName: '[DST to ST] `now` in ST after double hour, `newDate` in DST before double hour',
time: {h: 1, m: 55}
},
// FIXME
{
expString: '30/10/2022, 02:55:00 GMT+02:00',
now: new Date('2022-10-30T02:56:12.006Z'),
testName: '[DST to ST] `now` in ST after double hour, `newDate` in DST during double hour',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+01:00',
now: new Date('2022-10-30T02:56:12.006Z'),
testName: '[DST to ST] `now` in ST after double hour, `newDate` in ST during double hour',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 03:55:00 GMT+01:00',
now: new Date('2022-10-30T02:56:12.006Z'),
testName: '[DST to ST] `now` in ST after double hour, `newDate` in ST after double hour',
time: {h: 3, m: 55}
},
{
expString: '26/03/2023, 01:55:00 GMT+01:00',
now: new Date('2023-03-26T00:56:12.006Z'),
testName: '[ST to DST] `now` in ST before skipped hour, `newDate` in ST before skipped hour',
time: {h: 1, m: 55}
},
// FIXME
{
expString: 'Invalid Date',
now: new Date('2023-03-26T00:56:12.006Z'),
testName: '[ST to DST] `now` in ST before skipped hour, `newDate` in ST in skipped hour',
time: {h: 2, m: 55}
},
{
expString: '26/03/2023, 03:55:00 GMT+02:00',
now: new Date('2023-03-26T00:56:12.006Z'),
testName: '[ST to DST] `now` in ST before skipped hour, `newDate` in DST after skipped hour',
time: {h: 3, m: 55}
},
{
expString: '26/03/2023, 01:55:00 GMT+01:00',
now: new Date('2023-03-26T01:56:12.006Z'),
testName: '[ST to DST] `now` in DST after skipped hour, `newDate` in ST before skipped hour',
time: {h: 1, m: 55}
},
// FIXME
{
expString: 'Invalid Date',
now: new Date('2023-03-26T01:56:12.006Z'),
testName: '[ST to DST] `now` in DST after skipped hour, `newDate` in ST in skipped hour',
time: {h: 2, m: 55}
},
{
expString: '26/03/2023, 03:55:00 GMT+02:00',
now: new Date('2023-03-26T01:56:12.006Z'),
testName: '[ST to DST] `now` in DST after skipped hour, `newDate` in DST after skipped hour',
time: {h: 3, m: 55}
}
// TODO: Add a test of a date in DST and ST on a day on which there is no timezone change (two tests in total, one for DST and another for ST).
]
const results = tests.map(t => {
const newDate = setLocalTime({date: t.now, time: t.time, timezone: timezoneIana})
const newDateString = newDate.toLocaleString('en-GB', {timeZone: timezoneIana, timeZoneName: 'longOffset'})
const testResult = newDateString === t.expString
if (testResult) {
console.log(testResult, `: ${t.testName} : ${newDateString}`)
} else {
console.log(testResult, `: ${t.testName} : ${newDateString} :`, {newDate, newDateString, test: t})
}
return testResult
}).reduce((a, c, i) => {
if (c) {
a.passed++
} else {
a.failed++
a.failedTestIds.push(i)
}
return a
}, {failed: 0, failedTestIds: [], passed: 0})
console.log(results)</code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74245227,
"author": "Carsten Massmann",
"author_id": 2610061,
"author_profile": "https://Stackoverflow.com/users/2610061",
"pm_score": 0,
"selected": false,
"text": "Date"
},
{
"answer_id": 74245936,
"author": "tukusejssirs",
"author_id": 3408342,
"auth... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3408342/"
] |
74,243,883 | <p>i have a scenario where based on a number(say numberOfFlags) i want to render numberOfFlags times an radio button group.Each group has two radio buttons approve and reject as per screen<a href="https://i.stack.imgur.com/QSoya.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QSoya.png" alt="enter image description here" /></a>shot attached how to get values of all inputs when they change?
An lastly i have to store result of all radio buttons (approve/reject) in an array and send to API</p>
| [
{
"answer_id": 74243953,
"author": "Arifur Rahman Sujon",
"author_id": 8805898,
"author_profile": "https://Stackoverflow.com/users/8805898",
"pm_score": 1,
"selected": false,
"text": "onchange = handleOnChage(index, isApproveClicked)\n"
},
{
"answer_id": 74244138,
"author": "... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14465826/"
] |
74,243,901 | <p>I'm attempting to code a webpage from scratch and I'm stumped on how or where to adjust the opacity on the <code>background-image</code> URL without affecting the text on top.</p>
<p>I thought about giving the <code>background-image</code> its own class but I'm kind of confused about where this would go.</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>* {
margin: 0;
padding: 0;
font-family: 'Poppins', sans-serif;
}
.header {
min-height: 100vh;
width: 100%;
background-image: url(images/lake.jpg);
background-position: center;
background-size: cover;
position: relative;
}
nav {
display: flex;
padding: 2% 6%;
justify-content: space-between;
align-items: center;
}
nav img {
width: 300px;
}
.logo {
width: 0%;
height: 0%;
display: block;
}
.navbar {
flex: 1;
text-align: right;
}
.navbar ul li {
list-style: none;
display: inline-block;
padding: 8px 12px;
position: relative;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="header">
<nav>
<div class="logo">
<a href="index.html"><img src="https://cdn.pixabay.com/photo/2022/10/23/09/07/bicycle-7540835_960_720.png"></a>
</div>
<div class="navbar">
<ul>
<li><a href="">Home</a></li>
<li><a href="">About Me</a></li>
<li><a href="">Portfolio</a></li>
<li><a href="">Contact</a></li>
</ul>
</div>
</nav>
</section></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74243963,
"author": "Shivam kaushal",
"author_id": 13930696,
"author_profile": "https://Stackoverflow.com/users/13930696",
"pm_score": 1,
"selected": false,
"text": "linear-gradient"
},
{
"answer_id": 74243976,
"author": "HackerFrosch",
"author_id": 2035773... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20364325/"
] |
74,243,913 | <p>I am writing an app with Expo that uses expo-location to track the location of a user in the background. I would like to use hooks (states, useEffect...) when my app is in the background. At the moment the background tracking code looks like that</p>
<pre class="lang-js prettyprint-override"><code>export default function BackgroundLocationHook() {
[...]
const [position, setPosition] = useState(null);
const [newLocation, setNewLocation] = useState(null) ;
TaskManager.defineTask(LOCATION_TASK_NAME, async ({ data, error }) => {
if (error) {
console.error(error);
return;
}
if (data) {
// Extract location coordinates from data
const { locations } = data;
const location = locations[0];
if (location) {
console.log("Location in background", location.coords);
}
}
setPosition(location.coords);
});
[...]
return [position];
}
</code></pre>
<p>But it is a bit hacky as the geolocation_tracking task shares some states with the
I would also like to play some sounds when I am close to a some location even when my app is in the background. I plan to do it with <code>useEffect</code> like that:</p>
<pre class="lang-js prettyprint-override"><code>useEffect(() => {
const requestPermissions = async () => {
if(shouldPlaySound(newLocation)){
playSound()
}
};
requestPermissions();
}, [newLocation]);
</code></pre>
<p>This works when my app is in the foreground but I heard that react hooks such as <code>states</code>, and <code>useEffect</code> do not work when the app is in the background. So my question is what is the alternative to make sure I still have a sound being played when my app is in the background and if it is possible to have hooks working even when the app is in the background.</p>
| [
{
"answer_id": 74243963,
"author": "Shivam kaushal",
"author_id": 13930696,
"author_profile": "https://Stackoverflow.com/users/13930696",
"pm_score": 1,
"selected": false,
"text": "linear-gradient"
},
{
"answer_id": 74243976,
"author": "HackerFrosch",
"author_id": 2035773... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2197372/"
] |
74,243,914 | <p>I recently uploaded an app that I have made on Google Play though the Google Play Console. For some reason that I don't really understand on all the devices (mine, friend and family) shows that the app is not supported with my device. It's the first that I'm using Google Play Console and since the app past the review process from Google, I don't really understand why this is happening.
I found the device catalog tab, but I haven't put any exclusions there.</p>
<p>After I uploaded the app through Google Play Console, I've send the app to friends and family, like 20 people or so, but none of them was able to download the app. Same thing is happening on my 2 devices.</p>
<p>Here is the manifest</p>
<p></p>
<pre><code><uses-feature
android:name="android.hardware.Camera"
android:required="true" />
<queries>
<intent>
<action android:name="android.media.action.IMAGE_CAPTURE" />
</intent>
</queries>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.CAMERA" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.PITAFLPantryManager">
<activity
android:name=".ShoppingListActivity"
android:parentActivityName=".MainActivity" />
<activity android:name=".TextRecognitionActivity" />
<activity android:name=".BarcodeScannerActivity" />
<activity
android:name=".ProductsActivity"
android:parentActivityName=".MainActivity">
<meta-data android:name="android.app.default_searchable"
android:value=".SearchableActivity" />
</activity>
<activity
android:name=".SettingsActivity"
android:exported="false"
android:label="@string/title_activity_settings"
android:parentActivityName=".MainActivity"/>
<activity android:name=".AboutActivity"
android:parentActivityName=".MainActivity" />
<activity android:name=".SearchableActivity"
android:launchMode="singleTop"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data android:name="android.app.searchable"
android:resource="@xml/searchable" />
</activity>
<activity android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data android:name="android.app.default_searchable"
android:value=".SearchableActivity" />
</activity>
<meta-data
android:name="com.google.mlkit.vision.DEPENDENCIES"
android:value="ocr" />
<!--service
android:name=".ProductsWatcherWorker"
android:permission="android.permission.BIND_JOB_SERVICE"></service-->
</application>
</code></pre>
<p>And the build.gradle</p>
<pre><code>plugins {
id 'com.android.application'
}
// Creates a variable called keystorePropertiesFile, and initializes it to the
// keystore.properties file.
def keystorePropertiesFile = rootProject.file('keystore.properties')
// Initializes a new Properties() object called keystoreProperties.
def keystoreProperties = new Properties()
// Loads the keystore.properties file into the keystoreProperties object.
keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
android {
signingConfigs {
debug {
keyAlias keystoreProperties['debugKeyAlias']
keyPassword keystoreProperties['debugKeyPassword']
storeFile file(keystoreProperties['debugStoreFile'])
storePassword keystoreProperties['debugStorePassword']
}
release {
keyAlias keystoreProperties['releaseKeyAlias']
keyPassword keystoreProperties['releaseKeyPassword']
storeFile file(file(keystoreProperties['releaseStoreFile']))
storePassword keystoreProperties['releaseStorePassword']
}
}
compileSdkVersion 32
buildToolsVersion "30.0.3"
defaultConfig {
applicationId "com.timkom.pitafl"
minSdkVersion 27
targetSdkVersion 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
packagingOptions {
exclude 'AndroidManifest.xml'
exclude 'resources.arsc'
}
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
debuggable false
jniDebuggable false
renderscriptDebuggable false
zipAlignEnabled false
signingConfig signingConfigs.release
}
debug {
signingConfig signingConfigs.debug
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
buildFeatures {
viewBinding true
}
configurations {
compile.exclude group: 'com.google.android'
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'androidx.lifecycle:lifecycle-viewmodel:2.3.1'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.0'
implementation 'androidx.coordinatorlayout:coordinatorlayout:1.1.0'
implementation 'androidx.fragment:fragment:1.3.6'
implementation 'com.github.bumptech.glide:glide:4.12.0'
implementation 'com.github.bigfishcat.android:svg-android:2.0.8'
implementation 'androidx.work:work-runtime:2.5.0'
implementation 'androidx.preference:preference:1.1.0'
implementation 'com.google.mlkit:barcode-scanning:17.0.2'
implementation "androidx.camera:camera-camera2:1.0.2"
implementation "androidx.camera:camera-lifecycle:1.0.2"
implementation "androidx.camera:camera-view:1.0.0-alpha23"
implementation 'com.google.android.gms:play-services-mlkit-text-recognition:18.0.0'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
android.applicationVariants.all { variant ->
variant.outputs.all {
outputFileName = "${applicationId}-${variant.name}-${variant.versionName}.apk"
}
}
</code></pre>
| [
{
"answer_id": 74245142,
"author": "Timos Komni",
"author_id": 20114741,
"author_profile": "https://Stackoverflow.com/users/20114741",
"pm_score": 0,
"selected": false,
"text": "<uses-feature\n android:name=\"android.hardware.Camera\"\n android:required=\"true\" />\n"
},
{
... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20114741/"
] |
74,243,918 | <p>I want to get relation:</p>
<pre><code>Package::whereIn('id', $cart_items)->with('course')->select('id', 'name')->get();
</code></pre>
<p>It return successfully as object, but now I need to count this relation, I did:</p>
<pre><code>function courses(){
return $this->hasMany('App\Models\Course', 'package_id','id');
}
public function getCourseCount()
{
return $this->courses()->count();
}
</code></pre>
<p>And then:</p>
<pre><code>Package::whereIn('id', $cart_items)->with('getCourseCount')->select('id', 'name')->get();
</code></pre>
<p>But give me this error:</p>
<blockquote>
<p>Call to a member function addEagerConstraints() on int</p>
</blockquote>
<p>Any idea?</p>
<p>--
<em>I also used <code>withCount</code> but it return empty array.</em></p>
<pre><code>Package::whereIn('id', $cart_items)->withCount('courses')->select('id', 'name')->get();
</code></pre>
| [
{
"answer_id": 74244150,
"author": "N69S",
"author_id": 4369919,
"author_profile": "https://Stackoverflow.com/users/4369919",
"pm_score": 0,
"selected": false,
"text": "withCount()"
},
{
"answer_id": 74244173,
"author": "Can Vural",
"author_id": 1561146,
"author_profi... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9158178/"
] |
74,243,923 | <p>I'm unable to get the minimum (the float in the example) of a list of tuples. I converted them to an array and can't get the minimum there either. I also want to sort the order. I can't figure out how to do this.</p>
<pre class="lang-none prettyprint-override"><code>[(' handicapped-infants', 0.4255567528735632),
(' water-project-cost-sharing', 0.49741024814695456),
(' adoption-of-the-budget-resolution', 0.25584421930900736),
(' physician-fee-freeze', 0.05752597041257758),
(' el-salvador-aid', 0.21445519728116716),
(' religious-groups-in-schools', 0.3994529378797299),
(' anti-satellite-test-ban', 0.37440262843488636)]
</code></pre>
| [
{
"answer_id": 74244150,
"author": "N69S",
"author_id": 4369919,
"author_profile": "https://Stackoverflow.com/users/4369919",
"pm_score": 0,
"selected": false,
"text": "withCount()"
},
{
"answer_id": 74244173,
"author": "Can Vural",
"author_id": 1561146,
"author_profi... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14852733/"
] |
74,243,937 | <p>Missing required parameter for [Route: blog.update] [URI: blog/{post}/update] [Missing parameter: post].</p>
<p>in routes :
<code>Route::put('/blog/{post}/update', [BlogController::class, 'update'])->name('blog.update');</code></p>
<p>in BlogController :
`</p>
<pre><code>public function update(Request $request,Post $post){
$request->validate([
'title' => 'required',
'image' => 'required | image',
'body' => 'required'
]);
$postId = $post->id;
$title = $request->input('title');
$slug = Str::slug($title,'-').'-'.$postId;
// $user_id = Auth::user()->id;
$body = $request->input('body');
//File upload
$imagePath = 'storage/'. $request->file('image')->store('postImages','public');
// $post = new Post();
$post->title = $title;
$post->slug = $slug;
// $post->user_id = $user_id;
$post->body = $body;
$post->imagePath = $imagePath;
$post->save();
return redirect()->back()->with('status', 'Post edited successfully');
dd('validation passed . You can request the input');
}
</code></pre>
<p>`</p>
<p>Please solve this issue</p>
<p>I want to update the post</p>
| [
{
"answer_id": 74244063,
"author": "xenooooo",
"author_id": 20283630,
"author_profile": "https://Stackoverflow.com/users/20283630",
"pm_score": 1,
"selected": false,
"text": "route()"
},
{
"answer_id": 74245861,
"author": "Sumit kumar",
"author_id": 11545457,
"author_... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17268403/"
] |
74,243,946 | <p>am trying to call the user from data (am using firebase as database)
the profile page not working for more understanding check the other issue i posted last day :
<a href="https://stackoverflow.com/questions/74223375/firebaseexception-cloud-firestore-unavailable-the-service-is-currently-unavai/74228594#74228594">FirebaseException ([cloud_firestore/unavailable] The service is currently unavailable , and how to solve it</a></p>
<pre class="lang-dart prettyprint-override"><code>import 'package:cached_network_image/cached_network_image.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:yumor/models/progress.dart';
import 'package:yumor/models/user_model.dart';
class profile extends StatefulWidget {
const profile({Key? key,required this.userProfile}) : super(key: key);
final String? userProfile;
@override
State<profile> createState() => _profileState();
}
class _profileState extends State<profile> {
final userRef = FirebaseFirestore.instance.collection('users');
buildprofileheader() async{
final doc=await userRef.doc(widget.userProfile).get();
if(doc.exists){
var data=doc.data();
}
return FutureBuilder(future:FirebaseFirestore.instance.collection('users').doc(userRef.id).get(),
builder: ((context, snapshot) {
if(!snapshot.hasData){
return CircularProgress();
}
UserModel user=UserModel.fromMap(Map);
return Padding(padding:EdgeInsets.all(16.0),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(Icons.account_circle, size: 90,)
],
),
Container(
alignment: Alignment.center,
padding: EdgeInsets.all(12.0),
child: Text(
user.Username as String,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize:16.0,
),
),
),
],
),
);
}),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text(
"Profile",
),
),
body: ListView(children: <Widget>[
buildprofileheader(), // the error shows in this line <=======
]));
}
}
</code></pre>
| [
{
"answer_id": 74244063,
"author": "xenooooo",
"author_id": 20283630,
"author_profile": "https://Stackoverflow.com/users/20283630",
"pm_score": 1,
"selected": false,
"text": "route()"
},
{
"answer_id": 74245861,
"author": "Sumit kumar",
"author_id": 11545457,
"author_... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16571275/"
] |
74,243,956 | <p>After typing</p>
<pre><code>STATIC_ROOT = BASE_DIR / "staticfiles"
</code></pre>
<p>in settings.py I get the error in the tittle.</p>
<p>I tried with STATICDIR but it still doesn't work. I am pretty new to django so I don't really know other ways to fix it.</p>
<p>EDIT: turns out I tried to install the template folder in the INSTALLED APPs thingy</p>
| [
{
"answer_id": 74244063,
"author": "xenooooo",
"author_id": 20283630,
"author_profile": "https://Stackoverflow.com/users/20283630",
"pm_score": 1,
"selected": false,
"text": "route()"
},
{
"answer_id": 74245861,
"author": "Sumit kumar",
"author_id": 11545457,
"author_... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18208051/"
] |
74,243,961 | <p>Question:</p>
<pre><code>Create a program that keeps information about some students and their grades.
You will receive an integer number - n.
Then, you will receive 2 \* n rows of input.
First, you will receive the student's name. Аfter that, you will receive their grade.
If the student does not exist, add them.
Keep track of all of the grades of each student.
When you finish reading the data, keep only the students which have an average grade higher or equal to 4.50.
Order the filtered students by their average grade in descending order.
Print the students and their average grade in the following format:
"{name} -\> {averageGrade}"
Format the average grade to the second decimal place.
</code></pre>
<p>Test input:</p>
<pre><code>5
John
5.5
John
4.5
Alice
6
Alice
3
George
5
</code></pre>
<p>Test output:</p>
<pre><code>John -> 5.00
George -> 5.00
Alice -> 4.50
</code></pre>
<p>My answer:</p>
<pre><code>import java.util.*;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.nextLine());
Map<String, List<Double>> records = new HashMap<>();
while(n > 0){
String name = scanner.nextLine();
double grade = Double.parseDouble(scanner.nextLine());
records.putIfAbsent(name, new ArrayList<>());
records.get(name).add(grade);
n--;
}
records.entrySet().stream().filter(item -> {
double average = item.getValue().stream().mapToDouble(x -> x).average().getAsDouble();
return average >= 4.50;
}).sorted((a, b) -> {
double average1 = a.getValue().stream().mapToDouble(x -> x).average().getAsDouble();
double average2 = b.getValue().stream().mapToDouble(x -> x).average().getAsDouble();
return (int) (average2 - average1);
}).forEach(pair -> {
double average = pair.getValue().stream().mapToDouble(x -> x).average().getAsDouble();
System.out.printf("%s -> %.2f%n", pair.getKey(), average);
});
}
}
</code></pre>
<p>I'm pretty sure I'm not doing the sorting by average part correctly but I can't seem to find another way to go about it as the sorting requires an int and the average will always be a double?</p>
<p>Any pointers/explanation will be greatly appreciated!</p>
| [
{
"answer_id": 74244063,
"author": "xenooooo",
"author_id": 20283630,
"author_profile": "https://Stackoverflow.com/users/20283630",
"pm_score": 1,
"selected": false,
"text": "route()"
},
{
"answer_id": 74245861,
"author": "Sumit kumar",
"author_id": 11545457,
"author_... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19239946/"
] |
74,244,027 | <p>My AppCenter Android build pipeline started failing all of a sudden. Not much information other than <strong>"Error starting build"</strong> title and "Could not queue the build because there were validation errors or warnings." as body. Just FYI, the android project was generated using Flutter.
<a href="https://i.stack.imgur.com/UzNpa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UzNpa.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74244063,
"author": "xenooooo",
"author_id": 20283630,
"author_profile": "https://Stackoverflow.com/users/20283630",
"pm_score": 1,
"selected": false,
"text": "route()"
},
{
"answer_id": 74245861,
"author": "Sumit kumar",
"author_id": 11545457,
"author_... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74244027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1610651/"
] |
74,244,055 | <p>If I have compile time constant <code>num_bits</code> how can I get smallest integer type that can hold this amount of bits?</p>
<p>Of course I can do:</p>
<p><a href="https://godbolt.org/z/5Pnc1xoPb" rel="nofollow noreferrer">Try it online!</a></p>
<pre class="lang-cpp prettyprint-override"><code>#include <cstdint>
#include <type_traits>
std::size_t constexpr num_bits = 19;
using T =
std::conditional_t<num_bits <= 8, uint8_t,
std::conditional_t<num_bits <= 16, uint16_t,
std::conditional_t<num_bits <= 32, uint32_t,
std::conditional_t<num_bits <= 64, uint64_t,
void>>>>;
</code></pre>
<p>But maybe there exists some ready made meta function in standard library for achieving this goal?</p>
<p>I created this question only to find out single meta function specifically from standard library. But if you have other nice suggestions how to solve this task besides my proposed above solution, then please post such solutions too...</p>
<hr />
<p><strong>Update</strong>. As suggested in comments, <code>uint_leastX_t</code> should be used instead of <code>uintX_t</code> everywhere in my code above, as <code>uintX_t</code> may not exist on some platforms, while <code>uint_leastX_t</code> always exist.</p>
| [
{
"answer_id": 74250856,
"author": "starball",
"author_id": 11107541,
"author_profile": "https://Stackoverflow.com/users/11107541",
"pm_score": 2,
"selected": true,
"text": "std::numeric_limits<T>::max"
}
] | 2022/10/29 | [
"https://Stackoverflow.com/questions/74244055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/941531/"
] |
74,244,075 | <pre><code>#include <iostream>
#include <string>
#include <cstring>
using namespace std;
string empty(string str) {
for (int i = 0;i < str.length();i++) {
if (str[i] == ' ') {
str.insert(str[i], ",");
}
cout << str[i];
}
return st;
}
int main() {
string str;
getline(cin, str);
empty(str);
return 0;
}
</code></pre>
<p>I tried string.resize, or in loop i<str.max_size, str.size and str.replace, I tried to add +1 to size or to length but nothing works.</p>
| [
{
"answer_id": 74244239,
"author": "Remy Lebeau",
"author_id": 65863,
"author_profile": "https://Stackoverflow.com/users/65863",
"pm_score": 3,
"selected": true,
"text": "insert()"
},
{
"answer_id": 74244297,
"author": "Ankur Dahiya",
"author_id": 19084200,
"author_pr... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74244075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17321497/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.