qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,436,005 | <p>I want to use an older commit and add different changes (but I do not want to delete my commit history). Currently, something like this will delete the last 3 commits in my GitHub pull request history and show a new commit with my new changes:</p>
<pre><code>git reset HEAD~3
git add .
git commit -m "New changes"
git push --force
</code></pre>
<p>Is there a way to keep my last 3 commits and then have a 4th commit with "New changes"?</p>
<p><em>What I Want to Happen:</em>
Add a new commit WITHOUT removing the last three commits in history</p>
<p><em>What Actually Resulted:</em>
A new commit, in place of the last three commits.</p>
| [
{
"answer_id": 74436396,
"author": "knittl",
"author_id": 112968,
"author_profile": "https://Stackoverflow.com/users/112968",
"pm_score": 1,
"selected": false,
"text": "$ git rebase -i A\n$ # now change the line \"pick B\" to \"edit B\" and save the file\n$ # make your changes and stage (add) them\n$ git commit --amend # create commit B'\n$ git rebase --continue\n$ # git will automatically create C'-D'-E'\n"
},
{
"answer_id": 74437026,
"author": "eftshift0",
"author_id": 2437508,
"author_profile": "https://Stackoverflow.com/users/2437508",
"pm_score": 3,
"selected": true,
"text": "git restore --staged --worktree --source=HEAD~3 -- .\ngit commit \"reverting to blahblah\"\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8710452/"
] |
74,436,017 | <p>I'm having difficulty setting the <code>References:</code> field in the header of an outgoing SMTP email for Gmail. I'm using Python 3.8 with <code>smtplib</code> and <code>email.message</code> libraries. The code is:</p>
<pre><code>reference_ids = [
'<BN8PR17MB27372595A957D7912CEE184FBF6F9@BN8PR17MB2737.namprd17.prod.outlook.com>',
'<CAM9Ku=FZ5RGMvw3VzNrZz+DA78zyq2Am8fz9JNLmjUQ9ZEXpDQ@mail.gmail.com>',
'<BN8PR17MB27371C71A65834531DF028BBBF6F9@BN8PR17MB2737.namprd17.prod.outlook.com>',
'<CAM9Ku=E1wmpj=AMRhsh-Sk1RHqmK_x-J5ey8szVehefYQvn13w@mail.gmail.com>']
in_reply_to = reference_ids[0]
smtp = smtplib.SMTP_SSL(es.smtp_server)
smtp.login(es.username, es.password)
msg = email.message.EmailMessage()
if (reference_ids is not None):
msg.add_header('In-Reply-To', in_reply_to)
msg.add_header('References', (' ').join(reference_ids))
msg['Subject'] = request.vars.subject
msg['From'] = es.email
msg['To'] = request.vars.to
msg['CC'] = request.vars.cc
msg['BCC'] = request.vars.bcc
msg.set_content(request.vars.message)
smtp.send_message(msg)
smtp.quit()
</code></pre>
<p>where <code>reference_ids</code> is a list of Message-IDs previous "in_reply_to"s of "message_id"s back to the originating email.</p>
<p>I can send the email without errors and when I view the "Show original" the References look ok. it is the proper list of Message-IDs of the form "BNX_blah_blah@mail.gmail.com", without quotes, separated by a space.</p>
<p>However, when I try to later read the sent email with the <code>imaplib</code> library and <code>email.message_from_bytes(raw_email_response_body[1])</code> I get a real mess of characters. Most of the addresses in the References loose their BNX_blah_blah@mail.gmail.com" form. Message-ID and In-Reply-To looks ok though.</p>
<pre><code>References: =?utf-8?q?=22=3CBN8PR17MB27372595A957D7912CEE184FBF6F9=40BN8PR17?=
=?utf-8?q?MB2737=2Enamprd17=2Eprod=2Eoutlook=2Ecom=3E?=
<CAM9Ku=FZ5RGMvw3VzNrZz+DA78zyq2Am8fz9JNLmjUQ9ZEXpDQ@mail.gmail.com>
=?utf-8?q?=3CBN8PR17MB27371C71A65834531DF028BBBF6F9=40BN8PR17MB2737=2Enampr?=
=?utf-8?q?d17=2Eprod=2Eoutlook=2Ecom=3E_=3CBN8PR17MB27377F609B669D0E72638D6?=
=?utf-8?q?9BF6F9=40BN8PR17MB2737=2Enamprd17=2Eprod=2Eoutlook=2Ecom=3E?=
<CAM9Ku=E1wmpj=AMRhsh-Sk1RHqmK_x-J5ey8szVehefYQvn13w@mail.gmail.com>
</code></pre>
<p>Am I encoding the References properly? Am I decoding the References I read from IMAP properly?</p>
| [
{
"answer_id": 74436396,
"author": "knittl",
"author_id": 112968,
"author_profile": "https://Stackoverflow.com/users/112968",
"pm_score": 1,
"selected": false,
"text": "$ git rebase -i A\n$ # now change the line \"pick B\" to \"edit B\" and save the file\n$ # make your changes and stage (add) them\n$ git commit --amend # create commit B'\n$ git rebase --continue\n$ # git will automatically create C'-D'-E'\n"
},
{
"answer_id": 74437026,
"author": "eftshift0",
"author_id": 2437508,
"author_profile": "https://Stackoverflow.com/users/2437508",
"pm_score": 3,
"selected": true,
"text": "git restore --staged --worktree --source=HEAD~3 -- .\ngit commit \"reverting to blahblah\"\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7792905/"
] |
74,436,043 | <p>Please help me with a solution to extract in a new array only the specific object that has the paramenter checked: true.
See the example below:</p>
<pre><code> {nodeName: 'node1', nodeId: 1, checked: false },
{nodeName: 'node2', nodeId: 2, checked: true },
{nodeName: 'node3', nodeId: 3, checked: false },
{nodeName: 'node4', nodeId: 4, checked: true },
{nodeName: 'node5', nodeId: 5, checked: false },
{nodeName: 'node6', nodeId: 6, checked: true },
]
let checkedNodes = nodes.map(node => {
let options = {
"name": node.nodeName,
"id": node.nodeId,
"checked": node.checked
}
return options;
})
</code></pre>
<p>This will return all the nodes :(<br>
How can I make the verification, in order to return the array like this?</p>
<pre><code>[
{
"name": "node2",
"id": 2,
"checked": true
},
{
"name": "node4",
"id": 4,
"checked": true
},
{
"name": "node6",
"id": 6,
"checked": true
}
]
</code></pre>
| [
{
"answer_id": 74436059,
"author": "Chris Heald",
"author_id": 271475,
"author_profile": "https://Stackoverflow.com/users/271475",
"pm_score": 1,
"selected": false,
"text": "// Find the first checked node, or undefined if none are checked\nconst checkedNodes = nodes.find(node => node.checked);\n\n// Find all checked nodes\nconst checkedNodes = nodes.filter(node => node.checked);\n"
},
{
"answer_id": 74436089,
"author": "Majed Badawi",
"author_id": 7486313,
"author_profile": "https://Stackoverflow.com/users/7486313",
"pm_score": 0,
"selected": false,
"text": "Array#map"
},
{
"answer_id": 74436106,
"author": "samanime",
"author_id": 1261825,
"author_profile": "https://Stackoverflow.com/users/1261825",
"pm_score": 1,
"selected": true,
"text": ".map()"
},
{
"answer_id": 74436108,
"author": "ilkerkaran",
"author_id": 2630427,
"author_profile": "https://Stackoverflow.com/users/2630427",
"pm_score": 0,
"selected": false,
"text": "filter"
},
{
"answer_id": 74436147,
"author": "Nikkkshit",
"author_id": 11850259,
"author_profile": "https://Stackoverflow.com/users/11850259",
"pm_score": 0,
"selected": false,
"text": "filter()"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9971933/"
] |
74,436,073 | <p>I have this code:</p>
<pre><code> tbl <- with(mydata, table(Species, Depth))
library(ggplot2)
ggplot(as.data.frame(tbl), aes(factor(Depth), Freq, fill = Species)) +
geom_col(position = 'dodge')
</code></pre>
<p>and this dataframe</p>
<pre><code> Site Depth Substrate PoePres HaliPres Species
1 2 0.5 Sand 0 1 DMonte
2 2 0.5 Sand 0 1 DMonte
3 2 0.5 Sand 0 1 DMonte
4 2 0.5 Sand 0 1 DMonte
5 2 0.5 Sand 0 1 DMonte
6 2 0.5 Sand 0 1 DSandi
7 2 0.5 Sand 0 1 DSandi
8 2 0.5 Sand 0 1 DSandi
9 7 0.6 Sand 0 1 DMonte
10 7 0.6 Sand 0 1 DMonte
11 7 0.6 Sand 0 1 DMonte
</code></pre>
<p>That I took from this other question: <a href="https://stackoverflow.com/questions/29371333/bar-plot-for-count-data-by-group-in-r/74436026#74436026">Bar plot for count data by group in R</a></p>
<p>I would like to know how I could plot percentage per group ('Depth' in this case) rather than counts.</p>
<p>Thanks</p>
| [
{
"answer_id": 74436059,
"author": "Chris Heald",
"author_id": 271475,
"author_profile": "https://Stackoverflow.com/users/271475",
"pm_score": 1,
"selected": false,
"text": "// Find the first checked node, or undefined if none are checked\nconst checkedNodes = nodes.find(node => node.checked);\n\n// Find all checked nodes\nconst checkedNodes = nodes.filter(node => node.checked);\n"
},
{
"answer_id": 74436089,
"author": "Majed Badawi",
"author_id": 7486313,
"author_profile": "https://Stackoverflow.com/users/7486313",
"pm_score": 0,
"selected": false,
"text": "Array#map"
},
{
"answer_id": 74436106,
"author": "samanime",
"author_id": 1261825,
"author_profile": "https://Stackoverflow.com/users/1261825",
"pm_score": 1,
"selected": true,
"text": ".map()"
},
{
"answer_id": 74436108,
"author": "ilkerkaran",
"author_id": 2630427,
"author_profile": "https://Stackoverflow.com/users/2630427",
"pm_score": 0,
"selected": false,
"text": "filter"
},
{
"answer_id": 74436147,
"author": "Nikkkshit",
"author_id": 11850259,
"author_profile": "https://Stackoverflow.com/users/11850259",
"pm_score": 0,
"selected": false,
"text": "filter()"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9410595/"
] |
74,436,096 | <p>I find it difficult to force the deserialize operation to <strong>actually fail</strong> if the data doesn't match exactly what's expected for the output class.</p>
<pre><code>class ContainerClass {
string SomeString { get; set; } // <-- not nullable
}
</code></pre>
<p>Json file :</p>
<pre><code>[
{
"SomeString": null, // <-- null
}
]
</code></pre>
<p>Deserialize function :</p>
<pre><code>using JsonTextReader reader = new JsonTextReader(file); // <-- the file I got from my controller.
var serializer = Newtonsoft.Json.JsonSerializer.Create(); // or new Serializer, whatever
serializer.MissingMemberHandling = MissingMemberHandling.Error;
return serializer.Deserialize<Collection<RegisterImportItem>>(reader);
</code></pre>
<p>I want the deserialize to fail if the string has a null value.
The code above succeeds silently <strong>and places a null value in the non-nullable field.</strong> The horror!</p>
<p>I'd like to achive that by <strong>configuring</strong> the serializer (as in : I don't want to add <strong>a decorator above the field itself</strong> ).</p>
<p>Long things short: I want <strong>all</strong> non-nullable fields to fail if the value is null, no matter what.</p>
| [
{
"answer_id": 74436161,
"author": "Daniel A. White",
"author_id": 23528,
"author_profile": "https://Stackoverflow.com/users/23528",
"pm_score": 0,
"selected": false,
"text": "JsonProperty"
},
{
"answer_id": 74436736,
"author": "Serge",
"author_id": 11392290,
"author_profile": "https://Stackoverflow.com/users/11392290",
"pm_score": -1,
"selected": false,
"text": " var json=@\"[\n {\n \"\"SomeString\"\": null, // <-- null\n \"\"JustString\"\": \"\"test\"\" \n }\n]\";\n var test = JsonConvert.DeserializeObject<ContainerClass[]>(json);\n\n"
},
{
"answer_id": 74442470,
"author": "jeancallisti",
"author_id": 9359785,
"author_profile": "https://Stackoverflow.com/users/9359785",
"pm_score": -1,
"selected": false,
"text": "public class RequireObjectPropertiesContractResolver : DefaultContractResolver\n{\n protected override JsonObjectContract CreateObjectContract(Type objectType)\n {\n var contract = base.CreateObjectContract(objectType);\n contract.ItemRequired = Required.Always;\n return contract;\n }\n}\n\nvar settings = new JsonSerializerSettings { ContractResolver = new RequireObjectPropertiesContractResolver() };\n\nvar serializer = Newtonsoft.Json.JsonSerializer.Create(settings);\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9359785/"
] |
74,436,183 | <p>I am absolutely NOT a developer, but I am trying to get this abandoned app to work</p>
<p>This is the code in a file called layout.erb which is HTML</p>
<pre><code><div class="container">
<%= yield %>
</div>
</code></pre>
<p>It's throwing this error:</p>
<p>SyntaxError - /wallop/app/views/layout.erb:53: Invalid yield:</p>
<p>I understand that they're using Bootstrap and that "yield" is a special term in Ruby and the %'s are supposed to print and evaluate the code -- I get all that, I just don't see why it's erroring.</p>
<p>This app was written a long time ago and abandoned, the devs moved on and made a commercial version of it, so they are not interested in helping update the old source, I am more or less interested in tinkering with it so that I can teach myself Docker and some other things.</p>
<p>I have not tried anything, just researched the error</p>
<p>I think this may have something to do with the fact that this is an old app and it was written in Ruby 2 and I'm running Ruby 3, but that is just a guess.</p>
<p>UPDATE:</p>
<p>This is exactly the same problem, the app is also using Sinatra / Thin:</p>
<p><a href="https://github.com/mocdaniel/dashing-icinga2/issues/121" rel="nofollow noreferrer">https://github.com/mocdaniel/dashing-icinga2/issues/121</a></p>
<p>They fixed it by reverting to an older Ruby version, however I’m not sure I’ll be able to do that easily</p>
<p>I’m using alpine:latest and then running apk add ruby-json ruby-dev and ruby-bundler from the repo, it’s grabbing the latest versions…I don’t know alpine or Docker well enough to specify how to grab the older versions and I would prefer not to compile & install them manually.</p>
<p>It may actually be easier to just fix the code to work with Ruby 3.</p>
| [
{
"answer_id": 74436161,
"author": "Daniel A. White",
"author_id": 23528,
"author_profile": "https://Stackoverflow.com/users/23528",
"pm_score": 0,
"selected": false,
"text": "JsonProperty"
},
{
"answer_id": 74436736,
"author": "Serge",
"author_id": 11392290,
"author_profile": "https://Stackoverflow.com/users/11392290",
"pm_score": -1,
"selected": false,
"text": " var json=@\"[\n {\n \"\"SomeString\"\": null, // <-- null\n \"\"JustString\"\": \"\"test\"\" \n }\n]\";\n var test = JsonConvert.DeserializeObject<ContainerClass[]>(json);\n\n"
},
{
"answer_id": 74442470,
"author": "jeancallisti",
"author_id": 9359785,
"author_profile": "https://Stackoverflow.com/users/9359785",
"pm_score": -1,
"selected": false,
"text": "public class RequireObjectPropertiesContractResolver : DefaultContractResolver\n{\n protected override JsonObjectContract CreateObjectContract(Type objectType)\n {\n var contract = base.CreateObjectContract(objectType);\n contract.ItemRequired = Required.Always;\n return contract;\n }\n}\n\nvar settings = new JsonSerializerSettings { ContractResolver = new RequireObjectPropertiesContractResolver() };\n\nvar serializer = Newtonsoft.Json.JsonSerializer.Create(settings);\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20503357/"
] |
74,436,206 | <p>Hi I am trying to store Request Response of a client to a file.I was easily able to do it for HttpRequest</p>
<p>But when I am trying to write Encoder decoder for HttpResponse I am not able to understand how to write it for entity of HttpResponse in scala.</p>
<p>Heres the code for HTTP Request encoder decoder</p>
<pre><code>
val demo=HttpRequest(
method= HttpMethods.GET,
uri="myUri",
headers=generateHeaders(Map.empty),
entity="{\"customerReferenceIds\":[{\"customerId\":\"9600007934256702\",\"customerIdType\":\"CUSTOMER_ID\"}]}",
)
demo.asJson.spaces2
</code></pre>
<p>I was able to write encoder decoder for HttpRequest easily.</p>
<pre><code>implicit val HttpRequestEncoder: Encoder[HttpRequest] = new Encoder[HttpRequest] {
final def apply(x: HttpRequest): Json = Json.obj(
("method", Json.fromString(x.method.value)),
("Uri", Json.fromString(x.uri.toString())) ,
("headers", x.headers.map(y=>y.name->y.value).toMap.asJson),
("entity", Json.fromString(JsonUtil.toJson(x.entity)))
)
}
implicit val HttpRequestDecoder: Decoder[HttpRequest] = new Decoder[HttpRequest] {
final def apply(c: HCursor): Decoder.Result[HttpRequest] =
for {
method <- c.downField("method").as[String]
url <- c.downField("Uri").as[String]
header <- c.downField("headers").as[Map[String,String]]
entity <- c.downField("entity").as[String]
} yield {
HttpRequest(
method=HttpMethods.getForKeyCaseInsensitive(method).getOrElse(HttpMethods.GET),
uri = url,
headers=generateHeaders(header),
entity= HttpEntity(ContentTypes.`application/json`,JsonUtil.toJson(entity))
)
}
}
</code></pre>
<p>I am trying to write for encoder decoder for HttpResponse .Doing something like</p>
<pre><code>
//HttpResponse
implicit val HttpResponseEncoder: Encoder[HttpResponse] = new Encoder[HttpResponse] {
final def apply(x: HttpResponse): Json = {
Json.obj(
("response", Json.fromString(JsonUtil.toJson(x.entity))),
("status", Json.fromInt(x.status.intValue()))
)
}
}
implicit val HttpResponseDecoder: Decoder[HttpResponse] = new Decoder[HttpResponse] {
final def apply(c: HCursor): Decoder.Result[HttpResponse] =
for {
entity <- c.downField("response").as[String]
status <- c.downField("status").as[Int]
} yield {
HttpResponse(
status = StatusCode.int2StatusCode(status),
entity = HttpEntity(ContentTypes.`application/json`, JsonUtil.toJson(entity))
)
}
}
</code></pre>
<p>Where entity is something like this in debugger
<a href="https://i.stack.imgur.com/WUIKD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WUIKD.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74458347,
"author": "Stanislav Kovalenko",
"author_id": 8099169,
"author_profile": "https://Stackoverflow.com/users/8099169",
"pm_score": 0,
"selected": false,
"text": "HttpResponse"
},
{
"answer_id": 74458823,
"author": "Freez",
"author_id": 11526227,
"author_profile": "https://Stackoverflow.com/users/11526227",
"pm_score": -1,
"selected": true,
"text": " val testconfig: Config = ConfigFactory.load()\n implicit val actorSystem2: ActorSystem = ActorSystem.create(\"loyalty-execution-api\", testconfig)\n \n implicit val executionContext: ExecutionContext = actorSystem2.dispatcher\n \n implicit val HttpResponseEncoder: Encoder[HttpResponse] = new Encoder[HttpResponse] {\n import akka.http.scaladsl.unmarshalling\n final def apply(x: HttpResponse): Json = {\n val result = Unmarshal(x.entity).to[String].map { z =>\n Json.obj(\n (\"response\", Json.fromString(z)),\n (\"status\", Json.fromInt(x.status.intValue()))\n )\n }\n val r3 = Await.result(result, 20.seconds)\n r3\n }\n }\n \n implicit val HttpResponseDecoder: Decoder[HttpResponse] = new Decoder[HttpResponse] {\n final def apply(c: HCursor): Decoder.Result[HttpResponse] =\n for {\n entity <- c.downField(\"response\").as[String]\n status <- c.downField(\"status\").as[Int]\n } yield {\n HttpResponse(\n status = StatusCode.int2StatusCode(status),\n entity = HttpEntity(ContentTypes.`application/json`, JsonUtil.toJson(entity))\n )\n }\n }\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11526227/"
] |
74,436,238 | <p>I have a custom user model with a field 'customer'. Each user has a customer. I am trying to get the logged in users customer so that when I add infringer, the correct customer is added for the record.</p>
<ol>
<li>I think below is wrong in views. customer=request.user.customer</li>
<li>think below is wrong in forms. customer__user=self.customer</li>
</ol>
<p>views.py</p>
<pre><code>@login_required(login_url='login')
def createInfringer(request):
customer=request.user.customer
form = InfringerForm(customer=request.customer)
if request.method == 'POST':
form = InfringerForm(customer, request.POST)
if form.is_valid():
form.save()
return redirect('infringer-list')
context ={'form': form}
return render (request, 'base/infringement_form.html', context)
</code></pre>
<p>forms.py</p>
<pre><code>class InfringerForm(ModelForm):
def __init__(self, customer, *args, **kwargs):
self.customer = customer
super(InfringerForm,self).__init__(*args, **kwargs)
self.fields['customer'].queryset = Customer.objects.filter(customer__user=self.customer)
class Meta:
model = Infringer
fields = ['name', 'brand_name','status' , 'customer']
</code></pre>
<p>models.py</p>
<pre><code>class Infringer (models.Model):
name = models.CharField(max_length=200)
brand_name = models.CharField(max_length=200, null=True)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
groups = models.ForeignKey(Group, on_delete=models.CASCADE,default=1)
status = models.ForeignKey(Status, on_delete=models.SET_NULL,null=True)
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL,null=True)
class Meta:
ordering = ['-updated', '-created']
def __str__(self):
return self.name
class Customer (models.Model):
name = models.CharField(max_length=200)
email = models.EmailField(max_length=254, default='@cudo.ai')
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
phone_number = PhoneNumberField(blank=True)
groups = models.ForeignKey(Group, on_delete=models.CASCADE,default=1)
player = models.ManyToManyField(Player, related_name='player', blank=True)
is_active = models.BooleanField(default=False)
class Meta:
ordering = ['name']
def __str__(self):
return self.name
class User(AbstractUser):
email = models.EmailField(unique=True, null=True)
avatar = models.ImageField(null=True, default="logo.svg")
username = models.CharField(max_length=40, unique=False,
default='')
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL,null=True)
</code></pre>
| [
{
"answer_id": 74436913,
"author": "omer-bental",
"author_id": 14147658,
"author_profile": "https://Stackoverflow.com/users/14147658",
"pm_score": 3,
"selected": true,
"text": "form = InfringerForm(customer=customer)"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20453400/"
] |
74,436,263 | <p>I combined Firebase auth, riverpod, and Gorouter via Luca Venir's <a href="https://github.com/lucavenir/go_router_riverpod/tree/master/firebase_example" rel="nofollow noreferrer">repository here</a>. It really works great. Now my issue is that I'm making a web app, and I don't know how to access the GoRouter routes that are inside the routerProvider to change the page when the user clicks on a nav item. It seems like a simple issue, but I've had problems with navigation and global keys before.</p>
<p>I've abbreviated my code to what I believe are the most essential parts, but let me know if more is needed. My routerProvider is based on my auth repo, which utilizes Firebase.</p>
<pre><code>`final routerProvider = Provider<GoRouter>((ref) {
final authState = ref.watch(authStateProvider);
return GoRouter(
navigatorKey: key,
debugLogDiagnostics: true,
initialLocation: SplashPage.routeLocation,
routes: [
GoRoute(
path: SplashPage.routeLocation,
name: SplashPage.routeName,
builder: (context, state) {
return const SplashPage();
},
),
GoRoute(
path: '/preloginhome',
name: 'preloginhome',
builder: (context, state) {
return const PreLoginHome();
},
),
GoRoute(
path: '/dashboard',
name: 'dashboard',
builder: (context, state) {
return const Dashboard();
},
),
//more code
</code></pre>
<p>The main app watches the above routerProvider
`</p>
<pre><code>class MyAppWithFirebase extends ConsumerWidget {
const MyAppWithFirebase({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final router = ref.watch(routerProvider);
return MaterialApp.router(
theme: CustomTheme.darkTheme,
routeInformationParser: router.routeInformationParser,
routerDelegate: router.routerDelegate,
routeInformationProvider: router.routeInformationProvider,
);
}
}
</code></pre>
<p>Now my questoion is, how can I navigate with the routes declared in routerProvider? My custom app bar is something like this but I'm missing something..</p>
<pre><code>class CustomAppBar extends ConsumerWidget implements PreferredSizeWidget {
const CustomAppBar({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final router = ref.watch(routerProvider);
final isUserSignedIn = FirebaseAuth.instance.currentUser != null;
return AppBar(
title: TextButton(
onPressed: isUserSignedIn
? () {
key.currentState!.pushNamed(Dashboard.routeLocation);
}
: () {
key.currentState!.pushNamed('/preloginhome');
},
child: Text(
'Agroopet',
style: TextStyle(
fontSize: 22,
color: Theme.of(context).colorScheme.onSurface,
),
),
),
</code></pre>
<p>Just don't know how to properly access the routes in the routerProvider and also am incorrectly setting the global nav key.</p>
<p>With the above code I get the error</p>
<blockquote>
<p>"Another exception was thrown: Navigator.onGenerateRoute was null, but
the route named "/preloginhome" was referenced."</p>
</blockquote>
| [
{
"answer_id": 74436913,
"author": "omer-bental",
"author_id": 14147658,
"author_profile": "https://Stackoverflow.com/users/14147658",
"pm_score": 3,
"selected": true,
"text": "form = InfringerForm(customer=customer)"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16922954/"
] |
74,436,293 | <p>i would like to have a "global" object that persist in the application, even when you start other activity or fragment, its kind of annoying to use a bundle to pass the same elements in the app. Maybe with viewmodels? i dont know too much about that , so it would be handy if you give me an example or some guidance in this subject. Thank you in advance:)</p>
| [
{
"answer_id": 74436783,
"author": "Parneet Raghuvanshi",
"author_id": 13939499,
"author_profile": "https://Stackoverflow.com/users/13939499",
"pm_score": 0,
"selected": false,
"text": "import android.app.Application;\n\npublic class MyApplication extends Application {\n\n public String yourObj;\n\n public String getYourObj() {\n return yourObj;\n }\n\n public void setYourObj(String yourObj) {\n this.yourObj = yourObj;\n }\n}\n"
},
{
"answer_id": 74438141,
"author": "OVO Cuenta",
"author_id": 19861170,
"author_profile": "https://Stackoverflow.com/users/19861170",
"pm_score": 1,
"selected": false,
"text": "class ApplicationData {\n companion object {\n var string:String? =null\n }\n }\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19861170/"
] |
74,436,294 | <p>I have a</p>
<pre><code>Querysnapshot snapshot
</code></pre>
<p>I can supply an index and access the fields of the document perfectly like:</p>
<pre><code>snapshot.data!.docs[index]
</code></pre>
<p>However, I want to access the field of document 'thisParticularDocument' which is the id (name) of the document in Cloud Firestore.</p>
<p>I want to use</p>
<pre><code>snapshot.data!.docs[thisParticularDocument]
</code></pre>
<p>but that doesn't work because you can only supply an index to <em>docs</em>.</p>
<p>I want a solution that preferably involves no async await.</p>
| [
{
"answer_id": 74436476,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 0,
"selected": false,
"text": "QuerySnapshot"
},
{
"answer_id": 74437368,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 3,
"selected": true,
"text": " snapshot.data!.docs.firstWhere((doc) => doc.id == \"the document Id\").data() as Map<String, dynamic>;\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12917683/"
] |
74,436,295 | <p>Dear R community on SO,</p>
<p>I am trying to create a wrapper function around <code>ggplot2::facet_wrap()</code>.</p>
<p>My goal would be to pass a <code>split_by</code> parameter to <code>ggplot2::facet_wrap()</code>, possibly unquoted, as follows:</p>
<p><code>my_ggplot2_wrapper(my_data, x = some_x_col, y = some_y_col, split_by = another_discrete_var)</code>.</p>
<p><code>split_by</code> would be a column contained in the data I pass to my wrapper.</p>
<p>Below is what I have tried.</p>
<p>Thanks in advance for considering my request.</p>
<p>Other solutions I've tried without success:</p>
<ul>
<li><code>p + ggplot2::facet_wrap(ggplot2::vars(split_by), ncol = 2, nrow = 2)</code></li>
<li><code>p + ggplot2::facet_wrap({{ split_by }}, ncol = 2, nrow = 2)</code></li>
</ul>
<pre class="lang-r prettyprint-override"><code>sessionInfo()
#> R version 4.1.3 (2022-03-10)
#> Platform: x86_64-apple-darwin17.0 (64-bit)
#> Running under: macOS Big Sur/Monterey 10.16
#>
#> Matrix products: default
#> BLAS: /opt/R/4.1.3/Resources/lib/libRblas.0.dylib
#> LAPACK: /opt/R/4.1.3/Resources/lib/libRlapack.dylib
#>
#> locale:
#> [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
#>
#> attached base packages:
#> [1] stats graphics grDevices utils datasets methods base
#>
#> loaded via a namespace (and not attached):
#> [1] withr_2.5.0 digest_0.6.29 R.methodsS3_1.8.2 lifecycle_1.0.2
#> [5] magrittr_2.0.3 reprex_2.0.2 evaluate_0.16 highr_0.9
#> [9] stringi_1.7.8 rlang_1.0.6 cli_3.4.1 rstudioapi_0.14
#> [13] fs_1.5.2 R.utils_2.12.1 R.oo_1.25.0 styler_1.8.1
#> [17] rmarkdown_2.16 tools_4.1.3 stringr_1.4.1 R.cache_0.16.0
#> [21] glue_1.6.2 purrr_0.3.4 xfun_0.32 yaml_2.3.5
#> [25] fastmap_1.1.0 compiler_4.1.3 htmltools_0.5.3 knitr_1.40
set.seed(2022)
library(rlang)
ts <- tibble::tibble(
ds = seq(as.Date("2018-01-01"), as.Date("2019-12-31"), by = "1 day"),
y = rnorm(length(ds), mean = 50, sd = 10)
)
ts_component <- purrr::map_dfr(
c("A", "B", "C", "D"),
~ dplyr::mutate(ts, component = .x)
)
ts_component
#> # A tibble: 2,920 × 3
#> ds y component
#> <date> <dbl> <chr>
#> 1 2018-01-01 59.0 A
#> 2 2018-01-02 38.3 A
#> 3 2018-01-03 41.0 A
#> 4 2018-01-04 35.6 A
#> 5 2018-01-05 46.7 A
#> 6 2018-01-06 21.0 A
#> 7 2018-01-07 39.4 A
#> 8 2018-01-08 52.8 A
#> 9 2018-01-09 57.5 A
#> 10 2018-01-10 52.4 A
#> # … with 2,910 more rows
my_ggplot2_wrapper <- function(data, x = ds, y = y, split_by = NULL) {
split_by <- rlang::enquo(split_by)
p <- ggplot2::ggplot() +
ggplot2::geom_line(
data = data,
ggplot2::aes(x = {{ x }}, y = {{ y }})
)
if (!is.null(split_by)) {
p + ggplot2::facet_wrap(ggplot2::vars(!!split_by), ncol = 2, nrow = 2)
}
p
}
# I would expect `split_by` to work and provide four panels named A, B, C, D, instead of a single one.
my_ggplot2_wrapper(data = ts_component, split_by = component)
</code></pre>
<p><img src="https://i.imgur.com/GTov5He.png" alt="" /></p>
<p><sup>Created on 2022-11-14 with <a href="https://reprex.tidyverse.org" rel="nofollow noreferrer">reprex v2.0.2</a></sup></p>
| [
{
"answer_id": 74436790,
"author": "Gregor Thomas",
"author_id": 903061,
"author_profile": "https://Stackoverflow.com/users/903061",
"pm_score": 3,
"selected": true,
"text": "p <- p + facet_wrap..."
},
{
"answer_id": 74436809,
"author": "asd-tm",
"author_id": 5043424,
"author_profile": "https://Stackoverflow.com/users/5043424",
"pm_score": 1,
"selected": false,
"text": "library(ggplot2)\nlibrary(magrittr)\n\n\ngg <- function(coln = \"carb\"){\n mtcars %>% \n ggplot(aes(cyl, mpg))+\n geom_bar(stat = \"identity\") +\n facet_wrap(bquote(~ .(sym(coln)))) \n}\n\ngg(\"carb\")\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16468630/"
] |
74,436,325 | <p>I want to achieve the following Header Style with flexbox in React Native. The Image should always be centered and the Arrow Button must always stick on the left side.</p>
<p>What I tried so far:</p>
<pre><code> <View style={{ flexDirection: 'row' }}>
<Ionicons name="chevron-back" size={32} />
<Image
style={{ height: 120, width: 120 }}
source={{
uri: imgUrl,
}}
/>
</View>
</code></pre>
<p><a href="https://i.stack.imgur.com/F3DkK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/F3DkK.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74436545,
"author": "user18309290",
"author_id": 18309290,
"author_profile": "https://Stackoverflow.com/users/18309290",
"pm_score": 2,
"selected": true,
"text": "justifyContent"
},
{
"answer_id": 74436698,
"author": "Hemant Singh Yadav",
"author_id": 20470646,
"author_profile": "https://Stackoverflow.com/users/20470646",
"pm_score": 0,
"selected": false,
"text": " .main-div{\n display: flex;\n justify-content: space-between;\n }\n \n .size-Of-Icon {\n width: 40px;\n border: 1px solid blue;\n }\n \n .image {\n height: 180px;\n border: 1px solid red;\n }\n "
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10232665/"
] |
74,436,369 | <p>I have a <code>tweet();</code> function in a cronjob that executes every hour, and in one of my files used to get data for that function I have an if else statement. What I want to do is; if the statement is true, I want the <code>tweet()</code> function not to execute at that time, and since this is an hourly cronjob it should just skip execution for that hour but the app should still be running, it shouldn't stop or crash or anything. How would I do this?</p>
<p><strong>index.js (Where the tweet/cron is executed)</strong></p>
<pre><code>// MODULES
const rwClient = require("./TwitterClient.js");
const cronjob = require("cron").CronJob;
const priceModule = require("./price");
const nameModule = require("./name");
const dateModule = require("./date");
const stockModule = require("./stock");
const numShares = require("./numShares.js");
(async () => {
// Async function that creates the Tweet
const tweet = async () => {
try {
await rwClient.v2.tweet(
//
"New insider trade! (form 4 filed)" + '\n' + '\n' +
await nameModule() + " bought " + await numShares() + " shares at " + "$" + await priceModule() + '\n' + '\n' +
"Total Amount Purchased: " + "$" + await numShares() * await priceModule() + '\n' +
"Stock: " + await stockModule() + '\n' +
"Date: " + await dateModule() + '\n'
);
} catch (error) {
console.error(error);
}
}
// CronJob, starts from 10 am to 8pm EST
const job = new cronjob("0 14-23 * * *", () => {
tweet();
console.log("Tweet executed");
});
job.start();
})();
</code></pre>
<p><strong>price.js, file with the if statement</strong></p>
<pre><code>// MODULES
const puppeteer = require("puppeteer");
// Url where we get and scrape the data from
const url = "https://www.sec.gov/edgar/search/#/dateRange=30d&category=custom&forms=4";
let browser;
module.exports = () => (async () => {
browser = await puppeteer.launch();
const [page] = await browser.pages();
//Set User Agent
const ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36";
await page.setUserAgent(ua);
//Go to page from URL and reload
await page.goto(url, {waitUntil: "domcontentloaded", timeout: 0});
await page.reload({waitUntil: "domcontentloaded"});
//Get success response and check if url ends with .xml
const responseP = page.waitForResponse(res =>
res.status() === 200 && res.url().endsWith(".xml")
);
//Click on Form 4 link to the left
const a = await page.waitForSelector(".filetype .preview-file");
await a.click();
const html = await (await responseP).text();
await page.evaluate(html => document.body.outerHTML = html, html);
//Get the info about the stocks price
const price = await page.$$eval(".FormText", els =>
els.find(e => e.textContent.trim() === "$")//Search for a node with a "$" symbol
.parentNode
.textContent
.replace("$", "")
.replace("(1)", "")
.trim()
);
const Price = parseInt(price); //Convert price from string to number
await page.reload({waitUntil: "domcontentloaded"});
await page.close();
await browser.close();
// -------------------- IF STATEMENT --------------------
// If Price is less than $0.1, throw exception
if (Price < 0.1 || null || undefined) {
throw "Price is 0"
} else {
return Price;
}
// -------------------- IF STATEMENT --------------------
})()
.catch(err => console.error(err))
.finally(() => browser?.close());
</code></pre>
<p>PS: The <code>price</code> is exported as a module to the index.js as <code>priceModule</code> and I made an if statement that throws an error when the conditions are true, but that doesn't produce the effect I wanted, it just prints the error onto the terminal.</p>
| [
{
"answer_id": 74436545,
"author": "user18309290",
"author_id": 18309290,
"author_profile": "https://Stackoverflow.com/users/18309290",
"pm_score": 2,
"selected": true,
"text": "justifyContent"
},
{
"answer_id": 74436698,
"author": "Hemant Singh Yadav",
"author_id": 20470646,
"author_profile": "https://Stackoverflow.com/users/20470646",
"pm_score": 0,
"selected": false,
"text": " .main-div{\n display: flex;\n justify-content: space-between;\n }\n \n .size-Of-Icon {\n width: 40px;\n border: 1px solid blue;\n }\n \n .image {\n height: 180px;\n border: 1px solid red;\n }\n "
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17164833/"
] |
74,436,421 | <p>I have a list that I want to edit. For all the elements that start with '[x]', I want the list to remove those elements and place them into new list. But for the new list, in doing so, it should remove the '[x]' from the front of the elements.</p>
<pre><code>list1 = ['[x]final', '[x]gym', 'midterm', '[x]class', 'school']
</code></pre>
<p>list1 becomes:</p>
<pre><code>list1 = ['midterm', 'school']
</code></pre>
<p>new list that was created from removing the elements that had '[x]' in the front:</p>
<pre><code>new_list = ['final', 'gym', 'class']
</code></pre>
<p>I am new to coding and am having difficulties with this.</p>
| [
{
"answer_id": 74436545,
"author": "user18309290",
"author_id": 18309290,
"author_profile": "https://Stackoverflow.com/users/18309290",
"pm_score": 2,
"selected": true,
"text": "justifyContent"
},
{
"answer_id": 74436698,
"author": "Hemant Singh Yadav",
"author_id": 20470646,
"author_profile": "https://Stackoverflow.com/users/20470646",
"pm_score": 0,
"selected": false,
"text": " .main-div{\n display: flex;\n justify-content: space-between;\n }\n \n .size-Of-Icon {\n width: 40px;\n border: 1px solid blue;\n }\n \n .image {\n height: 180px;\n border: 1px solid red;\n }\n "
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20495138/"
] |
74,436,430 | <p>I want to debounce same function in two diferent scenarios, when user clicks search button and when user stops typing. So if the user types cat and in less than 1 second he clicks 3 times search icon we will only search one time, after 1 second he stops clicking search button.</p>
<p>I tried this:</p>
<pre><code>function debounce(your_func,time=1000){...}
function search_api(){...}
$("#my_input").on("input",
debounce(function(){search_api()})
);
$("#search_button").on("click",
debounce(function(){search_api()})
);
</code></pre>
<p>This works but not exacly what we want cause it debouce it "separately", so it debounces inputs by on hand and clicks to search on the other hand.</p>
| [
{
"answer_id": 74436431,
"author": "Dan.py",
"author_id": 8947060,
"author_profile": "https://Stackoverflow.com/users/8947060",
"pm_score": 0,
"selected": false,
"text": "function debounce(your_func,time=1000){...}\nfunction search_api(){...}\nconst debounce_search = debbounce(search_api)\n\n$(\"#my_input\").on(\"input\",\n debounce_search\n);\n\n$(\"#search_button\").on(\"click\",\n debounce_search\n);\n"
},
{
"answer_id": 74448712,
"author": "user15438246",
"author_id": 15438246,
"author_profile": "https://Stackoverflow.com/users/15438246",
"pm_score": 1,
"selected": false,
"text": "function debounce(func, timeout = 300){\n let timer;\n return (...args) => {\n clearTimeout(timer);\n timer = setTimeout(() => { func.apply(this, args); }, timeout);\n };\n}\nfunction saveInput(){\n console.log('Saving data');\n}\nconst processChange = debounce(() => saveInput());\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8947060/"
] |
74,436,435 | <p>I am in Uni and I am required to do a specific task the task is:</p>
<blockquote>
<p>Create a class that represents a system of linear algebra equations
(system of equations), finding roots and checking whether some set of
numbers exists as a solution of the system. Based on this class,
create descendant classes representing systems of two and three linear
equations, respectively, with two and three unknowns. By randomly
generating the data, to find the solution of systems of linear
algebraic equations of both types.</p>
</blockquote>
<p>The idea is that I Have to use a constructor and a solving method like this in order to solve the System of Equations. I still have to make a descendant class after but first I need to fix the main code.</p>
<pre><code>import numpy as np
class Linear:
# linear equation ax + by + c = 0
def __init__(self, a, c, x):
self.a = np.array([[8, 3, -2], [-4, 7, 5], [3, 4, -12]]) # coefficient of X's 8X + 3Y - 2z = 9
self.c = np.array([9, 15, 35]) # free term of Equation -4X + 7Y + 5Z = 15
self.x = np.linalg.solve(a, c) # 3X + 4Y - 12Z = 35
def solve(self):
if self.x
r1 = Linear(8, 3, -2)
print(r1.solve())
</code></pre>
<p>I've found on the web that you can use numpy easily to skip all the big steps however I'm having trouble solving and placing the code together</p>
| [
{
"answer_id": 74436522,
"author": "Tim Roberts",
"author_id": 1883316,
"author_profile": "https://Stackoverflow.com/users/1883316",
"pm_score": 2,
"selected": true,
"text": "a"
},
{
"answer_id": 74438195,
"author": "Полишук Макс",
"author_id": 19399005,
"author_profile": "https://Stackoverflow.com/users/19399005",
"pm_score": 0,
"selected": false,
"text": "import numpy as np\n\n\nclass linear:\n # linear equation bx + c = 0\n def __init__(self, a, c):\n self.a = a\n self.c = c\n\n def solve(self):\n return np.linalg.solve(self.a, self.c)\n\n\nclass two_unknown_lin(linear):\n # linear equation with 2 unknown ax + by + c = 0\n def __init__(self, a, c):\n super().__init__(a, c)\n\n def solve(self):\n return np.linalg.solve(self.a, self.c)\n\n\nclass three_unknown(two_unknown_lin):\n # linear equation with 2 unknown ax + by + cz + d = 0\n def __init__(self, a, c):\n super().__init__(a, c)\n\n def solve(self):\n return np.linalg.solve(self.a, self.c)\n\n\nr2 = two_unknown_lin(\n [[1, 3], [2, 8]],\n [6, -12]\n)\nprint(\"2 variable unknown roots are :\", r2.solve())\n\nr1 = three_unknown(\n [[8, 3, -2], [-4, 7, 5], [3, 4, -12]],\n [9, 15, 35]\n)\nprint(\"3 variable unknown roots are :\", r1.solve())\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19399005/"
] |
74,436,462 | <p>am developing a flutter application with firestore. in firestore I have a field called role and I managed to access it in my code. The role is printed correctly in the console.But I need help in displaying differnt page for each user.</p>
<p>`</p>
<pre><code>class _UserMangmentState extends State<UserMangment> {
String role = "";
@override
void initState() {
getRole();
super.initState();
}
Future getRole() async {
String id = FirebaseAuth.instance.currentUser!.uid.toString();
FirebaseFirestore.instance
.collection('users')
.doc(id)
.get()
.then((DocumentSnapshot doc) {
role = doc.get('role');
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder(
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Container();
} else {
getRole();
if (role == "vendor") {
return VendorInformation();
} else if (role == "planner") {
return PlannerPage();
} else {
return HomePage();
}
}
}),
);
}
}
</code></pre>
<p>`</p>
| [
{
"answer_id": 74436522,
"author": "Tim Roberts",
"author_id": 1883316,
"author_profile": "https://Stackoverflow.com/users/1883316",
"pm_score": 2,
"selected": true,
"text": "a"
},
{
"answer_id": 74438195,
"author": "Полишук Макс",
"author_id": 19399005,
"author_profile": "https://Stackoverflow.com/users/19399005",
"pm_score": 0,
"selected": false,
"text": "import numpy as np\n\n\nclass linear:\n # linear equation bx + c = 0\n def __init__(self, a, c):\n self.a = a\n self.c = c\n\n def solve(self):\n return np.linalg.solve(self.a, self.c)\n\n\nclass two_unknown_lin(linear):\n # linear equation with 2 unknown ax + by + c = 0\n def __init__(self, a, c):\n super().__init__(a, c)\n\n def solve(self):\n return np.linalg.solve(self.a, self.c)\n\n\nclass three_unknown(two_unknown_lin):\n # linear equation with 2 unknown ax + by + cz + d = 0\n def __init__(self, a, c):\n super().__init__(a, c)\n\n def solve(self):\n return np.linalg.solve(self.a, self.c)\n\n\nr2 = two_unknown_lin(\n [[1, 3], [2, 8]],\n [6, -12]\n)\nprint(\"2 variable unknown roots are :\", r2.solve())\n\nr1 = three_unknown(\n [[8, 3, -2], [-4, 7, 5], [3, 4, -12]],\n [9, 15, 35]\n)\nprint(\"3 variable unknown roots are :\", r1.solve())\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20478151/"
] |
74,436,466 | <p>I want to pull out a string from a txt file that shows how fast my SQL Server backups run. This shows me the line that contains the information:</p>
<pre><code>Select-String -Path "DatabaseBackup - USER_DATABASES - FULL*.txt" -pattern "MB/sec"
</code></pre>
<p>The problem is that the line of text is over 2000 characters so I want to pipe it to substring to grab just a portion. Unfortunately, this code:</p>
<pre><code>Select-String -Path "DatabaseBackup - USER_DATABASES - FULL*.txt" -pattern "MB/sec" | ForEach-Object { $_.substring(42,30) }
</code></pre>
<p>gives</p>
<blockquote>
<p>Method invocation failed because [Microsoft.PowerShell.Commands.MatchInfo] does not contain a method named 'substring'.</p>
</blockquote>
<p>Any hints on how to get this working?</p>
<p>Ken</p>
<p>[Edit] The solution is provided by JosefZ. For my own future reference, the database names are enclosed with single quotes and the speed is enclosed in open and close round brackets. This code:</p>
<pre><code>Select-String -Path "DatabaseBackup - USER_DATABASES - FULL*.txt" -pattern "MB/sec" |
ForEach-Object {
$_.Line.substring($_.Line.IndexOf(''''), $_.Line.IndexOf('''', $_.Line.IndexOf('''')+1)-$_.Line.IndexOf('''')+1) + " " + $_.Line.substring($_.Line.IndexOf('('),$_.Line.IndexOf(')')-$_.Line.IndexOf('(')+1)
}
</code></pre>
<p>produces output that looks like:</p>
<pre><code>'DBA' (796.230 MB/sec)
'ReportServer' (488.596 MB/sec)
'ReportServerTempDB' (139.270 MB/sec)
'TSTGP' (420.375 MB/sec)
</code></pre>
| [
{
"answer_id": 74436519,
"author": "frankM_DN",
"author_id": 20034020,
"author_profile": "https://Stackoverflow.com/users/20034020",
"pm_score": 0,
"selected": false,
"text": "Select-String"
},
{
"answer_id": 74436749,
"author": "JosefZ",
"author_id": 3439404,
"author_profile": "https://Stackoverflow.com/users/3439404",
"pm_score": 3,
"selected": true,
"text": "MatchInfo"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3047366/"
] |
74,436,483 | <p>I am trying to create an output that will be an array that contains 5 "sub-arrays". Every array should include 10 random numbers between 0 and 10.</p>
<p>I have this code:</p>
<pre><code>def count_tweets():
big_array = []
for i in range(5):
array = []
for p in range(10):
array.append(random.randint(0,10))
big_array.append(array)
print(big_array)
</code></pre>
<p>I get a result like:</p>
<pre><code>[[4, 2, 7, 1, 3, 2, 6, 9, 3, 10]]
[[4, 2, 7, 1, 3, 2, 6, 9, 3, 10], [5, 10, 7, 10, 7, 2, 1, 4, 8, 3]]
[[4, 2, 7, 1, 3, 2, 6, 9, 3, 10], [5, 10, 7, 10, 7, 2, 1, 4, 8, 3], [2, 7, 1, 3, 8, 5, 7, 6, 0, 0]]
[[4, 2, 7, 1, 3, 2, 6, 9, 3, 10], [5, 10, 7, 10, 7, 2, 1, 4, 8, 3], [2, 7, 1, 3, 8, 5, 7, 6, 0, 0], [0, 1, 9, 9, 4, 2, 10, 4, 3, 8]]
[[4, 2, 7, 1, 3, 2, 6, 9, 3, 10], [5, 10, 7, 10, 7, 2, 1, 4, 8, 3], [2, 7, 1, 3, 8, 5, 7, 6, 0, 0], [0, 1, 9, 9, 4, 2, 10, 4, 3, 8], [3, 7, 3, 5, 4, 0, 2, 8, 6, 2]]
</code></pre>
<p>But instead it should be like:</p>
<pre><code>[[0,2,6,7,9,4,6,1,10,5],[1,3,5,9,8,7,6,9,0,10],[3,5,1,7,9,4,7,2,7,9],[10,2,8,5,6,9,2,3,5,9],[4,5,2,9,8,7,5,1,3,5]]
</code></pre>
<p>I cannot seem to get the indentation correct. How do I fix the code?</p>
| [
{
"answer_id": 74436519,
"author": "frankM_DN",
"author_id": 20034020,
"author_profile": "https://Stackoverflow.com/users/20034020",
"pm_score": 0,
"selected": false,
"text": "Select-String"
},
{
"answer_id": 74436749,
"author": "JosefZ",
"author_id": 3439404,
"author_profile": "https://Stackoverflow.com/users/3439404",
"pm_score": 3,
"selected": true,
"text": "MatchInfo"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20503523/"
] |
74,436,485 | <p>Let's say I have a function called bars()</p>
<pre><code>bars () {
const bars = []
for (let i = 0; i < this.numberOfBars; i++) {
bars.push(Math.sqrt(this.numberOfBars * this.numberOfBars - i * i))
}
return bars
}
</code></pre>
<p>If I'm reducing the bars array to approximate PI, what should be on the right side of the arrow function?</p>
<pre><code>PI = bars().reduce((a, b) =>
</code></pre>
<p>I tried adding the values and dividing by the number of bars, but I'm not getting anywhere near the approximation of Pi. I feel like there's a simple trick that I'm missing.</p>
| [
{
"answer_id": 74436519,
"author": "frankM_DN",
"author_id": 20034020,
"author_profile": "https://Stackoverflow.com/users/20034020",
"pm_score": 0,
"selected": false,
"text": "Select-String"
},
{
"answer_id": 74436749,
"author": "JosefZ",
"author_id": 3439404,
"author_profile": "https://Stackoverflow.com/users/3439404",
"pm_score": 3,
"selected": true,
"text": "MatchInfo"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19803609/"
] |
74,436,487 | <p>I am using OR-Tools to solve a problem similar to the Nurse Scheduling problem. The difference in my case is that when I schedule a "Nurse" for a shift, they must then work consecutive days (i.e., there can be no gaps between days worked).</p>
<p>Most of the similar questions point to this <a href="https://github.com/google/or-tools/blob/master/examples/python/shift_scheduling_sat.py" rel="nofollow noreferrer">code</a>. I have attempted to implement the answer adapted from there. However, I am getting output solutions which do not respecting the constraints.</p>
<p>The logic I was trying to follow is that I want to forbid patterns that have gaps. For example:</p>
<pre><code>[1,0,1]
[1,0,0,1]
[1,0,0,0,1]
</code></pre>
<p>Below is an example of my code where for</p>
<pre><code># Modified from the code linked above:
def negated_bounded_span(works, start, length):
sequence = []
# Left border
sequence.append(works[start].Not())
# Middle
for i in range(1,length+1):
sequence.append(works[start + i])
# Right border
sequence.append(works[start + length + 1].Not())
return sequence
for n in range(num_nurses):
# nurse_days[(n,d)] is 1 if nurse n works on day d
nrses = [nurse_days[(n, d)] for d in range(5)]
for length in range(1, 4):
for start in range(5 - length - 1):
model.AddBoolOr(negated_bounded_span(nrses, start, length))
</code></pre>
<p>A modified excerpt of what the output of the above would look like is the following:</p>
<pre><code>['Not(nurse_days_n0d0)', nurse_days_n0d1(0..1), 'Not(nurse_days_n0d2)']
['Not(nurse_days_n0d1)', nurse_days_n0d2(0..1), 'Not(nurse_days_n0d3)']
['Not(nurse_days_n0d2)', nurse_days_n0d3(0..1), 'Not(nurse_days_n0d4)']
['Not(nurse_days_n0d0)', nurse_days_n0d1(0..1), nurse_days_n0d2(0..1), 'Not(nurse_days_n0d3)']
['Not(nurse_days_n0d1)', nurse_days_n0d2(0..1), nurse_days_n0d3(0..1), 'Not(nurse_days_n0d4)']
['Not(nurse_days_n0d0)', nurse_days_n0d1(0..1), nurse_days_n0d2(0..1), nurse_days_n0d3(0..1), 'Not(nurse_days_n0d4)']
</code></pre>
<p>Thanks for your help in advance.</p>
<p>Similar questions reviewed: [<a href="https://stackoverflow.com/questions/56872713/setting-binary-constraints-with-google-or-tools/56877058#56877058">1</a>], [<a href="https://stackoverflow.com/questions/62980487/or-tools-add-2-days-in-a-row-to-the-scheduling-problem?noredirect=1&lq=1">2</a>], [<a href="https://stackoverflow.com/questions/55100229/google-or-tools-employee-scheduling-the-condition-does-not-work-properly?rq=1">3</a>].</p>
| [
{
"answer_id": 74436519,
"author": "frankM_DN",
"author_id": 20034020,
"author_profile": "https://Stackoverflow.com/users/20034020",
"pm_score": 0,
"selected": false,
"text": "Select-String"
},
{
"answer_id": 74436749,
"author": "JosefZ",
"author_id": 3439404,
"author_profile": "https://Stackoverflow.com/users/3439404",
"pm_score": 3,
"selected": true,
"text": "MatchInfo"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18497033/"
] |
74,436,491 | <p>What is the difference between this:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
using namespace std;
int n, d, nr;
int main()
{
cin >> n;
for(d = 1; d * d < n; d++){
if (n % d == 0){
if (d % 2 == 0) nr++;
if (n / d % 2 == 0) nr++;
}
}
if (d * d == n && d % 2 == 0) nr++;
cout << nr;
}
</code></pre>
<p>And this:</p>
<pre><code>#include <iostream>
using namespace std;
int main()
{
int n, d, nr;
cin >> n;
for(d = 1; d * d < n; d++){
if (n % d == 0){
if (d % 2 == 0) nr++;
if (n / d % 2 == 0) nr++;
}
}
if (d * d == n && d % 2 == 0) nr++;
cout << nr;
}
</code></pre>
<p>I input 12 and expect 4. The first one works the second one doesn't.</p>
<p>Declaring the <code>n</code>, <code>d</code>, <code>nr</code> integers before <code>main()</code> returns a different value versus declaring them after the <code>main()</code> function. Why?</p>
| [
{
"answer_id": 74436543,
"author": "AndyG",
"author_id": 27678,
"author_profile": "https://Stackoverflow.com/users/27678",
"pm_score": 2,
"selected": false,
"text": "0"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19061985/"
] |
74,436,507 | <p>Given a user <code>id</code>, I want to find the followers that the user follows (i.e. follow each other)</p>
<p>My Prisma model looks like the following:</p>
<pre><code>model User {
id Int @id @default(autoincrement())
name String?
followedBy Follows[] @relation("following")
following Follows[] @relation("follower")
}
model Follows {
follower User @relation("follower", fields: [followerId], references: [id])
followerId Int
following User @relation("following", fields: [followingId], references: [id])
followingId Int
@@id([followerId, followingId])
}
</code></pre>
<p>I am also interested in counting them - this could be done in a separate query since the former might require pagination at some point.</p>
<p>Thank you in advance for your help.</p>
| [
{
"answer_id": 74438469,
"author": "G.G.",
"author_id": 931594,
"author_profile": "https://Stackoverflow.com/users/931594",
"pm_score": 1,
"selected": false,
"text": "function getFollowersMutual(userId: User[\"id\"]) {\n return prisma.$queryRawUnsafe<User[]>(\n `SELECT u.* FROM \"Follows\" AS f1\n INNER JOIN \"Follows\" AS f2\n ON f2.\"followingId\" = f1.\"followerId\"\n INNER JOIN \"User\" AS u\n ON f1.\"followerId\" = u.\"id\"\n WHERE f1.\"followingId\" = '${userId}`\n );\n}\n"
},
{
"answer_id": 74443057,
"author": "Nurul Sundarani",
"author_id": 4154062,
"author_profile": "https://Stackoverflow.com/users/4154062",
"pm_score": 0,
"selected": false,
"text": "import { PrismaClient } from '@prisma/client';\n\nconst prisma = new PrismaClient();\n\nasync function main() {\n await prisma.user.createMany({\n data: [\n {\n id: 1,\n name: 'User 1',\n },\n {\n id: 2,\n name: 'User 2',\n },\n {\n id: 3,\n name: 'User 3',\n },\n ],\n });\n\n // // User 1 follows User 2 and User 3\n // // User 2 follows User 1\n await prisma.follows.createMany({\n data: [\n {\n followerId: 1,\n followingId: 2,\n },\n {\n followerId: 1,\n followingId: 3,\n },\n {\n followerId: 2,\n followingId: 1,\n },\n ],\n });\n\n // For User id 1, get all the followers and all the users they follow\n const users = await prisma.follows.findMany({\n where: {\n OR: [\n {\n followerId: 1,\n },\n {\n followingId: 1,\n },\n ],\n },\n include: {\n following: true,\n },\n });\n\n console.log(users);\n\n const mutuals = [];\n\n // For each user, check if they follow each other\n for (let i = 0; i < users.length; i++) {\n const user = users[i];\n\n for (let j = i + 1; j < users.length; j++) {\n const innerUser = users[j];\n\n if (\n user.followerId === innerUser.followingId &&\n user.followingId === innerUser.followerId\n ) {\n mutuals.push(user);\n }\n }\n }\n\n console.log(mutuals);\n}\n\nmain()\n .catch((e) => {\n throw e;\n })\n .finally(async () => {\n await prisma.$disconnect();\n });\n\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/931594/"
] |
74,436,515 | <p>I am trying to set an alias name for column challenge_name especially when I encounter 'challenge' based on timestamp/date as challenge 1, challenge 2, etc. If it's not 'challenge' I would like to set the column name the same as challenge_name</p>
<p>This is my current input</p>
<pre><code>+-----------+----------------+
| date | challenge_name |
+-----------+----------------+
| 1/11/2022 | find the bug |
| 1/12/2022 | challenge |
| 1/13/2022 | kill pill |
| 1/14/2022 | hello copter |
| 1/15/2022 | challenge |
| 1/16/2022 | miami |
| 1/17/2022 | hello world |
| 1/18/2022 | challenge |
| 1/19/2022 | dominc |
| 1/20/2022 | challenge |
+-----------+----------------+
</code></pre>
<p>This is my expected output</p>
<pre><code>+-----------+----------------+--------------+
| date | challenge_name | updated_name |
+-----------+----------------+--------------+
| 1/11/2022 | find the bug | find the bug |
| 1/12/2022 | challenge | challenge 1 |
| 1/13/2022 | kill pill | kill pill |
| 1/14/2022 | hello copter | hello copter |
| 1/15/2022 | challenge | challenge 2 |
| 1/16/2022 | miami | miami |
| 1/17/2022 | hello world | hello world |
| 1/18/2022 | challenge | challenge 3 |
| 1/19/2022 | dominc | dominc |
| 1/20/2022 | challenge | challenge 4 |
+-----------+----------------+--------------+
</code></pre>
| [
{
"answer_id": 74438469,
"author": "G.G.",
"author_id": 931594,
"author_profile": "https://Stackoverflow.com/users/931594",
"pm_score": 1,
"selected": false,
"text": "function getFollowersMutual(userId: User[\"id\"]) {\n return prisma.$queryRawUnsafe<User[]>(\n `SELECT u.* FROM \"Follows\" AS f1\n INNER JOIN \"Follows\" AS f2\n ON f2.\"followingId\" = f1.\"followerId\"\n INNER JOIN \"User\" AS u\n ON f1.\"followerId\" = u.\"id\"\n WHERE f1.\"followingId\" = '${userId}`\n );\n}\n"
},
{
"answer_id": 74443057,
"author": "Nurul Sundarani",
"author_id": 4154062,
"author_profile": "https://Stackoverflow.com/users/4154062",
"pm_score": 0,
"selected": false,
"text": "import { PrismaClient } from '@prisma/client';\n\nconst prisma = new PrismaClient();\n\nasync function main() {\n await prisma.user.createMany({\n data: [\n {\n id: 1,\n name: 'User 1',\n },\n {\n id: 2,\n name: 'User 2',\n },\n {\n id: 3,\n name: 'User 3',\n },\n ],\n });\n\n // // User 1 follows User 2 and User 3\n // // User 2 follows User 1\n await prisma.follows.createMany({\n data: [\n {\n followerId: 1,\n followingId: 2,\n },\n {\n followerId: 1,\n followingId: 3,\n },\n {\n followerId: 2,\n followingId: 1,\n },\n ],\n });\n\n // For User id 1, get all the followers and all the users they follow\n const users = await prisma.follows.findMany({\n where: {\n OR: [\n {\n followerId: 1,\n },\n {\n followingId: 1,\n },\n ],\n },\n include: {\n following: true,\n },\n });\n\n console.log(users);\n\n const mutuals = [];\n\n // For each user, check if they follow each other\n for (let i = 0; i < users.length; i++) {\n const user = users[i];\n\n for (let j = i + 1; j < users.length; j++) {\n const innerUser = users[j];\n\n if (\n user.followerId === innerUser.followingId &&\n user.followingId === innerUser.followerId\n ) {\n mutuals.push(user);\n }\n }\n }\n\n console.log(mutuals);\n}\n\nmain()\n .catch((e) => {\n throw e;\n })\n .finally(async () => {\n await prisma.$disconnect();\n });\n\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11221870/"
] |
74,436,528 | <p>I have a dataframe which i'd like to repeatedly sample, with replacement. Everytime I sample the df, I would like to increase the size of the sample (n) by one, up to N.</p>
<p>For example:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>value_1</th>
<th>value_2</th>
</tr>
</thead>
<tbody>
<tr>
<td>a</td>
<td>5</td>
<td>10</td>
</tr>
<tr>
<td>b</td>
<td>10</td>
<td>30</td>
</tr>
<tr>
<td>c</td>
<td>6</td>
<td>8</td>
</tr>
<tr>
<td>d</td>
<td>9</td>
<td>12</td>
</tr>
</tbody>
</table>
</div>
<p>Would result in something like</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id's</th>
<th>sum_of_value_1</th>
<th>sum_of_value_2</th>
</tr>
</thead>
<tbody>
<tr>
<td>b</td>
<td>10</td>
<td>30</td>
</tr>
<tr>
<td>a, c</td>
<td>11 (5+6)</td>
<td>18 (10+8)</td>
</tr>
<tr>
<td>b,a,d</td>
<td>24 (10+5+9)</td>
<td>52 (30+10+12)</td>
</tr>
</tbody>
</table>
</div>
<p>I can do this with a for loop but can't figure how how to add the summation and the append into the query:</p>
<pre><code>for n in range(200):
print(df_groups.sample(n))
</code></pre>
| [
{
"answer_id": 74438469,
"author": "G.G.",
"author_id": 931594,
"author_profile": "https://Stackoverflow.com/users/931594",
"pm_score": 1,
"selected": false,
"text": "function getFollowersMutual(userId: User[\"id\"]) {\n return prisma.$queryRawUnsafe<User[]>(\n `SELECT u.* FROM \"Follows\" AS f1\n INNER JOIN \"Follows\" AS f2\n ON f2.\"followingId\" = f1.\"followerId\"\n INNER JOIN \"User\" AS u\n ON f1.\"followerId\" = u.\"id\"\n WHERE f1.\"followingId\" = '${userId}`\n );\n}\n"
},
{
"answer_id": 74443057,
"author": "Nurul Sundarani",
"author_id": 4154062,
"author_profile": "https://Stackoverflow.com/users/4154062",
"pm_score": 0,
"selected": false,
"text": "import { PrismaClient } from '@prisma/client';\n\nconst prisma = new PrismaClient();\n\nasync function main() {\n await prisma.user.createMany({\n data: [\n {\n id: 1,\n name: 'User 1',\n },\n {\n id: 2,\n name: 'User 2',\n },\n {\n id: 3,\n name: 'User 3',\n },\n ],\n });\n\n // // User 1 follows User 2 and User 3\n // // User 2 follows User 1\n await prisma.follows.createMany({\n data: [\n {\n followerId: 1,\n followingId: 2,\n },\n {\n followerId: 1,\n followingId: 3,\n },\n {\n followerId: 2,\n followingId: 1,\n },\n ],\n });\n\n // For User id 1, get all the followers and all the users they follow\n const users = await prisma.follows.findMany({\n where: {\n OR: [\n {\n followerId: 1,\n },\n {\n followingId: 1,\n },\n ],\n },\n include: {\n following: true,\n },\n });\n\n console.log(users);\n\n const mutuals = [];\n\n // For each user, check if they follow each other\n for (let i = 0; i < users.length; i++) {\n const user = users[i];\n\n for (let j = i + 1; j < users.length; j++) {\n const innerUser = users[j];\n\n if (\n user.followerId === innerUser.followingId &&\n user.followingId === innerUser.followerId\n ) {\n mutuals.push(user);\n }\n }\n }\n\n console.log(mutuals);\n}\n\nmain()\n .catch((e) => {\n throw e;\n })\n .finally(async () => {\n await prisma.$disconnect();\n });\n\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15243986/"
] |
74,436,564 | <p>I am using Kotlin.</p>
<p>I have a stored password (val password = 1111). I have an editText (passcode) that takes a "numberPassword" input. I would like the user to input the code and if it matches I will do something.</p>
<p>I have tried:</p>
<p><code>if (passcode.equals(1111)) { //do something }</code></p>
<p><code>if (passcode = password) { //do something }</code></p>
<p><code>if (passcode.text.toString() == password) { //do something }</code></p>
<p><code>if (passcode == "1111") { //do something }</code></p>
<p>...
and many other versions switching back and forth from int to string</p>
<p>This should be very simple since the user is either right or wrong. I am guessing it has to do with string/int stuff. Thanks for your help!</p>
<p>Just Tried:</p>
<pre><code> <EditText
android:id="@+id/passcode"
android:layout_width="120dp"
android:layout_height="75dp"
android:layout_gravity="center_horizontal"
android:textAlignment="center"
android:hint="@string/zeros"
android:drawableStart="@drawable/ic_key"
android:inputType="numberPassword"
android:maxLength="4"
android:maxLines="1"
android:textColor="@color/black"
android:textColorHint="@color/light_gray"
android:textCursorDrawable="@null"
android:textSize="35sp"
android:singleLine="true"
android:autofillHints="true" />
</code></pre>
<p><code>private var passcode: EditText? = null private var password: Int = 1111</code></p>
<pre><code> view.submitButton?.setOnClickListener {
if (passcode?.text.toString() == password.toString()){
Toast.makeText(this@SplashScreen, "Valid", Toast.LENGTH_LONG).show()
} else {
Toast.makeText(this@SplashScreen, "Invalid", Toast.LENGTH_LONG).show()
}
}
</code></pre>
<p>Result: Invalid when I enter 1111 in edittext</p>
| [
{
"answer_id": 74438469,
"author": "G.G.",
"author_id": 931594,
"author_profile": "https://Stackoverflow.com/users/931594",
"pm_score": 1,
"selected": false,
"text": "function getFollowersMutual(userId: User[\"id\"]) {\n return prisma.$queryRawUnsafe<User[]>(\n `SELECT u.* FROM \"Follows\" AS f1\n INNER JOIN \"Follows\" AS f2\n ON f2.\"followingId\" = f1.\"followerId\"\n INNER JOIN \"User\" AS u\n ON f1.\"followerId\" = u.\"id\"\n WHERE f1.\"followingId\" = '${userId}`\n );\n}\n"
},
{
"answer_id": 74443057,
"author": "Nurul Sundarani",
"author_id": 4154062,
"author_profile": "https://Stackoverflow.com/users/4154062",
"pm_score": 0,
"selected": false,
"text": "import { PrismaClient } from '@prisma/client';\n\nconst prisma = new PrismaClient();\n\nasync function main() {\n await prisma.user.createMany({\n data: [\n {\n id: 1,\n name: 'User 1',\n },\n {\n id: 2,\n name: 'User 2',\n },\n {\n id: 3,\n name: 'User 3',\n },\n ],\n });\n\n // // User 1 follows User 2 and User 3\n // // User 2 follows User 1\n await prisma.follows.createMany({\n data: [\n {\n followerId: 1,\n followingId: 2,\n },\n {\n followerId: 1,\n followingId: 3,\n },\n {\n followerId: 2,\n followingId: 1,\n },\n ],\n });\n\n // For User id 1, get all the followers and all the users they follow\n const users = await prisma.follows.findMany({\n where: {\n OR: [\n {\n followerId: 1,\n },\n {\n followingId: 1,\n },\n ],\n },\n include: {\n following: true,\n },\n });\n\n console.log(users);\n\n const mutuals = [];\n\n // For each user, check if they follow each other\n for (let i = 0; i < users.length; i++) {\n const user = users[i];\n\n for (let j = i + 1; j < users.length; j++) {\n const innerUser = users[j];\n\n if (\n user.followerId === innerUser.followingId &&\n user.followingId === innerUser.followerId\n ) {\n mutuals.push(user);\n }\n }\n }\n\n console.log(mutuals);\n}\n\nmain()\n .catch((e) => {\n throw e;\n })\n .finally(async () => {\n await prisma.$disconnect();\n });\n\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19934720/"
] |
74,436,580 | <p>I have a directory (<code>2022</code>) that has subdirectories with a date as their name (<code>20220101</code>, <code>20220102</code>, etc).</p>
<p>In each subdirectory I have files that I want to archive. These files have a name that starts with either <code>L0283</code> or <code>L0284</code> and then numbers and dates afterwards. E.g.: <code>L0284408.20220101.2123</code>. The filter I want to use is <code>L028*</code>. I want to archive each file in the same folder that they currently live in with a zipped a folder named <code>400401_L028<b>3</b>408archive.zip</code> or <code>400401_L028<b>4</b>408archive.zip</code>, depending on whether it was a <code>L0283</code> or <code>L0284</code> file.</p>
<p>That archive already exists, I can write a script that deletes it first but if I can overwrite it then it would save some time. I'll be rerunning this script in multiple root directories.</p>
<p>I looked into powershell's Compress-Archive functionality but I couldn't figure out how to add a filter to the file name and have a different output name, plus the <code>0283</code> vs <code>0284</code> was eluding me.</p>
| [
{
"answer_id": 74438469,
"author": "G.G.",
"author_id": 931594,
"author_profile": "https://Stackoverflow.com/users/931594",
"pm_score": 1,
"selected": false,
"text": "function getFollowersMutual(userId: User[\"id\"]) {\n return prisma.$queryRawUnsafe<User[]>(\n `SELECT u.* FROM \"Follows\" AS f1\n INNER JOIN \"Follows\" AS f2\n ON f2.\"followingId\" = f1.\"followerId\"\n INNER JOIN \"User\" AS u\n ON f1.\"followerId\" = u.\"id\"\n WHERE f1.\"followingId\" = '${userId}`\n );\n}\n"
},
{
"answer_id": 74443057,
"author": "Nurul Sundarani",
"author_id": 4154062,
"author_profile": "https://Stackoverflow.com/users/4154062",
"pm_score": 0,
"selected": false,
"text": "import { PrismaClient } from '@prisma/client';\n\nconst prisma = new PrismaClient();\n\nasync function main() {\n await prisma.user.createMany({\n data: [\n {\n id: 1,\n name: 'User 1',\n },\n {\n id: 2,\n name: 'User 2',\n },\n {\n id: 3,\n name: 'User 3',\n },\n ],\n });\n\n // // User 1 follows User 2 and User 3\n // // User 2 follows User 1\n await prisma.follows.createMany({\n data: [\n {\n followerId: 1,\n followingId: 2,\n },\n {\n followerId: 1,\n followingId: 3,\n },\n {\n followerId: 2,\n followingId: 1,\n },\n ],\n });\n\n // For User id 1, get all the followers and all the users they follow\n const users = await prisma.follows.findMany({\n where: {\n OR: [\n {\n followerId: 1,\n },\n {\n followingId: 1,\n },\n ],\n },\n include: {\n following: true,\n },\n });\n\n console.log(users);\n\n const mutuals = [];\n\n // For each user, check if they follow each other\n for (let i = 0; i < users.length; i++) {\n const user = users[i];\n\n for (let j = i + 1; j < users.length; j++) {\n const innerUser = users[j];\n\n if (\n user.followerId === innerUser.followingId &&\n user.followingId === innerUser.followerId\n ) {\n mutuals.push(user);\n }\n }\n }\n\n console.log(mutuals);\n}\n\nmain()\n .catch((e) => {\n throw e;\n })\n .finally(async () => {\n await prisma.$disconnect();\n });\n\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3215970/"
] |
74,436,582 | <p>I'm in the process of trying to connect the front end of my MERN application to the back end. The back end works just fine on its own, and I have no problem accessing data by manually executing HTTP requests. Now that I'm trying to connect it to the front end, I seem to be getting stuck everywhere.</p>
<p>My current problem is that when I try to fetch data via HTTP requests, the DOM disappears and displays a blank page.</p>
<pre><code>import React, {useEffect, useState} from "react"
import ItemRequests from "./dataservices/items.js"
function ItemList(props){
[items, setItems] = useState([])
useEffect(() => {
ItemRequests.getAll()
.then(results => {
console.log(results)
setItems(results.data)
})
.catch(e => {
console.log(e)
})
}, [])
return(
<h6>If this prints the issue has been resolved<h6/>
{/*Additional code*/}
)
}
</code></pre>
<p>ItemRequests class: contains all the requests specific to the Items collection</p>
<pre><code>import http from "http-config"
class ItemRequests{
getAll(page = 0){
return http.get("?page=" + page)
}
}
export default ItemRequests
</code></pre>
<p>http-config file</p>
<pre><code>import axios from "axios"
export default axios.create(){
baseURL: "https://localhost:XXXX/route/to/server",
headers: {
"Content-type": "application/json"
}
}
</code></pre>
<p>All other routes in the front end are functional. Only this route, which executes HTTP requests is not rendering properly. I'm debugging right now to see if I can gain any further details, but I would appreciate any insight from here.</p>
<p>Edit: According to my browser's console:</p>
<blockquote>
<p>Uncaught TypeError: <em>services_items__WEBPACK_IMPORTED_MODULE_1</em>_.default.getAll is not a function</p>
</blockquote>
<p>So for some reason JS does not recognize getAll() as a function, even though it is defined.</p>
| [
{
"answer_id": 74438469,
"author": "G.G.",
"author_id": 931594,
"author_profile": "https://Stackoverflow.com/users/931594",
"pm_score": 1,
"selected": false,
"text": "function getFollowersMutual(userId: User[\"id\"]) {\n return prisma.$queryRawUnsafe<User[]>(\n `SELECT u.* FROM \"Follows\" AS f1\n INNER JOIN \"Follows\" AS f2\n ON f2.\"followingId\" = f1.\"followerId\"\n INNER JOIN \"User\" AS u\n ON f1.\"followerId\" = u.\"id\"\n WHERE f1.\"followingId\" = '${userId}`\n );\n}\n"
},
{
"answer_id": 74443057,
"author": "Nurul Sundarani",
"author_id": 4154062,
"author_profile": "https://Stackoverflow.com/users/4154062",
"pm_score": 0,
"selected": false,
"text": "import { PrismaClient } from '@prisma/client';\n\nconst prisma = new PrismaClient();\n\nasync function main() {\n await prisma.user.createMany({\n data: [\n {\n id: 1,\n name: 'User 1',\n },\n {\n id: 2,\n name: 'User 2',\n },\n {\n id: 3,\n name: 'User 3',\n },\n ],\n });\n\n // // User 1 follows User 2 and User 3\n // // User 2 follows User 1\n await prisma.follows.createMany({\n data: [\n {\n followerId: 1,\n followingId: 2,\n },\n {\n followerId: 1,\n followingId: 3,\n },\n {\n followerId: 2,\n followingId: 1,\n },\n ],\n });\n\n // For User id 1, get all the followers and all the users they follow\n const users = await prisma.follows.findMany({\n where: {\n OR: [\n {\n followerId: 1,\n },\n {\n followingId: 1,\n },\n ],\n },\n include: {\n following: true,\n },\n });\n\n console.log(users);\n\n const mutuals = [];\n\n // For each user, check if they follow each other\n for (let i = 0; i < users.length; i++) {\n const user = users[i];\n\n for (let j = i + 1; j < users.length; j++) {\n const innerUser = users[j];\n\n if (\n user.followerId === innerUser.followingId &&\n user.followingId === innerUser.followerId\n ) {\n mutuals.push(user);\n }\n }\n }\n\n console.log(mutuals);\n}\n\nmain()\n .catch((e) => {\n throw e;\n })\n .finally(async () => {\n await prisma.$disconnect();\n });\n\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20187870/"
] |
74,436,601 | <p>I am writing a class in python that combines the functionality of dict, defaultdict, and SimpleNamespace</p>
<p>So far I have the following code:</p>
<pre><code>import warnings
class fluiddict:
"""! A class that emulates a dictionary, while also being able to support attribute assignment and default values.
The default value of `default_factory` is None. This means a KeyError will be raised when non-existent data is requested
To specify a default value of None, use `default_factory=lambda key: None`
"""
def __contains__(self, key):
return key in self.datastore
def __getitem__(self,key):
if self.raise_KeyError and key not in self.datastore:
raise KeyError(f"Key '{key}' was not found in the datastore and no default factory was provided.")
if key not in self.datastore:
try:
return self.default_factory(key)
except Exception as e:
print("An unknown exception occured while trying to provide a default value. Is your default factory valid?")
raise e
return self.datastore[key]
def __setitem__(self,key,value):
self.datastore[key] = value
def __delitem__(self, key):
if key not in self.datastore:
if not self.bypass_del_KeyError:
raise KeyError(f"Key {key} was not found in the datastore.")
else:
warnings.warn(f"Attemping to delete nonexistent key {key} in the datastore. Ignoring del statement...")
else:
del self.datastore[key]
def is_defined(self,key):
return key in self.datastore
def is_set(self,key): #PHP-style `isset` function
return key in self.datastore and key is not None
def __init__(self, default_factory =None, bypass_del_KeyError=False):
self.datastore = {}
self.raise_KeyError = False
if default_factory is None:
self.raise_KeyError = True
self.bypass_del_KeyError = bypass_del_KeyError
</code></pre>
<p>The code works, but I cannot figure out how to write a <code>__getattr__</code> or <code>__setattr__</code> function that provides SimpleNamespace-like functionality without infinite recursion.</p>
<p>With the following additional code, I get an infinite recursion error. I think it's because the <code>self.</code> syntax calls <code>__getattr__</code> under the hood. I find this odd, since I have seen in other SO posts that <code>__setattr__</code> and <code>__getattr__</code> will only be called if the attribute wasn't <em>found normally</em>.</p>
<p>If I add the code:</p>
<pre><code>def __getattr__(self,attr_name):
return self.__getitem__(attr_name)
def __setattr__(self,attr_name,value):
self.__setitem__(attr_name,value)
</code></pre>
<p>I get the following traceback:</p>
<pre><code> File "G:\My Drive\Image Processing\Mapping Project\core\types.py", line 30, in __getattr__
return self.__getitem__(attr_name)Lab
File "G:\My Drive\Image Processing\Mapping Project\core\types.py", line 14, in __getitem__
if self.raise_KeyError and key not in self.datastore:
File "G:\My Drive\Image Processing\Mapping Project\core\types.py", line 30, in __getattr__
return self.__getitem__(attr_name)
File "G:\My Drive\Image Processing\Mapping Project\core\types.py", line 14, in __getitem__
if self.raise_KeyError and key not in self.datastore:
File "G:\My Drive\Image Processing\Mapping Project\core\types.py", line 30, in __getattr__
return self.__getitem__(attr_name)
File "G:\My Drive\Image Processing\Mapping Project\core\types.py", line 14, in __getitem__
if self.raise_KeyError and key not in self.datastore:
File "G:\My Drive\Image Processing\Mapping Project\core\types.py", line 30, in __getattr__
return self.__getitem__(attr_name)
RecursionError: maximum recursion depth exceeded
</code></pre>
<p>Any help appreciated.</p>
| [
{
"answer_id": 74436911,
"author": "Tim Roberts",
"author_id": 1883316,
"author_profile": "https://Stackoverflow.com/users/1883316",
"pm_score": 3,
"selected": true,
"text": "__setattr__"
},
{
"answer_id": 74437189,
"author": "Michael Sohnen",
"author_id": 5166365,
"author_profile": "https://Stackoverflow.com/users/5166365",
"pm_score": 0,
"selected": false,
"text": "import warnings\n\nclass fluiddict:\n\n MEMBER_ATTRIBUTE_LIST = [\n \"raise_KeyError\",\n \"datastore\",\n \"default_factory\",\n \"bypass_del_KeyError\",\n \"__getstate__\" # Comes from pickling\n ]\n\n \"\"\"! A class that emulates a dictionary, while also being able to support attribute assignment and default values.\n The default value of `default_factory` is None. This means a KeyError will be raised when non-existent data is requested\n To specify a default value of None, use `default_factory=lambda key: None`\n \"\"\"\n\n def __contains__(self, key):\n return self.is_defined(key)\n\n def __getitem__(self,key):\n if self.raise_KeyError and key not in self.datastore:\n raise KeyError(f\"Key '{key}' was not found in the datastore and no default factory was provided.\")\n\n if key not in self.datastore:\n try:\n return self.default_factory(key)\n except Exception as e:\n print(\"An unknown exception occured while trying to provide a default value. Is your default factory valid?\")\n raise e\n\n return self.datastore[key]\n\n def __setitem__(self,key,value):\n self.datastore[key] = value\n\n def __getattr__(self, attr_name):\n if attr_name in fluiddict.MEMBER_ATTRIBUTE_LIST:\n return object.__getattr__(self,attr_name) \n return self.__getitem__(attr_name)\n\n def __setattr__(self,attr_name,value):\n if attr_name in fluiddict.MEMBER_ATTRIBUTE_LIST:\n object.__setattr__(self,attr_name,value)\n else:\n self.__setitem__(attr_name,value)\n\n def __delitem__(self, key):\n \n if key not in self.datastore:\n if not self.bypass_del_KeyError:\n raise KeyError(f\"Key {key} was not found in the datastore.\")\n else:\n warnings.warn(f\"Attemping to delete nonexistent key {key} in the datastore. Ignoring del statement...\")\n else:\n del self.datastore[key]\n\n def is_defined(self,key):\n return key in self.datastore\n\n def is_set(self,key): #PHP-style `isset` function\n return key in self.datastore and self.datastore[key] is not None\n\n def __init__(self, default_factory =None, bypass_del_KeyError=False):\n\n self.datastore = {}\n\n self.raise_KeyError = False\n\n if default_factory is None:\n self.raise_KeyError = True\n\n self.bypass_del_KeyError = bypass_del_KeyError\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5166365/"
] |
74,436,619 | <p>I have this form:</p>
<pre><code><form>
<input type="text" class="name" id="name1">
<input type="text" class="name" id="name2">
<input type="text" class="name" id="name3">
...
<input type="text" class="name" id="name100">
<input type="submit" value="Send">
</form>
<script>
$(document).ready(function() {
var items = [
"",
];
$(".name").autocomplete({
source: items
});
$('.name').on('keyup', function(e) {
var txtVal = this.value;
items.push(txtVal);
});
});
</script>
</code></pre>
<p>What I'm trying to achieve is to have autocomplete with the value from the fields above. I used jquery autocomplete. The variable that stores the autocomplete options is called "items" and on keyup I pushed that value on the array. The result is a mess and somwhere I must've screw it. Here is a working end user scenario:<br />
<strong>Step 1</strong>: Let's say in the field <strong>#name1</strong> I type <strong>Jon Doe</strong><br />
<strong>Step 2</strong>: When I go to <strong>#name2</strong>, I would like that after I type <strong>J</strong> to see an autocomplete option <strong>Jon Doe</strong> (the value from the above field).<br />
<strong>Step 3</strong>: Let's say I didn't choose Jon Doe as autocomplete for #name2 so I typed <strong>Joanna Doe</strong>.<br />
When I go to <strong>#name3</strong>, I should see <strong>Jon Doe</strong> and <strong>Joanna Doe</strong> as autocomplete options.</p>
| [
{
"answer_id": 74436911,
"author": "Tim Roberts",
"author_id": 1883316,
"author_profile": "https://Stackoverflow.com/users/1883316",
"pm_score": 3,
"selected": true,
"text": "__setattr__"
},
{
"answer_id": 74437189,
"author": "Michael Sohnen",
"author_id": 5166365,
"author_profile": "https://Stackoverflow.com/users/5166365",
"pm_score": 0,
"selected": false,
"text": "import warnings\n\nclass fluiddict:\n\n MEMBER_ATTRIBUTE_LIST = [\n \"raise_KeyError\",\n \"datastore\",\n \"default_factory\",\n \"bypass_del_KeyError\",\n \"__getstate__\" # Comes from pickling\n ]\n\n \"\"\"! A class that emulates a dictionary, while also being able to support attribute assignment and default values.\n The default value of `default_factory` is None. This means a KeyError will be raised when non-existent data is requested\n To specify a default value of None, use `default_factory=lambda key: None`\n \"\"\"\n\n def __contains__(self, key):\n return self.is_defined(key)\n\n def __getitem__(self,key):\n if self.raise_KeyError and key not in self.datastore:\n raise KeyError(f\"Key '{key}' was not found in the datastore and no default factory was provided.\")\n\n if key not in self.datastore:\n try:\n return self.default_factory(key)\n except Exception as e:\n print(\"An unknown exception occured while trying to provide a default value. Is your default factory valid?\")\n raise e\n\n return self.datastore[key]\n\n def __setitem__(self,key,value):\n self.datastore[key] = value\n\n def __getattr__(self, attr_name):\n if attr_name in fluiddict.MEMBER_ATTRIBUTE_LIST:\n return object.__getattr__(self,attr_name) \n return self.__getitem__(attr_name)\n\n def __setattr__(self,attr_name,value):\n if attr_name in fluiddict.MEMBER_ATTRIBUTE_LIST:\n object.__setattr__(self,attr_name,value)\n else:\n self.__setitem__(attr_name,value)\n\n def __delitem__(self, key):\n \n if key not in self.datastore:\n if not self.bypass_del_KeyError:\n raise KeyError(f\"Key {key} was not found in the datastore.\")\n else:\n warnings.warn(f\"Attemping to delete nonexistent key {key} in the datastore. Ignoring del statement...\")\n else:\n del self.datastore[key]\n\n def is_defined(self,key):\n return key in self.datastore\n\n def is_set(self,key): #PHP-style `isset` function\n return key in self.datastore and self.datastore[key] is not None\n\n def __init__(self, default_factory =None, bypass_del_KeyError=False):\n\n self.datastore = {}\n\n self.raise_KeyError = False\n\n if default_factory is None:\n self.raise_KeyError = True\n\n self.bypass_del_KeyError = bypass_del_KeyError\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1990897/"
] |
74,436,624 | <p>I have <code>LazyColumn</code> and I want to pass 2 lists in <code>items</code>, how I can do it</p>
<p>I want to do something like that if it is possible</p>
<pre><code>LazyColumn(
modifier = Modifier.fillMaxHeight(0.85f)
) {
items(cartItems,products) { cartItems,product ->
CardProduct2(cartItems, product)
}
}
</code></pre>
| [
{
"answer_id": 74436911,
"author": "Tim Roberts",
"author_id": 1883316,
"author_profile": "https://Stackoverflow.com/users/1883316",
"pm_score": 3,
"selected": true,
"text": "__setattr__"
},
{
"answer_id": 74437189,
"author": "Michael Sohnen",
"author_id": 5166365,
"author_profile": "https://Stackoverflow.com/users/5166365",
"pm_score": 0,
"selected": false,
"text": "import warnings\n\nclass fluiddict:\n\n MEMBER_ATTRIBUTE_LIST = [\n \"raise_KeyError\",\n \"datastore\",\n \"default_factory\",\n \"bypass_del_KeyError\",\n \"__getstate__\" # Comes from pickling\n ]\n\n \"\"\"! A class that emulates a dictionary, while also being able to support attribute assignment and default values.\n The default value of `default_factory` is None. This means a KeyError will be raised when non-existent data is requested\n To specify a default value of None, use `default_factory=lambda key: None`\n \"\"\"\n\n def __contains__(self, key):\n return self.is_defined(key)\n\n def __getitem__(self,key):\n if self.raise_KeyError and key not in self.datastore:\n raise KeyError(f\"Key '{key}' was not found in the datastore and no default factory was provided.\")\n\n if key not in self.datastore:\n try:\n return self.default_factory(key)\n except Exception as e:\n print(\"An unknown exception occured while trying to provide a default value. Is your default factory valid?\")\n raise e\n\n return self.datastore[key]\n\n def __setitem__(self,key,value):\n self.datastore[key] = value\n\n def __getattr__(self, attr_name):\n if attr_name in fluiddict.MEMBER_ATTRIBUTE_LIST:\n return object.__getattr__(self,attr_name) \n return self.__getitem__(attr_name)\n\n def __setattr__(self,attr_name,value):\n if attr_name in fluiddict.MEMBER_ATTRIBUTE_LIST:\n object.__setattr__(self,attr_name,value)\n else:\n self.__setitem__(attr_name,value)\n\n def __delitem__(self, key):\n \n if key not in self.datastore:\n if not self.bypass_del_KeyError:\n raise KeyError(f\"Key {key} was not found in the datastore.\")\n else:\n warnings.warn(f\"Attemping to delete nonexistent key {key} in the datastore. Ignoring del statement...\")\n else:\n del self.datastore[key]\n\n def is_defined(self,key):\n return key in self.datastore\n\n def is_set(self,key): #PHP-style `isset` function\n return key in self.datastore and self.datastore[key] is not None\n\n def __init__(self, default_factory =None, bypass_del_KeyError=False):\n\n self.datastore = {}\n\n self.raise_KeyError = False\n\n if default_factory is None:\n self.raise_KeyError = True\n\n self.bypass_del_KeyError = bypass_del_KeyError\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18823812/"
] |
74,436,654 | <p>I am trying to extract the user id from generated file name. First I wrote them as :</p>
<pre><code>id_timestamp.ext
</code></pre>
<p>And now I need to read the list and filter out of the list of files only specific user with the id owned files.</p>
<p>I think doing</p>
<pre><code>substring(fileName, id.length)
</code></pre>
<p>is to wonky.</p>
<p>Is there a way to do it ? Should I use a regex?</p>
| [
{
"answer_id": 74437479,
"author": "Jakob Em",
"author_id": 8995812,
"author_profile": "https://Stackoverflow.com/users/8995812",
"pm_score": 1,
"selected": false,
"text": "const filename = 'id_timestamp.ext';\nconst regex = /^(\\w+)_timestamp\\.ext$/;\nconst id = filename.match(regex)[1];\n"
},
{
"answer_id": 74437556,
"author": "Bergi",
"author_id": 1048572,
"author_profile": "https://Stackoverflow.com/users/1048572",
"pm_score": 3,
"selected": true,
"text": "const filename = `${id}_${timestamp}.ext`;\n"
},
{
"answer_id": 74437615,
"author": "Chirag Shah",
"author_id": 1744270,
"author_profile": "https://Stackoverflow.com/users/1744270",
"pm_score": 1,
"selected": false,
"text": "id"
},
{
"answer_id": 74439631,
"author": "Lewis E",
"author_id": 1724627,
"author_profile": "https://Stackoverflow.com/users/1724627",
"pm_score": 1,
"selected": false,
"text": "getId = function(s){ s = s.substring(this,s.lastIndexOf('.')); s = s.substring(this,s.lastIndexOf('_')); return s; }"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13603485/"
] |
74,436,665 | <p>I am trying to write a frontend for my API but I stuck at some point and couldn't figure out the solution. I get the issue that my "getResult" can not invoke map function at rendering. I tried everything and I end up with nothing.</p>
<p>So my Filter component as in the following. At the end of the render I implement GameTable component which is given after this codeblock.</p>
<pre><code>import React, { useState, useEffect } from 'react'
import { useQuery } from 'react-query';
import gameService from '../services/gameService'
import GameTable from './GameTable'
import '../App.css'
const Filter = () => {
const [getName, setGetName] = useState("")
const [getGenre, setGetGenre] = useState("")
//const [getPublisher, setGetPublisher] = useState("")
const [metadata,setMetadata] = useState([])
const [getResult, setGetResult] = useState([])
const fortmatResponse = (res) => {
return JSON.stringify(res,null, 2);
}
const {isLoading: isLoadingGames, refetch: getAllGames} = useQuery("query-games",
async() => {
return await gameService.get("/games");
},
{
enabled: false,
onSuccess: (res) => {
const result = {
status : res.status + "-" + res.statusText,
headers: res.headers,
data: res.data,
};
setMetadata(fortmatResponse(result.data.metadata));
setGetResult(fortmatResponse(result.data.games));
},
onError : (err) => {
setGetResult(fortmatResponse(err.response?.data || err));
},
}
);
useEffect(() => {
if (isLoadingGames) setGetResult("loading...");
},[isLoadingGames]);
function getAllData() {
try{
getAllGames();
}catch(err) {
setGetResult(fortmatResponse(err));
}
}
const {isLoading: isLoadingGame, refetch: getGamesByName} = useQuery(
"query-games-by-name",
async () => {
return await gameService.get(`/games?name=${getName}`);
},
{
enabled: false,
onSuccess: (res) => {
const result = {
status : res.status + "-" + res.statusText,
headers: res.headers,
data: res.data,
};
setMetadata(fortmatResponse(result.data.metadata));
setGetResult(fortmatResponse(result.data.games));
},
onError : (err) => {
setGetResult(fortmatResponse(err.response?.data || err));
},
}
);
useEffect(() => {
if (isLoadingGame) setGetResult("loading...");
}, [isLoadingGame]);
function getDataByName() {
if (getName) {
try {
getGamesByName();
} catch (err) {
setGetResult(fortmatResponse(err));
}
}
}
const {isLoading: isSearchingGame, refetch: findGamesByGenre} = useQuery(
"query-games-by-genre",
async () => {
return await gameService.get(`/games?genre=${getGenre}`);
},
{
enabled: false,
onSuccess: (res) => {
const result = {
status : res.status + "-" + res.statusText,
headers: res.headers,
data: res.data,
};
setMetadata(fortmatResponse(result.data.metadata));
setGetResult(fortmatResponse(result.data.games));
},
onError : (err) => {
setGetResult(fortmatResponse(err.response?.data || err));
},
}
);
useEffect(() => {
if (isSearchingGame) setGetResult("loading...");
}, [isSearchingGame]);
function getDataByGenre() {
if (getGenre) {
try {
findGamesByGenre();
} catch (err) {
setGetResult(fortmatResponse(err));
}
}
}
const clearGetOutput =() => {
setGetResult([]);
}
console.log(metadata)
return(
<div className='card'>
<div className='card-header input-group-sm'> GET Request </div>
<div className='card-body'>
<div className='input-group input-group-sm'>
<button className='btn btn-sm btn-primary' onClick={getAllData}>
Get All
</button>
<input
type="text"
value={getName}
onChange={(e) => setGetName(e.target.value)}
className='form-control ml-2'
placeholder='Name'
/>
<div className='input-group-append'>
<button className="btn btn-sm btn-primary" onClick={getDataByName}>
Get by Name
</button>
</div>
<input
type="text"
value={getGenre}
onChange={(e) => setGetGenre(e.target.value)}
className="form-control ml-2"
placeholder="Genre"
/>
<div className="input-group-append">
<button className="btn btn-sm btn-primary" onClick={getDataByGenre}>
Find By Genre
</button>
</div>
<button className="btn btn-sm btn-warning ml-2" onClick={clearGetOutput}>
Clear
</button>
</div>
<GameTable games={getResult} />
</div>
</div>
)
}
export default Filter;
</code></pre>
<p>Here is my GameTable.js</p>
<pre><code>import React from 'react'
import Game from './Game'
import '../App.css'
const GameTable = ({games}) => {
return (
<div className="table-wrapper">
<h2>Games</h2>
<table className='fl-table'>
<thead>
<tr>
<th> Name </th>
<th> Genre </th>
<th> Publisher </th>
</tr>
</thead>
<tbody>
{
games.map(game =>
<Game key={game.id} game={game} />
)
}
</tbody>
</table>
</div>
)
}
export default GameTable;
</code></pre>
<p>And Game.js is as following.</p>
<pre><code>import React from 'react'
const Game = ({game}) => {
return (
<tr>
<td>{game.name}</td>
<td>{game.genre}</td>
<td>{game.publisher_name}</td>
</tr>
)
}
export default Game
</code></pre>
<p>I am sure this is pretty straight-forward for some of you but I really stuck. Any helps and tips will be much appreciated. Thanks.</p>
<p>I have changed the initial state from null to [] but that didn't help.</p>
| [
{
"answer_id": 74436966,
"author": "David",
"author_id": 328193,
"author_profile": "https://Stackoverflow.com/users/328193",
"pm_score": 1,
"selected": true,
"text": ".map()"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5012090/"
] |
74,436,676 | <h2>start code</h2>
<pre><code><table style="width:100%">
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
</table>
</code></pre>
<h2>end code</h2>
<p>If for example I want to apply a border on the block how contain the 2 td's ( Maria Anders , Germany ) , which html can I possibly use to wrap my 2 td's. I searching for a html tag how can help me wrap td's element's .</p>
| [
{
"answer_id": 74436966,
"author": "David",
"author_id": 328193,
"author_profile": "https://Stackoverflow.com/users/328193",
"pm_score": 1,
"selected": true,
"text": ".map()"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20406999/"
] |
74,436,686 | <p>In a classic version of states, each state implementing some interface. So we can pass execution to any current state</p>
<pre><code>class Context
{
private State _state;
public void MethodA()
{
_state.MethodA();
}
public void MethodB()
{
_state.MethodB();
}
}
</code></pre>
<p>But in my case. I have a gameplay feature. It offers something to buy. And it also has states, like "Active", "Buying", "Preparing", "Finished" and so on. From some of them buying is allowed, from others - not.
In more abstract way - each of states implement only part of the context's interface methods. And methods may intersect</p>
<pre><code>class ConcreteStateA
{
public void MethodA()
{
// Do A
}
// No MethodB
}
class ConcreteStateB
{
// No MethodA
public void MethodB()
{
// Do B
}
}
</code></pre>
<p>The question: is it any modification to use state machine this way? The current variation cause to directly check whether it's correct state or not before call in context. State classes hierarchy doesn't save from the problem of state type checking</p>
| [
{
"answer_id": 74436966,
"author": "David",
"author_id": 328193,
"author_profile": "https://Stackoverflow.com/users/328193",
"pm_score": 1,
"selected": true,
"text": ".map()"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7769540/"
] |
74,436,704 | <p>I am coding a tip calculator for my class and we need to create 3 functions. The second function needs to use the number I got in the first function, and the third function needs to use the number I got in the second function.</p>
<p>What I tried:</p>
<pre><code>// Grab the HTML Elements you want to work with
const billTotal = document.querySelector("#billTotal");
const tipPercent = document.querySelector("#tipPercent");
const noPeople = document.querySelector("#noPeople");
const calcTip = document.querySelector("#calcTip");
const resultsDiv = document.querySelector("#resultsDiv");
// Add event Listeners for your elements
calcTip.addEventListener("click", function() {
getTipAmount();
getBillTotal();
});
// Declare any functions you will need
function getTipAmount() {
let total = Number(billTotal.value);
let tip = Number(tipPercent.value);
let output = total * (tip / 100);
let tipAmount = output.toFixed(2);
console.log(tipAmount);
}
function getBillTotal() {
let billAmount = Number(billTotal.value);
let billTotalur = tipAmount + billAmount;
let billTotalr = billTotalur.toFixed(2);
console.log(billTotalr)
}
function amountPerPerson() {
}
</code></pre>
<p>I was expecting the tipAmount to be added to billAmount but I receive tipAmount is not defined.</p>
| [
{
"answer_id": 74437163,
"author": "Lucasbk38",
"author_id": 20480528,
"author_profile": "https://Stackoverflow.com/users/20480528",
"pm_score": 3,
"selected": true,
"text": "// Grab the HTML Elements you want to work with\nconst billTotal = document.querySelector(\"#billTotal\");\nconst tipPercent = document.querySelector(\"#tipPercent\");\nconst noPeople = document.querySelector(\"#noPeople\");\nconst calcTip = document.querySelector(\"#calcTip\");\nconst resultsDiv = document.querySelector(\"#resultsDiv\");\n\n\n// Add event Listeners for your elements\ncalcTip.addEventListener(\"click\", function() {\n const tipAmount = getTipAmount();\n const billTotalr = getBillTotal(tipAmount);\n\n console.log(tipAmount);\n console.log(billTotalr)\n});\n\n// Declare any functions you will need \n\nfunction getTipAmount () {\n const total = Number(billTotal.value);\n const tip = Number(tipPercent.value);\n const output = total * (tip / 100);\n const tipAmount = output.toFixed(2);\n\n return tipAmount \n}\n\nfunction getBillTotal (tipAmount) {\n const billAmount = Number(billTotal.value);\n const billTotalur = tipAmount + billAmount;\n const billTotalr = billTotalur.toFixed(2);\n \n return billTotalr\n}\n\nfunction amountPerPerson() {\n\n}\n"
},
{
"answer_id": 74438177,
"author": "user3425506",
"author_id": 3425506,
"author_profile": "https://Stackoverflow.com/users/3425506",
"pm_score": 0,
"selected": false,
"text": "function func1() {\n return 'Hello';\n}\n\nfunction func2(string) {\n return string + ' world';\n}\n\nconst result1 = func1();\n\nconst result2 = func2(result1);\n\nconsole.log(result2);"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20503678/"
] |
74,436,717 | <p>In my application I am listing in an appBar several Containers that have the names of product categories, these categories are being listed in the body with their respective products.</p>
<p>The ListView that is in the appBar has the same indexes of the ListView of the body, so the idea was to press the index 'x' in the appBar and the user would be redirected to the index 'x' in the body.</p>
<p>I tried many solutions, one of then was the package <a href="https://pub.dev/packages/scrollable_positioned_list" rel="nofollow noreferrer">https://pub.dev/packages/scrollable_positioned_list</a>, but it did not works because when calling the function to scroll my list just disappears.</p>
<p>Here's de code:</p>
<pre><code>return Scaffold(
backgroundColor: Colors.white,
appBar: PreferredSize(
preferredSize: Size.fromHeight(120),
child: Column(
children: [
AppBar(...),
Expanded(
child: Container(
color: AppColors.primary,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: widget.listaProdutos.length,
itemBuilder: (context, index) {
return Padding(
padding: EdgeInsets.symmetric(...),
child: GestureDetector(
child: Container(
decoration: BoxDecoration(...),
child: Padding(...),
child: Center(
child: Text(
widget.listaProdutos[index].dsGrupo,
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
),
),
),
onTap: () {
SHOULD SCROLL TO INDEX
},
),
);
},
)
),
),
],
),
),
body: SingleChildScrollView(
child: Column(
children: [
Container(
child: ListView.builder(
physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemCount: widget.listaProdutos.length,
itemBuilder: (context, indexGrupo) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Card(...),
ListView.builder(..),
],
);
},
),
),
],
),
),
);
</code></pre>
| [
{
"answer_id": 74436928,
"author": "Yeasin Sheikh",
"author_id": 10157127,
"author_profile": "https://Stackoverflow.com/users/10157127",
"pm_score": 1,
"selected": false,
"text": "scrollDirection: Axis.vertical,"
},
{
"answer_id": 74464242,
"author": "Roberto Henrique",
"author_id": 16797604,
"author_profile": "https://Stackoverflow.com/users/16797604",
"pm_score": 0,
"selected": false,
"text": "body: SingleChildScrollView(\n child: Column(\n children: [\n Container(\n child: ScrollablePositionedList.builder(\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16797604/"
] |
74,436,760 | <p>I have a Users table (id, name, created_at) and a Transaction table(id, user_id, created_at, amount).
For each month, I would like to know the number of users who did not have any transaction in the 3 months interval before that month.
For example, for April 2022, the query would return number of users who did not have a transaction in January 2022, February 2022 and March 2022. And so on for every month.</p>
<p>Can I do this with a single MySQL query, and without PHP loop?</p>
<p>If I wanted it for April 2022 only, then I guess this would do the trick:</p>
<pre><code>SELECT count(distinct(users.id)) FROM users
INNER JOIN transactions
on users.id = transactions.user_id
WHERE transactions.user_id NOT IN
(SELECT user_id FROM transactions WHERE created_at > "2022-01-01" AND created_at < "2022-04-01" );
</code></pre>
<p>How to get it for all months?</p>
| [
{
"answer_id": 74437477,
"author": "Akina",
"author_id": 10138734,
"author_profile": "https://Stackoverflow.com/users/10138734",
"pm_score": 0,
"selected": false,
"text": "SELECT count(*) \nFROM users \nWHERE NOT EXISTS (\n SELECT NULL\n FROM transactions \n WHERE users.id = transactions.user_id \n AND created_at > '2022-01-01' AND created_at < '2022-04-01'\n );\n"
},
{
"answer_id": 74438525,
"author": "GMB",
"author_id": 10676716,
"author_profile": "https://Stackoverflow.com/users/10676716",
"pm_score": 1,
"selected": false,
"text": "calendar(start_of_month)"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3884029/"
] |
74,436,767 | <p>When I compute the following in Matlab</p>
<pre><code>myeps = abs(3*(4/3-1)-1);
format long e
eps_myeps = [eps ; myeps]
</code></pre>
<p>The output is as follows:</p>
<pre><code>eps_myeps =
2.220446049250313e-16
2.220446049250313e-16
</code></pre>
<p>Why is <code>myeps</code> not 0? Why does this not hold when the base is 3 instead of 2?</p>
| [
{
"answer_id": 74438012,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 2,
"selected": false,
"text": "4/3"
},
{
"answer_id": 74439782,
"author": "X Zhang",
"author_id": 1321247,
"author_profile": "https://Stackoverflow.com/users/1321247",
"pm_score": 0,
"selected": false,
"text": "3*(sym(4)/sym(3)-1)-1"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20354019/"
] |
74,436,801 | <pre class="lang-none prettyprint-override"><code>function[function name](parameters){
console.log(string attached to parameter, string attached to parameter, parameter) and print)
}
</code></pre>
<p>Now what I have is this:</p>
<p><a href="https://i.stack.imgur.com/pABjJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pABjJ.png" alt="What I have" /></a></p>
<p>Perform the task I want to do in the function.</p>
| [
{
"answer_id": 74438012,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 2,
"selected": false,
"text": "4/3"
},
{
"answer_id": 74439782,
"author": "X Zhang",
"author_id": 1321247,
"author_profile": "https://Stackoverflow.com/users/1321247",
"pm_score": 0,
"selected": false,
"text": "3*(sym(4)/sym(3)-1)-1"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20095017/"
] |
74,436,805 | <p>I have the following DataFrame</p>
<pre><code> Value Date
0 1 2022-01-01
1 2 2022-01-01
2 3 2022-01-01
3 4 2022-01-02
4 5 2022-01-02
5 6 2022-01-02
6 7 2022-01-03
7 8 2022-01-03
8 9 2022-01-03
</code></pre>
<p>I would like to obtain the following DataFrame, by grouping all the values associated with a given date:</p>
<pre><code>Date 2022-01-01 2022-01-02 2022-01-03
0 1 4 7
1 2 5 8
2 3 6 9
</code></pre>
<p>I know this should be a really simply task, but I'm struggling to figure it out. I have used
<code>df.groupby('Date')['Value].apply(list).to_frame.T</code>, but that didn't work. Any help in solving this would be greatly appreciated.</p>
| [
{
"answer_id": 74437069,
"author": "I'mahdi",
"author_id": 1740577,
"author_profile": "https://Stackoverflow.com/users/1740577",
"pm_score": 3,
"selected": true,
"text": "pandas.DataFrame.pivot"
},
{
"answer_id": 74437426,
"author": "PaulS",
"author_id": 11564487,
"author_profile": "https://Stackoverflow.com/users/11564487",
"pm_score": 1,
"selected": false,
"text": "pivot_wider"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12064467/"
] |
74,436,806 | <p>Consider whether <code>x</code> in the declaration <code>int x;</code> is an expression.</p>
<p>I used to think that it's certainly not, but the grammar calls the variable name an <em><a href="http://eel.is/c++draft/dcl.decl.general#nt:declarator-id" rel="noreferrer"><code>id-expression</code></a></em> here.</p>
<p>One could then argue that only <a href="http://eel.is/c++draft/expr.comma#nt:expression" rel="noreferrer"><em><code>expression</code></em></a> is an expression, not <em><code>??-expression</code></em>. But then in <code>1 + 2</code>, neither <code>1</code> nor <code>2</code> match, because those are <em><code>additive-expression</code></em> and <em><code>multiplicative-expression</code></em> respectively, not <i><code>expression</code></i>s. But common sense says those should be called expressions too.</p>
<p>We could decide that any <em><code>??-expression</code></em> (including <em><code>expression</code></em>) is an expression, but then the variable name in a declaration matches as well.</p>
<p>We could define an expression to be any <em><code>??-expression</code></em> except <em><code>id-expression</code></em>, but this feels rather arbitrary.</p>
<p>What's the right grammatical definition of an expression, and is the variable name in its declaration an expression or not?</p>
| [
{
"answer_id": 74437105,
"author": "n. m.",
"author_id": 775806,
"author_profile": "https://Stackoverflow.com/users/775806",
"pm_score": 2,
"selected": false,
"text": "x"
},
{
"answer_id": 74438164,
"author": "HolyBlackCat",
"author_id": 2752075,
"author_profile": "https://Stackoverflow.com/users/2752075",
"pm_score": 3,
"selected": true,
"text": "id-expression"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2752075/"
] |
74,436,810 | <p>I hope everyone is doing great! I'm currently learning how to use R. I'm trying to download Stock DATA from Yahoo Finance. In this case, I'm trying just to get closing prices from these securities. However, I'd like to extract only daily data from let's day September 1st 2022 to November 13rd 2022. How could I do that?</p>
<p>So far I got this:</p>
<pre><code>symbols <- c("SPY", "JNK", "EEM", "EMB", "TLT", "USO")
getSymbols(symbols)
ClosePrices <- do.call(merge, lapply(symbols, function(x) Cl(get(x))))
head(ClosePrices)
</code></pre>
<p>Thank you in advance for your help!
Eduardo</p>
| [
{
"answer_id": 74437323,
"author": "Ric Villalba",
"author_id": 6912817,
"author_profile": "https://Stackoverflow.com/users/6912817",
"pm_score": 1,
"selected": false,
"text": "library(quantmod)\n\nsymbols <- c(\"SPY\", \"JNK\", \"EEM\", \"EMB\", \"TLT\", \"USO\")\ngetSymbols(symbols)\n\nClosePrices <- do.call(merge, lapply(symbols, function(x) Cl(get(x))[seq.Date(\n from = as.Date(\"2022-09-01\"), \n to = as.Date(\"2022-11-13\"), \n by = \"days\")]))\n\nhead(ClosePrices)\n#> SPY.Close JNK.Close EEM.Close EMB.Close TLT.Close USO.Close\n#> 2022-09-01 396.42 91.56 39.12 84.78 109.60 70.95\n#> 2022-09-02 392.24 91.59 38.76 85.08 110.22 71.43\n#> 2022-09-06 390.76 91.38 38.30 84.30 107.49 71.42\n#> 2022-09-07 397.78 92.57 38.64 85.58 109.19 67.62\n#> 2022-09-08 400.38 92.95 38.43 85.61 108.07 68.09\n#> 2022-09-09 406.60 93.35 39.00 86.13 108.31 71.10\n"
},
{
"answer_id": 74452113,
"author": "Joshua Ulrich",
"author_id": 271616,
"author_profile": "https://Stackoverflow.com/users/271616",
"pm_score": 0,
"selected": false,
"text": "symbols <- c(\"SPY\", \"JNK\", \"EEM\", \"EMB\", \"TLT\", \"USO\")\n\n# Environment to hold data\nmyData <- new.env()\n\n# Tell getSymbols() to load the data into 'myData'\ngetSymbols(symbols, env = myData)\n\n# Combine all the close prices into one xts object\nClosePrices <- do.call(merge, lapply(myData, Cl))\n\n# Now use xts-style subset to get the date range you want\nClosePriceSubset <- ClosePrices[\"2022-09-01/2022-11-13\"]\n\nhead(ClosePriceSubset)\n## TLT.Close EEM.Close USO.Close EMB.Close JNK.Close SPY.Close\n## 2022-09-01 109.60 39.12 70.95 84.78 91.56 396.42\n## 2022-09-02 110.22 38.76 71.43 85.08 91.59 392.24\n## 2022-09-06 107.49 38.30 71.42 84.30 91.38 390.76\n## 2022-09-07 109.19 38.64 67.62 85.58 92.57 397.78\n## 2022-09-08 108.07 38.43 68.09 85.61 92.95 400.38\n## 2022-09-09 108.31 39.00 71.10 86.13 93.35 406.60\n\ntail(ClosePriceSubset)\n## TLT.Close EEM.Close USO.Close EMB.Close JNK.Close SPY.Close\n## 2022-11-04 94.22 36.20 76.82 80.41 89.33 376.35\n## 2022-11-07 93.28 36.22 76.56 80.38 89.33 379.95\n## 2022-11-08 94.30 36.48 74.47 80.94 89.15 382.00\n## 2022-11-09 94.61 35.85 71.67 79.85 88.09 374.13\n## 2022-11-10 98.25 37.15 72.24 83.52 90.84 394.69\n## 2022-11-11 97.89 38.16 74.38 83.50 91.16 398.51\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20503653/"
] |
74,436,815 | <p>I'm trying to deserialize json-formatted response below.</p>
<pre><code>{
"context": "xxxxxx"
"value": [
{
"Id": "123"
"Time": "2022-12-01"
}
{
"Id": "123"
"Time": "2022-12-01"
}
....
]
}
</code></pre>
<p>According to this: <a href="https://www.newtonsoft.com/json/help/html/deserializeobject.htm" rel="nofollow noreferrer">https://www.newtonsoft.com/json/help/html/deserializeobject.htm</a>, this code should work.</p>
<pre><code> public class WorkingSetContent
{
/// <summary>Collection ID</summary>
[JsonProperty("context")]
public string Context { get; set; }
/// <summary>UserRelationship</summary>
[JsonProperty("value")]
public IList<ItemClass> Items { get; set; }
}
</code></pre>
<p>But I'm getting a build error : "Change 'Items' to be read-only by removing the property setter."</p>
<p>I changed the setter to private to avoid this build error, then I was able to run it, but it causes a runtime error as null value is passed.</p>
| [
{
"answer_id": 74437323,
"author": "Ric Villalba",
"author_id": 6912817,
"author_profile": "https://Stackoverflow.com/users/6912817",
"pm_score": 1,
"selected": false,
"text": "library(quantmod)\n\nsymbols <- c(\"SPY\", \"JNK\", \"EEM\", \"EMB\", \"TLT\", \"USO\")\ngetSymbols(symbols)\n\nClosePrices <- do.call(merge, lapply(symbols, function(x) Cl(get(x))[seq.Date(\n from = as.Date(\"2022-09-01\"), \n to = as.Date(\"2022-11-13\"), \n by = \"days\")]))\n\nhead(ClosePrices)\n#> SPY.Close JNK.Close EEM.Close EMB.Close TLT.Close USO.Close\n#> 2022-09-01 396.42 91.56 39.12 84.78 109.60 70.95\n#> 2022-09-02 392.24 91.59 38.76 85.08 110.22 71.43\n#> 2022-09-06 390.76 91.38 38.30 84.30 107.49 71.42\n#> 2022-09-07 397.78 92.57 38.64 85.58 109.19 67.62\n#> 2022-09-08 400.38 92.95 38.43 85.61 108.07 68.09\n#> 2022-09-09 406.60 93.35 39.00 86.13 108.31 71.10\n"
},
{
"answer_id": 74452113,
"author": "Joshua Ulrich",
"author_id": 271616,
"author_profile": "https://Stackoverflow.com/users/271616",
"pm_score": 0,
"selected": false,
"text": "symbols <- c(\"SPY\", \"JNK\", \"EEM\", \"EMB\", \"TLT\", \"USO\")\n\n# Environment to hold data\nmyData <- new.env()\n\n# Tell getSymbols() to load the data into 'myData'\ngetSymbols(symbols, env = myData)\n\n# Combine all the close prices into one xts object\nClosePrices <- do.call(merge, lapply(myData, Cl))\n\n# Now use xts-style subset to get the date range you want\nClosePriceSubset <- ClosePrices[\"2022-09-01/2022-11-13\"]\n\nhead(ClosePriceSubset)\n## TLT.Close EEM.Close USO.Close EMB.Close JNK.Close SPY.Close\n## 2022-09-01 109.60 39.12 70.95 84.78 91.56 396.42\n## 2022-09-02 110.22 38.76 71.43 85.08 91.59 392.24\n## 2022-09-06 107.49 38.30 71.42 84.30 91.38 390.76\n## 2022-09-07 109.19 38.64 67.62 85.58 92.57 397.78\n## 2022-09-08 108.07 38.43 68.09 85.61 92.95 400.38\n## 2022-09-09 108.31 39.00 71.10 86.13 93.35 406.60\n\ntail(ClosePriceSubset)\n## TLT.Close EEM.Close USO.Close EMB.Close JNK.Close SPY.Close\n## 2022-11-04 94.22 36.20 76.82 80.41 89.33 376.35\n## 2022-11-07 93.28 36.22 76.56 80.38 89.33 379.95\n## 2022-11-08 94.30 36.48 74.47 80.94 89.15 382.00\n## 2022-11-09 94.61 35.85 71.67 79.85 88.09 374.13\n## 2022-11-10 98.25 37.15 72.24 83.52 90.84 394.69\n## 2022-11-11 97.89 38.16 74.38 83.50 91.16 398.51\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20503681/"
] |
74,436,837 | <p>I have a txt file I need to turn into a usable dataframe in R. An example row looks like this:</p>
<pre><code>10040 1491 32006 820085011 .007 .009 .043 -.003 .008 .036 -.031 -.036 .076 .056 .124 .093 -.112 -.091 .034 .043 .00600 .01200 .004500000000 .042333333333 .0568 .0058 -.0542 -.0304 .08625 .05425 .088857142857 .116142857143 -.072714285714 -.115571428571 .02125 .04350 8.71250 8.71825 8.729666666667 8.749500000000 8.6866 8.6722
</code></pre>
<p>I would like to end up with a df with multiple columns that looks like this:</p>
<pre><code>10040 1 49 1 3 2006 8 2008 50 1 1 .007 .009 .043 -.003 .008 .036 -.031 -.036 .076 .056 .124 .093 -.112 -.091 .034 .043 .00600 .01200 .004500000000 .042333333333 .0568 .0058 -.0542 -.0304 .08625 .05425 .088857142857 .116142857143 -.072714285714 -.115571428571 .02125 .04350 8.71250 8.71825 8.729666666667 8.749500000000 8.6866 8.6722
</code></pre>
<p>The data is not perfectly split by spaces, or I would know how to do that. I know the positions of where to split the string into multiple columns: positions <code>5, 7, 9, 10, 12, 16, 18, 22,</code> etc. but was wondering if there is a way to do this without 50 lines of code? Perhaps using tidyr's separate function? Can't seem to find any documentation or examples explaining how to use the sep parameter with numeric positions.</p>
| [
{
"answer_id": 74437323,
"author": "Ric Villalba",
"author_id": 6912817,
"author_profile": "https://Stackoverflow.com/users/6912817",
"pm_score": 1,
"selected": false,
"text": "library(quantmod)\n\nsymbols <- c(\"SPY\", \"JNK\", \"EEM\", \"EMB\", \"TLT\", \"USO\")\ngetSymbols(symbols)\n\nClosePrices <- do.call(merge, lapply(symbols, function(x) Cl(get(x))[seq.Date(\n from = as.Date(\"2022-09-01\"), \n to = as.Date(\"2022-11-13\"), \n by = \"days\")]))\n\nhead(ClosePrices)\n#> SPY.Close JNK.Close EEM.Close EMB.Close TLT.Close USO.Close\n#> 2022-09-01 396.42 91.56 39.12 84.78 109.60 70.95\n#> 2022-09-02 392.24 91.59 38.76 85.08 110.22 71.43\n#> 2022-09-06 390.76 91.38 38.30 84.30 107.49 71.42\n#> 2022-09-07 397.78 92.57 38.64 85.58 109.19 67.62\n#> 2022-09-08 400.38 92.95 38.43 85.61 108.07 68.09\n#> 2022-09-09 406.60 93.35 39.00 86.13 108.31 71.10\n"
},
{
"answer_id": 74452113,
"author": "Joshua Ulrich",
"author_id": 271616,
"author_profile": "https://Stackoverflow.com/users/271616",
"pm_score": 0,
"selected": false,
"text": "symbols <- c(\"SPY\", \"JNK\", \"EEM\", \"EMB\", \"TLT\", \"USO\")\n\n# Environment to hold data\nmyData <- new.env()\n\n# Tell getSymbols() to load the data into 'myData'\ngetSymbols(symbols, env = myData)\n\n# Combine all the close prices into one xts object\nClosePrices <- do.call(merge, lapply(myData, Cl))\n\n# Now use xts-style subset to get the date range you want\nClosePriceSubset <- ClosePrices[\"2022-09-01/2022-11-13\"]\n\nhead(ClosePriceSubset)\n## TLT.Close EEM.Close USO.Close EMB.Close JNK.Close SPY.Close\n## 2022-09-01 109.60 39.12 70.95 84.78 91.56 396.42\n## 2022-09-02 110.22 38.76 71.43 85.08 91.59 392.24\n## 2022-09-06 107.49 38.30 71.42 84.30 91.38 390.76\n## 2022-09-07 109.19 38.64 67.62 85.58 92.57 397.78\n## 2022-09-08 108.07 38.43 68.09 85.61 92.95 400.38\n## 2022-09-09 108.31 39.00 71.10 86.13 93.35 406.60\n\ntail(ClosePriceSubset)\n## TLT.Close EEM.Close USO.Close EMB.Close JNK.Close SPY.Close\n## 2022-11-04 94.22 36.20 76.82 80.41 89.33 376.35\n## 2022-11-07 93.28 36.22 76.56 80.38 89.33 379.95\n## 2022-11-08 94.30 36.48 74.47 80.94 89.15 382.00\n## 2022-11-09 94.61 35.85 71.67 79.85 88.09 374.13\n## 2022-11-10 98.25 37.15 72.24 83.52 90.84 394.69\n## 2022-11-11 97.89 38.16 74.38 83.50 91.16 398.51\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19542535/"
] |
74,436,838 | <p>Does anyone know if the <a href="https://github.com/davidstutz/bootstrap-multiselect" rel="nofollow noreferrer">Boostrap Multiselect</a> plugin works in <code>default_popup</code> for chrome extensions with Manifest V3?</p>
<p>I saved jQuery, Bootstrap & <a href="https://github.com/davidstutz/bootstrap-multiselect" rel="nofollow noreferrer">Boostrap Multiselect</a> into the chrome extension and loaded them within popup.js as per <a href="https://davidstutz.github.io/bootstrap-multiselect/" rel="nofollow noreferrer">guide on the plugins page</a>.</p>
<p>Popup.html</p>
<pre><code><link rel="stylesheet" href="css/bootstrap.min.css" type="text/css"/>
<!--<script type="text/javascript" src="js/jquery.min.js"></script>-->
<script type="text/javascript" src="js/jquery-2.2.4.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/bootstrap-multiselect.js"></script>
<link rel="stylesheet" href="css/bootstrap-multiselect.css" type="text/css"/>
<select id="example-getting-started" multiple="multiple">
<option value="cheese">Cheese</option>
<option value="tomatoes">Tomatoes</option>
<option value="mozarella">Mozzarella</option>
<option value="mushrooms">Mushrooms</option>
<option value="pepperoni">Pepperoni</option>
<option value="onions">Onions</option>
</select>
<script src="popup.js"></script>
</code></pre>
<p>since I can't initialise the plugin within popup.html</p>
<pre><code><script type="text/javascript">
$(document).ready(function() {
$('#example-getting-started').multiselect();
});
</script>
</code></pre>
<p>as I get the error:</p>
<blockquote>
<p>Refused to execute inline script because it violates the following
Content Security Policy directive: "script-src 'self'". Either the
'unsafe-inline' keyword, a hash
('sha256-4lndvGzcMkUnvdfuDCzL0sOEfIW9cdivCN8IPHGBevM='), or a nonce
('nonce-...') is required to enable inline execution.</p>
<p>popup.html:121 Refused to execute inline script because it violates
the following Content Security Policy directive: "script-src 'self'
'wasm-unsafe-eval'". Either the 'unsafe-inline' keyword, a hash
('sha256-4lndvGzcMkUnvdfuDCzL0sOEfIW9cdivCN8IPHGBevM='), or a nonce
('nonce-...') is required to enable inline execution.</p>
</blockquote>
<p>thus I placed it into popup.js</p>
<pre><code>$(document).ready(function() {
$('#example-getting-started').multiselect({
});
console.log("multiselect");
});
</code></pre>
<p>I'm not getting any error message in the console within extension popup (only the log message) but bootstrap multiselect is not showing, only a button "None selected".</p>
| [
{
"answer_id": 74437157,
"author": "user1731468",
"author_id": 1731468,
"author_profile": "https://Stackoverflow.com/users/1731468",
"pm_score": 1,
"selected": false,
"text": "\"content_security_policy\": \"default-src 'none'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; object-src 'none'\",\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8719001/"
] |
74,436,846 | <p>I have created a standalone Google Apps Script (it does not belong to any document). The script get triggered automatically at some fixed intervals. This script</p>
<ul>
<li>creates a couple of folder (if they don't exist)</li>
<li>creates a Google spreadsheet (if it doesn exist). Read said
spreadsheet.</li>
<li>update calendar events</li>
</ul>
<p>I noticed that when I first run it, it asked for permissions to read, delete all Google Drive items, all spreadsheets and all calendar events</p>
<p>I work on tailoring the scopes required and at least Google Drive does not have those broad permissions. I am still unable to reduce the scope for Google spreadsheet (And also calendar).
An expert @TheMaster made a post some years but is not exactly the same case.</p>
<p>I tried changing the scopes but the editor complained and requested that to use <code>openById</code> I need to change the scopes back</p>
| [
{
"answer_id": 74437503,
"author": "Rubén",
"author_id": 1595451,
"author_profile": "https://Stackoverflow.com/users/1595451",
"pm_score": 0,
"selected": false,
"text": "/**\n * @OnlyCurrentDoc\n */\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7926503/"
] |
74,436,856 | <p>I have such an array of card objects:</p>
<pre><code>const cards = [
{
type: { method: 'listen' },
reference: ['destroyed', 'word 2']
},
{
type: { method: 'synonym' },
reference: ['destroyed']
},
{
type: { method: 'listen' },
reference: ['destroyed']
},
{
type: { method: 'dictate' },
reference: ['destroyed']
}
]
</code></pre>
<p>I want to sort them as follows:</p>
<ol>
<li>the <code>listen</code> cards should come first</li>
<li>between listen cards the ones that have less <code>reference.length</code>
should come earlier</li>
<li>any other cards should come then</li>
<li><code>dictate</code> cards should come at last</li>
</ol>
<p>I have no idea how to do such a complex sorting except doing the first condition:</p>
<pre><code> cards.sort(compare);
function compare(a, b) {
if(a.type.method == 'listen') return a.reference.length - b.reference.length;
...
}
</code></pre>
| [
{
"answer_id": 74436953,
"author": "caTS",
"author_id": 18244921,
"author_profile": "https://Stackoverflow.com/users/18244921",
"pm_score": 1,
"selected": false,
"text": "const cards = [\n {\n type: { method: 'listen' },\n reference: ['destroyed', 'word 2']\n },\n {\n type: { method: 'synonym' },\n reference: ['destroyed']\n },\n {\n type: { method: 'listen' },\n reference: ['destroyed']\n },\n {\n type: { method: 'dictate' },\n reference: ['destroyed']\n }\n];\n\ncards.sort((a, b) => {\n // both types are 'dictate' - no change\n if (a.type.method === \"dictate\" && b.type.method === \"dictate\") return 0;\n // move `b` up since `a` is 'dictate'\n if (a.type.method === \"dictate\") return 1;\n // move `a` up since `b` is 'dictate'\n if (b.type.method === \"dictate\") return -1;\n \n // if both are 'listen' then order based on refs\n if (a.type.method === \"listen\" && b.type.method === \"listen\") return a.reference.length - b.reference.length;\n // move `a` up since `a` is 'listen'\n if (a.type.method === \"listen\") return -1;\n // move `b` up since `b` is 'listen'\n if (b.type.method === \"listen\") return 1;\n\n // no change\n return 0;\n});\n\nconsole.log(cards);"
},
{
"answer_id": 74437150,
"author": "alex",
"author_id": 379241,
"author_profile": "https://Stackoverflow.com/users/379241",
"pm_score": 1,
"selected": false,
"text": "const cards = [\n {\n type: { method: 'listen' },\n reference: ['destroyed', 'word 2']\n },\n {\n type: { method: 'synonym' },\n reference: ['destroyed']\n },\n {\n type: { method: 'listen' },\n reference: ['destroyed']\n },\n {\n type: { method: 'dictate' },\n reference: ['destroyed']\n }\n]\n\nconst sortedCards = cards.sort((a, b) => {\n const priority = ['listen', 'synonym', 'dictate'];\n const indexA = priority.indexOf(a.type.method);\n const indexB = priority.indexOf(b.type.method);\n \n // First try to compare against the type\n // If the types are equal, it will be eval to 0 from (indexA - indexB).\n // 0 is considered false in javascript and hence will evulate the length of the reference.\n return indexA - indexB || a.reference.length - b.reference.length;\n});\n\nconsole.log(sortedCards);"
},
{
"answer_id": 74437773,
"author": "DanJogin",
"author_id": 14236551,
"author_profile": "https://Stackoverflow.com/users/14236551",
"pm_score": 0,
"selected": false,
"text": "cards.sort(compare);\nfunction compare(a, b) {\n if(b.type.method == \"dictate\") return -1000\n if(a.type.method == \"listen\" && b.type.method !== \"listen\") return -1.5\n if(a.type.method === \"listen\" && b.type.method === \"listen\") \n return a.reference.length - b.reference.length\n }\nconst cards = [\n {\n type: { method: 'listen' },\n reference: ['destroyed', 'word 2']\n },\n {\n type: { method: 'synonym' },\n reference: ['destroyed']\n },\n {\n type: { method: 'listen' },\n reference: ['destroyed']\n },\n {\n type: { method: 'dictate' },\n reference: ['destroyed 1']\n },\n {\n type: { method: 'listen' },\n reference: ['destroyed', 'word 2', 'type 3']\n },\n {\n type: { method: 'synonym' },\n reference: ['destroyed']\n },\n {\n type: { method: 'listen' },\n reference: ['destroyed', 'listen']\n },\n {\n type: { method: 'dictate' },\n reference: ['destroyed']\n },\n {\n type: { method: 'listen' },\n reference: ['destroyed', 'listen']\n },\n ]\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10715551/"
] |
74,436,868 | <p>We have a user facing web app powered by a SQL Server that allows users top update a table in our SQL Server that also needs to update a document record in our dynamo database table.</p>
<p>How could I reliably ensure that both commits have taken place? We can allow up to a few seconds in latency.</p>
| [
{
"answer_id": 74444042,
"author": "Borislav Stoilov",
"author_id": 5625696,
"author_profile": "https://Stackoverflow.com/users/5625696",
"pm_score": 1,
"selected": false,
"text": "<begin trx>\nsave item in SQL db\nsave item in Dynamo DB\n<commit trx>\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1030135/"
] |
74,436,878 | <p>i have file.txt like this</p>
<pre><code>
</code></pre>
<p>It is necessary to use a script or command to make it look like this:</p>
<pre><code>
</code></pre>
<p>i try <code>sort -k2,2nr file.txt</code> it works, but I also change the column in the middle)
maybe you can help me with something, I also know that <strong>AWK</strong> can work with the column specified in $, but I can't understand how to do it correctly</p>
| [
{
"answer_id": 74444042,
"author": "Borislav Stoilov",
"author_id": 5625696,
"author_profile": "https://Stackoverflow.com/users/5625696",
"pm_score": 1,
"selected": false,
"text": "<begin trx>\nsave item in SQL db\nsave item in Dynamo DB\n<commit trx>\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20503633/"
] |
74,436,917 | <p>I have a register form which shows the label "Birthdate" overwritten in the same place as the dd/mm/yyyy placeholder. Is there anyway I can remove it?</p>
<p>I tried this in CSS but it didn't work:</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>input[type=date]:required:invalid::-webkit-datetime-edit {
color: transparent;
}
input[type=date]:focus::-webkit-datetime-edit {
color: black !important;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="date" required>
<label>Birthdate</label></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74444042,
"author": "Borislav Stoilov",
"author_id": 5625696,
"author_profile": "https://Stackoverflow.com/users/5625696",
"pm_score": 1,
"selected": false,
"text": "<begin trx>\nsave item in SQL db\nsave item in Dynamo DB\n<commit trx>\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17525000/"
] |
74,436,920 | <p>I want to split a text by different words and not by periods. Here is a code I tried:</p>
<pre><code>string StringFromTheInput = TextBox1.Text;
string[] splichar1 = Regex.Split(StringFromTheInput, @"(?<=[\because\and\now\this is])");
</code></pre>
<p>I want to use these words or phrases as delimiter in text instead of period mark, this is an example what output I need:</p>
<pre><code> Text: Sentence blah blah blahh because bblahhh balh and blahhh
Output: because bblahhh balh and blahhh
another example-
</code></pre>
<p>Text: bla now blahhh</p>
<p>Output: now blahhh</p>
| [
{
"answer_id": 74439187,
"author": "Zakaria Najim",
"author_id": 10155157,
"author_profile": "https://Stackoverflow.com/users/10155157",
"pm_score": 2,
"selected": false,
"text": "String.Contains Method"
},
{
"answer_id": 74441978,
"author": "Yiyi You",
"author_id": 13593736,
"author_profile": "https://Stackoverflow.com/users/13593736",
"pm_score": 1,
"selected": false,
"text": "\\because\\and\\now\\this is"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20465780/"
] |
74,436,959 | <p>Is there a possibility to evaluate multiple IP networks within the same condition for advanced rule like its possible for counties ? [Currently function inIpRange allows to process only 1 IP range][1]</p>
<p>this works
<code>'AT,DE,NL,CZ,IT,CH,SK,HR,HU,SI,PL'.contains(origin.region_code) </code></p>
<p>this not
<code>'34.90.0.0/15,34.141.128.0/17,66.249.64.0/19'.contains(origin.ip) </code></p>
<p>Any ideas ?</p>
<p>EDIT:
I need to use exclusion in an advanced multi logic rule (there is host and path matching also involved) not the simply deny IPranges.</p>
<p>[1]: https://cloud.google.com/armor/docs/rules-language-reference#:~:text=inIpRange(x,larger%20than%20/64.</p>
| [
{
"answer_id": 74439187,
"author": "Zakaria Najim",
"author_id": 10155157,
"author_profile": "https://Stackoverflow.com/users/10155157",
"pm_score": 2,
"selected": false,
"text": "String.Contains Method"
},
{
"answer_id": 74441978,
"author": "Yiyi You",
"author_id": 13593736,
"author_profile": "https://Stackoverflow.com/users/13593736",
"pm_score": 1,
"selected": false,
"text": "\\because\\and\\now\\this is"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7786358/"
] |
74,436,974 | <p>I have deployed a model on real-time inference in a single gpu instance, it works fine.</p>
<p>Now I want to use a multiple GPUs to decrease the inference time, what do I need to change in my inference.py to make it work?</p>
<p>Here is some of my code:</p>
<pre><code>DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
def model_fn(model_dir):
logger.info("Loading first model...")
model = Model().to(DEVICE)
with open(os.path.join(model_dir, "checkpoint.pth"), "rb") as f:
model.load_state_dict(torch.load(f, map_location=DEVICE)['state_dict'])
model = model.eval()
logger.info("Loading second model...")
model_2 = Model_2()
model_2.to(DEVICE)
checkpoint = torch.load('checkpoint_2.pth', map_location=DEVICE)
model_2(remove_prefix_state_dict(checkpoint['state_dict']), strict=True)
model_2 = model_2()
logger.info('Done loading models')
return {'first_model': model, 'second_model': model_2}
def input_fn(request_body, request_content_type):
assert request_content_type=='application/json'
url = json.loads(request_body)['url']
save_name = json.loads(request_body)['save_name']
logger.info(f'Image url: {url}')
img = Image.open(requests.get(url, stream=True).raw).convert('RGB')
w, h = img.size
input_tensor = preprocess(img)
input_batch = input_tensor.unsqueeze(0).to(DEVICE)
logger.info('Image ready to predict!')
return {'tensor':input_batch, 'w':w,'h':h,'image':img, 'save_name':save_name}
def predict_fn(input_object, model):
data = input_object['tensor']
logger.info('Generating prediction based on the input image')
model_1 = model['first_model']
model_2 = model['second_model']
d0, d1, d2, d3, d4, d5, d6 = model_1(data)
torch.cuda.empty_cache()
mask = torch.argmax(d0[0], axis=0).cpu().numpy()
mask = np.where(mask==2, 255, mask)
mask = np.where(mask==1, 128, mask)
img = input_object['image']
final_image = Image.fromarray(mask).resize((input_object['w'], input_object['h'])).convert('L')
img = np.array(img)[:,:,::-1]
final_image = np.array(final_image)
image_dict = to_dict(img, final_image)
final_image = model_2_process(model_2, image_dict)
torch.cuda.empty_cache()
return {"final_ouput": final_image, 'image':input_object['image'], 'save_name': input_object['save_name']}
</code></pre>
<p>I was thinking that maybe with torch multiprocessing, any tips?</p>
| [
{
"answer_id": 74437401,
"author": "Giuseppe La Gualano",
"author_id": 20249888,
"author_profile": "https://Stackoverflow.com/users/20249888",
"pm_score": 0,
"selected": false,
"text": "torch.nn.DataParallel"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19583119/"
] |
74,436,975 | <p>I have a dataframe, <code>df</code>, with <code>datetimeindex</code> and a single column, like this:</p>
<p><a href="https://i.stack.imgur.com/X66I0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/X66I0.png" alt="enter image description here" /></a>
<a href="https://i.stack.imgur.com/z0dEo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/z0dEo.png" alt="enter image description here" /></a></p>
<p>I need to count how many non-zero entries i have at each month. For example, according to those images, in January i would have 2 entries, in February 1 entry and in March 2 entries. I have more months in the dataframe, but i guess that explains the problem.</p>
<p>I tried using pandas <code>groupby</code>:</p>
<pre><code>df.groupby(df.index.month).count()
</code></pre>
<p>But that just gives me total days at each month and i don't saw any other parameter in <code>count()</code> that i could use here.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 74437401,
"author": "Giuseppe La Gualano",
"author_id": 20249888,
"author_profile": "https://Stackoverflow.com/users/20249888",
"pm_score": 0,
"selected": false,
"text": "torch.nn.DataParallel"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12297666/"
] |
74,436,976 | <p>I have to join user_name from user table where as first_name and last_names from user_profile table. Until here everything is fine, but when I try to fetch respective roles assigned from user_role tables it gives multiple rows for single user as 1 user can have multiple roles.</p>
<p>While trying to apply <code>string_agg</code> on role.names (so that multiple roles shown comma separated in single tuple), it gives each role in separate row.</p>
<p>Here is example query I am trying to run in postgresql:</p>
<pre><code> SELECT users.user_name, user_profiles.first_name, user_profiles.last_name,
(
SELECT string_agg (roles.name, ',')
from roles
where roles.id in (
select user_roles.role_id where users.id = user_roles.user_id
)
) as name
FROM users
JOIN user_profiles ON users.id = user_profiles.user_id
JOIN user_roles ON user_roles.user_id = users.id
</code></pre>
| [
{
"answer_id": 74437141,
"author": "JNevill",
"author_id": 2221001,
"author_profile": "https://Stackoverflow.com/users/2221001",
"pm_score": 2,
"selected": true,
"text": "GROUP BY"
},
{
"answer_id": 74437561,
"author": "Zegarek",
"author_id": 5298879,
"author_profile": "https://Stackoverflow.com/users/5298879",
"pm_score": 0,
"selected": false,
"text": "from"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3117920/"
] |
74,436,986 | <p>I just recently started learning Angular and I have a question. I want to implement a search method to search for a product on my site, I made search.pipe.ts, which works, but the input for input is in the header.component.ts component, and the products array is in the car-list.component.ts component.</p>
<h3>car-list.component.html</h3>
<pre><code><div *ngFor="let car of cars | paginate: { itemsPerPage: pageNumber, currentPage: currentPg} | **search:searchStr**" class="col-md-3">
<div class="product box">
<img src="{{'data:image/jpg;base64,' + car.image }}" alt="">
<h3>{{ car.name }}</h3>
<div class="price">{{ car.price | currency:'USD' }}</div>
<button class="btn btn-primary btn-sm">Add to cart</button> <!--(click)="addToCart(tempProduct)"-->
</div>
<br>
</div>
</code></pre>
<h3>header.component.html</h3>
<pre><code><form class="d-flex me-5">
<input type="text" class="form-control me-2" placeholder="Search cars...">
</form>
</code></pre>
<h3>header.component.ts</h3>
<pre><code>export class HeaderComponent implements OnInit {
searchStr: string = '';
constructor() {
}
ngOnInit(): void {
}
}
</code></pre>
<h3>search.pipe.ts</h3>
<pre><code>@Pipe({
name: 'search'
})
export class SearchPipe implements PipeTransform {
transform(cars: any[], value: any) {
return cars.filter(car => {
return car.name.includes(value);
})
}
}
</code></pre>
<p>I want the input values from the header component to be passed to the car-list component so that I can find the product I need.</p>
| [
{
"answer_id": 74437141,
"author": "JNevill",
"author_id": 2221001,
"author_profile": "https://Stackoverflow.com/users/2221001",
"pm_score": 2,
"selected": true,
"text": "GROUP BY"
},
{
"answer_id": 74437561,
"author": "Zegarek",
"author_id": 5298879,
"author_profile": "https://Stackoverflow.com/users/5298879",
"pm_score": 0,
"selected": false,
"text": "from"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74436986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20468277/"
] |
74,437,020 | <p>So I have an array of cities which I map to a react-router component (so I can redirect to the home page after the data for the city that is clicked is fetched). I put the .map index (index of the item in array) as an html id. This project was originally in JS but now I'm transforming it to TS. I get an error on id={i} which says: Type 'number' is not assignable to type 'string'. I understand what I have to do, but I have no idea how to do it. Where do I need to change the type so I can pass it properly?</p>
<pre><code>const cities = city.map((town, i) => {
return <Link
className={`citiy ${props.dark ? 'dark' : ''}`}
to='/home'
onClick={handleFetch}
key={nanoid()}
id={i}>
{town}
</Link>
})
</code></pre>
| [
{
"answer_id": 74437107,
"author": "Lucasbk38",
"author_id": 20480528,
"author_profile": "https://Stackoverflow.com/users/20480528",
"pm_score": 1,
"selected": false,
"text": "const cities = city.map((town, i) => {\n return <Link \n className={`citiy ${props.dark ? 'dark' : ''}`}\n to='/home' \n onClick={handleFetch} \n key={nanoid()} \n id={`${ i }`}>\n {town}\n </Link>\n})\n"
},
{
"answer_id": 74437308,
"author": "Saurabh Nemade",
"author_id": 8778804,
"author_profile": "https://Stackoverflow.com/users/8778804",
"pm_score": 0,
"selected": false,
"text": "const cities = city.map((town, i) => {\n return <Link \n className={`citiy ${props.dark ? 'dark' : ''}`}\n to='/home' \n onClick={handleFetch} \n key={String(id)} \n id={String(i)}>\n {town}\n </Link>\n })\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19118115/"
] |
74,437,061 | <p>I want to alert on failure of any serverless dataproc job. I think that I may need to create a log based metric and then an alerting policy based on that metric.</p>
<p>I tried creating an alerting policy with the filter below:</p>
<pre><code> filter = "metric.type=\"logging.googleapis.com/log_entry_count\" resource.type=\"cloud_dataproc_batch\" metric.label.\"severity\"=\"ERROR\""
</code></pre>
<p>I was expecting an alert to trigger upon failure, but this metric does not seem to be active.</p>
| [
{
"answer_id": 74437107,
"author": "Lucasbk38",
"author_id": 20480528,
"author_profile": "https://Stackoverflow.com/users/20480528",
"pm_score": 1,
"selected": false,
"text": "const cities = city.map((town, i) => {\n return <Link \n className={`citiy ${props.dark ? 'dark' : ''}`}\n to='/home' \n onClick={handleFetch} \n key={nanoid()} \n id={`${ i }`}>\n {town}\n </Link>\n})\n"
},
{
"answer_id": 74437308,
"author": "Saurabh Nemade",
"author_id": 8778804,
"author_profile": "https://Stackoverflow.com/users/8778804",
"pm_score": 0,
"selected": false,
"text": "const cities = city.map((town, i) => {\n return <Link \n className={`citiy ${props.dark ? 'dark' : ''}`}\n to='/home' \n onClick={handleFetch} \n key={String(id)} \n id={String(i)}>\n {town}\n </Link>\n })\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19582145/"
] |
74,437,065 | <p>I have a "main" function that reads data from input data and generates an output dtoOut of a kind of Employee ID with a random name, surname, etc.</p>
<p>Example of input data</p>
<pre><code> const dtoIn = {
count: 50,
age: {
min: 19,
max: 35
}
}
</code></pre>
<p>Example of output data</p>
<pre><code>const dtoOut = [
{
gender: "male",
birthdate: "1993-08-07T00:00:00.000Z",
name: "Vratislav",
surname: "Sýkora",
workload: 40
}
</code></pre>
<p>with this code:</p>
<pre><code>// main function
function main(input_data) {
// how many employees work at the firm
let dtoIn_counter = input_data.count
// minimal age of employees
let dtoIn_min = input_data.age.min
// maximal age of employees
let dtoIn_max = input_data.age.max
//output data
const dtoOut = {}
// for loop that counts the number of employees and repeats the process for each one
for (let i = 0; i < dtoIn_counter; i++) {
// randomly decides if the employee will be male or female and assigns first and last name
const male_female = getRandomArbitrary(1, 3)
if (male_female === 1){
dtoOut.name += male_name1[getRandomArbitrary(0, male_name1.length)]
dtoOut.surname += male_name2[getRandomArbitrary(0, male_name2.length)]
dtoOut.gender += "male"
dtoOut.workload += workload[getRandomArbitrary(0, workload.length)]
}
else {
dtoOut.name += female_name1[getRandomArbitrary(0, female_name1.length)]
dtoOut.surname += female_name2[getRandomArbitrary(0, female_name2.length)]
dtoOut.gender += "female"
dtoOut.workload += workload[getRandomArbitrary(0, workload.length)]
}
}
return dtoOut
}
</code></pre>
<p>I am struggling with how to put more of these "dictionaries" in the const without overwriting the already-made dictionary. So from my understanding is that what this code does so far is overwrite the output code 50 times and I would like to fix it but not really sure how.</p>
<p>Also if anybody knew how to randomly assign a birthrate from min, max age object and put it into the ISO Date-Time format - YYYY-MM-DDTHH:MM:SSZ that would be awesome.</p>
<p>Hopefully this question wont be too broad and I was clear in what I need help with. Thanks!</p>
| [
{
"answer_id": 74437107,
"author": "Lucasbk38",
"author_id": 20480528,
"author_profile": "https://Stackoverflow.com/users/20480528",
"pm_score": 1,
"selected": false,
"text": "const cities = city.map((town, i) => {\n return <Link \n className={`citiy ${props.dark ? 'dark' : ''}`}\n to='/home' \n onClick={handleFetch} \n key={nanoid()} \n id={`${ i }`}>\n {town}\n </Link>\n})\n"
},
{
"answer_id": 74437308,
"author": "Saurabh Nemade",
"author_id": 8778804,
"author_profile": "https://Stackoverflow.com/users/8778804",
"pm_score": 0,
"selected": false,
"text": "const cities = city.map((town, i) => {\n return <Link \n className={`citiy ${props.dark ? 'dark' : ''}`}\n to='/home' \n onClick={handleFetch} \n key={String(id)} \n id={String(i)}>\n {town}\n </Link>\n })\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18225712/"
] |
74,437,128 | <p>I am trying to setup a local Beam Runner for easier testing/developing.
I'd like to allow testing python pipeline which uses kafka IO locally on my mac.
Here's my current plan for the entire framework looks like:</p>
<p><a href="https://i.stack.imgur.com/Rg1nc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Rg1nc.png" alt="enter image description here" /></a></p>
<p>Here's my current <code>docker-compose</code></p>
<pre><code>services:
zookeeper:
image: wurstmeister/zookeeper
container_name: zookeeper
ports:
- "2181:2181"
kafka:
image: wurstmeister/kafka
container_name: kafka
environment:
KAFKA_ADVERTISED_HOST_NAME: kafka
KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
ports:
- "9092:9092"
jobmanager:
image: flink_image
command: ['jobmanager']
environment:
FLINK_PROPERTIES: "jobmanager.rpc.address: jobmanager\nparallelism.default: 2"
ports:
- "8081:8081"
taskmanager:
image: flink_image
scale: 1
depends_on:
- jobmanager
command: ['taskmanager']
environment:
FLINK_PROPERTIES: "jobmanager.rpc.address: jobmanager\ntaskmanager.numberOfTaskSlots: 2\nparallelism.default: 2"
beam-jobserver:
image: flink_image
ports:
- "8097:8097"
- "8098:8098"
- "8099:8099"
entrypoint:
- java
- -cp
- /target/flink/flink-web-upload/beam-runner.jar
- org.apache.beam.runners.flink.FlinkJobServerDriver
- --flink-master=jobmanager
- --job-host=0.0.0.0
</code></pre>
<p>And my pipeline looks like this:</p>
<pre><code>LOCAL_ARGS = [
'--streaming',
'--runner=portableRunner',
'--environment_type=LOOPBACK',
'--job_endpoint=localhost:8099',
'--artifact_endpoint=localhost:8098',
'--defaultEnvironmentType=EXTERNAL',
'--defaultEnvironmentConfig=host.docker.internal:5000',
]
with beam.Pipeline(options=PipelineOptions(LOCAL_ARGS)) as pipeline:
result = (
pipeline
| "Kafka Read" >> ReadFromKafka(
consumer_config={"bootstrap.servers": "kafka:9092", 'auto.offset.reset': 'earliest'},
topics=["test.topic"],
with_metadata=False,
expansion_service=default_io_expansion_service(
append_args=[
'--defaultEnvironmentType=PROCESS',
"--defaultEnvironmentConfig={\"command\":\"/opt/apache/beam/java_boot\"}",
'--experiments=use_deprecated_read',
]
)
)
| "logging" >> beam.Map(lambda x: logging.info(f"logged: {x}"))
)
</code></pre>
<p>However, it looks like the <code>LOOPBACK</code> tried to open a port on my host machine, and ask the task manager to talk to itself via <code>localhost:<randomPort></code>. Which is not accessible inside the container.</p>
<p>Unfortunately, <code>host</code> network is not supported for Docker on Mac, and thus I need to find a way to overwrite the Loopback settings so that it connect to <code>host.docker.internal:<dedicated_pool></code> instead of a random port on my host machine? or if there are other suggested workaround? Thanks!</p>
<p>(The entire infra can be found here: <a href="https://gist.github.com/lydian/0db7614652c2ccdc733884134bf67f9b" rel="nofollow noreferrer">https://gist.github.com/lydian/0db7614652c2ccdc733884134bf67f9b</a>)</p>
| [
{
"answer_id": 74437107,
"author": "Lucasbk38",
"author_id": 20480528,
"author_profile": "https://Stackoverflow.com/users/20480528",
"pm_score": 1,
"selected": false,
"text": "const cities = city.map((town, i) => {\n return <Link \n className={`citiy ${props.dark ? 'dark' : ''}`}\n to='/home' \n onClick={handleFetch} \n key={nanoid()} \n id={`${ i }`}>\n {town}\n </Link>\n})\n"
},
{
"answer_id": 74437308,
"author": "Saurabh Nemade",
"author_id": 8778804,
"author_profile": "https://Stackoverflow.com/users/8778804",
"pm_score": 0,
"selected": false,
"text": "const cities = city.map((town, i) => {\n return <Link \n className={`citiy ${props.dark ? 'dark' : ''}`}\n to='/home' \n onClick={handleFetch} \n key={String(id)} \n id={String(i)}>\n {town}\n </Link>\n })\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19259600/"
] |
74,437,146 | <p>I´m trying to convert a local md file to json in my API, but I get syntax errors.</p>
<p>The problem seems to be that when I read the file and store it as a string variable, it gets stored without the new rows that are required by md2json to work. When I console log the variable it gets printed line by line looking just like the md file, but I cannot convert it. When I send it as a respone and print it on my page it prints:</p>
<pre><code># Air ## The second largest heading ###### The smallest heading
</code></pre>
<p>But the original md file looks like this:</p>
<pre><code># Air
## The second largest heading
###### The smallest heading
</code></pre>
<p>This is what I´ve tried:</p>
<pre><code>const md2json = require('md-2-json');
const fs = require('fs');
router.get('/page', (req, res) => {
let content = fs.readFileSync('directory/file.md','utf8')
console.log(content)
res.send(content)
})
</code></pre>
<p>Is there some way to make this work, or is there some other better way to do it?
I saw some posts about XMLHttpRequest but didn´t really get it to work.</p>
<p>//* Edit:
I now saw that I forgot to include the converting; this is what it´s supposed to look like when using md2json:</p>
<pre><code>router.get('/page', (req, res) => {
let content = fs.readFileSync('directory/file.md','utf8')
console.log(content)
let newContent = md2json.parse(content)
console.log(newContent)
res.send(newContent)
})
</code></pre>
<p>//* Edit 2:
The lack of \n doesn´t seem to be the problem, since this works:</p>
<pre><code>let mdInput = `# Air ## The second largest heading ###### The smallest heading`
router.get('/page', (req, res) => {
let newContent = md2json.parse(mdInput)
console.log(newContent)
res.send(newContent)
</code></pre>
<p>But this doesn´t:</p>
<pre><code>let mdInput = `
# Air
## The second largest heading
##### The smallest heading
`
router.get('/page', (req, res) => {
let newContent = md2json.parse(mdInput)
console.log(newContent)
res.send(newContent)
</code></pre>
| [
{
"answer_id": 74437107,
"author": "Lucasbk38",
"author_id": 20480528,
"author_profile": "https://Stackoverflow.com/users/20480528",
"pm_score": 1,
"selected": false,
"text": "const cities = city.map((town, i) => {\n return <Link \n className={`citiy ${props.dark ? 'dark' : ''}`}\n to='/home' \n onClick={handleFetch} \n key={nanoid()} \n id={`${ i }`}>\n {town}\n </Link>\n})\n"
},
{
"answer_id": 74437308,
"author": "Saurabh Nemade",
"author_id": 8778804,
"author_profile": "https://Stackoverflow.com/users/8778804",
"pm_score": 0,
"selected": false,
"text": "const cities = city.map((town, i) => {\n return <Link \n className={`citiy ${props.dark ? 'dark' : ''}`}\n to='/home' \n onClick={handleFetch} \n key={String(id)} \n id={String(i)}>\n {town}\n </Link>\n })\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437146",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20349251/"
] |
74,437,149 | <p>I'm writing a simple utility in C and I'm writing codes to print error messages in STDERR.</p>
<p>I have a struct, defined as:</p>
<pre><code>struct arguments
{
FILE *source;
int modifier_value;
int filesize;
};
</code></pre>
<hr />
<p>I have declared a pointer to the above struct, and allocated memory to it:</p>
<pre><code>struct arguments *arg = NULL;
arg = malloc(sizeof(struct arguments));
if(arg == NULL)
{
fprintf(stderr, "error: malloc - %s\n", strerror(errno)); //I know i could use perror as well, but I like the convention of using fprintf() for both stdout, stderr, and other file streams, just for symmetry
return EXIT_FAILURE;
}
</code></pre>
<p>As you can see, I have only allocated memory sufficient to store one object of type <code>struct arguments</code> and I still error checking for it.</p>
<p>The problem is I have many pointers like that which points to space of one object, and error checking all of them just increases number of codes and affects readability of code.</p>
<p>Is it a "good practice" / "is it ok" if I <strong>ignore</strong> error checking just for the reason that <strong>I'm not allocating memory too much memory</strong> (I heard something about paging and I think system combines many pages if I request for too much memory and chances of error in that case would be high, but not for memory request of something like 64 bytes).</p>
| [
{
"answer_id": 74437393,
"author": "John Bollinger",
"author_id": 2402272,
"author_profile": "https://Stackoverflow.com/users/2402272",
"pm_score": 3,
"selected": true,
"text": "malloc()"
},
{
"answer_id": 74437408,
"author": "Peter Irich",
"author_id": 20275388,
"author_profile": "https://Stackoverflow.com/users/20275388",
"pm_score": -1,
"selected": false,
"text": "void *pvc;\npvc = malloc(how_many_for_all);\n"
},
{
"answer_id": 74437680,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 1,
"selected": false,
"text": "#ifndef MY_MALLOC\n#define MY_MALLOC(size) my_malloc((size), __FUNC__, __LINE__)\n#include <stdlib.h>\n\n// Return a valid allocation or don't return.\nvoid *my_malloc(size_t size, const char *func, unsigned line);\n\n#endif\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20333834/"
] |
74,437,156 | <p>In trying to clone the flickr homepage I've become stuck trying to get the background images to transition just as they do on the <a href="https://flickr.com" rel="nofollow noreferrer">flickr homepage</a>.</p>
<p>I tried using keyframes instead of javascript and the transition-duration and animation-duration properties.</p>
<p>the following is a distillation of the problem in code.</p>
<p>html document</p>
<pre><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">
<title>flickr_test</title>
<link rel="stylesheet" href="test.css">
</head>
<body>
</body>
</html>
</code></pre>
<p>css document</p>
<pre><code>body {
background-color: rgb(61, 61, 61);
background-image: url(./test_images/computers.jpg);
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center;
background-size: cover;
animation: changePhoto 100s ease-in-out forwards infinite;
}
@keyframes changePhoto {
0% {
background-image: url(./test_images/engineer.jpg);
}
10% {
background-image: url(./test_images/lion.jpg);
}
20% {
background-image: url(./test_images/horse.jpg);
}
30% {
background-image: url(./test_images/mountains.jpg);
}
40% {
background-image: url(./test_images/forest.jpg);
}
50% {
background-image: url(./test_images/computers.jpg);
}
60% {
background-image: url(./test_images/northernLights.jpg);
}
70% {
background-image: url(./test_images/stars.jpg);
}
80% {
background-image: url(./test_images/fern.jpg);
}
90% {
background-image: url(./test_images/fish.jpg);
}
100% {
background-image: url(./test_images/meditation.jpg);
}
}
</code></pre>
| [
{
"answer_id": 74437393,
"author": "John Bollinger",
"author_id": 2402272,
"author_profile": "https://Stackoverflow.com/users/2402272",
"pm_score": 3,
"selected": true,
"text": "malloc()"
},
{
"answer_id": 74437408,
"author": "Peter Irich",
"author_id": 20275388,
"author_profile": "https://Stackoverflow.com/users/20275388",
"pm_score": -1,
"selected": false,
"text": "void *pvc;\npvc = malloc(how_many_for_all);\n"
},
{
"answer_id": 74437680,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 1,
"selected": false,
"text": "#ifndef MY_MALLOC\n#define MY_MALLOC(size) my_malloc((size), __FUNC__, __LINE__)\n#include <stdlib.h>\n\n// Return a valid allocation or don't return.\nvoid *my_malloc(size_t size, const char *func, unsigned line);\n\n#endif\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437156",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20503271/"
] |
74,437,160 | <p>I'm pushing a large repo into another on Azure DevOps Repos and I'm getting error because one repo policy only allows author with <strong>@abc.com</strong> pattern for email.</p>
<blockquote>
<p>The push was rejected because one or more commits contain author email 'user1@xyz.com' which does not match the policy-specified patterns</p>
</blockquote>
<p>When I run the git command below on my window PC I can see the precise check-in from this user1@xyz.com</p>
<pre><code>git log --name-only --author="user1@xyz.com"
</code></pre>
<p>How can I run the git log command to find all commits that are not @abc.com? is there a built in command in git?</p>
<p>My un-successful attempts so far using regex:</p>
<pre><code>git log --name-only --author='@(?!abc\.com)([^.]+\.)+com$' --perl-regexp
git log --name-only --author='^((?!*)abc\.com)$' --perl-regexp
</code></pre>
| [
{
"answer_id": 74437393,
"author": "John Bollinger",
"author_id": 2402272,
"author_profile": "https://Stackoverflow.com/users/2402272",
"pm_score": 3,
"selected": true,
"text": "malloc()"
},
{
"answer_id": 74437408,
"author": "Peter Irich",
"author_id": 20275388,
"author_profile": "https://Stackoverflow.com/users/20275388",
"pm_score": -1,
"selected": false,
"text": "void *pvc;\npvc = malloc(how_many_for_all);\n"
},
{
"answer_id": 74437680,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 1,
"selected": false,
"text": "#ifndef MY_MALLOC\n#define MY_MALLOC(size) my_malloc((size), __FUNC__, __LINE__)\n#include <stdlib.h>\n\n// Return a valid allocation or don't return.\nvoid *my_malloc(size_t size, const char *func, unsigned line);\n\n#endif\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1038554/"
] |
74,437,199 | <p><strong>TL;DR (i.e. asking the question first):</strong></p>
<p>Is there any way to write an <code>INSERT INTO...SELECT FROM...GROUP BY...ON DUPLICATE KEY UPDATE</code> statement using row alias(es) in the <code>ON DUPLICATE KEY UPDATE</code> clause instead of the <code>col1 = VALUES(col1)</code> syntax that has been deprecated and will be removed from future MySQL releases?</p>
<p>My searches of SO relating to this issue tend to all suggest using the deprecated VALUES() function, which is why I believe that my question is not a duplicate.</p>
<p><strong>BACKGROUND (i.e. more info on how to reproduce the issue)</strong></p>
<p>I have a table that comprises grouped records from another table. For simplicity in describing this issue, I've created two sample tables purely to illustrate:</p>
<p><code>items</code>:</p>
<p><a href="https://i.stack.imgur.com/ckRKA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ckRKA.png" alt="items table" /></a></p>
<p><code>item_groups</code> (below) was populated using the following SQL:</p>
<pre><code>insert into item_groups (item_type,quantity) (select item_type, count(*) from items group by item_type order by item_type)
</code></pre>
<p>It also has a unique index on <code>item_type</code>:</p>
<p><a href="https://i.stack.imgur.com/glmLH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/glmLH.png" alt="item_groups table" /></a></p>
<p>Now, let's say that I add two more items to the <code>items</code> table, one with an item_type of 4 and one with a <strong>new</strong> item_type of 5. The quantity of item_type 4 in <code>item_groups</code> should be updated to 3 and a new row inserted for the item_type of 5 with quantity of 1.</p>
<p>Using the same <code>INSERT</code> statement I used above to initially populate the <code>item_groups</code> table, I now get an error, which is expected because of a duplicate key (4 of the 5 item_types currently in the <code>items</code> table are duplicates of the item_types that currently exist in the <code>item_groups</code> table):</p>
<p><a href="https://i.stack.imgur.com/kYxY8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kYxY8.png" alt="insert error 1" /></a></p>
<p>Zero updates or inserts were completed due to this error. To remedy this, we would have <strong>historically</strong> used the <code>ON DUPLICATE KEY UPDATE</code> (occasionally abbreviated to <em>ODKU</em> below) clause like so including the <code>VALUES()</code> function:</p>
<pre><code>insert into item_groups (item_type,quantity) (select item_type, count(*) from items group by item_type order by item_type) ON DUPLICATE KEY UPDATE quantity = VALUES(quantity);
</code></pre>
<p>The above <code>INSERT...ON DUPLICATE KEY UPDATE</code> statement with <code>VALUES()</code> DOES work (<em><strong>currently</strong></em>)...</p>
<p><a href="https://i.stack.imgur.com/gVEJp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gVEJp.png" alt="item_groups after first update" /></a></p>
<p>However, I am also greeted with the following warning:</p>
<blockquote>
<p>'VALUES function' is deprecated and will be removed in a future
release. Please use an alias (INSERT INTO ... VALUES (...) AS alias)
and replace VALUES(col) in the ON DUPLICATE KEY UPDATE clause with
alias.col instead</p>
</blockquote>
<p>Now, I know how to write a simple INSERT...<em>ODKU</em> statement to be future-proof against the warning above (generically):</p>
<pre><code>INSERT INTO `my_table` (col1,col2,col3) VALUES (1,2,3) AS new ON DUPLICATE KEY UPDATE col1 = new.col1, col2 = new.col2, col3 = new.col3
</code></pre>
<p>But let's insert more items into my <code>items</code> table and then use the above syntax for my more complicated INSERT...SELECT...<em>ODKU</em> statement into <code>item_groups</code>:</p>
<pre><code>insert into item_groups (item_type,quantity) (select item_type, count(*) from items group by item_type order by item_type) AS new ON DUPLICATE KEY UPDATE quantity = new.quantity;
</code></pre>
<p>I get this error:</p>
<blockquote>
<p>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 'AS new ON DUPLICATE KEY UPDATE quantity =
new.quantity' at line 1</p>
</blockquote>
<p>Adding "VALUES" prior to my SELECT subquery, like so...</p>
<pre><code>insert into item_groups (item_type,quantity) VALUES (select item_type, count(*) from items group by item_type order by item_type) AS new ON DUPLICATE KEY UPDATE quantity = new.quantity;
</code></pre>
<p>I now get a new syntax error:</p>
<blockquote>
<p>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 'select item_type, count(*) from items group by
item_type order by item_type) AS ' at line 1</p>
</blockquote>
<p>Finally, at my wit's end, I try adding another set of parentheses around the SELECT sub-query...</p>
<pre><code>insert into item_groups (item_type,quantity) VALUES ((select item_type, count(*) from items group by item_type order by item_type)) AS new ON DUPLICATE KEY UPDATE quantity = new.quantity;
</code></pre>
<p>...and I still get an error:</p>
<blockquote>
<p>ERROR 1136 (21S01): Column count doesn't match value count at row 1</p>
</blockquote>
<p>This <em><strong>appears</strong></em> to be "progress" as I'm no longer getting syntax errors; however, I don't understand why the column count doesn't match the value count. My SELECT subquery pulls in 2 values for each row and the INSERT attempts to insert those into 2 columns for each row. So it would seem to me that 2 values -> 2 columns should not be an issue; yet it is.</p>
<p><strong>CONCLUSION</strong></p>
<p>I'm frankly not even sure what else to try, and I'm about ready to give up doing it this way and just write a simple <code>SELECT</code>, store those retrieved values in variables, and then use a simple <code>INSERT</code> to insert those values (wrapping everything in a transaction). However, if there is a way to do what I'm trying to do in one statement, I would appreciate anyone who can help me to do this.</p>
| [
{
"answer_id": 74437393,
"author": "John Bollinger",
"author_id": 2402272,
"author_profile": "https://Stackoverflow.com/users/2402272",
"pm_score": 3,
"selected": true,
"text": "malloc()"
},
{
"answer_id": 74437408,
"author": "Peter Irich",
"author_id": 20275388,
"author_profile": "https://Stackoverflow.com/users/20275388",
"pm_score": -1,
"selected": false,
"text": "void *pvc;\npvc = malloc(how_many_for_all);\n"
},
{
"answer_id": 74437680,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 1,
"selected": false,
"text": "#ifndef MY_MALLOC\n#define MY_MALLOC(size) my_malloc((size), __FUNC__, __LINE__)\n#include <stdlib.h>\n\n// Return a valid allocation or don't return.\nvoid *my_malloc(size_t size, const char *func, unsigned line);\n\n#endif\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6516263/"
] |
74,437,231 | <p>How to write the correct Makefile if I want to define generic targets of the form <code>a.ext1.new_ext</code>, <code>a.ext2.new_ext</code>, <code>b.ext1.new_ext</code>, <code>b.ext2.new_ext</code> etc. with prerequisites <code>a.ext1</code>, <code>a.ext2</code>, <code>b.ext1</code>, <code>b.ext2</code> respectively?
Kind of this but general rule:</p>
<pre><code>a.ext1.new_ext: a.ext1
compiler --input a.ext1 --output a.ext1.new_ext
a.ext2.new_ext: a.ext2
compiler --input a.ext2 --output a.ext2.new_ext
b.ext1.ext: b.ext1
compiler --input b.ext1 --output b.ext1.new_ext
b.ext2.new_ext: b.ext2
compiler --input b.ext2 --output b.ext2.new_ext
...
</code></pre>
<p>Thanks!</p>
<p>P.S. I call Makefile from root directory <code>.</code>, prerequisites are in <code>./src/folder</code> and I need the output in <code>./build/folder</code>. More precisely, my Makefile:</p>
<pre><code>SRC := $(shell find ./src -type f \( -name '*.ext1' -or -name '*.ext2' \))
OBJ := $(patsubst ./src%, ./build%, $(SRC))
OBJ := $(addsuffix .ext, $(OBJ))
# Doesn't work
%.ext: %
mkdir -p $(dir $@)
compiler --input $< --output $@
</code></pre>
| [
{
"answer_id": 74437495,
"author": "MadScientist",
"author_id": 939557,
"author_profile": "https://Stackoverflow.com/users/939557",
"pm_score": 1,
"selected": false,
"text": "%.new_ext: %\n compiler --input $< --output $@\n"
},
{
"answer_id": 74438304,
"author": "Denisof",
"author_id": 2160656,
"author_profile": "https://Stackoverflow.com/users/2160656",
"pm_score": 0,
"selected": false,
"text": "./build/%.spv : ./src/%\n mkdir -p $(dir $@)\n $(GLSL) $(GLSL_FLAGS) $< -o $@\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2160656/"
] |
74,437,245 | <p>I am trying to query the location of an object (x,y,z coordinates) with xform, and then set the values harvested from xform to use in a setAttr command to influence the translation of a different object.</p>
<pre><code>pos = cmds.xform('pSphere1', r=True, ws=True, q=True, t=True )
print(pos)
cmds.setAttr('pSphere2', tx=pos[0], ty=pos[1], tz=pos[2])
</code></pre>
<p>The print command is providing me with the correct coordinates however the setAttr command isn't picking them up and using them.</p>
<p>I'm getting the error:</p>
<p>Error: TypeError: file line 1: Invalid flag 'tx'</p>
<p>Is this something to do with the 'data type' of the <strong>xform</strong> being "linear" and the <strong>setAttr</strong> being something else? If so, how do I work around or convert?</p>
| [
{
"answer_id": 74437495,
"author": "MadScientist",
"author_id": 939557,
"author_profile": "https://Stackoverflow.com/users/939557",
"pm_score": 1,
"selected": false,
"text": "%.new_ext: %\n compiler --input $< --output $@\n"
},
{
"answer_id": 74438304,
"author": "Denisof",
"author_id": 2160656,
"author_profile": "https://Stackoverflow.com/users/2160656",
"pm_score": 0,
"selected": false,
"text": "./build/%.spv : ./src/%\n mkdir -p $(dir $@)\n $(GLSL) $(GLSL_FLAGS) $< -o $@\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20454312/"
] |
74,437,249 | <p>I am trying to convert a performance critical part of a Java code to a C++ code.</p>
<p>In Java I work with lists containing a small sample of the original list. When I add objects of the first list to the second list actually only a reference to the object is stored, so I do not copy the object. This is what I would like to achieve in C++ also. Unfortunately I have not found a way to do so as the push_back method seems to create a deep copy instead.</p>
<p>Java code:</p>
<pre><code>class Data {
Data(int id){
this.id = id;
this.name = "Name " + id;
}
public int id;
public String name = "";
public boolean isFancy = false;
}
public class Main {
public static void main(String[] args) {
List<Data> dataList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Data data = new Data(i);
dataList.add(data);
}
List<Data> dataSublist = new ArrayList<>();
dataSublist.add(dataList.get(2));
dataSublist.add(dataList.get(3));
dataSublist.add(dataList.get(8));
dataSublist.forEach(data -> data.isFancy = true); // change isFancy in subList to alter the original object
System.out.println("Data 3 original isFancy = " + dataList.get(3).isFancy); // is true
}
}
</code></pre>
<p>C++ code:</p>
<pre><code>class Data {
public:
Data(int id) { id_ = id; };
int id_ = 0;
std::string name_ = "";
bool isFancy_ = false;
};
int main()
{
std::vector<Data> dataList;
for (int i = 0; i < 10; i++) {
Data data = Data(i);
dataList.push_back(data);
}
std::vector<Data> dataSublist;
dataSublist.push_back(dataList[2]);
dataSublist.push_back(dataList[3]);
dataSublist.push_back(dataList[8]);
for (int i = 0; i < dataSublist.size(); i++) {
dataSublist[i].isFancy_ = true; // change isFancy in subList to alter the original object
}
std::cout << "Data 3 original isFancy = " << ((dataList[3].isFancy_) ? "true" : "false"); // is false
}
</code></pre>
<p>How to I get the output to "true" here?</p>
| [
{
"answer_id": 74437495,
"author": "MadScientist",
"author_id": 939557,
"author_profile": "https://Stackoverflow.com/users/939557",
"pm_score": 1,
"selected": false,
"text": "%.new_ext: %\n compiler --input $< --output $@\n"
},
{
"answer_id": 74438304,
"author": "Denisof",
"author_id": 2160656,
"author_profile": "https://Stackoverflow.com/users/2160656",
"pm_score": 0,
"selected": false,
"text": "./build/%.spv : ./src/%\n mkdir -p $(dir $@)\n $(GLSL) $(GLSL_FLAGS) $< -o $@\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1854563/"
] |
74,437,266 | <p>I am trying to do commands to discord.py in other file but when i try to setup them i get error
'Client' object has no attribute 'add_cog'
My main.py file:</p>
<pre><code>import discord
import music
from discord.ext import commands
client = commands.Bot(command_prefix="!", intents=discord.Intents.all())
token = ""
cogs = [music]
@client.event
async def on_ready():
await client.load_extension(cogs.commands)
print(f"Logged in as {client.user})")
client.run(token)
</code></pre>
<p>music.py file:</p>
<pre><code>import discord
from discord.ext import commands
import youtube_dl
class music(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
async def join(self, ctx):
if ctx.author.voice is None:
await ctx.send("First join to voice channel")
voicechannel = ctx.author.voice.channel
if ctx.voicechannel is None:
await voicechannel.join()
else:
await voicechannel.move_to(ctx.voicechannel)
@commands.command()
async def disconnect(self, ctx):
await ctx.voice_client.disconnect()
@commands.command()
async def play(self,ctx,url):
ctx.voice_client.stop()
FFMPEG_OPTIONS = {'before options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn' }
YDL_OPTIONS = {'format':"bestaudio"}
vc = ctx.voice_client
with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
info = ydl.extract_info(url, download=False)
url2 = info['formats'][0]['url']
source = await discord.FFmpegOpusAudio.from_probe(url2,
**FFMPEG_OPTIONS)
vc.play(source)
@commands.command()
async def resume(self, ctx):
await ctx.voice_client.resume()
await ctx.send("resumed")
@commands.command()
async def pause(self, ctx):
await ctx.voice_client.pause()
await ctx.send("paused")
async def setup(client):
await client.add_cog(music(client))
</code></pre>
<p>I pasted everything from my file</p>
<p>The error:
AttributeError: 'Client' object has no attribute 'load_extension'
I tried to use help from similar thread but it wasnt working</p>
| [
{
"answer_id": 74437495,
"author": "MadScientist",
"author_id": 939557,
"author_profile": "https://Stackoverflow.com/users/939557",
"pm_score": 1,
"selected": false,
"text": "%.new_ext: %\n compiler --input $< --output $@\n"
},
{
"answer_id": 74438304,
"author": "Denisof",
"author_id": 2160656,
"author_profile": "https://Stackoverflow.com/users/2160656",
"pm_score": 0,
"selected": false,
"text": "./build/%.spv : ./src/%\n mkdir -p $(dir $@)\n $(GLSL) $(GLSL_FLAGS) $< -o $@\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20202578/"
] |
74,437,274 | <p>I'm trying to use mat-chip in a component. My code used to work before I upgraded to Angular 15</p>
<p>I am importing the module, which seems to be a common mistake</p>
<p>I think I've included everything according to the docs.</p>
<p>Assistance much appreciated. Thanks</p>
<p>The error is:</p>
<pre><code>Error: src/app/app.component.html:1:1 - error NG8001: 'mat-chip-list' is not a known element:
1. If 'mat-chip-list' is an Angular component, then verify that it is part of this module.
2. If 'mat-chip-list' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
1 <mat-chip-list>
~~~~~~~~~~~~~~~
src/app/app.component.ts:5:16
5 templateUrl: './app.component.html',
~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component AppComponent.
</code></pre>
<p>The version info is:</p>
<pre><code>Angular CLI: 15.0.0-rc.3
Node: 16.14.0
Package Manager: npm 9.1.1
OS: linux x64
Angular: 15.0.0-rc.3
... animations, cli, common, compiler, compiler-cli, core, forms
... platform-browser, platform-browser-dynamic, router
Package Version
---------------------------------------------------------
@angular-devkit/architect 0.1500.0-rc.3
@angular-devkit/build-angular 15.0.0-rc.3
@angular-devkit/core 15.0.0-rc.3
@angular-devkit/schematics 15.0.0-rc.3
@angular/cdk 15.0.0-rc.2
@angular/material 15.0.0-rc.2
@schematics/angular 15.0.0-rc.3
rxjs 7.5.7
typescript
</code></pre>
<pre><code> 4.8.4
</code></pre>
<p>My app.modules.ts:</p>
<pre><code>import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { MatChipsModule } from '@angular/material/chips';
@NgModule({
declarations: [
AppComponent
],
imports: [
MatChipsModule
],
exports: [
],
providers: [
],
bootstrap: [AppComponent],
entryComponents: [
]
})
export class AppModule` { }
</code></pre>
<p>and my component:</p>
<pre><code>`<mat-chip-list>
<mat-chip>
Dog one
</mat-chip>
<mat-chip color="primary">
Dog two
</mat-chip>
<mat-chip color="accent">
Dog three
</mat-chip>
</mat-chip-list>`
</code></pre>
<p>and component.ts:</p>
<pre><code> import { Component } from '@angular/core';
@Component({
selector: 'chips-example',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent
{
}
</code></pre>
| [
{
"answer_id": 74460264,
"author": "JSON Derulo",
"author_id": 5470544,
"author_profile": "https://Stackoverflow.com/users/5470544",
"pm_score": 2,
"selected": false,
"text": "<mat-chip-list>"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7462902/"
] |
74,437,275 | <p>When I run the application and search I got this error</p>
<blockquote>
<p>System.InvalidCastException - column contains NULL data</p>
<p>at Oracle.ManagedDataAccess.Client.OracleDataReader.GetDecimal</p>
</blockquote>
<p>This is my code DB repository code :</p>
<pre><code>public List<LabResult> Search(string term)
{
return db.LabResults
.Where(a => a.PatientNo.ToString() == term)
.ToList(); // error on this line
}
</code></pre>
<p>This is the view markup:</p>
<pre><code>@model IEnumerable<OracleHIS.Models.LabResult>
@{
ViewData["Title"] = "Index";
}
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.PatientNo)
</th>
<th>
@Html.DisplayNameFor(model => model.LabOrderNo)
</th>
<th>
@Html.DisplayNameFor(model => model.PatientNameE)
</th>
<th>
@Html.DisplayNameFor(model => model.LongForiegnDesc)
</th>
<th>
@Html.DisplayNameFor(model => model.ServNumResult)
</th>
</tr>
</thead>
<tbody>
@if (Model != null)
{
foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.PatientNo)
</td>
<td>
@Html.DisplayFor(modelItem => item.LabOrderNo)
</td>
<td>
@Html.DisplayFor(modelItem => item.PatientNameE)
</td>
<td>
@Html.DisplayFor(modelItem => item.LongForeignDesc)
</td>
<td>
@Html.DisplayFor(modelItem => item.ServNumResult)
</td>
<td>
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
</td>
</tr>
}
}
</tbody>
</table>
</code></pre>
<p>And this is the model class:</p>
<pre><code>namespace OracleHIS.Models
{
public partial class LabResult
{
public decimal PatientNo { get; set; }
public decimal LabOrderNo { get; set; }
public string PatientNameE { get; set; } = null!;
public string LongForiegnDesc { get; set; } = null!;
public decimal ServNumResult { get; set; }
}
}
</code></pre>
<p>I found this solution</p>
<pre><code>https://stackoverflow.com/questions/26024722/handle-null-values-when-reading-through-oracledatareader
</code></pre>
<p>but where I will use the <code>IsDBNull()</code> in my code?</p>
<p><code>OracleDataReader</code> provides a <code>IsDBNull()</code> method.</p>
<p>this is the Model in DBset context its a VIEW not TABLE include columns from multiple tables :</p>
<pre><code>protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("TRNGKAASH")
.UseCollation("USING_NLS_COMP");
modelBuilder.Entity<LabResult>(entity =>
{
entity.HasNoKey();
entity.ToView("LAB_RESULTS");
entity.Property(e => e.AbnormalFlag)
.HasColumnType("NUMBER")
.HasColumnName("ABNORMAL_FLAG");
entity.Property(e => e.ApprovingDateG)
.HasColumnType("DATE")
.HasColumnName("APPROVING_DATE_G");
entity.Property(e => e.CancelBy)
.HasMaxLength(8)
.IsUnicode(false)
.HasColumnName("CANCEL_BY");
entity.Property(e => e.CancelDateG)
.HasColumnType("DATE")
.HasColumnName("CANCEL_DATE_G");
entity.Property(e => e.CancelDateH)
.HasMaxLength(8)
.IsUnicode(false)
.HasColumnName("CANCEL_DATE_H");
entity.Property(e => e.CancelReason)
.HasPrecision(6)
.HasColumnName("CANCEL_REASON");
entity.Property(e => e.DateOfBirth)
.HasPrecision(8)
.HasColumnName("DATE_OF_BIRTH");
entity.Property(e => e.EndResult)
.HasPrecision(6)
.HasColumnName("END_RESULT");
entity.Property(e => e.EventNo)
.HasPrecision(4)
.HasColumnName("EVENT_NO");
entity.Property(e => e.GramStain)
.HasMaxLength(3000)
.IsUnicode(false)
.HasColumnName("GRAM_STAIN");
entity.Property(e => e.GroupNo)
.HasPrecision(6)
.HasColumnName("GROUP_NO");
entity.Property(e => e.HeparinFlag)
.HasPrecision(1)
.HasColumnName("HEPARIN_FLAG");
entity.Property(e => e.HospitalNo)
.HasMaxLength(10)
.IsUnicode(false)
.HasColumnName("HOSPITAL_NO");
entity.Property(e => e.InitDiagnisis)
.HasMaxLength(300)
.IsUnicode(false)
.HasColumnName("INIT_DIAGNISIS");
entity.Property(e => e.LabNo)
.HasPrecision(6)
.HasColumnName("LAB_NO");
entity.Property(e => e.LabOrderNo)
.HasPrecision(12)
.HasColumnName("LAB_ORDER_NO");
entity.Property(e => e.LastUpdateDate)
.HasColumnType("DATE")
.HasColumnName("LAST_UPDATE_DATE");
entity.Property(e => e.LastUpdateTransaction)
.HasMaxLength(1)
.IsUnicode(false)
.HasColumnName("LAST_UPDATE_TRANSACTION");
entity.Property(e => e.LastUpdateUser)
.HasMaxLength(8)
.IsUnicode(false)
.HasColumnName("LAST_UPDATE_USER");
entity.Property(e => e.LongForiegnDesc)
.HasMaxLength(40)
.IsUnicode(false)
.HasColumnName("LONG_FORIEGN_DESC");
entity.Property(e => e.MachineId)
.HasColumnType("NUMBER")
.HasColumnName("MACHINE_ID");
entity.Property(e => e.MedicalCheck)
.HasPrecision(1)
.HasColumnName("MEDICAL_CHECK");
entity.Property(e => e.MrMerge)
.HasPrecision(12)
.HasColumnName("MR_MERGE");
entity.Property(e => e.Nationality)
.HasPrecision(6)
.HasColumnName("NATIONALITY");
entity.Property(e => e.PanicFlag)
.HasColumnType("NUMBER")
.HasColumnName("PANIC_FLAG");
entity.Property(e => e.PatientCategory)
.HasPrecision(6)
.HasColumnName("PATIENT_CATEGORY");
entity.Property(e => e.PatientHospital)
.HasMaxLength(10)
.IsUnicode(false)
.HasColumnName("PATIENT_HOSPITAL");
entity.Property(e => e.PatientNameA)
.HasMaxLength(150)
.IsUnicode(false)
.HasColumnName("PATIENT_NAME_A");
entity.Property(e => e.PatientNameE)
.HasMaxLength(150)
.IsUnicode(false)
.HasColumnName("PATIENT_NAME_E");
entity.Property(e => e.PatientNo)
.HasPrecision(12)
.HasColumnName("PATIENT_NO");
entity.Property(e => e.PatientSourceInd)
.HasPrecision(6)
.HasColumnName("PATIENT_SOURCE_IND");
entity.Property(e => e.PrioFlag)
.HasPrecision(6)
.HasColumnName("PRIO_FLAG");
entity.Property(e => e.ProvidingResource)
.HasPrecision(6)
.HasColumnName("PROVIDING_RESOURCE");
entity.Property(e => e.Reason)
.HasMaxLength(300)
.IsUnicode(false)
.HasColumnName("REASON");
entity.Property(e => e.RefSourceNo)
.HasMaxLength(10)
.IsUnicode(false)
.HasColumnName("REF_SOURCE_NO");
entity.Property(e => e.RefType)
.HasPrecision(6)
.HasColumnName("REF_TYPE");
entity.Property(e => e.ResultNotes)
.IsUnicode(false)
.HasColumnName("RESULT_NOTES");
entity.Property(e => e.SampleCollectedBy)
.HasPrecision(5)
.HasColumnName("SAMPLE_COLLECTED_BY");
entity.Property(e => e.SampleCollectedDateG)
.HasColumnType("DATE")
.HasColumnName("SAMPLE_COLLECTED_DATE_G");
entity.Property(e => e.SampleCollectedDateH)
.HasMaxLength(8)
.IsUnicode(false)
.HasColumnName("SAMPLE_COLLECTED_DATE_H");
entity.Property(e => e.SampleNo)
.HasPrecision(12)
.HasColumnName("SAMPLE_NO");
entity.Property(e => e.SampleNote)
.HasMaxLength(300)
.IsUnicode(false)
.HasColumnName("SAMPLE_NOTE");
entity.Property(e => e.SampleReceivedDateG)
.HasColumnType("DATE")
.HasColumnName("SAMPLE_RECEIVED_DATE_G");
entity.Property(e => e.SampleReceivedDateH)
.HasMaxLength(8)
.IsUnicode(false)
.HasColumnName("SAMPLE_RECEIVED_DATE_H");
entity.Property(e => e.SampleRecievedBy)
.HasMaxLength(8)
.IsUnicode(false)
.HasColumnName("SAMPLE_RECIEVED_BY");
entity.Property(e => e.SampleType)
.HasPrecision(6)
.HasColumnName("SAMPLE_TYPE");
entity.Property(e => e.ServCancelBy)
.HasMaxLength(8)
.IsUnicode(false)
.HasColumnName("SERV_CANCEL_BY");
entity.Property(e => e.ServCancelDateG)
.HasColumnType("DATE")
.HasColumnName("SERV_CANCEL_DATE_G");
entity.Property(e => e.ServCancelDateH)
.HasMaxLength(8)
.IsUnicode(false)
.HasColumnName("SERV_CANCEL_DATE_H");
entity.Property(e => e.ServCancelReason)
.HasColumnType("NUMBER")
.HasColumnName("SERV_CANCEL_REASON");
entity.Property(e => e.ServNo)
.HasPrecision(6)
.HasColumnName("SERV_NO");
entity.Property(e => e.ServNumResult)
.HasColumnType("NUMBER")
.HasColumnName("SERV_NUM_RESULT");
entity.Property(e => e.ServRequestDateG)
.HasColumnType("DATE")
.HasColumnName("SERV_REQUEST_DATE_G");
entity.Property(e => e.ServRequestDateH)
.HasMaxLength(8)
.IsUnicode(false)
.HasColumnName("SERV_REQUEST_DATE_H");
entity.Property(e => e.ServRequestDoctorName)
.HasMaxLength(150)
.IsUnicode(false)
.HasColumnName("SERV_REQUEST_DOCTOR_NAME");
entity.Property(e => e.ServRequestDoctorNo)
.HasPrecision(5)
.HasColumnName("SERV_REQUEST_DOCTOR_NO");
entity.Property(e => e.ServRequestUserId)
.HasMaxLength(8)
.IsUnicode(false)
.HasColumnName("SERV_REQUEST_USER_ID");
entity.Property(e => e.ServTextResult)
.HasMaxLength(500)
.IsUnicode(false)
.HasColumnName("SERV_TEXT_RESULT");
entity.Property(e => e.ServType)
.HasPrecision(6)
.HasColumnName("SERV_TYPE");
entity.Property(e => e.Sex)
.HasPrecision(1)
.HasColumnName("SEX");
entity.Property(e => e.SpecialCase)
.HasPrecision(6)
.HasColumnName("SPECIAL_CASE");
});
</code></pre>
<p>And this is the VIEW declaration in SQL :</p>
<p><a href="https://i.stack.imgur.com/qd3zq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qd3zq.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/I8Pkf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/I8Pkf.png" alt="enter image description here" /></a></p>
<p>I opened view error details and this is the details :</p>
<pre><code> at Oracle.ManagedDataAccess.Client.OracleDataReader.GetInt32(Int32 i)
at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at OracleHIS.Models.Repository.LabDbRepository.Search(String term) in D:\HIS\OracleHIS\OracleHIS\Models\Repository\LabDbRepository.cs:line 59
at OracleHIS.Controllers.LabController.Search(String term) in D:\HIS\OracleHIS\OracleHIS\Controllers\LabController.cs:line 59
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
</code></pre>
| [
{
"answer_id": 74437998,
"author": "Mohm Zanaty",
"author_id": 1609232,
"author_profile": "https://Stackoverflow.com/users/1609232",
"pm_score": 1,
"selected": false,
"text": "public decimal? PatientNo { get; set; }\n"
},
{
"answer_id": 74441472,
"author": "Tarik",
"author_id": 990750,
"author_profile": "https://Stackoverflow.com/users/990750",
"pm_score": 0,
"selected": false,
"text": "Select * from labresults where PatientNo is null or LabOrderNo is null or ServNumResult is null\n"
},
{
"answer_id": 74441572,
"author": "Guru Stron",
"author_id": 2501279,
"author_profile": "https://Stackoverflow.com/users/2501279",
"pm_score": 3,
"selected": true,
"text": "null"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14008146/"
] |
74,437,284 | <p>I have a Pandas data frame, <code>attack_probability_df</code>:</p>
<pre><code> city date attack probability
0 Rome 1996-02-23 0.163317
1 Rome 1996-02-24 0.219221
2 Rome 1996-02-25 0.180625
3 Rome 1996-02-26 0.149749
4 Rome 1996-02-27 0.121288
</code></pre>
<p>I use <code>attack_probability_df.loc[attack_probability_df.date == date].loc[attack_probability_df.city == city]["attack probability"]</code> to extract <code>attack probability</code> by needed date and city, but my code returns this:</p>
<pre><code>2345 0.18593
Name: attack probability, dtype: float64
</code></pre>
<p>instead of numeric value. How can I extract the value itself?</p>
| [
{
"answer_id": 74437377,
"author": "cmauck10",
"author_id": 19935366,
"author_profile": "https://Stackoverflow.com/users/19935366",
"pm_score": 3,
"selected": true,
"text": ".values[0]"
},
{
"answer_id": 74437562,
"author": "medium-dimensional",
"author_id": 7789963,
"author_profile": "https://Stackoverflow.com/users/7789963",
"pm_score": 0,
"selected": false,
"text": "attack_probability"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19547474/"
] |
74,437,288 | <p>I am new in flutter I want to know how can i concatenate the list of strings into a single string.
I tried to do phrase.toString(). i have also tried</p>
<p>But I am not getting the required result. How can I get the concatenation of only tags of the list? Any help will be appreciated.</p>
<pre><code>List phrase = [
{
'tag': 'This is a flutter',
},
{
'tag': 'learning session',
'icon': icon.flutter,
},
{
'tag': 'Therefore,',
'icon': icon.learningHat,
},
{
'tag': 'Login here',
},
];
</code></pre>
<p>I am expecting the out should be: This is a flutter learning session. Therefore login here.</p>
<p>I have tried:</p>
<pre><code>final phraseTags = phrase[index]['tags'];
</code></pre>
<p>but not getting the required result</p>
| [
{
"answer_id": 74437377,
"author": "cmauck10",
"author_id": 19935366,
"author_profile": "https://Stackoverflow.com/users/19935366",
"pm_score": 3,
"selected": true,
"text": ".values[0]"
},
{
"answer_id": 74437562,
"author": "medium-dimensional",
"author_id": 7789963,
"author_profile": "https://Stackoverflow.com/users/7789963",
"pm_score": 0,
"selected": false,
"text": "attack_probability"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20503995/"
] |
74,437,296 | <p>I'm building an app with flutter and I have a question about <a href="https://pub.dev/packages/provider" rel="nofollow noreferrer"><code>Provider.of</code></a>. In my <code>Widget</code> I call this :</p>
<pre class="lang-dart prettyprint-override"><code>Provider.of<Auth>(context, listen: false).signup(emailController.text, passwordController.text);
</code></pre>
<p>And I would like to navigate with <code>Navigator</code> according to the return of my <code>signup</code> function.
I tried multiple other ways but couldn't make it work.</p>
<p>Naively I tried this:</p>
<pre class="lang-dart prettyprint-override"><code>onPressed: () {
var result = Provider.of<Auth>(context, listen: false)
.signup(emailController.text,
passwordController.text);
if (result == "failed") {
Navigator.of(context).push(MaterialPageRoute(
builder: (ctx) => SuccessfulScreen()));
} else {
Navigator.of(context).push(MaterialPageRoute(
builder: (ctx) => UnsuccessfulScreen()));
}
},
</code></pre>
<p>But I got this type for the var <code>result</code>: <code>Future<String></code></p>
<p>Here is my tree of my project:</p>
<pre><code>lib/
├── firebase_options.dart
├── images
├── main.dart
├── model
│ └── apis
│ └── auth.dart
└── view
└── screens
├── login_screen.dart
├── signup_screen.dart
├── successful_screen.dart
└── welcome_screen.dart
</code></pre>
<p>And the <code>auth.dart</code> contains this :</p>
<pre><code>import 'package:flutter/foundation.dart';
import 'package:firebase_auth/firebase_auth.dart';
class Auth with ChangeNotifier {
Future<String> signup(String email, String password) async {
try {
await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: email,
password: password,
);
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
return e.code;
} else if (e.code == 'email-already-in-use') {
return e.code;
}
} catch (e) {
return e.toString();
}
return "succes";
}
Future<void> login(String email, String password) async {
try {
await FirebaseAuth.instance
.signInWithEmailAndPassword(email: email, password: password);
} on FirebaseAuthException catch (e) {
if (e.code == 'user-not-found') {
print('No user found for that email.');
} else if (e.code == 'wrong-password') {
print('Wrong password provided for that user.');
}
}
}
}
</code></pre>
<p>I could make this logic directly in my build function (<code>login_screen.dart</code>) but I found that not easy to maintain. So I make it difficult for me but my guess is that I'm missing something, could someone help me on this ?</p>
| [
{
"answer_id": 74437377,
"author": "cmauck10",
"author_id": 19935366,
"author_profile": "https://Stackoverflow.com/users/19935366",
"pm_score": 3,
"selected": true,
"text": ".values[0]"
},
{
"answer_id": 74437562,
"author": "medium-dimensional",
"author_id": 7789963,
"author_profile": "https://Stackoverflow.com/users/7789963",
"pm_score": 0,
"selected": false,
"text": "attack_probability"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13947830/"
] |
74,437,303 | <p>I have a list of 50k+ URL's, and am looking for the most common 3/4/5/6 letters in these URLs (barring .com/.org/etc).</p>
<p>So if the URLs are <code>strings.com</code> and <code>string2.com</code>, it would tell me that <code>string</code> is the most common sequence of letters.</p>
<p>Is there a way to do this?</p>
<p>I tried <code>=INDEX(range, MODE(MATCH(range, range, 0 )))</code>, but it didn't work.</p>
| [
{
"answer_id": 74438452,
"author": "JvdV",
"author_id": 9758194,
"author_profile": "https://Stackoverflow.com/users/9758194",
"pm_score": 2,
"selected": false,
"text": "C2"
},
{
"answer_id": 74438702,
"author": "David Leal",
"author_id": 6237093,
"author_profile": "https://Stackoverflow.com/users/6237093",
"pm_score": 2,
"selected": true,
"text": "A"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20504067/"
] |
74,437,311 | <p>I have the following text file and I need to calculate average of sold units.</p>
<pre><code>"Time";"unit"
"2022-09-23 12:00:00";8.10
"2022-07-19 14:00:00";8.11
"2022-09-21 14:00:00";7.88
"2022-08-11 07:00:00";7.42
"2022-07-07 00:00:00";7.81
"2022-01-06 01:00:00";8.38
"2022-02-11 02:00:00";9.96
"2022-03-12 07:00:00";10.94
</code></pre>
<p><strong>Code to analyze length of file.</strong></p>
<pre><code>file = open ("data.txt",'r', encoding = "utf-8")
row = file.readline()
rows = file.readlines()
length = len(rows)
file.close()
</code></pre>
<p>Code for total, which I want to divide with lenght.</p>
<pre><code>total = 0
file = open ("data.txt",'r', encoding = "utf-8")
row = file.readline()
while (len(row) > 0):
x = int(row[22])
total = total + x
row = file.readline()
tiedosto.close ()
</code></pre>
<p>Unfortunately, I got following error message with the current code.</p>
<blockquote>
<p>ValueError: invalid literal for int() with base 10: ''</p>
</blockquote>
<p>I assume that error relates to date as it is inside the strings. What could be the fix for the current code or is there easier way?</p>
| [
{
"answer_id": 74437391,
"author": "Cobra",
"author_id": 17580381,
"author_profile": "https://Stackoverflow.com/users/17580381",
"pm_score": 2,
"selected": false,
"text": "with open('data.txt', newline='', encoding='utf-8') as file:\n lines = file.readlines()\n if (count := len(lines) - 1) > 0:\n total = 0.0\n for line in lines[1:]:\n _, v = line.split(';')\n total += float(v)\n print(f'{total/count:.2f}')\n"
},
{
"answer_id": 74437474,
"author": "Ali Muhammad",
"author_id": 11351501,
"author_profile": "https://Stackoverflow.com/users/11351501",
"pm_score": 1,
"selected": true,
"text": "with open('data.txt') as f:\n lines = f.readlines()\n lines = [line.strip() for line in lines]\n lines = [line.split(';') for line in lines]\n lines = [line[1] for line in lines[1:]]\n lines = [float(line) for line in lines]\n print(sum(lines)/len(lines))\n"
},
{
"answer_id": 74437807,
"author": "0x0fba",
"author_id": 20339407,
"author_profile": "https://Stackoverflow.com/users/20339407",
"pm_score": 0,
"selected": false,
"text": "rsplit(\";\", 1)"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20503939/"
] |
74,437,324 | <p>I am trying to determine the distance from the top of the page in JavaScript, and I am faced with a Problem that the return command won't update the new distance.</p>
<p>I tried to get the distance like this:</p>
<pre><code>document.addEventListener('wheel', getDistance);
function getDistance() {
var scrollTop = $(window).scrollTop(),
elementOffset = $('#distance-check').offset().top,
distance = (elementOffset - scrollTop);
return distance;
}
var distance = getDistance();
</code></pre>
<p>But for some reason it will get only the initial distance value and wont update.</p>
<p>Thanks in advance.</p>
| [
{
"answer_id": 74437422,
"author": "Lucasbk38",
"author_id": 20480528,
"author_profile": "https://Stackoverflow.com/users/20480528",
"pm_score": 1,
"selected": false,
"text": "function getDistance() {\n const scrollTop = $(window).scrollTop(),\n elementOffset = $('#distance-check').offset().top,\n distance = (elementOffset - scrollTop);\n \n return distance;\n}\n\nlet distance = getDistance();\n\n// This is the important part\ndocument.addEventListener('wheel', () => distance = getDistance());\n"
},
{
"answer_id": 74437448,
"author": "Lochard",
"author_id": 19642181,
"author_profile": "https://Stackoverflow.com/users/19642181",
"pm_score": 1,
"selected": true,
"text": "\nlet distance;\n\ndocument.addEventListener('wheel', getDistance);\n\nfunction getDistance() {\n var scrollTop = $(window).scrollTop(),\n elementOffset = $('#distance-check').offset().top;\n\n distance = (elementOffset - scrollTop);\n}\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20361409/"
] |
74,437,349 | <p>Let's assume that my Angular 14 app has a <code>FireService</code> that will fetch the latest information for an object when the application loads. A page on the application must wait for the <a href="https://rxjs.dev/guide/observable" rel="nofollow noreferrer">Observable</a> on the <code>FireService</code> to be ready before it can do whatever it needs to. This is what I'm currently doing, and I'm sure is wrong:</p>
<h4>fire.service.ts</h4>
<pre><code>export class FireService {
public thingA$ = new BehaviorSubject<ThingA | undefined>(undefined);
}
</code></pre>
<h4>page.component.ts</h4>
<pre><code>this.FireService.thingA$.subscribe((a: ThingA | undefined) {
if (a) {
this.thingB$.subscribe((b: ThingB) => doThingWithB(b));
}
});
</code></pre>
<p>Would I use a <a href="https://rxjs.dev/api/index/function/skipWhile" rel="nofollow noreferrer">skipWhile</a> like this?</p>
<pre><code>this.FireService.thingA$.pipe(skipWhile((a: ThingA | undefined) => !a)).subscribe((a: ThingA) {
if (a) {
this.thingB$.subscribe((b: ThingB) => doThingWithB(b));
}
});
</code></pre>
<p>Wouldn't this also be a <em>nested subscription</em>?</p>
| [
{
"answer_id": 74437575,
"author": "Ali Adravi",
"author_id": 586227,
"author_profile": "https://Stackoverflow.com/users/586227",
"pm_score": 0,
"selected": false,
"text": "forkJoin(\n this.FireService.thingA$(),\n this.FireService.thingB$()\n).subscribe(\n ([thisngA, thingB]) => {\n // do your things\n },\n (error) => console.error(error)\n)\n"
},
{
"answer_id": 74438350,
"author": "Francisco Santorelli",
"author_id": 10121165,
"author_profile": "https://Stackoverflow.com/users/10121165",
"pm_score": 3,
"selected": true,
"text": "filter"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3893519/"
] |
74,437,405 | <p>I have two strings for url and I am building a regexp to take out the domain, project and repo from url.</p>
<p>The urls looks like this:</p>
<pre><code>1. https://bitbucket.org/test/test-x.git
2. ssh://git@bitbucket.org/test/test-x
</code></pre>
<p>I have this regexp working:</p>
<pre><code>r"(?:ssh|https):\/\/(?:(?:git@|)bitbucket.org)\/([^/]*)\/([^/]*)"
</code></pre>
<p>I am able to get <code>project</code> and <code>slug</code> group. Now, I also want to strip <code>.git</code> in regexp if it;s present in <code>slug</code> group, I tried with adding a non capturing group <code>(?:.git|)</code>, but no success.</p>
<p>How to omit <code>.git</code> with regexp if it is present in the string, what I am missing here?</p>
| [
{
"answer_id": 74437575,
"author": "Ali Adravi",
"author_id": 586227,
"author_profile": "https://Stackoverflow.com/users/586227",
"pm_score": 0,
"selected": false,
"text": "forkJoin(\n this.FireService.thingA$(),\n this.FireService.thingB$()\n).subscribe(\n ([thisngA, thingB]) => {\n // do your things\n },\n (error) => console.error(error)\n)\n"
},
{
"answer_id": 74438350,
"author": "Francisco Santorelli",
"author_id": 10121165,
"author_profile": "https://Stackoverflow.com/users/10121165",
"pm_score": 3,
"selected": true,
"text": "filter"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7994074/"
] |
74,437,459 | <p>I am making a Hangman game for practice. The game is set so that the computer randomly chooses a word from a list I have provided and returns the word in list form. A function then compares user input with the list and checks if user_input in list. If True, then it removes the input from the word to prevent the user to pass the same input more than once. That is where the error arises.</p>
<p>I know the letter is still in the list, so I can't understand why it says it's not. Here is the code:</p>
<pre><code>import random
words = ["share","last","computer"]
def choose_word():
choice = random.choice(words)
return list(choice)
choice = choose_word()
original_word = choose_word()
choice == original_word
def get_input():
return input("Choose a letter: ")
def check_input(user_input,choice):
if user_input in choice:
print("Correct.")
else:
print("Wrong.")
return False
def list_to_string(l):
string = ""
return string.join(l)
tries = 0
while tries <= 6:
choose_word()
print(original_word) # This is for testing purposes.
user_input = get_input() # To ensure the computer doesn't call a new random value.
check = check_input(user_input,original_word)
if check == False:
tries += 1
else:
choice.remove(user_input) # To prevent the user from inputing the same value twice.
if len(choice) == 0:
print(f"You got it! The word is \'{list_to_string(original_word)}.\'")
break
if tries == 6:
print(f"Sorry, you are out of tries. The word was \'{list_to_string(original_word)}\'.")
</code></pre>
| [
{
"answer_id": 74437577,
"author": "Jean-Claude Arbaut",
"author_id": 13963867,
"author_profile": "https://Stackoverflow.com/users/13963867",
"pm_score": 1,
"selected": false,
"text": "choose_word()"
},
{
"answer_id": 74437687,
"author": "OneMadGypsy",
"author_id": 10292330,
"author_profile": "https://Stackoverflow.com/users/10292330",
"pm_score": 1,
"selected": false,
"text": "import random\n\n#game data\nwords = [\"share\",\"last\",\"computer\"]\nchoice = original = random.choice(words)\n\n#we can use a for loop to enforce tries\nfor _ in range(6):\n\n #this will run as long as the user keeps guessing correctly\n while (ch:=input(\"Choose a letter: \")) in choice:\n \n #remove guess letter\n choice = choice.replace(ch, '')\n \n #user won\n if not choice:\n print(f\"You got it! The word is \\'{original}\\'.\")\n break\n \n #user made a proper guess\n print('good guess')\n \n #if we got this far and there are still letters \n #it must have been a bad guess \n if choice: \n print('try again')\n continue\n \n #the word must have been guessed to get this far\n #break the for loop \n break\n \n#lose message\nif choice:\n print(f\"Sorry, you are out of tries. The word was \\'{original}\\'.\")\n"
},
{
"answer_id": 74441014,
"author": "McBrincie212",
"author_id": 20503634,
"author_profile": "https://Stackoverflow.com/users/20503634",
"pm_score": 0,
"selected": false,
"text": "import random\n\n\ndef main():\n words = [\"share\",\"last\",\"computer\"]\n choice_string = random.choice(words) # Make a Random Choice on List\n word_choice_listed = list(choice_string) # Make it as a List\n fails = 0\n\n def check_letter(word_choice_listed, letter, fails):\n if letter[0] not in word_choice_listed:\n print(\"Wrong Letter Given\")\n fails += 1 # Increment Fails By One\n return fails, word_choice_listed, False # Return is Very Necessary, Not Only to Give the 3 Values But To Break From Function\n print(\"Correct Letter Given\")\n word_choice_listed.remove(letter) # Remove the Letter\n return fails, word_choice_listed, True # 3 Returned Values, Use Check If You want Or Remove It All By Together\n\n while fails <= 3:\n print(word_choice_listed) # For Test purposes\n letter_input = input(\"Choose a letter: \") # Get the Letter Input, And Only Select the First Character\n while len(letter_input) == 0:\n print(\"You Didn't Input a Letter, Please Try Again!\")\n letter_input = input ( \"Choose a letter: \" )\n fails, word_choice_listed, check = check_letter(word_choice_listed, letter_input[0], fails) # We Take 3 Variables as Returned Values\n if len(word_choice_listed) == 0:\n print(f\"You Have Found The Word! {choice_string}\")\n return\n print ( f\"Sad You Didn't Found The Word, It Was {choice_string}!\" )\n\n\n# The If __name__ == \"__main__ idiom\nif __name__ == \"__main__\":\n main()\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20022629/"
] |
74,437,465 | <p>How to check for each row in dataframe if all its values are in specified range?</p>
<pre><code>import pandas as pd
new = pd.DataFrame({'a': [1,2,3], 'b': [-5,-8,-3], 'c': [20,0,0]})
</code></pre>
<p>For instance range <-5, 5>:</p>
<pre><code>>> a b c
>> 0 1 -5 20 # abs(20) > 5, hence no
>> 1 2 -8 0 # abs(-8) > 5, hence no
>> 2 3 -3 0 # abs(-3) <= 5, hence yes
</code></pre>
<p>Solution with iteration</p>
<pre><code>print(['no' if any(abs(i) > 5 for i in a) else 'yes' for _, a in new.iterrows()])
>> ['no', 'no', 'yes']
</code></pre>
| [
{
"answer_id": 74437664,
"author": "BeRT2me",
"author_id": 11865956,
"author_profile": "https://Stackoverflow.com/users/11865956",
"pm_score": 3,
"selected": true,
"text": "out = (df.gt(-5) & df.lt(5)).all(axis=1)\n# Or if you just want to supply a single value:\n# df.abs().lt(5).all(axis=1)\nprint(out)\n"
},
{
"answer_id": 74438008,
"author": "nikblg",
"author_id": 20493150,
"author_profile": "https://Stackoverflow.com/users/20493150",
"pm_score": 1,
"selected": false,
"text": "import pandas as pd\nimport numpy as np\n\n\ndf = pd.DataFrame({'a': [1, 2, 3], 'b': [-5, -8, -3], 'c': [20, 0, 0]})\n\n\ndf_ndarray = df.values\n\nbin_mask = np.where((df_ndarray > 5) | (df_ndarray < -5), 1, 0)\n\nres = np.equal(bin_mask.sum(axis=0), np.arange(len(df.columns)))\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19363912/"
] |
74,437,466 | <p>I have four polynomial (degree 2) functions and I need to find the intersection of these functions. but I do not know is any way to find all intersections in one step. my suggestion is to equalize two functions and find their roots using <code>numpy.roots</code>. but I am not sure if is it true or not. what should I do to find the intersections?
my functions are:</p>
<pre><code>y = 1.51250 * x + -0.07969 * x^2 + 18.96116
y = 1.54264 * x + -0.05879 * x^2 + 17.47277
y = 1.49669 * x + -0.04627 * x^2 + 17.69008
y = 1.72147 * x + 0.00052 * x^2 + 18.21067
</code></pre>
<p>I equal two first equations to find their roots, we will have :</p>
<pre><code>-0.03014x-0.0209x^2+1.48839=0
</code></pre>
<p>I used np.roots to find the roots:</p>
<pre><code>coeff=[-0.03014,-0.0209,1.48839]
np.roots(coeff)
</code></pre>
<p>the roots are:</p>
<pre><code>[-7.38253508, 6.68910443]
</code></pre>
<p>but when I put each of these roots in this equation <code>-0.03014x-0.0209x^2+1.48839=0</code> the output is not zero! what is the problem?</p>
| [
{
"answer_id": 74439025,
"author": "Vin",
"author_id": 7955271,
"author_profile": "https://Stackoverflow.com/users/7955271",
"pm_score": 2,
"selected": false,
"text": "import numpy as np\nfrom numpy.polynomial import Polynomial as Poly\n\n\nfrom matplotlib import pyplot as plt\n\n# Your functions:\n \n# y = 1.51250 * x + -0.07969 * x^2 + 18.96116\n# y = 1.54264 * x + -0.05879 * x^2 + 17.47277\n# y = 1.49669 * x + -0.04627 * x^2 + 17.69008\n# y = 1.72147 * x + 0.00052 * x^2 + 18.21067\n\ny1 = Poly((18.96116, 1.51250, -0.07969))\ny2 = Poly((17.47277, 1.54264, -0.05879))\ny3 = Poly((17.69008, 1.49669, -0.04627))\ny4 = Poly((18.21067, 1.72147, -0.00052))\n\n\n# Showing how to find intersections between y1 and y2 only\n# you could repeat this for other combinations as you please:\ny1_y2_intersections = (y1-y2).roots()\n\n# This returns the two x values at which the functions y1 and y2 have the same value\n\n# Plotting the curves and their intersections:\n\nx = np.arange(-15, 15) \n\nfig, ax = plt.subplots()\n\nax.plot(x, y1(x), label = 'y1') # Plotting y1\nax.plot(x, y2(x), label = 'y2') # Plotting y2\n\n# Plotting the intersection points\n\nfor x, y in zip(y1_y2_intersections, y1(y1_y2_intersections)):\n ax.plot(x, y, marker = 'x', color = 'red', linestyle = 'None', label = f'Root ({x:.2f}, {y:.2f})')\n \nax.grid()\nax.legend()\n"
},
{
"answer_id": 74442732,
"author": "MBo",
"author_id": 844416,
"author_profile": "https://Stackoverflow.com/users/844416",
"pm_score": 0,
"selected": false,
"text": "-0.03014x-0.0209x^2+1.48839=0 \n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11013499/"
] |
74,437,560 | <p>In my Flink project I cannot find certain libraries for connectors (specifically I need to ingest a CSV once and read several TBs of parquet data in either batch or streaming mode). I think I have all the required packages, but I am still getting:</p>
<pre class="lang-xml prettyprint-override"><code>[ERROR] import org.apache.flink.connector.file.src.FileSource
[ERROR] ^
[ERROR] C:\Users\alias\project\...\MyFlinkJob.scala:46: error: not found: type FileSource
</code></pre>
<p>My POM.xml is rather large, but I think I have the relevant imports:</p>
<pre class="lang-xml prettyprint-override"><code> <dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-parquet</artifactId>
<version>1.15.2</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-connector-filesystem_${scala.binary.version}</artifactId>
<version>1.11.6</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-hadoop-bulk_2.12</artifactId>
<version>1.14.6</version>
</dependency>
</code></pre>
<p>I am using the following versions:</p>
<pre class="lang-xml prettyprint-override"><code><scala.version>2.12.16</scala.version>
<scala.binary.version>2.12</scala.binary.version>
<log4j.version>2.17.1</log4j.version>
<flink.version>1.15.1</flink.version>
</code></pre>
<p>Do I need a different import path for Scala than Java?</p>
<p>I wish the Flink documentation had the imports in example code snippets as I spend a long time trying to figure out the imports. What are recommended <code>._</code> imports?</p>
<p>I've looked through the symbols in the package but didn't find FileSystem. I looked for different tutorials and example projects showing how to read/listen-to parquet and CSV files with Flink. I made some progress this way, but of the few examples I found in Scala (not Java) for using Parquet files as a source the imports still didn't work even after adding their dependencies and running <code>mvn clean install</code>.</p>
| [
{
"answer_id": 74439025,
"author": "Vin",
"author_id": 7955271,
"author_profile": "https://Stackoverflow.com/users/7955271",
"pm_score": 2,
"selected": false,
"text": "import numpy as np\nfrom numpy.polynomial import Polynomial as Poly\n\n\nfrom matplotlib import pyplot as plt\n\n# Your functions:\n \n# y = 1.51250 * x + -0.07969 * x^2 + 18.96116\n# y = 1.54264 * x + -0.05879 * x^2 + 17.47277\n# y = 1.49669 * x + -0.04627 * x^2 + 17.69008\n# y = 1.72147 * x + 0.00052 * x^2 + 18.21067\n\ny1 = Poly((18.96116, 1.51250, -0.07969))\ny2 = Poly((17.47277, 1.54264, -0.05879))\ny3 = Poly((17.69008, 1.49669, -0.04627))\ny4 = Poly((18.21067, 1.72147, -0.00052))\n\n\n# Showing how to find intersections between y1 and y2 only\n# you could repeat this for other combinations as you please:\ny1_y2_intersections = (y1-y2).roots()\n\n# This returns the two x values at which the functions y1 and y2 have the same value\n\n# Plotting the curves and their intersections:\n\nx = np.arange(-15, 15) \n\nfig, ax = plt.subplots()\n\nax.plot(x, y1(x), label = 'y1') # Plotting y1\nax.plot(x, y2(x), label = 'y2') # Plotting y2\n\n# Plotting the intersection points\n\nfor x, y in zip(y1_y2_intersections, y1(y1_y2_intersections)):\n ax.plot(x, y, marker = 'x', color = 'red', linestyle = 'None', label = f'Root ({x:.2f}, {y:.2f})')\n \nax.grid()\nax.legend()\n"
},
{
"answer_id": 74442732,
"author": "MBo",
"author_id": 844416,
"author_profile": "https://Stackoverflow.com/users/844416",
"pm_score": 0,
"selected": false,
"text": "-0.03014x-0.0209x^2+1.48839=0 \n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11039211/"
] |
74,437,598 | <p>When I hit play the game scene behaves as normal, <strong>even if I come from a different scene</strong>.</p>
<p>But when I am on the game scene and go to other scene and back again to the game scene some components from some game objects.</p>
<p>I am using <code>SceneManager.LoadScene("SceneName");</code> to move around scenes, and <strong>every component was added in the editor and saved in the scene</strong>.</p>
<p>And as an example here is the <em>Game Manager</em> inspector at first load of game scene:</p>
<p><a href="https://i.stack.imgur.com/KPJEe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KPJEe.png" alt="first load" /></a></p>
<p>And second load of game scene:</p>
<p><a href="https://i.stack.imgur.com/TK2pC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TK2pC.png" alt="second load" /></a></p>
<p><em>Windows Controls</em> is a script much like the others missing.</p>
<p>Am I doing something wrong?</p>
<p>Thanks in advance.</p>
| [
{
"answer_id": 74439025,
"author": "Vin",
"author_id": 7955271,
"author_profile": "https://Stackoverflow.com/users/7955271",
"pm_score": 2,
"selected": false,
"text": "import numpy as np\nfrom numpy.polynomial import Polynomial as Poly\n\n\nfrom matplotlib import pyplot as plt\n\n# Your functions:\n \n# y = 1.51250 * x + -0.07969 * x^2 + 18.96116\n# y = 1.54264 * x + -0.05879 * x^2 + 17.47277\n# y = 1.49669 * x + -0.04627 * x^2 + 17.69008\n# y = 1.72147 * x + 0.00052 * x^2 + 18.21067\n\ny1 = Poly((18.96116, 1.51250, -0.07969))\ny2 = Poly((17.47277, 1.54264, -0.05879))\ny3 = Poly((17.69008, 1.49669, -0.04627))\ny4 = Poly((18.21067, 1.72147, -0.00052))\n\n\n# Showing how to find intersections between y1 and y2 only\n# you could repeat this for other combinations as you please:\ny1_y2_intersections = (y1-y2).roots()\n\n# This returns the two x values at which the functions y1 and y2 have the same value\n\n# Plotting the curves and their intersections:\n\nx = np.arange(-15, 15) \n\nfig, ax = plt.subplots()\n\nax.plot(x, y1(x), label = 'y1') # Plotting y1\nax.plot(x, y2(x), label = 'y2') # Plotting y2\n\n# Plotting the intersection points\n\nfor x, y in zip(y1_y2_intersections, y1(y1_y2_intersections)):\n ax.plot(x, y, marker = 'x', color = 'red', linestyle = 'None', label = f'Root ({x:.2f}, {y:.2f})')\n \nax.grid()\nax.legend()\n"
},
{
"answer_id": 74442732,
"author": "MBo",
"author_id": 844416,
"author_profile": "https://Stackoverflow.com/users/844416",
"pm_score": 0,
"selected": false,
"text": "-0.03014x-0.0209x^2+1.48839=0 \n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14694660/"
] |
74,437,600 | <p>I have a data frame of individual animals with a unique ID, the lat/long where they were found, and the date they were found. The database has frequent returns of the same individual. I have over 2000 individuals. I want to add a column to my data frame to calculate euclidian distance between current location & previous location. I want to add a second column to tell me which calculation number I'm on for each individual. The data frame is already organized by sequential date. I'm trying to solve this in R.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Event</th>
<th>ID</th>
<th>Lat</th>
<th>Long</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>1</td>
<td>31.89</td>
<td>-80.98</td>
</tr>
<tr>
<td>2</td>
<td>2</td>
<td>31.54</td>
<td>-80.12</td>
</tr>
<tr>
<td>3</td>
<td>1</td>
<td>31.45</td>
<td>-81.92</td>
</tr>
<tr>
<td>4</td>
<td>1</td>
<td>31.64</td>
<td>-81.82</td>
</tr>
<tr>
<td>5</td>
<td>2</td>
<td>31.23</td>
<td>-80.98</td>
</tr>
</tbody>
</table>
</div>
<p>Add a column so that now it looks like</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Event</th>
<th>ID</th>
<th>Lat</th>
<th>Long</th>
<th>Dist.</th>
<th>Calculation #</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>1</td>
<td>31.89</td>
<td>-80.98</td>
<td>-</td>
<td>0</td>
</tr>
<tr>
<td>2</td>
<td>2</td>
<td>31.54</td>
<td>-80.12</td>
<td>-</td>
<td>0</td>
</tr>
<tr>
<td>3</td>
<td>1</td>
<td>31.45</td>
<td>-81.92</td>
<td>Distance between event 1 & 3</td>
<td>1</td>
</tr>
<tr>
<td>4</td>
<td>1</td>
<td>31.64</td>
<td>-81.82</td>
<td>Distance between event 3 & 4</td>
<td>2</td>
</tr>
<tr>
<td>5</td>
<td>2</td>
<td>31.23</td>
<td>-80.98</td>
<td>Distance between event 2 & 5</td>
<td>1</td>
</tr>
</tbody>
</table>
</div>
<p>Is there a faster way to do this without a for loop? I'm stuck on where to start. I know I can use a distance function from the geospatial package once, I have the uniqueID sorted, but I'm having trouble iterating through my data.</p>
| [
{
"answer_id": 74439025,
"author": "Vin",
"author_id": 7955271,
"author_profile": "https://Stackoverflow.com/users/7955271",
"pm_score": 2,
"selected": false,
"text": "import numpy as np\nfrom numpy.polynomial import Polynomial as Poly\n\n\nfrom matplotlib import pyplot as plt\n\n# Your functions:\n \n# y = 1.51250 * x + -0.07969 * x^2 + 18.96116\n# y = 1.54264 * x + -0.05879 * x^2 + 17.47277\n# y = 1.49669 * x + -0.04627 * x^2 + 17.69008\n# y = 1.72147 * x + 0.00052 * x^2 + 18.21067\n\ny1 = Poly((18.96116, 1.51250, -0.07969))\ny2 = Poly((17.47277, 1.54264, -0.05879))\ny3 = Poly((17.69008, 1.49669, -0.04627))\ny4 = Poly((18.21067, 1.72147, -0.00052))\n\n\n# Showing how to find intersections between y1 and y2 only\n# you could repeat this for other combinations as you please:\ny1_y2_intersections = (y1-y2).roots()\n\n# This returns the two x values at which the functions y1 and y2 have the same value\n\n# Plotting the curves and their intersections:\n\nx = np.arange(-15, 15) \n\nfig, ax = plt.subplots()\n\nax.plot(x, y1(x), label = 'y1') # Plotting y1\nax.plot(x, y2(x), label = 'y2') # Plotting y2\n\n# Plotting the intersection points\n\nfor x, y in zip(y1_y2_intersections, y1(y1_y2_intersections)):\n ax.plot(x, y, marker = 'x', color = 'red', linestyle = 'None', label = f'Root ({x:.2f}, {y:.2f})')\n \nax.grid()\nax.legend()\n"
},
{
"answer_id": 74442732,
"author": "MBo",
"author_id": 844416,
"author_profile": "https://Stackoverflow.com/users/844416",
"pm_score": 0,
"selected": false,
"text": "-0.03014x-0.0209x^2+1.48839=0 \n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20504219/"
] |
74,437,606 | <p>I just updated my solution to .NET7. I have a build/release pipeline setup on Azure Devops which now fails in the "Restore" step.</p>
<p>This is first error, which is then followed by multiple other errors of the same type:</p>
<blockquote>
<p>2:3>Target "_CheckForUnsupportedNETCoreVersion" in file "C:\Program
Files\dotnet\sdk\6.0.402\Sdks\Microsoft.NET.Sdk\targets\Microsoft.NET.TargetFrameworkInference.targets"
from project "D:\a\1\s\xxxx\xxxx.csproj" (target
"CollectPackageReferences" depends on it):
Using "NETSdkError" task from assembly "C:\Program Files\dotnet\sdk\6.0.402\Sdks\Microsoft.NET.Sdk\targets..\tools\net6.0\Microsoft.NET.Build.Tasks.dll".
Task "NETSdkError" 2:3>C:\Program Files\dotnet\sdk\6.0.402\Sdks\Microsoft.NET.Sdk\targets\Microsoft.NET.TargetFrameworkInference.targets(144,5):
error NETSDK1045: The current .NET SDK does not support targeting .NET
7.0. Either target .NET 6.0 or lower, or use a version of the .NET SDK that supports .NET 7.0. [D:\a\1\s\xxxx\xxxx.csproj]
Done executing task "NETSdkError" -- FAILED.</p>
</blockquote>
<p>I've tried using both "Windows Latest" and "Windows 2022" under "Agent specification" but neither works. I would have thought that "Windows Latest" would get automatically updated to the latest SDK once it's released? What do I have to change to make this build pipeline work with .NET7?</p>
| [
{
"answer_id": 74517408,
"author": "Vlad Rudenko",
"author_id": 901333,
"author_profile": "https://Stackoverflow.com/users/901333",
"pm_score": 0,
"selected": false,
"text": " - task: UseDotNet@2\n displayName: 'Install .NET Core SDK 7.x'\n inputs:\n version: 7.x\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/64157/"
] |
74,437,634 | <p>So I have dataframe that looks like this:</p>
<pre><code> STORE PRODUCT INVENTORY
1 store1 a 1
2 store1 b 0
3 store2 a 0
4 store2 b 0
5 store3 a 1
6 store3 b 1
</code></pre>
<p>I want to filter this such that it only shows me stores with a <code>total inventory > 0</code> in the sense that the result will be as follows because <code>store2</code> has a total inventory of 0.</p>
<pre><code> STORE PRODUCT INVENTORY
1 store1 a 1
2 store1 b 0
5 store3 a 1
6 store3 b 1
</code></pre>
<p>How do I do this?</p>
| [
{
"answer_id": 74437696,
"author": "Anoushiravan R",
"author_id": 14314520,
"author_profile": "https://Stackoverflow.com/users/14314520",
"pm_score": 3,
"selected": true,
"text": "df.loc[(df.groupby('STORE')['INVENTORY'].transform(sum) > 0)]\n\n STORE PRODUCT INVENTORY\n1 store1 a 1\n2 store1 b 0\n5 store3 a 1\n6 store3 b 1\n"
},
{
"answer_id": 74438467,
"author": "ThomasIsCoding",
"author_id": 12158757,
"author_profile": "https://Stackoverflow.com/users/12158757",
"pm_score": 2,
"selected": false,
"text": "filter"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17902784/"
] |
74,437,641 | <p>From the JSON string below I'm trying to pull just all the waiverId's:</p>
<pre><code>data =
{
"version": 4,
"id": "(requestId)",
"ts": "2022-11-14T20:24:50+00:00",
"type": "checkins",
"checkins": {
"fromDts": "2022-07-01",
"toDts": "2022-07-02",
"moreCheckins": true,
"checkins": [
{
"date": "2022-07-01 15:18:09",
"waiverId": "(id1)",
"position": 0,
"firstName": "(first name)",
"lastName": "(last name)"
},
{
"date": "2022-07-01 15:19:10",
"waiverId": "(id2)",
"position": 0,
"firstName": "(first name)",
"lastName": "(last name)"
}
]
}
}
</code></pre>
<p>I have tried the following:</p>
<pre><code>for checkins in data['checkins']:
print(checkins)
</code></pre>
<p>Which just gives:</p>
<pre><code>fromDts
toDts
moreCheckins
checkins
</code></pre>
<p>I would like just a list of:
id1
id2</p>
| [
{
"answer_id": 74437696,
"author": "Anoushiravan R",
"author_id": 14314520,
"author_profile": "https://Stackoverflow.com/users/14314520",
"pm_score": 3,
"selected": true,
"text": "df.loc[(df.groupby('STORE')['INVENTORY'].transform(sum) > 0)]\n\n STORE PRODUCT INVENTORY\n1 store1 a 1\n2 store1 b 0\n5 store3 a 1\n6 store3 b 1\n"
},
{
"answer_id": 74438467,
"author": "ThomasIsCoding",
"author_id": 12158757,
"author_profile": "https://Stackoverflow.com/users/12158757",
"pm_score": 2,
"selected": false,
"text": "filter"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437641",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20504251/"
] |
74,437,648 | <p>I have a string containing words, whitespace and numbers (integers and decimals). I want to separate them into two columns in a data frame so that column <code>A</code> contains the text and column <code>B</code> contains the number. It seems like a super simple task but I cannot figure out how to capture the text. I did capture the numbers though.</p>
<pre><code>require(tidyr)
df <- data.frame(x = c("This is text0", "This is a bit more text 0.01", "Even more text12.231"))
</code></pre>
<p>Captured the number in column <code>B</code> but I cannot figure out how what regex to put in the first set of parentheses to get the text in <code>A</code>:</p>
<pre><code>df |>
extract(x, c("A", "B"), "()(\\d+\\.*\\d*)")
# A B
#1 0
#2 0.01
#3 12.231
</code></pre>
| [
{
"answer_id": 74437667,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 3,
"selected": true,
"text": "extract(x, c(\"A\", \"B\"), \"^(.*?)\\\\s*(\\\\d+(?:\\\\.\\\\d+)?)$\")\n"
},
{
"answer_id": 74437707,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": false,
"text": "([A-Za-z ]+)"
},
{
"answer_id": 74566395,
"author": "moodymudskipper",
"author_id": 2270475,
"author_profile": "https://Stackoverflow.com/users/2270475",
"pm_score": 2,
"selected": false,
"text": "df <- data.frame(x = c(\"This is text0\", \"This is a bit more text 0.01\", \"Even more text12.231\"))\nunglue::unglue_unnest(df, x, \"{A}{B=[0-9.]+}\")\n#> A B\n#> 1 This is text 0\n#> 2 This is a bit more text 0.01\n#> 3 Even more text 12.231\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4308815/"
] |
74,437,650 | <p>I want to find the text that is visible on screen from a div (i.e. that is not clipped by the scrollbar regions). Is there a way to see if a child node part is visible on screen?
I can't find anywhere to even find the node coordinates, let alone how to see coords of the word parts of a node.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function doTest() {
var elem = document.getElementById('mydiv');
var nodes = elem.childNodes;
for (var n = 0; n < nodes.length; n++) {
console.log(nodes[n].textContent + isNodeVisible(nodes[n]));
var words = nodes[n].textContent.split(' ');
for (var w = 0; w < words.length; w++) {
console.log(nodes[n].textContent + isNodeWordVisible(nodes[n], w));
if (w > 10) break; // give up
}
if (n > 100) break;
}
}
function isNodeVisible(node) {
return 'who knows';
}
function isNodeWordVisible(node, wordN) {
return 'who knows';
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
margin: 20px;
border: solid 1px grey;
padding: 10px;
width: 200px;
height: 200px;
overflow: scroll
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='mydiv' onScroll='doTest()'>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Nunc eget lorem dolor sed viverra ipsum. Quis varius quam quisque id diam vel quam elementum pulvinar. Turpis egestas sed tempus
urna et pharetra pharetra massa. Sed risus pretium quam vulputate dignissim suspendisse in. Quis hendrerit dolor magna eget est. Augue neque gravida in fermentum et sollicitudin. Nec sagittis aliquam malesuada bibendum arcu vitae elementum. Nibh tortor
id aliquet lectus. Volutpat diam ut venenatis tellus in metus vulputate. Massa vitae tortor condimentum lacinia quis vel. Nec ultrices dui sapien eget mi proin sed. Augue neque gravida in fermentum et.Consectetur lorem donec massa sapien. Quis imperdiet
massa tincidunt nunc pulvinar sapien et ligula ullamcorper. Fringilla est ullamcorper eget nulla. Sagittis id consectetur purus ut faucibus. Consequat ac felis donec et. Tellus orci ac auctor augue mauris augue neque gravida. Ut pharetra sit amet aliquam.
A diam maecenas sed enim ut. Cras pulvinar mattis nunc sed blandit libero. Facilisi nullam vehicula ipsum a. Viverra tellus in hac habitasse.Neque gravida in fermentum et sollicitudin ac orci phasellus egestas. Tellus at urna condimentum mattis pellentesque
id nibh. Lorem donec massa sapien faucibus et molestie ac. Aliquam malesuada bibendum arcu vitae. Fermentum et sollicitudin ac orci phasellus egestas tellus rutrum. Pharetra vel turpis nunc eget. Vitae elementum curabitur vitae nunc. Venenatis lectus
magna fringilla urna porttitor rhoncus dolor purus non. Enim ut sem viverra aliquet eget sit amet. Sem nulla pharetra diam sit amet nisl suscipit. Amet massa vitae tortor condimentum lacinia quis vel. Erat pellentesque adipiscing commodo elit at imperdiet.
Tortor id aliquet lectus proin nibh nisl condimentum id venenatis. A iaculis at erat pellentesque adipiscing. Porta lorem mollis aliquam ut porttitor leo.Tincidunt augue interdum velit euismod in pellentesque massa placerat duis. Bibendum neque egestas
congue quisque. Adipiscing vitae proin sagittis nisl rhoncus mattis. Sem nulla pharetra diam sit amet nisl suscipit adipiscing. Sodales ut eu sem integer. Accumsan lacus vel facilisis volutpat. Adipiscing tristique risus nec feugiat in fermentum posuere
urna nec. Malesuada fames ac turpis egestas sed tempus urna et pharetra. Bibendum est ultricies integer quis auctor elit. Sagittis nisl rhoncus mattis rhoncus urna. Amet facilisis magna etiam tempor orci eu.Fusce ut placerat orci nulla. Suscipit adipiscing
bibendum est ultricies integer quis auctor elit sed. Platea dictumst quisque sagittis purus sit amet volutpat. Ac orci phasellus egestas tellus rutrum tellus pellentesque. Aenean et tortor at risus viverra adipiscing at. Nullam eget felis eget nunc
lobortis mattis aliquam faucibus. Orci dapibus ultrices in iaculis nunc sed. Etiam erat velit scelerisque in dictum non consectetur a. Morbi tristique senectus et netus et malesuada fames ac. Urna duis convallis convallis tellus id interdum velit. Nam
at lectus urna duis convallis convallis tellus id. Nullam eget felis eget nunc lobortis mattis aliquam. Faucibus turpis in eu mi bibendum neque. Orci porta non pulvinar neque laoreet suspendisse interdum consectetur. Sed augue lacus viverra vitae congue.
Fermentum posuere urna nec tincidunt praesent semper feugiat nibh. Vel facilisis volutpat est velit. Dignissim diam quis enim lobortis scelerisque fermentum dui. Neque ornare aenean euismod elementum. At urna condimentum mattis pellentesque id.Massa
eget egestas purus viverra accumsan in nisl nisi. Arcu cursus vitae congue mauris. Phasellus faucibus scelerisque eleifend donec pretium. Odio facilisis mauris sit amet massa vitae. Amet commodo nulla facilisi nullam vehicula ipsum a. Est velit egestas
dui id ornare arcu odio. Enim lobortis scelerisque fermentum dui. Natoque penatibus et magnis dis parturient montes nascetur ridiculus. Morbi tristique senectus et netus et malesuada fames ac turpis. Nec tincidunt praesent semper feugiat nibh sed pulvinar.
Consequat semper viverra nam libero. Non curabitur gravida arcu ac tortor dignissim convallis aenean. Dignissim suspendisse in est ante in nibh mauris cursus.Tellus in metus vulputate eu scelerisque. In massa tempor nec feugiat nisl pretium fusce id.
Eget velit aliquet sagittis id consectetur. Dictumst quisque sagittis purus sit. Eget sit amet tellus cras adipiscing enim. Non enim praesent elementum facilisis leo vel fringilla est. Aliquet eget sit amet tellus cras adipiscing enim eu. Pellentesque
id nibh tortor id aliquet lectus proin nibh. Imperdiet massa tincidunt nunc pulvinar sapien et. Leo integer malesuada nunc vel risus commodo. Feugiat sed lectus vestibulum mattis. Eu feugiat pretium nibh ipsum consequat nisl. Maecenas accumsan lacus
vel facilisis volutpat est velit egestas.Orci phasellus egestas tellus rutrum tellus pellentesque eu tincidunt tortor. Nunc pulvinar sapien et ligula ullamcorper. Nullam vehicula ipsum a arcu cursus vitae congue mauris. Erat imperdiet sed euismod nisi
porta lorem mollis. In vitae turpis massa sed elementum tempus egestas sed. Sit amet venenatis urna cursus eget nunc scelerisque viverra mauris. Tortor vitae purus faucibus ornare suspendisse. Eget magna fermentum iaculis eu non diam. Dui id ornare
arcu odio ut sem nulla pharetra. Viverra vitae congue eu consequat ac felis donec et odio. Aliquam sem et tortor consequat id porta nibh venenatis. Consequat semper viverra nam libero justo laoreet. Purus faucibus ornare suspendisse sed nisi lacus.
In arcu cursus euismod quis viverra. Tortor id aliquet lectus proin nibh nisl condimentum. Egestas congue quisque egestas diam in arcu. Sed risus ultricies tristique nulla aliquet enim tortor. Amet luctus venenatis lectus magna. Est placerat in egestas
erat imperdiet sed euismod.Leo integer malesuada nunc vel risus commodo viverra maecenas. Mi proin sed libero enim sed faucibus turpis. Ac turpis egestas maecenas pharetra convallis posuere morbi leo urna. Vel risus commodo
</div></code></pre>
</div>
</div>
</p>
<p>Any thoughts?</p>
| [
{
"answer_id": 74437667,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 3,
"selected": true,
"text": "extract(x, c(\"A\", \"B\"), \"^(.*?)\\\\s*(\\\\d+(?:\\\\.\\\\d+)?)$\")\n"
},
{
"answer_id": 74437707,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": false,
"text": "([A-Za-z ]+)"
},
{
"answer_id": 74566395,
"author": "moodymudskipper",
"author_id": 2270475,
"author_profile": "https://Stackoverflow.com/users/2270475",
"pm_score": 2,
"selected": false,
"text": "df <- data.frame(x = c(\"This is text0\", \"This is a bit more text 0.01\", \"Even more text12.231\"))\nunglue::unglue_unnest(df, x, \"{A}{B=[0-9.]+}\")\n#> A B\n#> 1 This is text 0\n#> 2 This is a bit more text 0.01\n#> 3 Even more text 12.231\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1432181/"
] |
74,437,663 | <p>I'm a beginner-casual, web developer, I want to surround my menu with a background image, I've tried to do it by myself, but still, it's shows the default white background, can someone please help me out?</p>
<p>Here is my CSS script:</p>
<pre class="lang-css prettyprint-override"><code> body {
background-image: url(https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.bonappetit.com%2Fstory%2Fhow-to-buy-coffee-beans&psig=AOvVaw2rGyzxjYnZTpqbQELy-_qH&ust=1668543336904000&source=images&cd=vfe&ved=0CBAQjRxqFwoTCIj8h7q-rvsCFQAAAAAdAAAAABAD);
font-family: sans-serif;
padding: 20px;
}
.menu {
max-width: 500px;
width: 80%;
margin-left: auto;
margin-right: auto;
background-color: burlywood;
padding: 10px;
}
</code></pre>
| [
{
"answer_id": 74438058,
"author": "Edy",
"author_id": 18466936,
"author_profile": "https://Stackoverflow.com/users/18466936",
"pm_score": 0,
"selected": false,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Document</title>\n</head>\n\n<body>\n a\n</body>\n\n</html>\n\n<style>\n body {\n background-image: url(https://th.bing.com/th/id/R.5e6520289b44e11a9e74363c18ce3ee1?rik=0NsMGzWCfTqnyA&riu=http%3a%2f%2fcdn.wallpapersafari.com%2f34%2f38%2ffNuD4F.jpg&ehk=rWygJFVz8poo%2buNiEqsllRqA4jP9BCE6VYuBOMM03GA%3d&risl=&pid=ImgRaw&r=0);\n font-family: sans-serif;\n padding: 20px;\n height: 100%;\n background-position: center center;\n background-repeat: no-repeat;\n /* this is to make the image fits all the screen doesnt matter the image size, but it will cut the image\n background-size: cover; */\n }\n</style>\n"
},
{
"answer_id": 74438935,
"author": "Boatti",
"author_id": 19192614,
"author_profile": "https://Stackoverflow.com/users/19192614",
"pm_score": 0,
"selected": false,
"text": ".menu { \n max-width: 500px;\n width: 80%;\n margin-left: auto;\n margin-right: auto;\n background-color: burlywood;\n padding: 10px;\n }\n \n \nbody{\n background: url(\"https://img.freepik.com/free-photo/vivid-blurred-colorful-background_58702-2545.jpg?w=2000\");\n font-family: sans-serif;\n padding: 20px;\n }"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20504207/"
] |
74,437,669 | <p>I wish to convert a DataFrame into a dictionary where columns are the keys and (column-wise) rows are its values. I also need to use grouping when doing so.</p>
<pre><code> team id name salary
0 Alpha 10 Jack 1000
1 Alpha 15 John 2000
2 Alpha 20 John 2000
3 Bravo 50 Thomas 5000
4 Bravo 55 Robert 6000
5 Bravo 60 Albert 7000
</code></pre>
<h3>Expected output:</h3>
<pre><code># expected output WITH duplicates
ex = {'Alpha': {'id': [10, 15, 20], 'name': ['Jack', 'John', 'John'], 'salary': [1000, 2000, 2000]},
'Bravo': {'id': [50, 55, 60], 'name': ['Thomas', 'Robert', 'Albert'], 'salary': [5000, 6000, 7000]}
}
# expected output WITHOUT duplicates ('name', 'salary')
ex = {'Alpha': {'id': [10, 15, 20], 'name': ['Jack', 'John'], 'salary': [1000, 2000]},
'Bravo': {'id': [50, 55, 60], 'name': ['Thomas', 'Robert', 'Albert'], 'salary': [5000, 6000, 7000]}
}
</code></pre>
<p>Can it be done somehow using <code>df.to_dict()</code> ?</p>
<h3>Code for example:</h3>
<pre><code>import pandas as pd
d = {'team': ['Alpha', 'Alpha', 'Alpha', 'Bravo', 'Bravo', 'Bravo'],
'id': [10, 15, 20, 50, 55, 60],
'name': ['Jack', 'John', 'John', 'Thomas', 'Robert', 'Albert'],
'salary': [1000, 2000, 2000, 5000, 6000, 7000]}
df = pd.DataFrame(data=d)
</code></pre>
| [
{
"answer_id": 74437853,
"author": "BeRT2me",
"author_id": 11865956,
"author_profile": "https://Stackoverflow.com/users/11865956",
"pm_score": 2,
"selected": false,
"text": "Groupby"
},
{
"answer_id": 74437936,
"author": "Panda Kim",
"author_id": 20430449,
"author_profile": "https://Stackoverflow.com/users/20430449",
"pm_score": 1,
"selected": false,
"text": "df.groupby('team').agg(list).T.to_dict()\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9855909/"
] |
74,437,705 | <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>//Code that I have tried but it doesnt work:
$('#historyOfStatus table td').not(':contains("Revisions Required – CM")').parents("tr").remove();</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="historyOfStatus">
<table>
<tbody>
<tr>
<th>Value</th>
<th>Date Time</th>
<th>By</th>
</tr>
<tr>
<td class="Data1">Draft</td>
<td class="Data1">2022-11-14 13:34:31</td>
<td class="Data1">Muhammad Akhtar</td>
</tr>
<tr>
<td class="Data1">Revisions Required – CM</td>
<td class="Data1">2022-11-14 13:40:18</td>
<td class="Data1">a</td>
</tr>
<tr>
<td class="Data2">Under CFF Contracts Manager Review</td>
<td class="Data2">2022-11-14 13:41:38</td>
<td class="Data2">aa</td>
</tr>
<tr>
<td class="Data1">Under CFF Compliance Review</td>
<td class="Data1">2022-11-14 13:41:43</td>
<td class="Data1">aaaa</td>
</tr>
<tr>
<td class="Data2">Revisions Required – CM</td>
<td class="Data2">2022-11-14 13:41:48</td>
<td class="Data2">bb</td>
</tr>
<tr>
<td class="Data2">Revisions Required – CM</td>
<td class="Data2">2022-11-14 13:43:10</td>
<td class="Data2">cc</td>
</tr>
</tbody>
</table>
</div></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74437853,
"author": "BeRT2me",
"author_id": 11865956,
"author_profile": "https://Stackoverflow.com/users/11865956",
"pm_score": 2,
"selected": false,
"text": "Groupby"
},
{
"answer_id": 74437936,
"author": "Panda Kim",
"author_id": 20430449,
"author_profile": "https://Stackoverflow.com/users/20430449",
"pm_score": 1,
"selected": false,
"text": "df.groupby('team').agg(list).T.to_dict()\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/603380/"
] |
74,437,709 | <p>So I got a numeric list <code>[0-12]</code> that matches the length of my columns in my spreadsheet and also replaced the column headers with that list <code>df.columns = list</code>.
Now i want to drop specific columns out of that spreadsheet like <a href="https://i.stack.imgur.com/f0Tt9.png" rel="nofollow noreferrer">this</a>.</p>
<p>To create the list of numbers to match the length of columns I got this:</p>
<pre><code>listOfNumbers = []
column_name = []
for i in range(0, len(df.columns)):
listOfNumbers.append(i)
df.columns = listOfNumbers
for i in range(1, len(df.columns)):
for j in range(1, len(df.columns)):
if i != colList[j]:
df.drop(i, inplace=True)
</code></pre>
<p>And I got the list <code>[1,2,3]</code> as seen in the picture.
But i always get this Error:</p>
<blockquote>
<p>KeyError: '[1] not found in axis</p>
</blockquote>
<p>I tried to replace <code>df.drop(i, inplace=True)</code> with <code>df.drop(i, axis=1, inplace=True)</code> but that didn't work either.</p>
<p>Any suggestions? Thanks.</p>
| [
{
"answer_id": 74437853,
"author": "BeRT2me",
"author_id": 11865956,
"author_profile": "https://Stackoverflow.com/users/11865956",
"pm_score": 2,
"selected": false,
"text": "Groupby"
},
{
"answer_id": 74437936,
"author": "Panda Kim",
"author_id": 20430449,
"author_profile": "https://Stackoverflow.com/users/20430449",
"pm_score": 1,
"selected": false,
"text": "df.groupby('team').agg(list).T.to_dict()\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12719205/"
] |
74,437,715 | <p>I'm trying to print some words stored in a list using for loop:</p>
<pre><code>#!/bin/sh
list="bla1 bla2 * bla3"
for i in $list
do
echo "$i"
done
</code></pre>
<p>I want this output:</p>
<pre><code>bla1
bla2
*
bla3
</code></pre>
<p>Running the script gives:</p>
<pre><code>bla1
bla2
[LIST OF FILES]
bla3
</code></pre>
<p>I want the words stored in the list to be treated as strings, please HELP!</p>
<p>I tried:
<code>echo "\$i"</code>
<code>echo ""$i""</code>
<code>echo "'$i'"</code>
...</p>
<p>It does not work</p>
| [
{
"answer_id": 74437762,
"author": "Charles Duffy",
"author_id": 14122,
"author_profile": "https://Stackoverflow.com/users/14122",
"pm_score": 2,
"selected": true,
"text": "/bin/sh"
},
{
"answer_id": 74438876,
"author": "Gary_W",
"author_id": 2543416,
"author_profile": "https://Stackoverflow.com/users/2543416",
"pm_score": 0,
"selected": false,
"text": "$ cat x.sh\n#!/bin/sh\n\nlist=\"bla1 bla2 * bla3\"\n\nfor i in \"$list\"\ndo\n echo \"$i\"\ndone\n\n$ ./x.sh\nbla1 bla2 * bla3\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13399725/"
] |
74,437,717 | <p>Consider two tibbles <code>data</code> and <code>key</code>, given here:</p>
<pre><code>library(tidyverse) # v1.3.2
set.seed(123)
data <- tibble(id = rep(LETTERS[1:10], each = 10),
position = rep(1:10, 10),
zip = sample(letters, 100, replace = T),
zap = sample(letters, 100, replace = T),
zop = sample(letters, 100, replace = T))
# A tibble: 100 × 5
id position zip zap zop
<chr> <int> <chr> <chr> <chr>
1 A 1 l n u
2 A 2 y f h
3 A 3 n y u
4 A 4 c h g
5 A 5 n l t
6 A 6 g z r
7 A 7 c d q
8 A 8 w m a
9 A 9 v n b
10 A 10 z u q
# … with 90 more rows
</code></pre>
<pre><code>key <- tibble(id = c("A","D","H"),
start = c(2, 5, 7),
end = c(4, 6, 9))
# A tibble: 3 × 3
id start end
<chr> <dbl> <dbl>
1 A 2 4
2 D 5 6
3 H 7 9
</code></pre>
<p>And the desired output:</p>
<pre><code># A tibble: 8 × 5
id position zip zap zop
<chr> <int> <chr> <chr> <chr>
1 A 2 s u w
2 A 3 n e a
3 A 4 c h h
4 D 5 j j w
5 D 6 m e z
6 H 7 m v h
7 H 8 e q w
8 H 9 v j y
</code></pre>
<p>What's the most efficient way to subset <code>data</code> by <code>id</code> and the range of <code>position</code> given by <code>key</code>? I can think of two approaches, but neither is very fast.</p>
<h2>1. <code>apply()</code> across rows of <code>key</code>, and bind the pieces</h2>
<pre><code>apply(X = key, MARGIN = 1, function(x) {
data |>
dplyr::filter(id == x[1],
position %in% x[2]:x[3])
}
) |> dplyr::bind_rows()
</code></pre>
<h2>2. pivot and fill <code>key</code>, then <code>join()</code></h2>
<pre><code>key |> tidyr::pivot_longer(cols = c(start, end),
values_to = "position") |>
dplyr::select(id, position) |>
dplyr::group_by(id) |>
tidyr::complete(position = seq(from = min(position),
to = max(position))) |>
dplyr::left_join(data)
</code></pre>
<p>What tidy approach would likely be fastest given <code>data</code> with millions of lines and a <code>key</code> with hundreds?</p>
| [
{
"answer_id": 74437752,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 3,
"selected": true,
"text": "slice"
},
{
"answer_id": 74482716,
"author": "acvill",
"author_id": 7976890,
"author_profile": "https://Stackoverflow.com/users/7976890",
"pm_score": 1,
"selected": false,
"text": "inner_join"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7976890/"
] |
74,437,727 | <p>I have this hook in Wordpress that will convert any uploaded PNGs or JPEGS to WebP images:</p>
<pre><code> add_filter( 'wp_handle_upload', 'create_webp' );
function create_webp($file) {
if ($file['type'] === "image/png") {
// Create and save
$img = imagecreatefrompng($file['file']);
imagepalettetotruecolor($img);
imagealphablending($img, true);
imagesavealpha($img, true);
imagewebp($img, str_replace(".png" ,".webp", $file['file']), 100);
imagedestroy($img);
}
elseif($file['type'] === "image/jpg" || $file['type'] === "image/jpeg"){
$img = imagecreatefromjpeg($file['file']);
imagepalettetotruecolor($img);
imagealphablending($img, true);
imagesavealpha($img, true);
if($file['type'] === "image/jpg"){
imagewebp($img, str_replace(".jpg" ,".webp", $file['file']), 100);
}
else{
imagewebp($img, str_replace(".jpeg" ,".webp", $file['file']), 100);
}
imagedestroy($img);
}
return $file;
}
</code></pre>
<p>So now every time I upload a new image to the media library, a .webp version is also created. However, I would like to find a way to replace the old PNG or JPEG image that was uploaded to the media library with the newly created .webp image. So when I go to the media library in Wordpress, I would see the .webp image and not the PNG or JPEG Is this possible?</p>
| [
{
"answer_id": 74473852,
"author": "Николай",
"author_id": 9098414,
"author_profile": "https://Stackoverflow.com/users/9098414",
"pm_score": 2,
"selected": true,
"text": "$posts = get_posts([\n 'post_mime_type' => 'image',\n 'post_type' => 'attachment',\n 'post_status' => 'inherit',\n 'posts_per_page' => -1,\n]);\n\nforeach ($posts as $post) {\n // Here you can compare the file extension\n // and, using your code, convert the image (by creating another one)\n // and delete the original jpg/png file :)\n}\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1356860/"
] |
74,437,741 | <p>Given the following dictionary:</p>
<pre><code>dict1 = {'AA':['THISISSCARY'],
'BB':['AREYOUAFRAID'],
'CC':['DONOTWORRY']}
</code></pre>
<p>I'd like to update the values in the dictionary given the information in the following table</p>
<pre><code>Table = pd.DataFrame({'KEY':['AA','AA','BB','CC'],
'POSITION':[2,4,9,3],
'oldval':['I','I','A','O'],
'newval':['X','X','U','I']})
</code></pre>
<p>that looks like this</p>
<pre><code> KEY POSITION oldval newval
0 AA 2 I X
1 AA 4 I X
2 BB 9 A U
3 CC 3 O I
</code></pre>
<p>The end result should look like this:</p>
<pre><code>dict1 = {'AA':['THXSXSSCARY'],
'BB':['AREYOUAFRUID'],
'CC':['DONITWORRY']}
</code></pre>
<p>Essentially, I'm using the <strong>KEY</strong> and <strong>POSITION</strong> to find the location of the value in the dictionary then if the <strong>oldvalue</strong> matches the one in the dictionary, then replacing it with the <strong>newval</strong></p>
<p>I've been looking at the update function where I'd convert my table to a dictionary but I'm unsure how to apply to my example.</p>
| [
{
"answer_id": 74473852,
"author": "Николай",
"author_id": 9098414,
"author_profile": "https://Stackoverflow.com/users/9098414",
"pm_score": 2,
"selected": true,
"text": "$posts = get_posts([\n 'post_mime_type' => 'image',\n 'post_type' => 'attachment',\n 'post_status' => 'inherit',\n 'posts_per_page' => -1,\n]);\n\nforeach ($posts as $post) {\n // Here you can compare the file extension\n // and, using your code, convert the image (by creating another one)\n // and delete the original jpg/png file :)\n}\n"
}
] | 2022/11/14 | [
"https://Stackoverflow.com/questions/74437741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16922748/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.