qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,574,974
|
<p>I have two vectors</p>
<pre><code>a <- c(1,1,1,1,20,30,40,100,300)
b <- c(2,2,2,2,100,0,0,120,5)
</code></pre>
<p>I want to create a vector that compares and gives you the maximum of both vectors only for last 5 elements.</p>
<p>The first 4 elements must remain the same as in vector <code>a</code>.</p>
<pre><code>output <- c(1,1,1,1,100,30,40,120,300)
</code></pre>
|
[
{
"answer_id": 74574986,
"author": "Jilber Urbina",
"author_id": 1315767,
"author_profile": "https://Stackoverflow.com/users/1315767",
"pm_score": 4,
"selected": true,
"text": "pmax > pmax(a,b)\n[1] 100 30 40 120 300\n > a <- c(1,1,1,1,20, 30,40,100,300)\n> b <- c(2,2,2,2, 100, 0, 0, 120, 5)\n> c(a[!a %in% tail(a, 5)], pmax(tail(a, 5), tail(b, 5)))\n[1] 1 1 1 1 100 30 40 120 300\n"
},
{
"answer_id": 74575178,
"author": "Ric Villalba",
"author_id": 6912817,
"author_profile": "https://Stackoverflow.com/users/6912817",
"pm_score": 2,
"selected": false,
"text": "a <- c(1,1,1,1,20,30,40,100,300)\nb <- c(2,2,2,2,100,0,0,120,5)\n\nreplace(a, tail(seq(a),5), pmax(tail(a,5),tail(b,5)))\n#> [1] 1 1 1 1 100 30 40 120 300\n"
},
{
"answer_id": 74575263,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 1,
"selected": false,
"text": "head tail c(head(a,-5), ifelse(tail(a,5)>tail(b,5), tail(a,5), tail(b,5)))\n [1] 1 1 1 1 100 30 40 120 300\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74574974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19633374/"
] |
74,575,002
|
<p>Let's assume I have this table:</p>
<pre><code>| ID | Amount | Value |
|----------|-------------|-------|
| 1 | 3 | 10 |
| 1 | 1 | 25 |
| 2 | 1 | 35 |
</code></pre>
<p>How can I transform into this?:</p>
<pre><code>| ID | Total Value |
|---------------|-------------|
| 1 | 55 |
| 2 | 35 |
</code></pre>
<p>Showing how to sum the values without doing the multiplication on the <code>amount</code> would also be useful for my further research.</p>
|
[
{
"answer_id": 74575058,
"author": "masoud rafiee",
"author_id": 4256602,
"author_profile": "https://Stackoverflow.com/users/4256602",
"pm_score": 0,
"selected": false,
"text": "Select id,Sum(Amount *Value) as TotalValue\nfrom table \ngroup by id\n"
},
{
"answer_id": 74575079,
"author": "nbk",
"author_id": 5193536,
"author_profile": "https://Stackoverflow.com/users/5193536",
"pm_score": -1,
"selected": false,
"text": "SELECT\n ID,\n SUM( amount * value) as total_value\nFROmtable1\nGROUPO BY ID \n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20553293/"
] |
74,575,016
|
<p>There are two layers in a mapbox map inside a react app. I am new to both. I want to disable clicking in one layer, when the other is visible. I control the visibility of each layer from a checkbox value via react.</p>
<p>I have this code</p>
<pre><code>export default function Map () {
const [checkedLayer, setCheckedLayer] = useState(true);
const [checkedOtherLayer, setCheckedOtherLayer] = useState(true);
//when a checkbox is on or off make layer visible or not
const handleVisibility = (event) => {
let visible ; let layer;
event.target.checked ? visible = 'visible' : visible = 'none'
if (event.target.id === 'mylayer') {
setCheckedLayer(event.target.checked);
layer = 'mylayer';
}
if (event.target.id === 'myotherlayer') {
setCheckedOtherLayer(event.target.checked);
layer = 'myotherlayer';
}
map.current.setLayoutProperty(layer, 'visibility', visible);
};
useEffect(() => {
if (map.current) return; // initialize map only once
map.current = new mapboxgl.Map({
container: mapContainer.current,
style: 'mapbox://styles/mapbox/satellite-streets-v11',
center: [lng, lat],
zoom: zoom
});//map
map.current.on('load', () => {
//...set layers and sources
});//load
map.current.on('click', 'mylayer', (e) => {
console.log('other layer visibility ', map.current.getLayoutProperty('myotherlayer', 'visibility'));
// I want to do something like
// if map.current.getLayoutProperty('myotherlayer', 'visibility')) == 'visible'
// return
// but the above console.log keeps giving "undefined"
// map.current.getLayoutProperty('mylayer', 'visibility') works
});
},[checkedLayer, checkedOtherLayer]);//useEffect
return (
<div>
<Checkbox
id="mylayer"
checked={checkedLayer}
onChange={handleVisibility}
inputProps={{ 'aria-label': 'controlled' }}
/>
<Checkbox
id="myotherlayer"
checked={checkedOtherLayer}
onChange={handleVisibility}
inputProps={{ 'aria-label': 'controlled' }}
/>
<div ref={mapContainer} className="map-container"> </div>
</div>
)
}
</code></pre>
<p>When <code>mylayer</code> is clicked I try to check the value of the visibility of <code>myotherlayer</code> and if it is <code>visible</code>, return, so nothing is executed inside <code>'click', 'mylayer'</code> function. But the value of <code>map.current.getLayoutProperty('myotherlayer', 'visibility'));</code> is <code>undefined</code>.</p>
<p>What am I doing wrong here?</p>
<p>Thanks</p>
|
[
{
"answer_id": 74575058,
"author": "masoud rafiee",
"author_id": 4256602,
"author_profile": "https://Stackoverflow.com/users/4256602",
"pm_score": 0,
"selected": false,
"text": "Select id,Sum(Amount *Value) as TotalValue\nfrom table \ngroup by id\n"
},
{
"answer_id": 74575079,
"author": "nbk",
"author_id": 5193536,
"author_profile": "https://Stackoverflow.com/users/5193536",
"pm_score": -1,
"selected": false,
"text": "SELECT\n ID,\n SUM( amount * value) as total_value\nFROmtable1\nGROUPO BY ID \n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9267316/"
] |
74,575,017
|
<p>I am expecting JSON object from an API which is like:</p>
<pre><code>{
"header":{
"message_type":"message_type",
"notification_type":"notification_type"
},
"body":{
"id":"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"related_entity_type":"inbound_funds",
}
}
</code></pre>
<p>The problem is that body can have any number and type of props. And, I have corresponding C# Models for each and every Body type. Is there any efficient way to parse and Deserialize these objects to relevant C# Models, dynamically?</p>
<p>I tried this, bus then Body doesn't desterilize at runtime.</p>
<pre><code>public class PushNotification : Body
{
[JsonProperty("header")]
public Header Header { get; set; }
[JsonProperty("body")]
public Body Body { get; set; }
}
public class Body
{
}
</code></pre>
|
[
{
"answer_id": 74575058,
"author": "masoud rafiee",
"author_id": 4256602,
"author_profile": "https://Stackoverflow.com/users/4256602",
"pm_score": 0,
"selected": false,
"text": "Select id,Sum(Amount *Value) as TotalValue\nfrom table \ngroup by id\n"
},
{
"answer_id": 74575079,
"author": "nbk",
"author_id": 5193536,
"author_profile": "https://Stackoverflow.com/users/5193536",
"pm_score": -1,
"selected": false,
"text": "SELECT\n ID,\n SUM( amount * value) as total_value\nFROmtable1\nGROUPO BY ID \n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3044446/"
] |
74,575,018
|
<p>I'm creating a VBA script which will delete a lot of blank columns from a downloaded excel file. As the total number of columns are likely to change over time, I can't just use the cell reference as any changes would knock the macro out of sync (like it has already). Now, I want to target the columns by their column header, as not their cell reference. So, I've collated a complete list of columns I want to delete (there are a lot) and added them to the VBA module with the correct syntax surrounding them ("@", & _)</p>
<p>I'm quite new to using VBA and I've not found much online that is much use. I found the below script which does a good job of deleting a single column.</p>
<pre><code>Sub FindAddressColumn()
'Updateby Extendoffcie
Dim xRg As Range
Dim xRgUni As Range
Dim xFirstAddress As String
Dim xStr As String
On Error Resume Next
xStr = "Name"
Set xRg = Range("A1:P1").Find(xStr, , xlValues, xlWhole, , , True)
If Not xRg Is Nothing Then
xFirstAddress = xRg.Address
Do
Set xRg = Range("A1:P1").FindNext(xRg)
If xRgUni Is Nothing Then
Set xRgUni = xRg
Else
Set xRgUni = Application.Union(xRgUni, xRg)
End If
Loop While (Not xRg Is Nothing) And (xRg.Address <> xFirstAddress)
End If
xRgUni.EntireColumn.Select
End Sub**
</code></pre>
<p>But when I tried making amendments to include a range of column headers I am hit with an error message - 'Compile Error: Wrong number of arguments or invalid property assignment'</p>
<pre><code>Sub deleteEmptyCols()
'Updateby Extendoffcie
Dim xRg As Range
Dim xRgUni As Range
Dim xFirstAddress As String
Dim xStr As String
On Error Resume Next
xStr = Range("PREVIOUS TRANSACTION ID", "PARENT TRANSACTION ID", "TRANSACTION COMMENTS", "HP INVOICE NUMBER", "REPORTER PURCHASE ORDER ID", "PARTNER PURCHASE PRICE", "CUSTOMER TO CHANNEL PARTNER PURCHASE ORDER ID", "PARTNER INTERNAL TRANSACTION ID", "PARTNER REQUESTED REBATE AMOUNT", "PARTNER COMMENT", "DEAL/PROMO ID #2", "DEAL/PROMO ID #3", "DEAL/PROMO ID #4", "DEAL/PROMO ID #5", "DEAL/PROMO ID #6", "DEAL BUNDLE ID #1", "REBATE DEAL 1 MINIMUM RESELLER QUANTITY", "REBATE DEAL 1 MAX RESELLER QUANTITY", "EXTENDED REFERENCE PRICE (SNOP) 1", "DEAL BUNDLE ID #2" & _
"REBATE DEAL 2", "REBATE DEAL 2 START DATE", "REBATE DEAL 2 END DATE", "REBATE DEAL 2 MC CODE", "REBATE DEAL 2 MINIMUM RESELLER QUANTITY", "REBATE DEAL 2 MAX RESELLER QUANTITY", "REBATE DEAL 2 DEAL VERSION", "REBATE DEAL 2 REMAINING QTY", "BACKEND DEAL DISCOUNT TYPE BASE 2", "BACKEND DEAL REBATE AMOUNT PER UNIT TOTAL 2", "BACKEND DEAL NET TOTAL 2", "DCT FLAG DEAL 2", "EXTENDED REFERENCE PRICE (SNOP) 2", "DEAL BUNDLE ID #3", "REBATE DEAL 3", "REBATE DEAL 3 START DATE", "REBATE DEAL 3 END DATE", "REBATE DEAL 3 MC CODE", "REBATE DEAL 3 MINIMUM RESELLER QUANTITY", "REBATE DEAL 3 MAX RESELLER QUANTITY" & _
"REBATE DEAL 3 DEAL VERSION", "REBATE DEAL 3 REMAINING QTY", "BACKEND DEAL DISCOUNT TYPE BASE 3", "BACKEND DEAL REBATE AMOUNT PER UNIT TOTAL 3", "BACKEND DEAL NET TOTAL 3", "DCT FLAG DEAL 3", "EXTENDED REFERENCE PRICE (SNOP) 3", "DEAL BUNDLE ID #4", "REBATE DEAL 4", "REBATE DEAL 4 START DATE", "REBATE DEAL 4 END DATE", "REBATE DEAL 4 MC CODE", "REBATE DEAL 4 MINIMUM RESELLER QUANTITY", "REBATE DEAL 4 MAX RESELLER QUANTITY", "REBATE DEAL 4 DEAL VERSION", "REBATE DEAL 4 REMAINING QTY", "BACKEND DEAL DISCOUNT TYPE BASE 4", "BACKEND DEAL REBATE AMOUNT PER UNIT TOTAL 4", "EXTENDED REFERENCE PRICE (SNOP) 4", "BACKEND DEAL NET TOTAL 4" & _
"DCT FLAG DEAL 4", "DEAL BUNDLE ID #5", "REBATE DEAL 5", "REBATE DEAL 5 START DATE", "REBATE DEAL 5 END DATE", "REBATE DEAL 5 MC CODE", "REBATE DEAL 5 MINIMUM RESELLER QUANTITY", "REBATE DEAL 5 MAX RESELLER QUANTITY", "REBATE DEAL 5 DEAL VERSION", "REBATE DEAL 5 REMAINING QTY", "BACKEND DEAL DISCOUNT TYPE BASE 5", "BACKEND DEAL REBATE AMOUNT PER UNIT TOTAL 5", "BACKEND DEAL NET TOTAL 5", "DCT FLAG DEAL 5", "EXTENDED REFERENCE PRICE (SNOP) 5", "DEAL BUNDLE ID #6", "PARTNER REPORTED CBN#", "PARTNER REFERENCE", "INTERCOMPANY FLAG", "SOLD TO STATE" & _
"END USER CUSTOMER NAME", "END USER ID", "UPFRONT DEAL ID", "SUB REGION PARTNER LOCATOR NUMBER", "WW PARTNER LOCATOR NUMBER", "CUSTOMER ID", "EXTENDED SHIPMENT PRICE", "DERIVED INVOICE PRICE", "REBATE ADJUSTMENT", "ELIGIBLE SALES ADJUSTMENT", "IS MAXCAP MET", "BUNDLE COMPLETENESS STATUS", "IS MINCAP MET", "CREDIT MEMO DATE", "CREDIT MEMO REFERENCE", "PAID QUANTITY", "PAID AMOUNT", "PAID COMMENTS", "DNQ", "STACKING VALIDATION" & _
"ADJUSTMENT COMMENTS", "REVERSAL PAYMENT REFERENCE", "FCM PRICING REBATE FLAG", "CASE NUMBER", "CASE STATUS", "CASE LAST STATUS UPDATE DATE", "CASE CREATION DATE", "CASE COMMENT", "REASON CODE", "REASON DESCRIPTION", "PRICE POINT WARNING DETAILS")
Set xRg = Range("A1:GO1").Find(xStr, , xlValues, xlWhole, , , True)
If Not xRg Is Nothing Then
xFirstAddress = xRg.Address
Do
Set xRg = Range("A1:P1").FindNext(xRg)
If xRgUni Is Nothing Then
Set xRgUni = xRg
Else
Set xRgUni = Application.Union(xRgUni, xRg)
End If
Loop While (Not xRg Is Nothing) And (xRg.Address <> xFirstAddress)
End If
xRgUni.EntireColumn.Select
End Sub
```
</code></pre>
<p>All I expect to happen is select all of the columns mentioned in the range, and then be able to delete them all using the macro.</p>
|
[
{
"answer_id": 74575260,
"author": "Notus_Panda",
"author_id": 19353309,
"author_profile": "https://Stackoverflow.com/users/19353309",
"pm_score": 2,
"selected": false,
"text": "Sub deleteEmptyColumns()\n Dim lastColumn As Long\n lastColumn = Cells(1, Columns.Count).End(xlToLeft).Column\n For i = lastColumn To 1 Step -1\n If WorksheetFunction.CountA(ActiveSheet.Columns(i)) <= 1 Then ActiveSheet.Columns(i).EntireColumn.Delete\n Next\n \nEnd Sub\n"
},
{
"answer_id": 74575415,
"author": "pgSystemTester",
"author_id": 11732320,
"author_profile": "https://Stackoverflow.com/users/11732320",
"pm_score": 0,
"selected": false,
"text": "Sub removeColumns()\n\nDim zRay()\nzRay = Array(\"PREVIOUS TRANSACTION ID\", \"PARENT TRANSACTION ID\", \"TRANSACTION COMMENTS\")\n\n\nDim i As Long, killRange As Range, testZone As Range, ws As Worksheet, acell As Range\n\nSet ws = ActiveSheet 'or whatever sheet you're looking at\n\n'dynmaic range of all active values in row 1\nSet testZone = Intersect(ws.UsedRange, ws.Rows(1))\n\n\nFor Each acell In testZone.Cells\n 'loops through above array values looking for exact match\n For i = LBound(zRay) To UBound(zRay)\n If zRay(i) = acell.Value Then\n 'delete it?\n If killRange Is Nothing Then\n Set killRange = acell.EntireColumn\n Else\n Set killRange = Union(acell.EntireColumn, killRange)\n End If\n Exit For\n Else\n 'keep it?\n \n End If\n Next i\n \nNext acell\n\nIf Not killRange Is Nothing Then\n killRange.Delete\nEnd If\n\nEnd Sub\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10664729/"
] |
74,575,019
|
<p>I'm having troubles trying to write intelligible <code>pandas</code> which makes me feel like I'm missing some feature or usage (probably of the <code>pd.melt</code> method).</p>
<p>I have two datasets I want to combine. Both are similar:</p>
<ul>
<li><code>time</code> indicating when the state changed</li>
<li><code>name</code> and <code>instance</code> a compound identity used to uniquely identify the record entry to a thing.</li>
<li>Finally a single value named for the state that has changed at that time for that thing.</li>
</ul>
<p>So an example record from each one of these dataset I want to combine would be:</p>
<ol>
<li><code>dict(time=0, name="a", instance=0, state=1)</code></li>
<li><code>dict(time=5, name="a", instance=0, location="london")</code></li>
</ol>
<p>I want to combine these two record sets into one, which have the last known <code>state</code> and <code>location</code> for each <code>(name, instance)</code> at each time.</p>
<pre class="lang-py prettyprint-override"><code>[
dict(time=0, name="a", instance=0, state=1, location=np.nan),
dict(time=5, name="a", instance=0, state=1, location="london"),
]
</code></pre>
<p>To get to this I currently do a combination of <code>pd.DataFrame.pivot_table</code>, <code>pd.DataFrame.ffill</code>, <code>pd.DataFrame.melt</code>, and <code>pd.DataFrame.reset_index</code>. It seems to work as intended, but it feels very cumbersome/unreadable, especially once I get into using the <code>pd.DataFrame.melt</code>.</p>
<p>I feel like I'm missing some usage for the <code>pd.DataFrame.melt</code> function, but I'm not really sure how to apply the documentation to the dataset with a <code>pd.MultiIndex</code> columns, that I'm working with, or if I'm missing some other <code>pandas</code> utility I should be using instead.</p>
<p>I'll update the question title with something more appropriate if it turns out <code>melt</code> isn't what I should be using.</p>
<p>Here's what I have:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
states = [
dict(time=0, name="a", instance=0, state=0),
dict(time=0, name="a", instance=1, state=0),
dict(time=0, name="a", instance=2, state=0),
dict(time=0, name="b", instance=1, state=0),
dict(time=0, name="b", instance=2, state=0),
dict(time=1, name="a", instance=1, state=1),
dict(time=2, name="a", instance=2, state=1),
dict(time=2, name="b", instance=1, state=1),
]
locations = [
dict(time=0, name="a", instance=0, location="tokyo"),
dict(time=0, name="a", instance=1, location="tokyo"),
dict(time=0, name="a", instance=2, location="tokyo"),
dict(time=0, name="b", instance=1, location="tokyo"),
dict(time=0, name="b", instance=2, location="tokyo"),
dict(time=1, name="a", instance=0, location="london"),
dict(time=1, name="a", instance=2, location="london"),
dict(time=1, name="b", instance=1, location="london"),
dict(time=1, name="b", instance=2, location="london"),
dict(time=1, name="a", instance=1, location="paris"),
dict(time=2, name="a", instance=2, location="paris"),
dict(time=2, name="b", instance=1, location="paris"),
]
states = pd.DataFrame.from_dict(states)
locations = pd.DataFrame.from_dict(locations)
combined = pd.concat([states, locations], axis="index")
combined = combined.pivot_table(
index="time",
columns=["name", "instance"],
values=["state", "location"],
aggfunc="last",
)
combined = combined.ffill()
ugly_melt = combined.melt(ignore_index=False)
ugly_melt = ugly_melt.rename(columns={None: "state_status"})
ugly_melt = (
ugly_melt.reset_index()
.pivot(
index=["time", "name", "instance"],
columns=["state_status"],
values="value",
)
.reset_index()
)
print(ugly_melt)
</code></pre>
|
[
{
"answer_id": 74575260,
"author": "Notus_Panda",
"author_id": 19353309,
"author_profile": "https://Stackoverflow.com/users/19353309",
"pm_score": 2,
"selected": false,
"text": "Sub deleteEmptyColumns()\n Dim lastColumn As Long\n lastColumn = Cells(1, Columns.Count).End(xlToLeft).Column\n For i = lastColumn To 1 Step -1\n If WorksheetFunction.CountA(ActiveSheet.Columns(i)) <= 1 Then ActiveSheet.Columns(i).EntireColumn.Delete\n Next\n \nEnd Sub\n"
},
{
"answer_id": 74575415,
"author": "pgSystemTester",
"author_id": 11732320,
"author_profile": "https://Stackoverflow.com/users/11732320",
"pm_score": 0,
"selected": false,
"text": "Sub removeColumns()\n\nDim zRay()\nzRay = Array(\"PREVIOUS TRANSACTION ID\", \"PARENT TRANSACTION ID\", \"TRANSACTION COMMENTS\")\n\n\nDim i As Long, killRange As Range, testZone As Range, ws As Worksheet, acell As Range\n\nSet ws = ActiveSheet 'or whatever sheet you're looking at\n\n'dynmaic range of all active values in row 1\nSet testZone = Intersect(ws.UsedRange, ws.Rows(1))\n\n\nFor Each acell In testZone.Cells\n 'loops through above array values looking for exact match\n For i = LBound(zRay) To UBound(zRay)\n If zRay(i) = acell.Value Then\n 'delete it?\n If killRange Is Nothing Then\n Set killRange = acell.EntireColumn\n Else\n Set killRange = Union(acell.EntireColumn, killRange)\n End If\n Exit For\n Else\n 'keep it?\n \n End If\n Next i\n \nNext acell\n\nIf Not killRange Is Nothing Then\n killRange.Delete\nEnd If\n\nEnd Sub\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1560414/"
] |
74,575,072
|
<p>I have a .Rmd file which I am converting to PDF. For layout reasons, I want to display the generated output plot of my code chunk on the next page even though it would just fit in underneath.</p>
<p>Normally with text etc. one would use</p>
<pre><code>\pagebreak
</code></pre>
<p>But how can I signalize the code chunk that it should display its output on the next page?
Thanks for helping!</p>
|
[
{
"answer_id": 74575328,
"author": "polkas",
"author_id": 5442527,
"author_profile": "https://Stackoverflow.com/users/5442527",
"pm_score": 0,
"selected": false,
"text": "knitr ```{r cars-plot, dev='png', fig.show='hide'}\nplot(cars)\n```\n\n\\newpage\n\n\\`)\n\n ```{r}\npng(\"NAME.png\") \n# your code to generate plot \ndev.off()\n```\n  ```{r echo=FALSE, out.width='100%', ...}\nknitr::include_graphics('PATH/NAME.png')\n```\n"
},
{
"answer_id": 74576040,
"author": "shafee",
"author_id": 10858321,
"author_profile": "https://Stackoverflow.com/users/10858321",
"pm_score": 3,
"selected": true,
"text": "knitr next_page TRUE ---\ntitle: \"Chunk Output in Next page\"\noutput: pdf_document\ndate: \"2022-11-25\"\n---\n\n```{r setup, include=FALSE}\nknitr::opts_chunk$set(echo = TRUE)\n```\n\n## R Markdown\n\n```{r, include=FALSE}\nlibrary(knitr)\n\ndefault_source_hook <- knit_hooks$get('source')\n\nknit_hooks$set(\n source = function(x, options) {\n if(isTRUE(options$next_page)) {\n paste0(default_source_hook(x, options),\n \"\\n\\n\\\\newpage\\n\\n\")\n } else {\n default_source_hook(x, options)\n }\n }\n)\n```\n\n```{r, next_page=TRUE}\nplot(mpg ~ disp, data = mtcars)\n```\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20573894/"
] |
74,575,084
|
<p>I have a df which looks like this</p>
<pre><code>Type range
Mike 10..13|7|8|
Ni 3..4
NANA 2|1|6
</code></pre>
<p>and desired output should look like this</p>
<pre><code>Type range
Mike 10
Mike 11
Mike 12
Mike 13
Mike 7
Mike 8
Nico 3
Nico 4
NANA 2
NANA 1
NANA 6
</code></pre>
<p>so, Totaling column presenet the multiple values per Type. range values are presnted with two <code>number</code> seperated by two <code>..</code> and one value (with no range) is presented between two <code>| |</code></p>
|
[
{
"answer_id": 74575328,
"author": "polkas",
"author_id": 5442527,
"author_profile": "https://Stackoverflow.com/users/5442527",
"pm_score": 0,
"selected": false,
"text": "knitr ```{r cars-plot, dev='png', fig.show='hide'}\nplot(cars)\n```\n\n\\newpage\n\n\\`)\n\n ```{r}\npng(\"NAME.png\") \n# your code to generate plot \ndev.off()\n```\n  ```{r echo=FALSE, out.width='100%', ...}\nknitr::include_graphics('PATH/NAME.png')\n```\n"
},
{
"answer_id": 74576040,
"author": "shafee",
"author_id": 10858321,
"author_profile": "https://Stackoverflow.com/users/10858321",
"pm_score": 3,
"selected": true,
"text": "knitr next_page TRUE ---\ntitle: \"Chunk Output in Next page\"\noutput: pdf_document\ndate: \"2022-11-25\"\n---\n\n```{r setup, include=FALSE}\nknitr::opts_chunk$set(echo = TRUE)\n```\n\n## R Markdown\n\n```{r, include=FALSE}\nlibrary(knitr)\n\ndefault_source_hook <- knit_hooks$get('source')\n\nknit_hooks$set(\n source = function(x, options) {\n if(isTRUE(options$next_page)) {\n paste0(default_source_hook(x, options),\n \"\\n\\n\\\\newpage\\n\\n\")\n } else {\n default_source_hook(x, options)\n }\n }\n)\n```\n\n```{r, next_page=TRUE}\nplot(mpg ~ disp, data = mtcars)\n```\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17561414/"
] |
74,575,086
|
<p>I need to pass a parameter from a parent validator to a child validator, by using <code>.SetValidator()</code> but having trouble with registering a validator to the DI container using FluentValidation's <a href="https://docs.fluentvalidation.net/en/latest/di.html#automatic-registration" rel="nofollow noreferrer">automatic registration</a>, when the validator is parameterized.</p>
<p><strong>Parent Validator</strong>:</p>
<pre><code>public class FooValidator: AbstractValidator<Foo>
{
public FooValidator()
{
RuleFor(foo => foo.Bar)
.SetValidator(foo => new BarValidator(foo.SomeStringValue))
.When(foo => foo.Bar != null);
}
}
</code></pre>
<p><strong>Child Validator:</strong></p>
<pre><code>
public class BarValidator: AbstractValidator<Bar>
{
public BarValidator(string someStringValue)
{
RuleFor(bar => bar.Baz)
.Must(BeValid(bar.Baz, someStringValue)
.When(bar => bar.Baz != null);
}
private static bool BeValid(Baz baz, string someStringValue)
{
return baz == someStringValue;
}
}
</code></pre>
<p><strong>DI registration</strong></p>
<pre><code>services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly(), ServiceLifetime.Transient);
</code></pre>
<p><strong>Error message</strong></p>
<pre><code>System.AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: FluentValidation.IValidator`1[Domain.ValueObjects.Bar] Lifetime: Transient ImplementationType: Application.Common.Validators.BarValidator':
Unable to resolve service for type 'System.String' while attempting to activate 'Application.Common.Validators.BarValidator'.)
</code></pre>
<pre><code> ---> System.InvalidOperationException: Unable to resolve service for type 'System.String' while attempting to activate 'Application.Common.Validators.BarValidator'.
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, Type serviceType, Type implementationType, CallSiteChain callSiteChain)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, Type serviceType, CallSiteChain callSiteChain, Int32 slot)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.GetCallSite(ServiceDescriptor serviceDescriptor, CallSiteChain callSiteChain)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.ValidateService(ServiceDescriptor descriptor)
--- End of inner exception stack trace ---
at Microsoft.Extensions.DependencyInjection.ServiceProvider.ValidateService(ServiceDescriptor descriptor)
at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(ICollection`1 serviceDescriptors, ServiceProviderOptions options)
--- End of inner exception stack trace ---
at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(ICollection`1 serviceDescriptors, ServiceProviderOptions options)
at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection services, ServiceProviderOptions options)
at Microsoft.Extensions.Hosting.HostApplicationBuilder.Build()
at Microsoft.AspNetCore.Builder.WebApplicationBuilder.Build()
at Program.<Main>$(String[] args) in C:\Program.cs:line 9
</code></pre>
<ul>
<li>.NET 7</li>
<li>FluentValidation v11.2.2</li>
<li>Microsoft.Extensions.DependencyInjection</li>
</ul>
<p>Any ideas?</p>
<p>Have tried circumventing the use of automatic registration by filtering it out and registering it manually, but this changes nothing.</p>
<pre><code>_ = services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly(), ServiceLifetime.Transient, filter => filter.ValidatorType != typeof(BarValidator));
_ = services.AddTransient<IValidator<Bar>>(_ => new BarValidator(""));
</code></pre>
|
[
{
"answer_id": 74575328,
"author": "polkas",
"author_id": 5442527,
"author_profile": "https://Stackoverflow.com/users/5442527",
"pm_score": 0,
"selected": false,
"text": "knitr ```{r cars-plot, dev='png', fig.show='hide'}\nplot(cars)\n```\n\n\\newpage\n\n\\`)\n\n ```{r}\npng(\"NAME.png\") \n# your code to generate plot \ndev.off()\n```\n  ```{r echo=FALSE, out.width='100%', ...}\nknitr::include_graphics('PATH/NAME.png')\n```\n"
},
{
"answer_id": 74576040,
"author": "shafee",
"author_id": 10858321,
"author_profile": "https://Stackoverflow.com/users/10858321",
"pm_score": 3,
"selected": true,
"text": "knitr next_page TRUE ---\ntitle: \"Chunk Output in Next page\"\noutput: pdf_document\ndate: \"2022-11-25\"\n---\n\n```{r setup, include=FALSE}\nknitr::opts_chunk$set(echo = TRUE)\n```\n\n## R Markdown\n\n```{r, include=FALSE}\nlibrary(knitr)\n\ndefault_source_hook <- knit_hooks$get('source')\n\nknit_hooks$set(\n source = function(x, options) {\n if(isTRUE(options$next_page)) {\n paste0(default_source_hook(x, options),\n \"\\n\\n\\\\newpage\\n\\n\")\n } else {\n default_source_hook(x, options)\n }\n }\n)\n```\n\n```{r, next_page=TRUE}\nplot(mpg ~ disp, data = mtcars)\n```\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1792207/"
] |
74,575,089
|
<p>I allocated a space of memory with malloc (to have a matrix) and I have to move the "row" at the end, I tried this:</p>
<pre><code>double **dataset = fill_dataset(....);
double* temp = malloc((d + 1) * sizeof(double ));
for (int i = 0; i < d + 1; i++) {
temp[i] = dataset[0][i];
}
memmove(&dataset[0], &dataset[1], (p_in_retained - 1) * sizeof(double *));
for (int i = 0; i < d + 1; i++) {
dataset[p_in_retained - 1][i] = temp[i];
}
</code></pre>
<p>p_in_retained is the number of rows, the problem is that when the second loop ends I have the same element in the last and the second to last element, for example, suppose that this is the initial matrix:</p>
<pre><code>id col1 col2
1 1 1
2 6 3
3 8 2
4 9 1
</code></pre>
<p>what I expect to have is the following:</p>
<pre><code>id col1 col2
2 6 3
3 8 2
4 9 1
1 1 1
</code></pre>
<p>what I get is:</p>
<pre><code>id col1 col2
2 6 3
3 8 2
1 1 1
1 1 1
</code></pre>
|
[
{
"answer_id": 74575328,
"author": "polkas",
"author_id": 5442527,
"author_profile": "https://Stackoverflow.com/users/5442527",
"pm_score": 0,
"selected": false,
"text": "knitr ```{r cars-plot, dev='png', fig.show='hide'}\nplot(cars)\n```\n\n\\newpage\n\n\\`)\n\n ```{r}\npng(\"NAME.png\") \n# your code to generate plot \ndev.off()\n```\n  ```{r echo=FALSE, out.width='100%', ...}\nknitr::include_graphics('PATH/NAME.png')\n```\n"
},
{
"answer_id": 74576040,
"author": "shafee",
"author_id": 10858321,
"author_profile": "https://Stackoverflow.com/users/10858321",
"pm_score": 3,
"selected": true,
"text": "knitr next_page TRUE ---\ntitle: \"Chunk Output in Next page\"\noutput: pdf_document\ndate: \"2022-11-25\"\n---\n\n```{r setup, include=FALSE}\nknitr::opts_chunk$set(echo = TRUE)\n```\n\n## R Markdown\n\n```{r, include=FALSE}\nlibrary(knitr)\n\ndefault_source_hook <- knit_hooks$get('source')\n\nknit_hooks$set(\n source = function(x, options) {\n if(isTRUE(options$next_page)) {\n paste0(default_source_hook(x, options),\n \"\\n\\n\\\\newpage\\n\\n\")\n } else {\n default_source_hook(x, options)\n }\n }\n)\n```\n\n```{r, next_page=TRUE}\nplot(mpg ~ disp, data = mtcars)\n```\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11999953/"
] |
74,575,127
|
<p>(I am new to Python so forgive me in advance) I have to write a program that calculates the total of integers from 1 to the user input. So if I input 4, it would add 1+2+3+4. I also added an argument that makes a number that is less than 1 print "invalid number". I am stuck on adding a sentinel that is a letter. Thank you</p>
<pre><code>value = input("Enter a number or press J to terminate: ")
if value < 1:
print("Invalid number")
else:
i = 1
while value > 1:
i = i + value
value = value - 1
print(i)
</code></pre>
<p>This is the code that I tried to do:</p>
<pre><code>value = input("Enter a number or J to finish: ")
if value < 1:
print("Invalid number")
while value ! = "J":
i = float(value)
else:
i = 1
while value > 1:
i = i + value
value = value - 1
print(i)
value = input("Enter a number or J to finish: ")
</code></pre>
<p>Error when J or any number is inputted, '<' not supported between instances of 'str' and 'int'.</p>
|
[
{
"answer_id": 74575328,
"author": "polkas",
"author_id": 5442527,
"author_profile": "https://Stackoverflow.com/users/5442527",
"pm_score": 0,
"selected": false,
"text": "knitr ```{r cars-plot, dev='png', fig.show='hide'}\nplot(cars)\n```\n\n\\newpage\n\n\\`)\n\n ```{r}\npng(\"NAME.png\") \n# your code to generate plot \ndev.off()\n```\n  ```{r echo=FALSE, out.width='100%', ...}\nknitr::include_graphics('PATH/NAME.png')\n```\n"
},
{
"answer_id": 74576040,
"author": "shafee",
"author_id": 10858321,
"author_profile": "https://Stackoverflow.com/users/10858321",
"pm_score": 3,
"selected": true,
"text": "knitr next_page TRUE ---\ntitle: \"Chunk Output in Next page\"\noutput: pdf_document\ndate: \"2022-11-25\"\n---\n\n```{r setup, include=FALSE}\nknitr::opts_chunk$set(echo = TRUE)\n```\n\n## R Markdown\n\n```{r, include=FALSE}\nlibrary(knitr)\n\ndefault_source_hook <- knit_hooks$get('source')\n\nknit_hooks$set(\n source = function(x, options) {\n if(isTRUE(options$next_page)) {\n paste0(default_source_hook(x, options),\n \"\\n\\n\\\\newpage\\n\\n\")\n } else {\n default_source_hook(x, options)\n }\n }\n)\n```\n\n```{r, next_page=TRUE}\nplot(mpg ~ disp, data = mtcars)\n```\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17678643/"
] |
74,575,147
|
<p>I have this dropdown select is working</p>
<pre><code> <select name="name" [(ngModel)]="name">
<option value="ACTIVE" [selected]="name.status=='ACTIVE' || name.status==null">Active</option>
<option value="INACTIVE" [selected]="name.status=='INACTIVE'">Inactive</option>
</select>
</code></pre>
<p>but i want if <code>name.status</code> is null then by default select <code>ACTIVE</code>.</p>
<p>This is not working.</p>
<p>Any Solution Thanks</p>
|
[
{
"answer_id": 74575297,
"author": "MoxxiManagarm",
"author_id": 11011793,
"author_profile": "https://Stackoverflow.com/users/11011793",
"pm_score": 1,
"selected": false,
"text": "ngModel selected <select [(ngModel)]=\"name.status\">\n <option value=\"ACTIVE\">Active</option>\n <option value=\"INACTIVE\">Inactive</option>\n</select>\n name: NameType;\n@Input()\nset rawName(value: NameType) {\n this.name = {\n ...value,\n status: value.status || 'ACTIVE';\n }\n}\n"
},
{
"answer_id": 74585320,
"author": "Satsangpriyadas Swami",
"author_id": 9677279,
"author_profile": "https://Stackoverflow.com/users/9677279",
"pm_score": 0,
"selected": false,
"text": "<select name=\"name\" [ngModel]=\"name.status || 'ACTIVE'\" (ngModelChange)=\"name.status=$event\">\n <option value=\"ACTIVE\">Active</option>\n <option value=\"INACTIVE\">Inactive</option>\n</select>\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3653474/"
] |
74,575,151
|
<p>I have a dataframe that includes a column ['locality_name'] with names of villages, towns, cities. Some names are written like "town of Hamilton", some like "Hamilton", some like "city of Hamilton" etc. As such, it's hard to count unique values etc. My goal is to leave the names only.</p>
<p>I want to write a function that removes the part of a string till the capital letter and then apply it to my dataframe.</p>
<p>That's what I tried:</p>
<p>import re</p>
<p>def my_slicer(row):
"""
Returns a string with the name of locality
"""
return re.sub('ABCDEFGHIKLMNOPQRSTVXYZ','', row['locality_name'])</p>
<p>raw_data['locality_name_only'] = raw_data.apply(my_slicer, axis=1)</p>
<p>I excpected it to return a new column with the names of places. Instead, nothing changed - ['locality_name_only'] has the same values as in ['locality_name'].</p>
|
[
{
"answer_id": 74575297,
"author": "MoxxiManagarm",
"author_id": 11011793,
"author_profile": "https://Stackoverflow.com/users/11011793",
"pm_score": 1,
"selected": false,
"text": "ngModel selected <select [(ngModel)]=\"name.status\">\n <option value=\"ACTIVE\">Active</option>\n <option value=\"INACTIVE\">Inactive</option>\n</select>\n name: NameType;\n@Input()\nset rawName(value: NameType) {\n this.name = {\n ...value,\n status: value.status || 'ACTIVE';\n }\n}\n"
},
{
"answer_id": 74585320,
"author": "Satsangpriyadas Swami",
"author_id": 9677279,
"author_profile": "https://Stackoverflow.com/users/9677279",
"pm_score": 0,
"selected": false,
"text": "<select name=\"name\" [ngModel]=\"name.status || 'ACTIVE'\" (ngModelChange)=\"name.status=$event\">\n <option value=\"ACTIVE\">Active</option>\n <option value=\"INACTIVE\">Inactive</option>\n</select>\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19256527/"
] |
74,575,184
|
<p>I'm unable to change background-color of list items to black while :hover.
one the other hand there is no problem with changing color.</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>.nav li {
display: inline-block;
height: 100%;
padding: 0px 35px;
border-width: 0 1px 1px 0px;
border-color: white;
border-style: solid;
box-sizing: border-box;
line-height: 37px;
background: linear-gradient(rgb(81, 59, 192) 26%, rgb(183, 172, 237))
}
.nav li:hover {
background-color: black;
color: black;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="nav">
<li>Lorem</li>
<li>Ipsum</li>
<li>dolor</li>
<li>amet</li>
</ul></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74575297,
"author": "MoxxiManagarm",
"author_id": 11011793,
"author_profile": "https://Stackoverflow.com/users/11011793",
"pm_score": 1,
"selected": false,
"text": "ngModel selected <select [(ngModel)]=\"name.status\">\n <option value=\"ACTIVE\">Active</option>\n <option value=\"INACTIVE\">Inactive</option>\n</select>\n name: NameType;\n@Input()\nset rawName(value: NameType) {\n this.name = {\n ...value,\n status: value.status || 'ACTIVE';\n }\n}\n"
},
{
"answer_id": 74585320,
"author": "Satsangpriyadas Swami",
"author_id": 9677279,
"author_profile": "https://Stackoverflow.com/users/9677279",
"pm_score": 0,
"selected": false,
"text": "<select name=\"name\" [ngModel]=\"name.status || 'ACTIVE'\" (ngModelChange)=\"name.status=$event\">\n <option value=\"ACTIVE\">Active</option>\n <option value=\"INACTIVE\">Inactive</option>\n</select>\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20479364/"
] |
74,575,197
|
<p>I'm writing a simple console application in C# using top-level statements, and I want to check at the beginning whethere there exists a database. Here's my code:</p>
<pre class="lang-csharp prettyprint-override"><code>using MySql.Data.MySqlClient;
using (MySqlConnection connection = new MySqlConnection("Server=localhost;Uid=root;Pwd=password;"))
{
connection.Open();
if (CheckDatabaseExistence(connection)) Console.WriteLine("Database Exists.");
}
bool CheckDatabaseExistence(MySqlConnection connection)
{
MySqlCommand myCommand = connection.CreateCommand();
myCommand.CommandText = "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA" +
"WHERE SCHEMA_NAME LIKE 'database_name';";
return Convert.ToInt32(myCommand.ExecuteScalar()) == 1;
}
</code></pre>
<p>After executing this code, I get the following error message:</p>
<blockquote>
<p>MySql.Data.MySqlClient.MySqlException: '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 'LIKE 'sql_store'' at line 1'</p>
</blockquote>
<p>The SQL query syntax for checking database existence is from <a href="https://dev.mysql.com/doc/refman/5.7/en/information-schema-schemata-table.html" rel="nofollow noreferrer">MySQL Documentation, Section 24.3.22</a></p>
<pre class="lang-mysql prettyprint-override"><code>SELECT SCHEMA_NAME AS `Database`
FROM INFORMATION_SCHEMA.SCHEMATA
[WHERE SCHEMA_NAME LIKE 'wild']
</code></pre>
<p>I've tried replacing <code>LIKE</code> with <code>=</code>, but I get the same error.</p>
|
[
{
"answer_id": 74575268,
"author": "vivek nuna",
"author_id": 6527049,
"author_profile": "https://Stackoverflow.com/users/6527049",
"pm_score": 1,
"selected": false,
"text": "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATAWHERE SCHEMA_NAME LIKE 'database_name'; SCHEMATAWHERE SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME LIKE 'database_name'; SHOW DATABASES LIKE 'database_name';"
},
{
"answer_id": 74576869,
"author": "user09938",
"author_id": 10024425,
"author_profile": "https://Stackoverflow.com/users/10024425",
"pm_score": 1,
"selected": true,
"text": "Console App Console App MySql.Data Application Configuration File <?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<configuration>\n <connectionStrings>\n <add name=\"MySqlConnectionAdmin\" connectionString=\"Server=localhost;Database=information_schema;Uid=test;Pwd=mySuperSecretPassword;\" />\n </connectionStrings>\n</configuration>\n using System;\nusing System.Collections.Generic;\nusing MySql.Data.MySqlClient;\nusing System.Configuration;\nusing System.Diagnostics;\n\nnamespace DatabaseMySqlTest\n{\n public class HelperMySql\n {\n public static bool CheckDatabaseExistence(string dbName)\n {\n //get connection string\n string connectionStrAdmin = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetExecutingAssembly().Location).ConnectionStrings.ConnectionStrings[\"MySqlConnectionAdmin\"].ConnectionString;\n\n using (MySqlConnection conn = new MySqlConnection(connectionStrAdmin))\n {\n //open\n conn.Open();\n\n using (MySqlCommand cmd = new MySqlCommand(\"SELECT COUNT(SCHEMA_NAME) FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME LIKE @dbName\", conn))\n {\n cmd.Parameters.Add(\"@dbName\", MySqlDbType.VarChar).Value = dbName;\n\n int count = Convert.ToInt32(cmd.ExecuteScalar());\n Debug.WriteLine($\"count: {count}\");\n\n if (count > 0)\n return true;\n }\n }\n\n return false;\n }\n }\n}\n JavaScript JSON Configuration File {\n \"ConnectionStrings\": {\n \"MySqlConnectionAdmin\": \"Server=localhost;Database=information_schema;Uid=test;Pwd=mySuperSecretPassword;\"\n }\n}\n Microsoft.Extensions.Configuration.Json using System;\nusing System.Collections.Generic;\nusing MySql.Data.MySqlClient;\nusing System.Configuration;\nusing System.Diagnostics;\nusing Microsoft.Extensions.Configuration;\n\nnamespace DatabaseMySqlTest\n{\n public class HelperMySql\n {\n public static bool CheckDatabaseExistence(string dbName)\n {\n //create new instance\n Microsoft.Extensions.Configuration.ConfigurationBuilder builder = new ConfigurationBuilder();\n builder.SetBasePath(Directory.GetCurrentDirectory());\n builder.AddJsonFile(\"appsettings.json\");\n\n IConfigurationRoot configuration = builder.Build();\n string? connectionStrAdmin = configuration.GetConnectionString(\"MySqlConnectionAdmin\");\n System.Diagnostics.Debug.WriteLine($\"connectionStrAdmin: {connectionStrAdmin}\");\n\n using (MySqlConnection conn = new MySqlConnection(connectionStrAdmin))\n {\n //open\n conn.Open();\n\n using (MySqlCommand cmd = new MySqlCommand(\"SELECT COUNT(SCHEMA_NAME) FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME LIKE @dbName\", conn))\n {\n cmd.Parameters.Add(\"@dbName\", MySqlDbType.VarChar).Value = dbName;\n\n int count = Convert.ToInt32(cmd.ExecuteScalar());\n Debug.WriteLine($\"count: {count}\");\n\n if (count > 0)\n return true;\n }\n\n }\n\n return false;\n }\n }\n}\n using System;\n\nnamespace DatabaseMySqlTest // Note: actual namespace depends on the project name.\n{\n internal class Program\n {\n static void Main(string[] args)\n {\n //ToDo: change to desired database name\n string dbName = \"testdb\";\n Console.WriteLine($\"{dbName} exists? {HelperMySql.CheckDatabaseExistence(dbName)}\");\n }\n }\n}\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20590337/"
] |
74,575,198
|
<p>I learned how to have a textbox and when the value is empty the button is disabled and when I enter a value in the textbox the button is enabled.</p>
<p>Now I want to have a login form that contains one textbox (for username) and another textbox (for password), so here I learned how to code.
But how should I write the code so that when the condition (both text boxes are empty) the button is disabled and when the condition is (both text boxes have values) the button is enabled.</p>
|
[
{
"answer_id": 74575374,
"author": "Jonathan Barraone",
"author_id": 17957703,
"author_profile": "https://Stackoverflow.com/users/17957703",
"pm_score": 2,
"selected": true,
"text": " private void txtUserName_TextChanged(object sender, EventArgs e)\n {\n CheckFields();\n }\n\n private void txtPassword_TextChanged(object sender, EventArgs e)\n {\n CheckFields();\n }\n\n private void CheckFields()\n {\n btnLogin.Enabled = txtPassword.Text.Length == 0 || txtUserName.Text.Length == 0 ? false : true;\n }\n username txtUserName password txtPassword login btnLogin btnLogin false Load private void Form1_Load(object sender, EventArgs e)\n {\n btnLogin.Enabled = false;\n }\n"
},
{
"answer_id": 74575470,
"author": "Abraham Tellez",
"author_id": 12980737,
"author_profile": "https://Stackoverflow.com/users/12980737",
"pm_score": 0,
"selected": false,
"text": "private void CheckTextboxes(object sender, EventArgs e)\n {\n if (string.IsNullOrWhiteSpace(txtUsername.Text) || string.IsNullOrWhiteSpace(txtPassword.Text)) \n {\n button.Enabled = false;\n return;\n }\n button.Enabled = true;\n }\n\nprivate void txtUsername_TextChanged(object sender, EventArgs e)\n {\n CheckTextboxes();\n }\n\nprivate void txtPassword_TextChanged(object sender, EventArgs e)\n {\n CheckTextboxes();\n }\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14348692/"
] |
74,575,200
|
<p>I have an application that runs inside a docker container. First I build the image and then run the container. My run command is:</p>
<pre><code>docker run --rm -it -e MODE=custom -e Station=RT -e StartDateReport=2022-09-10 -e Period=1 my-image:1.0.0
</code></pre>
<p>I declare the variables <code>MODE, Station, StartDateReport and Period</code> as environment variables. When I start a terminal from the container and type <code>echo $MODE</code> I will get the correct value, <code>custom</code>.</p>
<p>So far, so good, but I am interested in using these variables in a <code>bash script</code>. For example in <code>start.sh</code> I have the following code:</p>
<pre><code>#!/bin/bash
if [[ $MODE == custom ]]; then
// do sth
fi
</code></pre>
<p>and here inside the script my variable <code>MODE</code> is <code>undefined</code>, and hence I obtain wrong results.</p>
<p><strong>EDIT</strong></p>
<p>As discussed in the comments below, my application if based on a cronjob to start running.</p>
<p><strong>I managed to solve by myself the problem and the answer is in the comments.</strong></p>
|
[
{
"answer_id": 74575374,
"author": "Jonathan Barraone",
"author_id": 17957703,
"author_profile": "https://Stackoverflow.com/users/17957703",
"pm_score": 2,
"selected": true,
"text": " private void txtUserName_TextChanged(object sender, EventArgs e)\n {\n CheckFields();\n }\n\n private void txtPassword_TextChanged(object sender, EventArgs e)\n {\n CheckFields();\n }\n\n private void CheckFields()\n {\n btnLogin.Enabled = txtPassword.Text.Length == 0 || txtUserName.Text.Length == 0 ? false : true;\n }\n username txtUserName password txtPassword login btnLogin btnLogin false Load private void Form1_Load(object sender, EventArgs e)\n {\n btnLogin.Enabled = false;\n }\n"
},
{
"answer_id": 74575470,
"author": "Abraham Tellez",
"author_id": 12980737,
"author_profile": "https://Stackoverflow.com/users/12980737",
"pm_score": 0,
"selected": false,
"text": "private void CheckTextboxes(object sender, EventArgs e)\n {\n if (string.IsNullOrWhiteSpace(txtUsername.Text) || string.IsNullOrWhiteSpace(txtPassword.Text)) \n {\n button.Enabled = false;\n return;\n }\n button.Enabled = true;\n }\n\nprivate void txtUsername_TextChanged(object sender, EventArgs e)\n {\n CheckTextboxes();\n }\n\nprivate void txtPassword_TextChanged(object sender, EventArgs e)\n {\n CheckTextboxes();\n }\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16978454/"
] |
74,575,237
|
<p>I have installed Appium 2.0 using command line but unable to see the appium-webdriveragent folder under <strong>/usr/local/lib/node_modules/appium/node_modules/</strong> path (no folder found which is starts with appium).</p>
<p><strong>Theses are the following commands I ran:</strong>
npm install -g appium@next
brew install Carthage
npm install -g appium-doctor
appium --base-path /wd/hub
appium driver install xcuitest
appium plugin install images
appium plugin install execute-driver
appium plugin install relaxed-caps</p>
<p><strong>This is the appium version:</strong>
~ % appium -v
2.0.0-beta.46</p>
<p><strong>This is the driver installed location:</strong>
~ % npm ls -g appium-webdriveragent
/usr/local/lib
└── (empty)</p>
<p><strong>I am using Xcode:</strong>
Version 14.1 (14B47b)</p>
<p><strong>This is the execution failure log:</strong>
org.openqa.selenium.SessionNotCreatedException: Could not start a new session. Response code 500. Message: An unknown server-side error occurred while processing the command. <strong>Original error: Unable to launch WebDriverAgent because of xcodebuild failure: xcodebuild failed with code 65</strong>
xcodebuild error message:
. Make sure you follow the tutorial at <a href="https://github.com/appium/appium-xcuitest-driver/blob/master/docs/real-device-config.md" rel="nofollow noreferrer">https://github.com/appium/appium-xcuitest-driver/blob/master/docs/real-device-config.md</a>. Try to remove the WebDriverAgentRunner application from the device if it is installed and reboot the device.
Host info: host: 'L0057s-MacBook-Pro.local', ip: 'fe80:0:0:0:1863:fbc8:e2f5:1313%en0'
Build info: version: '4.5.0', revision: 'fe167b119a'
System info: os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '12.5.1', java.version: '18.0.1.1'
Driver info: io.appium.java_client.AppiumDriver
Command: [null, newSession {capabilities=[{appium:appName=XXXX APP, appium:automationName=XCUITest, browserName=, appium:deviceName=iPhone 6s, appium:newCommandTimeout=60, platformName=IOS, appium:platformVersion=15.7.1, appium:udid=0ee9ce6c7e262203d06348ed55de4e747cfaab75, appium:usePrebuiltWDA=true}], desiredCapabilities=Capabilities {appName: XXXX APP, automationName: XCUITest, browserName: , deviceName: iPhone 6s, newCommandTimeout: 60, platformName: IOS, platformVersion: 15.7.1, udid: XXXXXXXX1234..., usePrebuiltWDA: true}}]
Capabilities {}</p>
<p>have followed <a href="https://github.com/appium/appium" rel="nofollow noreferrer">https://github.com/appium/appium</a></p>
|
[
{
"answer_id": 74575374,
"author": "Jonathan Barraone",
"author_id": 17957703,
"author_profile": "https://Stackoverflow.com/users/17957703",
"pm_score": 2,
"selected": true,
"text": " private void txtUserName_TextChanged(object sender, EventArgs e)\n {\n CheckFields();\n }\n\n private void txtPassword_TextChanged(object sender, EventArgs e)\n {\n CheckFields();\n }\n\n private void CheckFields()\n {\n btnLogin.Enabled = txtPassword.Text.Length == 0 || txtUserName.Text.Length == 0 ? false : true;\n }\n username txtUserName password txtPassword login btnLogin btnLogin false Load private void Form1_Load(object sender, EventArgs e)\n {\n btnLogin.Enabled = false;\n }\n"
},
{
"answer_id": 74575470,
"author": "Abraham Tellez",
"author_id": 12980737,
"author_profile": "https://Stackoverflow.com/users/12980737",
"pm_score": 0,
"selected": false,
"text": "private void CheckTextboxes(object sender, EventArgs e)\n {\n if (string.IsNullOrWhiteSpace(txtUsername.Text) || string.IsNullOrWhiteSpace(txtPassword.Text)) \n {\n button.Enabled = false;\n return;\n }\n button.Enabled = true;\n }\n\nprivate void txtUsername_TextChanged(object sender, EventArgs e)\n {\n CheckTextboxes();\n }\n\nprivate void txtPassword_TextChanged(object sender, EventArgs e)\n {\n CheckTextboxes();\n }\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575237",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16087057/"
] |
74,575,280
|
<p>I want to create a script (for Google Tag Manager) that checks if an object's property is present in an array:</p>
<pre><code>var array1 = [X, Y, Z]
var array2 =
[
{item1=value1,item2=value2,item3=value3},
{item1=value1,item2=value2,item3=value3}
]
var total = 0;
</code></pre>
<p>If property 1 of the object is present in array 1, then we add property 2 in a variable to calculate the total</p>
<p>Here is my code but I think my logic is not good :</p>
<pre><code> var array1 = array1;
var array2 = array2;
var amount = 0;
for(var i=0; i<array2.length; i++) {
var propertyTarget = array2[i].item1
if(propertyTarget === array1[i]) {
total += array2[i].item2;
</code></pre>
<p>I also tested:</p>
<pre><code> for (var i = 0; i < array2.length; i++) {
for (var j = 0; j < array1.length; j++) {
if(array2[i].item1 === array1[j]) {
total += array2[i].item2;
</code></pre>
<p>I have read on other discussions that it is also possible to use filter or include but without success...</p>
<p>Your help would be very helpful</p>
|
[
{
"answer_id": 74575374,
"author": "Jonathan Barraone",
"author_id": 17957703,
"author_profile": "https://Stackoverflow.com/users/17957703",
"pm_score": 2,
"selected": true,
"text": " private void txtUserName_TextChanged(object sender, EventArgs e)\n {\n CheckFields();\n }\n\n private void txtPassword_TextChanged(object sender, EventArgs e)\n {\n CheckFields();\n }\n\n private void CheckFields()\n {\n btnLogin.Enabled = txtPassword.Text.Length == 0 || txtUserName.Text.Length == 0 ? false : true;\n }\n username txtUserName password txtPassword login btnLogin btnLogin false Load private void Form1_Load(object sender, EventArgs e)\n {\n btnLogin.Enabled = false;\n }\n"
},
{
"answer_id": 74575470,
"author": "Abraham Tellez",
"author_id": 12980737,
"author_profile": "https://Stackoverflow.com/users/12980737",
"pm_score": 0,
"selected": false,
"text": "private void CheckTextboxes(object sender, EventArgs e)\n {\n if (string.IsNullOrWhiteSpace(txtUsername.Text) || string.IsNullOrWhiteSpace(txtPassword.Text)) \n {\n button.Enabled = false;\n return;\n }\n button.Enabled = true;\n }\n\nprivate void txtUsername_TextChanged(object sender, EventArgs e)\n {\n CheckTextboxes();\n }\n\nprivate void txtPassword_TextChanged(object sender, EventArgs e)\n {\n CheckTextboxes();\n }\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20600776/"
] |
74,575,294
|
<p>I am desperate over a data analysis task that I would like to perform on a dataframe in python.
So, this is the dataframe that I have:</p>
<pre><code>df = pd.DataFrame({"Person": ["P1", "P1","P1","P1","P1","P1","P1","P1","P1","P1", "P2", "P2","P2","P2","P2","P2","P2","P2","P2","P2"],
"Activity": ["A", "A", "A", "B", "A", "A", "A", "A", "A", "A", "A", "A", "A", "B", "A", "A", "B", "A", "B", "A"],
"Time": ["0", "0", "1", "1", "1", "3", "5", "5", "6", "6", "6", "6", "6", "6", "6", "6", "6", "6", "6", "6"]
})
</code></pre>
<p>I would like</p>
<ul>
<li>to find the number of groups with more than 2 consecutive repetitive activities "A" per Person and</li>
<li>to calculate the average time of consecutive repetitive "A"s as end time minus start time for each group divided by the number of groups</li>
</ul>
<p>I.e. the targeted resulting dataframe should look like this (AVGTime for P1 calculates as (1-0 + 6-1)/2):</p>
<pre><code>solution = pd.DataFrame({"Person": ["P1", "P2"],
"Activity": ["A", "A"],
"Count": [2, 1],
"AVGTime": [3, 0]})
</code></pre>
<p>I understand there is kind of a close solution here: <a href="https://datascience-stackexchange-com.translate.goog/questions/41428/how-to-find-the-count-of-consecutive-same-string-values-in-a-pandas-dataframe?_x_tr_sl=en&_x_tr_tl=de&_x_tr_hl=de&_x_tr_pto=sc" rel="nofollow noreferrer">https://datascience-stackexchange-com.translate.goog/questions/41428/how-to-find-the-count-of-consecutive-same-string-values-in-a-pandas-dataframe?_x_tr_sl=en&_x_tr_tl=de&_x_tr_hl=de&_x_tr_pto=sc</a></p>
<p>However, the solution does not aggregate over a col, such as "Person" in my case. Also the solution does not seem to perform well given that I have a dataframe with about 7 Mio. rows.</p>
<p>I would really appreciate any hint!</p>
<pre><code></code></pre>
|
[
{
"answer_id": 74575374,
"author": "Jonathan Barraone",
"author_id": 17957703,
"author_profile": "https://Stackoverflow.com/users/17957703",
"pm_score": 2,
"selected": true,
"text": " private void txtUserName_TextChanged(object sender, EventArgs e)\n {\n CheckFields();\n }\n\n private void txtPassword_TextChanged(object sender, EventArgs e)\n {\n CheckFields();\n }\n\n private void CheckFields()\n {\n btnLogin.Enabled = txtPassword.Text.Length == 0 || txtUserName.Text.Length == 0 ? false : true;\n }\n username txtUserName password txtPassword login btnLogin btnLogin false Load private void Form1_Load(object sender, EventArgs e)\n {\n btnLogin.Enabled = false;\n }\n"
},
{
"answer_id": 74575470,
"author": "Abraham Tellez",
"author_id": 12980737,
"author_profile": "https://Stackoverflow.com/users/12980737",
"pm_score": 0,
"selected": false,
"text": "private void CheckTextboxes(object sender, EventArgs e)\n {\n if (string.IsNullOrWhiteSpace(txtUsername.Text) || string.IsNullOrWhiteSpace(txtPassword.Text)) \n {\n button.Enabled = false;\n return;\n }\n button.Enabled = true;\n }\n\nprivate void txtUsername_TextChanged(object sender, EventArgs e)\n {\n CheckTextboxes();\n }\n\nprivate void txtPassword_TextChanged(object sender, EventArgs e)\n {\n CheckTextboxes();\n }\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20600825/"
] |
74,575,299
|
<p>I have a list let suppose F = [Jonii, Max, anna, xyz, etc..] and df which contains 2 column- Name and Corrected_Name.
<a href="https://i.stack.imgur.com/k6dWr.png" rel="nofollow noreferrer">df</a></p>
<p>I need to search each string from list into df[Name] and replace it with df[Corrected_Name]. For eg. in above, code will search list in df[Name] and if found which is "Jonii" then replace it with "Jon" which is from df[Corrected_Name].
So finally output will be f = [<strong>Jon</strong>, Max, anna, xyz, etc..]</p>
<p>Thanks in advance!! I am learner so pls ignore writing mistakes.</p>
|
[
{
"answer_id": 74575512,
"author": "Pierre D",
"author_id": 758174,
"author_profile": "https://Stackoverflow.com/users/758174",
"pm_score": 1,
"selected": false,
"text": "dict d = {k: v for k, v in zip(df['Name'], df['Corrected_Name'])}\nf = [d.get(k, k) for k in F]\n df = pd.DataFrame([['a', 'b'], ['b', 'c'], ['foo', 'bar']], columns=['Name', 'Corrected_Name'])\nF = ['a', 'aa', 'b', 'hello', 'foo']\n\n# code above\n\n>>> f\n['b', 'aa', 'c', 'hello', 'bar']\n"
},
{
"answer_id": 74575596,
"author": "CozyCode",
"author_id": 13984609,
"author_profile": "https://Stackoverflow.com/users/13984609",
"pm_score": 1,
"selected": true,
"text": "import pandas as pd\n\ndf = pd.DataFrame({\"Name\": [\"Johnii\", \"Tommi\", \"Marc\"], \"CorrectedName\": [\"John\", \"Tom\", \"Mark\"]})\nnames = [\"Johnii\", \"Elizabeth\", \"Arthur\", \"Tommi\"]\n\noutput = []\nfor name in names:\n updated_value = [cn for n, cn in zip(df['Name'], df['CorrectedName']) if n == name]\n output.append(updated_value[0] if updated_value else name)\n\nprint(output)\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18620929/"
] |
74,575,307
|
<p>The case is that I have some data separated by commas that originally are two variables. One categorical and one numerical. Here you can see a sample:</p>
<pre><code>-5,50,D
-5,50,S
0,00,T
-5,50,S
-5,28,S
-5,25,C
</code></pre>
<p>As you can see in the previous sample if I separate the file by commas I get a dataset of 3 columns when there are only two:</p>
<pre><code>-5.50,D
-5.50,S
0,00,T
-5.50,S
-5.28,S
-5.25,C
</code></pre>
<p>I thought that the best idea to do it would be through a regex. Any code proposal?</p>
|
[
{
"answer_id": 74575396,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 2,
"selected": false,
"text": "tidyr::extract() library(tidyr)\n\nextract(dat, x, into = c(\"num\", \"char\"), \"(-?\\\\d*,\\\\d*),(\\\\w*)\")\n num char\n1 -5,50 D\n2 -5,50 S\n3 0,00 T\n4 -5,50 S\n5 -5,28 S\n6 -5,25 C\n dat <- data.frame(\n x = c(\"-5,50,D\", \"-5,50,S\", \"0,00,T\", \"-5,50,S\", \"-5,28,S\", \"-5,25,C\")\n)\n"
},
{
"answer_id": 74575479,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 1,
"selected": false,
"text": "library(tidyverse)\n\ndat |>\n mutate(x = sub(\"(.*)(?<=\\\\d),(?=\\\\d)(.*?$)\", \"\\\\1.\\\\2\", x, perl = TRUE)) |>\n separate(x, into = c(\"num\", \"char\"), sep = \",\")\n#> num char\n#> 1 -5.50 D\n#> 2 -5.50 S\n#> 3 0.00 T\n#> 4 -5.50 S\n#> 5 -5.28 S\n#> 6 -5.25 C\n"
},
{
"answer_id": 74575561,
"author": "Chris Ruehlemann",
"author_id": 8039978,
"author_profile": "https://Stackoverflow.com/users/8039978",
"pm_score": 1,
"selected": false,
"text": "library(tidyr)\ndat %>%\n # extract into two columns:\n extract(x, \n into = c(\"num\", \"char\"), \n regex = \"(.*),(.*)\") %>%\n # change \",\" to \".\":\n mutate(num = sub(\",\", \".\", num))\n num char\n1 -5.50 D\n2 -5.50 S\n3 0.00 T\n4 -5.50 S\n5 -5.28 S\n6 -5.25 C\n regex . dat <- data.frame(\n x = c(\"-5,50,D\", \"-5,50,S\", \"0,00,T\", \"-5,50,S\", \"-5,28,S\", \"-5,25,C\")\n )\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20503504/"
] |
74,575,329
|
<p>I have a Google sheet like this: <a href="https://i.stack.imgur.com/q5PFg.png" rel="nofollow noreferrer">spreadsheet</a> and I am trying to figure out if in column O it is possible to check if there is a value in a cell and then count all empty cells before it in the row? So for example O2 should say 3 and O3 should 5.</p>
<p>I have been trying using =COUNTBLANK for the row, but can't figure out a way to only count backwards from the first value (marked in yellow on the screenshot).</p>
|
[
{
"answer_id": 74575396,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 2,
"selected": false,
"text": "tidyr::extract() library(tidyr)\n\nextract(dat, x, into = c(\"num\", \"char\"), \"(-?\\\\d*,\\\\d*),(\\\\w*)\")\n num char\n1 -5,50 D\n2 -5,50 S\n3 0,00 T\n4 -5,50 S\n5 -5,28 S\n6 -5,25 C\n dat <- data.frame(\n x = c(\"-5,50,D\", \"-5,50,S\", \"0,00,T\", \"-5,50,S\", \"-5,28,S\", \"-5,25,C\")\n)\n"
},
{
"answer_id": 74575479,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 1,
"selected": false,
"text": "library(tidyverse)\n\ndat |>\n mutate(x = sub(\"(.*)(?<=\\\\d),(?=\\\\d)(.*?$)\", \"\\\\1.\\\\2\", x, perl = TRUE)) |>\n separate(x, into = c(\"num\", \"char\"), sep = \",\")\n#> num char\n#> 1 -5.50 D\n#> 2 -5.50 S\n#> 3 0.00 T\n#> 4 -5.50 S\n#> 5 -5.28 S\n#> 6 -5.25 C\n"
},
{
"answer_id": 74575561,
"author": "Chris Ruehlemann",
"author_id": 8039978,
"author_profile": "https://Stackoverflow.com/users/8039978",
"pm_score": 1,
"selected": false,
"text": "library(tidyr)\ndat %>%\n # extract into two columns:\n extract(x, \n into = c(\"num\", \"char\"), \n regex = \"(.*),(.*)\") %>%\n # change \",\" to \".\":\n mutate(num = sub(\",\", \".\", num))\n num char\n1 -5.50 D\n2 -5.50 S\n3 0.00 T\n4 -5.50 S\n5 -5.28 S\n6 -5.25 C\n regex . dat <- data.frame(\n x = c(\"-5,50,D\", \"-5,50,S\", \"0,00,T\", \"-5,50,S\", \"-5,28,S\", \"-5,25,C\")\n )\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4098476/"
] |
74,575,336
|
<p>I have the following function below</p>
<p>I'd like to sample from this CDF (x values) but can't find the inverse function by hand. Is there a way to do it in R?</p>
<pre><code>a <- 3.1
be <- -0.15
ga <- 0.78
delt <- 0.12
c<- 3.5
b <- exp(a+be*c*(1+c))
g <- exp((ga+delt*c)*c)
flc_F <- function(x){
#x between 0 and 1
if (x<1){
return ((b*(g-1)*(1-b^x))/(b*(g-1)+(1-b*g)*b^x))
} else {
return (1)
}
}
</code></pre>
|
[
{
"answer_id": 74575396,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 2,
"selected": false,
"text": "tidyr::extract() library(tidyr)\n\nextract(dat, x, into = c(\"num\", \"char\"), \"(-?\\\\d*,\\\\d*),(\\\\w*)\")\n num char\n1 -5,50 D\n2 -5,50 S\n3 0,00 T\n4 -5,50 S\n5 -5,28 S\n6 -5,25 C\n dat <- data.frame(\n x = c(\"-5,50,D\", \"-5,50,S\", \"0,00,T\", \"-5,50,S\", \"-5,28,S\", \"-5,25,C\")\n)\n"
},
{
"answer_id": 74575479,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 1,
"selected": false,
"text": "library(tidyverse)\n\ndat |>\n mutate(x = sub(\"(.*)(?<=\\\\d),(?=\\\\d)(.*?$)\", \"\\\\1.\\\\2\", x, perl = TRUE)) |>\n separate(x, into = c(\"num\", \"char\"), sep = \",\")\n#> num char\n#> 1 -5.50 D\n#> 2 -5.50 S\n#> 3 0.00 T\n#> 4 -5.50 S\n#> 5 -5.28 S\n#> 6 -5.25 C\n"
},
{
"answer_id": 74575561,
"author": "Chris Ruehlemann",
"author_id": 8039978,
"author_profile": "https://Stackoverflow.com/users/8039978",
"pm_score": 1,
"selected": false,
"text": "library(tidyr)\ndat %>%\n # extract into two columns:\n extract(x, \n into = c(\"num\", \"char\"), \n regex = \"(.*),(.*)\") %>%\n # change \",\" to \".\":\n mutate(num = sub(\",\", \".\", num))\n num char\n1 -5.50 D\n2 -5.50 S\n3 0.00 T\n4 -5.50 S\n5 -5.28 S\n6 -5.25 C\n regex . dat <- data.frame(\n x = c(\"-5,50,D\", \"-5,50,S\", \"0,00,T\", \"-5,50,S\", \"-5,28,S\", \"-5,25,C\")\n )\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4504877/"
] |
74,575,344
|
<p>I have a table 'processes' with the following columns :</p>
<ul>
<li>id</li>
<li>date_creation</li>
<li>date_lastrun</li>
</ul>
<p>For example I have the following entries:</p>
<pre><code>id;date_creation;date_lastrun
1;2022-01-01 00:00:00;2022-02-01 00:00:00
2;2022-03-01 00:00:00;NULL
</code></pre>
<p>I want to select the element with the bigger date in MySQL
I can do</p>
<pre><code>SELECT id, MAX(IFNULL(date_lastrun, date_creation)) as lastdate
FROM processes
</code></pre>
<p>It's OK it works but now I want to get the element with the bigger date compared to a specific date time.
I tried :</p>
<pre><code>SELECT id, MAX(IFNULL(date_lastrun, date_creation)) as lastdate
FROM processes
WHERE DATE(lastdate) > "2022-03-01"
</code></pre>
<p>but it returns *#1054 - Unknown column 'lastdate' in 'where clause'</p>
<pre><code>SELECT id, MAX(IFNULL(date_lastrun, date_creation)) as lastdate
FROM processes
WHERE DATE(MAX(IFNULL(date_lastrun, date_creation))) > "2022-03-01"
</code></pre>
<p>but it returns <em>#1111 - Invalid use of group function</em></p>
<p>Do you have any idea how to accomplish that?</p>
<p>I hope to return the element with the bigger date compared to a specific date.</p>
|
[
{
"answer_id": 74575696,
"author": "Jonas Metzler",
"author_id": 18794826,
"author_profile": "https://Stackoverflow.com/users/18794826",
"pm_score": 0,
"selected": false,
"text": "GREATEST COALESCE SELECT id, GREATEST(COALESCE(date_creation,0), COALESCE(date_lastrun,0)) AS lastdate\nFROM processes\nWHERE GREATEST(COALESCE(date_creation,0), COALESCE(date_lastrun,0)) > \"2022-03-01\";\n MAX COALESCE GREATEST NULL"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18881168/"
] |
74,575,380
|
<p>So I'm totally at a loss as to the issue here and for once can't find the answer already on here.</p>
<p>I have an access database that calls a sub in excel and runs it perfectly.
Then it flicks back to access, asks a question and then, depending upon the answer of that, should call a second sub in the same excel spreadsheet that was already open.
Both subs in excel are 'public' and both sit under "thisworkbook' and I definitely have the name of the second sub correct.
Access code is below. (xlApp is earlier defined by</p>
<pre><code> Set xlApp = CreateObject("Excel.Application")
</code></pre>
<p>I get run-time error 424 "object required" when i hit the second .run MacroName line.
Thanks</p>
<pre><code> With xlApp
.Visible = True
.Workbooks.Open progsPathName & "excel_for_plots.xlsm"
MacroName = .ActiveWorkbook.Name & "!" & "ThisWorkbook.do_the_country_stuff"
.Run MacroName
' check the labels
m = MsgBox("Are the labels ok?", vbYesNo, "Label positions")
If m = vbNo Then
MacroName = .ActiveWorkbook.Name & "!" & "ThisWorkbook.first_check"
.Run MacroName
End If
End With
</code></pre>
<p>I have tried checking the sub names, checking they are public, calling the sub something different, using the immediate window to check the 2 MacroName strings are the same except for the sub names. Always get the same error :(</p>
|
[
{
"answer_id": 74575696,
"author": "Jonas Metzler",
"author_id": 18794826,
"author_profile": "https://Stackoverflow.com/users/18794826",
"pm_score": 0,
"selected": false,
"text": "GREATEST COALESCE SELECT id, GREATEST(COALESCE(date_creation,0), COALESCE(date_lastrun,0)) AS lastdate\nFROM processes\nWHERE GREATEST(COALESCE(date_creation,0), COALESCE(date_lastrun,0)) > \"2022-03-01\";\n MAX COALESCE GREATEST NULL"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20600871/"
] |
74,575,387
|
<p>Unique values of the column as follows:</p>
<pre><code>array(['..', '0', nan, ..., '30.0378539547197', '73.3261637778593',
'59.9402466154723'], dtype=object)
</code></pre>
<p>I use the following codes to drop NaNs and None.</p>
<pre><code>df[df["Country Name"].isin([None]) == False]
</code></pre>
<p>and it still includes the NaNs.</p>
|
[
{
"answer_id": 74575696,
"author": "Jonas Metzler",
"author_id": 18794826,
"author_profile": "https://Stackoverflow.com/users/18794826",
"pm_score": 0,
"selected": false,
"text": "GREATEST COALESCE SELECT id, GREATEST(COALESCE(date_creation,0), COALESCE(date_lastrun,0)) AS lastdate\nFROM processes\nWHERE GREATEST(COALESCE(date_creation,0), COALESCE(date_lastrun,0)) > \"2022-03-01\";\n MAX COALESCE GREATEST NULL"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18049878/"
] |
74,575,389
|
<p>I have a scenario where I want to change properties of object in an array. That array is wrapped inside another object.</p>
<pre class="lang-js prettyprint-override"><code>
const defaultData = {
title: "Title",
subtitle: "Subtitle",
books: [
{
bookId: "1",
imageSrc:
"any.png",
name: "Issue",
userOwnsData: true,
panelsCollected: 0,
totalPanels: 123,
link: "https://google.com",
},
],
bgColor: "black",
};
</code></pre>
<p>When I spread it like this:</p>
<pre class="lang-js prettyprint-override"><code>{...defaultData, ...defaultData.books[0], panelsCollected:123} //previously it was 0
</code></pre>
<p>then it adds another extra object to <strong>parent object</strong> but not update it inside first index of <strong>books array</strong></p>
<p>How can I just change that <strong>panelsCollected property</strong> without disturbing whole structure as we are using typescript.</p>
<p><strong>Edit:</strong></p>
<p>We can change it directly accessing the property too as we know index but that comes with a side effect of manipulating original dataset also which we should avoid and only copy needs to be updated.</p>
<p>Thanks</p>
|
[
{
"answer_id": 74575688,
"author": "dram95",
"author_id": 13335147,
"author_profile": "https://Stackoverflow.com/users/13335147",
"pm_score": 0,
"selected": false,
"text": " console.log({...defaultData['books'][0]['panelsCollected'] = 10})\n console.log(defaultData);\n"
},
{
"answer_id": 74575690,
"author": "nate-kumar",
"author_id": 9987590,
"author_profile": "https://Stackoverflow.com/users/9987590",
"pm_score": 2,
"selected": true,
"text": "... defaultData books defaultData.books[0] panelsCollected books const defaultData = {\n title: \"Title\",\n subtitle: \"Subtitle\",\n books: [\n {\n bookId: \"1\",\n imageSrc:\n \"any.png\",\n name: \"Issue\",\n userOwnsData: true,\n panelsCollected: 0,\n totalPanels: 123,\n link: \"https://google.com\",\n },\n ],\n bgColor: \"black\",\n};\n\nconst newBook = {\n ...defaultData,\n books: [\n {\n ...defaultData.books[0],\n panelsCollected: 123\n }\n ]\n}\n\nconsole.log(newBook)\n/*\n{\n title: \"Title\",\n subtitle: \"Subtitle\",\n books: [\n {\n bookId: \"1\",\n imageSrc:\n \"any.png\",\n name: \"Issue\",\n userOwnsData: true,\n panelsCollected: 123,\n totalPanels: 123,\n link: \"https://google.com\",\n },\n ],\n bgColor: \"black\",\n};\n*/\n books find findIndex const bookToUpdateIndex = defaultData.books.findIndex(book => book.bookId === '1')\n\nconst updatedBooks = [...defaultData.books]\nupdatedBooks[bookToUpdateIndex] = {\n ...updatedBooks[bookToUpdateIndex],\n panelsCollected: 123\n}\n\nconst newBook = {\n ...defaultData,\n books: updatedBooks\n}\n"
},
{
"answer_id": 74576324,
"author": "Andy",
"author_id": 1377002,
"author_profile": "https://Stackoverflow.com/users/1377002",
"pm_score": 0,
"selected": false,
"text": "find const defaultData={title:\"Title\",subtitle:\"Subtitle\",books:[{bookId:\"1\",imageSrc:\"any.png\",name:\"Issue\",userOwnsData:!0,panelsCollected:0,totalPanels:123,link:\"https://google.com\"}],bgColor:\"black\"};\n\nconst copy = JSON.parse(JSON.stringify(defaultData));\ncopy.books[0].panelsCollected = 123;\n\nconsole.log(defaultData);\nconsole.log(copy);"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11213551/"
] |
74,575,436
|
<p>The assignment operator appears to work differently for lists than it does for integers:</p>
<pre><code>>>> list1 = [1,2,3,4,5]
>>> newlist1 = list1
>>> print(id(list1))
140282759536448
>>> print(id(newlist1))
140282759536448
>>> newlist1.append(6)
>>> print(id(newlist1))
140282759536448
>>> print(list1)
[1, 2, 3, 4, 5, 6]
>>> print(newlist1)
[1, 2, 3, 4, 5, 6]
</code></pre>
<p>The Assignment Operator works in a similar way with integers:</p>
<pre><code>>>> int1 = 1
>>> newint1 = int1
>>> print(id(int1))
140282988331248
>>> print(id(newint1))
140282988331248
</code></pre>
<p>But modifying one of the integers creates a new ID:</p>
<pre><code>>>> newint1 = newint1 + 1
>>> print(id(newint1))
140282988331280
>>> print(id(int1))
140282988331248
</code></pre>
<p>Why does modifying a list not create a new ID?</p>
<p>As well, how would you create a new ID for a list?</p>
|
[
{
"answer_id": 74575688,
"author": "dram95",
"author_id": 13335147,
"author_profile": "https://Stackoverflow.com/users/13335147",
"pm_score": 0,
"selected": false,
"text": " console.log({...defaultData['books'][0]['panelsCollected'] = 10})\n console.log(defaultData);\n"
},
{
"answer_id": 74575690,
"author": "nate-kumar",
"author_id": 9987590,
"author_profile": "https://Stackoverflow.com/users/9987590",
"pm_score": 2,
"selected": true,
"text": "... defaultData books defaultData.books[0] panelsCollected books const defaultData = {\n title: \"Title\",\n subtitle: \"Subtitle\",\n books: [\n {\n bookId: \"1\",\n imageSrc:\n \"any.png\",\n name: \"Issue\",\n userOwnsData: true,\n panelsCollected: 0,\n totalPanels: 123,\n link: \"https://google.com\",\n },\n ],\n bgColor: \"black\",\n};\n\nconst newBook = {\n ...defaultData,\n books: [\n {\n ...defaultData.books[0],\n panelsCollected: 123\n }\n ]\n}\n\nconsole.log(newBook)\n/*\n{\n title: \"Title\",\n subtitle: \"Subtitle\",\n books: [\n {\n bookId: \"1\",\n imageSrc:\n \"any.png\",\n name: \"Issue\",\n userOwnsData: true,\n panelsCollected: 123,\n totalPanels: 123,\n link: \"https://google.com\",\n },\n ],\n bgColor: \"black\",\n};\n*/\n books find findIndex const bookToUpdateIndex = defaultData.books.findIndex(book => book.bookId === '1')\n\nconst updatedBooks = [...defaultData.books]\nupdatedBooks[bookToUpdateIndex] = {\n ...updatedBooks[bookToUpdateIndex],\n panelsCollected: 123\n}\n\nconst newBook = {\n ...defaultData,\n books: updatedBooks\n}\n"
},
{
"answer_id": 74576324,
"author": "Andy",
"author_id": 1377002,
"author_profile": "https://Stackoverflow.com/users/1377002",
"pm_score": 0,
"selected": false,
"text": "find const defaultData={title:\"Title\",subtitle:\"Subtitle\",books:[{bookId:\"1\",imageSrc:\"any.png\",name:\"Issue\",userOwnsData:!0,panelsCollected:0,totalPanels:123,link:\"https://google.com\"}],bgColor:\"black\"};\n\nconst copy = JSON.parse(JSON.stringify(defaultData));\ncopy.books[0].panelsCollected = 123;\n\nconsole.log(defaultData);\nconsole.log(copy);"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11805477/"
] |
74,575,439
|
<p><a href="https://i.stack.imgur.com/8wLmc.png" rel="nofollow noreferrer">example of output should be </a></p>
<p>please help thank you in advance!!</p>
<p>the output of the code in username should be the 2 letter in firt name and 3 in last name and date number</p>
<pre><code>public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("Enter Fullname:");
String fullname = sc.nextLine();
System.out.println("Enter Birthday : ");
String bday = sc.nextLine();
System.out.println("Your Login Details");
System.out.println("Enter Fullname:" + fullname);
System.out.println("Enter Birthday : " + bday);
System.out.println("Enter Username: " + );
}
}
</code></pre>
|
[
{
"answer_id": 74575688,
"author": "dram95",
"author_id": 13335147,
"author_profile": "https://Stackoverflow.com/users/13335147",
"pm_score": 0,
"selected": false,
"text": " console.log({...defaultData['books'][0]['panelsCollected'] = 10})\n console.log(defaultData);\n"
},
{
"answer_id": 74575690,
"author": "nate-kumar",
"author_id": 9987590,
"author_profile": "https://Stackoverflow.com/users/9987590",
"pm_score": 2,
"selected": true,
"text": "... defaultData books defaultData.books[0] panelsCollected books const defaultData = {\n title: \"Title\",\n subtitle: \"Subtitle\",\n books: [\n {\n bookId: \"1\",\n imageSrc:\n \"any.png\",\n name: \"Issue\",\n userOwnsData: true,\n panelsCollected: 0,\n totalPanels: 123,\n link: \"https://google.com\",\n },\n ],\n bgColor: \"black\",\n};\n\nconst newBook = {\n ...defaultData,\n books: [\n {\n ...defaultData.books[0],\n panelsCollected: 123\n }\n ]\n}\n\nconsole.log(newBook)\n/*\n{\n title: \"Title\",\n subtitle: \"Subtitle\",\n books: [\n {\n bookId: \"1\",\n imageSrc:\n \"any.png\",\n name: \"Issue\",\n userOwnsData: true,\n panelsCollected: 123,\n totalPanels: 123,\n link: \"https://google.com\",\n },\n ],\n bgColor: \"black\",\n};\n*/\n books find findIndex const bookToUpdateIndex = defaultData.books.findIndex(book => book.bookId === '1')\n\nconst updatedBooks = [...defaultData.books]\nupdatedBooks[bookToUpdateIndex] = {\n ...updatedBooks[bookToUpdateIndex],\n panelsCollected: 123\n}\n\nconst newBook = {\n ...defaultData,\n books: updatedBooks\n}\n"
},
{
"answer_id": 74576324,
"author": "Andy",
"author_id": 1377002,
"author_profile": "https://Stackoverflow.com/users/1377002",
"pm_score": 0,
"selected": false,
"text": "find const defaultData={title:\"Title\",subtitle:\"Subtitle\",books:[{bookId:\"1\",imageSrc:\"any.png\",name:\"Issue\",userOwnsData:!0,panelsCollected:0,totalPanels:123,link:\"https://google.com\"}],bgColor:\"black\"};\n\nconst copy = JSON.parse(JSON.stringify(defaultData));\ncopy.books[0].panelsCollected = 123;\n\nconsole.log(defaultData);\nconsole.log(copy);"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20068089/"
] |
74,575,458
|
<p>I have a function:</p>
<pre><code>with open(filename,'r') as text:
data=text.readlines()
split=str(data).split('([.|?])')
for line in split:
print(line)
</code></pre>
<p>This prints the sentences that we have after splitting a text by 2 different marks. I also want to show the split symbol in the output, this is why I use <code>()</code> but the split do not work fine.</p>
<p>It returns:</p>
<pre><code>['Chapter 16. My new goal. \n','Chapter 17. My new goal 2. \n']
</code></pre>
<p>As you can see the split haven't splitted by all dots.</p>
|
[
{
"answer_id": 74575688,
"author": "dram95",
"author_id": 13335147,
"author_profile": "https://Stackoverflow.com/users/13335147",
"pm_score": 0,
"selected": false,
"text": " console.log({...defaultData['books'][0]['panelsCollected'] = 10})\n console.log(defaultData);\n"
},
{
"answer_id": 74575690,
"author": "nate-kumar",
"author_id": 9987590,
"author_profile": "https://Stackoverflow.com/users/9987590",
"pm_score": 2,
"selected": true,
"text": "... defaultData books defaultData.books[0] panelsCollected books const defaultData = {\n title: \"Title\",\n subtitle: \"Subtitle\",\n books: [\n {\n bookId: \"1\",\n imageSrc:\n \"any.png\",\n name: \"Issue\",\n userOwnsData: true,\n panelsCollected: 0,\n totalPanels: 123,\n link: \"https://google.com\",\n },\n ],\n bgColor: \"black\",\n};\n\nconst newBook = {\n ...defaultData,\n books: [\n {\n ...defaultData.books[0],\n panelsCollected: 123\n }\n ]\n}\n\nconsole.log(newBook)\n/*\n{\n title: \"Title\",\n subtitle: \"Subtitle\",\n books: [\n {\n bookId: \"1\",\n imageSrc:\n \"any.png\",\n name: \"Issue\",\n userOwnsData: true,\n panelsCollected: 123,\n totalPanels: 123,\n link: \"https://google.com\",\n },\n ],\n bgColor: \"black\",\n};\n*/\n books find findIndex const bookToUpdateIndex = defaultData.books.findIndex(book => book.bookId === '1')\n\nconst updatedBooks = [...defaultData.books]\nupdatedBooks[bookToUpdateIndex] = {\n ...updatedBooks[bookToUpdateIndex],\n panelsCollected: 123\n}\n\nconst newBook = {\n ...defaultData,\n books: updatedBooks\n}\n"
},
{
"answer_id": 74576324,
"author": "Andy",
"author_id": 1377002,
"author_profile": "https://Stackoverflow.com/users/1377002",
"pm_score": 0,
"selected": false,
"text": "find const defaultData={title:\"Title\",subtitle:\"Subtitle\",books:[{bookId:\"1\",imageSrc:\"any.png\",name:\"Issue\",userOwnsData:!0,panelsCollected:0,totalPanels:123,link:\"https://google.com\"}],bgColor:\"black\"};\n\nconst copy = JSON.parse(JSON.stringify(defaultData));\ncopy.books[0].panelsCollected = 123;\n\nconsole.log(defaultData);\nconsole.log(copy);"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5556466/"
] |
74,575,484
|
<p>I wrote a function with clsql. All it does is read the entire table. First it opens the connection, reads, then closes.</p>
<pre class="lang-lisp prettyprint-override"><code>(defun select()
(clsql:connect "new.db" :database-type :sqlite3)
(clsql:print-query
"select * from contacts"
:titles '("id" "firstname" "email" "company" "firstline" "status"))
(clsql:disconnect :database "new.db"))
</code></pre>
<p>With the <code>disconnect</code> expression last, I get <code>T</code> as the return value.</p>
<p>I want to get the value of <code>clsql:print-query</code> returned. However, the disconnection should go last because I need to make sure the connection closes.</p>
<p>I tried <code>block</code> and <code>return-with</code>, with no luck.</p>
<p>What is the best way to approach returning values</p>
|
[
{
"answer_id": 74575578,
"author": "Rainer Joswig",
"author_id": 69545,
"author_profile": "https://Stackoverflow.com/users/69545",
"pm_score": 4,
"selected": true,
"text": "UNWIND-PROTECT (unwind-protect (read-the-file stream)\n (print \"closing\")\n (close stream))\n CL-USER 41 > (unwind-protect (progn ; protected form\n (print \"doing-something\")\n (values))\n (print \"ensuring safety\")) ; this WILL run\n\n\"doing-something\" \n\"ensuring safety\" \n CL-USER 42 > (unwind-protect (progn\n (error \"foo\")\n (print \"doing-something\")\n (values))\n (print \"ensuring safety\"))\n\nError: foo\n 1 (abort) Return to top loop level 0.\n\nType :b for backtrace or :c <option number> to proceed.\nType :bug-form \"<subject>\" for a bug report template or :? for other options.\n\nCL-USER 43 : 1 > :c 1 ; ABORTING\n\n\"ensuring safety\" \n CL-USER 44 > (prog1\n (sin 3)\n (print \"hello\"))\n\n\"hello\" \n0.14112\n (let ((temp1 (sin 3)))\n (print \"hello\")\n temp1)\n (defun select()\n (clsql:connect \"new.db\" :database-type :sqlite3)\n (unwind-protect\n (clsql:print-query\n \"select * from contacts\"\n :titles '(\"id\" \"firstname\" \"email\" \"company\" \"firstline\" \"status\"))\n (clsql:disconnect :database \"new.db\")))\n"
},
{
"answer_id": 74584576,
"author": "Ehvince",
"author_id": 1506338,
"author_profile": "https://Stackoverflow.com/users/1506338",
"pm_score": 2,
"selected": false,
"text": "clsql:with-database unwind-protect (clsql:with-database (db '(\"new.db\") :database-type :sqlite3\n :make-default nil)\n (clsql:database-name db))\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16237416/"
] |
74,575,504
|
<p>The following <strong>SecurityWebFilterChain</strong> works very fine in Spring Boot 2.7.x but not working any more in Spring Boot 3.0.0. It just show "<strong>An expected CSRF token cannot be found</strong>" when calling the REST API in Postman. Would you please to teach me how to solve it?</p>
<pre><code>@Bean
public SecurityWebFilterChain securitygWebFilterChain(ServerHttpSecurity http) {
http
.cors().disable()
.csrf().disable()
.exceptionHandling()
.authenticationEntryPoint((swe, e) ->
Mono.fromRunnable(() -> swe.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED))
).accessDeniedHandler((swe, e) ->
Mono.fromRunnable(() -> swe.getResponse().setStatusCode(HttpStatus.FORBIDDEN))
)
.and()
.authenticationManager(authenticationManager)
.securityContextRepository(securityContextRepository)
.authorizeExchange(exchange -> exchange
.pathMatchers(HttpMethod.OPTIONS).permitAll()
.pathMatchers("/login", "/register").permitAll()
.anyExchange().authenticated()
.and()
.cors().disable()
.csrf().disable()
)
.formLogin().disable()
.httpBasic().disable()
;
return http.csrf(csrf -> csrf.disable()).build();
}
</code></pre>
<p><a href="https://i.stack.imgur.com/VgzqV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VgzqV.png" alt="Postman screen capture" /></a></p>
|
[
{
"answer_id": 74575578,
"author": "Rainer Joswig",
"author_id": 69545,
"author_profile": "https://Stackoverflow.com/users/69545",
"pm_score": 4,
"selected": true,
"text": "UNWIND-PROTECT (unwind-protect (read-the-file stream)\n (print \"closing\")\n (close stream))\n CL-USER 41 > (unwind-protect (progn ; protected form\n (print \"doing-something\")\n (values))\n (print \"ensuring safety\")) ; this WILL run\n\n\"doing-something\" \n\"ensuring safety\" \n CL-USER 42 > (unwind-protect (progn\n (error \"foo\")\n (print \"doing-something\")\n (values))\n (print \"ensuring safety\"))\n\nError: foo\n 1 (abort) Return to top loop level 0.\n\nType :b for backtrace or :c <option number> to proceed.\nType :bug-form \"<subject>\" for a bug report template or :? for other options.\n\nCL-USER 43 : 1 > :c 1 ; ABORTING\n\n\"ensuring safety\" \n CL-USER 44 > (prog1\n (sin 3)\n (print \"hello\"))\n\n\"hello\" \n0.14112\n (let ((temp1 (sin 3)))\n (print \"hello\")\n temp1)\n (defun select()\n (clsql:connect \"new.db\" :database-type :sqlite3)\n (unwind-protect\n (clsql:print-query\n \"select * from contacts\"\n :titles '(\"id\" \"firstname\" \"email\" \"company\" \"firstline\" \"status\"))\n (clsql:disconnect :database \"new.db\")))\n"
},
{
"answer_id": 74584576,
"author": "Ehvince",
"author_id": 1506338,
"author_profile": "https://Stackoverflow.com/users/1506338",
"pm_score": 2,
"selected": false,
"text": "clsql:with-database unwind-protect (clsql:with-database (db '(\"new.db\") :database-type :sqlite3\n :make-default nil)\n (clsql:database-name db))\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3156889/"
] |
74,575,522
|
<p>I have two lists.</p>
<p>List1 is the list of items I am trying to format</p>
<p>List2 is a list of item locations in List1 that I need to remove (condensing duplicates)</p>
<p>The issue seems to be that it first removes the first location (9) and then removes the second (16) after...instead of doing them simultaneously. After it removes 9, the list is changed and 16 is removed in a different intended location because of that.</p>
<pre><code>List1 = ["HST", "BA", "CRM", "QQQ", "IYR", "TDG", "HD", "TDY", "UAL", "CRM", "XOM", "CCL", "LLY", "QCOM", "UPS", "MPW", "CCL", "ILMN", "MU", "GOOGL", "AXP", "IVZ", "WY"]
List2 = [9, 16]
print(List1)
print(List2)
for x in List2:
List1.pop(x)
print(List1)
</code></pre>
|
[
{
"answer_id": 74575639,
"author": "Jonas",
"author_id": 20599721,
"author_profile": "https://Stackoverflow.com/users/20599721",
"pm_score": 1,
"selected": false,
"text": "sorted(List2, key=List2.index, reverse=True) List1 = [\"HST\", \"BA\", \"CRM\", \"QQQ\", \"IYR\", \"TDG\", \"HD\", \"TDY\", \"UAL\", \"CRM\", \"XOM\", \"CCL\", \"LLY\", \"QCOM\", \"UPS\", \"MPW\", \"CCL\", \"ILMN\", \"MU\", \"GOOGL\", \"AXP\", \"IVZ\", \"WY\"]\nList2 = [9, 16]\n\nList2 = sorted(List2, key=List2.index, reverse=True)\nfor x in List2:\n List1.pop(x)\n\nprint(List1)\n\n"
},
{
"answer_id": 74575640,
"author": "Ulisse Rubizzo",
"author_id": 4412510,
"author_profile": "https://Stackoverflow.com/users/4412510",
"pm_score": 1,
"selected": true,
"text": "List1 = [\"HST\", \"BA\", \"CRM\", \"QQQ\", \"IYR\", \"TDG\", \"HD\", \"TDY\", \"UAL\", \"CRM\", \"XOM\", \"CCL\", \"LLY\", \"QCOM\", \"UPS\", \"MPW\", \"CCL\", \"ILMN\", \"MU\", \"GOOGL\", \"AXP\", \"IVZ\", \"WY\"]\nList2 = [9, 16]\n\nprint(List1)\nprint(List2)\n\n\nfor i, x in enumerate(List2):\n List1.pop(x-i)\n\nprint(List1)\n"
},
{
"answer_id": 74575642,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 0,
"selected": false,
"text": "S = set(List2)\n\nout = [x for i, x in enumerate(List1) if i not in S]\n"
},
{
"answer_id": 74575660,
"author": "Davi A. Sampaio",
"author_id": 14593213,
"author_profile": "https://Stackoverflow.com/users/14593213",
"pm_score": 0,
"selected": false,
"text": "for i, j in enumerate(list2):\n list1.pop(i - j)\n enumerate"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14775158/"
] |
74,575,523
|
<p>I have this program that reads a file and prints the desired amount of most common words. I don't know how to print the words that appear the same amount of times.</p>
<p>Here's my code:</p>
<pre><code>number_of_words = int(input('Enter how many top words you want to see: '))
uniques = []
stop_words = ["a", "an", "and", "in", "is"]
for word in words:
check_special = False
if word.isalnum():
check_special = True
if word not in uniques and word not in stop_words and check_special:
uniques.append(word)
counts = []
for unique in uniques:
count = 0
for word in words:
if word == unique:
count += 1
counts.append((count, unique))
counts.sort()
counts.reverse()
for i in range(min(number_of_words, len(counts))):
count, word = counts[i]
print('The following words appeared %d each: %s ' % (count, word))
</code></pre>
<p>As a demo it prints:</p>
<pre><code>The following words appeared 11 each: night
The following words appeared 11 each: go
</code></pre>
<p>I want the output to be:</p>
<pre><code>The following words appeared 11 each: go, night
</code></pre>
<p>How can I achieve this?</p>
|
[
{
"answer_id": 74575644,
"author": "Usman Arshad",
"author_id": 20582506,
"author_profile": "https://Stackoverflow.com/users/20582506",
"pm_score": 1,
"selected": false,
"text": "count_with_word = {}\nfor i in range(min(number_of_words, len(counts))):\n count, word = counts[i]\n if count in count_with_word:\n count_with_word[count].append(word)\n else:\n count_with_word[count] = [word]\n\nfor count, words in count_with_word.items():\n print('The following words appeared %d each: %s ' % (count, ', '.join(words)))\n The following words appeared 2 each: t1, t2"
},
{
"answer_id": 74575715,
"author": "JayPeerachai",
"author_id": 12135518,
"author_profile": "https://Stackoverflow.com/users/12135518",
"pm_score": 0,
"selected": false,
"text": "dict counts_dict = {count: [] for count, word in counts}\nfor count, word in counts:\n counts_dict[count].append(word)\n\ncount_num_word = 0\nfor count in counts_dict:\n if count_num_word >= number_of_words:\n break\n print('The following words appeared %d each: %s ' % (count, ', '.join(counts_dict[count])))\n count_num_word += len(counts_dict[count])\n words = ['B', 'B', 'A', 'A', 'C']\n\n> Enter how many top words you want to see: 3\n> The following words appeared 2 each: B, A \n> The following words appeared 1 each: C \n\n> Enter how many top words you want to see: 2\n> The following words appeared 2 each: B, A \n\n> Enter how many top words you want to see: 1\n> The following words appeared 2 each: B, A \n number_of_words"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20238116/"
] |
74,575,556
|
<p>I have this problem and I know that it can be carried out in several ways.</p>
<p>Assume that the returns of a security X are distributed according to a normal law with mean
m=0 and standard deviation s=5.</p>
<ul>
<li>What is the value at risk at 1 percent (i.e., that minimum value below which it will go in 1
percent of the cases)?</li>
</ul>
<p>I solved it this way but I would like to know if there are other ways</p>
<pre><code>qnorm(0.01,mean=0,sd=5)
pnorm(-11.63174,mean=0,sd=5)
</code></pre>
|
[
{
"answer_id": 74575644,
"author": "Usman Arshad",
"author_id": 20582506,
"author_profile": "https://Stackoverflow.com/users/20582506",
"pm_score": 1,
"selected": false,
"text": "count_with_word = {}\nfor i in range(min(number_of_words, len(counts))):\n count, word = counts[i]\n if count in count_with_word:\n count_with_word[count].append(word)\n else:\n count_with_word[count] = [word]\n\nfor count, words in count_with_word.items():\n print('The following words appeared %d each: %s ' % (count, ', '.join(words)))\n The following words appeared 2 each: t1, t2"
},
{
"answer_id": 74575715,
"author": "JayPeerachai",
"author_id": 12135518,
"author_profile": "https://Stackoverflow.com/users/12135518",
"pm_score": 0,
"selected": false,
"text": "dict counts_dict = {count: [] for count, word in counts}\nfor count, word in counts:\n counts_dict[count].append(word)\n\ncount_num_word = 0\nfor count in counts_dict:\n if count_num_word >= number_of_words:\n break\n print('The following words appeared %d each: %s ' % (count, ', '.join(counts_dict[count])))\n count_num_word += len(counts_dict[count])\n words = ['B', 'B', 'A', 'A', 'C']\n\n> Enter how many top words you want to see: 3\n> The following words appeared 2 each: B, A \n> The following words appeared 1 each: C \n\n> Enter how many top words you want to see: 2\n> The following words appeared 2 each: B, A \n\n> Enter how many top words you want to see: 1\n> The following words appeared 2 each: B, A \n number_of_words"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16168529/"
] |
74,575,557
|
<p>I need to bind a formControl to a form with a formGroup without being nested into it, and keeping the default mat-errot error state matching.</p>
<p>I have tried</p>
<p>app.component.html</p>
<pre><code><form [formGroup]="formAdd" (ngSubmit)="onSubmit()"></form>
<!-- somewhere else in the same file -->
<mat-form-field>
<input matInput [formControl]="formAdd.controls.username">
<mat-error>Username is required</mat-error>
</mat-form-field>
</code></pre>
<p>app.component.ts</p>
<pre><code>ngOnInit(): void {
this.formAdd = this._formBuilder.group({
username: ['', [Validators.required]]
});
}
</code></pre>
<p>However when I do it like that, the mat-error doesn't appear when the form is submitted and the input is empty. I can't put the input inside the form as it goes inside a custom component with other inputs not related to the form.</p>
<p>Inspecting further, the errorStateMatcher says that the form of the control is null and so it cannot check if it is submitted or not, and so it never shows the mat-error.</p>
<p>Is there a way to bind an input to an external form and keeping the validation logic?</p>
|
[
{
"answer_id": 74575644,
"author": "Usman Arshad",
"author_id": 20582506,
"author_profile": "https://Stackoverflow.com/users/20582506",
"pm_score": 1,
"selected": false,
"text": "count_with_word = {}\nfor i in range(min(number_of_words, len(counts))):\n count, word = counts[i]\n if count in count_with_word:\n count_with_word[count].append(word)\n else:\n count_with_word[count] = [word]\n\nfor count, words in count_with_word.items():\n print('The following words appeared %d each: %s ' % (count, ', '.join(words)))\n The following words appeared 2 each: t1, t2"
},
{
"answer_id": 74575715,
"author": "JayPeerachai",
"author_id": 12135518,
"author_profile": "https://Stackoverflow.com/users/12135518",
"pm_score": 0,
"selected": false,
"text": "dict counts_dict = {count: [] for count, word in counts}\nfor count, word in counts:\n counts_dict[count].append(word)\n\ncount_num_word = 0\nfor count in counts_dict:\n if count_num_word >= number_of_words:\n break\n print('The following words appeared %d each: %s ' % (count, ', '.join(counts_dict[count])))\n count_num_word += len(counts_dict[count])\n words = ['B', 'B', 'A', 'A', 'C']\n\n> Enter how many top words you want to see: 3\n> The following words appeared 2 each: B, A \n> The following words appeared 1 each: C \n\n> Enter how many top words you want to see: 2\n> The following words appeared 2 each: B, A \n\n> Enter how many top words you want to see: 1\n> The following words appeared 2 each: B, A \n number_of_words"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14184507/"
] |
74,575,570
|
<p>I have a list <code>testEle</code> which contains 100 elements. I am iterating over it an need to filter only the values which contains anyone of elements in second list <code>finalList</code> {a1,a2,a3...so on}</p>
<pre><code>testEle.stream().filter( x -> x.matches(// any one of finalList element here))
</code></pre>
<p>I am not sure what should be inside the <code>.matches()</code> or if I should be using something else ?</p>
|
[
{
"answer_id": 74575644,
"author": "Usman Arshad",
"author_id": 20582506,
"author_profile": "https://Stackoverflow.com/users/20582506",
"pm_score": 1,
"selected": false,
"text": "count_with_word = {}\nfor i in range(min(number_of_words, len(counts))):\n count, word = counts[i]\n if count in count_with_word:\n count_with_word[count].append(word)\n else:\n count_with_word[count] = [word]\n\nfor count, words in count_with_word.items():\n print('The following words appeared %d each: %s ' % (count, ', '.join(words)))\n The following words appeared 2 each: t1, t2"
},
{
"answer_id": 74575715,
"author": "JayPeerachai",
"author_id": 12135518,
"author_profile": "https://Stackoverflow.com/users/12135518",
"pm_score": 0,
"selected": false,
"text": "dict counts_dict = {count: [] for count, word in counts}\nfor count, word in counts:\n counts_dict[count].append(word)\n\ncount_num_word = 0\nfor count in counts_dict:\n if count_num_word >= number_of_words:\n break\n print('The following words appeared %d each: %s ' % (count, ', '.join(counts_dict[count])))\n count_num_word += len(counts_dict[count])\n words = ['B', 'B', 'A', 'A', 'C']\n\n> Enter how many top words you want to see: 3\n> The following words appeared 2 each: B, A \n> The following words appeared 1 each: C \n\n> Enter how many top words you want to see: 2\n> The following words appeared 2 each: B, A \n\n> Enter how many top words you want to see: 1\n> The following words appeared 2 each: B, A \n number_of_words"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13983643/"
] |
74,575,595
|
<p>I am building REST APIs in Nodejs using AWS. I am expecting a response on Postman saying that the
"</p>
<pre><code>Your Bid Must Be Higher than ${auction.highestBid.amount}
</code></pre>
<p>"
But instead, I get an Internal Server Error on Postman and the error on AWS Cloudwatch looks like:
<a href="https://i.stack.imgur.com/ocZYE.png" rel="nofollow noreferrer">enter image description here</a>.
However, I am sending a request on Postman as:
<a href="https://i.stack.imgur.com/DwfdE.png" rel="nofollow noreferrer">enter image description here</a>
Please help!!</p>
<p>I am Expecting the response as:
Your bid must be higher than</p>
<pre><code>${auction.highestBid.amount}
</code></pre>
<p>The patch request body looks like:
<a href="https://i.stack.imgur.com/COK0N.png" rel="nofollow noreferrer">enter image description here</a>
While the create Request looks like:
<a href="https://i.stack.imgur.com/W7RUk.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>//placeBid.js</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const AWS = require('aws-sdk');
const createError = require('http-errors');
const {getAuctionById} = require('./getAuction');
const dynamodb = new AWS.DynamoDB.DocumentClient();
async function placeBid(req) {
const { id } = req.pathParameters;
const { amount } = JSON.parse(req.body);
const auction = getAuctionById(id);
if(amount <= auction.highestBid.amount)
throw new createError.Forbidden(`Your Bid Must Be Higher than ${auction.highestBid.amount}`);
const params = {
TableName: 'AuctionsTable',
Key : {id},
UpdateExpression : 'set highestBid.amount = :amount',
ExpressionAttributeValues: {
':amount' : amount
},
ReturnValues : 'ALL_NEW'
}
let updatedAuction;
try {
const result = await dynamodb.update(params).promise();
updatedAuction = result.Attributes;
} catch (error) {
console.error(error);
throw new createError.InternalServerError(error);
}
return{
statusCode : 200,
body : JSON.stringify(updatedAuction)
}
}
module.exports.handler = placeBid;</code></pre>
</div>
</div>
</p>
<p>//getAuction.js</p>
<pre class="lang-js prettyprint-override"><code>const AWS = require('aws-sdk');
const createError = require('http-errors');
const dynamodb = new AWS.DynamoDB.DocumentClient();
module.exports.getAuctionById = async(id) => {
let auction;
try {
const result = await dynamodb.get({
TableName : 'AuctionsTable',
Key : {id}
}).promise()
auction = result.Item;
} catch (error) {
console.error(error);
throw new createError.InternalServerError(error);
}
if(!auction){
throw new createError.NotFound(`Auction with ID ${id} not found`);
}
return auction;
}
async function getAuction(req) {
const { id } = req.pathParameters;
const auction = await getAuctionById(id);
return{
statusCode : 200,
body : JSON.stringify(auction)
}
}
module.exports.handler = getAuction
</code></pre>
|
[
{
"answer_id": 74575644,
"author": "Usman Arshad",
"author_id": 20582506,
"author_profile": "https://Stackoverflow.com/users/20582506",
"pm_score": 1,
"selected": false,
"text": "count_with_word = {}\nfor i in range(min(number_of_words, len(counts))):\n count, word = counts[i]\n if count in count_with_word:\n count_with_word[count].append(word)\n else:\n count_with_word[count] = [word]\n\nfor count, words in count_with_word.items():\n print('The following words appeared %d each: %s ' % (count, ', '.join(words)))\n The following words appeared 2 each: t1, t2"
},
{
"answer_id": 74575715,
"author": "JayPeerachai",
"author_id": 12135518,
"author_profile": "https://Stackoverflow.com/users/12135518",
"pm_score": 0,
"selected": false,
"text": "dict counts_dict = {count: [] for count, word in counts}\nfor count, word in counts:\n counts_dict[count].append(word)\n\ncount_num_word = 0\nfor count in counts_dict:\n if count_num_word >= number_of_words:\n break\n print('The following words appeared %d each: %s ' % (count, ', '.join(counts_dict[count])))\n count_num_word += len(counts_dict[count])\n words = ['B', 'B', 'A', 'A', 'C']\n\n> Enter how many top words you want to see: 3\n> The following words appeared 2 each: B, A \n> The following words appeared 1 each: C \n\n> Enter how many top words you want to see: 2\n> The following words appeared 2 each: B, A \n\n> Enter how many top words you want to see: 1\n> The following words appeared 2 each: B, A \n number_of_words"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14062271/"
] |
74,575,599
|
<p>I'm trying to query a table using <code>pandas.read_sql_query</code>, where I want to match multiple columns to python lists passed in as <code>param</code> arguments. Running into various <code>psycopg2</code> errors when trying to accomplish this.</p>
<p>Ideally, I would provide a reproducible example, but unfortunately, that's not possible here due to the SQL connection requirement. If there is some way to provide a reproducible example, please let me know and I will edit the code below. Assume that the entries of <code>col1</code> are strings and those of <code>col2</code> are numeric values.</p>
<p>Note that I'm trying to ensure that each row of <code>col1</code> and <code>col2</code> matches the corresponding combination of <code>list1</code> and <code>list2</code>, so it would not be possible to do separate <code>where</code> clauses for each, i.e., <code>where col1 = any(%(list1)s) and col2 = any(%(list2)s)</code>.</p>
<p>First, I tried passing the lists as separate parameters and then combining them into an array within the SQL query:</p>
<pre><code>import pandas as pd
list1 = ['a', 'b', 'c']
list2 = [1,2,3]
pd.read_sql_query(
"""
select * from table
where (col1, col2) = any(array[(%(list1)s, %(list2)s)])
""",
con = conn,
params = {'list1': list1, 'list2':list2}
)
</code></pre>
<p>When I try this, I get <code>Datatype Mismatch: cannot compare dissimilar columns of type text and text[] at column 1</code>.</p>
<p>Also tried the following variant, where I passed a list of lists into <code>param</code>:</p>
<pre><code>pd.read_sql_query(
"""
select * from table
where (col1, col2) = any(%(arr)s)
""",
con = conn,
params = {'arr': [[x,y] for x,y in zip(list1,list2)]}
)
</code></pre>
<p>Here, I got <code>DataError: (psycopg2.errors.InvalidTextRepresentation) in valid input syntax for integer: "a"</code>.</p>
<p>Tried a few other minor variants of the above, but every attempt threw some kind of error. So, what's the syntax needed in order to accomplish this?</p>
<p><strong>EDIT:</strong>
Including a reproducible example:</p>
<pre><code>import numpy as np
import pandas as pd
from sqlalchemy import create_engine
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
n = 100
engine = create_engine(
"postgresql+psycopg2://postgres:password@localhost:5432/database"
)
np.random.seed(2022)
df = pd.DataFrame(
{
"col1": np.random.choice(list1, n, replace=True),
"col2": np.random.choice(list2, n, replace=True),
}
)
# write table to database
df.to_sql("toy_table", engine, if_exists="replace", index=False)
# query with where any
df_query = pd.read_sql_query(
"""
select * from toy_table
where col1 = any(%(list1)s) and col2=any(%(list2)s)
""",
con=engine,
params={"list1": list1, "list2": list2},
)
# expected output
rows = [(x, y) for x, y in zip(list1, list2)]
df_expected = df.loc[df.apply(lambda x: tuple(x.values) in rows, axis=1)]
# Throws assertion error
assert df_expected.equals(df_query)
</code></pre>
|
[
{
"answer_id": 74577571,
"author": "Pepe N O",
"author_id": 15062361,
"author_profile": "https://Stackoverflow.com/users/15062361",
"pm_score": 1,
"selected": false,
"text": "#combine lists into a dictionary then convert to json\njson1 = json.dumps(dict(zip(list1, list2)))\n df = pd.read_sql_query(\n \"\"\"\n select * \n from \"table\"\n where concat('{\"',col1,'\":',col2,'}')::jsonb <@ %s::jsonb\n \"\"\",\n con = conn,\n params = (json1,)\n )\n list1 = ['a', 'b', 'c']\nlist2 = [1,2,3]\nlist3 = ['z', 'y', 'x']\n\n#assemble a json\njson1 = ','.join(['\"f1\": \"'+x+'\"' for x in list1])\njson2 = ','.join(['\"f2\": '+str(x) for x in list2])\njson3 = ','.join(['\"f3\": \"'+x+'\"' for x in list3])\njson_string = '{'+json1+', '+json2+ ', '+json3+'}' \n df = pd.read_sql_query(\n \"\"\"\n select * \n from \"table\"\n where row_to_json(row(col1,col2,col3))::jsonb <@ %s::jsonb\n \"\"\",\n con = conn,\n params = (json_string,)\n )\n"
},
{
"answer_id": 74585869,
"author": "user3294195",
"author_id": 3294195,
"author_profile": "https://Stackoverflow.com/users/3294195",
"pm_score": 1,
"selected": true,
"text": "df_query = pd.read_sql_query(\n \"\"\"\n select * from toy_table\n join (select unnest(%(list1)s) as list1, unnest(%(list2)s) as list2) as tmp\n on col1 = list1 and col2 = list2\n \"\"\",\n con=engine,\n params={\"list1\": list1, \"list2\": list2},\n)\n\n# expected output\nrows = [(x, y) for x, y in zip(list1, list2)]\ndf_expected = df.loc[df.apply(lambda x: tuple(x.values) in rows, axis=1)]\n\nassert df_query.equals(df_expected)\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3294195/"
] |
74,575,621
|
<p>I am trying to learn Go and I was experimenting in the playground. I have a very simple go code. I was trying to use Structs and Slices together in a go routine. I am not sure if this will be a thing I will use in production but it seemed a little off, so here:</p>
<pre><code>
func main() {
routinemsg := make(chan []Person)
routinemsg2 := make(chan []Person)
// create the person records
p1 := newPerson("john doe", 25)
p2 := newPerson("dohn joe", 52)
p3 := newPerson("bohn joo", 30)
// send a slice of Person to the first routine
go func() { routinemsg <- []Person{p1, p2} }()
// retrieve the slice from the first routine[in the append]
// append p3 to the slice retrieved from the first routine
// send the new slice to the second routine
go func() { routinemsg2 <- append(<-routinemsg, p3) }()
// I am able to see the first Println but when I insert the second one I get a deadlock error
// also, same error if I use one Println with 2 arguments.
fmt.Println(<-routinemsg)
fmt.Println(<-routinemsg2)
}
</code></pre>
<p>I heard about wait groups but dont know them yet! So, be nice to me :D and thanks for your time</p>
|
[
{
"answer_id": 74575942,
"author": "icza",
"author_id": 1705598,
"author_profile": "https://Stackoverflow.com/users/1705598",
"pm_score": 2,
"selected": true,
"text": "routinemsg main routinemsg main main routinemsg2 routinemsg2 main fmt.Println(<-routinemsg) main() routinemsg2 p1 p2 p3 [{john doe 25} {dohn joe 52} {bohn joo 30}]\n"
},
{
"answer_id": 74582308,
"author": "afyonkes",
"author_id": 14897605,
"author_profile": "https://Stackoverflow.com/users/14897605",
"pm_score": 0,
"selected": false,
"text": " buffered := make(chan string, 2)\n buffered <- \"1\"\n buffered <- \"2\"\n\n fmt.Println(<-buffered)\n fmt.Println(<-buffered)\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14897605/"
] |
74,575,653
|
<p>I created a WPF Listview and is populated with instances of ProductCategory.</p>
<pre><code>public class ProductCategory
{
public int Id { get; set; }
public string CategoryName { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime LastUpdated { get; set; }
}
</code></pre>
<p>Next I create the list, populate it and assign it to the Listview control.</p>
<p>private List myProductList = new List();</p>
<p>// add some items to myProductList</p>
<p>// assign product list to ItemsSource property of a ListView</p>
<p>myListView.ItemsSource = myProductList;</p>
<p>In the XAML code, a button labelled "Edit" is added to each row. Each row represents an instance of ProductCategory:</p>
<pre><code> <ListView x:Name="myListView" Height="352" HorizontalAlignment="Left" Margin="20,90,0,0" VerticalAlignment="Top" Width="1008">
<ListView.View>
<GridView>
<GridViewColumn Header="Category Name" DisplayMemberBinding="{Binding CategoryName}" Width="200"/>
<GridViewColumn Header="Created Date" DisplayMemberBinding="{Binding CreatedDate}" Width="200"/>
<GridViewColumn Header="Last Updated" DisplayMemberBinding="{Binding LastUpdated}" Width="200"/>
<GridViewColumn Header="Edit" Width="200">
<GridViewColumn.CellTemplate>
<DataTemplate>
<Button Content="Edit" Click="EditCategory" CommandParameter="{Binding}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</code></pre>
<p>When the user clicks the button, a dialog appears and the user can edit the data for an instance of ProductCategory. When the user closes the dialog, the user is returned to the Listview.</p>
<p>At this point I want to disable all the buttons in the Listview. How could I programmatically achieve this goal?</p>
<p>The buttons are not accessible in myListView.ItemsSource.</p>
|
[
{
"answer_id": 74576469,
"author": "EldHasp",
"author_id": 13349759,
"author_profile": "https://Stackoverflow.com/users/13349759",
"pm_score": -1,
"selected": false,
"text": "using Simplified;\nusing System;\nusing System.Collections.ObjectModel;\nusing System.Windows;\n\nnamespace Core2022.SO.user2949159\n{\n public class ProductsViewModel : BaseInpc\n {\n public ObservableCollection<ProductCategory> Products { get; } = new()\n {\n new ProductCategory() {Id = 1, CategoryName = \"Electronics\", CreatedDate = DateTime.Now.AddDays(-15).Date, LastUpdated= DateTime.Now.AddDays(-5).Date},\n new ProductCategory() {Id = 2, CategoryName = \"Сlothes\", CreatedDate = DateTime.Now.AddDays(-7).Date, LastUpdated= DateTime.Now.AddDays(-1).Date}\n };\n\n private RelayCommand? _editCommand;\n private bool _editingOff;\n\n public RelayCommand EditCommand => _editCommand ??= new RelayCommand<ProductCategory>(EditExecute, EditCanExecute);\n\n public bool EditingOff\n {\n get => _editingOff;\n set\n {\n if (Set(ref _editingOff, value))\n EditCommand.RaiseCanExecuteChanged();\n }\n }\n private bool EditCanExecute(ProductCategory product) => !EditingOff;\n\n private void EditExecute(ProductCategory product)\n {\n // Some Code for edit product\n MessageBox.Show($\"{product.Id}: {product.CategoryName}\");\n }\n }\n <Window x:Class=\"Core2022.SO.user2949159.ProductsWindow\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:d=\"http://schemas.microsoft.com/expression/blend/2008\"\n xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\"\n xmlns:local=\"clr-namespace:Core2022.SO.user2949159\"\n mc:Ignorable=\"d\"\n Title=\"ProductsWindow\" Height=\"450\" Width=\"800\"\n DataContext=\"{DynamicResource vm}\">\n <Window.Resources>\n <local:ProductsViewModel x:Key=\"vm\"/>\n </Window.Resources>\n <Grid>\n <Grid.RowDefinitions>\n <RowDefinition Height=\"Auto\"/>\n <RowDefinition/>\n </Grid.RowDefinitions>\n <CheckBox Content=\"Editing Off\" IsChecked=\"{Binding EditingOff}\" Margin=\"5\"/>\n <ListView Grid.Row=\"1\" ItemsSource=\"{Binding Products}\" HorizontalAlignment=\"Left\" Margin=\"20\">\n <ListView.View>\n <GridView>\n <GridViewColumn Header=\"Category Name\" DisplayMemberBinding=\"{Binding CategoryName}\" Width=\"200\"/>\n <GridViewColumn Header=\"Created Date\" DisplayMemberBinding=\"{Binding CreatedDate}\" Width=\"200\"/>\n <GridViewColumn Header=\"Last Updated\" DisplayMemberBinding=\"{Binding LastUpdated}\" Width=\"200\"/>\n <GridViewColumn Header=\"Edit\" Width=\"200\">\n <GridViewColumn.CellTemplate>\n <DataTemplate>\n <Button Content=\"Edit\"\n CommandParameter=\"{Binding}\"\n Command=\"{Binding EditCommand, Mode=OneWay, Source={StaticResource vm}}\"/>\n </DataTemplate>\n </GridViewColumn.CellTemplate>\n </GridViewColumn>\n </GridView>\n </ListView.View>\n </ListView>\n </Grid>\n</Window>\n"
},
{
"answer_id": 74584869,
"author": "Dragan Radovac",
"author_id": 3602074,
"author_profile": "https://Stackoverflow.com/users/3602074",
"pm_score": 1,
"selected": false,
"text": "List<Button> buttons = \n new List<Button>();\n\nprivate void Button_Click(object sender, RoutedEventArgs e)\n{\n myListView.Items\n .Cast<dynamic>()\n .ToList()\n .ForEach(item => {\n var listviewitem = \n (ListViewItem) \n (myListView\n .ItemContainerGenerator\n .ContainerFromItem(item));\n\n Button editbutton = \n FindVisualChild<Button>\n (listviewitem);\n\n buttons\n .Add(editbutton);\n });\n\n buttons[1]\n .IsEnabled = false;\n buttons[3]\n .IsEnabled = false;\n}\n\nprivate childItem FindVisualChild<childItem>(DependencyObject obj)\n where childItem : DependencyObject\n{\n for (int i = 0; \n i < VisualTreeHelper\n .GetChildrenCount(obj); \n i++)\n {\n DependencyObject child = \n VisualTreeHelper\n .GetChild(obj, i);\n\n if (child != null \n && child is childItem)\n {\n return \n (childItem)child;\n }\n else\n {\n childItem childOfChild = \n FindVisualChild<childItem>\n (child);\n\n if (childOfChild != null)\n return \n childOfChild;\n }\n }\n return null;\n}\n"
},
{
"answer_id": 74620158,
"author": "user2949159",
"author_id": 2949159,
"author_profile": "https://Stackoverflow.com/users/2949159",
"pm_score": 0,
"selected": false,
"text": " private childItem FindVisualChild<childItem>(DependencyObject obj) where childItem : DependencyObject\n {\n for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)\n {\n DependencyObject child = VisualTreeHelper.GetChild(obj, i);\n\n if (child != null && child is childItem)\n {\n return (childItem)child;\n }\n else\n {\n childItem childOfChild = FindVisualChild<childItem>(child);\n\n if (childOfChild != null)\n {\n return childOfChild;\n }\n }\n }\n return null;\n }\n\n private void disableEditButtonsInListView()\n {\n myListView.Items.Cast<dynamic>().ToList().ForEach(item =>\n {\n var myListViewItem = (ListViewItem)(myListView.ItemContainerGenerator.ContainerFromItem(item));\n Button editButton = FindVisualChild<Button>(myListViewItem);\n if (editButton != null)\n {\n editButton.IsEnabled = false;\n }\n });\n }\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2949159/"
] |
74,575,654
|
<p>I am using Azure devops to deploy services to AKS. There are few instances that even though the pods weren't started(in crashed state) the pipeline still shows it as success.</p>
<p>I add this task to validate the kubectl pod:</p>
<pre><code>- task: Kubernetes@1
displayName: 'Deploy ${{ parameters.project_display_name }} to ${{ parameters.cluster }}'
inputs:
connectionType: Kubernetes Service Connection
kubernetesServiceEndpoint: ${{ parameters.cluster }}-${{ parameters.namespace }}
command: apply
arguments: -f $(System.ArtifactsDirectory)/k8_manifest/manifest.yml -n ${{ parameters.namespace }}
outputFormat: 'yaml'
- task: AzureCLI@2
displayName: 'Validate Deployment of ${{ parameters.project_display_name }} to ${{ parameters.cluster }}'
inputs:
scriptType: 'pscore'
scriptLocation: 'inlineScript'
inlineScript: |
containerStatuses=$(kubectl get deployment loss-limit-api --namespace betting -o=jsonpath='{$.status.conditions}')
for row in $(echo "${containerStatuses}" | jq -r '.[] | @base64'); do
_jq() {
echo ${row} | base64 --decode | jq -r ${1}
}
if [ $(_jq '.status') != "True" ]; then
echo "Inactive Pod erron on the deployment"
exit 1
fi
done
</code></pre>
<p>it returns and error:</p>
<pre><code>Starting: Validate Deployment of Loss Limit API to core-dev00
==============================================================================
Task : Azure CLI
Description : Run Azure CLI commands against an Azure subscription in a PowerShell Core/Shell script when running on Linux agent or PowerShell/PowerShell Core/Batch script when running on Windows agent.
Version : 2.208.0
Author : Microsoft Corporation
Help : https://docs.microsoft.com/azure/devops/pipelines/tasks/deploy/azure-cli
==============================================================================
##[error]Script failed with error: Error: Unable to locate executable file: 'pwsh'. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.
Finishing: Validate Deployment of Loss Limit API to core-dev00
</code></pre>
|
[
{
"answer_id": 74576469,
"author": "EldHasp",
"author_id": 13349759,
"author_profile": "https://Stackoverflow.com/users/13349759",
"pm_score": -1,
"selected": false,
"text": "using Simplified;\nusing System;\nusing System.Collections.ObjectModel;\nusing System.Windows;\n\nnamespace Core2022.SO.user2949159\n{\n public class ProductsViewModel : BaseInpc\n {\n public ObservableCollection<ProductCategory> Products { get; } = new()\n {\n new ProductCategory() {Id = 1, CategoryName = \"Electronics\", CreatedDate = DateTime.Now.AddDays(-15).Date, LastUpdated= DateTime.Now.AddDays(-5).Date},\n new ProductCategory() {Id = 2, CategoryName = \"Сlothes\", CreatedDate = DateTime.Now.AddDays(-7).Date, LastUpdated= DateTime.Now.AddDays(-1).Date}\n };\n\n private RelayCommand? _editCommand;\n private bool _editingOff;\n\n public RelayCommand EditCommand => _editCommand ??= new RelayCommand<ProductCategory>(EditExecute, EditCanExecute);\n\n public bool EditingOff\n {\n get => _editingOff;\n set\n {\n if (Set(ref _editingOff, value))\n EditCommand.RaiseCanExecuteChanged();\n }\n }\n private bool EditCanExecute(ProductCategory product) => !EditingOff;\n\n private void EditExecute(ProductCategory product)\n {\n // Some Code for edit product\n MessageBox.Show($\"{product.Id}: {product.CategoryName}\");\n }\n }\n <Window x:Class=\"Core2022.SO.user2949159.ProductsWindow\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:d=\"http://schemas.microsoft.com/expression/blend/2008\"\n xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\"\n xmlns:local=\"clr-namespace:Core2022.SO.user2949159\"\n mc:Ignorable=\"d\"\n Title=\"ProductsWindow\" Height=\"450\" Width=\"800\"\n DataContext=\"{DynamicResource vm}\">\n <Window.Resources>\n <local:ProductsViewModel x:Key=\"vm\"/>\n </Window.Resources>\n <Grid>\n <Grid.RowDefinitions>\n <RowDefinition Height=\"Auto\"/>\n <RowDefinition/>\n </Grid.RowDefinitions>\n <CheckBox Content=\"Editing Off\" IsChecked=\"{Binding EditingOff}\" Margin=\"5\"/>\n <ListView Grid.Row=\"1\" ItemsSource=\"{Binding Products}\" HorizontalAlignment=\"Left\" Margin=\"20\">\n <ListView.View>\n <GridView>\n <GridViewColumn Header=\"Category Name\" DisplayMemberBinding=\"{Binding CategoryName}\" Width=\"200\"/>\n <GridViewColumn Header=\"Created Date\" DisplayMemberBinding=\"{Binding CreatedDate}\" Width=\"200\"/>\n <GridViewColumn Header=\"Last Updated\" DisplayMemberBinding=\"{Binding LastUpdated}\" Width=\"200\"/>\n <GridViewColumn Header=\"Edit\" Width=\"200\">\n <GridViewColumn.CellTemplate>\n <DataTemplate>\n <Button Content=\"Edit\"\n CommandParameter=\"{Binding}\"\n Command=\"{Binding EditCommand, Mode=OneWay, Source={StaticResource vm}}\"/>\n </DataTemplate>\n </GridViewColumn.CellTemplate>\n </GridViewColumn>\n </GridView>\n </ListView.View>\n </ListView>\n </Grid>\n</Window>\n"
},
{
"answer_id": 74584869,
"author": "Dragan Radovac",
"author_id": 3602074,
"author_profile": "https://Stackoverflow.com/users/3602074",
"pm_score": 1,
"selected": false,
"text": "List<Button> buttons = \n new List<Button>();\n\nprivate void Button_Click(object sender, RoutedEventArgs e)\n{\n myListView.Items\n .Cast<dynamic>()\n .ToList()\n .ForEach(item => {\n var listviewitem = \n (ListViewItem) \n (myListView\n .ItemContainerGenerator\n .ContainerFromItem(item));\n\n Button editbutton = \n FindVisualChild<Button>\n (listviewitem);\n\n buttons\n .Add(editbutton);\n });\n\n buttons[1]\n .IsEnabled = false;\n buttons[3]\n .IsEnabled = false;\n}\n\nprivate childItem FindVisualChild<childItem>(DependencyObject obj)\n where childItem : DependencyObject\n{\n for (int i = 0; \n i < VisualTreeHelper\n .GetChildrenCount(obj); \n i++)\n {\n DependencyObject child = \n VisualTreeHelper\n .GetChild(obj, i);\n\n if (child != null \n && child is childItem)\n {\n return \n (childItem)child;\n }\n else\n {\n childItem childOfChild = \n FindVisualChild<childItem>\n (child);\n\n if (childOfChild != null)\n return \n childOfChild;\n }\n }\n return null;\n}\n"
},
{
"answer_id": 74620158,
"author": "user2949159",
"author_id": 2949159,
"author_profile": "https://Stackoverflow.com/users/2949159",
"pm_score": 0,
"selected": false,
"text": " private childItem FindVisualChild<childItem>(DependencyObject obj) where childItem : DependencyObject\n {\n for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)\n {\n DependencyObject child = VisualTreeHelper.GetChild(obj, i);\n\n if (child != null && child is childItem)\n {\n return (childItem)child;\n }\n else\n {\n childItem childOfChild = FindVisualChild<childItem>(child);\n\n if (childOfChild != null)\n {\n return childOfChild;\n }\n }\n }\n return null;\n }\n\n private void disableEditButtonsInListView()\n {\n myListView.Items.Cast<dynamic>().ToList().ForEach(item =>\n {\n var myListViewItem = (ListViewItem)(myListView.ItemContainerGenerator.ContainerFromItem(item));\n Button editButton = FindVisualChild<Button>(myListViewItem);\n if (editButton != null)\n {\n editButton.IsEnabled = false;\n }\n });\n }\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2785937/"
] |
74,575,655
|
<p>I am using <a href="https://ng-mocks.sudo.eu/" rel="nofollow noreferrer">ng-mocks</a> for mocking and so far everything works OK with a few exceptions of some quirks.</p>
<p>I'm using <a href="https://ng-mocks.sudo.eu/extra/auto-spy" rel="nofollow noreferrer">autoSpy</a> to spy every method automatically so I don't have to manually spy on functions. So according to the documentation, I've got, in my <code>test.ts</code>:</p>
<pre><code>ngMocks.autoSpy('jasmine');
</code></pre>
<p>And I can use the spy method to test. For example, I've got something like this:</p>
<pre><code>// in the main beforeEach() while setting up TestBed
myService: MyService = MockService(MyService);
describe(`When button A is clicked`, () => {
beforeEach(() => {
//button click code here
});
it(`Should call functionA one time`, () => {
expect(myService.functionA).toHaveBeenCalled(); // This works ok
});
});
// Further down in the same file
describe(`When button B is clicked`, () => {
beforeEach(() => {
//button click code here
ngMocks.reset(); // I don't think this does what I think it does
});
it(`Should NOT call functionA`, () => {
expect(myService.functionA).not.toHaveBeenCalled(); // This DOES NOT work.
});
});
</code></pre>
<p>The second time around, I'm trying to test that the function is not called with a different button, but the spy counts the previous call and fails. If I run just this test with <code>jit</code>, then it passes. Or if I move this test case above the first one, the first then it works. I can't just do <code>mySpy.calls.reset()</code> because I haven't assigned a spy manually. I tried <code>myService.functionA.calls.reset()</code> but there's an error - <code>functoinA</code> doesn't have <code>calls</code> method as it's not recognised as a spy.</p>
<p>Furthermore, if I put a debugger just before my <code>expect.not.toHaveBeenCalled()</code> and check through chrome dev window, I can run this <code>myService.functionA.calls.reset()</code> on the console and then it works fine.</p>
<p>How do I reset the all spy calls in <code>ng-mocks</code> please?</p>
|
[
{
"answer_id": 74575856,
"author": "Facundo Gallardo",
"author_id": 20375146,
"author_profile": "https://Stackoverflow.com/users/20375146",
"pm_score": 0,
"selected": false,
"text": "ngMock.autoSpy('reset') beforeEach(() => {\n ngMocks.autoSpy('jasmine');\n});\n\n.\n.\n.\n\nafterEach(() => {\n ngMocks.autoSpy('reset');\n});\n"
},
{
"answer_id": 74581132,
"author": "satanTime",
"author_id": 13112018,
"author_profile": "https://Stackoverflow.com/users/13112018",
"pm_score": 2,
"selected": true,
"text": "ngMocks.autoSpy('jasmine'); jasmine.createSpy beforeEach MockService // in the main beforeEach() while setting up TestBed\nconst myService = MockService(MyService);\n ngMocks.reset(); describe('root suite', () => {\n // in the main beforeEach() while setting up TestBed\n let myService: MyService\n\n beforeEach(() => myService = MockService(MyService));\n\n describe(`When button A is clicked`, () => {\n beforeEach(() => {\n //button click code here\n });\n\n it(`Should call functionA one time`, () => {\n expect(myService.functionA).toHaveBeenCalled(); // This works ok\n });\n });\n\n // Further down in the same file\n describe(`When button B is clicked`, () => {\n beforeEach(() => {\n //button click code here\n });\n\n it(`Should NOT call functionA`, () => {\n expect(myService.functionA).not.toHaveBeenCalled(); // This DOES NOT work. \n });\n });\n});\n MyService (myService.functionA as jasmine.Spy).calls.reset();\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/435867/"
] |
74,575,674
|
<p>When trying to use MUI Autocomplete to select an object from a list of options, the value is set to <code>0</code>. How can I get it to set the actual object?</p>
<p>Example here: <a href="https://codesandbox.io/s/ecstatic-diffie-mf9ydl" rel="nofollow noreferrer">https://codesandbox.io/s/ecstatic-diffie-mf9ydl</a>
Select an option from the autocomplete field and click submit. You'll see the valid in the console is <code>0</code> instead of <code>{ _id: 1, name: "Option 1" }</code></p>
|
[
{
"answer_id": 74575856,
"author": "Facundo Gallardo",
"author_id": 20375146,
"author_profile": "https://Stackoverflow.com/users/20375146",
"pm_score": 0,
"selected": false,
"text": "ngMock.autoSpy('reset') beforeEach(() => {\n ngMocks.autoSpy('jasmine');\n});\n\n.\n.\n.\n\nafterEach(() => {\n ngMocks.autoSpy('reset');\n});\n"
},
{
"answer_id": 74581132,
"author": "satanTime",
"author_id": 13112018,
"author_profile": "https://Stackoverflow.com/users/13112018",
"pm_score": 2,
"selected": true,
"text": "ngMocks.autoSpy('jasmine'); jasmine.createSpy beforeEach MockService // in the main beforeEach() while setting up TestBed\nconst myService = MockService(MyService);\n ngMocks.reset(); describe('root suite', () => {\n // in the main beforeEach() while setting up TestBed\n let myService: MyService\n\n beforeEach(() => myService = MockService(MyService));\n\n describe(`When button A is clicked`, () => {\n beforeEach(() => {\n //button click code here\n });\n\n it(`Should call functionA one time`, () => {\n expect(myService.functionA).toHaveBeenCalled(); // This works ok\n });\n });\n\n // Further down in the same file\n describe(`When button B is clicked`, () => {\n beforeEach(() => {\n //button click code here\n });\n\n it(`Should NOT call functionA`, () => {\n expect(myService.functionA).not.toHaveBeenCalled(); // This DOES NOT work. \n });\n });\n});\n MyService (myService.functionA as jasmine.Spy).calls.reset();\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/565633/"
] |
74,575,680
|
<p>I'm making a component that has multiple sets of children.</p>
<p>The question <a href="https://stackoverflow.com/questions/35181333/react-component-with-two-sets-of-children">React component with two sets of children</a> suggests to index <code>children</code>, as in <code>props.children[0]</code>. This works great in JavaScript.</p>
<p>But in TypeScript, I'm getting a type error, even though the code works fine at runtime.</p>
<pre class="lang-js prettyprint-override"><code>function MyComponent(props: { children: React.ReactNode }) {
return <>
...
{props.children[0]}
...
{props.children[1]}
...
</>;
}
</code></pre>
<p>TypeScript fails with the following error messages on <code>props.children[0]</code>:</p>
<pre><code>Object is possibly 'null' or 'undefined'.
ts(2533)
</code></pre>
<pre><code>Element implicitly has an 'any' type because expression of type '0' can't be used to index type 'string | number | boolean | ReactElement<any, string | JSXElementConstructor<any>> | ReactFragment | ReactPortal'.
Property '0' does not exist on type 'string | number | boolean | ReactElement<any, string | JSXElementConstructor<any>> | ReactFragment | ReactPortal'.
ts(7053)
</code></pre>
<p>How do I make it typecheck?</p>
|
[
{
"answer_id": 74575856,
"author": "Facundo Gallardo",
"author_id": 20375146,
"author_profile": "https://Stackoverflow.com/users/20375146",
"pm_score": 0,
"selected": false,
"text": "ngMock.autoSpy('reset') beforeEach(() => {\n ngMocks.autoSpy('jasmine');\n});\n\n.\n.\n.\n\nafterEach(() => {\n ngMocks.autoSpy('reset');\n});\n"
},
{
"answer_id": 74581132,
"author": "satanTime",
"author_id": 13112018,
"author_profile": "https://Stackoverflow.com/users/13112018",
"pm_score": 2,
"selected": true,
"text": "ngMocks.autoSpy('jasmine'); jasmine.createSpy beforeEach MockService // in the main beforeEach() while setting up TestBed\nconst myService = MockService(MyService);\n ngMocks.reset(); describe('root suite', () => {\n // in the main beforeEach() while setting up TestBed\n let myService: MyService\n\n beforeEach(() => myService = MockService(MyService));\n\n describe(`When button A is clicked`, () => {\n beforeEach(() => {\n //button click code here\n });\n\n it(`Should call functionA one time`, () => {\n expect(myService.functionA).toHaveBeenCalled(); // This works ok\n });\n });\n\n // Further down in the same file\n describe(`When button B is clicked`, () => {\n beforeEach(() => {\n //button click code here\n });\n\n it(`Should NOT call functionA`, () => {\n expect(myService.functionA).not.toHaveBeenCalled(); // This DOES NOT work. \n });\n });\n});\n MyService (myService.functionA as jasmine.Spy).calls.reset();\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/525872/"
] |
74,575,687
|
<p>How can I print from an array of elements in Python every second pair of elements one below another, without commas and brackets?</p>
<p>My array looks like this:</p>
<pre><code>m=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
</code></pre>
<p>And, I want to print in one of the cases:</p>
<pre><code>1 2
5 6
9 10
</code></pre>
<p>or in another case:</p>
<pre><code>3 4
7 8
11 12
</code></pre>
<p>I didn't know how to do that, so i created two separate arrays, but when i try to print elements in separate rows, each pair has brackets and coma. Is there any way to solve this easier and to make it look as i wrote?</p>
<p>What I've tried:</p>
<pre><code>a=[m[j:j+2] for j in range(0,len(m),2)]
a1=m[::2]
a2=m[1::2]
if s1>s2:
print("\n".join(map(str,a1)))
elif s1<s2:
print("\n".join(map(str,a2)))
</code></pre>
<p>My current output:</p>
<pre><code>[3, 4]
[7, 8]
[11, 12]
</code></pre>
|
[
{
"answer_id": 74575856,
"author": "Facundo Gallardo",
"author_id": 20375146,
"author_profile": "https://Stackoverflow.com/users/20375146",
"pm_score": 0,
"selected": false,
"text": "ngMock.autoSpy('reset') beforeEach(() => {\n ngMocks.autoSpy('jasmine');\n});\n\n.\n.\n.\n\nafterEach(() => {\n ngMocks.autoSpy('reset');\n});\n"
},
{
"answer_id": 74581132,
"author": "satanTime",
"author_id": 13112018,
"author_profile": "https://Stackoverflow.com/users/13112018",
"pm_score": 2,
"selected": true,
"text": "ngMocks.autoSpy('jasmine'); jasmine.createSpy beforeEach MockService // in the main beforeEach() while setting up TestBed\nconst myService = MockService(MyService);\n ngMocks.reset(); describe('root suite', () => {\n // in the main beforeEach() while setting up TestBed\n let myService: MyService\n\n beforeEach(() => myService = MockService(MyService));\n\n describe(`When button A is clicked`, () => {\n beforeEach(() => {\n //button click code here\n });\n\n it(`Should call functionA one time`, () => {\n expect(myService.functionA).toHaveBeenCalled(); // This works ok\n });\n });\n\n // Further down in the same file\n describe(`When button B is clicked`, () => {\n beforeEach(() => {\n //button click code here\n });\n\n it(`Should NOT call functionA`, () => {\n expect(myService.functionA).not.toHaveBeenCalled(); // This DOES NOT work. \n });\n });\n});\n MyService (myService.functionA as jasmine.Spy).calls.reset();\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20600892/"
] |
74,575,709
|
<p>I have implemented Radio button in Flutter namely <strong>'Today'</strong> , <strong>'Tomorrow'</strong> , <strong>'User Input Date'</strong>, and have wrapped them in a Column, but I am unable to reduce the space between the 3 radio buttons and also I am not able to move them towards the left. Is there any way I can shift them towards left side and decrease the default space taken between the radio button. Also I want to stick to the use of RadioListTile only.
I am attaching a picture to give a clear idea.
<a href="https://i.stack.imgur.com/lIe8Z.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lIe8Z.png" alt="Radio Button Flutter" /></a></p>
<p>Code</p>
<pre><code> Column(
children: [
RadioListTile<DateTime>(
activeColor: Colors.white,
title: Text(
"Today",
style: Theme.of(context).textTheme.bodyMedium,
),
value: today,
groupValue: selectedMatchDateFilter,
onChanged: (DateTime? value) => setState(() {
selectedMatchDateFilter = value;
}),
),
RadioListTile<DateTime>(
activeColor: Colors.white,
title: Text(
"Tomorrow",
style: Theme.of(context).textTheme.bodyMedium,
),
value: DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day + 1),
groupValue: selectedMatchDateFilter,
onChanged: (DateTime? value) => setState(() {
selectedMatchDateFilter = value;
}),
),
RadioListTile<DateTime>(
activeColor: Colors.white,
title: Row(
children: [
DropdownButton2<String>(
isExpanded: true,
buttonHeight: 30.h,
buttonWidth: 220.w,
items: const [
DropdownMenuItem<String>(
value: "",
child: Text("Till Date"),
),
DropdownMenuItem<String>(
value: "",
child: Text("Precise Date"),
),
],
),
1 == 2
? Checkbox(
value: true,
onChanged: (bool? _value) {},
)
: IconButton(
icon: const Icon(Icons.calendar_today),
onPressed: () => showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2022, 11, 16),
lastDate: DateTime(2023, 1, 1),
),
),
],
),
value: DateTime.now(),
groupValue: selectedMatchDateFilter,
onChanged: (value) {},
)
],
),
</code></pre>
|
[
{
"answer_id": 74575911,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 2,
"selected": true,
"text": "visualDensity dense contentPadding RadioListTile<DateTime>(\n activeColor: Colors.white,\n visualDensity: VisualDensity(horizontal: -4, vertical: -4),//<-- add this\n dense: true,//<-- add this\n contentPadding: EdgeInsets.zero,//<-- add this\n \n title: Text(\n \"Tomorrow\",\n style: Theme.of(context).textTheme.bodyMedium,\n ),\n value: DateTime(DateTime.now().year, DateTime.now().month,\n DateTime.now().day + 1),\n groupValue: selectedMatchDateFilter,\n onChanged: (DateTime? value) => setState(() {}),\n ),\n Widget CustomRadioTile<T>(\n {required Function(T?) onChanged,\n required String title,\n required T groupValue,\n required T value,\n required BuildContext context}) {\n return InkWell(\n onTap: () {\n onChanged(value);\n },\n child: Row(\n children: [\n SizedBox(\n height: 20,\n width: 20,\n child: Radio<T>(\n value: value,\n groupValue: groupValue,\n onChanged: (value) {},\n ),\n ),\n Padding(\n padding: const EdgeInsets.only(left: 4.0),\n child: Text(\n title,\n style: Theme.of(context).textTheme.bodyMedium,\n ),\n ),\n ],\n ),\n );\n }\n CustomRadioTile<DateTime>(\n onChanged: (DateTime? value) => setState(() {\n selectedMatchDateFilter = value;\n }),\n title: 'Tomorrow',\n groupValue: selectedMatchDateFilter,\n value: DateTime(DateTime.now().year, DateTime.now().month,\n DateTime.now().day + 1),\n context: context),\n"
},
{
"answer_id": 74576032,
"author": "Delwinn",
"author_id": 16714498,
"author_profile": "https://Stackoverflow.com/users/16714498",
"pm_score": 0,
"selected": false,
"text": "Radio Text Radio Text class LabeledRadio extends StatelessWidget {\n const LabeledRadio({\n super.key,\n required this.label,\n required this.padding,\n required this.groupValue,\n required this.value,\n required this.onChanged,\n });\n\n final String label;\n final EdgeInsets padding;\n final bool groupValue;\n final bool value;\n final ValueChanged<bool> onChanged;\n\n @override\n Widget build(BuildContext context) {\n return InkWell(\n onTap: () {\n if (value != groupValue) {\n onChanged(value);\n }\n },\n child: Padding(\n padding: padding,\n child: Row(\n children: <Widget>[\n Radio<bool>(\n groupValue: groupValue,\n value: value,\n onChanged: (bool? newValue) {\n onChanged(newValue!);\n },\n ),\n Text(label),\n ],\n ),\n ),\n );\n }\n}\n RadioListTile"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14075086/"
] |
74,575,717
|
<p>I have a client whose SQL database is decades old. Software engineers do not have access to update schema objects and DBAs do not use code-first to update the database.</p>
<p>.NET Core 6 is a requirement for me. Since <code>.edmx</code> is not a part of .NET Core, does anyone have recommendations for an ORM that implements a "database-first" approach?</p>
|
[
{
"answer_id": 74575911,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 2,
"selected": true,
"text": "visualDensity dense contentPadding RadioListTile<DateTime>(\n activeColor: Colors.white,\n visualDensity: VisualDensity(horizontal: -4, vertical: -4),//<-- add this\n dense: true,//<-- add this\n contentPadding: EdgeInsets.zero,//<-- add this\n \n title: Text(\n \"Tomorrow\",\n style: Theme.of(context).textTheme.bodyMedium,\n ),\n value: DateTime(DateTime.now().year, DateTime.now().month,\n DateTime.now().day + 1),\n groupValue: selectedMatchDateFilter,\n onChanged: (DateTime? value) => setState(() {}),\n ),\n Widget CustomRadioTile<T>(\n {required Function(T?) onChanged,\n required String title,\n required T groupValue,\n required T value,\n required BuildContext context}) {\n return InkWell(\n onTap: () {\n onChanged(value);\n },\n child: Row(\n children: [\n SizedBox(\n height: 20,\n width: 20,\n child: Radio<T>(\n value: value,\n groupValue: groupValue,\n onChanged: (value) {},\n ),\n ),\n Padding(\n padding: const EdgeInsets.only(left: 4.0),\n child: Text(\n title,\n style: Theme.of(context).textTheme.bodyMedium,\n ),\n ),\n ],\n ),\n );\n }\n CustomRadioTile<DateTime>(\n onChanged: (DateTime? value) => setState(() {\n selectedMatchDateFilter = value;\n }),\n title: 'Tomorrow',\n groupValue: selectedMatchDateFilter,\n value: DateTime(DateTime.now().year, DateTime.now().month,\n DateTime.now().day + 1),\n context: context),\n"
},
{
"answer_id": 74576032,
"author": "Delwinn",
"author_id": 16714498,
"author_profile": "https://Stackoverflow.com/users/16714498",
"pm_score": 0,
"selected": false,
"text": "Radio Text Radio Text class LabeledRadio extends StatelessWidget {\n const LabeledRadio({\n super.key,\n required this.label,\n required this.padding,\n required this.groupValue,\n required this.value,\n required this.onChanged,\n });\n\n final String label;\n final EdgeInsets padding;\n final bool groupValue;\n final bool value;\n final ValueChanged<bool> onChanged;\n\n @override\n Widget build(BuildContext context) {\n return InkWell(\n onTap: () {\n if (value != groupValue) {\n onChanged(value);\n }\n },\n child: Padding(\n padding: padding,\n child: Row(\n children: <Widget>[\n Radio<bool>(\n groupValue: groupValue,\n value: value,\n onChanged: (bool? newValue) {\n onChanged(newValue!);\n },\n ),\n Text(label),\n ],\n ),\n ),\n );\n }\n}\n RadioListTile"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1073399/"
] |
74,575,768
|
<p>I'm trying to figure out how to use a variable containing an ANSI-C quoting string as an argument for a subsequent bash command.
The string in the variable itself is a list of files (can virtually be a list of anything).</p>
<p>For example, I have a file containing a list of other files, for example <code>test.lst</code> containing :</p>
<pre><code> >$ cat test.lst
a.txt
b.txt
c.txt
</code></pre>
<p>I need to pass the file content as a single string so I'm doing :
<code>test_str=$(cat test.lst)</code>
then converts to ANSI-C quoting string:
<code>test_str=${test_str@Q}</code></p>
<p>So at the end I have :</p>
<pre><code> >$ test_str=$(cat test.lst)
>$ test_str=${test_str@Q}
>$ echo $test_str
$'a.txt\nb.txt\nc.txt'
</code></pre>
<p>which is what I'm looking for.</p>
<p>Then problem arises when I try to reuse this variable as a string list in another bash command.
For example direct use into a for loop :</p>
<pre><code> >$ for str in $test_str; do echo $str; done
$'a.txt\nb.txt\nc.txt'
</code></pre>
<p>What I expect at this step is that it prints the same thing as the content of the original <code>test.lst</code></p>
<p>I also tried expanding it back but it leaves leading <code>$'</code> and trailing <code>'</code></p>
<pre><code> >$ str=${test_str@E}
>$ echo $str
$'a.txt b.txt c.txt'
</code></pre>
<p>I also tried <code>printf</code> and some other stuffs to no avail. What is the correct way to use such ANSI-C quoting variable into a bash command ?</p>
|
[
{
"answer_id": 74575911,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 2,
"selected": true,
"text": "visualDensity dense contentPadding RadioListTile<DateTime>(\n activeColor: Colors.white,\n visualDensity: VisualDensity(horizontal: -4, vertical: -4),//<-- add this\n dense: true,//<-- add this\n contentPadding: EdgeInsets.zero,//<-- add this\n \n title: Text(\n \"Tomorrow\",\n style: Theme.of(context).textTheme.bodyMedium,\n ),\n value: DateTime(DateTime.now().year, DateTime.now().month,\n DateTime.now().day + 1),\n groupValue: selectedMatchDateFilter,\n onChanged: (DateTime? value) => setState(() {}),\n ),\n Widget CustomRadioTile<T>(\n {required Function(T?) onChanged,\n required String title,\n required T groupValue,\n required T value,\n required BuildContext context}) {\n return InkWell(\n onTap: () {\n onChanged(value);\n },\n child: Row(\n children: [\n SizedBox(\n height: 20,\n width: 20,\n child: Radio<T>(\n value: value,\n groupValue: groupValue,\n onChanged: (value) {},\n ),\n ),\n Padding(\n padding: const EdgeInsets.only(left: 4.0),\n child: Text(\n title,\n style: Theme.of(context).textTheme.bodyMedium,\n ),\n ),\n ],\n ),\n );\n }\n CustomRadioTile<DateTime>(\n onChanged: (DateTime? value) => setState(() {\n selectedMatchDateFilter = value;\n }),\n title: 'Tomorrow',\n groupValue: selectedMatchDateFilter,\n value: DateTime(DateTime.now().year, DateTime.now().month,\n DateTime.now().day + 1),\n context: context),\n"
},
{
"answer_id": 74576032,
"author": "Delwinn",
"author_id": 16714498,
"author_profile": "https://Stackoverflow.com/users/16714498",
"pm_score": 0,
"selected": false,
"text": "Radio Text Radio Text class LabeledRadio extends StatelessWidget {\n const LabeledRadio({\n super.key,\n required this.label,\n required this.padding,\n required this.groupValue,\n required this.value,\n required this.onChanged,\n });\n\n final String label;\n final EdgeInsets padding;\n final bool groupValue;\n final bool value;\n final ValueChanged<bool> onChanged;\n\n @override\n Widget build(BuildContext context) {\n return InkWell(\n onTap: () {\n if (value != groupValue) {\n onChanged(value);\n }\n },\n child: Padding(\n padding: padding,\n child: Row(\n children: <Widget>[\n Radio<bool>(\n groupValue: groupValue,\n value: value,\n onChanged: (bool? newValue) {\n onChanged(newValue!);\n },\n ),\n Text(label),\n ],\n ),\n ),\n );\n }\n}\n RadioListTile"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20527947/"
] |
74,575,773
|
<p>This is Edit profile feature i am trying to build.first i get the user details and fill up the fields by assigning them to a state</p>
<pre><code>const [name, setName] = useState('')
useEffect(() => {
if (localStorage.getItem('userInfo') === null) {
navigate('/login')
}
else{
userInfo=JSON.parse(localStorage.getItem('userInfo'))
setName(userInfo.name)
}
},)
</code></pre>
<p>until now everything is fine i can see the name in input field default value</p>
<pre><code> <Form onSubmit={submitHandler}>
<Form.Group controlId='name'>
<Form.Label>Name</Form.Label>
<Form.Control
type='name'
placeholder='Enter name'
defaultValue={name}
onChange={(e) => setName(e.target.value)}
></Form.Control>
</Form.Group>
</Form>
</code></pre>
<p>when i submit the form i am still sending the initial value to the server not the edited value.</p>
|
[
{
"answer_id": 74575837,
"author": "Sadman Sakib",
"author_id": 19684597,
"author_profile": "https://Stackoverflow.com/users/19684597",
"pm_score": 0,
"selected": false,
"text": "defaultValue value"
},
{
"answer_id": 74576045,
"author": "Samuel Lee",
"author_id": 20580174,
"author_profile": "https://Stackoverflow.com/users/20580174",
"pm_score": 1,
"selected": false,
"text": "export default function App() {\n const [name, setName] = useState(\"\"); // useState hook\n\n // handle change event\n const handleChange = (e) => {\n e.preventDefault(); // prevent the default action\n setName(e.target.value); // set name to e.target.value (event)\n };\n\n // render\n return (\n <div>\n <Form>\n <Form.Group>\n <Form.Control\n defaultValue={name}\n type=\"name\"\n onChange={handleChange}\n ></Form.Control>\n </Form.Group>\n </Form>\n </div>\n );\n}\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6005809/"
] |
74,575,794
|
<p>Consider the following simple code:</p>
<pre><code>import re
def my_match(s):
if re.match("^[a-zA-Z]+", s):
return True
else:
return False
</code></pre>
<p>Is there a way to collapse this in a single <code>return</code> statement? In <code>C</code> we could do for example:</p>
<pre><code>return match("^[a-zA-Z]+", s) ? true : false;
</code></pre>
<p>Is there something similar in python?</p>
|
[
{
"answer_id": 74575841,
"author": "Frank",
"author_id": 13483275,
"author_profile": "https://Stackoverflow.com/users/13483275",
"pm_score": 1,
"selected": false,
"text": "return re.match(\"^[a-zA-Z]+\", s) is not None\n"
},
{
"answer_id": 74575846,
"author": "CoffeeTableEspresso",
"author_id": 7339171,
"author_profile": "https://Stackoverflow.com/users/7339171",
"pm_score": 2,
"selected": true,
"text": "import re\n\ndef my_match(s):\n return True if re.match(\"^[a-zA-Z]+\", s) else False\n val_when_true if cond else val_when_false cond ? val_when_true : val_when_false import re\n\ndef my_match(s):\n return bool(re.match(\"^[a-zA-Z]+\", s))\n"
},
{
"answer_id": 74575906,
"author": "RufusVS",
"author_id": 925592,
"author_profile": "https://Stackoverflow.com/users/925592",
"pm_score": 0,
"selected": false,
"text": "truthiness my_match = lambda s : bool(re.match(\"^[a-zA-Z]+\", s))\n"
},
{
"answer_id": 74576021,
"author": "John Gordon",
"author_id": 494134,
"author_profile": "https://Stackoverflow.com/users/494134",
"pm_score": 0,
"selected": false,
"text": "re.match() True False match() def my_match(s):\n return re.match(\"^[a-zA-Z]+\", s)\n if my_match(x):\n ...\nelse:\n ...\n my_match() re.match(...) if re.match(...):\n ...\nelse:\n ...\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/738154/"
] |
74,575,802
|
<p>I have a list values_count which contains boolean values True and False. I am trying to calculate number of True values present in the list. For example , for the list ltr=[False,True,True,True] I expect my answer to be 3 but my answer comes 0, the initial value of the count variable that I have declared. Below is my code.</p>
<pre><code> class Solution(object):
def count_true(self, values_count=[]):
am = 0
for i in values_count:
if values_count[i] == True:
am + 1
return am
else:
pass
if __name__ == '__main__':
p = Solution()
ltr = [False, True, True, True]
print(p.count_true(ltr))
</code></pre>
|
[
{
"answer_id": 74575841,
"author": "Frank",
"author_id": 13483275,
"author_profile": "https://Stackoverflow.com/users/13483275",
"pm_score": 1,
"selected": false,
"text": "return re.match(\"^[a-zA-Z]+\", s) is not None\n"
},
{
"answer_id": 74575846,
"author": "CoffeeTableEspresso",
"author_id": 7339171,
"author_profile": "https://Stackoverflow.com/users/7339171",
"pm_score": 2,
"selected": true,
"text": "import re\n\ndef my_match(s):\n return True if re.match(\"^[a-zA-Z]+\", s) else False\n val_when_true if cond else val_when_false cond ? val_when_true : val_when_false import re\n\ndef my_match(s):\n return bool(re.match(\"^[a-zA-Z]+\", s))\n"
},
{
"answer_id": 74575906,
"author": "RufusVS",
"author_id": 925592,
"author_profile": "https://Stackoverflow.com/users/925592",
"pm_score": 0,
"selected": false,
"text": "truthiness my_match = lambda s : bool(re.match(\"^[a-zA-Z]+\", s))\n"
},
{
"answer_id": 74576021,
"author": "John Gordon",
"author_id": 494134,
"author_profile": "https://Stackoverflow.com/users/494134",
"pm_score": 0,
"selected": false,
"text": "re.match() True False match() def my_match(s):\n return re.match(\"^[a-zA-Z]+\", s)\n if my_match(x):\n ...\nelse:\n ...\n my_match() re.match(...) if re.match(...):\n ...\nelse:\n ...\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20502753/"
] |
74,575,809
|
<p>I am not able to convert from decimal to binary in C.Everytime I get a output which is one less than the desired output.For ex.:5 should be 101 but shows up as 100 or 4 should be 100 but shows up as 99.</p>
<pre><code>#include<stdio.h>
#include<math.h>
void main() {
int a,b=0;
int n;
printf("Enter a Decimal Number\n");
scanf("%d",&n);
for(int i=0;n>0;i++) {
a=n%2;
n=n/2;
b=b+(pow(10,i)*a);
}
printf("%d",b);
}
</code></pre>
<p>My output is always one less than the correct answer and I dont know why.It fixes the problem if take b as 1 instead of 0 in the beginning but i dont know why.Please Help.I have just started C a few days ago.</p>
|
[
{
"answer_id": 74576201,
"author": "Eric Postpischil",
"author_id": 298225,
"author_profile": "https://Stackoverflow.com/users/298225",
"pm_score": 1,
"selected": false,
"text": "pow double double pow int unsigned char scanf(\"%d\",&n); n n"
},
{
"answer_id": 74576293,
"author": "Ashish Neupane",
"author_id": 7553113,
"author_profile": "https://Stackoverflow.com/users/7553113",
"pm_score": 0,
"selected": false,
"text": "pow() pow() #include<stdio.h>\nvoid main() {\n int remainder,result = 0,multiplier = 1;\n int input;\n printf(\"Enter a Decimal Number\\n\");\n scanf(\"%d\",&input);\n while(input){\n remainder = input%2;\n result = remainder*multiplier + result;\n multiplier*=10;\n input/=2;\n }\n printf(\"The binary version of the decimal value is: %d\",result);\n}\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20555048/"
] |
74,575,858
|
<p>i have a list of usernames, which are basically accounts</p>
<pre><code>let users = [
"user1","user2","user3","user4","user5","user6","user7"
]
</code></pre>
<pre><code>users.map(async (user, i) => {
console.log(user, i)
let res = await sendmessage(user)
if(res) {
console.log("Message Sent to: " + user)
}
})
</code></pre>
<p>What should happen, is it wait 3 seconds, then send message, then wait 3 seconds, then send message, but what actually is happening.
=> <code>console.log(user, i)</code> it executes this all at once,
I don't understand what is wrong with my code?</p>
|
[
{
"answer_id": 74575935,
"author": "Finbar",
"author_id": 17525834,
"author_profile": "https://Stackoverflow.com/users/17525834",
"pm_score": 2,
"selected": false,
"text": "const wait = async (ms) => {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n })\n}\n\nconst users = [\n \"user1\",\"user2\",\"user3\",\"user4\",\"user5\",\"user6\",\"user7\"\n];\n\n\nfor(let i = 0; i < users.length; i++){\n const user = users[i];\n let res = await sendmessage(user)\n if(res) {\n console.log(\"Message Sent to: \" + user)\n }\n await wait(3000);\n}\n"
},
{
"answer_id": 74575937,
"author": "Jaood_xD",
"author_id": 18891587,
"author_profile": "https://Stackoverflow.com/users/18891587",
"pm_score": 3,
"selected": true,
"text": "map for of let users = [\n\"user1\",\"user2\",\"user3\",\"user4\",\"user5\",\"user6\",\"user7\"\n]\nfor (const user of users){\n console.log(user)\n let res = await sendmessage(user)\n if(res) {\n console.log(\"Message Sent to: \" + user)\n }\n}\n"
},
{
"answer_id": 74575949,
"author": "Sarkar",
"author_id": 13741787,
"author_profile": "https://Stackoverflow.com/users/13741787",
"pm_score": 1,
"selected": false,
"text": "for(let i = 0; i < users.length; i++){\n let user = users[i];\n let res = await sendmessage(user)\n if(res) {\n console.log(\"Message Sent to: \" + user)\n }\n}\n"
},
{
"answer_id": 74576035,
"author": "epascarello",
"author_id": 14104,
"author_profile": "https://Stackoverflow.com/users/14104",
"pm_score": 0,
"selected": false,
"text": "let users = [\n\"user1\",\"user2\",\"user3\",\"user4\",\"user5\",\"user6\",\"user7\"\n]\n\n\n\nconst sendMessage = (users, message, delay) => {\n\n const remaining = users.slice();\n \n const send = () => {\n const user = remaining.shift(); \n console.log(message, user);\n \n if (remaining.length) {\n setTimeout(send, delay);\n }\n }\n \n send();\n}\n\nsendMessage(users, \"hello\", 1000);"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19709381/"
] |
74,575,867
|
<p>I have this POD file:</p>
<pre><code>=head1 Create professional slideshows with Mojolicious::Plugin::RevealJS
=head2 Install and run a Mojolicious server
Santa's elf had a problem. He had to write very fast a presentation and show it to a bunch of new elf's.
The email assigning this to him was sent by Santa himself.
The elf started to look on Metacpan and found this module: L<Mojolicious::Plugin::RevealJS|https://metacpan.org/pod/Mojolicious::Plugin::RevealJS>
He quickly typed the following commands:
C<cpanm Mojolicius Mojolicious::Plugin::RevealJS>
Now he could generate an mojo lite app using:
C<mojo generate lite-app slide_show>
Because the elf was trained in the ancient arts of the elders
he cloud open new file with vim and paste this code in:
=begin perl
use Mojolicious::Lite -signatures;
app->static->paths(['.']);
plugin 'RevealJS';
any '/' => { template => 'presentation', layout => 'revealjs' };
app->start;
=end perl
</code></pre>
<p>When I run <code>perldoc t.pod</code>, the code between '=begin perl' and '=end perl' is not visible. I don't understand what I'm doing wrong.</p>
|
[
{
"answer_id": 74575972,
"author": "simbabque",
"author_id": 1331451,
"author_profile": "https://Stackoverflow.com/users/1331451",
"pm_score": 3,
"selected": true,
"text": "perldoc perl perl \n=head2 frobnicate($foo)\n\nThis function frobnicates the C<$foo>.\n\n my $bar = frobnicate($foo)\n\n=cut\n\nsub frobnicate { ... }\n"
},
{
"answer_id": 74576018,
"author": "Dave Cross",
"author_id": 7231,
"author_profile": "https://Stackoverflow.com/users/7231",
"pm_score": 2,
"selected": false,
"text": "=begin <format> =end <format> =begin perl =end perl"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6115421/"
] |
74,575,889
|
<p>Whenever i change the background color of a button in CSS, it becomes unclickable. Same happens if i remove button border in css</p>
<p>HTML</p>
<pre><code><div class="row">
<button onclick="click('7')" class="btn">7</button>
<button onclick="click('8')" class="btn">8</button>
<button onclick="click('9')" class="btn">9</button>
<button onclick="click('/')" class="btn">/</button>
</div>
</code></pre>
<p>CSS</p>
<pre><code>.btn{
width: 60px;
height: 60px;
margin-left: 30px;
margin-top: 25px;
background: beige;
}
</code></pre>
|
[
{
"answer_id": 74575972,
"author": "simbabque",
"author_id": 1331451,
"author_profile": "https://Stackoverflow.com/users/1331451",
"pm_score": 3,
"selected": true,
"text": "perldoc perl perl \n=head2 frobnicate($foo)\n\nThis function frobnicates the C<$foo>.\n\n my $bar = frobnicate($foo)\n\n=cut\n\nsub frobnicate { ... }\n"
},
{
"answer_id": 74576018,
"author": "Dave Cross",
"author_id": 7231,
"author_profile": "https://Stackoverflow.com/users/7231",
"pm_score": 2,
"selected": false,
"text": "=begin <format> =end <format> =begin perl =end perl"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20512460/"
] |
74,575,954
|
<p>I'm looking for a way to do a file search between two dates and I'm searching for a method to make this <strong>more beautiful than my example below</strong> , I specify that this example code below works</p>
<p>I know the ansible <code>find</code> module exists but I can't perform a search between two dates like I want to implement in my example (or at least I didn't succeed)</p>
<ol>
<li><p>file search between the 2022-09-26 and the 2022-10-26</p>
</li>
<li><p>create some files for the test <code>touch -d "35 days ago" /tmp/toto /tmp/tata /tmp/tutu.zip</code></p>
</li>
<li><p>run the playbook</p>
</li>
</ol>
<pre class="lang-yaml prettyprint-override"><code>- name: "test find"
gather_facts: false
become: yes
hosts: "localhost"
tasks:
- name: "create vars"
set_fact:
path_to_find: "/tmp"
BEGIN_DATE: "{{lookup('pipe','date -d \"2 months ago\" -I')}}"
END_DATE: "{{lookup('pipe','date -d \"1 months ago\" -I')}}"
ZIP_NAME: "archive_test_name.zip"
- name: "find between two dates "
shell: find "{{ path_to_find }}" -type f ! -name "*.zip" -newermt "{{ BEGIN_DATE }}" ! -newermt "{{ END_DATE }}"
register: FindFiles
- debug:
msg: "{{ FindFiles }}"
</code></pre>
<p>I hope someone has an idea or a best practice !</p>
|
[
{
"answer_id": 74578073,
"author": "Vladimir Botka",
"author_id": 6482561,
"author_profile": "https://Stackoverflow.com/users/6482561",
"pm_score": 3,
"selected": true,
"text": "shell> ls -ogla /tmp/test/\ntotal 28\ndrwxrwxr-x 2 4096 Nov 25 21:23 .\ndrwxrwxrwt 70 20480 Nov 25 22:28 ..\n-rw-rw-r-- 1 0 Jul 25 00:00 file1\n-rw-rw-r-- 1 0 Aug 25 00:00 file2\n-rw-rw-r-- 1 0 Sep 25 00:00 file3\n-rw-rw-r-- 1 0 Oct 25 00:00 file4\n-rw-rw-r-- 1 0 Nov 25 00:00 file5\n begin_date: \"{{ lookup('pipe', 'date -d \\\"2 months ago\\\" -I') }}\"\n end_date: \"{{ lookup('pipe', 'date -d \\\"1 months ago\\\" -I') }}\"\n today: \"{{ '%Y-%m-%d'|strftime }}\"\n begin_days: \"{{ ((today|to_datetime('%Y-%m-%d')) -\n (begin_date|to_datetime('%Y-%m-%d'))).days }}\"\n end_days: \"{{ ((today|to_datetime('%Y-%m-%d')) -\n (end_date|to_datetime('%Y-%m-%d'))).days }}\"\n begin_date: 2022-09-25\n end_date: 2022-10-25\n today: 2022-11-25\n begin_days: 61\n end_days: 31\n - find:\n path: /tmp/test\n age: \"{{ begin_days }}d\"\n register: begin\n\n - find:\n path: /tmp/test\n age: \"{{ end_days }}d\"\n register: end\n begin_files: \"{{ begin.files|map(attribute='path')|list }}\"\n end_files: \"{{ end.files|map(attribute='path')|list }}\"\n my_files: \"{{ end_files|difference(begin_files) }}\"\n begin_files: ['/tmp/test/file3', '/tmp/test/file2', '/tmp/test/file1']\n end_files: ['/tmp/test/file3', '/tmp/test/file4', '/tmp/test/file2', '/tmp/test/file1']\n my_files: ['/tmp/test/file4']\n - hosts: localhost\n\n vars:\n\n today: \"{{ '%Y-%m-%d'|strftime }}\"\n begin_date: \"{{ lookup('pipe', 'date -d \\\"2 months ago\\\" -I') }}\"\n end_date: \"{{ lookup('pipe', 'date -d \\\"1 months ago\\\" -I') }}\"\n begin_days: \"{{ ((today|to_datetime('%Y-%m-%d')) -\n (begin_date|to_datetime('%Y-%m-%d'))).days }}\"\n end_days: \"{{ ((today|to_datetime('%Y-%m-%d')) -\n (end_date|to_datetime('%Y-%m-%d'))).days }}\"\n begin_files: \"{{ begin.files|map(attribute='path')|list }}\"\n end_files: \"{{ end.files|map(attribute='path')|list }}\"\n my_files: \"{{ end_files|difference(begin_files) }}\"\n\n tasks:\n\n - debug:\n msg: |\n today: {{ today }}\n begin_date: {{ begin_date }}\n end_date: {{ end_date }}\n begin_days: {{ begin_days }}\n end_days: {{ end_days }}\n\n - find:\n path: /tmp/test\n age: \"{{ begin_days }}d\"\n register: begin\n\n - find:\n path: /tmp/test\n age: \"{{ end_days }}d\"\n register: end\n\n - debug:\n msg: |\n begin_files: {{ begin_files }}\n end_files: {{ end_files }}\n my_files: {{ my_files }}\n begin_date_cmd: \"date -d '2 months ago' '+%s'\"\n begin_date: \"{{ lookup('pipe', begin_date_cmd) }}\"\n end_date_cmd: \"date -d '1 months ago' '+%s'\"\n end_date: \"{{ lookup('pipe', end_date_cmd) }}\"\n begin_date: 1664143922\n end_date: 1666735922\n files_all: \"{{ all.files|map(attribute='path')|list }}\"\n - find:\n path: /tmp/test\n register: all\n - stat:\n path: \"{{ item }}\"\n register: st\n loop: \"{{ files_all }}\"\n my_files: \"{{ st.results|selectattr('stat.mtime', 'gt', begin_date|float)|\n selectattr('stat.mtime', 'lt', end_date|float)|\n map(attribute='item')|list }}\"\n my_files:\n - /tmp/test/file4\n - hosts: localhost\n\n vars:\n\n begin_date_cmd: \"date -d '2 months ago' '+%s'\"\n begin_date: \"{{ lookup('pipe', begin_date_cmd) }}\"\n end_date_cmd: \"date -d '1 months ago' '+%s'\"\n end_date: \"{{ lookup('pipe', end_date_cmd) }}\"\n files_all: \"{{ all.files|map(attribute='path')|list }}\"\n my_files: \"{{ st.results|selectattr('stat.mtime', 'gt', begin_date|float)|\n selectattr('stat.mtime', 'lt', end_date|float)|\n map(attribute='item')|list }}\"\n\n tasks:\n\n - debug:\n msg: |\n begin_date: {{ begin_date }}\n end_date: {{ end_date }}\n\n - find:\n path: /tmp/test\n register: all\n - debug:\n var: files_all\n\n - stat:\n path: \"{{ item }}\"\n register: st\n loop: \"{{ files_all }}\"\n - debug:\n var: st\n \n - debug:\n var: my_files\n"
},
{
"answer_id": 74614509,
"author": "U880D",
"author_id": 6771046,
"author_profile": "https://Stackoverflow.com/users/6771046",
"pm_score": 1,
"selected": false,
"text": "find path begin end between.sh #!/bin/sh\n\nexec 3>&1 4>&2 > /dev/null 2>&1\n\n# Create functions\n\nfunction return_json() {\n\n exec 1>&3 2>&4\n\n jq --null-input --monochrome-output \\\n --arg changed \"$changed\" \\\n --arg rc \"$rc\" \\\n --arg stdout \"$stdout\" \\\n --arg stderr \"$stderr\" \\\n --arg files \"$files\" \\\n '$ARGS.named'\n\n exec 3>&1 4>&2 > /dev/null 2>&1\n\n}\n\n# Set default values\n\nchanged=\"false\"\nrc=0\nstdout=\"\"\nstderr=\"\"\nfiles=\"[]\"\n\nsource \"$1\" # to read the tmp file and source the parameters given by Ansible\n\n# Check prerequisites\n\nif ! which jq &>/dev/null; then\n exec 1>&3 2>&4\n printf \"{ \\\"changed\\\": \\\"$changed\\\",\n \\\"rc\\\": \\\"1\\\" ,\n \\\"stdout\\\": \\\"\\\",\n \\\"stderr\\\": \\\"Command not found: This module require 'jq' installed on the target host. Exiting ...\\\",\n \\\"files\\\": \\\"[]\\\"}\"\n exit 127\nfi\n\nif ! grep -q \"Red Hat Enterprise Linux\" /etc/redhat-release; then\n stderr=\"Operation not supported: Red Hat Enterprise Linux not found. Exiting ...\"\n rc=95\n\n return_json\n\n exit $rc\nfi\n\n# Validate parameter key and value\n\nif [ -z \"$path\" ]; then\n stderr=\"Invalid argument: Parameter path is not provided. Exiting ...\"\n rc=22\n\n return_json\n\n exit $rc\nfi\n\nif [[ $path == *['!:*']* ]]; then\n stderr=\"Invalid argument: Value path contains invalid characters. Exiting ...\"\n rc=22\n\n return_json\n\n exit $rc\nfi\n\nif [ ${#path} -ge 127 ]; then\n stderr=\"Argument too long: Value path has too many characters. Exiting ...\"\n rc=7\n\n return_json\n\n exit $rc\nfi\n\n# Main (logic part)\n\n if [ -d \"$path\" ]; then\n files=$(find $path -type f -name \"file*\" -newermt \"$begin\" ! -newermt \"$end\" | jq --raw-input . | jq --slurp .)\n else\n stderr=\"Cannot access: No such directory or Permission denied.\"\n rc=1\n fi\n\n# Return\n\nchanged=\"false\"\n\nreturn_json\n\nexit $rc\n between.yml ---\n- hosts: test\n become: false\n gather_facts: false\n\n tasks:\n\n - name: Get files between\n between:\n path: \"/home/{{ ansible_user }}/files\"\n begin: \"3 month ago\"\n end: \"1 month ago\"\n register: result\n\n - name: Show result\n debug:\n var: result.files\n ls -ogla /home/${ANSIBLE_USER}/files\ntotal 8\ndrwxr-xr-x. 2 4096 Nov 29 11:41 .\ndrwx------. 37 4096 Nov 29 14:04 ..\n-rw-r--r--. 1 0 Jul 29 12:43 file1.zip\n-rw-r--r--. 1 0 Aug 29 12:44 file2.zip\n-rw-r--r--. 1 0 Sep 29 12:44 file3.zip\n-rw-r--r--. 1 0 Oct 29 12:44 file4.zip\n-rw-r--r--. 1 0 Nov 29 11:41 file5.zip\n sshpass -p ${PASSWORD} ansible-playbook --user ${ANSIBLE_USER} --ask-pass between.yml TASK [Show result] ***********\nok: [test.example.com] =>\n result.files:\n - /home/user/files/file4.zip\n - /home/user/files/file3.zip\n -name \"file*\""
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16174465/"
] |
74,575,957
|
<p>I am trying to setup Cordova for running cordova-android9.0. My problem is that when I downgraded my java version, it no longer works.</p>
<p>I downloaded <a href="https://www.oracle.com/java/technologies/downloads/#java8-windows" rel="nofollow noreferrer">Java 8</a> and set my environment variables to:
<strong>User variable Path</strong> to:
<code>C:\Program Files\Java\jdk1.8.0_351\bin</code>
and Gradle to this version:
<code>C:\Gradle\gradle-4.10.3\bin</code> (recommended by Cordova)</p>
<p><strong>System variables:</strong></p>
<pre><code>JAVA_HOME C:\Program Files\Java\jdk1.8.0_351
</code></pre>
<p>and Path the same as on user variables</p>
<p>When I run <code>java -version</code> in terminal it gives me error message:</p>
<pre><code>Error occurred during initialization of VM
Failed setting boot class path.
</code></pre>
<p>I cannot figure out why Java is not responding correctly</p>
|
[
{
"answer_id": 74576524,
"author": "Kaushal",
"author_id": 20593455,
"author_profile": "https://Stackoverflow.com/users/20593455",
"pm_score": 0,
"selected": false,
"text": "C:\\Program Files\\Java\\jdk1.8.0_351\\bin\n C:\\Program Files(x86)\\Java\\jdk1.8.0_351\\bin"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4492357/"
] |
74,575,988
|
<p>I'm not very long in Django, sorry for the probably stupid question.
But after many hours of trying to solve and a huge number of searches on the Internet, I did not find a solution.</p>
<p>My Models:</p>
<pre><code>class Offer(models.Model):
seller = models.ForeignKey()<..>
# other fields
</code></pre>
<pre><code>class OfferViewCount(models.Model):
offer = models.ForeignKey(Offer, verbose_name=_('Offer'), on_delete=models.CASCADE)
user_agent = models.CharField(verbose_name=_('User Agent'), max_length=200)
ip_address = models.CharField(verbose_name=_('IP Address'), max_length=32)
created_date = models.DateTimeField(auto_now_add=True)
</code></pre>
<p>The database of the OfferViewCount model has the following data:</p>
<pre><code>id;user_agent;ip_address;created_date;offer_id
24;insomnia/2022.6.0f;127.0.0.1;2022-11-18 14:14:52.501008+00;192
25;insomnia/2022.6.0z;127.0.0.1;2022-11-18 15:03:31.471366+00;192
23;insomnia/2022.6.0;127.0.0.1;2022-11-18 14:14:49.840141+00;193
28;insomnia/2022.6.0;127.0.0.1;2022-11-18 15:04:18.867051+00;195
29;insomnia/2022.6.0;127.0.0.1;2022-11-21 11:33:15.719524+00;195
30;test;127.0.1.1;2022-11-22 19:34:39+00;195
</code></pre>
<p>If I use the default output in Django Admin like this:</p>
<pre><code>class OfferViewCountAdmin(admin.ModelAdmin):
list_display = ('offer',)
</code></pre>
<p>I get this:</p>
<pre><code>Offer
offer #192
offer #192
offer #193
offer #195
offer #195
offer #195
</code></pre>
<p>I want to get a result like this:</p>
<pre><code>Offer;Views
offer #192;2
offer #193;1
offer #195;3
</code></pre>
<p>Simply put, I want to display one instance of each duplicate post in the admin, and display the total number of them in a custom field.
In SQL it would look something like this:</p>
<pre><code>SELECT offer_id, COUNT(*) AS count FROM offer_offerviewcount GROUP BY offer_id ORDER BY COUNT DESC;
</code></pre>
<p>I've tried many options, including overwriting get_queryset.
In general, I managed to achieve the desired result like this:</p>
<pre><code>class OfferViewCountAdmin(admin.ModelAdmin):
list_display = ('offer', 'get_views')
list_filter = ['created_date', 'offer']
list_per_page = 20
def get_views(self, obj):
return OfferViewCount.objects.filter(offer=obj.offer).count()
def get_queryset(self, request):
qs = OfferViewCount.objects.filter(
~Exists(OfferViewCount.objects.filter(
Q(offer__lt=OuterRef('offer')) | Q(offer=OuterRef('offer'), pk__lt=OuterRef('pk')),
offer=OuterRef('offer')
))
)
return qs
get_views.short_description = _('Views')
</code></pre>
<p>But in this case, sorting by Views does not work.
If I add it explicitly via admin_order_field for get_views, I get an error because there is no such field in the database.
To avoid such an error, it is necessary to fasten the overwritten annotate queriset, something like this:</p>
<pre><code>qs = OfferViewCount.objects.filter(
~Exists(OfferViewCount.objects.filter(
Q(offer__lt=OuterRef('offer')) | Q(offer=OuterRef('offer'), pk__lt=OuterRef('pk')),
offer=OuterRef('offer')
))
).annotate(_views_count=Count('offer'))
</code></pre>
<p>And change <code>get_views</code> to:</p>
<pre><code>def get_views(self, obj):
return obj._views_count
</code></pre>
<p>But in this case, <code>Count('offer')</code> always returns 1, probably because not the entire base is analyzed there.</p>
<p>Actually, tell me, please, how to add a working sorting?
If there is some much simpler way (without <code>~Exists</code> and constructions with <code>Q()|Q()</code>).</p>
|
[
{
"answer_id": 74580970,
"author": "Md Shahbaz Ahmad",
"author_id": 7584066,
"author_profile": "https://Stackoverflow.com/users/7584066",
"pm_score": 0,
"selected": false,
"text": "from django.db.models import Count\n\ndef get_queryset(self, request):\n qs = OfferViewCount.objects.values(\n 'offer'\n ).annotate(\n offer_count=Count('id')\n ).order_by(\"-offer_count\")\n return qs\n SELECT \n`offer_offerviewcount`.`offer_id`, \nCOUNT(`offer_offerviewcount`.`id`) AS `offer_count` \nFROM `offer_offerviewcount` \nGROUP BY `offer_offerviewcount`.`offer_id` \nORDER BY `offer_count` DESC\n"
},
{
"answer_id": 74590377,
"author": "alvand_ashhadi",
"author_id": 19617077,
"author_profile": "https://Stackoverflow.com/users/19617077",
"pm_score": 1,
"selected": false,
"text": "def get_queryset(self, request):\n qs = OfferViewCount.objects.values(\"offer\")\n .annotate(count=Count(\"offer\")).distinct().order_by(\"count\")\n return qs\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20601125/"
] |
74,576,013
|
<p>I am trying to increase the values of an array of integers using a variable, but it doesn't seem to be accessing the array values properly.
It is to start from 0 in an ascending order, while incrementing the current array value at each iteration.
I tried this:</p>
<pre><code>array=(2 0 1)
tag=(H H H)
count=0
for i in ${array[@]}
do
if [[ "$array[$i]"="$count" ]]
then
array[$i]=$((${array[$i]}+1))
tag[$i]="C"
fi
count=$(($count + 1))
done
</code></pre>
<p>Instead it kept updating from 2, then 1, before 0. I want it to start from 0, since that is the index that is equal to count.
This was the output.</p>
<pre><code> 0 H H C
2 0 2
1 C H C
3 0 2
2 C C C
3 1 2
</code></pre>
|
[
{
"answer_id": 74577004,
"author": "chuckj",
"author_id": 2415831,
"author_profile": "https://Stackoverflow.com/users/2415831",
"pm_score": 0,
"selected": false,
"text": "for array tag array tag array tag declare -a array=(2 0 1)\ndeclare -a tag=(\"here\" \"here\" \"here\")\ndeclare -i count=0\ndeclare -i i\n\necho \"$count: ${array[*]}\"\necho \" ${tag[*]}\"\n\nfor (( i=0; i<${#array[*]}; ++i )); do\n (( array[i]++ )) # no need for '$' within (( ))\n tag[$i]=\"changed\"\n (( count++ ))\n echo \"$count: ${array[*]}\"\n echo \" ${tag[*]}\"\ndone\n echo"
},
{
"answer_id": 74577133,
"author": "Vab",
"author_id": 17600005,
"author_profile": "https://Stackoverflow.com/users/17600005",
"pm_score": 0,
"selected": false,
"text": "0 array 3 3 $array $tag #!/bin/bash\n#array=(2 0 1) \n\n# Advantage of the logic of this script is that you may have more elements\n# in $tag array but are able to change only a few of them that is mentioned in $array.\narray=(2 3 1) # Change 2nd, 3rd, 1st elements accordingly.\ntag=(H H H)\n\nfor i in `seq 1 ${#array[@]}` ;do\n (( i-- ))\n ii=\"${array[i]}\"\n (( ii-- ))\n tag[$ii]=\"C\"\n echo -e \"$i:\\t${tag[@]}\"\ndone\n 0: H C H\n1: H C C\n2: C C C\n"
},
{
"answer_id": 74577224,
"author": "Andrej Podzimek",
"author_id": 8584929,
"author_profile": "https://Stackoverflow.com/users/8584929",
"pm_score": 1,
"selected": false,
"text": "\"${!array[@]}\" array=(2 0 1)\ntag=(H H H)\necho \"${array[@]@A}; ${tag[@]@A};\"\n\nfor index in \"${!array[@]}\"; do\n ((++array[index]))\n tag[index]=C\n echo \"${array[@]@A}; ${tag[@]@A};\"\ndone\n declare -a array=([0]=\"2\" [1]=\"0\" [2]=\"1\"); declare -a tag=([0]=\"H\" [1]=\"H\" [2]=\"H\");\ndeclare -a array=([0]=\"3\" [1]=\"0\" [2]=\"1\"); declare -a tag=([0]=\"C\" [1]=\"H\" [2]=\"H\");\ndeclare -a array=([0]=\"3\" [1]=\"1\" [2]=\"1\"); declare -a tag=([0]=\"C\" [1]=\"C\" [2]=\"H\");\ndeclare -a array=([0]=\"3\" [1]=\"1\" [2]=\"2\"); declare -a tag=([0]=\"C\" [1]=\"C\" [2]=\"C\");\n"
},
{
"answer_id": 74579657,
"author": "Bach Lien",
"author_id": 3973676,
"author_profile": "https://Stackoverflow.com/users/3973676",
"pm_score": 0,
"selected": false,
"text": "count count tag #!/bin/bash\narray=(2 0 1)\ntag=(H H H)\nn=${#array[*]} ## array size\necho \"${array[@]@A}; ${tag[@]@A};\" ## for testing\nfor (( count=0; count<n; ++count )); do\n for (( i=0; i<n; ++i )); do\n if [[ ${array[$i]} -eq $count && ${tag[$i]} = \"H\" ]]; then\n (( array[i]++ ))\n tag[$i]=\"C\" ## C=changed\n break ## break inner loop\n fi\n done\n echo \"${array[@]@A}; ${tag[@]@A};\" ## for testing\ndone\n declare -a array=([0]=\"2\" [1]=\"0\" [2]=\"1\"); declare -a tag=([0]=\"H\" [1]=\"H\" [2]=\"H\");\ndeclare -a array=([0]=\"2\" [1]=\"1\" [2]=\"1\"); declare -a tag=([0]=\"H\" [1]=\"C\" [2]=\"H\");\ndeclare -a array=([0]=\"2\" [1]=\"1\" [2]=\"2\"); declare -a tag=([0]=\"H\" [1]=\"C\" [2]=\"C\");\ndeclare -a array=([0]=\"3\" [1]=\"1\" [2]=\"2\"); declare -a tag=([0]=\"C\" [1]=\"C\" [2]=\"C\");\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19668361/"
] |
74,576,027
|
<p>I am working on the task where I have to Augment the data. For data augmentation, I have to do polynomial approximation of the data (Non linear data). But if I do the polynomial approximation, I am not getting an accurate approximation of the data.</p>
<p>Below are 35 points which I used as an original data.</p>
<pre><code>x = [0.7375, 0.7405, 0.7445, 0.7488, 0.7515, 0.7545, 0.7593, 0.7625, 0.7657, 0.7687, 0.7715, 0.776, 0.7794, 0.7826, 0.7889, 0.7916, 0.7945, 0.8011, 0.8038, 0.8079, 0.8125, 0.8168, 0.8233, 0.826, 0.8287, 0.8318, 0.8361, 0.8391, 0.845, 0.8506, 0.8534, 0.8563, 0.8595, 0.8625, 0.8734]
y = [7797.61, 7829.59, 7833.6, 7837.02, 7854.76, 7862.18, 7893.06, 7927.04, 7946.49, 7975.83, 8038.12, 8110.94, 8115.37, 8125.11, 8172.58, 8182.54, 8215.06, 8232.01, 8274.98, 8272.71, 8243.45, 8242.93, 8225.08, 8199.25, 8180.92, 8143.29, 8152.09, 8136.59, 8164.3, 8202.04, 8203.57, 8174.67, 8192.0, 8201.25, 8131.32]
</code></pre>
<p>Below picture describes you more.
<a href="https://i.stack.imgur.com/f8yxo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/f8yxo.png" alt="enter image description here" /></a></p>
<p>I have used <code>from sklearn.preprocessing import PolynomialFeatures</code>.</p>
<pre><code>x_plot = np.linspace(min(x), max(x), 1000)
model = make_pipeline(PolynomialFeatures(42), Ridge(alpha=1e-3))
model.fit(x, y)
y_plot = model.predict(x_plot)
r2 = model.score(x,y)
</code></pre>
<p>Where <code>x</code> and <code>y</code> is my original data, 35 points.</p>
<p>I want to get closest to perfect (more accurate) approximation as obtained curve does not represent the accurate enough.</p>
|
[
{
"answer_id": 74577004,
"author": "chuckj",
"author_id": 2415831,
"author_profile": "https://Stackoverflow.com/users/2415831",
"pm_score": 0,
"selected": false,
"text": "for array tag array tag array tag declare -a array=(2 0 1)\ndeclare -a tag=(\"here\" \"here\" \"here\")\ndeclare -i count=0\ndeclare -i i\n\necho \"$count: ${array[*]}\"\necho \" ${tag[*]}\"\n\nfor (( i=0; i<${#array[*]}; ++i )); do\n (( array[i]++ )) # no need for '$' within (( ))\n tag[$i]=\"changed\"\n (( count++ ))\n echo \"$count: ${array[*]}\"\n echo \" ${tag[*]}\"\ndone\n echo"
},
{
"answer_id": 74577133,
"author": "Vab",
"author_id": 17600005,
"author_profile": "https://Stackoverflow.com/users/17600005",
"pm_score": 0,
"selected": false,
"text": "0 array 3 3 $array $tag #!/bin/bash\n#array=(2 0 1) \n\n# Advantage of the logic of this script is that you may have more elements\n# in $tag array but are able to change only a few of them that is mentioned in $array.\narray=(2 3 1) # Change 2nd, 3rd, 1st elements accordingly.\ntag=(H H H)\n\nfor i in `seq 1 ${#array[@]}` ;do\n (( i-- ))\n ii=\"${array[i]}\"\n (( ii-- ))\n tag[$ii]=\"C\"\n echo -e \"$i:\\t${tag[@]}\"\ndone\n 0: H C H\n1: H C C\n2: C C C\n"
},
{
"answer_id": 74577224,
"author": "Andrej Podzimek",
"author_id": 8584929,
"author_profile": "https://Stackoverflow.com/users/8584929",
"pm_score": 1,
"selected": false,
"text": "\"${!array[@]}\" array=(2 0 1)\ntag=(H H H)\necho \"${array[@]@A}; ${tag[@]@A};\"\n\nfor index in \"${!array[@]}\"; do\n ((++array[index]))\n tag[index]=C\n echo \"${array[@]@A}; ${tag[@]@A};\"\ndone\n declare -a array=([0]=\"2\" [1]=\"0\" [2]=\"1\"); declare -a tag=([0]=\"H\" [1]=\"H\" [2]=\"H\");\ndeclare -a array=([0]=\"3\" [1]=\"0\" [2]=\"1\"); declare -a tag=([0]=\"C\" [1]=\"H\" [2]=\"H\");\ndeclare -a array=([0]=\"3\" [1]=\"1\" [2]=\"1\"); declare -a tag=([0]=\"C\" [1]=\"C\" [2]=\"H\");\ndeclare -a array=([0]=\"3\" [1]=\"1\" [2]=\"2\"); declare -a tag=([0]=\"C\" [1]=\"C\" [2]=\"C\");\n"
},
{
"answer_id": 74579657,
"author": "Bach Lien",
"author_id": 3973676,
"author_profile": "https://Stackoverflow.com/users/3973676",
"pm_score": 0,
"selected": false,
"text": "count count tag #!/bin/bash\narray=(2 0 1)\ntag=(H H H)\nn=${#array[*]} ## array size\necho \"${array[@]@A}; ${tag[@]@A};\" ## for testing\nfor (( count=0; count<n; ++count )); do\n for (( i=0; i<n; ++i )); do\n if [[ ${array[$i]} -eq $count && ${tag[$i]} = \"H\" ]]; then\n (( array[i]++ ))\n tag[$i]=\"C\" ## C=changed\n break ## break inner loop\n fi\n done\n echo \"${array[@]@A}; ${tag[@]@A};\" ## for testing\ndone\n declare -a array=([0]=\"2\" [1]=\"0\" [2]=\"1\"); declare -a tag=([0]=\"H\" [1]=\"H\" [2]=\"H\");\ndeclare -a array=([0]=\"2\" [1]=\"1\" [2]=\"1\"); declare -a tag=([0]=\"H\" [1]=\"C\" [2]=\"H\");\ndeclare -a array=([0]=\"2\" [1]=\"1\" [2]=\"2\"); declare -a tag=([0]=\"H\" [1]=\"C\" [2]=\"C\");\ndeclare -a array=([0]=\"3\" [1]=\"1\" [2]=\"2\"); declare -a tag=([0]=\"C\" [1]=\"C\" [2]=\"C\");\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17289097/"
] |
74,576,048
|
<p>I have a table <code>CabinCrew</code> and another table <code>Employee</code>. The <code>CabinCrew</code> table, among other things, records the <code>FlightHours</code> of the crew for a particular flight.</p>
<p><code>CabinCrew(EmployeeID, FlightID, Hours)</code></p>
<p><code>Employee(EmployeeID, FirstName, LastName, Email, JobTitle, FlightHours)</code></p>
<p><code>EmployeeID</code> is the primary key of the <code>Employee</code> table and both the primary and foreign key of the <code>CabinCrew</code> table.</p>
<p>The <code>Employee</code> table also has an attribute <code>FlightHours</code>, which is the total flying hours for the crew. How do I create a trigger such that an entry in the <code>CabinCrew</code> table, triggers an update on the <code>Employee</code> table which adds the <code>FlightHours</code> from <code>CabinCrew</code> to the total flight hours in the Employee table?</p>
|
[
{
"answer_id": 74577004,
"author": "chuckj",
"author_id": 2415831,
"author_profile": "https://Stackoverflow.com/users/2415831",
"pm_score": 0,
"selected": false,
"text": "for array tag array tag array tag declare -a array=(2 0 1)\ndeclare -a tag=(\"here\" \"here\" \"here\")\ndeclare -i count=0\ndeclare -i i\n\necho \"$count: ${array[*]}\"\necho \" ${tag[*]}\"\n\nfor (( i=0; i<${#array[*]}; ++i )); do\n (( array[i]++ )) # no need for '$' within (( ))\n tag[$i]=\"changed\"\n (( count++ ))\n echo \"$count: ${array[*]}\"\n echo \" ${tag[*]}\"\ndone\n echo"
},
{
"answer_id": 74577133,
"author": "Vab",
"author_id": 17600005,
"author_profile": "https://Stackoverflow.com/users/17600005",
"pm_score": 0,
"selected": false,
"text": "0 array 3 3 $array $tag #!/bin/bash\n#array=(2 0 1) \n\n# Advantage of the logic of this script is that you may have more elements\n# in $tag array but are able to change only a few of them that is mentioned in $array.\narray=(2 3 1) # Change 2nd, 3rd, 1st elements accordingly.\ntag=(H H H)\n\nfor i in `seq 1 ${#array[@]}` ;do\n (( i-- ))\n ii=\"${array[i]}\"\n (( ii-- ))\n tag[$ii]=\"C\"\n echo -e \"$i:\\t${tag[@]}\"\ndone\n 0: H C H\n1: H C C\n2: C C C\n"
},
{
"answer_id": 74577224,
"author": "Andrej Podzimek",
"author_id": 8584929,
"author_profile": "https://Stackoverflow.com/users/8584929",
"pm_score": 1,
"selected": false,
"text": "\"${!array[@]}\" array=(2 0 1)\ntag=(H H H)\necho \"${array[@]@A}; ${tag[@]@A};\"\n\nfor index in \"${!array[@]}\"; do\n ((++array[index]))\n tag[index]=C\n echo \"${array[@]@A}; ${tag[@]@A};\"\ndone\n declare -a array=([0]=\"2\" [1]=\"0\" [2]=\"1\"); declare -a tag=([0]=\"H\" [1]=\"H\" [2]=\"H\");\ndeclare -a array=([0]=\"3\" [1]=\"0\" [2]=\"1\"); declare -a tag=([0]=\"C\" [1]=\"H\" [2]=\"H\");\ndeclare -a array=([0]=\"3\" [1]=\"1\" [2]=\"1\"); declare -a tag=([0]=\"C\" [1]=\"C\" [2]=\"H\");\ndeclare -a array=([0]=\"3\" [1]=\"1\" [2]=\"2\"); declare -a tag=([0]=\"C\" [1]=\"C\" [2]=\"C\");\n"
},
{
"answer_id": 74579657,
"author": "Bach Lien",
"author_id": 3973676,
"author_profile": "https://Stackoverflow.com/users/3973676",
"pm_score": 0,
"selected": false,
"text": "count count tag #!/bin/bash\narray=(2 0 1)\ntag=(H H H)\nn=${#array[*]} ## array size\necho \"${array[@]@A}; ${tag[@]@A};\" ## for testing\nfor (( count=0; count<n; ++count )); do\n for (( i=0; i<n; ++i )); do\n if [[ ${array[$i]} -eq $count && ${tag[$i]} = \"H\" ]]; then\n (( array[i]++ ))\n tag[$i]=\"C\" ## C=changed\n break ## break inner loop\n fi\n done\n echo \"${array[@]@A}; ${tag[@]@A};\" ## for testing\ndone\n declare -a array=([0]=\"2\" [1]=\"0\" [2]=\"1\"); declare -a tag=([0]=\"H\" [1]=\"H\" [2]=\"H\");\ndeclare -a array=([0]=\"2\" [1]=\"1\" [2]=\"1\"); declare -a tag=([0]=\"H\" [1]=\"C\" [2]=\"H\");\ndeclare -a array=([0]=\"2\" [1]=\"1\" [2]=\"2\"); declare -a tag=([0]=\"H\" [1]=\"C\" [2]=\"C\");\ndeclare -a array=([0]=\"3\" [1]=\"1\" [2]=\"2\"); declare -a tag=([0]=\"C\" [1]=\"C\" [2]=\"C\");\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20239849/"
] |
74,576,082
|
<p>We use Shopware 6, V6.4.16.1, community edition. Currently we are only selling in the United States and US Dollar.</p>
<p>When product prices are listed on the frontend, the auto formatting updates them to include the US country ISO code, dollar sign, and an asterisk. The end formatting looks like this: <strong>US$2,999.00</strong>*</p>
<p>We would like to update the formatting to remove the Country Code, asterisk, and cents. Ideally the above price would look like this instead: <strong>$2,999</strong></p>
<p>This occurs on landing pages, listing pages, and product detail pages. Thanks in advance for the help.</p>
<p>Here's an example of the product price formatting currently: <a href="https://i.stack.imgur.com/jZtAV.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jZtAV.jpg" alt="enter image description here" /></a></p>
<ol>
<li>I've tried removing all other currencies and countries from our Shopware settings.</li>
</ol>
|
[
{
"answer_id": 74577530,
"author": "dneustadt",
"author_id": 8556259,
"author_profile": "https://Stackoverflow.com/users/8556259",
"pm_score": 3,
"selected": true,
"text": "CurrencyFormatter <service id=\"My\\Plugin\\Decorator\\CurrencyFormatterDecorator\" decorates=\"Shopware\\Core\\System\\Currency\\CurrencyFormatter\">\n <argument type=\"service\" id=\"My\\Plugin\\Decorator\\CurrencyFormatterDecorator.inner\"/>\n <argument type=\"service\" id=\"Shopware\\Core\\System\\Locale\\LanguageLocaleCodeProvider\"/>\n</service>\n class CurrencyFormatterDecorator extends CurrencyFormatter\n{\n private CurrencyFormatter $decorated;\n\n public function __construct(CurrencyFormatter $decorated, LanguageLocaleCodeProvider $languageLocaleProvider)\n {\n $this->decorated = $decorated;\n parent::__construct($languageLocaleProvider);\n }\n\n public function formatCurrencyByLanguage(float $price, string $currency, string $languageId, Context $context, ?int $decimals = null): string\n {\n $currency = $this->decorated->formatCurrencyByLanguage($price, $currency, $languageId, $context, $decimals);\n\n return str_replace('US$', '$', $currency);\n }\n}\n messages.en-GB general.star"
},
{
"answer_id": 74588649,
"author": "Alex",
"author_id": 288568,
"author_profile": "https://Stackoverflow.com/users/288568",
"pm_score": 0,
"selected": false,
"text": "$ /admin#/sw/settings/currency/index"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576082",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6042057/"
] |
74,576,129
|
<p>I've extracted key words from a different column to make a new column (hard skills) that looks like this:
(<a href="https://i.stack.imgur.com/XNOIK.png" rel="nofollow noreferrer">https://i.stack.imgur.com/XNOIK.png</a>)</p>
<p>But I want to make each key word into a list format within the "hards skills" column.
For example, for the 1st row of "hard skills" column, my desired outcome would be:</p>
<p>['Python Programming', 'Machine Learning', 'Data Analysis'...]</p>
<p>instead of</p>
<p>Python Programming,Machine Learning,Data Analysis...</p>
<p>This is how I filtered the key words out into the new "hard skills" column.</p>
<p>#Filter and make new column for hard skills
hard_skills = ['Python Programming', 'Statistics', 'Statistical Hypothesis Testing','Data Cleansing', 'Tensorflow', 'Machine Learning', 'Data Analysis','Data Visualization', 'Cloud Computing', 'R Programming', 'Data Science','Computer Programming', 'Deep Learning', 'Data Analysis', 'SQL', 'Regression Analysis', 'Algorithms', 'JavaScript', 'Python']</p>
<p>def get_hard_skills(skills):
return_hard_skills = ""
for hard_skill in hard_skills:
if skills.find(hard_skill) >= 0:
if return_hard_skills == "":
return_hard_skills = hard_skill
else:
return_hard_skills = return_hard_skills + "," + hard_skill
if return_hard_skills == "":
return ('not found')
else:
return return_hard_skills</p>
<p>course_name_skills['hard skills'] = ""</p>
<p>#loop through data frame to get hard skills</p>
<p>for i in range(0,len(course_name_skills)-1): #every single line of the data science courses
skills = course_name_skills.loc[i,"skills"]
if not isNaN(skills): #if not empty
course_name_skills.loc[i,"hard skills"] = get_hard_skills(skills)</p>
<p>course_name_skills = course_name_skills.replace('not found',np.NaN)
only_hardskills = course_name_skills.dropna(subset=['hard skills'])</p>
<p>Is there a way I could change the code that filtered the data frame for key words? Or is there a more efficient way?</p>
<p>I tried strip.() or even tried my luck with</p>
<pre><code>return_hard_skills = "[" + return_hard_skills + "," + hard_skill + "]"
</code></pre>
<p>But it didn't come through.</p>
<p>[Dataframe with original column]</p>
<p><img src="https://i.stack.imgur.com/wbZ08.png" alt="1" /></p>
<p><a href="https://i.stack.imgur.com/sC6gD.png" rel="nofollow noreferrer">random, but needed, true or false table generated</a></p>
|
[
{
"answer_id": 74577530,
"author": "dneustadt",
"author_id": 8556259,
"author_profile": "https://Stackoverflow.com/users/8556259",
"pm_score": 3,
"selected": true,
"text": "CurrencyFormatter <service id=\"My\\Plugin\\Decorator\\CurrencyFormatterDecorator\" decorates=\"Shopware\\Core\\System\\Currency\\CurrencyFormatter\">\n <argument type=\"service\" id=\"My\\Plugin\\Decorator\\CurrencyFormatterDecorator.inner\"/>\n <argument type=\"service\" id=\"Shopware\\Core\\System\\Locale\\LanguageLocaleCodeProvider\"/>\n</service>\n class CurrencyFormatterDecorator extends CurrencyFormatter\n{\n private CurrencyFormatter $decorated;\n\n public function __construct(CurrencyFormatter $decorated, LanguageLocaleCodeProvider $languageLocaleProvider)\n {\n $this->decorated = $decorated;\n parent::__construct($languageLocaleProvider);\n }\n\n public function formatCurrencyByLanguage(float $price, string $currency, string $languageId, Context $context, ?int $decimals = null): string\n {\n $currency = $this->decorated->formatCurrencyByLanguage($price, $currency, $languageId, $context, $decimals);\n\n return str_replace('US$', '$', $currency);\n }\n}\n messages.en-GB general.star"
},
{
"answer_id": 74588649,
"author": "Alex",
"author_id": 288568,
"author_profile": "https://Stackoverflow.com/users/288568",
"pm_score": 0,
"selected": false,
"text": "$ /admin#/sw/settings/currency/index"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20601282/"
] |
74,576,152
|
<p>I want to see my result text appear if I type anything into my input field and disappear if it is not.
My JSX:</p>
<pre><code>import React, { useState } from "react";
import "./SearchBarStyle.css"
const SearchBar = () => {
const waterInfo = [
{title: "About Water", link:"https://en.wikipedia.org/wiki/Water"},
{title: "Water (Molecule)", link: "https://en.wikipedia.org/wiki/Properties_of_water"},
{title: "Water (Chemistry)", link: "https://pubchem.ncbi.nlm.nih.gov/compound/Water"}
]
const [input, setInput] = useState("")
const HandleInput = (event) => {
setInput(event.target.value)
}
const filterItems = waterInfo.filter((wI) => {
return wI.title.includes(input)
})
return(
<div>
<input type={"text"} value={input} onChange={HandleInput} placeholder="About Water?" className="searchbar"/>
<ul className="results">
{filterItems.map((wI) => {
return <li><a href={wI.link} target="_blank" className="link">{wI.title}</a></li>
})}
</ul>
</div>
)
}
export default SearchBar
</code></pre>
<p>My CSS:</p>
<pre><code>.results {
text-align: center;
list-style-type: none;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
display: none;
}
.searchbar:focus // 1. How to dectect if I am typing anything into the searchbar {
// 2. How to toggle the results to appear if I type any word into the searchbar
}
</code></pre>
<p>So I want to see my result getting displayed whenever I type something into my searchbar.
In question: 1. How to dectect if I am typing anything into the searchbar
2. How to toggle the results to appear if I type any word into the searchbar</p>
|
[
{
"answer_id": 74577530,
"author": "dneustadt",
"author_id": 8556259,
"author_profile": "https://Stackoverflow.com/users/8556259",
"pm_score": 3,
"selected": true,
"text": "CurrencyFormatter <service id=\"My\\Plugin\\Decorator\\CurrencyFormatterDecorator\" decorates=\"Shopware\\Core\\System\\Currency\\CurrencyFormatter\">\n <argument type=\"service\" id=\"My\\Plugin\\Decorator\\CurrencyFormatterDecorator.inner\"/>\n <argument type=\"service\" id=\"Shopware\\Core\\System\\Locale\\LanguageLocaleCodeProvider\"/>\n</service>\n class CurrencyFormatterDecorator extends CurrencyFormatter\n{\n private CurrencyFormatter $decorated;\n\n public function __construct(CurrencyFormatter $decorated, LanguageLocaleCodeProvider $languageLocaleProvider)\n {\n $this->decorated = $decorated;\n parent::__construct($languageLocaleProvider);\n }\n\n public function formatCurrencyByLanguage(float $price, string $currency, string $languageId, Context $context, ?int $decimals = null): string\n {\n $currency = $this->decorated->formatCurrencyByLanguage($price, $currency, $languageId, $context, $decimals);\n\n return str_replace('US$', '$', $currency);\n }\n}\n messages.en-GB general.star"
},
{
"answer_id": 74588649,
"author": "Alex",
"author_id": 288568,
"author_profile": "https://Stackoverflow.com/users/288568",
"pm_score": 0,
"selected": false,
"text": "$ /admin#/sw/settings/currency/index"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20159329/"
] |
74,576,190
|
<p>I'm learning Python via Udemy and we did a coding project where you have to get a user's height and weight, calculate their BMI and print the result. In my code, for the embedded <code>if</code> (<code>elif</code>) statements, I did something like this (variable is bmi to hold the actual BMI calculation): <code>elif 18.5 < bmi < 25</code></p>
<pre class="lang-py prettyprint-override"><code>if bmi < 18.5:
print(f"Your BMI is {bmi}, you are slightly underweight.")
elif 18.5 < bmi < 25:
print(f"Your BMI is {bmi}, you have a normal weight.")
elif 25 < bmi < 30:
print(f"Your BMI is {bmi}, you are slightly overweight.")
</code></pre>
<p>Now, the instructor instead did this: <code>elif bmi < 25</code>.
She didn't use the format <code>< var <</code> like I did. Now my code worked just fine from what I can tell but it was implied that there could be a potential issue using my format. Can anyone confirm/deny that my format could cause a problem under the right circumstances???</p>
<p>I just want to make sure I'm coding correctly.</p>
|
[
{
"answer_id": 74576217,
"author": "The Photon",
"author_id": 1630971,
"author_profile": "https://Stackoverflow.com/users/1630971",
"pm_score": 2,
"selected": false,
"text": "bmi > 18.5 bmi >= 18.5 bmi == 18.5"
},
{
"answer_id": 74576286,
"author": "C-3PO",
"author_id": 4667669,
"author_profile": "https://Stackoverflow.com/users/4667669",
"pm_score": -1,
"selected": false,
"text": "x < bmi < y x < bmi and bmi < y bmi = 18.5 25 if, elif, ... if bmi < 25, etc. if/elif if bmi < 18.5"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6377355/"
] |
74,576,198
|
<p>In a SQL script I'm trying to get data based on the year within a string value field. Each year the table adds a new row for the current year . So the ID_TYPE_NAME column has a row with:</p>
<p>"MS-DRG V38 (FY 2021)"
"MS-DRG V39 (FY 2022)"
and so on...</p>
<p>Being new to SQL I hoped that a formula like the one below would work:</p>
<pre><code>WHERE ID_TYPE_NAME LIKE 'MS-DRG%'
and ID_TYPE_NAME LIKE YEAR(CURDATE())
</code></pre>
<p>but I get a message that</p>
<blockquote>
<p>CURDATE is not a recognized built-in function name</p>
</blockquote>
<p>Can I use like or do I need to go a different route? If I must go a different route, what method do I use to accomplish this?</p>
|
[
{
"answer_id": 74576566,
"author": "Álvaro González",
"author_id": 13508,
"author_profile": "https://Stackoverflow.com/users/13508",
"pm_score": 1,
"selected": false,
"text": "LIKE % _ CURDATE select pink_elephants() CURRENT_TIMESTAMP YEAR() CAST() + where id_type_name like 'MS-DRG% (FY ' + cast(year(current_timestamp) as varchar(4)) + ')'\n"
},
{
"answer_id": 74576696,
"author": "Jonas Metzler",
"author_id": 18794826,
"author_profile": "https://Stackoverflow.com/users/18794826",
"pm_score": 1,
"selected": true,
"text": "CONCAT SELECT ID_TYPE_NAME\nFROM yourtable\nWHERE ID_TYPE_NAME \nLIKE CONCAT('MS-DRG%',YEAR(GETDATE()),')');\n YEAR LIKE MS-DRG%2022) SELECT ID_TYPE_NAME\nFROM yourtable\nWHERE ID_TYPE_NAME \nLIKE CONCAT('MS-DRG%FY ',YEAR(GETDATE()),')');\n LIKE MS-DRG%FY 2022) MS-DRG V39 (FY 2022)"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20106370/"
] |
74,576,200
|
<p>I'm doing a parallelization exercise using mpi4py where 2 dice are thrown a defined number of times (divided by the processes, i.e, <code>npp</code>) and the dots are counted. The results are stored in a dictionary, the mean deviation is calculated and until the condition of
<code>mean_dev</code> being less than 0.001 the number of throws is doubled.</p>
<p>All of this works as expected, the problem is that the code doesn't quit. The condition is met, there's no more outputs, but the code hangs.</p>
<pre><code>from ctypes.wintypes import SIZE
from dice import * #This is just a class that creates the dictionaries
from random import randint
import matplotlib.pyplot as plt
import numpy as np
from mpi4py import MPI
from math import sqrt
def simulation(f_events, f_sides, f_n_dice):
f_X = dice(sides, n_dice).myDice() #Nested dictionary composed of dices (last dict stores the sum)
for j in range(f_events): #for loop to handle all the dice throwings aka events
n = [] #List to store index respective to number on each dice
for i in range(1, f_n_dice+1): #for cycle for each dice
k = randint(1, f_sides) #Random number
n.append(k)
f_X[i][k] += 1 #The index (k) related to each throw is increased for the dice (i)
sum_throw = sum(n) #Sum of the last throw
f_X[f_n_dice+1][sum_throw] += 1 #Sum dictionary "increases" the index respective to the sum of the last throw
return f_X
npp = int(4)//4 #Number of events divided by the number of processes
sides = 6 #Number of sides per dice
n_dice = 2 #Number of dices
comm = MPI.COMM_WORLD #Communicator to handle point-to-point communication
rank = comm.Get_rank() #Hierarchy of processes
size = comm.Get_size() #Number of processes
#-------------------- Parallelization portion of the code --------------------#
seq = (2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
AUX = dict.fromkeys(seq, 0)
mean_dev = 1
while True:
msg = comm.bcast(npp, root = 0)
print("---> msg: ", msg, " for rank ", rank)
print("The mean dev for %d" %rank + " is: ", mean_dev)
D = simulation(npp, sides, n_dice)
Dp = comm.gather(D, root = 0)
print("This is Dp: ", Dp)
summ = 0
prob = [1/36, 2/36, 3/36, 4/36, 5/36, 6/36, 5/36, 4/36, 3/36, 2/36, 1/36]
if rank==0:
for p in range(0, size):
for n in range(dice().min, dice().max+1): #Range from minimum sum possible to the maximum sum possible depending on the number of dices used
AUX[n] += Dp[p][n_dice+1][n] #Adds the new data to the final sum dictionary
#of the previously initiated nested dictionary
print(Dp[p][n_dice+1])
print("The final dictionary is: ", AUX, sum(AUX[j] for j in AUX))
for i in range(dice().min, dice().max+1):
exp = (prob[i-2])*(sum(AUX[j] for j in AUX))
x = (AUX[i]-exp)/exp
summ = summ + pow(x, 2)
mean_dev = (1/11)*sqrt(summ)
print("The deviation for {} is {}.".format(sum(AUX[j] for j in AUX), mean_dev))
if mean_dev > 0.001:
npp = 2*npp
# new_msg = comm.bcast(npp, root = 0)
# print("---> new_msg: ", new_msg, " for rank ", rank)
else:
break
</code></pre>
<p>I'm stumped on this one. Thanks in advance for any input!</p>
<hr />
<p>The new code with the solution proposed by @victor-eijkhout:</p>
<pre><code>from ctypes.wintypes import SIZE
from dice import *
from random import randint
import matplotlib.pyplot as plt
import numpy as np
from mpi4py import MPI
from math import sqrt
def simulation(f_events, f_sides, f_n_dice):
f_X = dice(sides, n_dice).myDice() #Nested dictionary composed of dices (last dict stores the sum)
for j in range(f_events): #for loop to handle all the dice throwings aka events
n = [] #List to store index respective to number on each dice
for i in range(1, f_n_dice+1): #for cycle for each dice
k = randint(1, f_sides) #Random number
n.append(k)
f_X[i][k] += 1 #The index (k) related to each throw is increased for the dice (i)
sum_throw = sum(n) #Sum of the last throw
f_X[f_n_dice+1][sum_throw] += 1 #Sum dictionary "increases" the index respective to the sum of the last throw
return f_X
npp = int(4)//4 #Number of events divided by the number of processes
sides = 6 #Number of sides per dice
n_dice = 2 #Number of dices
comm = MPI.COMM_WORLD #Communicator to handle point-to-point communication
rank = comm.Get_rank() #Hierarchy of processes
size = comm.Get_size() #Number of processes
#-------------------- Parallelization portion of the code --------------------#
seq = (2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
AUX = dict.fromkeys(seq, 0)
mean_dev = 1
while True:
msg = comm.bcast(npp, root = 0)
#print("---> msg: ", msg, " for rank ", rank)
D = simulation(npp, sides, n_dice)
Dp = comm.gather(D, root = 0)
#if Dp != None: print("This is Dp: ", Dp)
#print("The mean dev for %d" %rank + " is: ", mean_dev)
if rank==0:
summ = 0
prob = [1/36, 2/36, 3/36, 4/36, 5/36, 6/36, 5/36, 4/36, 3/36, 2/36, 1/36]
for p in range(0, size):
for n in range(dice().min, dice().max+1): #Range from minimum sum possible to the maximum sum possible depending on the number of dices used
AUX[n] += Dp[p][n_dice+1][n] #Adds the new data to the final sum dictionary
#of the previously initiated nested dictionary
print(Dp[p][n_dice+1])
print("The final dictionary is: ", AUX, sum(AUX[j] for j in AUX))
for i in range(dice().min, dice().max+1):
exp = (prob[i-2])*(sum(AUX[j] for j in AUX))
x = (AUX[i]-exp)/exp
summ = summ + pow(x, 2)
mean_dev = (1/11)*sqrt(summ)
print("The deviation for {} is {}.".format(sum(AUX[j] for j in AUX), mean_dev))
#new_mean_dev = comm.gather(mean_dev, root = 0)
new_mean_dev = comm.bcast(mean_dev, root = 0)
print("---> msg2: ", new_mean_dev, " for rank ", rank)
if new_mean_dev < 0.001:
break
# new_msg = comm.bcast(npp, root = 0)
# print("---> new_msg: ", new_msg, " for rank ", rank)
else:
npp = 2*npp
print("The new npp is: ", npp)
</code></pre>
|
[
{
"answer_id": 74576455,
"author": "kd4ttc",
"author_id": 820321,
"author_profile": "https://Stackoverflow.com/users/820321",
"pm_score": -1,
"selected": false,
"text": "True: while mean_dev > 0.001: if mean_dev mean_dev (1/11)*sqrt(sum …) mean_dev mean_dev mean_dev npp"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20601425/"
] |
74,576,240
|
<p>In Javascript you can convert a callback to a promise with:</p>
<pre class="lang-js prettyprint-override"><code>function timeout(time){
return new Promise(resolve=>{
setTimeout(()=>{
resolve('done with timeout');
}, time)
});
}
</code></pre>
<p>Is that possible in Flutter?</p>
<p>Example:</p>
<pre class="lang-dart prettyprint-override"><code>// I'd like to use await syntax, so I make this return a future
Future<void> _doSomething() async {
// I'm call a function I don't control that uses callbacks
// I want to convert it to async/await syntax (Future)
SchedulerBinding.instance.addPostFrameCallback((_) async {
// I want to do stuff in here and have the return of
// `_doSomething` await it
await _doSomethingElse();
});
}
await _doSomething();
// This will currently finish before _doSomethingElse does.
</code></pre>
|
[
{
"answer_id": 74576455,
"author": "kd4ttc",
"author_id": 820321,
"author_profile": "https://Stackoverflow.com/users/820321",
"pm_score": -1,
"selected": false,
"text": "True: while mean_dev > 0.001: if mean_dev mean_dev (1/11)*sqrt(sum …) mean_dev mean_dev mean_dev npp"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1759443/"
] |
74,576,244
|
<p>I am using SQL Server and facing problem to get my required data.</p>
<p>Here is my sample table:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Date</th>
<th>PlayID</th>
<th>Name</th>
<th>City</th>
</tr>
</thead>
<tbody>
<tr>
<td>11/20/2022</td>
<td>101</td>
<td>Rishi</td>
<td>Mumbai</td>
</tr>
<tr>
<td>11/20/2022</td>
<td>102</td>
<td>Smita</td>
<td>New Mumbai</td>
</tr>
<tr>
<td>11/21/2022</td>
<td>102</td>
<td>Maiyand</td>
<td>Bangalore</td>
</tr>
<tr>
<td>11/22/2022</td>
<td>102</td>
<td>Rishi</td>
<td>Mumbai</td>
</tr>
<tr>
<td>11/22/2022</td>
<td>101</td>
<td>Smita</td>
<td>New Mumbai</td>
</tr>
<tr>
<td>11/23/2022</td>
<td>101</td>
<td>Maiyand</td>
<td>Bangalore</td>
</tr>
<tr>
<td>11/23/2022</td>
<td>102</td>
<td>Smita</td>
<td>New Mumbai</td>
</tr>
</tbody>
</table>
</div>
<p>I need output like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Date</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>11/20/2022</td>
<td>Rishi,Smita</td>
</tr>
<tr>
<td>11/21/2022</td>
<td>Maiyand</td>
</tr>
<tr>
<td><strong>11/22/2022</strong></td>
<td><strong>Smita,Rishi</strong></td>
</tr>
<tr>
<td>11/23/2022</td>
<td>Maiyand,Smita</td>
</tr>
</tbody>
</table>
</div>
<p>But I am getting output this way :</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Date</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>11/20/2022</td>
<td>Rishi,Smita</td>
</tr>
<tr>
<td>11/21/2022</td>
<td>,Maiyand</td>
</tr>
<tr>
<td>11/22/2022</td>
<td>Rishi,Smita</td>
</tr>
<tr>
<td>11/23/2022</td>
<td>Maiyand,Smita</td>
</tr>
</tbody>
</table>
</div>
<p>You can see there is a difference of names order in <code>Name</code> column. SQL Server is making <code>STUFF()</code> on how the records are inserted in main table. But I want records in similar manner, means if you see bold values in required table: <code>Name</code> is like <strong>Smita,Rishi</strong> even Rishi is inserted before Smita. But the actual output I am getting is like
<code>Rishi,Smita</code>.</p>
<p>It will be ok if all the records will return like <code>Rishi,Smita</code> or <code>Smita,Rishi</code> and no problem with single names.</p>
<p>My SQL statement:</p>
<pre><code>SELECT DISTINCT
Date,
STUFF((SELECT ',' + Name (SELECT Name FROM PlayGroup _p
WHERE _p.Date = P.Date) PL
FOR XML PATH('')), 1, 1, '') AS Name
FROM
(SELECT DISTINCT
Date, PlayID, Name
FROM
PlayGroup P
WHERE
1 = 1) Q
WHERE
Q.Date
ORDER BY
Desc
</code></pre>
<p>I tried to put <code>PlayID</code> in order by but I don't want to select it.
Because I want distinct records and arrange Names on the basis of asc <code>PlayID</code>.</p>
|
[
{
"answer_id": 74577319,
"author": "Aaron Bertrand",
"author_id": 61305,
"author_profile": "https://Stackoverflow.com/users/61305",
"pm_score": 1,
"selected": false,
"text": "SELECT DISTINCT P.Date, Name = STUFF(\n (SELECT ',' + Name \n FROM dbo.PlayGroup AS _p \n WHERE _p.Date = P.Date\n ORDER BY PlayID -- <-- here is the ORDER BY\n FOR XML PATH('')\n ), 1, 1, '')\nFROM dbo.PlayGroup AS P \nORDER BY P.Date;\n STUFF()"
},
{
"answer_id": 74596315,
"author": "Tim Jarosz",
"author_id": 2452207,
"author_profile": "https://Stackoverflow.com/users/2452207",
"pm_score": 3,
"selected": true,
"text": "ORDER BY STUFF(SELECT FOR XML PATH()) SELECT DISTINCT\n Date, \n STUFF((\n SELECT ',' + Name\n FROM PlayGroup _p \n WHERE _p.Date = P.Date\n ORDER BY _p.PlayID ASC --Added the ORDER BY here.\n FOR XML PATH('')\n ), 1, 1, '') AS Name \nFROM PlayGroup p\nORDER BY p.Date ASC\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4923942/"
] |
74,576,298
|
<p>I have a following json</p>
<pre class="lang-json prettyprint-override"><code>{
"kind":"testObject",
"spec":{
},
"status":{
"code":"503"
}
}
</code></pre>
<p>I would like to just retrieve the value of code, so that it would just show <code>503</code> as an output.</p>
<p>I did try with JMESPath, but that binary is out of question, and not sure what to use.</p>
|
[
{
"answer_id": 74577319,
"author": "Aaron Bertrand",
"author_id": 61305,
"author_profile": "https://Stackoverflow.com/users/61305",
"pm_score": 1,
"selected": false,
"text": "SELECT DISTINCT P.Date, Name = STUFF(\n (SELECT ',' + Name \n FROM dbo.PlayGroup AS _p \n WHERE _p.Date = P.Date\n ORDER BY PlayID -- <-- here is the ORDER BY\n FOR XML PATH('')\n ), 1, 1, '')\nFROM dbo.PlayGroup AS P \nORDER BY P.Date;\n STUFF()"
},
{
"answer_id": 74596315,
"author": "Tim Jarosz",
"author_id": 2452207,
"author_profile": "https://Stackoverflow.com/users/2452207",
"pm_score": 3,
"selected": true,
"text": "ORDER BY STUFF(SELECT FOR XML PATH()) SELECT DISTINCT\n Date, \n STUFF((\n SELECT ',' + Name\n FROM PlayGroup _p \n WHERE _p.Date = P.Date\n ORDER BY _p.PlayID ASC --Added the ORDER BY here.\n FOR XML PATH('')\n ), 1, 1, '') AS Name \nFROM PlayGroup p\nORDER BY p.Date ASC\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20601465/"
] |
74,576,312
|
<p>I'm trying to use settings module but is shows "ModuleNotFoundError: No module named 'settings'" and whien I try to install the module it shows "Requirement already satisfied: python-settings in c:\users\harsh\appdata\local\programs\python\python310\lib\site-packages (0.2.2)"</p>
<pre><code>import settings
</code></pre>
<p>import settings module</p>
|
[
{
"answer_id": 74576339,
"author": "urek mazino",
"author_id": 17411406,
"author_profile": "https://Stackoverflow.com/users/17411406",
"pm_score": 1,
"selected": false,
"text": "pip install python-settings from python_settings import settings"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19033899/"
] |
74,576,364
|
<p>I have the following problem: I would like to find different "cuts" of the array into two different arrays by adding one element each time, for example:</p>
<p>If I have an array</p>
<pre><code>a = [0,1,2,3]
</code></pre>
<p>The following splits are desired:</p>
<pre><code>[0] [1,2,3]
[0,1] [2,3]
[0,1,2] [3]
</code></pre>
<p>In the past I had easier tasks so <code>np.split()</code> function was quite enough for me. How should I act in this particular case?</p>
<p>Many thanks in advance and apologies if this question was asked before.</p>
|
[
{
"answer_id": 74576436,
"author": "I'mahdi",
"author_id": 1740577,
"author_profile": "https://Stackoverflow.com/users/1740577",
"pm_score": 3,
"selected": true,
"text": "a = [0,1,2,3]\n\nfor i in range(len(a)-1):\n print(a[:i+1], a[i+1:])\n [0] [1, 2, 3]\n[0, 1] [2, 3]\n[0, 1, 2] [3]\n"
},
{
"answer_id": 74576451,
"author": "Adrian Kurzeja",
"author_id": 8571154,
"author_profile": "https://Stackoverflow.com/users/8571154",
"pm_score": 1,
"selected": false,
"text": "a = [0,1,2,3]\n\nresult = [(a[:x], a[x:]) for x in range(1, len(a))]\n\nprint(result)\n# [([0], [1, 2, 3]), ([0, 1], [2, 3]), ([0, 1, 2], [3])]\n\n# you can access result like normal list\nprint(result[0])\n# ([0], [1, 2, 3])\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576364",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3079439/"
] |
74,576,366
|
<p>I would like to compare elements in lists in 1 column and assign unique values that are on no other row in new column in the same Pandas df:</p>
<p>Int.:</p>
<pre><code>data = {'object_1':[1, 3, 4, 5, 77],
'object_2':[1, 5, 100, 3, 4],
"object_3": [1, 3, 4, 5, 5],
"object_4": [1, 3, 5, 47, 48]}
</code></pre>
<p>Out.:</p>
<pre><code>data = {'object_1':[1, 3, 4, 5, 77],
'object_2':[1, 5, 100, 3, 4],
"object_3": [1, 3, 4, 5, 5],
"object_4": [1, 3, 5, 47, 48],
"unique_values": [[77], [100], [None], [47,48]],
}
</code></pre>
<p>Thanks.</p>
|
[
{
"answer_id": 74576556,
"author": "Nuri Taş",
"author_id": 19255749,
"author_profile": "https://Stackoverflow.com/users/19255749",
"pm_score": 1,
"selected": false,
"text": "isin stack data['unique_values'] = ([df.loc[~df[col].isin(df.set_index(col).stack()), col].tolist()\n for col in df.columns])\n {'object_1': [1, 3, 4, 5, 77],\n 'object_2': [1, 5, 100, 3, 4],\n 'object_3': [1, 3, 4, 5, 5],\n 'object_4': [1, 3, 5, 47, 48],\n 'unique_values': [[77], [100], [], [47, 48]]}\n"
},
{
"answer_id": 74576657,
"author": "rhug123",
"author_id": 13802115,
"author_profile": "https://Stackoverflow.com/users/13802115",
"pm_score": 0,
"selected": false,
"text": "drop_duplicates() df.stack().drop_duplicates(keep=False).groupby(level=1).agg(list).to_dict()\n {'object_1': [77], 'object_2': [100], 'object_4': [47, 48]}\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20051041/"
] |
74,576,368
|
<p>I have an array like so:</p>
<pre><code>$array = [
['record' => 1, 'sponsor' => 2, 'email' => 'some@email.com'],
['record' => 2, 'sponsor' => 2, 'email' => 'some1@email.com'],
['record' => 3, 'sponsor' => 2, 'email' => 'some2@email.com'],
['record' => 4, 'sponsor' => 2, 'email' => 'some3@email.com'],
];
</code></pre>
<p>Each row has a unique <code>record</code> and <code>email</code> and the <code>sponsor</code> key is related to the <code>record</code>. So, instead of an integer, I am trying to replace the value of the <code>sponsor</code> key with the corresponding <code>email</code> based on the <code>record</code>, something like this:</p>
<pre><code>$array = [
['record' => 1, 'sponsor' => 'some1@email.com', 'email' => 'some@email.com'],
['record' => 2, 'sponsor' => 'some1@email.com', 'email' => 'some1@email.com'],
['record' => 3, 'sponsor' => 'some1@email.com', 'email' => 'some2@email.com'],
['record' => 4, 'sponsor' => 'some1@email.com', 'email' => 'some3@email.com'],
];
</code></pre>
<p>I have tried using a <code>foreach</code> loop but it doesn't give me the expected result:</p>
<pre><code>$yes = [];
foreach ($array as $key => $arr) {
if ( ! empty($arr['sponsor']) ) {
if ( $arr['sponsor'] == $array[$key]['record'] ) {
$yes[] = ['sponsor' => $array[$key]['email']];
}
}
$yes[] = [
'record' => $array[$key]['record'],
'email' => $array[$key]['email'],
'sponsor' => $array[$key]['sponsor'],
];
}
print_r($yes);
</code></pre>
|
[
{
"answer_id": 74576556,
"author": "Nuri Taş",
"author_id": 19255749,
"author_profile": "https://Stackoverflow.com/users/19255749",
"pm_score": 1,
"selected": false,
"text": "isin stack data['unique_values'] = ([df.loc[~df[col].isin(df.set_index(col).stack()), col].tolist()\n for col in df.columns])\n {'object_1': [1, 3, 4, 5, 77],\n 'object_2': [1, 5, 100, 3, 4],\n 'object_3': [1, 3, 4, 5, 5],\n 'object_4': [1, 3, 5, 47, 48],\n 'unique_values': [[77], [100], [], [47, 48]]}\n"
},
{
"answer_id": 74576657,
"author": "rhug123",
"author_id": 13802115,
"author_profile": "https://Stackoverflow.com/users/13802115",
"pm_score": 0,
"selected": false,
"text": "drop_duplicates() df.stack().drop_duplicates(keep=False).groupby(level=1).agg(list).to_dict()\n {'object_1': [77], 'object_2': [100], 'object_4': [47, 48]}\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2339045/"
] |
74,576,394
|
<p>I am a beginner C programmer and while writing a tictactoe game in C, I encountered a strange output. I mainly used if statements to check if the "squares" are either 'X' or 'O'</p>
<pre><code>#include <stdio.h>
int main(){
int p1,p2;
char arr[] = {'1','2','3','4','5','6','7','8','9'};
void drawboard(){
printf("%c|%c|%c\n",arr[0],arr[1],arr[2]);
printf("-----\n");
printf("%c|%c|%c\n",arr[3],arr[4],arr[5]);
printf("-----\n");
printf("%c|%c|%c\n",arr[6],arr[7],arr[8]);
}
while(1>0){
drawboard();
printf("Player 1, enter your choice:\n");
scanf("%d",&p1);
printf("Player 2, enter your choice:\n");
scanf("%d",&p2);
arr[p1-1] = 'X';
arr[p2-1] = 'O';
if(arr[0]&&arr[1]&&arr[2]=='X'){
printf("Player 1 won.\n");
return 1;
}
if(arr[3]&&arr[4]&&arr[5]=='X'){
printf("Player 1 won.\n");
return 1;
}
if(arr[6]&&arr[7]&&arr[8]=='X'){
printf("Player 1 won.\n");
return 1;
}
if(arr[0]&&arr[3]&&arr[6]=='X'){
printf("Player 1 won.\n");
return 1;
}
if(arr[1]&&arr[4]&&arr[7]=='X'){
printf("Player 1 won.\n");
return 1;
}
if(arr[2]&&arr[5]&&arr[8]=='X'){
printf("Player 1 won.\n");
return 1;
}
if(arr[0]&&arr[4]&&arr[8]=='X'){
printf("Player 1 won.\n");
return 1;
}
if(arr[2]&&arr[4]&&arr[6]=='X'){
printf("Player 1 won.\n");
return 1;
}
else if(arr[0]&&arr[1]&&arr[2]=='O'){
printf("Player 2 won.\n");
return 1;
}
else if(arr[3]&&arr[4]&&arr[5]=='O'){
printf("Player 2 won.\n");
return 1;
}
else if(arr[6]&&arr[7]&&arr[8]=='O'){
printf("Player 2 won.\n");
return 1;
}
else if(arr[0]&&arr[3]&&arr[6]=='O'){
printf("Player 2 won.\n");
return 1;
}
else if(arr[1]&&arr[4]&&arr[7]=='O'){
printf("Player 2 won.\n");
return 1;
}
else if(arr[2]&&arr[5]&&arr[8]=='O'){
printf("Player 2 won.\n");
return 1;
}
else if(arr[0]&&arr[4]&&arr[8]=='O'){
printf("Player 2 won.\n");
return 1;
}
else if(arr[2]&&arr[4]&&arr[6]=='O'){
printf("Player 2 won.\n");
return 1;
}
else{
continue;
}
}
return 0;
}
</code></pre>
<p>After the first and the second player's input, if the input is '8' or '6', it says he won, even if only one space was occupied.</p>
|
[
{
"answer_id": 74576597,
"author": "user253751",
"author_id": 106104,
"author_profile": "https://Stackoverflow.com/users/106104",
"pm_score": 1,
"selected": false,
"text": "arr[6]&&arr[7]&&arr[8]=='X'\n arr[6] arr[7] arr[8]=='X' '\\0' arr[8] arr[6]=='X' && arr[7]=='X' && arr[8]=='X'\n if"
},
{
"answer_id": 74577242,
"author": "Craig Estey",
"author_id": 5382650,
"author_profile": "https://Stackoverflow.com/users/5382650",
"pm_score": 0,
"selected": false,
"text": "arr if if(arr[0]&&arr[1]&&arr[2]=='X') if ((arr[0] == 'X') && (arr[1] == 'X') && (arr[2] == 'X')) #include <stdio.h>\n#include <stdlib.h>\n#include <termios.h>\n\nchar arr[] = { '1', '2', '3', '4', '5', '6', '7', '8', '9' };\n\nvoid\ndrawboard(void)\n{\n printf(\"%c|%c|%c\\n\", arr[0], arr[1], arr[2]);\n printf(\"-----\\n\");\n printf(\"%c|%c|%c\\n\", arr[3], arr[4], arr[5]);\n printf(\"-----\\n\");\n printf(\"%c|%c|%c\\n\", arr[6], arr[7], arr[8]);\n}\n\n// match3 -- decide if win\n// RETURNS: winning char or zero\nint\nmatch3(int a,int b,int c)\n{\n int x;\n\n --a;\n --b;\n --c;\n\n x = arr[a];\n\n return ((arr[b] == x) && (arr[c] == x)) ? x : 0;\n}\n\n// check -- check for win\nint\ncheck(void)\n{\n int win;\n\n do {\n // top row\n win = match3(1,2,3);\n if (win)\n break;\n\n // middle row\n win = match3(4,5,6);\n if (win)\n break;\n\n // bottom row\n win = match3(7,8,9);\n if (win)\n break;\n\n // left column\n win = match3(1,4,7);\n if (win)\n break;\n\n // middle column\n win = match3(2,5,8);\n if (win)\n break;\n\n // right column\n win = match3(3,6,9);\n if (win)\n break;\n\n // left to right diagonal\n win = match3(1,5,9);\n if (win)\n break;\n\n // right to left diagonal\n win = match3(3,5,7);\n if (win)\n break;\n } while (0);\n\n switch (win) {\n case 'X':\n printf(\"Player 1 won.\\n\");\n break;\n case 'O':\n printf(\"Player 2 won.\\n\");\n break;\n }\n\n if (win)\n drawboard();\n\n return win;\n}\n\n// legal -- check for remaining legal moves\nvoid\nlegal(void)\n{\n int more;\n\n // look for remaining legal moves\n more = 0;\n for (int idx = 0; idx < 9; ++idx) {\n more = (arr[idx] != 'X') && (arr[idx] != 'O');\n if (more)\n break;\n }\n\n if (! more) {\n printf(\"No more legal moves -- no winner\\n\");\n drawboard();\n exit(0);\n }\n}\n\n// ask -- ask player for moves\nint\nask(int playno,int x)\n{\n char buf[100];\n char *cp;\n int move;\n\n printf(\"\\n\");\n legal();\n\n while (1) {\n drawboard();\n\n printf(\"Player %d, enter your choice:\\n\",playno);\n if (fgets(buf,sizeof(buf),stdin) == NULL) {\n printf(\"EOF\\n\");\n exit(0);\n }\n\n // echo for debug input from file\n do {\n struct termios tio;\n if (tcgetattr(fileno(stdin),&tio) < 0)\n fputs(buf,stdout);\n } while (0);\n\n // get the move\n move = strtol(buf,&cp,10);\n\n if (*cp != '\\n') {\n printf(\"syntax error\\n\");\n continue;\n }\n\n // move is within bounds\n if ((move >= 1) && (move <= 9)) {\n --move;\n\n // check for move to an already occupied space\n if ((arr[move] == 'X') || (arr[move] == 'O')) {\n printf(\"already has an '%c'\\n\",arr[move]);\n continue;\n }\n\n // make the move\n arr[move] = x;\n break;\n }\n\n printf(\"move out of range\\n\");\n }\n\n return check();\n}\n\nint\nmain(void)\n{\n int more;\n\n while (1) {\n if (ask(1,'X'))\n break;\n if (ask(2,'O'))\n break;\n }\n\n return 0;\n}\n \n1|2|3\n-----\n4|5|6\n-----\n7|8|9\nPlayer 1, enter your choice:\n1\n\nX|2|3\n-----\n4|5|6\n-----\n7|8|9\nPlayer 2, enter your choice:\n4\n\nX|2|3\n-----\nO|5|6\n-----\n7|8|9\nPlayer 1, enter your choice:\n2\n\nX|X|3\n-----\nO|5|6\n-----\n7|8|9\nPlayer 2, enter your choice:\n5\n\nX|X|3\n-----\nO|O|6\n-----\n7|8|9\nPlayer 1, enter your choice:\n3\nPlayer 1 won.\nX|X|X\n-----\nO|O|6\n-----\n7|8|9\n \n1|2|3\n-----\n4|5|6\n-----\n7|8|9\nPlayer 1, enter your choice:\n1\n\nX|2|3\n-----\n4|5|6\n-----\n7|8|9\nPlayer 2, enter your choice:\n4\n\nX|2|3\n-----\nO|5|6\n-----\n7|8|9\nPlayer 1, enter your choice:\n2\n\nX|X|3\n-----\nO|5|6\n-----\n7|8|9\nPlayer 2, enter your choice:\n5\n\nX|X|3\n-----\nO|O|6\n-----\n7|8|9\nPlayer 1, enter your choice:\n3\nPlayer 1 won.\nX|X|X\n-----\nO|O|6\n-----\n7|8|9\n \n1|2|3\n-----\n4|5|6\n-----\n7|8|9\nPlayer 1, enter your choice:\n1\n\nX|2|3\n-----\n4|5|6\n-----\n7|8|9\nPlayer 2, enter your choice:\n2\n\nX|O|3\n-----\n4|5|6\n-----\n7|8|9\nPlayer 1, enter your choice:\n3\n\nX|O|X\n-----\n4|5|6\n-----\n7|8|9\nPlayer 2, enter your choice:\n4\n\nX|O|X\n-----\nO|5|6\n-----\n7|8|9\nPlayer 1, enter your choice:\n5\n\nX|O|X\n-----\nO|X|6\n-----\n7|8|9\nPlayer 2, enter your choice:\n9\n\nX|O|X\n-----\nO|X|6\n-----\n7|8|O\nPlayer 1, enter your choice:\n8\n\nX|O|X\n-----\nO|X|6\n-----\n7|X|O\nPlayer 2, enter your choice:\n7\n\nX|O|X\n-----\nO|X|6\n-----\nO|X|O\nPlayer 1, enter your choice:\n6\n\nNo more legal moves -- no winner\nX|O|X\n-----\nO|X|X\n-----\nO|X|O\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20601569/"
] |
74,576,401
|
<p><a href="https://i.stack.imgur.com/K1hqi.png" rel="nofollow noreferrer">Here is image from page</a></p>
<p>Hi all, I'm new here. How to create loop for fixture file with multiple arr in Cypress to check all the list?</p>
<pre><code>[
{
"firstName": "John",
"email": "jsmith@gmail.com",
"due": "50$",
"webSite": "www"
},
{
"firstName": "Frank",
"email": "fbach@yahoo.com",
"due": "51$",
"webSite": "www"
},
{
"firstName": "Jason",
"email": "jdoe@hotmail.com",
"due": "100$",
"webSite": "www"
}
]
</code></pre>
<pre><code>cy.fixture('folderName/fileName.json').then(function (testdata) {
this.testdata = testdata
})
it('DDT fixture file', function () {
cy.get('name_selector').should('have.text', this.testdata.firstName);
cy.get('email_selector').should('have.text', this.testdata.email);
cy.get('due_selector').should('have.text', this.testdata.due);
cy.get('website_selector').should('have.text', this.testdata.website);
})
</code></pre>
|
[
{
"answer_id": 74578094,
"author": "jjhelguero",
"author_id": 17917809,
"author_profile": "https://Stackoverflow.com/users/17917809",
"pm_score": 0,
"selected": false,
"text": "const testData = require('cypress/fixture/folder/path')\n\nCypress._.forEach(testData, (data) => {\n it(`${data} test`, () => {\n cy.get('name_selector').should('have.text', data.firstName)\n cy.get('email_selector').should('have.text', data.email)\n cy.get('due_selector').should('have.text', data.due)\n cy.get('website_selector').should('have.text', data.website)\n }\n})\n"
},
{
"answer_id": 74579638,
"author": "Paul Murdin",
"author_id": 20602038,
"author_profile": "https://Stackoverflow.com/users/20602038",
"pm_score": 1,
"selected": false,
"text": "Array.forEach() cy.fixture('folderName/fileName.json').as('testdata') // alias sets \"this.testdata\"\n\ndescribe('All testdata' function() {\n\n this.testdata.forEach(item => {\n\n it('DDT fixture file for ' + item.firstName, () => {\n cy.get('name_selector').should('have.text', item.firstName);\n cy.get('email_selector').should('have.text', item.email);\n cy.get('due_selector').should('have.text', item.due);\n cy.get('website_selector').should('have.text', item.website);\n })\n })\n})\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20601475/"
] |
74,576,439
|
<p>I'm trying to create a project of an ATM where you have to enter the card number and pin but it's not working when I put the right pin says "Pin not found!" which is the catch but I copied the code from above and just changed what I thought necessary, does anyone know what's wrong?</p>
<pre><code>static void Main()
{
using (var cn = new SqlConnection("Data Source=MAD-PC-023;Database=atmbd;Trusted_Connection=True;"))
{
cn.Open();
string debitCard = "";
Console.WriteLine("Insert your card number: ");
while (true)
{
try
{
debitCard = Console.ReadLine();
if (debitCard.Length != 8)
{
Console.WriteLine("Wrong format!");
}
else
{
// falta algum IF EXISTS IN DB
using (var cmd = new SqlCommand() { Connection = cn, CommandText = "SELECT FirstName FROM atm WHERE CardNumber = '" + debitCard + "'" })
{
var reader = cmd.ExecuteReader();
if (reader.Read() == true)
{
Console.WriteLine("Hi, " + reader.GetString(0));
break;
}
else
{
Console.WriteLine("Not found");
}
}
}
}
catch
{
Console.WriteLine("Not found!");
}
}
string pin = "";
Console.WriteLine("Insert pin ");
while (true)
{
try
{
pin = Console.ReadLine();
using (var cmd = new SqlCommand() { Connection = cn, CommandText = "SELECT FirstName, LastName FROM atm WHERE Pin = '" + pin + "'" })
{
var reader = cmd.ExecuteReader();
if (reader.Read() == true)
{
Console.WriteLine("User Found");
break;
}
else
{
Console.WriteLine("Not found!");
}
}
}
catch
{
Console.WriteLine("Pin not found!");
}
}
}
}
</code></pre>
<p>I've tried many different ways and I can't do it. If anyone can help me, I'd be grateful</p>
|
[
{
"answer_id": 74576502,
"author": "Sarath Baiju",
"author_id": 12198981,
"author_profile": "https://Stackoverflow.com/users/12198981",
"pm_score": 0,
"selected": false,
"text": "catch(Exception ex) { Console.WriteLine(ex.Message); }"
},
{
"answer_id": 74576932,
"author": "vivek nuna",
"author_id": 6527049,
"author_profile": "https://Stackoverflow.com/users/6527049",
"pm_score": 3,
"selected": true,
"text": "IF EXISTS SELECT 1 FROM … ExecuteScalar"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20571251/"
] |
74,576,479
|
<p>form page not displaying response,</p>
<p>I left off some tags that were supposed to be closed. I changed that already. Basically, once i fill out the form and click on the submit button it should take me to the display page where it displays a string such as " Hello" + string + "thank you for submitting!"</p>
<p>main.py code</p>
<pre><code>
#import the flask module
from flask import Flask, render_template, request,url_for
ap Flask(__name__)
@app.route("/")
def home():
return render_template('home.html')
@app.route("/teams")
def teams():
return render_template('teams.html')
@app.route("/form", methods = ['GET','POST'])
def form():
#get the method of the post and the method of the get
if request.method == "POST" and request.form.get('submit'):
string = request.form.get('name')
feedback = "Hello" + string + "\n Thank you for submiting!!"
//
else:
return render_template('form.html').format(feedback = "")
</code></pre>
|
[
{
"answer_id": 74576502,
"author": "Sarath Baiju",
"author_id": 12198981,
"author_profile": "https://Stackoverflow.com/users/12198981",
"pm_score": 0,
"selected": false,
"text": "catch(Exception ex) { Console.WriteLine(ex.Message); }"
},
{
"answer_id": 74576932,
"author": "vivek nuna",
"author_id": 6527049,
"author_profile": "https://Stackoverflow.com/users/6527049",
"pm_score": 3,
"selected": true,
"text": "IF EXISTS SELECT 1 FROM … ExecuteScalar"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20482343/"
] |
74,576,490
|
<p>Am stuck with a problem assigned by my mentor who wants me to write a PHP script which reads a UTF-8 encoded file content and return the number of occurrences of each word as json.</p>
<p>The language of the file content is Russian Cyrillic.</p>
<p><strong>Here is the Sample text</strong></p>
<pre><code>Он бледен. Мыслит страшный путь.
В его душе живут виденья.
Ударом жизни вбита грудь,
А щеки выпили сомненья.
Клоками сбиты волоса,
Чело высокое в морщинах,
Но ясных грез его краса
Горит в продуманных картинах.
Сидит он в тесном чердаке,
Огарок свечки режет взоры,
А карандаш в его руке
Ведет с ним тайно разговоры.
Он пишет песню грустных дум,
Он ловит сердцем тень былого.
И этот шум… душевный шум…
Снесет он завтра за целковый.
</code></pre>
<p>As per my research, PHP's predefined string functions can seamlessly handle this problem only under a condition that it must be ASCII encoded. In this case do we have some third party libraries or APIs to handle utf-8 encoded strings of other non English language.</p>
|
[
{
"answer_id": 74576502,
"author": "Sarath Baiju",
"author_id": 12198981,
"author_profile": "https://Stackoverflow.com/users/12198981",
"pm_score": 0,
"selected": false,
"text": "catch(Exception ex) { Console.WriteLine(ex.Message); }"
},
{
"answer_id": 74576932,
"author": "vivek nuna",
"author_id": 6527049,
"author_profile": "https://Stackoverflow.com/users/6527049",
"pm_score": 3,
"selected": true,
"text": "IF EXISTS SELECT 1 FROM … ExecuteScalar"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14914216/"
] |
74,576,496
|
<p>I have a Text Widget with some properties that I am viewing on two screens. One is a canvas and the other is overlaid on a T-Shirt Image. On the canvas, the Text Container takes the whole screen. But when I overlay it on the shirt. The text wraps to other line for some reason.</p>
<p>This is the Text Widget:</p>
<pre><code>class EditableTextWidget extends StatelessWidget {
const EditableTextWidget({
Key? key,
required this.rotationAngle,
required this.opacity,
required this.textAlign,
required this.text,
required this.style,
required this.textStrokeWidth,
required this.textStrokeColor,
required this.textColor,
required this.letterSpacing,
required this.lineHeight,
required this.fontSize,
required this.shadowAngle,
required this.shadowDistance,
required this.shadowColor,
this.backgroundColor,
required this.isShadowSet,
this.scalingFactor = 1.0,
required this.backGroundColorTakesFullWidth,
}) : super(key: key);
// final double width;
final int rotationAngle;
final double opacity;
final TextAlign textAlign;
final String text;
final TextStyle style;
final double textStrokeWidth;
final Color textStrokeColor;
final Color textColor;
final double letterSpacing;
final double lineHeight;
final double fontSize;
final double shadowAngle;
final double shadowDistance;
final Color shadowColor;
final double scalingFactor;
final Color? backgroundColor;
final bool backGroundColorTakesFullWidth;
final bool isShadowSet;
@override
Widget build(BuildContext context) {
return Transform.scale(
scale: scalingFactor,
child: RotationTransition(
turns: AlwaysStoppedAnimation(rotationAngle / 360),
child: AnimatedOpacity(
opacity: opacity,
duration: const Duration(milliseconds: 500),
child: Container(
color: Colors.amber,
width: double.infinity,
child: Stack(
alignment: Alignment.center,
children: [
if (textStrokeWidth != 0)
Text(
text,
textAlign: textAlign,
style: style.copyWith(
color: textStrokeWidth == 0
? textColor.withOpacity(opacity)
: null,
letterSpacing: letterSpacing,
height: lineHeight,
foreground: Paint()
..style = PaintingStyle.stroke
..strokeWidth = textStrokeWidth
..color = textStrokeColor,
fontSize: fontSize,
backgroundColor: backgroundColor,
shadows: [
Shadow(
offset: Offset.fromDirection(
radians(shadowAngle), shadowDistance),
blurRadius: 2.0,
color: shadowColor,
),
],
),
),
Text(
text,
textAlign: textAlign,
style: style.copyWith(
color: textColor.withOpacity(opacity),
letterSpacing: letterSpacing,
height: lineHeight,
fontSize: fontSize,
shadows: [
if (isShadowSet)
Shadow(
offset: Offset.fromDirection(
radians(shadowAngle), shadowDistance),
blurRadius: 2.0,
color: shadowColor,
),
],
),
),
],
),
),
),
),
);
}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/xVLJa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xVLJa.png" alt="Text Widget on Canvas" /></a>
This is the widget on canvas</p>
<pre><code>CustomSingleChildLayout(
delegate:
CustomDelegate(offset: model.positionOffset),
child: GestureDetector(
onDoubleTap: () {
Get.back();
Get.to(() => const AddText());
},
child: EditableTextWidget(
rotationAngle: model.lastTextRotationAngle,
opacity: model.selectedTextColourOpacity,
textAlign: model.lastTextAlign,
text: text,
style: model.currentFont,
textColor: model.selectedTextColor,
textStrokeColor: model.lastTextStrokeColor,
textStrokeWidth: model.lastTextStrokeWidth,
letterSpacing: model.lastTextLetterSpacing,
lineHeight: model.lastTextLineHeight,
fontSize: model.lastTextFontSize,
shadowAngle: model.lastTextShadowAngle,
shadowDistance: model.lastTextShadowDistance,
shadowColor: model.lastTextShadowColor,
backgroundColor:
model.lastApplyTextBackgroundColor
? model.lastTextBackgroundColor
: Colors.transparent,
isShadowSet: model.isShadowColorSet,
scalingFactor: model.scalingFactor,
backGroundColorTakesFullWidth: false,
),
),
),
</code></pre>
<p><a href="https://i.stack.imgur.com/dHlXX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dHlXX.png" alt="Text Widget overlayed on shirt" /></a>
This is the same widget overlaid on the tshirt:</p>
<pre><code> CustomSingleChildLayout(
delegate: CustomDelegate(
offset: addModel.positionOffset,
),
child: Container(
color: Colors.red,
width: double.infinity,
child: EditableTextWidget(
key: textKey,
scalingFactor: 0.5,
rotationAngle:
addModel.lastTextRotationAngle,
opacity:
addModel.selectedTextColourOpacity,
textAlign: addModel.lastTextAlign,
text: addModel.lastText,
style: addModel.currentFont,
textColor: addModel.selectedTextColor,
textStrokeColor:
addModel.lastTextStrokeColor,
textStrokeWidth:
addModel.lastTextStrokeWidth,
letterSpacing:
addModel.lastTextLetterSpacing,
lineHeight: addModel.lastTextLineHeight,
fontSize: addModel.lastTextFontSize,
shadowAngle:
addModel.lastTextShadowAngle,
shadowDistance:
addModel.lastTextShadowDistance,
shadowColor:
addModel.lastTextShadowColor,
backgroundColor: addModel
.lastApplyTextBackgroundColor
? addModel.lastTextBackgroundColor
: Colors.transparent,
isShadowSet: addModel.isShadowColorSet,
backGroundColorTakesFullWidth: true,
),
),
),
</code></pre>
<p>Is there anyway to fix the issue so that the text doesn't wrap to next line?</p>
|
[
{
"answer_id": 74576502,
"author": "Sarath Baiju",
"author_id": 12198981,
"author_profile": "https://Stackoverflow.com/users/12198981",
"pm_score": 0,
"selected": false,
"text": "catch(Exception ex) { Console.WriteLine(ex.Message); }"
},
{
"answer_id": 74576932,
"author": "vivek nuna",
"author_id": 6527049,
"author_profile": "https://Stackoverflow.com/users/6527049",
"pm_score": 3,
"selected": true,
"text": "IF EXISTS SELECT 1 FROM … ExecuteScalar"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12005580/"
] |
74,576,514
|
<p><a href="https://i.stack.imgur.com/l0QbX.png" rel="nofollow noreferrer">enter image description here</a></p>
<pre><code>x <- function(){
number<- 10
y <- function(){
number <- 20
}
y()
print(number)
}
x()
</code></pre>
<p>This code prints the value 10. How would I set the value of "number" within function "y ", so that it changes the value of "number" to 20 within function "x" and therefore prints the value 20, without assigning it to the global environment.</p>
<p>I tried to do this using the assign() function but I couldn't figure out what to set the parameter of "envir" to in order to achieve this e.g. assign("number", 20, envir = "whatever environment the of x is").</p>
|
[
{
"answer_id": 74576599,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 3,
"selected": true,
"text": "parent.frame() rlang::caller_env() x <- function(){\n number<- 10\n y <- function() {\n assign(\"number\", 20, envir = parent.frame())\n }\n y()\n print(number)\n}\nx()\n# 20\n <<- x <- function(){\n number<- 10\n y <- function() {\n number <<- 20\n }\n y()\n print(number)\n}\nx()\n <<-"
},
{
"answer_id": 74576615,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 1,
"selected": false,
"text": "x <- function(){\nnumber<- 10\n y <- function(env = parent.frame()){\n env$number <- 20\n }\n y()\nprint(number)\n}\n x()\n[1] 20\n"
},
{
"answer_id": 74576630,
"author": "Vida",
"author_id": 9620304,
"author_profile": "https://Stackoverflow.com/users/9620304",
"pm_score": 1,
"selected": false,
"text": "x <- function(){\n number <- 10\n y <- function(){\n number <<- 20\n }\n y()\n print(number)\n}\nx()\n x <- function(){\n number <- 10\n y <- function(){\n number <- 20\n return(number)\n }\n number <- y()\n print(number)\n}\nx()\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15444689/"
] |
74,576,530
|
<p>I need to convert all characters to uppercase except for the last character in the following string:</p>
<pre><code><?php
$str = "Hello";
echo $_str = mb_strtoupper(mb_substr($str, 0, strtolower($str)));
?>
</code></pre>
|
[
{
"answer_id": 74576599,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 3,
"selected": true,
"text": "parent.frame() rlang::caller_env() x <- function(){\n number<- 10\n y <- function() {\n assign(\"number\", 20, envir = parent.frame())\n }\n y()\n print(number)\n}\nx()\n# 20\n <<- x <- function(){\n number<- 10\n y <- function() {\n number <<- 20\n }\n y()\n print(number)\n}\nx()\n <<-"
},
{
"answer_id": 74576615,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 1,
"selected": false,
"text": "x <- function(){\nnumber<- 10\n y <- function(env = parent.frame()){\n env$number <- 20\n }\n y()\nprint(number)\n}\n x()\n[1] 20\n"
},
{
"answer_id": 74576630,
"author": "Vida",
"author_id": 9620304,
"author_profile": "https://Stackoverflow.com/users/9620304",
"pm_score": 1,
"selected": false,
"text": "x <- function(){\n number <- 10\n y <- function(){\n number <<- 20\n }\n y()\n print(number)\n}\nx()\n x <- function(){\n number <- 10\n y <- function(){\n number <- 20\n return(number)\n }\n number <- y()\n print(number)\n}\nx()\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13646793/"
] |
74,576,569
|
<p>i'm trying to make an if into my code html with flask:</p>
<pre><code> {% if {{ role }} = 1 %}
<div id="cabecera">
<header class="py-3 mb-4 border-bottom">
<div class="container d-flex flex-wrap justify-content-center">
<a href="/home" class="d-flex align-items-center mb-3 mb-lg-0 me-lg-auto text-dark text-decoration-none">
</code></pre>
<p>i send {{ role }} from the login but when i execute the code, it say this:</p>
<p><a href="https://i.stack.imgur.com/zlsoU.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>i'm trying to control the view with permissions, if role is 1 show a div but if is other number, show a diferent div.</p>
|
[
{
"answer_id": 74576623,
"author": "Adrian Kurzeja",
"author_id": 8571154,
"author_profile": "https://Stackoverflow.com/users/8571154",
"pm_score": 1,
"selected": true,
"text": "{% if role == 1 %}\n <div id=\"cabecera\">\n <header class=\"py-3 mb-4 border-bottom\">\n <div class=\"container d-flex flex-wrap justify-content-center\">\n <a href=\"/home\" class=\"d-flex align-items-center mb-3 mb-lg-0 me-lg-auto text-dark text-decoration-none\">\n(...)\n{% endif %}\n"
},
{
"answer_id": 74576624,
"author": "ljdyer",
"author_id": 17568469,
"author_profile": "https://Stackoverflow.com/users/17568469",
"pm_score": 1,
"selected": false,
"text": "{{ }} role {% if role == 1 %}\n <div id=\"cabecera\">\n etc...\n{% endif %}\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9657230/"
] |
74,576,606
|
<p>I am trying to write to a <code>.txt</code> file within a program, and I am using the following code snippet. I want to output a line of the form:</p>
<p><code>a(space)b</code></p>
<p>but I get nothing on the txt file.</p>
<pre><code>#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
int main(){
string a = "string";
int b = 0;
fstream f;
f.open("filename.txt",ios::in | ios::out );
f << a << ' ' << b << endl;
f.close();
return 0;
}
</code></pre>
|
[
{
"answer_id": 74576667,
"author": "Stack Danny",
"author_id": 6039995,
"author_profile": "https://Stackoverflow.com/users/6039995",
"pm_score": 2,
"selected": false,
"text": "f.open(\"filename.txt\", ios::in | ios::out);\nif (!f.is_open()) {\n cout << \"error\";\n}\n ios::in std::fstream::open() std::ios::out f.open() f.open(\"filename.txt\", ios::out);\n using namespace std;"
},
{
"answer_id": 74576786,
"author": "Costantino Grana",
"author_id": 6070341,
"author_profile": "https://Stackoverflow.com/users/6070341",
"pm_score": 0,
"selected": false,
"text": "<string> <cstring> using namespace std; std::ofstream .open() .close() std::endl '\\n' #include <iostream>\n#include <fstream>\n#include <string>\n\nint main() \n{\n std::string a = \"string\";\n int b = 0;\n\n std::ofstream f(\"filename.txt\");\n if (!f) {\n return EXIT_FAILURE;\n }\n\n f << a << ' ' << b << '\\n';\n\n return EXIT_SUCCESS;\n}\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17115570/"
] |
74,576,610
|
<p>I am trying to build a spider, that gathers information regarding startups. Therefore I wrote a Python script with scrapy that should access the website and store the information in a dictionary. I think the code should work from a logik point of view, but somehow I do not get any output. My code:</p>
<pre><code>import scrapy
class StartupsSpider(scrapy.Spider):
name = 'startups'
#name of the spider
allowed_domains = ['www.bmwk.de/Navigation/DE/InvestDB/INVEST-DB_Liste/investdb.html']
#list of allowed domains
start_urls = ['https://bmwk.de/Navigation/DE/InvestDB/INVEST-DB_Liste/investdb.html']
#starting url
def parse(self, response):
startups = response.xpath('//*[contains(@class,"card-link-overlay")]/@href').getall()
#parse initial start URL for the specific startup URL
for startup in startups:
absolute_url = response.urljoin(startup)
yield scrapy.Request(absolute_url, callback=self.parse_startup)
#parse the actual startup information
next_page_url = response.xpath('//*[@class ="pagination-link"]/@href').get()
#link to next page
absolute_next_page_url = response.urljoin(next_page_url)
#go through all pages on start URL
yield scrapy.Request(absolute_next_page_url)
def parse_startup(self, response):
#get information regarding startup
startup_name = response.css('h1::text').get()
startup_hompage = response.xpath('//*[@class="document-info-item"]/a/@href').get()
startup_description = response.css('div.document-info-item::text')[16].get()
branche = response.css('div.document-info-item::text')[4].get()
founded = response.xpath('//*[@class="date"]/text()')[0].getall()
employees = response.css('div.document-info-item::text')[9].get()
capital = response.css('div.document-info-item::text')[11].get()
applied_for_invest = response.xpath('//*[@class="date"]/text()')[1].getall()
contact_name = response.css('p.card-title-subtitle::text').get()
contact_phone = response.css('p.tel > span::text').get()
contact_mail = response.xpath('//*[@class ="person-contact"]/p/a/span/text()').get()
contact_address_street = response.xpath('//*[@class ="adr"]/text()').get()
contact_address_plz = response.xpath('//*[@class ="locality"]/text()').getall()
contact_state = response.xpath('//*[@class ="country-name"]/text()').get()
yield{'Startup':startup_name,
'Homepage': startup_hompage,
'Description': startup_description,
'Branche': branche,
'Gründungsdatum': founded,
'Anzahl Mitarbeiter':employees,
'Kapital Bedarf':capital,
'Datum des Förderbescheids':applied_for_invest,
'Contact': contact_name,
'Telefon':contact_phone,
'E-Mail':contact_mail,
'Adresse': contact_address_street + contact_address_plz + contact_state}
</code></pre>
|
[
{
"answer_id": 74580571,
"author": "SuperUser",
"author_id": 16429780,
"author_profile": "https://Stackoverflow.com/users/16429780",
"pm_score": 1,
"selected": false,
"text": "allowed_domains Adresse list str None import scrapy\n\n\nclass StartupsSpider(scrapy.Spider):\n # name of the spider\n name = 'startups'\n\n # list of allowed domains\n allowed_domains = ['bmwk.de']\n\n # starting url\n start_urls = ['https://bmwk.de/Navigation/DE/InvestDB/INVEST-DB_Liste/investdb.html']\n \n def parse(self, response):\n # parse initial start URL for the specific startup URL\n startups = response.xpath('//*[contains(@class,\"card-link-overlay\")]/@href').getall()\n\n for startup in startups:\n absolute_url = response.urljoin(startup)\n\n # parse the actual startup information\n yield scrapy.Request(absolute_url, callback=self.parse_startup)\n\n # link to next page\n next_page_url = response.xpath('(//*[@class =\"pagination-link\"])[last()]/@href').get()\n if next_page_url:\n # go through all pages on start URL\n absolute_next_page_url = response.urljoin(next_page_url)\n yield scrapy.Request(absolute_next_page_url)\n\n def parse_startup(self, response):\n # get information regarding startup\n startup_name = response.css('h1::text').get()\n startup_hompage = response.xpath('//*[@class=\"document-info-item\"]/a/@href').get()\n # for example for some of the pages you'll get an error here:\n startup_description = response.css('div.document-info-item::text')[16].get()\n branche = response.css('div.document-info-item::text')[4].get()\n founded = response.xpath('//*[@class=\"date\"]/text()')[0].getall()\n employees = response.css('div.document-info-item::text')[9].get()\n capital = response.css('div.document-info-item::text')[11].get()\n applied_for_invest = response.xpath('//*[@class=\"date\"]/text()')[1].getall()\n\n contact_name = response.css('p.card-title-subtitle::text').get()\n contact_phone = response.css('p.tel > span::text').get()\n contact_mail = response.xpath('//*[@class =\"person-contact\"]/p/a/span/text()').get()\n Adresse = ' '.join(response.xpath('//*[@class =\"address\"]//text()').getall())\n\n yield {'Startup': startup_name,\n 'Homepage': startup_hompage,\n 'Description': startup_description,\n 'Branche': branche,\n 'Gründungsdatum': founded,\n 'Anzahl Mitarbeiter': employees,\n 'Kapital Bedarf': capital,\n 'Datum des Förderbescheids': applied_for_invest,\n 'Contact': contact_name,\n 'Telefon': contact_phone,\n 'E-Mail': contact_mail,\n 'Adresse': Adresse}\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20371027/"
] |
74,576,637
|
<p>I try to send an input with for example <code>echo "some_input" | write /dev/pts/0</code> or <code>echo "some_input" > /dev/pts/0</code> from a terminal <code>/dev/pts/1</code> to another <code>/dev/pts/0</code></p>
<p>In the second terminal, a program is running, for example :</p>
<pre><code>#include <iostream>
#include <string>
int main()
{
while(std::cin){
std::string s;
std::cin >> s;
std::cout << s;
}
}
</code></pre>
<p>I am having some difficulty with it. I can write the input (using echo) to the other terminal but the input is not validated and the program gets stuck in <code>std::cin</code>.
I would like to write an input and validate it as if I press enter</p>
<p>How could I do this?</p>
|
[
{
"answer_id": 74580571,
"author": "SuperUser",
"author_id": 16429780,
"author_profile": "https://Stackoverflow.com/users/16429780",
"pm_score": 1,
"selected": false,
"text": "allowed_domains Adresse list str None import scrapy\n\n\nclass StartupsSpider(scrapy.Spider):\n # name of the spider\n name = 'startups'\n\n # list of allowed domains\n allowed_domains = ['bmwk.de']\n\n # starting url\n start_urls = ['https://bmwk.de/Navigation/DE/InvestDB/INVEST-DB_Liste/investdb.html']\n \n def parse(self, response):\n # parse initial start URL for the specific startup URL\n startups = response.xpath('//*[contains(@class,\"card-link-overlay\")]/@href').getall()\n\n for startup in startups:\n absolute_url = response.urljoin(startup)\n\n # parse the actual startup information\n yield scrapy.Request(absolute_url, callback=self.parse_startup)\n\n # link to next page\n next_page_url = response.xpath('(//*[@class =\"pagination-link\"])[last()]/@href').get()\n if next_page_url:\n # go through all pages on start URL\n absolute_next_page_url = response.urljoin(next_page_url)\n yield scrapy.Request(absolute_next_page_url)\n\n def parse_startup(self, response):\n # get information regarding startup\n startup_name = response.css('h1::text').get()\n startup_hompage = response.xpath('//*[@class=\"document-info-item\"]/a/@href').get()\n # for example for some of the pages you'll get an error here:\n startup_description = response.css('div.document-info-item::text')[16].get()\n branche = response.css('div.document-info-item::text')[4].get()\n founded = response.xpath('//*[@class=\"date\"]/text()')[0].getall()\n employees = response.css('div.document-info-item::text')[9].get()\n capital = response.css('div.document-info-item::text')[11].get()\n applied_for_invest = response.xpath('//*[@class=\"date\"]/text()')[1].getall()\n\n contact_name = response.css('p.card-title-subtitle::text').get()\n contact_phone = response.css('p.tel > span::text').get()\n contact_mail = response.xpath('//*[@class =\"person-contact\"]/p/a/span/text()').get()\n Adresse = ' '.join(response.xpath('//*[@class =\"address\"]//text()').getall())\n\n yield {'Startup': startup_name,\n 'Homepage': startup_hompage,\n 'Description': startup_description,\n 'Branche': branche,\n 'Gründungsdatum': founded,\n 'Anzahl Mitarbeiter': employees,\n 'Kapital Bedarf': capital,\n 'Datum des Förderbescheids': applied_for_invest,\n 'Contact': contact_name,\n 'Telefon': contact_phone,\n 'E-Mail': contact_mail,\n 'Adresse': Adresse}\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14261606/"
] |
74,576,641
|
<p>I am working in react and have a resonse ( <code>ReviewerService.getReviewers()</code>) that returns an array of values:</p>
<pre><code>0: {id: 1, firstName: 'John', lastName: 'Doe', email: 'johndoe@aol.com', responses: '{"q1":"yes","q2":"no","q3":"yes","rating":4}'}
1: {id: 2, firstName: 'bob', lastName: 'jefferson', email: 'bob@aol.com', responses: '{"q1":"bob","q2":"yes","q3":"yes","rating":5}'}.
</code></pre>
<p>If <code>this.state = { reviewers: [] }</code>.</p>
<p>How do i pass the response data into reviewers and parse the responses property at the same time? Therefore, then I can access these properties of the responses easily.</p>
<pre><code>class ListReviewsComponent extends Component {
constructor(props) {
super(props);
this.state = {
reviewers: [],
};
}
async componentDidMount() {
await ReviewerService.getReviewers().then((res) => {
this.setState({ reviewers: res.data });
});
this.setState({ reviewers.responses: JSON.parse(this.state.reviewers.responses)}); // error
}
</code></pre>
|
[
{
"answer_id": 74580571,
"author": "SuperUser",
"author_id": 16429780,
"author_profile": "https://Stackoverflow.com/users/16429780",
"pm_score": 1,
"selected": false,
"text": "allowed_domains Adresse list str None import scrapy\n\n\nclass StartupsSpider(scrapy.Spider):\n # name of the spider\n name = 'startups'\n\n # list of allowed domains\n allowed_domains = ['bmwk.de']\n\n # starting url\n start_urls = ['https://bmwk.de/Navigation/DE/InvestDB/INVEST-DB_Liste/investdb.html']\n \n def parse(self, response):\n # parse initial start URL for the specific startup URL\n startups = response.xpath('//*[contains(@class,\"card-link-overlay\")]/@href').getall()\n\n for startup in startups:\n absolute_url = response.urljoin(startup)\n\n # parse the actual startup information\n yield scrapy.Request(absolute_url, callback=self.parse_startup)\n\n # link to next page\n next_page_url = response.xpath('(//*[@class =\"pagination-link\"])[last()]/@href').get()\n if next_page_url:\n # go through all pages on start URL\n absolute_next_page_url = response.urljoin(next_page_url)\n yield scrapy.Request(absolute_next_page_url)\n\n def parse_startup(self, response):\n # get information regarding startup\n startup_name = response.css('h1::text').get()\n startup_hompage = response.xpath('//*[@class=\"document-info-item\"]/a/@href').get()\n # for example for some of the pages you'll get an error here:\n startup_description = response.css('div.document-info-item::text')[16].get()\n branche = response.css('div.document-info-item::text')[4].get()\n founded = response.xpath('//*[@class=\"date\"]/text()')[0].getall()\n employees = response.css('div.document-info-item::text')[9].get()\n capital = response.css('div.document-info-item::text')[11].get()\n applied_for_invest = response.xpath('//*[@class=\"date\"]/text()')[1].getall()\n\n contact_name = response.css('p.card-title-subtitle::text').get()\n contact_phone = response.css('p.tel > span::text').get()\n contact_mail = response.xpath('//*[@class =\"person-contact\"]/p/a/span/text()').get()\n Adresse = ' '.join(response.xpath('//*[@class =\"address\"]//text()').getall())\n\n yield {'Startup': startup_name,\n 'Homepage': startup_hompage,\n 'Description': startup_description,\n 'Branche': branche,\n 'Gründungsdatum': founded,\n 'Anzahl Mitarbeiter': employees,\n 'Kapital Bedarf': capital,\n 'Datum des Förderbescheids': applied_for_invest,\n 'Contact': contact_name,\n 'Telefon': contact_phone,\n 'E-Mail': contact_mail,\n 'Adresse': Adresse}\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576641",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16426400/"
] |
74,576,661
|
<p>I have been working on drawing the contour plots of the basic reproduction number (R0) of a model with respect to two parameters. For practice, I am currently working on replicating the graph attached below from a paper by Kifle et al, <a href="https://www.sciencedirect.com/science/article/pii/S2211379722000122" rel="nofollow noreferrer">https://www.sciencedirect.com/science/article/pii/S2211379722000122</a>.</p>
<p><a href="https://i.stack.imgur.com/3w6pb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3w6pb.png" alt="Contour Plots" /></a></p>
<p>The MATLAB codes that I used to calculate R0 of the model are given below.</p>
<pre><code>%Parameters
theta = 141302; %recruitment rate
mu = 0.001229; %natural death rate
tau = 0.45; %modification factor for A
zeta = 1/14; %influx from Q to S
beta = 0.88; %transmission coefficient
alpha = 0.75214; %hospitalization rate
q = 0.31167; %influx from Q to I
eta_1 = 0.81692; %influx from E to Q
eta_2 = 0.02557; %influx from E to A
eta_3 = 1/7; %influx from E to I
delta_1 = 0.16673; %disease death rate for A
delta_2 = 0.00147; %disease death rate for I
delta_3 = 0.00038; %disease death rate for J
gamma_1 = 0.00827; %recovery rate for A
gamma_2 = 0.00787; %recovery rate for I
gamma_3 = 0.20186; %recovery rate for J
%Basic Reproduction Number
K_1 = eta_1 + eta_2 + eta_3 + mu
K_2 = zeta + q + mu
K_3 = gamma_1 + delta_1 + mu
K_4 = alpha + gamma_2 + delta_2 + mu
K_5 = gamma_3 + delta_3 + mu
R_0 = beta*(tau*eta_2*K_2*K_4 + K_3*(eta_3*K_2 + eta_1*q))/(K_1*K_2*K_3*K_4)
</code></pre>
<p>This is what I tried so far and it doesn't seem right.</p>
<pre><code>[beta,eta_1] = meshgrid(0.1:0.001:1,0.1:0.001:1);
R_0 = beta.*(tau.*eta_2.*K_2.*K_4 + K_3.*(eta_3.*K_2 + eta_1.*q).)./(K_1.*K_2.*K_3.*K_4)
%Drawing the plot
surf(beta,eta_1,R_0)
hold on
z2 = 0*beta + 1
surf(beta,eta_1,z2,'MarkerFaceColor','red')
</code></pre>
<p>I would be very much grateful, if someone could please help me draw the contour plots using MATLAB or R.</p>
|
[
{
"answer_id": 74576883,
"author": "Ben Bolker",
"author_id": 190277,
"author_profile": "https://Stackoverflow.com/users/190277",
"pm_score": 2,
"selected": false,
"text": "R_0_fun <- function(beta, eta_1) {\n K_1 = eta_1 + eta_2 + eta_3 + mu\n K_2 = zeta + q + mu\n K_3 = gamma_1 + delta_1 + mu\n K_4 = alpha + gamma_2 + delta_2 + mu\n K_5 = gamma_3 + delta_3 + mu\n R_0 = beta*(tau*eta_2*K_2*K_4 + K_3*(eta_3*K_2 + eta_1*q))/(K_1*K_2*K_3*K_4)\n return(R_0)\n}\nlibrary(emdbook)\ncc <- curve3d(R_0_fun(beta, eta_1), varnames = c(\"beta\", \"eta_1\"),\n sys3d = \"contour\")\n cc cc$x cc$y cc$z sys3d cc"
},
{
"answer_id": 74577803,
"author": "Allan Cameron",
"author_id": 12500315,
"author_profile": "https://Stackoverflow.com/users/12500315",
"pm_score": 3,
"selected": true,
"text": "R0 <- function(beta, eta_1, theta = 141302, mu = 0.001229, tau = 0.45,\n zeta = 1/14, alpha = 0.75214, q = 0.31167, eta_2 = 0.02557,\n eta_3 = 1/7, delta_1 = 0.16673, delta_2 = 0.00147, \n delta_3 = 0.00038, gamma_1 = 0.00827, gamma_2 = 0.00787, \n gamma_3 = 0.20186) {\n \n K_1 <- eta_1 + eta_2 + eta_3 + mu\n K_2 <- zeta + q + mu\n K_3 <- gamma_1 + delta_1 + mu\n K_4 <- alpha + gamma_2 + delta_2 + mu\n K_5 <- gamma_3 + delta_3 + mu\n\n beta * (tau * eta_2*K_2*K_4 + K_3*(eta_3*K_2 + eta_1*q)) / (K_1*K_2*K_3*K_4)\n}\n library(dplyr)\nlibrary(geomtextpath)\n\nexpand.grid(beta = seq(0, 1, 0.01), eta1 = seq(0, 1, 0.01)) %>%\n mutate(R0 = apply(., 1, function(x) R0(x[1], x[2]))) %>%\n ggplot(aes(beta, eta1)) +\n geom_contour_filled(aes(z = R0)) +\n geom_textcontour(aes(z = R0, label = after_stat(level)), size = 6) +\n scale_x_continuous(name = bquote(beta), expand = c(0, 0)) +\n scale_y_continuous(name = bquote(eta[1]), expand = c(0, 0)) +\n coord_equal() +\n theme_classic(base_size = 20) +\n scale_fill_manual(values = c(\"red\", \"yellow\", \"blue\", \"gray\", \"#00bfbf\",\n \"purple\", \"red\", \"yellow\"), name = bquote(R[0])) +\n guides(fill = guide_colorsteps(key_height = unit(10, \"mm\"))) +\n theme(legend.key.height = unit(15, \"mm\"))\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20557703/"
] |
74,576,678
|
<p>I have a table on Snowflake that contains messages between company admins and users. Here's what the table looks like.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>message</th>
<th>destination</th>
<th>messageable_id</th>
<th>sent_at</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Hello Customer!</td>
<td>outgoing</td>
<td>1700103</td>
<td>2022-03-22 22:42:11.000</td>
</tr>
<tr>
<td>2</td>
<td>Hello Company!</td>
<td>incoming</td>
<td>1700103</td>
<td>2022-03-22 22:39:56.000</td>
</tr>
</tbody>
</table>
</div>
<p>I have been trying to get the response time by using <code>lag(sent_at,1) over (partition by messageable_id order by sent_at)</code> to get the sent_at value from the previous row, and calculating the datediff there as the response time.</p>
<p>However, I realized that there are records where I have 3 consecutive outgoing rows, and it would make more sense for me to get the earliest sent_at value in that group rather than the latest one.</p>
<p>I'm wondering if it would be possible to implement a condition on the offset in the lag() syntax. Something along the lines of IF 3 consecutive outgoing values in column, then offset = 3 else 1.</p>
<p>So far, I've looked into using window functions but no luck there.</p>
|
[
{
"answer_id": 74576883,
"author": "Ben Bolker",
"author_id": 190277,
"author_profile": "https://Stackoverflow.com/users/190277",
"pm_score": 2,
"selected": false,
"text": "R_0_fun <- function(beta, eta_1) {\n K_1 = eta_1 + eta_2 + eta_3 + mu\n K_2 = zeta + q + mu\n K_3 = gamma_1 + delta_1 + mu\n K_4 = alpha + gamma_2 + delta_2 + mu\n K_5 = gamma_3 + delta_3 + mu\n R_0 = beta*(tau*eta_2*K_2*K_4 + K_3*(eta_3*K_2 + eta_1*q))/(K_1*K_2*K_3*K_4)\n return(R_0)\n}\nlibrary(emdbook)\ncc <- curve3d(R_0_fun(beta, eta_1), varnames = c(\"beta\", \"eta_1\"),\n sys3d = \"contour\")\n cc cc$x cc$y cc$z sys3d cc"
},
{
"answer_id": 74577803,
"author": "Allan Cameron",
"author_id": 12500315,
"author_profile": "https://Stackoverflow.com/users/12500315",
"pm_score": 3,
"selected": true,
"text": "R0 <- function(beta, eta_1, theta = 141302, mu = 0.001229, tau = 0.45,\n zeta = 1/14, alpha = 0.75214, q = 0.31167, eta_2 = 0.02557,\n eta_3 = 1/7, delta_1 = 0.16673, delta_2 = 0.00147, \n delta_3 = 0.00038, gamma_1 = 0.00827, gamma_2 = 0.00787, \n gamma_3 = 0.20186) {\n \n K_1 <- eta_1 + eta_2 + eta_3 + mu\n K_2 <- zeta + q + mu\n K_3 <- gamma_1 + delta_1 + mu\n K_4 <- alpha + gamma_2 + delta_2 + mu\n K_5 <- gamma_3 + delta_3 + mu\n\n beta * (tau * eta_2*K_2*K_4 + K_3*(eta_3*K_2 + eta_1*q)) / (K_1*K_2*K_3*K_4)\n}\n library(dplyr)\nlibrary(geomtextpath)\n\nexpand.grid(beta = seq(0, 1, 0.01), eta1 = seq(0, 1, 0.01)) %>%\n mutate(R0 = apply(., 1, function(x) R0(x[1], x[2]))) %>%\n ggplot(aes(beta, eta1)) +\n geom_contour_filled(aes(z = R0)) +\n geom_textcontour(aes(z = R0, label = after_stat(level)), size = 6) +\n scale_x_continuous(name = bquote(beta), expand = c(0, 0)) +\n scale_y_continuous(name = bquote(eta[1]), expand = c(0, 0)) +\n coord_equal() +\n theme_classic(base_size = 20) +\n scale_fill_manual(values = c(\"red\", \"yellow\", \"blue\", \"gray\", \"#00bfbf\",\n \"purple\", \"red\", \"yellow\"), name = bquote(R[0])) +\n guides(fill = guide_colorsteps(key_height = unit(10, \"mm\"))) +\n theme(legend.key.height = unit(15, \"mm\"))\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20601690/"
] |
74,576,680
|
<p>The first string has percentage symbol (<code>'%'</code>) at last and the second string has letters <code>"fan ..."</code> in the beginning. But after concatenating, it is showing some weird symbol instead of <code>"............ %fan .........."</code></p>
<pre><code>var abc = document.getElementById("myInput").value; ("fan" will be stored in abc)
$value = "WHERE Product_ID LIKE '%" + abc + " %' OR Product_Name LIKE '%" + abc + "%' OR Description LIKE '%" + abc + "%' OR MRP LIKE '%"+abc+"%' OR Net_Amount LIKE '%"+abc+"%' OR Category LIKE '%"+abc+"%' OR Tags LIKE '%"+abc+"%'";
</code></pre>
<p>Output:</p>
<pre><code>"WHERE Product_ID LIKE '�rt %' OR Product_Name LIKE '�rt%' OR Description LIKE '�rt%' OR MRP LIKE '�rt%' OR Net_Amount LIKE '�rt%' OR Category LIKE '�rt%' OR Tags LIKE '�rt%'"
</code></pre>
<p>I tried replacing <code>'%'</code> by <code>'\%'</code> but still it is not working.</p>
|
[
{
"answer_id": 74576772,
"author": "Johnny Craig",
"author_id": 20601873,
"author_profile": "https://Stackoverflow.com/users/20601873",
"pm_score": -1,
"selected": false,
"text": "var abc = document.getElementById(\"myInput\").value + \"\";\n\n$value = \"WHERE Product_ID LIKE '%\" + abc + \" %' OR Product_Name LIKE '%\" + abc + \"%' OR Description LIKE '%\" + abc + \"%' OR MRP LIKE '%\"+abc+\"%' OR Net_Amount LIKE '%\"+abc+\"%' OR Category LIKE '%\"+abc+\"%' OR Tags LIKE '%\"+abc+\"%'\"\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13878468/"
] |
74,576,691
|
<p>I have a spreadsheet with a lot of code that breaks down completely depending on the machine I use it on if the date formatting in a =TEXT() function does not work as it was supposed to.</p>
<p>I have 2 computers at at home with the same version of Excel- a desktop and a laptop, both with English subscription versions of Excel. It works on desktop, but not on laptop, apparently different regional settings. Then again it works on a German machine with German regional settings - where it is supposed to work.</p>
<p>What I assumed was, that using yyyymmdd would produce 20221125 for today regardless of a machine. Turns out it is not so, as seen in the picture. Super irritating.</p>
<p>In order to mitigate that I now check the result of a</p>
<pre><code>=TEXT(A1,"yyyymmdd")
=TEXT(A1,"jjjjMMTT")
</code></pre>
<p>and so on where A1 is a known date and I now that result of that field should be 20000101 for example.
The other alternative that also worked is to look for letters from "yyyymmdd" in a result of the TEXT formula.</p>
<p>Once I found the correct string I can use it further to format all dates.</p>
<p>It is doable, but super irritating.</p>
<p><a href="https://i.stack.imgur.com/Qu13U.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Qu13U.png" alt="enter image description here" /></a></p>
<p>Is there a way to know the regional settings without jumping through hoops?</p>
|
[
{
"answer_id": 74576772,
"author": "Johnny Craig",
"author_id": 20601873,
"author_profile": "https://Stackoverflow.com/users/20601873",
"pm_score": -1,
"selected": false,
"text": "var abc = document.getElementById(\"myInput\").value + \"\";\n\n$value = \"WHERE Product_ID LIKE '%\" + abc + \" %' OR Product_Name LIKE '%\" + abc + \"%' OR Description LIKE '%\" + abc + \"%' OR MRP LIKE '%\"+abc+\"%' OR Net_Amount LIKE '%\"+abc+\"%' OR Category LIKE '%\"+abc+\"%' OR Tags LIKE '%\"+abc+\"%'\"\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9178508/"
] |
74,576,709
|
<p>I don't understand how to swap 2 random strings in LinkedList.<br />
I know how to swap Integers but Strings are too diferent</p>
<pre class="lang-java prettyprint-override"><code>import java.util.*;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
LinkedList<String> ll = new LinkedList<>();
Scanner sc = new Scanner(System.in);
System.out.println("enter total count of elements -> ");
int num = Integer.parseInt(sc.next());
while(num>0) {
ll.add(sc.next());
num--;
}
sc.close();
System.out.println(ll);
}
}
</code></pre>
|
[
{
"answer_id": 74576993,
"author": "g00se",
"author_id": 16376827,
"author_profile": "https://Stackoverflow.com/users/16376827",
"pm_score": 0,
"selected": false,
"text": "public static <T> void swapTwo(List<T> list) {\n int len = list.size();\n int ixOne = (int)(Math.random() * len);\n int ixTwo = (int)(Math.random() * len);\n Collections.swap(list, ixOne, ixTwo);\n}\n"
},
{
"answer_id": 74577200,
"author": "DevilsHnd",
"author_id": 4725875,
"author_profile": "https://Stackoverflow.com/users/4725875",
"pm_score": 2,
"selected": true,
"text": "LinkedList<String> ll = new LinkedList<>(Arrays.asList(\n \"Billy\", \"Tracey\", \"Fred\", \"Jack\", \"Joe\", \"Carlie\"));\nSystem.out.println(\"Original LinkedList contents:\");\nSystem.out.println(ll); // Display original List\nSystem.out.println();\n \n// Get a random index number\nint swapFrom = new Random().nextInt(ll.size());\n \n// Ensure the next random index number is different.\nint swapTo = swapFrom;\nwhile (swapTo == swapFrom) {\n swapTo = new Random().nextInt(ll.size());\n}\n \nSystem.out.println(\"Swap content at index \" + swapFrom \n + \" of LinkedList with content at index \" + swapTo + \":\");\nString tmp = ll.get(swapTo); // Temporarily hold content at index swapTo.\nll.set(swapTo, ll.get(swapFrom)); // Place what is at index swapFrom and overwrite what is at index swapTo.\nll.set(swapFrom, tmp); // Overwrite what is at index swapfrom with what is in tmp.\nSystem.out.println(ll); // Display List with swapped elements.\nSystem.out.println();\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20601795/"
] |
74,576,721
|
<p>This question has been asked many times but after reading all the responses, mine still doesn't work and I think it has something to do with the scope of the variable.</p>
<p>I am trying to make a request and return it's result back into the main scope but it either returns undefined or a promise even though the promise has already been fulfilled.</p>
<pre class="lang-js prettyprint-override"><code>const getLastMessage = fetch("/history?id="+getChatID())
.then((response) => response.json())
.then((messages) => {
return messages[messages.length-1]['id']
// returns correct result
})
const getLastFetched = async () => {
lastMessage = await getLastMessage
// sets lastMessage to correct value
};
let lastMessage = getLastFetched()
console.log(lastMessage)
// undefined
</code></pre>
<p>If I make <code>getLastFetched</code> return data to <code>lastMessage</code> it will return a promise object.
I tried this exact same thing previously and it worked?</p>
|
[
{
"answer_id": 74576993,
"author": "g00se",
"author_id": 16376827,
"author_profile": "https://Stackoverflow.com/users/16376827",
"pm_score": 0,
"selected": false,
"text": "public static <T> void swapTwo(List<T> list) {\n int len = list.size();\n int ixOne = (int)(Math.random() * len);\n int ixTwo = (int)(Math.random() * len);\n Collections.swap(list, ixOne, ixTwo);\n}\n"
},
{
"answer_id": 74577200,
"author": "DevilsHnd",
"author_id": 4725875,
"author_profile": "https://Stackoverflow.com/users/4725875",
"pm_score": 2,
"selected": true,
"text": "LinkedList<String> ll = new LinkedList<>(Arrays.asList(\n \"Billy\", \"Tracey\", \"Fred\", \"Jack\", \"Joe\", \"Carlie\"));\nSystem.out.println(\"Original LinkedList contents:\");\nSystem.out.println(ll); // Display original List\nSystem.out.println();\n \n// Get a random index number\nint swapFrom = new Random().nextInt(ll.size());\n \n// Ensure the next random index number is different.\nint swapTo = swapFrom;\nwhile (swapTo == swapFrom) {\n swapTo = new Random().nextInt(ll.size());\n}\n \nSystem.out.println(\"Swap content at index \" + swapFrom \n + \" of LinkedList with content at index \" + swapTo + \":\");\nString tmp = ll.get(swapTo); // Temporarily hold content at index swapTo.\nll.set(swapTo, ll.get(swapFrom)); // Place what is at index swapFrom and overwrite what is at index swapTo.\nll.set(swapFrom, tmp); // Overwrite what is at index swapfrom with what is in tmp.\nSystem.out.println(ll); // Display List with swapped elements.\nSystem.out.println();\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19708567/"
] |
74,576,722
|
<p>I want to show a text carousel with dots below the text on the onboarding screen of my app. How can I achieve this? Watch the image to see what I wanna achieve.
<a href="https://i.stack.imgur.com/ayCY6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ayCY6.png" alt="Reference Image" /></a></p>
|
[
{
"answer_id": 74576993,
"author": "g00se",
"author_id": 16376827,
"author_profile": "https://Stackoverflow.com/users/16376827",
"pm_score": 0,
"selected": false,
"text": "public static <T> void swapTwo(List<T> list) {\n int len = list.size();\n int ixOne = (int)(Math.random() * len);\n int ixTwo = (int)(Math.random() * len);\n Collections.swap(list, ixOne, ixTwo);\n}\n"
},
{
"answer_id": 74577200,
"author": "DevilsHnd",
"author_id": 4725875,
"author_profile": "https://Stackoverflow.com/users/4725875",
"pm_score": 2,
"selected": true,
"text": "LinkedList<String> ll = new LinkedList<>(Arrays.asList(\n \"Billy\", \"Tracey\", \"Fred\", \"Jack\", \"Joe\", \"Carlie\"));\nSystem.out.println(\"Original LinkedList contents:\");\nSystem.out.println(ll); // Display original List\nSystem.out.println();\n \n// Get a random index number\nint swapFrom = new Random().nextInt(ll.size());\n \n// Ensure the next random index number is different.\nint swapTo = swapFrom;\nwhile (swapTo == swapFrom) {\n swapTo = new Random().nextInt(ll.size());\n}\n \nSystem.out.println(\"Swap content at index \" + swapFrom \n + \" of LinkedList with content at index \" + swapTo + \":\");\nString tmp = ll.get(swapTo); // Temporarily hold content at index swapTo.\nll.set(swapTo, ll.get(swapFrom)); // Place what is at index swapFrom and overwrite what is at index swapTo.\nll.set(swapFrom, tmp); // Overwrite what is at index swapfrom with what is in tmp.\nSystem.out.println(ll); // Display List with swapped elements.\nSystem.out.println();\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15908450/"
] |
74,576,725
|
<p>I am trying to output the contents of a bash script into a file, but when i put the file name into a variable, it does not work. But if I hardcode the same filename, it works.</p>
<p>I tried this</p>
<pre><code>{
echo "in the script"
file='file.txt'
} | tee -a "$file"
</code></pre>
<p>however I get the error <code>tee: : No such file or directory</code> I also echo "$file" and I get back file.txt, so I know the variable is getting set correctly.
when I do:</p>
<pre><code>{
echo "in the script"
} | tee -a "file.txt"
</code></pre>
<p>it creates the file and fills it no problem. Why isn't my variable working here?</p>
<p>Edit: I am using brackets {} to encase my script because it is a rather large script that I want to output to a file. so <code>echo "in the script" | tee -a "$file"</code> will not work</p>
|
[
{
"answer_id": 74576993,
"author": "g00se",
"author_id": 16376827,
"author_profile": "https://Stackoverflow.com/users/16376827",
"pm_score": 0,
"selected": false,
"text": "public static <T> void swapTwo(List<T> list) {\n int len = list.size();\n int ixOne = (int)(Math.random() * len);\n int ixTwo = (int)(Math.random() * len);\n Collections.swap(list, ixOne, ixTwo);\n}\n"
},
{
"answer_id": 74577200,
"author": "DevilsHnd",
"author_id": 4725875,
"author_profile": "https://Stackoverflow.com/users/4725875",
"pm_score": 2,
"selected": true,
"text": "LinkedList<String> ll = new LinkedList<>(Arrays.asList(\n \"Billy\", \"Tracey\", \"Fred\", \"Jack\", \"Joe\", \"Carlie\"));\nSystem.out.println(\"Original LinkedList contents:\");\nSystem.out.println(ll); // Display original List\nSystem.out.println();\n \n// Get a random index number\nint swapFrom = new Random().nextInt(ll.size());\n \n// Ensure the next random index number is different.\nint swapTo = swapFrom;\nwhile (swapTo == swapFrom) {\n swapTo = new Random().nextInt(ll.size());\n}\n \nSystem.out.println(\"Swap content at index \" + swapFrom \n + \" of LinkedList with content at index \" + swapTo + \":\");\nString tmp = ll.get(swapTo); // Temporarily hold content at index swapTo.\nll.set(swapTo, ll.get(swapFrom)); // Place what is at index swapFrom and overwrite what is at index swapTo.\nll.set(swapFrom, tmp); // Overwrite what is at index swapfrom with what is in tmp.\nSystem.out.println(ll); // Display List with swapped elements.\nSystem.out.println();\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14040069/"
] |
74,576,751
|
<p>I need to write an <code>multiply</code> macro which converts ident into single letter idents and multiply them.</p>
<pre class="lang-rust prettyprint-override"><code>let a = 4;
let b = 7;
println!("{}", multiply!(abbabbb));
// println!("{}", (a * b * b * a * b * b * b))
</code></pre>
<p>but I dont know how to match a single letter.</p>
<p>I want to do something like this:</p>
<pre class="lang-rust prettyprint-override"><code>macro_rules! multiply {
($id:letter$other:tt) => {
$id * multiply!($other)
};
($id:ident) => {
$id
}
}
</code></pre>
|
[
{
"answer_id": 74576987,
"author": "totikom",
"author_id": 6784879,
"author_profile": "https://Stackoverflow.com/users/6784879",
"pm_score": 3,
"selected": true,
"text": "String"
},
{
"answer_id": 74581265,
"author": "Jmb",
"author_id": 5397009,
"author_profile": "https://Stackoverflow.com/users/5397009",
"pm_score": 2,
"selected": false,
"text": "macro_rules macro_rules! multiply {\n ($($id:ident)*) => {\n 1 $(* $id)*\n }\n}\n\nfn main() {\n let a = 4;\n let b = 7;\n println!(\"{}\", multiply!(a b b a b b b));\n}\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18032908/"
] |
74,576,775
|
<p>This is the code for storing an array only. What I want now is to update each field or can add new rows but I don't know how.</p>
<pre><code> foreach ($request->requirements as $key => $requirements) {
$req = new FormReq();
$req->requirements = $requirements['title'];
$req->form_id = $id;
$req->save();
}
</code></pre>
<p>My blade file</p>
<pre><code>@foreach ($requirements as $reqs)
<tr>
<td><input type="text" name="requirements[0][title]"
placeholder="Enter requirements" class="form-control"
value="{{ $reqs->requirements }}" />
</td>
<td><button type="button" class="btn btn-sm btn-danger remove-tr">Remove</button>
</td>
</tr>
@endforeach
</code></pre>
<p><a href="https://i.stack.imgur.com/Tjw1V.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Tjw1V.png" alt="enter image description here" /></a>
<a href="https://i.stack.imgur.com/6x4In.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6x4In.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74576987,
"author": "totikom",
"author_id": 6784879,
"author_profile": "https://Stackoverflow.com/users/6784879",
"pm_score": 3,
"selected": true,
"text": "String"
},
{
"answer_id": 74581265,
"author": "Jmb",
"author_id": 5397009,
"author_profile": "https://Stackoverflow.com/users/5397009",
"pm_score": 2,
"selected": false,
"text": "macro_rules macro_rules! multiply {\n ($($id:ident)*) => {\n 1 $(* $id)*\n }\n}\n\nfn main() {\n let a = 4;\n let b = 7;\n println!(\"{}\", multiply!(a b b a b b b));\n}\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17919686/"
] |
74,576,784
|
<p>Why my stack implementation not working and giving the error "Segmentation fault (core dumped)"
Here is the code
`</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
int main()
{
struct node *head, *newNode, *temp;
head = 0;
int choice=1;
while(choice)
{
newNode = (struct node *)malloc(sizeof(struct node));
printf("Enter Data: \n");
scanf("%d", &newNode->data);
newNode->next = 0;
if (head == 0)
{
head=newNode;
}
else{
temp->next=newNode;
temp=newNode;
}
printf("Do You Want to Continue(0,1)?\n");
scanf("%d",&choice);
}
temp=head;
while(temp!=0){
printf("%d",temp->data);
temp=temp->next;
}
return 0;
}
</code></pre>
<p>I was trying to implement the LInked LIst but got the error "Segmentation fault (core dumped)"</p>
|
[
{
"answer_id": 74576823,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 1,
"selected": false,
"text": " else{\n temp->next=newNode;\n temp=newNode;\n }\n temo struct node *head, *newNode, *temp;\n temp->next=newNode;\n if (head == 0)\n {\n head=newNode;\n temp = head;\n }\n newNode = malloc(sizeof(struct node));\n\n printf(\"Enter Data: \\n\");\n scanf(\"%d\", &newNode->data);\n\n newNode->next = head;\n head = newNode;\n while ( head != NULL )\n{\n temp = head;\n head = head->next;\n free( temp );\n}\n"
},
{
"answer_id": 74576841,
"author": "azhen7",
"author_id": 20341797,
"author_profile": "https://Stackoverflow.com/users/20341797",
"pm_score": 0,
"selected": false,
"text": "temp->next=newNode;\n temp temp temp temp temp->next if (head == 0)\n{\n head=newNode;\n temp = head=newNode;\n}\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74576784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20601854/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.