qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,571,381
|
<p>I have the following <code>df</code> :</p>
<pre><code>df=pd.DataFrame({
'Q0_0': ["A vs. Z", "A vs. Bc", "B vs. Z", "B vs Bc", "Bc vs. A", "Bc vs. B", "Z vs. A", "Z vs. B", "C vs. A", "Bc vs. A"],
'Q1_1': [np.random.randint(1,100) for i in range(10)],
'Q1_2': np.random.random(10),
'Q1_3': np.random.randint(2, size=10),
'Q2_1': [np.random.randint(1,100) for i in range(10)],
'Q2_2': np.random.random(10),
'Q2_3': np.random.randint(2, size=10),
'Q3_1': [np.random.randint(1,100) for i in range(10)],
'Q3_2': np.random.random(10),
'Q3_3': np.random.randint(2, size=10),
'Q4_1': [np.random.randint(1,100) for i in range(10)],
'Q4_2': np.random.random(10),
'Q4_3': np.random.randint(2, size=10)
})
</code></pre>
<p>It has the following display:</p>
<pre><code>Q0_0 Q1_1 Q1_2 Q1_3 Q2_1 Q2_2 Q2_3 Q3_1 Q3_2 Q3_3 Q4_1 Q4_2 Q4_3
0 A vs. Z 76 0.475198 0 31 0.785794 0 93 0.713219 0 31 0.549401 0
1 A vs. Bc 36 0.441907 0 28 0.008276 1 79 0.132327 0 61 0.657476 1
2 B vs. Z 68 0.474950 0 49 0.401341 1 1 0.409924 0 13 0.471476 0
3 B vs Bc 74 0.462356 0 42 0.762348 0 16 0.337623 1 76 0.548017 1
4 Bc vs. A 63 0.738769 1 34 0.340055 1 74 0.488053 1 84 0.663768 1
5 Bc vs. B 18 0.384001 1 75 0.188500 1 72 0.464784 1 32 0.355016 1
6 Z vs. A 34 0.700306 1 92 0.348228 1 99 0.347391 0 13 0.810568 0
7 Z vs. B 84 0.262367 0 11 0.217050 0 77 0.144048 0 44 0.262738 0
8 C vs. A 90 0.846719 1 53 0.603059 1 53 0.212426 1 86 0.515018 1
9 Bc vs. A 11 0.492974 0 76 0.351270 0 5 0.297710 1 40 0.185969 1
</code></pre>
<p>I want a rule allowing me to consider <code>Z vs. A</code> as duplicate of <code>A vs. Z</code> and so on for each <code>b vs. a</code> as a diplicate of <code>a vs. b</code> in column <code>Q0_0</code>.</p>
<p>Then proceed with removing those considered as duplicates.</p>
<p><strong>Expected output is :</strong></p>
<pre><code>Q0_0 Q1_1 Q1_2 Q1_3 Q2_1 Q2_2 Q2_3 Q3_1 Q3_2 Q3_3 Q4_1 Q4_2 Q4_3
0 A vs. Z 76 0.475198 0 31 0.785794 0 93 0.713219 0 31 0.549401 0
1 A vs. Bc 36 0.441907 0 28 0.008276 1 79 0.132327 0 61 0.657476 1
2 B vs. Z 68 0.474950 0 49 0.401341 1 1 0.409924 0 13 0.471476 0
3 B vs Bc 74 0.462356 0 42 0.762348 0 16 0.337623 1 76 0.548017 1
8 C vs. A 90 0.846719 1 53 0.603059 1 53 0.212426 1 86 0.515018 1
</code></pre>
<p>There is a way to do that in my pandas dataframe ?</p>
<p>Any help from your side will be highly appreciated, thanks.</p>
|
[
{
"answer_id": 74571413,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": true,
"text": "str.extract str.split vs. frozenset duplicated s = df['Q0_0'].str.extract('(\\w+)\\s*vs\\.?\\s*(\\w+)').agg(frozenset, axis=1)\n# or\n# s = df['Q0_0'].str.split(r'\\s*vs\\.?\\s*', expand=True).agg(frozenset, axis=1)\n\nout = df[~s.duplicated()]\n Q0_0 Q1_1 Q1_2 Q1_3 Q2_1 Q2_2 Q2_3 Q3_1 Q3_2 Q3_3 Q4_1 Q4_2 Q4_3\n0 A vs. Z 88 0.664299 0 99 0.102871 0 55 0.905342 0 55 0.789227 1\n1 A vs. Bc 71 0.577607 0 99 0.784006 1 39 0.698947 0 82 0.055739 1\n2 B vs. Z 81 0.248065 1 9 0.216285 0 13 0.128918 0 49 0.571096 0\n3 B vs Bc 95 0.991130 1 80 0.346051 1 54 0.197197 1 30 0.928300 0\n8 C vs. A 97 0.440715 0 88 0.986333 1 75 0.161888 0 42 0.831142 0\n s\n\n0 (Z, A)\n1 (Bc, A)\n2 (Z, B)\n3 (Bc, B)\n4 (A, Bc)\n5 (B, Bc)\n6 (Z, A)\n7 (Z, B)\n8 (C, A)\n9 (A, Bc)\ndtype: object\n\n~s.duplicated()\n\n0 True\n1 True\n2 True\n3 True\n4 False\n5 False\n6 False\n7 False\n8 True\n9 False\ndtype: bool\n"
},
{
"answer_id": 74571493,
"author": "gants_kuhelgarten",
"author_id": 3903807,
"author_profile": "https://Stackoverflow.com/users/3903807",
"pm_score": 0,
"selected": false,
"text": "'.join(sorted(str)) drop_duplicates"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74571381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15852600/"
] |
74,571,395
|
<p>This is my html</p>
<pre><code>
<div class="pr-2" style="width: 130px">
<div *ngIf="!element.editing" >
<span class="ss">{{element.barcode}}</span>
</div>
<div *ngIf="element.editing" >
<input type="text" [(ngModel)]="element.barcode" style="width: 130px"/>
</div>
</div>
</code></pre>
<p>This is my css</p>
<pre><code>.ss {
font-family: 'Libre Barcode 128 Text', cursive;
font-size: 22px;
}
</code></pre>
<p>This is my javascript function</p>
<pre><code>barcodeGenerator(value){
let x = value
let i, j, intWeight, intLength, intWtProd = 0, arrayData = [];
let arraySubst = [ "Ã", "Ä", "Å", "Æ", "Ç", "È", "É", "Ê" ];
/*
* Checksum Calculation for Code 128 B
*/
intLength = x.length;
arrayData[0] = 104; // Assume Code 128B, Will revise to support A, C and switching.
intWtProd = 104;
for (j = 0; j < intLength; j += 1) {
arrayData[j + 1] = x.charCodeAt(j) - 32; // Have to convert to Code 128 encoding
intWeight = j + 1; // to generate the checksum
intWtProd += intWeight * arrayData[j + 1]; // Just a weighted sum
}
arrayData[j + 1] = intWtProd % 103; // Modulo 103 on weighted sum
arrayData[j + 2] = 106; // Code 128 Stop character
const chr = parseInt(arrayData[j + 1], 10); // Gotta convert from character to a number
if (chr > 94) {
var chrString = arraySubst[chr - 95];
} else {
chrString = String.fromCharCode(chr + 32);
}
// document.getElementById(id).innerHTML =
return 'Ì' + // Start Code B
x + // The originally typed string
chrString + // The generated checksum
'Î'; // Stop Code
// return `<span class="ss">${x}</span>`;
}
</code></pre>
<p>This is the Output
<a href="https://i.stack.imgur.com/Qhzyg.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>but i want to hide/remove text under barcode.</p>
<p>like this <a href="https://i.stack.imgur.com/99czn.png" rel="nofollow noreferrer">enter image description here</a></p>
|
[
{
"answer_id": 74571413,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": true,
"text": "str.extract str.split vs. frozenset duplicated s = df['Q0_0'].str.extract('(\\w+)\\s*vs\\.?\\s*(\\w+)').agg(frozenset, axis=1)\n# or\n# s = df['Q0_0'].str.split(r'\\s*vs\\.?\\s*', expand=True).agg(frozenset, axis=1)\n\nout = df[~s.duplicated()]\n Q0_0 Q1_1 Q1_2 Q1_3 Q2_1 Q2_2 Q2_3 Q3_1 Q3_2 Q3_3 Q4_1 Q4_2 Q4_3\n0 A vs. Z 88 0.664299 0 99 0.102871 0 55 0.905342 0 55 0.789227 1\n1 A vs. Bc 71 0.577607 0 99 0.784006 1 39 0.698947 0 82 0.055739 1\n2 B vs. Z 81 0.248065 1 9 0.216285 0 13 0.128918 0 49 0.571096 0\n3 B vs Bc 95 0.991130 1 80 0.346051 1 54 0.197197 1 30 0.928300 0\n8 C vs. A 97 0.440715 0 88 0.986333 1 75 0.161888 0 42 0.831142 0\n s\n\n0 (Z, A)\n1 (Bc, A)\n2 (Z, B)\n3 (Bc, B)\n4 (A, Bc)\n5 (B, Bc)\n6 (Z, A)\n7 (Z, B)\n8 (C, A)\n9 (A, Bc)\ndtype: object\n\n~s.duplicated()\n\n0 True\n1 True\n2 True\n3 True\n4 False\n5 False\n6 False\n7 False\n8 True\n9 False\ndtype: bool\n"
},
{
"answer_id": 74571493,
"author": "gants_kuhelgarten",
"author_id": 3903807,
"author_profile": "https://Stackoverflow.com/users/3903807",
"pm_score": 0,
"selected": false,
"text": "'.join(sorted(str)) drop_duplicates"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74571395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20386007/"
] |
74,571,396
|
<p>repalce a string with python</p>
<p>I have tried the replace function but it gives me an str error</p>
|
[
{
"answer_id": 74571413,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": true,
"text": "str.extract str.split vs. frozenset duplicated s = df['Q0_0'].str.extract('(\\w+)\\s*vs\\.?\\s*(\\w+)').agg(frozenset, axis=1)\n# or\n# s = df['Q0_0'].str.split(r'\\s*vs\\.?\\s*', expand=True).agg(frozenset, axis=1)\n\nout = df[~s.duplicated()]\n Q0_0 Q1_1 Q1_2 Q1_3 Q2_1 Q2_2 Q2_3 Q3_1 Q3_2 Q3_3 Q4_1 Q4_2 Q4_3\n0 A vs. Z 88 0.664299 0 99 0.102871 0 55 0.905342 0 55 0.789227 1\n1 A vs. Bc 71 0.577607 0 99 0.784006 1 39 0.698947 0 82 0.055739 1\n2 B vs. Z 81 0.248065 1 9 0.216285 0 13 0.128918 0 49 0.571096 0\n3 B vs Bc 95 0.991130 1 80 0.346051 1 54 0.197197 1 30 0.928300 0\n8 C vs. A 97 0.440715 0 88 0.986333 1 75 0.161888 0 42 0.831142 0\n s\n\n0 (Z, A)\n1 (Bc, A)\n2 (Z, B)\n3 (Bc, B)\n4 (A, Bc)\n5 (B, Bc)\n6 (Z, A)\n7 (Z, B)\n8 (C, A)\n9 (A, Bc)\ndtype: object\n\n~s.duplicated()\n\n0 True\n1 True\n2 True\n3 True\n4 False\n5 False\n6 False\n7 False\n8 True\n9 False\ndtype: bool\n"
},
{
"answer_id": 74571493,
"author": "gants_kuhelgarten",
"author_id": 3903807,
"author_profile": "https://Stackoverflow.com/users/3903807",
"pm_score": 0,
"selected": false,
"text": "'.join(sorted(str)) drop_duplicates"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74571396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16499617/"
] |
74,571,403
|
<p>I have a data which contain 2 different language information.</p>
<pre><code>IF OBJECT_ID('tempdb..#TblName') IS NOT NULL
BEGIN
DROP TABLE #TblName
END
CREATE TABLE #TblName (
JobNum varchar(10)
,CommentText nvarchar(max)
)
INSERT INTO #TblName VALUES ('F001234','Vietnamese point-1; Vietnamese point-2; Vietnamese point-3; Vietnamese point-4; Vietnamese point-5; English point-1; English point-2; English point-3; English point-4; English point-5;')
INSERT INTO #TblName VALUES ('F005678','Vietnamese point-1; English point-2; Vietnamese point-3; English point-1; Vietnamese point-2; English point-3; English point-4')
select * from #TblName
</code></pre>
<p>and the output is as below:</p>
<pre><code>JobNum CommentText
F001234 Vietnamese point-1; Vietnamese point-2; Vietnamese point-3; Vietnamese point-4; Vietnamese point-5; English point-1; English point-2; English point-3; English point-4; English point-5;
F005678 Vietnamese point-1; English point-2; Vietnamese point-3; English point-1; Vietnamese point-2; English point-3; English point-4
</code></pre>
<p>is there a way in SQL query to get output like in 2 different columns for each language information:</p>
<p><a href="https://i.stack.imgur.com/ZCsHK.png" rel="nofollow noreferrer">ouput</a></p>
<p>Thanks in advance to any answer...</p>
|
[
{
"answer_id": 74573580,
"author": "Madhukar",
"author_id": 7023503,
"author_profile": "https://Stackoverflow.com/users/7023503",
"pm_score": 1,
"selected": true,
"text": "IF OBJECT_ID('tempdb..#TblName') IS NOT NULL\n BEGIN\n DROP TABLE #TblName\n END\n\nIF OBJECT_ID('tempdb..#tableB') IS NOT NULL\n BEGIN\n DROP TABLE #tableB\n END\n\nCREATE TABLE #TblName (\n JobNum varchar(10)\n ,CommentText nvarchar(max)\n)\n\nINSERT INTO #TblName VALUES ('F001234','Vietnamese point-1; Vietnamese point-2; Vietnamese point-3; Vietnamese point-4; Vietnamese point-5; English point-1; English point-2; English point-3; English point-4; English point-5;')\nINSERT INTO #TblName VALUES ('F005678','Vietnamese point-1; English point-2; Vietnamese point-3; English point-1; Vietnamese point-2; English point-3; English point-4')\n\nselect * from #TblName\n #tableB SELECT JobNum, RetVal, SUBSTRING(retval,1,CHARINDEX(' ',retval,0)) Lang \nINTO #tableB \nFROM (\n Select A.JobNum\n ,B.*\n FROM #TblName A\n CROSS APPLY (SELECT RetVal = LTRIM(RTRIM(B.i.value('(./text())[1]', 'varchar(max)')))\n From (\n SELECT x = CAST('<x>' + REPLACE((SELECT REPLACE(A.CommentText,';','§§Split§§') AS [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')\n ) as A \n CROSS APPLY x.nodes('x') AS B(i)) B\n )t where retval IS NOT NULL\n\nSELECT * from #tableB\n SELECT * \nFROM (\n SELECT jobnum,lang, STUFF((\n SELECT ';' + RetVal\n FROM #tableB xx\n WHERE xx.JobNum = xy.JobNum and xx.Lang = xy.Lang\n ORDER BY XX.RetVal\n FOR XML PATH('')\n \n ), 1, 1, '') AS a\n FROM #tableB xy\n GROUP BY JobNum,Lang\n )t\nPIVOT (MAX(a) \n FOR lang IN ([English],[Vietnamese])) piv\n"
},
{
"answer_id": 74573675,
"author": "SQLpro",
"author_id": 12659872,
"author_profile": "https://Stackoverflow.com/users/12659872",
"pm_score": -1,
"selected": false,
"text": "WITH \nT AS\n(\nselect JobNum, LTRIM(value) AS V, LEFT(LTRIM(value), CHARINDEX(' ', LTRIM(value)) - 1) AS L\nfrom #TblName\n CROSS APPLY STRING_SPLIT(CommentText, ';')\nWHERE LTRIM(value) <> ''\n)\nSELECT JobNum, \n CASE WHEN L = 'Vietnamese' THEN RIGHT(V, LEN(V) - CHARINDEX (' ', V)) ELSE NULL END AS Vietnamese,\n CASE WHEN L = 'English' THEN RIGHT(V, LEN(V) - CHARINDEX (' ', V)) ELSE NULL END AS English\nFROM T\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74571403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20598188/"
] |
74,571,410
|
<p>I experienced some weird behavior when I was reading a csv file into 2 dimensional byte slice. The first 42 rows are fine and after that it seems like extra line ending are put into the data which messes up things:</p>
<p>first row in the first 42 times:</p>
<pre><code>row 0: 504921600000000000,truck_0,South,Trish,H-2,v2.3,1500,150,12,52.31854,4.72037,124,0,221,0,25
</code></pre>
<p>first row after I appended 43 rows:</p>
<pre><code>row 0: 504921600000000000,truck_49,South,Andy,F-150,v2.0,2000,200,15,38.9349,179.94282,289,0,269,0
row 1: 25
</code></pre>
<p>minimal code to reproduce the problem:</p>
<pre class="lang-golang prettyprint-override"><code>package main
import (
"bufio"
"log"
"os"
)
type fileDataSource struct {
scanner *bufio.Scanner
}
type batch struct {
rows [][]byte
}
func (b *batch) Len() uint {
return uint(len(b.rows))
}
func (b *batch) Append(row []byte) {
b.rows = append(b.rows, row)
for index, row := range b.rows {
log.Printf("row %d: %s\n", index, string(row))
}
if len(b.rows) > 43 {
log.Fatalf("asdf")
}
}
type factory struct{}
func (f *factory) New() *batch {
return &batch{rows: make([][]byte, 0)}
}
func main() {
file, _ := os.Open("/tmp/data1.csv")
scanner := bufio.NewScanner(bufio.NewReaderSize(file, 4<<20))
b := batch{}
for scanner.Scan() {
b.Append(scanner.Bytes())
}
}
</code></pre>
<p>csv I used:</p>
<pre><code>504921600000000000,truck_0,South,Trish,H-2,v2.3,1500,150,12,52.31854,4.72037,124,0,221,0,25
504921600000000000,truck_1,South,Albert,F-150,v1.5,2000,200,15,72.45258,68.83761,255,0,181,0,25
504921600000000000,truck_2,North,Derek,F-150,v1.5,2000,200,15,24.5208,28.09377,428,0,304,0,25
504921600000000000,truck_3,East,Albert,F-150,v2.0,2000,200,15,18.11037,98.65573,387,0,192,0,25
504921600000000000,truck_4,West,Andy,G-2000,v1.5,5000,300,19,81.93919,56.12266,236,0,335,0,25
504921600000000000,truck_5,East,Seth,F-150,v2.0,2000,200,15,5.00552,114.50557,89,0,187,0,25
504921600000000000,truck_6,East,Trish,G-2000,v1.0,5000,300,19,41.59689,57.90174,395,0,150,0,25
504921600000000000,truck_8,South,Seth,G-2000,v1.0,5000,300,19,21.89157,44.58919,411,0,232,0,25
504921600000000000,truck_9,South,Andy,H-2,v2.3,1500,150,12,15.67271,112.4023,402,0,75,0,25
504921600000000000,truck_10,North,Albert,F-150,v2.3,2000,200,15,35.05682,36.20513,359,0,68,0,25
504921600000000000,truck_7,East,Andy,H-2,v2.0,1500,150,12,7.74826,14.96075,105,0,323,0,25
504921600000000000,truck_11,South,Derek,F-150,v1.0,2000,200,15,87.9924,134.71544,293,0,133,0,25
504921600000000000,truck_14,North,Albert,H-2,v1.0,1500,150,12,66.68217,105.76965,222,0,252,0,25
504921600000000000,truck_18,West,Trish,F-150,v2.0,2000,200,15,67.15164,153.56165,252,0,240,0,25
504921600000000000,truck_20,North,Rodney,G-2000,v2.0,5000,300,19,38.88807,65.86698,104,0,44,0,25
504921600000000000,truck_21,East,Derek,G-2000,v2.0,5000,300,19,81.87812,167.8083,345,0,327,0,25
504921600000000000,truck_22,West,Albert,G-2000,v1.5,5000,300,19,39.9433,16.0241,449,0,42,0,25
504921600000000000,truck_23,South,Andy,F-150,v2.0,2000,200,15,73.28358,98.05159,198,0,276,0,25
504921600000000000,truck_24,West,Rodney,G-2000,v2.3,5000,300,19,22.19262,0.27462,223,0,318,0,25
504921600000000000,truck_25,North,Trish,F-150,v2.0,2000,200,15,17.26704,16.91226,461,0,183,0,25
504921600000000000,truck_26,South,Seth,F-150,v1.5,2000,200,15,45.65327,144.60354,58,0,182,0,25
504921600000000000,truck_12,East,Trish,G-2000,v1.0,5000,300,19,36.03928,113.87118,39,0,294,0,25
504921600000000000,truck_13,West,Derek,H-2,v1.0,1500,150,12,14.07479,110.77267,152,0,69,0,25
504921600000000000,truck_27,West,Seth,G-2000,v1.5,5000,300,19,79.55971,97.86182,252,0,345,0,25
504921600000000000,truck_28,West,Rodney,G-2000,v1.5,5000,300,19,60.33457,4.62029,74,0,199,0,25
504921600000000000,truck_16,South,Albert,G-2000,v1.5,5000,300,19,51.16438,121.32451,455,0,290,0,25
504921600000000000,truck_19,West,Derek,G-2000,v1.5,5000,300,19,19.69355,139.493,451,0,300,0,25
504921600000000000,truck_31,North,Albert,G-2000,v1.0,5000,300,19,0.75251,116.83474,455,0,49,0,25
504921600000000000,truck_32,West,Seth,F-150,v2.0,2000,200,15,4.07566,164.43909,297,0,277,0,25
504921600000000000,truck_33,West,Rodney,G-2000,v1.5,5000,300,19,89.19448,10.47499,407,0,169,0,25
504921600000000000,truck_34,West,Rodney,G-2000,v2.0,5000,300,19,73.7383,10.79582,488,0,170,0,25
504921600000000000,truck_35,West,Seth,G-2000,v2.3,5000,300,19,60.02428,2.51011,480,0,307,0,25
504921600000000000,truck_36,North,Andy,G-2000,v1.0,5000,300,19,87.52877,45.07308,161,0,128,0,25
504921600000000000,truck_38,West,Andy,H-2,v2.3,,150,12,63.54604,119.82031,282,0,325,0,25
504921600000000000,truck_39,East,Derek,G-2000,v1.5,5000,300,19,33.83548,3.90996,294,0,123,0,25
504921600000000000,truck_40,West,Albert,H-2,v2.0,1500,150,12,32.32773,118.43138,276,0,316,0,25
504921600000000000,truck_41,East,Rodney,F-150,v1.0,2000,200,15,68.85572,173.23123,478,0,207,0,25
504921600000000000,truck_42,West,Trish,F-150,v2.0,2000,200,15,38.45195,171.2884,113,0,180,0,25
504921600000000000,truck_43,East,Derek,H-2,v2.0,1500,150,12,52.90189,49.76966,295,0,195,0,25
504921600000000000,truck_44,South,Seth,H-2,v1.0,1500,150,12,32.33297,3.89306,396,0,320,0,25
504921600000000000,truck_30,East,Andy,G-2000,v1.5,5000,300,19,29.62198,83.73482,291,0,267,0,25
504921600000000000,truck_46,West,Seth,H-2,v2.3,1500,150,12,26.07966,118.49629,321,,267,0,25
504921600000000000,truck_37,South,Andy,G-2000,v2.0,5000,300,19,57.90077,77.20136,77,0,179,0,25
504921600000000000,truck_49,South,Andy,F-150,v2.0,2000,200,15,38.9349,179.94282,289,0,269,0,25
504921600000000000,truck_53,West,Seth,G-2000,v2.3,5000,300,19,25.02,157.45082,272,0,5,0,25
504921600000000000,truck_54,North,Andy,H-2,v2.0,1500,150,12,87.62736,106.0376,360,0,66,0,25
504921600000000000,truck_55,East,Albert,G-2000,v1.0,5000,300,19,78.56605,71.16225,295,0,150,0,25
504921600000000000,truck_56,North,Derek,F-150,v2.0,2000,200,15,23.51619,123.22682,71,0,209,0,25
504921600000000000,truck_57,South,Rodney,F-150,v2.3,2000,200,15,26.07996,159.92716,454,0,22,0,25
504921600000000000,truck_58,South,Derek,F-150,v2.0,2000,200,15,84.79333,79.23813,175,0,246,0,25
504921600000000000,truck_59,East,Andy,H-2,v2.0,1500,150,12,8.7621,82.48318,82,0,55,0,25
504921600000000000,truck_45,East,Trish,G-2000,v1.0,5000,300,19,17.48624,100.78121,306,0,193,0,25
504921600000000000,truck_47,South,Derek,G-2000,v1.5,5000,300,19,41.62173,110.80422,111,0,78,0,25
504921600000000000,truck_48,East,Trish,G-2000,v1.5,5000,300,19,63.90773,141.50555,53,0,,0,25
504921600000000000,truck_50,East,Andy,H-2,v2.3,1500,150,12,45.44111,172.39833,219,0,88,0,25
504921600000000000,truck_51,East,Rodney,F-150,v2.3,2000,200,15,89.03645,91.57675,457,0,337,0,25
504921600000000000,truck_52,West,Derek,G-2000,v1.0,5000,300,19,89.0133,97.8037,23,0,168,0,25
504921600000000000,truck_61,East,Albert,G-2000,v2.3,5000,300,19,75.91676,167.78366,462,0,60,0,25
504921600000000000,truck_62,East,Derek,H-2,v1.5,1500,150,12,54.61668,103.21398,231,0,143,0,25
504921600000000000,truck_63,South,Rodney,H-2,v2.0,1500,150,12,37.13702,149.25546,46,0,118,0,25
504921600000000000,truck_64,South,Albert,G-2000,v2.0,5000,300,19,45.04214,10.73002,447,0,253,0,25
504921600000000000,truck_60,South,Derek,H-2,v1.5,1500,150,12,57.99184,33.45994,310,0,93,0,25
504921600000000000,truck_67,South,Seth,H-2,v1.0,1500,150,12,4.62985,155.01707,308,0,22,0,25
504921600000000000,truck_68,West,Rodney,F-150,v1.5,2000,200,15,16.90741,123.03863,303,0,43,0,25
504921600000000000,truck_69,East,Derek,H-2,v2.3,1500,150,12,79.88424,120.79121,407,0,138,0,25
504921600000000000,truck_70,North,Albert,H-2,v2.0,1500,150,12,77.87592,164.70924,270,0,21,0,25
504921600000000000,truck_71,West,Seth,G-2000,v2.3,5000,300,19,72.75635,78.0365,391,0,32,0,25
504921600000000000,truck_73,North,Seth,F-150,v1.5,2000,200,15,37.67468,91.09732,489,0,103,0,25
504921600000000000,truck_74,North,Trish,H-2,v1.0,1500,150,12,41.4456,158.13897,206,0,79,0,25
504921600000000000,truck_75,South,Andy,F-150,v1.5,2000,200,15,4.11709,175.65994,378,0,176,0,25
504921600000000000,truck_66,South,Seth,G-2000,v2.0,5000,300,19,42.24286,151.8978,227,0,67,0,25
504921600000000000,truck_72,South,Andy,G-2000,v2.3,5000,300,19,82.46228,2.44504,487,0,39,0,25
504921600000000000,truck_76,South,Rodney,F-150,v2.3,2000,200,15,71.62798,121.89842,283,0,164,0,25
504921600000000000,truck_78,South,Seth,F-150,v2.0,2000,200,15,13.96218,39.04615,433,0,326,0,25
504921600000000000,truck_79,South,Andy,G-2000,v2.0,5000,300,19,56.54137,,46,0,127,0,25
504921600000000000,truck_81,West,Rodney,G-2000,v2.3,5000,300,19,59.42624,115.59744,68,0,296,0,25
504921600000000000,truck_83,South,Albert,F-150,v2.0,2000,200,15,49.20261,115.98262,449,0,132,0,25
504921600000000000,truck_84,West,Derek,H-2,v1.0,1500,150,12,70.16476,59.05399,301,0,134,0,25
504921600000000000,truck_85,West,Derek,G-2000,v1.0,5000,300,19,11.75251,142.86513,358,0,339,0,25
504921600000000000,truck_86,West,Rodney,G-2000,v1.0,5000,300,19,30.92821,127.53274,367,0,162,0,25
504921600000000000,truck_87,West,Rodney,H-2,v2.0,1500,150,12,32.86913,155.7666,122,0,337,0,25
504921600000000000,truck_88,West,Andy,G-2000,v1.5,5000,300,19,60.03367,9.5707,204,0,333,0,25
504921600000000000,truck_80,East,Andy,G-2000,v2.3,5000,300,,46.13937,137.42962,295,0,290,0,25
504921600000000000,truck_91,East,Derek,F-150,v2.0,2000,200,15,7.13401,52.78885,100,0,147,0,25
504921600000000000,truck_93,North,Derek,G-2000,v2.0,5000,300,19,11.46065,20.57173,242,0,148,0,25
504921600000000000,truck_94,North,Derek,F-150,v1.0,2000,200,15,59.53287,26.98247,427,0,341,0,25
504921600000000000,truck_95,East,Albert,G-2000,v2.0,5000,300,19,37.31513,134.40078,383,0,121,0,25
504921600000000000,truck_96,East,Albert,G-2000,v1.5,5000,300,19,15.78803,146.68255,348,0,189,0,25
504921600000000000,truck_97,South,Seth,F-150,v1.0,2000,200,15,14.08559,18.49763,369,0,34,0,25
504921600000000000,truck_98,South,Albert,G-2000,v1.5,5000,300,19,15.1474,71.85194,89,0,238,0,25
504921600000000000,truck_77,East,Trish,F-150,v2.0,2000,200,15,80.5734,17.68311,389,0,218,0,25
504921600000000000,truck_82,West,Derek,H-2,v2.0,1500,150,12,57.00976,90.13642,102,0,296,0,25
504921600000000000,truck_92,North,Derek,H-2,v1.0,1500,150,12,54.40335,153.5809,123,0,150,0,25
504921600000000000,truck_99,West,Trish,G-2000,v1.5,5000,300,19,62.73061,26.1884,309,0,202,0,25
504921610000000000,truck_1,South,Albert,F-150,v1.5,2000,200,15,72.45157,68.83919,259,0,180,2,27.5
504921610000000000,truck_2,North,Derek,F-150,v1.5,2000,200,15,24.5195,28.09369,434,6,302,0,22.1
504921610000000000,truck_3,East,Albert,F-150,v2.0,2000,200,15,18.107,98.66002,390,,190,0,21.2
504921610000000000,truck_4,West,Andy,G-2000,v1.5,5000,300,19,81.9438,56.12717,244,8,334,2,27.6
504921610000000000,truck_5,East,Seth,F-150,v2.0,2000,200,15,5.00695,114.50676,92,7,183,2,28.5
504921610000000000,truck_6,East,Trish,G-2000,v1.0,5000,300,19,41.59389,57.90166,403,0,149,0,22.7
504921610000000000,truck_7,East,Andy,H-2,v2.0,1500,150,12,7.74392,14.95756,,0,320,0,28.2
504921610000000000,truck_12,East,Trish,G-2000,v1.0,5000,300,19,36.03979,113.8752,34,0,293,1,26.3
504921610000000000,truck_13,West,Derek,H-2,v1.0,1500,150,12,14.07315,110.77235,150,0,72,,21.9
504921610000000000,truck_14,North,Albert,H-2,v1.0,1500,150,12,,105.76727,218,5,253,1,21.9
504921610000000000,truck_15,South,Albert,H-2,v1.5,1500,150,12,6.78254,166.86685,5,0,110,0,26.3
504921610000000000,truck_16,South,Albert,G-2000,v1.5,5000,300,19,51.16405,121.32556,445,0,294,3,29.9
504921610000000000,truck_17,West,Derek,H-2,v1.5,1500,150,12,8.12913,56.57343,9,0,6,4,29
504921610000000000,truck_18,West,Trish,F-150,v2.0,2000,200,15,67.15167,153.56094,260,1,239,1,23.3
504921610000000000,truck_19,West,Derek,G-2000,v1.5,5000,300,19,19.69456,139.49545,448,4,298,0,29.9
504921610000000000,truck_20,North,Rodney,G-2000,v2.0,5000,300,19,38.88968,65.86504,103,0,41,1,23.6
504921610000000000,truck_21,East,Derek,G-2000,v2.0,5000,300,19,81.88232,167.81287,345,0,326,0,20.8
504921610000000000,truck_0,South,Trish,H-2,v2.3,1500,150,12,52.32335,4.71786,128,9,225,0,25.8
504921610000000000,truck_22,West,Albert,G-2000,v1.5,5000,300,19,39.94345,16.02353,440,1,45,0,27.8
504921610000000000,truck_8,South,Seth,G-2000,v1.0,5000,300,19,21.89464,44.58628,402,0,234,0,20.3
504921610000000000,truck_23,South,Andy,F-150,v2.0,2000,200,15,73.28131,98.05635,201,7,277,0,25.3
504921610000000000,truck_24,West,Rodney,G-2000,v2.3,5000,300,19,22.19506,0.27702,217,0,321,2,29.5
504921610000000000,truck_9,South,Andy,H-2,v2.3,1500,150,12,,112.40429,402,9,75,4,29.5
504921610000000000,truck_26,South,Seth,F-150,v1.5,2000,200,15,45.65798,144.60844,59,1,183,0,21.7
504921610000000000,truck_27,West,Seth,G-2000,v1.5,5000,300,19,79.55699,97.86561,255,7,348,2,20.2
504921610000000000,truck_25,North,Trish,F-150,v2.0,2000,200,15,17.26506,16.91691,453,8,186,0,24.3
504921610000000000,truck_28,West,Rodney,G-2000,v1.5,5000,300,19,60.33272,4.61578,84,3,198,0,23.1
504921610000000000,truck_29,East,Rodney,G-2000,v2.0,5000,300,19,80.30331,146.54254,340,5,118,0,25.6
504921610000000000,truck_30,East,Andy,G-2000,v1.5,5000,300,19,29.62434,83.73246,300,0,270,4,22.3
504921610000000000,truck_33,West,Rodney,G-2000,v1.5,5000,300,19,89.19593,10.47733,403,8,170,0,29.6
504921610000000000,truck_36,North,Andy,G-2000,v1.0,5000,300,19,87.53087,45.07276,163,0,132,1,27.6
</code></pre>
<p>I expected the rows [][]byte contain the csv data row by row</p>
|
[
{
"answer_id": 74571652,
"author": "nj_",
"author_id": 5993518,
"author_profile": "https://Stackoverflow.com/users/5993518",
"pm_score": 3,
"selected": true,
"text": "encoding/csv Bytes() // Bytes returns the most recent token generated by a call to Scan.\n// The underlying array may point to data that will be overwritten\n// by a subsequent call to Scan. It does no allocation.\nfunc (s *Scanner) Bytes() []byte {\n return s.token\n}\n Scan() for scanner.Scan() {\n row := scanner.Bytes()\n bs := make([]byte, len(row))\n copy(bs, row)\n b.Append(bs)\n}\n"
},
{
"answer_id": 74571654,
"author": "mkopriva",
"author_id": 965900,
"author_profile": "https://Stackoverflow.com/users/965900",
"pm_score": 1,
"selected": false,
"text": "Bytes for scanner.Scan() {\n row := make([]byte, len(scanner.Bytes()))\n copy(row, scanner.Bytes())\n b.Append(row)\n}\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74571410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5565422/"
] |
74,571,477
|
<p>I have created first dropdown which returns a bit. It is either Outbound or Inbound and based on that selection I need to enable the respective further Outbound or Inbound dropdown. It means one dropdown will remain disabled.</p>
<pre><code> <div class="form-group" id="type">
<label class="control-label col-md-2">@Localiser["Outbound"] / @Localiser["Inbound"]</label>
<div class="col-md-10">
<select id="outboundInboundType" name="outboundInboundType" asp-items="@await SelectLists.OutboundInboundTypes()" class="form-control"></select>
</div>
</div>
```
Based on the selection of above code I need to open Either 'Outbound' dropdown shown below
```
<div class="form-group" id="claimOutbound">
<label asp-for="ClaimStatus" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select asp-for="ClaimStatus" class="form-control" asp-items="@await SelectLists.ClaimStatusTypes()"></select>
<span asp-validation-for="ClaimStatus" class="text-danger"/>
</div>
</div>
```
Or Inbound Dropdown below
```
<div class="form-group" id="claimInbound">
<label asp-for="ClaimStatus" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select asp-for="ClaimStatus" class="form-control" asp-items="@await SelectLists.InboundClaimStatusTypes()"></select>
<span asp-validation-for="ClaimStatus" class="text-danger" />
</div>
</div>
```
I need to achieve this using Jquery, I have tried using the ajax call but it is not working
</code></pre>
|
[
{
"answer_id": 74571652,
"author": "nj_",
"author_id": 5993518,
"author_profile": "https://Stackoverflow.com/users/5993518",
"pm_score": 3,
"selected": true,
"text": "encoding/csv Bytes() // Bytes returns the most recent token generated by a call to Scan.\n// The underlying array may point to data that will be overwritten\n// by a subsequent call to Scan. It does no allocation.\nfunc (s *Scanner) Bytes() []byte {\n return s.token\n}\n Scan() for scanner.Scan() {\n row := scanner.Bytes()\n bs := make([]byte, len(row))\n copy(bs, row)\n b.Append(bs)\n}\n"
},
{
"answer_id": 74571654,
"author": "mkopriva",
"author_id": 965900,
"author_profile": "https://Stackoverflow.com/users/965900",
"pm_score": 1,
"selected": false,
"text": "Bytes for scanner.Scan() {\n row := make([]byte, len(scanner.Bytes()))\n copy(row, scanner.Bytes())\n b.Append(row)\n}\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74571477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20174900/"
] |
74,571,482
|
<p>I am currently creating a dropdown where the value of it should by dynamic depending the selected value that I am going to use in different widget. This is my current dropdown stateful widget:</p>
<p>periodic_modal.dart</p>
<pre class="lang-dart prettyprint-override"><code>extension StringExtension on String {
String capitalize() {
return "${this[0].toUpperCase()}${this.substring(1).toLowerCase()}";
}
}
class DropDown1 extends StatefulWidget {
DropDown1({super.key});
@override
State<DropDown1> createState() => _DropDown1State();
}
class _DropDown1State extends State<DropDown1> {
String? selectedMonth;
String? selectedYear;
@override
Widget build(BuildContext context) {
print("Selection month = ${Selection.currMonth}");
return Row(
children: [
DropdownButton(
// isExpanded: true,
hint: Text("Pilih Bulan"),
underline: Container(
height: 2,
color: Colors.black,
),
icon: Visibility(visible: false, child: Icon(Icons.arrow_downward)),
items: months
.map((item) => DropdownMenuItem<String>(
value: item,
child: Text(
item,
style: const TextStyle(
fontSize: 14,
color: Colors.black,
),
overflow: TextOverflow.ellipsis,
),
))
.toList(),
value: Selection.currMonth.capitalize().isEmpty?null:Selection.currMonth.capitalize(),
onChanged: (value) {
setState(() {
selectedMonth = value as String;
Selection.currMonth = value as String;
Selection.nextMonth = value as String;
});
},
),
SizedBox(
width: 50,
),
DropdownButton(
underline: Container(
height: 2,
color: Colors.black,
),
icon: Visibility(visible: false, child: Icon(Icons.arrow_downward)),
items: years
.map((item) => DropdownMenuItem<String>(
value: item,
child: Text(
item,
style: const TextStyle(
fontSize: 14,
color: Colors.black,
),
overflow: TextOverflow.ellipsis,
),
))
.toList(),
hint: Text("Pilih Tahun"),
value: Selection.currYear == -1 ? null : Selection.currYear.toString(),
onChanged: (value) {
setState(() {
// selectedYear = value as String;
Selection.currYear = value as int;
print("value = ${value} selection currYear = ${Selection.currYear}");
print("Selection.currYear = ${Selection.currYear}");
Selection.nextYear = value as int;
print("Selection.nextYear = ${Selection.nextYear}");
});
})
],
);
}
}
</code></pre>
<p>home_page.dart (Part of this whole file)</p>
<pre class="lang-dart prettyprint-override"><code>class Selection{
static int _currYear = 0;
static String _currMonth = "";
static int _nextYear = 0;
static String _nextMonth = "";
static int get currYear => _currYear;
static String get currMonth => _currMonth;
static int get nextYear => _nextYear;
static String get nextMonth => _nextMonth;
static set currYear(int value) => _currYear = value;
static set currMonth(String value) => _currMonth = value;
static set nextYear(int value) => _nextYear = value;
static set nextMonth(String value) => _nextMonth = value;
}
</code></pre>
<p>after I did a small debugging, I have an inkling that there is something wrong on this part of code within <code>periodic_model.dart</code></p>
<pre class="lang-dart prettyprint-override"><code>onChanged: (value) {
setState(() {
// selectedYear = value as String;
Selection.currYear = value as int;
print("value = ${value} selection currYear = ${Selection.currYear}");
print("Selection.currYear = ${Selection.currYear}");
Selection.nextYear = value as int;
print("Selection.nextYear = ${Selection.nextYear}");
});
})
</code></pre>
<p>if I write <code>print("value = ${value} selection currYear = ${Selection.currYear}");</code> above <code>Selection.currYear = value as int;</code> it prints successfully before I get the error. But if I did it the way I do it in the snippet - I got the error without print the print, therefore I assume there is something wrong in <code>Selection.currYear = value as int;</code> although I am not 100% sure.</p>
<p>How should I fix this?</p>
<p><strong>//Edit</strong></p>
<p>this is the list for <code>years</code></p>
<pre class="lang-dart prettyprint-override"><code>final List<String> years = [
'2022',
'2021',
'2020',
'2019',
'2018',
'2017',
'2016',
'2015',
'2014',
'2013',
'2012',
'2011',
'2010',
'2009',
];
</code></pre>
<p>//Edit 2:
This is the class for Selection that is placed in home_page.dart</p>
<pre class="lang-dart prettyprint-override"><code>class Selection{
static List<List<Map<String,String>>> dataDummy = dummy;
static int _currYear = 0;
static String _currMonth = "";
static int _nextYear = 0;
static String _nextMonth = "";
static int get currYear => _currYear;
static String get currMonth => _currMonth;
static int get nextYear => _nextYear;
static String get nextMonth => _nextMonth;
static set currYear(int value) => _currYear = value;
static set currMonth(String value) => _currMonth = value;
static set nextYear(int value) => _nextYear = value;
static set nextMonth(String value) => _nextMonth = value;
}
</code></pre>
|
[
{
"answer_id": 74571652,
"author": "nj_",
"author_id": 5993518,
"author_profile": "https://Stackoverflow.com/users/5993518",
"pm_score": 3,
"selected": true,
"text": "encoding/csv Bytes() // Bytes returns the most recent token generated by a call to Scan.\n// The underlying array may point to data that will be overwritten\n// by a subsequent call to Scan. It does no allocation.\nfunc (s *Scanner) Bytes() []byte {\n return s.token\n}\n Scan() for scanner.Scan() {\n row := scanner.Bytes()\n bs := make([]byte, len(row))\n copy(bs, row)\n b.Append(bs)\n}\n"
},
{
"answer_id": 74571654,
"author": "mkopriva",
"author_id": 965900,
"author_profile": "https://Stackoverflow.com/users/965900",
"pm_score": 1,
"selected": false,
"text": "Bytes for scanner.Scan() {\n row := make([]byte, len(scanner.Bytes()))\n copy(row, scanner.Bytes())\n b.Append(row)\n}\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74571482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10467473/"
] |
74,571,489
|
<p>I have a v-autocomplete that only displays after I click on a loop button in my navbar.<br />
My application is supposed to allow the search on actors. I have a placeholder on this autocomplete and I'd like to style the appearance of it.<br />
At the moment it is black and in regular font, I'd like it white in italic but since I can't inspect the element I can't know which class to edit in the css.</p>
<p>Here's my code:</p>
<pre class="lang-html prettyprint-override"><code><template>
<div class="inspire">
<v-app-bar style="padding: 10px 0px;"
color="rgba(33,33,33,255)"
elevation="0"
height="64px"
>
<div style="width:100%" v-if="$route.name == 'Mapping'">
<template>
<v-autocomplete
v-model="valuesActor"
placeholder="Search on actors"
:items="actorArray"
:search-input.sync="searchActor"
filled
autofocus
mutliple
@blur="toggleSearch"
background-color="#313131"
append-icon=""
prepend-inner-icon="mdi-arrow-left"
color="var(--textLightGrey)"
:menu-props="{maxWidth: 1600}"
>
</v-autocomplete>
</template>
</div>
</v-app-bar>
</div>
</template>
</code></pre>
|
[
{
"answer_id": 74571879,
"author": "Neha Soni",
"author_id": 11834856,
"author_profile": "https://Stackoverflow.com/users/11834856",
"pm_score": 2,
"selected": true,
"text": "<style scoped>\n>>> ::placeholder {\n color: white !important;\n font-style: italic !important;\n}\n</style>\n"
},
{
"answer_id": 74571936,
"author": "charlycou",
"author_id": 9731186,
"author_profile": "https://Stackoverflow.com/users/9731186",
"pm_score": 0,
"selected": false,
"text": "color v-autocomplete color style style=\"'color:var(--textLightGrey);'\""
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74571489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16162488/"
] |
74,571,547
|
<p>I would like to know how to load the HTML form in the iframe in reactjs.</p>
<p>I have one form component that has all the input fields, and I want to load that form component in the iframe. I would like to know how I can do that.</p>
<pre><code>const Form = () => {
return (
<>
<iframe name="iframe-form" title="This is an iframe form." />
<form target="iframe-form" onSubmit={handleSubmit}>
<div>
<label htmlFor="name">Name</label>
<input
type="text"
id="name"
/>
</div>
<div>
<label htmlFor="email">Email</label>
<input type="email" id="email" />
</div>
<button>Submit</button>
</form>
</>
);
};
export default Form;
</code></pre>
<p>Currently, it's rendering like this.
<a href="https://i.stack.imgur.com/6vBcw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6vBcw.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74571879,
"author": "Neha Soni",
"author_id": 11834856,
"author_profile": "https://Stackoverflow.com/users/11834856",
"pm_score": 2,
"selected": true,
"text": "<style scoped>\n>>> ::placeholder {\n color: white !important;\n font-style: italic !important;\n}\n</style>\n"
},
{
"answer_id": 74571936,
"author": "charlycou",
"author_id": 9731186,
"author_profile": "https://Stackoverflow.com/users/9731186",
"pm_score": 0,
"selected": false,
"text": "color v-autocomplete color style style=\"'color:var(--textLightGrey);'\""
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74571547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12566640/"
] |
74,571,584
|
<p>I need a function that splits the string by indexes specified in indexes. Wrong indexes must be ignored.
My code:</p>
<pre><code>def split_by_index(s: str, indexes: List[int]) -> List[str]:
parts = [s[i:j] for i,j in zip(indexes, indexes[1:]+[None])]
return parts
</code></pre>
<p>My strings:</p>
<pre><code>split_by_index("pythoniscool,isn'tit?", [6, 8, 12, 13, 18])
split_by_index("no luck", [42])
</code></pre>
<p>Output:</p>
<pre><code>['is', 'cool', ',', "isn't", 'it?']
['']
</code></pre>
<p>Expected output:</p>
<pre><code>["python", "is", "cool", ",", "isn't", "it?"]
["no luck"]
</code></pre>
<p>Where is my mistake?</p>
|
[
{
"answer_id": 74571879,
"author": "Neha Soni",
"author_id": 11834856,
"author_profile": "https://Stackoverflow.com/users/11834856",
"pm_score": 2,
"selected": true,
"text": "<style scoped>\n>>> ::placeholder {\n color: white !important;\n font-style: italic !important;\n}\n</style>\n"
},
{
"answer_id": 74571936,
"author": "charlycou",
"author_id": 9731186,
"author_profile": "https://Stackoverflow.com/users/9731186",
"pm_score": 0,
"selected": false,
"text": "color v-autocomplete color style style=\"'color:var(--textLightGrey);'\""
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74571584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17986583/"
] |
74,571,588
|
<p>I'm using python to create a 3D surface map, I have an array of data I'm trying to plot as a 3D surface, the issue is that I have logged the Z axis (necessary to show peaks in data) which means the default colormap doesn't work (displays one continous color). I've tried using the LogNorm to normalise the colormap but again this produces one continous color. I'm not sure whether I should be using the logged values to normalise the map, but if i do this the max is negative and produces an error?</p>
<pre><code>fig=plt.figure(figsize=(10,10))
ax=plt.axes(projection='3d')
def log_tick_formatter(val, pos=None):
return "{:.2e}".format(10**val)
ax.zaxis.set_major_formatter(mticker.FuncFormatter(log_tick_formatter))
X=np.arange(0,2,1)
Y=np.arange(0,3,1)
X,Y=np.meshgrid(X,Y)
Z=[[1.2e-11,1.3e-11,-1.8e-11],[6e-13,1.3e-13,2e-15]]
Z_min=np.amin(Z)
Z_max=np.amax(Z)
norm = colors.LogNorm(vmin=1e-15,vmax=(Z_max),clip=False)
ax.plot_surface(X,Y,np.transpose(np.log10(Z)),norm=norm,cmap='rainbow')
</code></pre>
|
[
{
"answer_id": 74571879,
"author": "Neha Soni",
"author_id": 11834856,
"author_profile": "https://Stackoverflow.com/users/11834856",
"pm_score": 2,
"selected": true,
"text": "<style scoped>\n>>> ::placeholder {\n color: white !important;\n font-style: italic !important;\n}\n</style>\n"
},
{
"answer_id": 74571936,
"author": "charlycou",
"author_id": 9731186,
"author_profile": "https://Stackoverflow.com/users/9731186",
"pm_score": 0,
"selected": false,
"text": "color v-autocomplete color style style=\"'color:var(--textLightGrey);'\""
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74571588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12450454/"
] |
74,571,603
|
<p>I have a dataframe like this:</p>
<pre><code>data = {'SalePrice':[10,10,10,20,20,3,3,1,4,8,8],'HandoverDateA':['2022-04-30','2022-04-30','2022-04-30','2022-04-30','2022-04-30','2022-04-30','2022-04-30','2022-04-30','2022-04-30','2022-03-30','2022-03-30'],'ID': ['Tom', 'Tom','Tom','Joseph','Joseph','Ben','Ben','Eden','Tim','Adam','Adam'], 'Tranche': ['Red', 'Red', 'Red', 'Red','Red','Blue','Blue','Red','Red','Red','Red'],'Totals':[100,100,100,50,50,90,90,70,60,70,70],'Sent':['2022-01-18','2022-02-19','2022-03-14','2022-03-14','2022-04-22','2022-03-03','2022-02-07','2022-01-04','2022-01-10','2022-01-15','2022-03-12'],'Amount':[20,10,14,34,15,60,25,10,10,40,20],'Opened':['2021-12-29','2021-12-29','2021-12-29','2022-12-29','2022-12-29','2021-12-19','2021-12-19','2021-12-29','2021-12-29','2021-12-29','2021-12-29']}
</code></pre>
<p>I need to find the sent date which is closest to the HandoverDate. I've seen plenty of examples that work when you give one date to search but here the date I want to be closest to can change for every ID. I have tried to adapt the following:</p>
<pre><code>def nearest(items, pivot):
return min([i for i in items if i <= pivot], key=lambda x: abs(x - pivot))
</code></pre>
<p>And also tried to write a loop where I make a dataframe for each ID and use max on the date column then stick them together, but it's incredibly slow!</p>
<p>Thanks for any suggestions :)</p>
|
[
{
"answer_id": 74571879,
"author": "Neha Soni",
"author_id": 11834856,
"author_profile": "https://Stackoverflow.com/users/11834856",
"pm_score": 2,
"selected": true,
"text": "<style scoped>\n>>> ::placeholder {\n color: white !important;\n font-style: italic !important;\n}\n</style>\n"
},
{
"answer_id": 74571936,
"author": "charlycou",
"author_id": 9731186,
"author_profile": "https://Stackoverflow.com/users/9731186",
"pm_score": 0,
"selected": false,
"text": "color v-autocomplete color style style=\"'color:var(--textLightGrey);'\""
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74571603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5574107/"
] |
74,571,607
|
<p>So I was doing something like this:</p>
<pre><code> Base * pParentPtr
// ... pParentPtr is used
// Cast result pointer
Derived* castedResult = (Derived*)pParentPtr;
// Copy the referenced object to stack object
Derived resultExplicitCopy = Derived(*castedResult);
// run Derived class functions
resultExplicitCopy.DeviredSpecialFunction();
// Free memory allocated by factory
delete pParentPtr;
</code></pre>
<p>Which means that the code uses <code>pParentPtr</code> but at the end we need it to be converted to <code>Derived</code>, then call a function that belongs only to <code>Derived</code> and then delete the initial pointer.</p>
<p>Although this works, the idea is to simplify the code. I thought on creating a contructor for <code>Derived</code> that takes a <code>Base*</code> for input:</p>
<pre><code>Derived::Derived(Base* basePtr)
{
// Cast result pointer
Derived* castedResult = (Derived*)basePtr;
// Copy the referenced object to stack object
Derived resultExplicitCopy = Derived(*castedResult); // This looks bad
// run Derived class functions
resultExplicitCopy.DeviredSpecialFunction();
*this = resultExplicitCopy; // ??? this seems weird and dangerous
}
</code></pre>
<p>Creating a <code>Derived</code> instance inside the constructor seems like a bad idea, also reseting the whole object before it actually exists.</p>
<p>So, is there a way of pasing <code>Base</code>'s pointer to <code>Derived</code>'s constructor and properly building it?</p>
<p>I'd like it to look like this:</p>
<pre><code> Base * pParentPtr
// ... pParentPtr is used
// Init derived with base
derivedInstance = Derived(pParentPtr);
// Free memory allocated by factory
delete pParentPtr;
</code></pre>
|
[
{
"answer_id": 74571879,
"author": "Neha Soni",
"author_id": 11834856,
"author_profile": "https://Stackoverflow.com/users/11834856",
"pm_score": 2,
"selected": true,
"text": "<style scoped>\n>>> ::placeholder {\n color: white !important;\n font-style: italic !important;\n}\n</style>\n"
},
{
"answer_id": 74571936,
"author": "charlycou",
"author_id": 9731186,
"author_profile": "https://Stackoverflow.com/users/9731186",
"pm_score": 0,
"selected": false,
"text": "color v-autocomplete color style style=\"'color:var(--textLightGrey);'\""
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74571607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11261546/"
] |
74,571,608
|
<p>If I have total qty = 100. and it has been shipped in 4 phases line 40, 10, 25, 25 that equals to 100. when I am running this query:</p>
<p>Someone Helped me with this query. I want the same runnable for DB2.</p>
<pre><code>SET totalQty = -1;
SELECT
IF(@totalQty<0, pl.quantity, @totalQty) AS totalQty,
pr.invoiceqty,
@totalQty:=(@totalQty - pr.invoiceqty) AS balance
FROM
purchaseorderline pl, replenishmentrequisition pr
</code></pre>
<p>I am getting result like this :</p>
<pre class="lang-none prettyprint-override"><code>--total qty-- --invoice qty-- --balance qty--
100 40 60
100 10 90
100 25 75
100 25 70
</code></pre>
<p>The result I want :</p>
<pre class="lang-none prettyprint-override"><code>--total qty-- --invoice qty-- --balance qty--
100 40 60
60 10 50
50 25 25
25 25 00
</code></pre>
|
[
{
"answer_id": 74571996,
"author": "Mark Barinstein",
"author_id": 10418264,
"author_profile": "https://Stackoverflow.com/users/10418264",
"pm_score": 1,
"selected": false,
"text": "WITH MYTAB (PHASE_ID, QTY) AS\n(\n-- Your initial data as the result of\n-- your base SELECT statement\nVALUES\n (1, 40)\n, (2, 10)\n, (3, 25)\n, (4, 25)\n)\nSELECT \n QTY + QTY_TOT - QTY_RTOT AS \"total qty\"\n, QTY AS \"invoice qty\"\n, QTY_TOT - QTY_RTOT AS \"balance qty\"\nFROM \n(\n SELECT \n PHASE_ID\n , QTY\n -- Running total sum\n , SUM (QTY) OVER (ORDER BY PHASE_ID) AS QTY_RTOT\n -- Total sum\n , SUM (QTY) OVER () AS QTY_TOT\n FROM MYTAB\n)\nORDER BY PHASE_ID\n"
},
{
"answer_id": 74580389,
"author": "Lennart - Slava Ukraini",
"author_id": 3592396,
"author_profile": "https://Stackoverflow.com/users/3592396",
"pm_score": 0,
"selected": false,
"text": "WITH MYTAB (PHASE_ID, QTY) AS\n(\n -- Your initial data as the result of\n -- your base SELECT statement\n VALUES (1, 40)\n , (2, 10)\n , (3, 25)\n , (4, 25)\n)\nSELECT QTY_TOT AS \"total qty\"\n , QTY AS \"invoice qty\"\n , coalesce(lead(QTY_TOT) over (order by phase_id),0) AS \"balance qty\"\nFROM \n( SELECT PHASE_ID\n , QTY\n -- Running total sum\n , SUM (QTY) OVER (ORDER BY PHASE_ID desc) AS qty_tot\n FROM MYTAB\n)\nORDER BY PHASE_ID\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74571608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20212658/"
] |
74,571,611
|
<p>I have a Class like this that I want to serialize and deserialize</p>
<pre><code>using Newtonsoft.Json;
TestClass testClass = new TestClass();
testClass.Foo = "Foo";
testClass.Bar[0] = 3;
// to JSON
string json = JsonConvert.SerializeObject(testClass);
// and back
TestClass result = JsonConvert.DeserializeObject<TestClass>(json)!;
/// <summary>
/// External class that I cannot change
/// </summary>
public class TestClass
{
public string Foo { get; set; }
public int[] Bar { get; } = new int[3];
}
</code></pre>
<p>Serializing works well, but at deserializing "Bar" is not writeable, so skipped and has default values.
Is there a way to tell Json.net to deserialize element by element of the (maybe reaonly arrays?) array and set it as value for the corresponding array index?</p>
|
[
{
"answer_id": 74571996,
"author": "Mark Barinstein",
"author_id": 10418264,
"author_profile": "https://Stackoverflow.com/users/10418264",
"pm_score": 1,
"selected": false,
"text": "WITH MYTAB (PHASE_ID, QTY) AS\n(\n-- Your initial data as the result of\n-- your base SELECT statement\nVALUES\n (1, 40)\n, (2, 10)\n, (3, 25)\n, (4, 25)\n)\nSELECT \n QTY + QTY_TOT - QTY_RTOT AS \"total qty\"\n, QTY AS \"invoice qty\"\n, QTY_TOT - QTY_RTOT AS \"balance qty\"\nFROM \n(\n SELECT \n PHASE_ID\n , QTY\n -- Running total sum\n , SUM (QTY) OVER (ORDER BY PHASE_ID) AS QTY_RTOT\n -- Total sum\n , SUM (QTY) OVER () AS QTY_TOT\n FROM MYTAB\n)\nORDER BY PHASE_ID\n"
},
{
"answer_id": 74580389,
"author": "Lennart - Slava Ukraini",
"author_id": 3592396,
"author_profile": "https://Stackoverflow.com/users/3592396",
"pm_score": 0,
"selected": false,
"text": "WITH MYTAB (PHASE_ID, QTY) AS\n(\n -- Your initial data as the result of\n -- your base SELECT statement\n VALUES (1, 40)\n , (2, 10)\n , (3, 25)\n , (4, 25)\n)\nSELECT QTY_TOT AS \"total qty\"\n , QTY AS \"invoice qty\"\n , coalesce(lead(QTY_TOT) over (order by phase_id),0) AS \"balance qty\"\nFROM \n( SELECT PHASE_ID\n , QTY\n -- Running total sum\n , SUM (QTY) OVER (ORDER BY PHASE_ID desc) AS qty_tot\n FROM MYTAB\n)\nORDER BY PHASE_ID\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74571611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12107765/"
] |
74,571,624
|
<p>So basically I have this list in code</p>
<pre><code>list_names = [
{"name":"Jullemyth","seat_number":4,"category":"Student"},
{"name":"Leonhard","seat_number":1,"category":"OFW"},
{"name":"Scarion","seat_number":3,"category":"Businessman"},
{"name":"Jaguar","seat_number":2,"category":"Animal Manager"},
{"name":"Cutiepie","seat_number":10,"category":"Streamer"},
{"name":"Hannah Bee","seat_number":11,"category":"Streamer"}
]
</code></pre>
<p>I was thinking I could print only all the names by this</p>
<pre><code>print(list_names[:]["name"])
</code></pre>
<p>but it doesn't work...how can I do that? I just want to get all the list of names in dict. Is that possible or not? without using loops.</p>
|
[
{
"answer_id": 74571648,
"author": "charon25",
"author_id": 16114044,
"author_profile": "https://Stackoverflow.com/users/16114044",
"pm_score": 2,
"selected": false,
"text": "print([lst[\"name\"] for lst in list_names])\n"
},
{
"answer_id": 74571955,
"author": "Alibederchi ",
"author_id": 20598580,
"author_profile": "https://Stackoverflow.com/users/20598580",
"pm_score": 0,
"selected": false,
"text": "for name in [D['name'] for D in list_names]:\n print(name)\n"
},
{
"answer_id": 74572924,
"author": "Yaman Jain",
"author_id": 2756517,
"author_profile": "https://Stackoverflow.com/users/2756517",
"pm_score": 0,
"selected": false,
"text": "itemgetter operator import operator\n\nlist_names = [\n {\"name\":\"Jullemyth\",\"seat_number\":4,\"category\":\"Student\"},\n {\"name\":\"Leonhard\",\"seat_number\":1,\"category\":\"OFW\"},\n {\"name\":\"Scarion\",\"seat_number\":3,\"category\":\"Businessman\"},\n {\"name\":\"Jaguar\",\"seat_number\":2,\"category\":\"Animal Manager\"},\n {\"name\":\"Cutiepie\",\"seat_number\":10,\"category\":\"Streamer\"},\n {\"name\":\"Hannah Bee\",\"seat_number\":11,\"category\":\"Streamer\"}\n]\n\noutput_names = list(map(operator.itemgetter('name'), list_names))\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74571624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14811688/"
] |
74,571,636
|
<p>I am new to PHP and I want to refresh the HTML table when I insert a list of data using the SQL command in XAMPP.</p>
<blockquote>
<p>This is the <code>index.php</code> that displays fetches data from the database and display it in the table.</p>
</blockquote>
<pre><code>`<?php
include("connect_db.php");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
table,tr,th,td{
border: 1px solid black;
border-collapse: collapse;
}
table{
width: 60%;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<th> Data User Id </th>
<th> Date </th>
<th> Time</th>
</tr>
</thead>
<?php
$result = mysqli_query($conn, "SELECT * FROM data_table WHERE data_user_id = 1001 ORDER BY data_id DESC");
while ($res = mysqli_fetch_array($result)){
echo "<tr >";
echo "<td >".$res['data_user_id']."</td>";
echo "<td >".$res['data_date']."</td>";
echo "<td>".$res['data_times']."</td>";
echo "</tr>";
}
?>
</table>
</body>
</html>`
</code></pre>
<blockquote>
<p>Create connection to database. connect_db.php</p>
</blockquote>
<pre><code><?php
$server_name = "localhost";
$username = "root";
$password = "";
$database = "user_db";
$path = $_SERVER['DOCUMENT_ROOT'];
$conn = new mysqli($server_name,$username,$password,$database);
if (!$conn){
die ('Connection Failed: '.mysqli_connect_error());
}
?>
</code></pre>
<blockquote>
<p>And it display like this. I want to refresh the table data without reloading or click button when I add a list of data using SQL command in XAMPP. I saw a lot reference from the internet that uses AJAX and JQUERY but most of them uses buttons. I humbly request for your help and code reference . Thank you</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/BNKbl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BNKbl.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74571648,
"author": "charon25",
"author_id": 16114044,
"author_profile": "https://Stackoverflow.com/users/16114044",
"pm_score": 2,
"selected": false,
"text": "print([lst[\"name\"] for lst in list_names])\n"
},
{
"answer_id": 74571955,
"author": "Alibederchi ",
"author_id": 20598580,
"author_profile": "https://Stackoverflow.com/users/20598580",
"pm_score": 0,
"selected": false,
"text": "for name in [D['name'] for D in list_names]:\n print(name)\n"
},
{
"answer_id": 74572924,
"author": "Yaman Jain",
"author_id": 2756517,
"author_profile": "https://Stackoverflow.com/users/2756517",
"pm_score": 0,
"selected": false,
"text": "itemgetter operator import operator\n\nlist_names = [\n {\"name\":\"Jullemyth\",\"seat_number\":4,\"category\":\"Student\"},\n {\"name\":\"Leonhard\",\"seat_number\":1,\"category\":\"OFW\"},\n {\"name\":\"Scarion\",\"seat_number\":3,\"category\":\"Businessman\"},\n {\"name\":\"Jaguar\",\"seat_number\":2,\"category\":\"Animal Manager\"},\n {\"name\":\"Cutiepie\",\"seat_number\":10,\"category\":\"Streamer\"},\n {\"name\":\"Hannah Bee\",\"seat_number\":11,\"category\":\"Streamer\"}\n]\n\noutput_names = list(map(operator.itemgetter('name'), list_names))\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74571636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15772809/"
] |
74,571,665
|
<p>Why can't I add null in the list of model data arrays in Kotlin language?</p>
<p><a href="https://i.stack.imgur.com/HIIMB.png" rel="nofollow noreferrer">enter image description here</a></p>
<pre><code>adapterPaging!!.setOnLoadMoreListener {
var customersModels: List<CustomersModel> = ArrayList()
customersModels.add(null)
}
</code></pre>
|
[
{
"answer_id": 74572410,
"author": "cactustictacs",
"author_id": 13598222,
"author_profile": "https://Stackoverflow.com/users/13598222",
"pm_score": 2,
"selected": true,
"text": "var customersModels: List<CustomersModel> = ArrayList()\n customersModels List add MutableList ArrayList add ArrayList is List customersModels List MutableList List add // or 'as ArrayList' if you really need to be that specific for some reason - you probably don't\n(customersModels as MutableList).add(thing)\n // confirm the object's type - this will result in a 'smart cast' because the compiler\n// can see that you're handling it safely, so it basically allows you to treat\n// myList as that type\nif (myList is MutableList) myList.add(thing)\n\n// same deal but you can cast with a null fallback if it fails, then null-check the result\n(myList as? MutableList)?.add(thing)\n // MutableList, since you want to mutate it by adding stuff\nvar customersModels: MutableList<CustomersModel> = ArrayList()\ncustomersModels.add(null)\n MutableList customersModels List MutableList LiveData private val _myData = MutableLiveData<String>(\"hi\")\nval myData: LiveData<String> = _myData\n myData MutableLiveData LiveData MutableLiveData List MutableList ArrayList List MutableList val numbers = List(5) { it + 1 }\nval greetings = mutableListOf(\"hi\", \"hey\", \"sup\")\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74571665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15346902/"
] |
74,571,696
|
<p>I have a outlook plugin that add custom categories to outlook when add-in startup completes.</p>
<pre><code> public void CreateCategories()
{
RDOCategories categories = null;
RDOCategory category = null;
try
{
var customCategoryList = FileManager.GetCustomCategoryList();
categories = rSession.Categories;
// add category
foreach (var customCategory in customCategoryList)
{
try
{
category = categories.Add(customCategory.Name
, PaintHelper.GetHexCodeByColorName(customCategory.Color));
}
catch (Exception ex)
{
}
finally
{
if (category != null)
{
Marshal.ReleaseComObject(category);
}
}
}
}
catch (Exception ex)
{
}
finally
{
if (categories != null)
{
Marshal.ReleaseComObject(categories);
}
}
}
</code></pre>
<p>when I delete all categories from outlook and try to run the plugin still it shows count of <strong>rSession.categories</strong> as 6 and it adds all default 6 categories along with the custom categories.</p>
<p>Can we omit adding default categories when all outlook categories are deleted.</p>
|
[
{
"answer_id": 74572410,
"author": "cactustictacs",
"author_id": 13598222,
"author_profile": "https://Stackoverflow.com/users/13598222",
"pm_score": 2,
"selected": true,
"text": "var customersModels: List<CustomersModel> = ArrayList()\n customersModels List add MutableList ArrayList add ArrayList is List customersModels List MutableList List add // or 'as ArrayList' if you really need to be that specific for some reason - you probably don't\n(customersModels as MutableList).add(thing)\n // confirm the object's type - this will result in a 'smart cast' because the compiler\n// can see that you're handling it safely, so it basically allows you to treat\n// myList as that type\nif (myList is MutableList) myList.add(thing)\n\n// same deal but you can cast with a null fallback if it fails, then null-check the result\n(myList as? MutableList)?.add(thing)\n // MutableList, since you want to mutate it by adding stuff\nvar customersModels: MutableList<CustomersModel> = ArrayList()\ncustomersModels.add(null)\n MutableList customersModels List MutableList LiveData private val _myData = MutableLiveData<String>(\"hi\")\nval myData: LiveData<String> = _myData\n myData MutableLiveData LiveData MutableLiveData List MutableList ArrayList List MutableList val numbers = List(5) { it + 1 }\nval greetings = mutableListOf(\"hi\", \"hey\", \"sup\")\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74571696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6611760/"
] |
74,571,705
|
<p>I'm building an interactive widget that consists in making a button list out of a list of HTML markups. To achieve that, the HTML markup is wrapped with a button-like component <code><div role="button" tabindex="0" aria-label="Action..."></code>. When clicking on the button, some script is executed.</p>
<p>I don't have control over that child HTML markup, and I want to prevent all other interactive elements from being interacted with. They should stay visible, though.</p>
<p>From the point of view of a mouse user, this can be achieved by setting <code>pointer-events: none;</code> on all child elements.</p>
<p>From the point of view of a keyboard user, I need a way to prevent interactive elements from being interacted with.</p>
<p>In this example, the focus should go from the first div with tabindex="0" to the second div with tabindex="0", without focusing on the <code><a></code> tag.</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>.focusable {
border: 1px solid blue;
margin: 10px;
padding: 10px;
}
.focusable > * {
pointer-events: none;
}
.focusable:hover {
background-color: lightgrey;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div role="button" tabindex="0" class="focusable" aria-label="Action 0">
<div>Some html markup
<a href="#">Should not be focusable, but should be visible</a>
</div>
</div>
<div role="button" tabindex="0" class="focusable" aria-label="Action 1">
<div>Some html markup
<input type="text" placeholder="should not be focusable" />
</div>
</div></code></pre>
</div>
</div>
</p>
<p>One way I thought of achieving that is to set <code>tabindex="-1"</code> on the child interactive elements. It will remove those from the tab order. However, it will not prevent them from being accessed programmatically, for example, from a screen reader links menu.</p>
<p>I wondered if there are other techniques to make all child elements of an element non-interactive. Especially something that can be applied on a wrapper, so there is no need to find all interactive elements and replace them.</p>
|
[
{
"answer_id": 74599481,
"author": "Andy",
"author_id": 608042,
"author_profile": "https://Stackoverflow.com/users/608042",
"pm_score": 2,
"selected": false,
"text": "<button aria-label=\"Label text … additional text\">\n <div inert>\n …\n <a tabindex=\"-1\"\n aria-hidden=\"true\"\n style=\"pointer-events: none\">\n …\n role=\"presentation\" role=\"none\" aria-hidden aria-label aria-label inert tabindex=\"-1\" document.querySelectorAll('button *').forEach(n => {\n n.setAttribute('inert', '');\n n.setAttribute('tabindex', '-1');\n n.setAttribute('aria-hidden', '')\n}); button * {\n pointer-events: none;\n} <button>\n This should not be <a href=\"#\" onclick=\"alert('damn, it‘s still a link')\">a link</a>\n</button>"
},
{
"answer_id": 74625920,
"author": "neiya",
"author_id": 5548351,
"author_profile": "https://Stackoverflow.com/users/5548351",
"pm_score": 1,
"selected": true,
"text": "<div role=\"button\"> aria-hidden=\"true\" tabindex=\"-1\" pointer-events: 'none'"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74571705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5548351/"
] |
74,571,722
|
<p>Is there an algorithm similar to the bloom filter, that allows you to:</p>
<ol>
<li>Compactly represent two (large) sets independently of each other and</li>
<li>probabilistically check for disjointness between them using their lossy-compressed representations?</li>
</ol>
<p>In the special case where one set only has a single same and you don't compress it, this problem reduces to probablistic set membership, for which one can consider the Bloom filter.</p>
|
[
{
"answer_id": 74599481,
"author": "Andy",
"author_id": 608042,
"author_profile": "https://Stackoverflow.com/users/608042",
"pm_score": 2,
"selected": false,
"text": "<button aria-label=\"Label text … additional text\">\n <div inert>\n …\n <a tabindex=\"-1\"\n aria-hidden=\"true\"\n style=\"pointer-events: none\">\n …\n role=\"presentation\" role=\"none\" aria-hidden aria-label aria-label inert tabindex=\"-1\" document.querySelectorAll('button *').forEach(n => {\n n.setAttribute('inert', '');\n n.setAttribute('tabindex', '-1');\n n.setAttribute('aria-hidden', '')\n}); button * {\n pointer-events: none;\n} <button>\n This should not be <a href=\"#\" onclick=\"alert('damn, it‘s still a link')\">a link</a>\n</button>"
},
{
"answer_id": 74625920,
"author": "neiya",
"author_id": 5548351,
"author_profile": "https://Stackoverflow.com/users/5548351",
"pm_score": 1,
"selected": true,
"text": "<div role=\"button\"> aria-hidden=\"true\" tabindex=\"-1\" pointer-events: 'none'"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74571722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/139802/"
] |
74,571,736
|
<p>I usually checked this with the following code:</p>
<pre><code>$email = '/[^@:="\'\s]*@[^@\s]*\.[a-z]+/iU';
if(preg_match($email,$article->text) == true) {
to something
}
</code></pre>
<p>In PHP 8 this is deprecated (Works, but with warning), because I can't always guarantee that there really is an email in it.</p>
<blockquote>
<p>Passing null to parameter #2 ($subject) of type string is deprecated</p>
</blockquote>
<p>What are the alternatives?</p>
<p>I know that this solution still works, but I want to be fit for the future.</p>
<p>When searching, I did not find a solution. "str_contains" seems to allow only one string.</p>
|
[
{
"answer_id": 74572452,
"author": "Álvaro González",
"author_id": 13508,
"author_profile": "https://Stackoverflow.com/users/13508",
"pm_score": 2,
"selected": false,
"text": "declare(strict_types=1);\n if ($article->text !== null && preg_match($email, $article->text)) {\n}\n if (preg_match($email, $article->text ?? '')) {\n}\n"
},
{
"answer_id": 74573244,
"author": "Gratia-Mira",
"author_id": 19270976,
"author_profile": "https://Stackoverflow.com/users/19270976",
"pm_score": 0,
"selected": false,
"text": "$email = '/[^@:=\"\\'\\s]*@[^@\\s]*\\.[a-z]+/iU';\nif($article->text AND preg_match($email,$article->text) == true) {\n to something\n}\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74571736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19270976/"
] |
74,571,751
|
<p>Below code snippet gives error. Can someone guide why this is happening?</p>
<pre><code>class Test() private constructor {
constructor(name: String): this() {
println("test called constructor $name")
}
}
fun main() {
Test("hk")
}
</code></pre>
<p>Removing private constructor , this is working.</p>
<p>I tried to resolve this on my side. but I got no success.</p>
<p>I am getting this error: <code>Expecting a top level declaration Expecting a top level declaration Function declaration must have a name Unresolved reference: constructor Unresolved reference: name Unexpected type specification Unexpected tokens (use ';' to separate expressions on the same line) Unresolved reference: name</code></p>
|
[
{
"answer_id": 74571845,
"author": "Sunny",
"author_id": 909317,
"author_profile": "https://Stackoverflow.com/users/909317",
"pm_score": 2,
"selected": true,
"text": "class Test private constructor() {\n\n constructor(name: String): this() {\n println(\"test called constructor $name\")\n }\n\n}\n\nfun main() {\n Test(\"hk\")\n}\n"
},
{
"answer_id": 74571903,
"author": "cactustictacs",
"author_id": 13598222,
"author_profile": "https://Stackoverflow.com/users/13598222",
"pm_score": 2,
"selected": false,
"text": "() Test Test constructor() constructor constructor() private class Test private constructor()\n"
},
{
"answer_id": 74571912,
"author": "Thankgod Richard",
"author_id": 5065783,
"author_profile": "https://Stackoverflow.com/users/5065783",
"pm_score": 1,
"selected": false,
"text": "class Test{\n\n private constructor(){}\n\n constructor(name: String): this() {\n println(\"test called constructor $name\")\n }\n}\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74571751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8547203/"
] |
74,571,757
|
<pre><code>new Thread(() -> {
while (true){
Scanner sc = new Scanner(System.in);
StringBuilder builder = new StringBuilder();
System.out.println("请输入要输出的文本:");
while (sc.hasNextLine()) {
builder.append(sc.nextLine());
}
System.out.println(builder.toString());
}
}).start();
</code></pre>
<p>I wanted to keep typing in a thread, but when I printed the string for the first time, the program didn't work the way I expected.as follows
<a href="https://i.stack.imgur.com/pg1EP.png" rel="nofollow noreferrer">enter image description here</a>
The program kept repeating, but it didn't stop for me to input.
Can you help me with this problem?</p>
<p>I tried to change the terminator of the input stream with an overloaded method about hasNext().</p>
<pre><code>new Thread(() -> {
while (true){
Scanner sc = new Scanner(System.in);
StringBuilder builder = new StringBuilder();
System.out.println("enter text information:");
while (!sc.hasNext("#")) {
builder.append(sc.nextLine());
}
System.out.println(builder.toString());
}
}).start();
</code></pre>
<p>The results of this code are consistent with my goals,but I don't want to use another terminator instead of the default terminator. What should I do?
Please help me thank you!</p>
|
[
{
"answer_id": 74571845,
"author": "Sunny",
"author_id": 909317,
"author_profile": "https://Stackoverflow.com/users/909317",
"pm_score": 2,
"selected": true,
"text": "class Test private constructor() {\n\n constructor(name: String): this() {\n println(\"test called constructor $name\")\n }\n\n}\n\nfun main() {\n Test(\"hk\")\n}\n"
},
{
"answer_id": 74571903,
"author": "cactustictacs",
"author_id": 13598222,
"author_profile": "https://Stackoverflow.com/users/13598222",
"pm_score": 2,
"selected": false,
"text": "() Test Test constructor() constructor constructor() private class Test private constructor()\n"
},
{
"answer_id": 74571912,
"author": "Thankgod Richard",
"author_id": 5065783,
"author_profile": "https://Stackoverflow.com/users/5065783",
"pm_score": 1,
"selected": false,
"text": "class Test{\n\n private constructor(){}\n\n constructor(name: String): this() {\n println(\"test called constructor $name\")\n }\n}\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74571757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16214891/"
] |
74,571,765
|
<p>i have a csv file which has a column named 'jsonColumn'. below is a sample data.</p>
<pre><code>jsonColumn
{"page":"mainpage","_timestamp":"2022-11-22T10:47:45.8060+01:00","object":"object1","destination":"destination1","subObject":"subObject1","type":"event"}
...
</code></pre>
<p>now i want to extract several fields from the jsonColumn, the expected result is</p>
<pre><code>_timestamp,page,object,subObject
2022-11-22T10:47:45.8060+01:00,mainpage,object1,subObject1
...
</code></pre>
<p>Here is the code i used, but the why all the extracted fields' value are null?</p>
<pre><code>%python
from pyspark.sql import SparkSession
from pyspark.sql.functions import get_json_object
spark=SparkSession.builder.appName('practice').getOrCreate()
df2 = spark.read.csv('/FileStore/test1.csv', header=True)
df2_extractJSON = df2.withColumn("_timestamp", get_json_object(df2.jsonColumn, "$._timestamp"))\
.withColumn("page", get_json_object(df2.jsonColumn, "$.page"))\
.withColumn("object", get_json_object(df2.jsonColumn, "$.object"))\
.withColumn("subObject", get_json_object(df2.jsonColumn, "$.subObject"))
df2_extractJSON.show()
</code></pre>
<p>The result are all null.</p>
<p><a href="https://i.stack.imgur.com/XCn4N.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XCn4N.png" alt="enter image description here" /></a></p>
<p>original dataframe is not empty. Please refer to jsonColumn in below screenshot, it's not empty.
<a href="https://i.stack.imgur.com/XCn4N.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XCn4N.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74571845,
"author": "Sunny",
"author_id": 909317,
"author_profile": "https://Stackoverflow.com/users/909317",
"pm_score": 2,
"selected": true,
"text": "class Test private constructor() {\n\n constructor(name: String): this() {\n println(\"test called constructor $name\")\n }\n\n}\n\nfun main() {\n Test(\"hk\")\n}\n"
},
{
"answer_id": 74571903,
"author": "cactustictacs",
"author_id": 13598222,
"author_profile": "https://Stackoverflow.com/users/13598222",
"pm_score": 2,
"selected": false,
"text": "() Test Test constructor() constructor constructor() private class Test private constructor()\n"
},
{
"answer_id": 74571912,
"author": "Thankgod Richard",
"author_id": 5065783,
"author_profile": "https://Stackoverflow.com/users/5065783",
"pm_score": 1,
"selected": false,
"text": "class Test{\n\n private constructor(){}\n\n constructor(name: String): this() {\n println(\"test called constructor $name\")\n }\n}\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74571765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11960929/"
] |
74,571,787
|
<p>I would want to generate a new object type having only the properties of another Object that matches the requested types.
Like Pick do, but specifying the types and not the property names.</p>
<p>For example:</p>
<pre><code>interface A {
a: string;
b: number;
c: string[];
d: { [key: string]: never };
}
</code></pre>
<pre><code>interface B extends PickPropertyTypes<A, string | number>{}
</code></pre>
<p>The interface B should have only the properties <strong>a: string</strong> and <strong>b: number</strong> resulting in an interface like</p>
<pre><code>{
a: string;
b: number;
}
</code></pre>
<p>Is it possible?</p>
<p>Thanks</p>
|
[
{
"answer_id": 74571970,
"author": "Dimava",
"author_id": 5734961,
"author_profile": "https://Stackoverflow.com/users/5734961",
"pm_score": 2,
"selected": false,
"text": "interface A {\n a: string;\n b: number;\n c: string[];\n d: { [key: string]: never };\n}\n\ntype PickPropertyTypes<T, V> = {\n [K in keyof T as T[K] extends V ? K : never] : T[K]\n}\n\ntype B = PickPropertyTypes<A, string | number>\n// ^?\n"
},
{
"answer_id": 74572387,
"author": "Wiktor Zychla",
"author_id": 941240,
"author_profile": "https://Stackoverflow.com/users/941240",
"pm_score": 2,
"selected": true,
"text": "interface A {\n a: string;\n b: number;\n c: string[];\n d: { [key: string]: never };\n}\n\ntype ExtractPropertyTypes<T, U> = { [K in keyof T]: T[K] extends U ? K : never; }[keyof T]\ntype PickPropertyTypes<T, V> = { [K in ExtractPropertyTypes<T, V>]: T[K] }\n\ntype Test = PickPropertyTypes<A, string | number>\n Pick Extract Omit Exclude"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74571787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1335141/"
] |
74,571,792
|
<p>Here is my snippet:</p>
<pre><code>core = client.CoreV1Api()
apps = client.AppsV1Api()
def get_pod_parent(resource, tmp):
if resource.metadata.owner_references:
parrent = eval(f"apps.read_namespaced_{re.sub(r'(?<!^)(?=[A-Z])', '_', resource.metadata.owner_references[0].kind).lower()}")(
resource.metadata.owner_references[0].name,
resource.metadata.namespace
)
get_pod_parent(parrent, tmp)
else:
#print(resource) it prints the resource which I need to take
tmp = resource #Local variable 'tmp' value is not used
pod = core.read_namespaced_pod('test_name', 'test_namespace')
last_parrent = None
test = get_pod_parent(pod, last_parrent)
print(last_parrent) # It prints None
</code></pre>
<p>Why does it print <code>None</code>? I can't understand! I need to store the resource when it gets into the else. The resource is there, but I cant store it somehow. Is there someone who can explain what is going on and how can I take the needed resource outside of the function?</p>
|
[
{
"answer_id": 74571876,
"author": "K-D-G",
"author_id": 9836388,
"author_profile": "https://Stackoverflow.com/users/9836388",
"pm_score": 1,
"selected": false,
"text": "return resource\n"
},
{
"answer_id": 74572411,
"author": "htodev",
"author_id": 12798744,
"author_profile": "https://Stackoverflow.com/users/12798744",
"pm_score": 0,
"selected": false,
"text": "def get_pod_parent(resource, store):\nif resource.metadata.owner_references:\n parrent = eval(\n f\"apps.read_namespaced_{re.sub(r'(?<!^)(?=[A-Z])', '_', resource.metadata.owner_references[0].kind).lower()}\")(\n resource.metadata.owner_references[0].name,\n resource.metadata.namespace\n\n )\n get_pod_parent(parrent, store)\nelse:\n store.update({'name': resource.metadata.name, 'namespace': resource.metadata.name})\npod = core.read_namespaced_pod('test_name', 'test_namespace')\nstore = {}\nget_pod_parent(pod, store)\nprint(store) \n store"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74571792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12798744/"
] |
74,571,795
|
<p>It was working fine, but it stopped working.</p>
<pre><code>const SearchBar = ({ carddata}) => {
let arr = [];
function searchResult(e) {
if (e.key === "Enter") {
if (e.target.value === "") return;
arr = [];
carddata.filter((result) => {
if (`${result.heading}`.toLowerCase().match(e.target.value)) {
arr.push(result);
console.log(arr)
}
});
}
}
return (
<div className="flex">
<input
onKeyDown={searchResult}
className="search-input w-100 br bb fw4"
type="text"
placeholder="Search here..."
></input>
<SearchIcon
className="search-icon h2 br bb hover-black"
style={{ fill: "red" }}
sx={{ fontSize: 40 }}
/>
</div>
);
};
export default SearchBar;
</code></pre>
|
[
{
"answer_id": 74571857,
"author": "Mohammed Shahed",
"author_id": 19067773,
"author_profile": "https://Stackoverflow.com/users/19067773",
"pm_score": 0,
"selected": false,
"text": "value input <input\nvalue={somestate}\nonChange={e=> setState(e.target.value)}\n/>\n"
},
{
"answer_id": 74571924,
"author": "exphoenee",
"author_id": 13804256,
"author_profile": "https://Stackoverflow.com/users/13804256",
"pm_score": -1,
"selected": false,
"text": "import React, {useState, useEffect} from \"react\";\n\nconst SearchBar = ({ carddata}) => {\n const [searchValue, setSearchValue]\n\n let arr = [];\n \n useEffect()=>{\n function searchResult() {\n if (e.key === \"Enter\") {\n if (searchValue === \"\") return;\n arr = [];\n carddata.filter((result) => {\n if (`${result.heading}`.toLowerCase().match(e.target.value)) {\n arr.push(result);\n console.log(arr)\n }\n });\n }\n }, [searchValue]\n }\n\n return (\n <div className=\"flex\">\n <input\n onChange={e=>setSearchValue(e.target.value)}\n className=\"search-input w-100 br bb fw4\"\n type=\"text\"\n placeholder=\"Search here...\"\n value=\"searchValue\"\n />\n\n <SearchIcon\n className=\"search-icon h2 br bb hover-black\"\n style={{ fill: \"red\" }}\n sx={{ fontSize: 40 }}\n />\n </div>\n );\n};\n\nexport default SearchBar; <script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js\"></script>"
},
{
"answer_id": 74574302,
"author": "David manga",
"author_id": 19226647,
"author_profile": "https://Stackoverflow.com/users/19226647",
"pm_score": 0,
"selected": false,
"text": "onKeyDown <input\n onKeyDown={(e)=>searchResult(e)}\n className=\"search-input w-100 br bb fw4\"\n type=\"text\"\n placeholder=\"Search here...\"\n ></input>\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74571795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20393875/"
] |
74,571,800
|
<p>My react app won't be <strong>public</strong>, It will be called by some other application(rails application with redirect_to) that is written in another programming language(ruby on rails).</p>
<p>To launch my react app, I want post requests to be used and they will redirect to my react application.</p>
<p>That's by I added a simple HTML form that will send a post request to my react app. Finally, the user will be redirected to my react application.</p>
<p>The reason I am going to use the post method is I can use get because it will contain tokens and other useful information which should not be in the get method URL.</p>
<p>Thanks in advance, Please suggest here...!</p>
<p>I am trying to find a way that will load the react application and provide sensitive information like token in safer way(not in URL)</p>
|
[
{
"answer_id": 74571857,
"author": "Mohammed Shahed",
"author_id": 19067773,
"author_profile": "https://Stackoverflow.com/users/19067773",
"pm_score": 0,
"selected": false,
"text": "value input <input\nvalue={somestate}\nonChange={e=> setState(e.target.value)}\n/>\n"
},
{
"answer_id": 74571924,
"author": "exphoenee",
"author_id": 13804256,
"author_profile": "https://Stackoverflow.com/users/13804256",
"pm_score": -1,
"selected": false,
"text": "import React, {useState, useEffect} from \"react\";\n\nconst SearchBar = ({ carddata}) => {\n const [searchValue, setSearchValue]\n\n let arr = [];\n \n useEffect()=>{\n function searchResult() {\n if (e.key === \"Enter\") {\n if (searchValue === \"\") return;\n arr = [];\n carddata.filter((result) => {\n if (`${result.heading}`.toLowerCase().match(e.target.value)) {\n arr.push(result);\n console.log(arr)\n }\n });\n }\n }, [searchValue]\n }\n\n return (\n <div className=\"flex\">\n <input\n onChange={e=>setSearchValue(e.target.value)}\n className=\"search-input w-100 br bb fw4\"\n type=\"text\"\n placeholder=\"Search here...\"\n value=\"searchValue\"\n />\n\n <SearchIcon\n className=\"search-icon h2 br bb hover-black\"\n style={{ fill: \"red\" }}\n sx={{ fontSize: 40 }}\n />\n </div>\n );\n};\n\nexport default SearchBar; <script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js\"></script>"
},
{
"answer_id": 74574302,
"author": "David manga",
"author_id": 19226647,
"author_profile": "https://Stackoverflow.com/users/19226647",
"pm_score": 0,
"selected": false,
"text": "onKeyDown <input\n onKeyDown={(e)=>searchResult(e)}\n className=\"search-input w-100 br bb fw4\"\n type=\"text\"\n placeholder=\"Search here...\"\n ></input>\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74571800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20569884/"
] |
74,571,815
|
<p>Consider the following code (<a href="https://godbolt.org/z/6cYq8Mhqd" rel="nofollow noreferrer">godbolt</a>):</p>
<pre><code>#include <optional>
#include <array>
struct LargeType {
std::array<int, 256> largeContents;
};
LargeType doSomething();
std::optional<LargeType> wrapIntoOptional(){
return std::optional<LargeType> {doSomething()};
}
</code></pre>
<p>As you see, there is a function returning a large POD and then a function wrapping it into a <code>std::optional</code>. As visible in godbolt, the compiler creates a <code>memcpy</code> here, so it cannot fully elide moving the object. Why is this?</p>
<p>If I understand it correctly, the C++ language would allow eliding the move due to the as-if rule, as there are no visible side effects to it. So it seems that the compiler really cannot avoid it. But why?</p>
<p>My (probably incorrect) understanding how the compiler could optimize the <code>memcpy</code> out is to hand a reference to the storage inside the optional to <code>doSomething()</code> (as I guess such large objects get passed by hidden reference anyway). The optional itself would already lie on the stack of the caller of <code>wrapIntoOptional</code> due to RVO. As the definition of the constructor of <code>std::optional</code> is in the header, it is available to the compiler, so it should be able to inline it, so it can hand that storage location to <code>doSomething</code> in the first place. So what's wrong about my intuition here?</p>
<p>To clarify: I don't argue that the C++ language requires the compiler to inline this. I just thought it would be a reasonable optimization and given that wrapping things into optionals is a common operation, it would be an optimization that is implemented in modern compilers.</p>
|
[
{
"answer_id": 74571899,
"author": "user17732522",
"author_id": 17732522,
"author_profile": "https://Stackoverflow.com/users/17732522",
"pm_score": 3,
"selected": false,
"text": "doSomething()"
},
{
"answer_id": 74572802,
"author": "smitsyn",
"author_id": 11158992,
"author_profile": "https://Stackoverflow.com/users/11158992",
"pm_score": 2,
"selected": false,
"text": "noexcept"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74571815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1408611/"
] |
74,571,817
|
<p>I have a dataset in excel with multiple columns that contain one specific set of data that is randomly distributed within these columns. The data looks like this:</p>
<pre><code>Col1 Col2 Col3 Col4 Col5 Col6
Data 34 NA NA NA NA
NA NA Data 32 NA NA
NA NA NA NA Data 12
NA Data 89 NA NA NA
</code></pre>
<p>I want to get all the <code>Data</code> fields into one column named data, so the data set looks like this (the <code>NA</code> columns are not important for now, I have this issue with several fields, so I will need to replicate the solution for other fields as well):</p>
<pre><code>Data
34
32
12
89
</code></pre>
<p>As I am currently working in excel, an easy solution there would be great, however, I will move to R at some point, so a solution in R would also be welcomed!</p>
<p>Thank you very much and sorry for the cryptic description.</p>
<p>Edit: Here is a picture of my real data - in this example I want a column named "Total supply", one named "Ticker" and one named "Accepted Currencies", with the respective data (following the named cell) in the correct column.</p>
<p><a href="https://i.stack.imgur.com/Pxu1b.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Pxu1b.png" alt="enter image description here" /></a></p>
<p>The output should look like this:</p>
<p><a href="https://i.stack.imgur.com/wWH6J.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wWH6J.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74571919,
"author": "arg0naut91",
"author_id": 8389003,
"author_profile": "https://Stackoverflow.com/users/8389003",
"pm_score": 1,
"selected": false,
"text": "df df[] <- lapply(df, as.character)\ndf <- data.frame(Data = c(t(df)), stringsAsFactors = FALSE)\n\nsubset(df, ave(Data, cumsum(is.na(Data)), FUN = length) > 1L & Data != 'Data')\n Data\n2 34\n10 32\n18 12\n21 89\n NA Data Data non-NA NA Data df <- read.table(\n text = 'Col1 Col2 Col3 Col4 Col5 Col6\nData 34 NA NA NA NA\nNA NA Data 32 NA NA\nNA NA NA NA Data 12\nNA Data 89 NA NA NA', header = TRUE\n)\n"
},
{
"answer_id": 74572112,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "mat apply(mat, 1L, \\(row) row[which(row == 'Data') + 1L])\n# [1] \"34\" \"32\" \"12\" \"89\"\n apply ind = which(mat == 'Data', arr.ind = TRUE)\nord = order(ind[, 1L])\nmat[cbind(seq_along(ord), ind[ord, 2L] + 1L)]\n"
},
{
"answer_id": 74573162,
"author": "JvdV",
"author_id": 9758194,
"author_profile": "https://Stackoverflow.com/users/9758194",
"pm_score": 2,
"selected": false,
"text": "A6 =TOCOL(IF(A1:E4=\"Data\",B1:F4,NA()),3)\n =LET(a,A1:F4,TOCOL(IF(DROP(a,,-1)=\"Data\",DROP(a,,1),NA()),3))\n F2 =LET(a,TOCOL(A1:D13,3),IFERROR(DROP(REDUCE(EXPAND(0,,3),SEQUENCE(ROWS(a-1)),LAMBDA(x,y,LET(b,INDEX(a,y+1),c,FILTER(x,NOT(ISERROR(TAKE(x,,1)))),SWITCH(INDEX(a,y),\"Ticker\",VSTACK(c,b),\"Total Supply\",VSTACK(DROP(c,-1),HSTACK(TOROW(TAKE(c,-1),3),b)),\"Accepted Currencies\",VSTACK(DROP(c,-1),HSTACK(TAKE(c,-1,2),b)),c)))),1),\"\"))\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74571817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11361967/"
] |
74,571,840
|
<p>I'm trying to run a macro with an IF AND THEN statement in a sheet with ListObjects.</p>
<p><a href="https://i.stack.imgur.com/8tHai.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8tHai.png" alt="enter image description here" /></a></p>
<p>In sheet "CommissionVoice" the macro has to check IF column "L" contains the text values "No Pay" or "Below Target". If it contains these strings then column K (an integer) needs to be calculated with column E (a percentage).</p>
<p>So far I was only able to create the next (Test) code with a simple IF statement but that didn't work:</p>
<pre><code>Sub Test()
Dim tbl As ListObject
Dim rng As Range
Dim cel As Range
Set tbl = ActiveSheet.ListObjects("CommissionVoice")
Set rng = tbl.ListColumns(12).DataBodyRange
For Each cel In rng
If InStr(1, cel.Value, "No pay") > 0 Then
cel.Offset(0, -1).Value = "OK"
End If
Next cel
End Sub
</code></pre>
<p>Can someone help me with this?</p>
|
[
{
"answer_id": 74571919,
"author": "arg0naut91",
"author_id": 8389003,
"author_profile": "https://Stackoverflow.com/users/8389003",
"pm_score": 1,
"selected": false,
"text": "df df[] <- lapply(df, as.character)\ndf <- data.frame(Data = c(t(df)), stringsAsFactors = FALSE)\n\nsubset(df, ave(Data, cumsum(is.na(Data)), FUN = length) > 1L & Data != 'Data')\n Data\n2 34\n10 32\n18 12\n21 89\n NA Data Data non-NA NA Data df <- read.table(\n text = 'Col1 Col2 Col3 Col4 Col5 Col6\nData 34 NA NA NA NA\nNA NA Data 32 NA NA\nNA NA NA NA Data 12\nNA Data 89 NA NA NA', header = TRUE\n)\n"
},
{
"answer_id": 74572112,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "mat apply(mat, 1L, \\(row) row[which(row == 'Data') + 1L])\n# [1] \"34\" \"32\" \"12\" \"89\"\n apply ind = which(mat == 'Data', arr.ind = TRUE)\nord = order(ind[, 1L])\nmat[cbind(seq_along(ord), ind[ord, 2L] + 1L)]\n"
},
{
"answer_id": 74573162,
"author": "JvdV",
"author_id": 9758194,
"author_profile": "https://Stackoverflow.com/users/9758194",
"pm_score": 2,
"selected": false,
"text": "A6 =TOCOL(IF(A1:E4=\"Data\",B1:F4,NA()),3)\n =LET(a,A1:F4,TOCOL(IF(DROP(a,,-1)=\"Data\",DROP(a,,1),NA()),3))\n F2 =LET(a,TOCOL(A1:D13,3),IFERROR(DROP(REDUCE(EXPAND(0,,3),SEQUENCE(ROWS(a-1)),LAMBDA(x,y,LET(b,INDEX(a,y+1),c,FILTER(x,NOT(ISERROR(TAKE(x,,1)))),SWITCH(INDEX(a,y),\"Ticker\",VSTACK(c,b),\"Total Supply\",VSTACK(DROP(c,-1),HSTACK(TOROW(TAKE(c,-1),3),b)),\"Accepted Currencies\",VSTACK(DROP(c,-1),HSTACK(TAKE(c,-1,2),b)),c)))),1),\"\"))\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74571840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10011370/"
] |
74,571,849
|
<p>I am trying to generate some R code that creates a data.frame (or tibble). E.g. like this:</p>
<pre><code>library(tidyverse)
example_data <- tibble(`Letter number`=1:10, Letter=letters[1:10])
</code></pre>
<p>I.e. without creating a .csv or .rds file that gets loaded. This is for some training material (a standalone html file created using R markdown), from which people can just copy and paste some code to their R editor/RStudio session. I want to provide a small example dataset to use in exercises.</p>
<p>Let's say I have created the dataset I want on my computer (e.g. reading tables from a pdf using tabulizer, various processing etc.) and now want to create code like the one above in order to be able to copy & paste this code into the .Rmd for generating the html file. Is there something like</p>
<pre><code>create_code_to_generate_tibble( example_data )
</code></pre>
<p>that would output the first code chunk (minus the library loading)?</p>
|
[
{
"answer_id": 74571919,
"author": "arg0naut91",
"author_id": 8389003,
"author_profile": "https://Stackoverflow.com/users/8389003",
"pm_score": 1,
"selected": false,
"text": "df df[] <- lapply(df, as.character)\ndf <- data.frame(Data = c(t(df)), stringsAsFactors = FALSE)\n\nsubset(df, ave(Data, cumsum(is.na(Data)), FUN = length) > 1L & Data != 'Data')\n Data\n2 34\n10 32\n18 12\n21 89\n NA Data Data non-NA NA Data df <- read.table(\n text = 'Col1 Col2 Col3 Col4 Col5 Col6\nData 34 NA NA NA NA\nNA NA Data 32 NA NA\nNA NA NA NA Data 12\nNA Data 89 NA NA NA', header = TRUE\n)\n"
},
{
"answer_id": 74572112,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "mat apply(mat, 1L, \\(row) row[which(row == 'Data') + 1L])\n# [1] \"34\" \"32\" \"12\" \"89\"\n apply ind = which(mat == 'Data', arr.ind = TRUE)\nord = order(ind[, 1L])\nmat[cbind(seq_along(ord), ind[ord, 2L] + 1L)]\n"
},
{
"answer_id": 74573162,
"author": "JvdV",
"author_id": 9758194,
"author_profile": "https://Stackoverflow.com/users/9758194",
"pm_score": 2,
"selected": false,
"text": "A6 =TOCOL(IF(A1:E4=\"Data\",B1:F4,NA()),3)\n =LET(a,A1:F4,TOCOL(IF(DROP(a,,-1)=\"Data\",DROP(a,,1),NA()),3))\n F2 =LET(a,TOCOL(A1:D13,3),IFERROR(DROP(REDUCE(EXPAND(0,,3),SEQUENCE(ROWS(a-1)),LAMBDA(x,y,LET(b,INDEX(a,y+1),c,FILTER(x,NOT(ISERROR(TAKE(x,,1)))),SWITCH(INDEX(a,y),\"Ticker\",VSTACK(c,b),\"Total Supply\",VSTACK(DROP(c,-1),HSTACK(TOROW(TAKE(c,-1),3),b)),\"Accepted Currencies\",VSTACK(DROP(c,-1),HSTACK(TAKE(c,-1,2),b)),c)))),1),\"\"))\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74571849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7744356/"
] |
74,571,858
|
<p>I want to re-start my app through Pending intent. Below code is not working.</p>
<pre><code>val intent = Intent(this, Activity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
}
val pendingIntentId = 1
val pendingIntent = PendingIntent.getActivity(this, pendingIntentId, intent, PendingIntent.FLAG_CANCEL_CURRENT)
val mgr = getSystemService(Context.ALARM_SERVICE) as AlarmManager
val timeToStart = System.currentTimeMillis() + 1000L
mgr.set(AlarmManager.RTC, timeToStart, pendingIntent)
exitProcess(0)
</code></pre>
<p>Target version is 31, so updated pending intent with <code>PendingIntent.FLAG_MUTABLE</code> still not working. I searched in many links related to this but no luck.</p>
<p><a href="https://stackoverflow.com/questions/46070938/restarting-android-app-programmatically">Restarting Android app programmatically</a></p>
<p><a href="https://stackoverflow.com/questions/2470870/force-application-to-restart-on-first-activity">Force application to restart on first activity</a></p>
<p><a href="https://www.folkstalk.com/tech/restart-application-programmatically-android-with-code-examples/#:%7E:text=How%20do%20I%20programmatically%20restart,finishes%20and%20automatically%20relaunches%20us.%20%7D" rel="nofollow noreferrer">https://www.folkstalk.com/tech/restart-application-programmatically-android-with-code-examples/#:~:text=How%20do%20I%20programmatically%20restart,finishes%20and%20automatically%20relaunches%20us.%20%7D</a></p>
<p>In Nov 2022, When target version is 31 & min sdk version is 29, above pending intent code is not restarting the App.</p>
<p>Any clue why above pending intent is not working or any other suggestion apart from re-launching the activity ?? I don't want to re-launch using <code>startActivity(intent)</code></p>
|
[
{
"answer_id": 74613696,
"author": "TIMBLOCKER",
"author_id": 15959434,
"author_profile": "https://Stackoverflow.com/users/15959434",
"pm_score": 1,
"selected": false,
"text": "ProcessPhoenix.triggerRebirth(context);\n Intent nextIntent = //...\nProcessPhoenix.triggerRebirth(context, nextIntent);\n"
},
{
"answer_id": 74674387,
"author": "J. M. Arnold",
"author_id": 14852784,
"author_profile": "https://Stackoverflow.com/users/14852784",
"pm_score": -1,
"selected": false,
"text": "val intent = Intent(this, Activity::class.java).apply {\n flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK\n}\nval pendingIntentId = 1\nval pendingIntent = PendingIntent.getActivity(this, pendingIntentId, intent, PendingIntent.FLAG_CANCEL_CURRENT)\nval mgr = getSystemService(Context.ALARM_SERVICE) as AlarmManager\nval timeToStart = System.currentTimeMillis() + 1000L\nmgr.set(AlarmManager.RTC, timeToStart, pendingIntent)\nfinish() // Close the current Activity\n Intent Activity FLAG_ACTIVITY_CLEAR_TOP FLAG_ACTIVITY_NEW_TASK PendingIntent Intent AlarmManager Intent finish Activity Intent exitProcess exitProcess finish Activity Intent Intent.FLAG_ACTIVITY_NEW_TASK Intent"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74571858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2914684/"
] |
74,571,865
|
<p>We develop with Viewport3D a chart looks like this
<a href="https://i.stack.imgur.com/MrGoU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MrGoU.png" alt="normal appearence" /></a></p>
<p>It works a long time very well, but this week a cutomer send as following screen shot:
<a href="https://i.stack.imgur.com/QfhBP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QfhBP.png" alt="destroyed appearence" /></a></p>
<p>We check already pc. All things new and up to date (Windows 10 22H2, NVIDIA RTX A1006 ...). We try other resolutions. Nothing helps.</p>
<p>Is there anybody there that can give us a suggestion, what we should try.</p>
|
[
{
"answer_id": 74613696,
"author": "TIMBLOCKER",
"author_id": 15959434,
"author_profile": "https://Stackoverflow.com/users/15959434",
"pm_score": 1,
"selected": false,
"text": "ProcessPhoenix.triggerRebirth(context);\n Intent nextIntent = //...\nProcessPhoenix.triggerRebirth(context, nextIntent);\n"
},
{
"answer_id": 74674387,
"author": "J. M. Arnold",
"author_id": 14852784,
"author_profile": "https://Stackoverflow.com/users/14852784",
"pm_score": -1,
"selected": false,
"text": "val intent = Intent(this, Activity::class.java).apply {\n flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK\n}\nval pendingIntentId = 1\nval pendingIntent = PendingIntent.getActivity(this, pendingIntentId, intent, PendingIntent.FLAG_CANCEL_CURRENT)\nval mgr = getSystemService(Context.ALARM_SERVICE) as AlarmManager\nval timeToStart = System.currentTimeMillis() + 1000L\nmgr.set(AlarmManager.RTC, timeToStart, pendingIntent)\nfinish() // Close the current Activity\n Intent Activity FLAG_ACTIVITY_CLEAR_TOP FLAG_ACTIVITY_NEW_TASK PendingIntent Intent AlarmManager Intent finish Activity Intent exitProcess exitProcess finish Activity Intent Intent.FLAG_ACTIVITY_NEW_TASK Intent"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74571865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3090965/"
] |
74,571,947
|
<p>I have some logfiles in some directories which are <code>.txt</code> files and in their names they have some unique name code which are in <code>ddMMyyy</code> format for example <code>BlockPanel Logs_**23112022_00**.txt</code> the bolded block is that unique name which is a date as I said. What I want to do is filter those text files which were generated within two dates which I picked by those DatePickers.</p>
|
[
{
"answer_id": 74572185,
"author": "vivek nuna",
"author_id": 6527049,
"author_profile": "https://Stackoverflow.com/users/6527049",
"pm_score": 1,
"selected": false,
"text": "SubString var myFiles = Directory\n .EnumerateFiles(dir, \"*.txt\", SearchOption.AllDirectories)\n .Where(s => Convert.ToDateTime(s.Substring(x,y)) > dt1 && Convert.ToDateTime(s.Substring(x,y)) < dt2);\n"
},
{
"answer_id": 74577492,
"author": "Idle_Mind",
"author_id": 2330053,
"author_profile": "https://Stackoverflow.com/users/2330053",
"pm_score": 0,
"selected": false,
"text": "private void button1_Click(object sender, EventArgs e)\n{\n DateTime dt;\n String dtFormat = \"ddMMyyyy\";\n String folderPath = @\"C:\\Users\\mikes\\Documents\\Test\\\";\n\n DateTime dtStart = dateTimePicker1.Value.Date;\n DateTime dtStop = dateTimePicker2.Value.Date;\n if (dtStart <= dtStop)\n { \n DirectoryInfo di = new DirectoryInfo(folderPath); \n foreach(FileInfo fi in di.GetFiles(\"*.txt\"))\n {\n String[] parts = Path.GetFileNameWithoutExtension(fi.Name).Split(\"_\".ToCharArray());\n if (parts.Length>=2)\n {\n if (DateTime.TryParseExact(parts[1], dtFormat, null, System.Globalization.DateTimeStyles.None, out dt))\n {\n if (dt >= dtStart && dt <= dtStop)\n {\n // ... do something with \"fi\" ...\n Console.WriteLine(fi.FullName);\n }\n }\n }\n } \n }\n}\n _ _ _"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74571947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15604508/"
] |
74,571,953
|
<p>For my Django CMS Admin I would like to prevent it returning a specific object to the CMS. What is the best way to do this?</p>
<p>I would like to do something like</p>
<pre><code>class MyModuleAdmin(admin.ModelAdmin):
list_display = ['name']
list_filter = ('my_module__name__is_not=moduleidontwant',)
</code></pre>
|
[
{
"answer_id": 74572431,
"author": "G. Vallereau",
"author_id": 6609345,
"author_profile": "https://Stackoverflow.com/users/6609345",
"pm_score": 1,
"selected": false,
"text": "get_queryset class MyModuleAdmin(admin.ModelAdmin):\n list_display = ['name']\n\n def get_queryset(self, request):\n queryset = super(MyModuleAdmin, self).get_queryset(request)\n return queryset.exclude(name='moduleidontwant')\n"
},
{
"answer_id": 74572888,
"author": "Dev Kansara",
"author_id": 18036441,
"author_profile": "https://Stackoverflow.com/users/18036441",
"pm_score": 0,
"selected": false,
"text": "# custom_filters.py\nfrom django.contrib.admin import SimpleListFilter\n\nclass testFilter(SimpleListFilter):\n \"\"\" This filter is being used in django admin panel in specified model.\"\"\"\n title = 'Title of you field'\n parameter_name = 'field_name'\n \n def queryset(self, request, queryset):\n if not self.value():\n return queryset\n else:\n return queryset.filter(my_module__name__is_not='moduleidontwant') #add your filter here.\n list_filter # admin.py\nfrom django.contrib import admin\nfrom .models import *\nfrom .custom_filters import testFilter\n\nclass MyModuleAdmin(admin.ModelAdmin):\n list_display = ['name']\n list_filter = (testFilter)\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74571953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14183621/"
] |
74,571,960
|
<p>I have some javascript which will change the <code>col-span-{x}</code> class of a div to correctly give the element its width on the page. I would like this change to be animated over a second instead of an instant jump.</p>
<pre><code><div class="card col-span-{colSpan} transition duration-1000">...</div>
</code></pre>
|
[
{
"answer_id": 74572891,
"author": "superdunck",
"author_id": 15721671,
"author_profile": "https://Stackoverflow.com/users/15721671",
"pm_score": 0,
"selected": false,
"text": "transition transition-all transition"
},
{
"answer_id": 74573969,
"author": "Matvey Andreyev",
"author_id": 1722529,
"author_profile": "https://Stackoverflow.com/users/1722529",
"pm_score": 2,
"selected": true,
"text": "col-span-{number} grid-column grid-column: span 1 / span 1; grid-column: span 2 / span 2; let grid; \n\nconst hide = (elem) => {\n elem.style.opacity = 0;\n}\n\nconst show = (elem) => {\n elem.style.opacity = 1;\n}\n\nconst animateWidth = (elem) => {\n const gridRect = grid.getBoundingClientRect();\n const targetRect = elem.getBoundingClientRect();\n \n const clone = elem.cloneNode();\n clone.style.pointerEvents = 'none';\n clone.innerHTML = elem.innerHTML + ' clone';\n clone.classList.add('clone');\n clone.style.position = 'absolute';\n clone.style.zIndex = 999;\n clone.style.transition = 'width 1s, left 1s, top 1s';\n \n const oldWidth = targetRect.width;\n clone.style.width = oldWidth + 'px';\n \n const top = targetRect.y - gridRect.y;\n clone.style.top = top ? top + 'px' : 0;\n \n const left = targetRect.x - gridRect.x;\n clone.style.left = left ? left + 'px' : 0;\n\n grid.appendChild(clone);\n\n hide(elem);\n \n let nextSibling;\n let nextSiblingClone;\n if (elem.nextSibling && !elem.nextSibling.classList.contains('clone')) {\n nextSibling = elem.nextSibling;\n nextSiblingClone = createAndGetNextSiblingClone(elem.nextSibling);\n }\n \n elem.classList.toggle('col-span-1');\n elem.classList.toggle('col-span-2');\n \n const newWidth = elem.getBoundingClientRect().width;\n clone.style.width = newWidth ? newWidth + 'px' : 0;\n \n const newLeft = elem.getBoundingClientRect().x - gridRect.x;\n clone.style.left = newLeft ? newLeft + 'px' : 0;\n \n const newTop = elem.getBoundingClientRect().y - gridRect.y;\n clone.style.top = newTop ? newTop + 'px' : 0;\n \n if (nextSibling) {\n const nextSiblingRect = nextSibling.getBoundingClientRect();\n \n const nextSiblingLeft = nextSiblingRect.x - gridRect.x;\n nextSiblingClone.style.left = nextSiblingLeft ? nextSiblingLeft + 'px' : 0;\n \n const nextSiblingTop = nextSiblingRect.y - gridRect.y;\n nextSiblingClone.style.top = nextSiblingTop ? nextSiblingTop + 'px' : 0;\n }\n \n clone.ontransitionend = (event) => {\n show(elem);\n if (event && event.target && event.target.parentNode) {\n event.target.parentNode.removeChild(event.target);\n }\n }\n}\n\nconst createAndGetNextSiblingClone = (elem) => {\n const gridRect = grid.getBoundingClientRect();\n const targetRect = elem.getBoundingClientRect();\n \n const clone = elem.cloneNode();\n clone.innerHTML = elem.innerHTML + ' clone';\n clone.classList.add('clone');\n clone.style.position = 'absolute';\n clone.style.zIndex = 999;\n clone.style.transition = 'left 1s, top 1s';\n clone.style.pointerEvents = 'none';\n clone.style.width = targetRect.width ? targetRect.width + 'px' : 0;\n \n const top = targetRect.y - gridRect.y;\n clone.style.top = top ? top + 'px' : 0;\n \n const left = targetRect.x - gridRect.x;\n clone.style.left = left ? left + 'px' : 0;\n \n grid.appendChild(clone);\n \n hide(elem);\n \n clone.ontransitionend = (event) => {\n show(elem);\n if (event && event.target && event.target.parentNode) {\n event.target.parentNode.removeChild(event.target);\n }\n }\n \n return clone;\n}\n\nconst onGridItemClick = (event) => {\n animateWidth(event.target);\n}\n\nconst displayTheGrid = () => {\n grid = document.getElementById('grid');\n \n 'lightgreen lightblue #dabaf9 beige #ffbbbb #f9daba #99cefa'\n .split(' ')\n .forEach((color, index) => {\n const gridItem = document.createElement('div');\n gridItem.innerHTML = index;\n gridItem.style.backgroundColor = color;\n grid.appendChild(gridItem);\n gridItem.onclick = onGridItemClick;\n });\n}\n\nwindow.addEventListener('DOMContentLoaded', displayTheGrid); * {\n box-sizing: border-box;\n}\n\n#grid {\n display: grid;\n grid-template-columns: 20fr 20fr 20fr 20fr 20fr;\n grid-gap: 10px;\n margin-top: 10px;\n position: relative;\n}\n\n#grid > div {\n border-radius: 6px;\n padding: 10px;\n background-color: silver;\n}\n\n.col-span-1 {\n grid-column: span 1 / span 1;\n}\n\n.col-span-2 {\n grid-column: span 2 / span 2;\n} <!-- https://stackoverflow.com/questions/74571960 -->\n<div id=\"grid\"></div>"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74571960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15691/"
] |
74,571,963
|
<p>I have to write a function to recognize if unknown value has specific property. Unfortunately typescript still don't know what kind of value I have.</p>
<p>Here is my code:</p>
<pre><code>export function isMySpecificError(error: unknown) {
if (error && typeof error === 'object' && 'code' in error && error.hasOwnProperty('code')) {
//TS2339: Property 'code' does not exist on type 'object'.
return typeof error.code === 'string';
}
}
</code></pre>
<p>I know my if statement could be written differently but I can't understand why typescript still doesn't know if property 'code' exist in 'error' after double check <code>'code' in error && error.hasOwnProperty('code')</code></p>
<p>Here is my current solution which works, but I had to declare new type for 'error' instead of check it:</p>
<pre><code>export function isMySpecificError(error: unknown): error is MySpecificError {
if (error && typeof error === 'object' && error.hasOwnProperty('code')) {
const errorWithCodeProperty = error as { code: unknown };
return typeof errorWithCodeProperty.code === 'string' && errorWithCodeProperty.code.startsWith('someErrorCodeValue');
}
return false;
}
</code></pre>
<p>Could it be simplified? Is it possible to check differently if unknown object has a specific property?</p>
|
[
{
"answer_id": 74572059,
"author": "Dimava",
"author_id": 5734961,
"author_profile": "https://Stackoverflow.com/users/5734961",
"pm_score": 0,
"selected": false,
"text": "interface ErrorWithCode<T extends number = number> extends Error {\n code: T\n}\n\nfunction isErrorWithCode<T extends number>(\n err: ErrorWithCode<T> | unknown\n): err is ErrorWithCode<T> {\n return err instanceof Error && 'code' in err;\n}\n\nlet e = Object.assign(new Error(), {code: 444 as const})\n\nif (isErrorWithCode(e)) {\n e.code // 444\n // ^?\n}\n\nlet e1 = new Error()\nif (isErrorWithCode(e1)) {\n e1.code // number\n // ^?\n}\n"
},
{
"answer_id": 74572099,
"author": "Tobias S.",
"author_id": 8613630,
"author_profile": "https://Stackoverflow.com/users/8613630",
"pm_score": 2,
"selected": false,
"text": "in in object Record<\"propName\", unknown> // version 4.9\n\nfunction isMySpecificError(error: unknown) {\n if (error && typeof error === 'object' && 'code' in error && error.hasOwnProperty('code')) {\n\n error\n// ^? error: object & Record<\"code\", unknown>\n\n return typeof error.code === 'string';\n }\n return false;\n}\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74571963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9284037/"
] |
74,571,986
|
<p>I want like a this button
but I can not make it</p>
<p>Please tell me that how to make about</p>
<p><a href="https://i.stack.imgur.com/fOA9m.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fOA9m.png" alt="enter image description here" /></a></p>
<p>I did tryed code</p>
<pre><code>ElevatedButton(
style: ElevatedButton.styleFrom(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30)),
backgroundColor: Colors.lightBlue[400],
side:BorderSide(width: 2, color: Colors.black)),
</code></pre>
<p>result
<a href="https://i.stack.imgur.com/jtJd1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jtJd1.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74572205,
"author": "Kemal Yilmaz",
"author_id": 20518203,
"author_profile": "https://Stackoverflow.com/users/20518203",
"pm_score": 0,
"selected": false,
"text": "Card(\n elevation: 8,\n color: Color.fromARGB(255, 132, 255, 199),\n shape: RoundedRectangleBorder(\n borderRadius: BorderRadius.circular(15),\n side: BorderSide(width: 2)),\n child: InkWell(\n borderRadius: BorderRadius.circular(15),\n onTap: () {},\n child: Container(\n padding:\n EdgeInsets.only(left: 20, right: 20, top: 10, bottom: 10),\n child: Text(\n \"LOGIN\",\n style: TextStyle(fontWeight: FontWeight.w700),\n ))),\n )\n"
},
{
"answer_id": 74572292,
"author": "Sabahat Hussain Qureshi",
"author_id": 17901132,
"author_profile": "https://Stackoverflow.com/users/17901132",
"pm_score": 3,
"selected": true,
"text": "Container(\n height: 50,\n width: 200,\n decoration: BoxDecoration(\n color: Color(0xff92fcd1),\n border: Border.all(color: Colors.black),\n borderRadius: BorderRadius.circular(100),\n boxShadow: <BoxShadow>[\n BoxShadow(\n color: Colors.black,\n offset: Offset(2.5, 2.5),\n spreadRadius: 0.1\n )\n ], \n ),\n child: Center(\n child: Text('LOGIN'),\n )\n),\n"
},
{
"answer_id": 74572341,
"author": "baek",
"author_id": 1049200,
"author_profile": "https://Stackoverflow.com/users/1049200",
"pm_score": 2,
"selected": false,
"text": "Container(\n width: 100,\n height: 30,\n decoration: BoxDecoration(\n border: Border.all(\n width: 1,\n color: Colors.black,\n ),\n color: const Color(0xff93fbd1),\n borderRadius: BorderRadius.circular(15),\n boxShadow: const [\n BoxShadow(\n color: Colors.black,\n blurRadius: 1,\n offset: Offset(1, 2), // Shadow position\n ),\n ],\n ),\n child: TextButton(\n child: const Text(\n 'LOGIN',\n style: TextStyle(\n fontStyle: FontStyle.italic,\n color: Colors.black,\n fontWeight: FontWeight.bold),\n ),\n onPressed: () {\n // TODO: button onTap events\n },\n ),\n );\n"
},
{
"answer_id": 74572437,
"author": "Stanly",
"author_id": 18627424,
"author_profile": "https://Stackoverflow.com/users/18627424",
"pm_score": 0,
"selected": false,
"text": " GestureDetector(\n behavior: HitTestBehavior.opaque,\n onTap: () {},\n child: Container(\n width: MediaQuery.of(context).size.width * 0.4,\n height: MediaQuery.of(context).size.height * 0.05,\n decoration: BoxDecoration(\n color: const Color(0xff92fcd1),\n border: Border.all(color: Colors.black),\n borderRadius: BorderRadius.circular(100),\n boxShadow: [\n BoxShadow(\n color: Colors.black.withOpacity(0.7),\n spreadRadius: 2,\n offset:\n const Offset(2, 2), // changes position of shadow\n ),\n ],\n ),\n child: const Center(\n child: Text(\"Login\",\n style: TextStyle(\n fontStyle: FontStyle.italic, color: Colors.black)),\n ),\n ),\n )\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74571986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18096205/"
] |
74,571,988
|
<p><a href="https://i.stack.imgur.com/vaeLh.jpg" rel="nofollow noreferrer">The series:- </a>
I want to write a python program in which we can can input the the value of x and n and solve this series.
can anyone help me please?
<strong>The Series:- x-x^2+x^3/3-x^4/4+...x^n/n</strong></p>
<pre><code>x = int (input ("Enter value of x: "))
numbed = int (input ("Enter value of n: "))
summed = 0
for a in range (numbed + 1) :
if a%2==0:
summed += (x**a)/numbed
else:
summed -= (x**a)/numbed
print ("Sum of series", summed)
</code></pre>
<p>**I tried this code, but no matter what values I enter, the output is always 0.00. **</p>
|
[
{
"answer_id": 74572155,
"author": "Hein de Wilde",
"author_id": 7746170,
"author_profile": "https://Stackoverflow.com/users/7746170",
"pm_score": 1,
"selected": false,
"text": "x = int(input(\"Enter value of x: \"))\nn = int(input(\"Enter value of n: \"))\ntotal = x\n\nfor i in range(2, n+1):\n if i%2==0:\n total -= x**i/i\n else:\n total += x**i/i\n \nprint(\"Sum: \", total)\n"
},
{
"answer_id": 74572429,
"author": "Kavya Kommuri",
"author_id": 18726537,
"author_profile": "https://Stackoverflow.com/users/18726537",
"pm_score": 1,
"selected": false,
"text": "x = int (input (\"Enter value of x: \"))\n numbed = int (input (\"Enter value of n: \"))\n sum1 = x\n \n for i in range(2,numbed+1):\n if i%2==0:\n sum1=sum1-((x**i)/i)\n else:\n sum1=sum1+((x**i)/i)\n print(\"The sum of series is\",round(sum1,2))\n"
},
{
"answer_id": 74573668,
"author": "SergFSM",
"author_id": 18344512,
"author_profile": "https://Stackoverflow.com/users/18344512",
"pm_score": 0,
"selected": false,
"text": "x = int(input(\"Enter value of x: \"))\nn = int(input(\"Enter value of n: \"))\n\ndef f(x,n,i=1,s=1):\n return 0 if i>n else x**i/i*s + f(x,n,i+1,-s)\n\nf(3,5) # 35.85\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74571988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20237989/"
] |
74,572,019
|
<p>I want to flag Komp and Bauspar if either one of them is <1 with -, >1 with + and if one of them is blank --> no flag.
Tried the following, but it produces with two 2022_Bauspar_flag columns somehow?
Can you give me hint?
Thanks a lot.
Kind regards,
Ben</p>
<pre><code>%macro target_years2(table,type);
%local name_Bauspar name_Komp;
data &table ;
set work.&table;
%let name_Komp = "2022_ZZ_Komp"n;
%let name_Bauspar = "2022_ZZ_Bauspar"n;
&name_Komp = (1+("2022_Komposit"n-"2022_Komposit_Ziel"n)/"2022_Komposit_Ziel"n);
&name_Bauspar = (1+("2022_Bausparen"n-"2022_Bausparen_Ziel"n)/"2022_Bausparen_Ziel"n);
/*create ZZ_flags*/
if &name_Komp > 1 THEN do;
"2022_ZZ_Komp_flag"n = '+';
end;
else if &name_Komp < 1 and &name_Komp <> . THEN do;
"2022_ZZ_Komp_flag"n = '-';
end;
else if &name_Bauspar > 1 THEN do;
"2022_ZZ_Baupar_flag"n = '+';
end;
else if &name_Bauspar < 1 and &name_Bauspar <> . THEN do;
"2022_ZZ_Bauspar_flag"n = '-';
end;
else do;
end;
run;
%mend;
%target_years2(Produktion_temp,Produktion)
</code></pre>
|
[
{
"answer_id": 74572155,
"author": "Hein de Wilde",
"author_id": 7746170,
"author_profile": "https://Stackoverflow.com/users/7746170",
"pm_score": 1,
"selected": false,
"text": "x = int(input(\"Enter value of x: \"))\nn = int(input(\"Enter value of n: \"))\ntotal = x\n\nfor i in range(2, n+1):\n if i%2==0:\n total -= x**i/i\n else:\n total += x**i/i\n \nprint(\"Sum: \", total)\n"
},
{
"answer_id": 74572429,
"author": "Kavya Kommuri",
"author_id": 18726537,
"author_profile": "https://Stackoverflow.com/users/18726537",
"pm_score": 1,
"selected": false,
"text": "x = int (input (\"Enter value of x: \"))\n numbed = int (input (\"Enter value of n: \"))\n sum1 = x\n \n for i in range(2,numbed+1):\n if i%2==0:\n sum1=sum1-((x**i)/i)\n else:\n sum1=sum1+((x**i)/i)\n print(\"The sum of series is\",round(sum1,2))\n"
},
{
"answer_id": 74573668,
"author": "SergFSM",
"author_id": 18344512,
"author_profile": "https://Stackoverflow.com/users/18344512",
"pm_score": 0,
"selected": false,
"text": "x = int(input(\"Enter value of x: \"))\nn = int(input(\"Enter value of n: \"))\n\ndef f(x,n,i=1,s=1):\n return 0 if i>n else x**i/i*s + f(x,n,i+1,-s)\n\nf(3,5) # 35.85\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13899067/"
] |
74,572,028
|
<p>I have a dataframe (cells) that it looks like this (it has more rows):</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th style="text-align: right;">Time(min) </th>
<th style="text-align: right;">Cell1</th>
<th style="text-align: right;">Cell2</th>
<th style="text-align: right;">Cell3</th>
<th style="text-align: right;">Cell4</th>
<th style="text-align: right;">Cell5</th>
<th style="text-align: right;">Cell6</th>
<th style="text-align: right;">Cell7</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>AA001</td>
<td style="text-align: right;">0</td>
<td style="text-align: right;">10.57</td>
<td style="text-align: right;">77.28</td>
<td style="text-align: right;">14.11</td>
<td style="text-align: right;">15.12</td>
<td style="text-align: right;">1.56</td>
<td style="text-align: right;">95.83</td>
<td style="text-align: right;">3.41</td>
<td></td>
</tr>
<tr>
<td>AA001</td>
<td style="text-align: right;">30</td>
<td style="text-align: right;">12.99</td>
<td style="text-align: right;">77.96</td>
<td style="text-align: right;">15.01</td>
<td style="text-align: right;">15.35</td>
<td style="text-align: right;">1.60</td>
<td style="text-align: right;">96.02</td>
<td style="text-align: right;">3.37</td>
<td></td>
</tr>
<tr>
<td>AA001</td>
<td style="text-align: right;">90</td>
<td style="text-align: right;">11.41</td>
<td style="text-align: right;">79.85</td>
<td style="text-align: right;">16.69</td>
<td style="text-align: right;">19.65</td>
<td style="text-align: right;">1.28</td>
<td style="text-align: right;">92.14</td>
<td style="text-align: right;">6.01</td>
<td></td>
</tr>
<tr>
<td>AA001</td>
<td style="text-align: right;">180</td>
<td style="text-align: right;">15.89</td>
<td style="text-align: right;">75.11</td>
<td style="text-align: right;">12.48</td>
<td style="text-align: right;">11.95</td>
<td style="text-align: right;">1.34</td>
<td style="text-align: right;">95.90</td>
<td style="text-align: right;">3.69</td>
<td></td>
</tr>
<tr>
<td>AA001</td>
<td style="text-align: right;">360</td>
<td style="text-align: right;">10.16</td>
<td style="text-align: right;">83.67</td>
<td style="text-align: right;">19.51</td>
<td style="text-align: right;">14.68</td>
<td style="text-align: right;">1.09</td>
<td style="text-align: right;">70.80</td>
<td style="text-align: right;">26.21</td>
<td></td>
</tr>
<tr>
<td>AA003</td>
<td style="text-align: right;">0</td>
<td style="text-align: right;">12.34</td>
<td style="text-align: right;">81.16</td>
<td style="text-align: right;">17.77</td>
<td style="text-align: right;">17.49</td>
<td style="text-align: right;">1.83</td>
<td style="text-align: right;">84.94</td>
<td style="text-align: right;">13.31</td>
<td></td>
</tr>
<tr>
<td>AA006</td>
<td style="text-align: right;">0</td>
<td style="text-align: right;">21.71</td>
<td style="text-align: right;">71.24</td>
<td style="text-align: right;">7.67</td>
<td style="text-align: right;">11.43</td>
<td style="text-align: right;">1.56</td>
<td style="text-align: right;">90.03</td>
<td style="text-align: right;">7.62</td>
<td></td>
</tr>
<tr>
<td>AA006</td>
<td style="text-align: right;">7</td>
<td style="text-align: right;">15.23</td>
<td style="text-align: right;">78.81</td>
<td style="text-align: right;">15.60</td>
<td style="text-align: right;">12.19</td>
<td style="text-align: right;">2.23</td>
<td style="text-align: right;">93.38</td>
<td style="text-align: right;">3.4</td>
<td></td>
</tr>
</tbody>
</table>
</div>
<p>I have grouped by the variables ID and Time, because I would like to see the "evolution" of each cell for each sample:</p>
<pre><code>inmune %>%
group_by(PID, Time)
</code></pre>
<p>So, I have performed a scatter plot, but it's a mess with so many lines connected to each point.</p>
<p>Also I tried transform in a long-data format:</p>
<pre><code>df2<- melt(cells, id = "Time")
</code></pre>
<p>But it results in a table with 3 variables (Time, cells, values) so I miss the ID.</p>
<p>The idea is to represent the difference of the values for each time, grouped by the ID.</p>
<p>But any suggestion about other type of graphs more suitable for this kind of data is more than welcome.
Thanks!!</p>
|
[
{
"answer_id": 74572155,
"author": "Hein de Wilde",
"author_id": 7746170,
"author_profile": "https://Stackoverflow.com/users/7746170",
"pm_score": 1,
"selected": false,
"text": "x = int(input(\"Enter value of x: \"))\nn = int(input(\"Enter value of n: \"))\ntotal = x\n\nfor i in range(2, n+1):\n if i%2==0:\n total -= x**i/i\n else:\n total += x**i/i\n \nprint(\"Sum: \", total)\n"
},
{
"answer_id": 74572429,
"author": "Kavya Kommuri",
"author_id": 18726537,
"author_profile": "https://Stackoverflow.com/users/18726537",
"pm_score": 1,
"selected": false,
"text": "x = int (input (\"Enter value of x: \"))\n numbed = int (input (\"Enter value of n: \"))\n sum1 = x\n \n for i in range(2,numbed+1):\n if i%2==0:\n sum1=sum1-((x**i)/i)\n else:\n sum1=sum1+((x**i)/i)\n print(\"The sum of series is\",round(sum1,2))\n"
},
{
"answer_id": 74573668,
"author": "SergFSM",
"author_id": 18344512,
"author_profile": "https://Stackoverflow.com/users/18344512",
"pm_score": 0,
"selected": false,
"text": "x = int(input(\"Enter value of x: \"))\nn = int(input(\"Enter value of n: \"))\n\ndef f(x,n,i=1,s=1):\n return 0 if i>n else x**i/i*s + f(x,n,i+1,-s)\n\nf(3,5) # 35.85\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9152842/"
] |
74,572,037
|
<p>I am trying to center text in my content container. In my full versions, I have a wrapper, a header, a footer and a content containers and would like to center text horizontally and vertically inside the content container for some specific pages. Unfortunately when the number of lines exceeds the size of the content container, the top lines of the text just keep hidden (in some other cases they just overflow invading the header and footer container).</p>
<p>I have build a smaller example of my problem which reproduces the error and which is based on a W3 example. I have also tried several posts here but I am most probably doing something wrong.</p>
<p>I have tried everything that could come to mind knowing that I am not an expert on the matter. The problem only comes up when the text (lines) exceeds the size of the container. Some time I get an overflow visible effect and sometimes I loose the top lines.</p>
<p>All hints and help will be appreciated.</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>#main {
width: 220px;
height: 300px;
border: 1px solid black;
display: flex;
align-items: stretch;
}
#main div {
flex: 1;
border: 1px solid black;
display: flex;
overflow-y: scroll;
align-items: center;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2>align-items: stretch</h2>
<div id="main">
<div style="background-color:coral;min-height:30px;">RED</div>
<div style="background-color:lightblue;min-height:50px;">BLUE</div>
<div style="background-color:lightgreen;min-height:190px;">
The number is: 1<br>
The number is: 2<br>
The number is: 3<br>
The number is: 4<br>
The number is: 5<br>
The number is: 6<br>
The number is: 7<br>
The number is: 8<br>
The number is: 9<br>
The number is: 10<br>
The number is: 11<br>
The number is: 12<br>
The number is: 13<br>
The number is: 14<br>
The number is: 15<br>
The number is: 16<br>
The number is: 17<br>
The number is: 18<br>
The number is: 19<br>
The number is: 20
</div>
</div>
<p><b>Note:</b> Internet Explorer 10 and earlier versions do not support the align-items property.</p></code></pre>
</div>
</div>
</p>
<p>Where are the 1st 7 lines?</p>
|
[
{
"answer_id": 74572155,
"author": "Hein de Wilde",
"author_id": 7746170,
"author_profile": "https://Stackoverflow.com/users/7746170",
"pm_score": 1,
"selected": false,
"text": "x = int(input(\"Enter value of x: \"))\nn = int(input(\"Enter value of n: \"))\ntotal = x\n\nfor i in range(2, n+1):\n if i%2==0:\n total -= x**i/i\n else:\n total += x**i/i\n \nprint(\"Sum: \", total)\n"
},
{
"answer_id": 74572429,
"author": "Kavya Kommuri",
"author_id": 18726537,
"author_profile": "https://Stackoverflow.com/users/18726537",
"pm_score": 1,
"selected": false,
"text": "x = int (input (\"Enter value of x: \"))\n numbed = int (input (\"Enter value of n: \"))\n sum1 = x\n \n for i in range(2,numbed+1):\n if i%2==0:\n sum1=sum1-((x**i)/i)\n else:\n sum1=sum1+((x**i)/i)\n print(\"The sum of series is\",round(sum1,2))\n"
},
{
"answer_id": 74573668,
"author": "SergFSM",
"author_id": 18344512,
"author_profile": "https://Stackoverflow.com/users/18344512",
"pm_score": 0,
"selected": false,
"text": "x = int(input(\"Enter value of x: \"))\nn = int(input(\"Enter value of n: \"))\n\ndef f(x,n,i=1,s=1):\n return 0 if i>n else x**i/i*s + f(x,n,i+1,-s)\n\nf(3,5) # 35.85\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20598583/"
] |
74,572,055
|
<p>I need to create a measure that subtracts 2 months from the date column "Sale_Date". However, when I use the below measure I get error "Wrong Data type". Something is wrong in day argument of date function. Because when I hardcode the day value , I start getting results</p>
<pre><code>Min_Date =
var val = SELECTEDVALUE(EX4[Sale_Date])
var month = month(SELECTEDVALUE(EX4[Sale_Date]))-2
var Year = Year(SELECTEDVALUE(EX4[Sale_Date]))
var Day = day(SELECTEDVALUE(EX4[Sale_Date]))
return
DATE(Year,month,Day)
</code></pre>
<p>You can replicate this scenario using the below calculated table :</p>
<pre><code>EX4 = DATATABLE("Sale_Date",datetime,{{"2022-10-01"},{"2022-10-09"},{"2022-11-12"},{"2022-11-23"}})
</code></pre>
<p>Below is the image of visual which is giving error because of this measure:</p>
<p><a href="https://i.stack.imgur.com/XloQv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XloQv.png" alt="Below is the image of visual which is giving error because of this measure" /></a></p>
<p>Now when I hardcode the day value, I start getting output:</p>
<p><a href="https://i.stack.imgur.com/gYlYY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gYlYY.png" alt="enter image description here" /></a></p>
<p>I do not want to solve using calculated column. Any help will be appreciated.</p>
|
[
{
"answer_id": 74573117,
"author": "Peter",
"author_id": 7108589,
"author_profile": "https://Stackoverflow.com/users/7108589",
"pm_score": 3,
"selected": true,
"text": "Min_Date = \nVAR thisdate = MAX(EX4[Sale_Date])\nRETURN\n DATE(YEAR(thisdate), MONTH(thisdate) - 2, DAY(thisdate))\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4054314/"
] |
74,572,069
|
<p>I am working on Cypress API Automation task and want to pass value to an endpoint. I fetched value from postgress database and stored it in a variable called <strong>user_id</strong>. But I am facing issue while hitting endpoint.</p>
<p><strong>Value fetched from database:</strong></p>
<blockquote>
<p>log[{user_id: 52}]</p>
</blockquote>
<p><strong>Issue:</strong></p>
<pre><code>cy.request() failed on:
http://localhost:8080/user/[object%20Object]
The response we received from your web server was:
</code></pre>
<p><strong>Below is my Code</strong></p>
<pre><code>it.only('Delete User', ()=>{
let user_id = cy.task("connectDB","select user_id from user_details where first_name='XYZ'").then(cy.log);
cy.request({
method:'DELETE',
url:'localhost:8080/user/'+user_id+''
}).then((res) => {
expect(res.status).to.eq(200);
})
})
</code></pre>
<p><strong>I want to pass '52' as a value to the endpoint, Can someone help here ?</strong></p>
|
[
{
"answer_id": 74572118,
"author": "Delano van londen",
"author_id": 19923550,
"author_profile": "https://Stackoverflow.com/users/19923550",
"pm_score": 0,
"selected": false,
"text": "cy.url().should('include', '/user_id') \n"
},
{
"answer_id": 74575554,
"author": "jjhelguero",
"author_id": 17917809,
"author_profile": "https://Stackoverflow.com/users/17917809",
"pm_score": 0,
"selected": false,
"text": "user_id user_id[0].user_id it.only('Delete User', ()=>{\n let user_id = cy.task(\"connectDB\",\"select user_id from user_details where first_name='XYZ'\").then(cy.log);\ncy.request({\n method:'DELETE',\n url:'localhost:8080/user/'+ user_id[0].user_id\n}).then((res) => {\n expect(res.status).to.eq(200);\n})\n})\n"
},
{
"answer_id": 74577063,
"author": "Paul Murdin",
"author_id": 20602038,
"author_profile": "https://Stackoverflow.com/users/20602038",
"pm_score": 1,
"selected": false,
"text": "cy.task() .then() cy.task(\"connectDB\", \"select user_id from user_details where first_name='XYZ'\")\n .then(user_id => {\n cy.request({\n method: 'DELETE',\n url: 'localhost:8080/user/' + user_id\n }).then((res) => {\n expect(res.status).to.eq(200) // passes\n })\n })\n let user_id = cy.task(\"connectDB\"... .then()"
},
{
"answer_id": 74601456,
"author": "Ab123",
"author_id": 2857455,
"author_profile": "https://Stackoverflow.com/users/2857455",
"pm_score": 1,
"selected": true,
"text": " it(\"Database Test\", () => {\n cy.task(\"READFROMDB\",\n {\n dbConfig: Cypress.config('DB'),\n sql:'select * from \"user_details\"'\n }).then((result) =>\n {\n //console.log(result.rows)\n let user_id = result.rows[0].user_id\n console.log(\"user id is :\"+user_id)\n })\n});\n const {defineConfig} = require(\"cypress\");\nconst pg= require(\"pg\")\n\nmodule.exports = defineConfig({\n e2e:{\n setupNodeEvents(on,config){\n on(\"task\",{\n READFROMDB({dbConfig,sql}){\n const client = new pg.Pool(dbConfig);\n return client.query(sql);\n }\n })\n },\n DB:{\n user: \"postgres\",\n password: \"password\",\n host: \"localhost\",\n database: \"postgres\",\n port: '5432'\n },\n }\n})\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2857455/"
] |
74,572,070
|
<p>i dont want to keep repeat Almost the same code</p>
<p>look like this</p>
<p><a href="https://codepen.io/lechan87/pen/LYrmQaW" rel="nofollow noreferrer">codepen</a></p>
<pre><code>const text01_edit = document.querySelector(".text01_edit");
const input_text01 = document.querySelector(".text01_contain");
const text02_edit = document.querySelector(".text02_edit");
const input_text02 = document.querySelector(".text02_contain");
// txt
const txtFunction = function (txt) {
txt.disabled = false;
txt.setSelectionRange(txt.value.length, txt.value.length);
};
text01_edit.addEventListener("click", function () {
txtFunction(input_text01);
});
text02_edit.addEventListener("click", function () {
txtFunction(input_text02);
});
</code></pre>
<p>if i need add more (ex:text3 、text4)</p>
<p>i just can only add more like this?</p>
<p>or have something can simplify this code.
i try to use this in my function but it doesn't work , maybe use for?</p>
<p>Please let me know if you don't understand english is not my language !</p>
|
[
{
"answer_id": 74572118,
"author": "Delano van londen",
"author_id": 19923550,
"author_profile": "https://Stackoverflow.com/users/19923550",
"pm_score": 0,
"selected": false,
"text": "cy.url().should('include', '/user_id') \n"
},
{
"answer_id": 74575554,
"author": "jjhelguero",
"author_id": 17917809,
"author_profile": "https://Stackoverflow.com/users/17917809",
"pm_score": 0,
"selected": false,
"text": "user_id user_id[0].user_id it.only('Delete User', ()=>{\n let user_id = cy.task(\"connectDB\",\"select user_id from user_details where first_name='XYZ'\").then(cy.log);\ncy.request({\n method:'DELETE',\n url:'localhost:8080/user/'+ user_id[0].user_id\n}).then((res) => {\n expect(res.status).to.eq(200);\n})\n})\n"
},
{
"answer_id": 74577063,
"author": "Paul Murdin",
"author_id": 20602038,
"author_profile": "https://Stackoverflow.com/users/20602038",
"pm_score": 1,
"selected": false,
"text": "cy.task() .then() cy.task(\"connectDB\", \"select user_id from user_details where first_name='XYZ'\")\n .then(user_id => {\n cy.request({\n method: 'DELETE',\n url: 'localhost:8080/user/' + user_id\n }).then((res) => {\n expect(res.status).to.eq(200) // passes\n })\n })\n let user_id = cy.task(\"connectDB\"... .then()"
},
{
"answer_id": 74601456,
"author": "Ab123",
"author_id": 2857455,
"author_profile": "https://Stackoverflow.com/users/2857455",
"pm_score": 1,
"selected": true,
"text": " it(\"Database Test\", () => {\n cy.task(\"READFROMDB\",\n {\n dbConfig: Cypress.config('DB'),\n sql:'select * from \"user_details\"'\n }).then((result) =>\n {\n //console.log(result.rows)\n let user_id = result.rows[0].user_id\n console.log(\"user id is :\"+user_id)\n })\n});\n const {defineConfig} = require(\"cypress\");\nconst pg= require(\"pg\")\n\nmodule.exports = defineConfig({\n e2e:{\n setupNodeEvents(on,config){\n on(\"task\",{\n READFROMDB({dbConfig,sql}){\n const client = new pg.Pool(dbConfig);\n return client.query(sql);\n }\n })\n },\n DB:{\n user: \"postgres\",\n password: \"password\",\n host: \"localhost\",\n database: \"postgres\",\n port: '5432'\n },\n }\n})\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20116577/"
] |
74,572,084
|
<p>I'm using a simple script to check when something is in the viewport which then adds a class.</p>
<p>However the script stops working in Webpack when I try to import anything.</p>
<p>Below is basic example of importing which breaks my JS file. It doesn't matter what order I put the import and script etc.</p>
<pre><code>window.jQuery = $;
import 'slick-carousel';
$(function ($, win) {
$.fn.inViewport = function (cb) {
return this.each(function (i, el) {
function visPx() {
var H = $(this).height(),
r = el.getBoundingClientRect(), t = r.top, b = r.bottom;
return cb.call(el, Math.max(0, t > 0 ? H - t : (b < H ? b : H)));
} visPx();
$(win).on("resize scroll", visPx);
});
};
}(jQuery, window));
$(".preload").inViewport(function (px) {
if (px) $(this).addClass("is-active");
});
</code></pre>
<p>If I remove <code>import 'slick-carousel';</code> or any of my imports (its not specific to slick-carousel) the script stops working.</p>
<p><a href="https://codepen.io/Probablybest/pen/eYKBPRN" rel="nofollow noreferrer">Here is an example</a> the viewport script working.</p>
|
[
{
"answer_id": 74614049,
"author": "JohanSellberg",
"author_id": 551049,
"author_profile": "https://Stackoverflow.com/users/551049",
"pm_score": 1,
"selected": false,
"text": "import bar from './bar.js';\n\nbar();\n"
},
{
"answer_id": 74650972,
"author": "Andrew Shearer",
"author_id": 10688837,
"author_profile": "https://Stackoverflow.com/users/10688837",
"pm_score": 0,
"selected": false,
"text": "$ jQuery slick-carousel $ jQuery $ jQuery slick-carousel $ jQuery slick-carousel import $, { jQuery } from 'slick-carousel';\n\n$(function () {\n $.fn.inViewport = function (cb) {\n return this.each(function (i, el) {\n function visPx() {\n var H = $(this).height(),\n r = el.getBoundingClientRect(), t = r.top, b = r.bottom;\n return cb.call(el, Math.max(0, t > 0 ? H - t : (b < H ? b : H)));\n }\n visPx();\n $(win).on(\"resize scroll\", visPx);\n });\n };\n});\n\n$(\".preload\").inViewport(function (px) {\n if (px) $(this).addClass(\"is-active\");\n});\n $ jQuery $ jQuery slick-carousel $ jQuery require() const $ = require('slick-carousel').default;\nconst jQuery = require('slick-carousel').jQuery;\n\n$(function () {\n // Your code here...\n});\n import require()"
},
{
"answer_id": 74674469,
"author": "sidverma",
"author_id": 7721497,
"author_profile": "https://Stackoverflow.com/users/7721497",
"pm_score": 0,
"selected": false,
"text": "// Import jQuery and slick-carousel\nimport $ from 'jquery';\nimport 'slick-carousel';\n\n// Use jQuery and slick-carousel in your code\n$(function () {\n $(\".preload\").inViewport(function (px) {\n if (px) $(this).addClass(\"is-active\");\n });\n});\n // Import jQuery and slick-carousel using require\nvar $ = require('jquery');\nrequire('slick-carousel');\n\n// Use jQuery and slick-carousel in your code\n$(function () {\n $(\".preload\").inViewport(function (px) {\n if (px) $(this).addClass(\"is-active\");\n });\n});\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648610/"
] |
74,572,102
|
<p>I want to hand over the name of a variable as a string to the <code>order_by</code> argument of <code>dplyr::slice_max()</code>, but I'm getting weird results. Using the <code>iris</code> data here.</p>
<pre><code>library(dplyr)
lastcol <- first(colnames(iris))
</code></pre>
<p>My expected result would be a df/tibble of 5 rows, which works while using the actual column name.</p>
<pre><code>i <- iris %>%
slice_max(n = 5, order_by = Sepal.Length)
</code></pre>
<p>But when handing over the column name, I'm either getting unexpected results or errors.</p>
<pre><code># unexpected result: one row
i <- iris %>%
slice_max(n = 5, order_by = lastcol)
# unexpected result: one row
i <- iris %>%
slice_max(n = 5, order_by = !!lastcol)
# Error: `:=` can only be used within a quasiquoted argument
i <- iris %>%
slice_max(n = 5, order_by := .data[[lastcol]])
</code></pre>
<p>What's missing?</p>
|
[
{
"answer_id": 74614049,
"author": "JohanSellberg",
"author_id": 551049,
"author_profile": "https://Stackoverflow.com/users/551049",
"pm_score": 1,
"selected": false,
"text": "import bar from './bar.js';\n\nbar();\n"
},
{
"answer_id": 74650972,
"author": "Andrew Shearer",
"author_id": 10688837,
"author_profile": "https://Stackoverflow.com/users/10688837",
"pm_score": 0,
"selected": false,
"text": "$ jQuery slick-carousel $ jQuery $ jQuery slick-carousel $ jQuery slick-carousel import $, { jQuery } from 'slick-carousel';\n\n$(function () {\n $.fn.inViewport = function (cb) {\n return this.each(function (i, el) {\n function visPx() {\n var H = $(this).height(),\n r = el.getBoundingClientRect(), t = r.top, b = r.bottom;\n return cb.call(el, Math.max(0, t > 0 ? H - t : (b < H ? b : H)));\n }\n visPx();\n $(win).on(\"resize scroll\", visPx);\n });\n };\n});\n\n$(\".preload\").inViewport(function (px) {\n if (px) $(this).addClass(\"is-active\");\n});\n $ jQuery $ jQuery slick-carousel $ jQuery require() const $ = require('slick-carousel').default;\nconst jQuery = require('slick-carousel').jQuery;\n\n$(function () {\n // Your code here...\n});\n import require()"
},
{
"answer_id": 74674469,
"author": "sidverma",
"author_id": 7721497,
"author_profile": "https://Stackoverflow.com/users/7721497",
"pm_score": 0,
"selected": false,
"text": "// Import jQuery and slick-carousel\nimport $ from 'jquery';\nimport 'slick-carousel';\n\n// Use jQuery and slick-carousel in your code\n$(function () {\n $(\".preload\").inViewport(function (px) {\n if (px) $(this).addClass(\"is-active\");\n });\n});\n // Import jQuery and slick-carousel using require\nvar $ = require('jquery');\nrequire('slick-carousel');\n\n// Use jQuery and slick-carousel in your code\n$(function () {\n $(\".preload\").inViewport(function (px) {\n if (px) $(this).addClass(\"is-active\");\n });\n});\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2123452/"
] |
74,572,111
|
<p>I have Modal box popin with some text wrapped in a function. This modal is displayed when you click on a div.</p>
<p>Now I want to add a separate script with a div and when you click this div I want it to call the modal function and display that same modal popin.</p>
<p>Can anyone help me?</p>
<p>Here is the modal code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function modalpopin() {
// Get the modal
var modal = document.getElementById("myModal");
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Trigger/Open The Modal -->
<div id="myBtn">Open Modal</div>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">&times;</span>
<p>Some text in the Modal..</p>
</div>
</div></code></pre>
</div>
</div>
</p>
<p>This is the second script I tried. I want this to open the same modal popin. It does not seem to work...</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$("#modal-popin").click(function() {
modalpopin();
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="modal-popin">Click Here to open the Modal</div></code></pre>
</div>
</div>
</p>
<p><a href="https://jsfiddle.net/mk2jsvxg/" rel="nofollow noreferrer">JsFiddle Link Here</a></p>
|
[
{
"answer_id": 74614049,
"author": "JohanSellberg",
"author_id": 551049,
"author_profile": "https://Stackoverflow.com/users/551049",
"pm_score": 1,
"selected": false,
"text": "import bar from './bar.js';\n\nbar();\n"
},
{
"answer_id": 74650972,
"author": "Andrew Shearer",
"author_id": 10688837,
"author_profile": "https://Stackoverflow.com/users/10688837",
"pm_score": 0,
"selected": false,
"text": "$ jQuery slick-carousel $ jQuery $ jQuery slick-carousel $ jQuery slick-carousel import $, { jQuery } from 'slick-carousel';\n\n$(function () {\n $.fn.inViewport = function (cb) {\n return this.each(function (i, el) {\n function visPx() {\n var H = $(this).height(),\n r = el.getBoundingClientRect(), t = r.top, b = r.bottom;\n return cb.call(el, Math.max(0, t > 0 ? H - t : (b < H ? b : H)));\n }\n visPx();\n $(win).on(\"resize scroll\", visPx);\n });\n };\n});\n\n$(\".preload\").inViewport(function (px) {\n if (px) $(this).addClass(\"is-active\");\n});\n $ jQuery $ jQuery slick-carousel $ jQuery require() const $ = require('slick-carousel').default;\nconst jQuery = require('slick-carousel').jQuery;\n\n$(function () {\n // Your code here...\n});\n import require()"
},
{
"answer_id": 74674469,
"author": "sidverma",
"author_id": 7721497,
"author_profile": "https://Stackoverflow.com/users/7721497",
"pm_score": 0,
"selected": false,
"text": "// Import jQuery and slick-carousel\nimport $ from 'jquery';\nimport 'slick-carousel';\n\n// Use jQuery and slick-carousel in your code\n$(function () {\n $(\".preload\").inViewport(function (px) {\n if (px) $(this).addClass(\"is-active\");\n });\n});\n // Import jQuery and slick-carousel using require\nvar $ = require('jquery');\nrequire('slick-carousel');\n\n// Use jQuery and slick-carousel in your code\n$(function () {\n $(\".preload\").inViewport(function (px) {\n if (px) $(this).addClass(\"is-active\");\n });\n});\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18769882/"
] |
74,572,123
|
<p>I am confused about the differences between the useRef hook and a plain variable inside the component.</p>
<p>Am I right that every component renders, the plain variable also re-renders and persists its value, but the useRef just persists the value and does not re-render?</p>
<p>If that so, what would you recommend between the two?</p>
|
[
{
"answer_id": 74572224,
"author": "Mohammed Shahed",
"author_id": 19067773,
"author_profile": "https://Stackoverflow.com/users/19067773",
"pm_score": 2,
"selected": false,
"text": "useRef useRef useRef"
},
{
"answer_id": 74572283,
"author": "Oleg Brazhnichenko",
"author_id": 7028321,
"author_profile": "https://Stackoverflow.com/users/7028321",
"pm_score": 2,
"selected": false,
"text": "filteredData"
},
{
"answer_id": 74572370,
"author": "Vin Xi",
"author_id": 19450576,
"author_profile": "https://Stackoverflow.com/users/19450576",
"pm_score": 2,
"selected": true,
"text": "let a = 0;\nconst ref = useRef(0);\nconst [state,setState] = useState(0);\n const firstClick = () => {\n a = 2;\n ref.current = 2;\n}\n\nconst secondClick = () => {\n setState(2);\n}\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15958428/"
] |
74,572,140
|
<p>I've got a following table in csv:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Date</th>
<th>Results</th>
</tr>
</thead>
<tbody>
<tr>
<td>2015/09/01</td>
<td>1 811</td>
</tr>
<tr>
<td>2015/09/03</td>
<td>1 009</td>
</tr>
<tr>
<td>2015/09/20</td>
<td>1 889</td>
</tr>
<tr>
<td>2015/10/03</td>
<td>1 139</td>
</tr>
<tr>
<td>2015/10/06</td>
<td>1 275</td>
</tr>
</tbody>
</table>
</div>
<p>I would like to summarize values from "result" for each month and convert them into a bar chart.
I cannot find any sum function to fit my problem which can summarize by year and month ignoring days in the month.</p>
<p>I should look like this (except yellow bar):</p>
<p><img src="https://i.stack.imgur.com/UHd5D.png" alt="barchart" /></p>
|
[
{
"answer_id": 74572224,
"author": "Mohammed Shahed",
"author_id": 19067773,
"author_profile": "https://Stackoverflow.com/users/19067773",
"pm_score": 2,
"selected": false,
"text": "useRef useRef useRef"
},
{
"answer_id": 74572283,
"author": "Oleg Brazhnichenko",
"author_id": 7028321,
"author_profile": "https://Stackoverflow.com/users/7028321",
"pm_score": 2,
"selected": false,
"text": "filteredData"
},
{
"answer_id": 74572370,
"author": "Vin Xi",
"author_id": 19450576,
"author_profile": "https://Stackoverflow.com/users/19450576",
"pm_score": 2,
"selected": true,
"text": "let a = 0;\nconst ref = useRef(0);\nconst [state,setState] = useState(0);\n const firstClick = () => {\n a = 2;\n ref.current = 2;\n}\n\nconst secondClick = () => {\n setState(2);\n}\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20378645/"
] |
74,572,159
|
<p>I tried to convert PDF file that contains the data table to excel file.
Here is my cord.</p>
<pre><code>import tabula
# Read PDF File
df = tabula.read_pdf("files/Seniority List 2018 19.pdf", pages = 1)
# Convert into Excel File
df.to_excel('files/excel.xlsx')
</code></pre>
<p>but error occurred.</p>
<pre><code>AttributeError Traceback (most recent call last)
Input In [5], in <cell line: 9>()
6 df = tabula.read_pdf("files/Seniority List 2018 19.pdf", pages = 1)
8 # # Convert into Excel File
----> 9 df.to_excel('files/excel.xlsx')
AttributeError: 'list' object has no attribute 'to_excel'
</code></pre>
<p>PDF is from here
<a href="https://www.docdroid.net/jTWmB15/seniority-list-2018-19-pdf" rel="nofollow noreferrer">https://www.docdroid.net/jTWmB15/seniority-list-2018-19-pdf</a></p>
<p>How can I use 'to_excel'??</p>
<p>I just mentioned the above settings in this question but still if more code is required then tell me I'll update my question with that information. Thank you</p>
|
[
{
"answer_id": 74572224,
"author": "Mohammed Shahed",
"author_id": 19067773,
"author_profile": "https://Stackoverflow.com/users/19067773",
"pm_score": 2,
"selected": false,
"text": "useRef useRef useRef"
},
{
"answer_id": 74572283,
"author": "Oleg Brazhnichenko",
"author_id": 7028321,
"author_profile": "https://Stackoverflow.com/users/7028321",
"pm_score": 2,
"selected": false,
"text": "filteredData"
},
{
"answer_id": 74572370,
"author": "Vin Xi",
"author_id": 19450576,
"author_profile": "https://Stackoverflow.com/users/19450576",
"pm_score": 2,
"selected": true,
"text": "let a = 0;\nconst ref = useRef(0);\nconst [state,setState] = useState(0);\n const firstClick = () => {\n a = 2;\n ref.current = 2;\n}\n\nconst secondClick = () => {\n setState(2);\n}\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16122184/"
] |
74,572,165
|
<p>Hi i am trying to split the column<br />
Below is my df</p>
<pre><code>value = c("AB/cc/dd/id,1,3,33","CC/DD/EE/F,F/GG,22,33,4","AB/cc,22,2,34","KK/SS/G,G,3,22,41")
df = data.frame(value)
</code></pre>
<p>I am trying to split the column and get the string untill 3rd "comma(,)" from last<br />
i.e my output df should look like below</p>
<pre><code>value1 = c("AB/cc/dd/id","CC/DD/EE/F,F/GG","AB/cc","KK/SS/G,G")
df_out = data.frame(value1)
</code></pre>
<p>I used stringr package to get it done</p>
<pre><code>library(stringr)
df[c('col1', 'col2')] <- str_split_fixed(df$value, ',', 2)
</code></pre>
<p>Thanks in advance</p>
|
[
{
"answer_id": 74572351,
"author": "Ricardo Semião e Castro",
"author_id": 13048728,
"author_profile": "https://Stackoverflow.com/users/13048728",
"pm_score": 0,
"selected": false,
"text": "gsub gsub(\"[^[:alpha:],/]\", \"\", value) |> gsub(\",+$\", \"\", .)\n[1] \"AB/cc/dd/id\" \"CC/DD/EE/F,F/GG\" \"AB/cc\" \"KK/SS/G,G\"\n \"[^[:alpha:],/]\" [] ^ [:alpha:],/ \",+$\" , + $"
},
{
"answer_id": 74572955,
"author": "ThomasIsCoding",
"author_id": 12158757,
"author_profile": "https://Stackoverflow.com/users/12158757",
"pm_score": 0,
"selected": false,
"text": "gsub > gsub(\"(,[^,]+){3}$\", \"\", value)\n[1] \"AB/cc/dd/id\" \"CC/DD/EE/F,F/GG\" \"AB/cc\" \"KK/SS/G,G\"\n"
},
{
"answer_id": 74573254,
"author": "MarBlo",
"author_id": 4282026,
"author_profile": "https://Stackoverflow.com/users/4282026",
"pm_score": 1,
"selected": false,
"text": "a <- \"AB/cc/dd/id,1,/gg/,33\"\n\nstringr::str_extract(a, \".*(?=(\\\\,[/A-z0-9]+){3})\")\n#> [1] \"AB/cc/dd/id\"\n gsub(\"(\\\\,.*){3}$\", \"\", a)\n"
},
{
"answer_id": 74573327,
"author": "Abdur Rohman",
"author_id": 14812170,
"author_profile": "https://Stackoverflow.com/users/14812170",
"pm_score": 1,
"selected": false,
"text": "df$value |> \nstr_split(\",\") |> \nmap(function(x) x[1: (length(x)-3)] |> \nstr_c(collapse = \",\")) |> \nmap_df(as.data.frame) |> \nsetNames(\"value1\")\n\n# value1\n#1 AB/cc/dd/id\n#2 CC/DD/EE/F,F/GG\n#3 AB/cc\n#4 KK/SS/G,G\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9097114/"
] |
74,572,166
|
<p>I am developing a scala web application with http4s and use tapir for endpoints. I am new in it, and now I am looking for a better way to organize my project.</p>
<p>Now I have different classes with endpoints description and server logic in one. They have a java-spring-like name controller. For example:</p>
<pre><code>class SomeController[F[_] : MonadThrow] {
val something: ServerEndpoint[Any, F] =
endpoint
.description("Something")
.post
.in(query[String]("something"))
.out(jsonBody[String])
.errorOut(stringBody)
.serverLogicSuccess {
something => Monad[F].pure(something)
}
val allEndpoints: List[ServerEndpoint[Fs2Streams[F], F]] = List(resend)
}
</code></pre>
<p>And then collect them in one configuration, generate open api documentation and http routes. Configuration looks like this:</p>
<pre><code>object RoutesConfiguration {
private val endpoints: List[ServerEndpoint[Fs2Streams[IO], IO]] = new SomeController[IO].allEndpoints
private val openApi: List[ServerEndpoint[Any, IO]] =
SwaggerInterpreter()
.fromEndpoints(endpoints.map(_.endpoint), "Something", "1.0")
val routes: HttpRoutes[IO] = Http4sServerInterpreter[IO]().toRoutes(List(openApi, endpoints).flatten)
}
</code></pre>
<p>Is it better to separate endpoints description and server logic? Are there better ways to organize endpoints?</p>
|
[
{
"answer_id": 74572351,
"author": "Ricardo Semião e Castro",
"author_id": 13048728,
"author_profile": "https://Stackoverflow.com/users/13048728",
"pm_score": 0,
"selected": false,
"text": "gsub gsub(\"[^[:alpha:],/]\", \"\", value) |> gsub(\",+$\", \"\", .)\n[1] \"AB/cc/dd/id\" \"CC/DD/EE/F,F/GG\" \"AB/cc\" \"KK/SS/G,G\"\n \"[^[:alpha:],/]\" [] ^ [:alpha:],/ \",+$\" , + $"
},
{
"answer_id": 74572955,
"author": "ThomasIsCoding",
"author_id": 12158757,
"author_profile": "https://Stackoverflow.com/users/12158757",
"pm_score": 0,
"selected": false,
"text": "gsub > gsub(\"(,[^,]+){3}$\", \"\", value)\n[1] \"AB/cc/dd/id\" \"CC/DD/EE/F,F/GG\" \"AB/cc\" \"KK/SS/G,G\"\n"
},
{
"answer_id": 74573254,
"author": "MarBlo",
"author_id": 4282026,
"author_profile": "https://Stackoverflow.com/users/4282026",
"pm_score": 1,
"selected": false,
"text": "a <- \"AB/cc/dd/id,1,/gg/,33\"\n\nstringr::str_extract(a, \".*(?=(\\\\,[/A-z0-9]+){3})\")\n#> [1] \"AB/cc/dd/id\"\n gsub(\"(\\\\,.*){3}$\", \"\", a)\n"
},
{
"answer_id": 74573327,
"author": "Abdur Rohman",
"author_id": 14812170,
"author_profile": "https://Stackoverflow.com/users/14812170",
"pm_score": 1,
"selected": false,
"text": "df$value |> \nstr_split(\",\") |> \nmap(function(x) x[1: (length(x)-3)] |> \nstr_c(collapse = \",\")) |> \nmap_df(as.data.frame) |> \nsetNames(\"value1\")\n\n# value1\n#1 AB/cc/dd/id\n#2 CC/DD/EE/F,F/GG\n#3 AB/cc\n#4 KK/SS/G,G\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20595039/"
] |
74,572,195
|
<p>I can compare the length but, I can't return mismatch value.</p>
<pre class="lang-js prettyprint-override"><code>var str1 ="zoho";
var str2 ="zogo";
//find the mismatched one
let output = hg;
let names = "zoho";
let nam2= "zogo"
let rest = names.match(nam2)
console.log(rest);
</code></pre>
|
[
{
"answer_id": 74572340,
"author": "Mina",
"author_id": 11887902,
"author_profile": "https://Stackoverflow.com/users/11887902",
"pm_score": 1,
"selected": false,
"text": "length const findDifference = (first, second) => {\n let diff = ''\n for (let i = 0; i < first.length; i++) {\n if (first[i] !== second[i]) {\n diff += first[i] + second[i];\n }\n }\n return diff\n}\n\nconsole.log(findDifference('zoho', 'zogo'));"
},
{
"answer_id": 74572559,
"author": "Sedat Polat",
"author_id": 668572,
"author_profile": "https://Stackoverflow.com/users/668572",
"pm_score": 1,
"selected": true,
"text": "const findDifference = (str1, str2) => {\n let result = \"\";\n if (str1.length >= str2.length) {\n str1.split(\"\").forEach((char, index) => {\n if (char!=str2[index]) {\n result = result + char + (str2[index] || '');\n }\n });\n } else {\n str2.split(\"\").forEach((char, index) => {\n if (char!=str1[index]) {\n result = result + (str1[index] || \"\") + char;\n }\n });\n }\n return result;\n}\n \nconsole.log(findDifference(\"zoho\", \"zogo\"));\nconsole.log(findDifference(\"zohox\", \"zogo\"));\nconsole.log(findDifference(\"zoho\", \"zogox\"));\nconsole.log(findDifference(\"zoho\", \"\"));\nconsole.log(findDifference(\"\", \"zogo\")); hg hgx hgx zoho zogo"
},
{
"answer_id": 74574224,
"author": "Rohìt Jíndal",
"author_id": 4116300,
"author_profile": "https://Stackoverflow.com/users/4116300",
"pm_score": 0,
"selected": false,
"text": "var str1 =\"zoho\";\nvar str2 =\"zogo\";\n\nlet differenceValue = '';\n\nArray(Math.max(str1.length, str2.length)).fill().forEach((v, index) => {\n if (str1[index] !== str2[index]) {\n differenceValue += (str1[index] ?? '') + (str2[index] ?? '');\n }\n})\n\nconsole.log(differenceValue);"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20598739/"
] |
74,572,209
|
<p><a href="https://i.stack.imgur.com/KWXAV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KWXAV.png" alt="enter image description here" /></a></p>
<p>Hi all,</p>
<p>I have a table as shown in the screenshot above. I wrote a query using <code>CASE</code> statement so that it will return extra columns that I need. Below is the query that I wrote:</p>
<pre><code>SELECT
*,
CASE WHEN (SUM(CASE WHEN class = 'class 1' THEN 1 END) OVER(PARTITION BY student_id)) >= 1 THEN 1 ELSE 0 END AS 'Class 1',
CASE WHEN (SUM(CASE WHEN class = 'class 2' THEN 1 END) OVER(PARTITION BY student_id)) >= 1 THEN 1 ELSE 0 END AS 'Class 2',
CASE WHEN (SUM(CASE WHEN class = 'class 3' THEN 1 END) OVER(PARTITION BY student_id)) >= 1 THEN 1 ELSE 0 END AS 'Class 3',
CASE WHEN (SUM(CASE WHEN class = 'class 4' THEN 1 END) OVER(PARTITION BY student_id)) >= 1 THEN 1 ELSE 0 END AS 'Class 4'
FROM qa;
</code></pre>
<p>This is the result table that I get:</p>
<p><a href="https://i.stack.imgur.com/iJ1sk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iJ1sk.png" alt="enter image description here" /></a></p>
<p>What I want to achieve in this query is, if the student attended the class, it will show <code>1</code> under the column of the class for all the rows belong to that student.</p>
<p>For example, student with <code>student_id</code> <code>2</code> attended <code>class 1</code>, so under <code>Class 1</code> column, both rows for <code>student_id</code> <code>2</code> will show <code>1</code>.</p>
<p>I already achieved what I want in my query, but right now instead of using <code>1</code>, I want it to be the <code>enrollment_date</code> of the class. Below is the final output that I want:</p>
<p><a href="https://i.stack.imgur.com/88YgO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/88YgO.png" alt="enter image description here" /></a></p>
<p>May I know how should I modify my query to get the final output in the screenshot above?</p>
<p><strong>2nd Question:</strong></p>
<p>As you can see in my query above, every class is having one <code>CASE</code> statement respectively in order to create the column for the class. However, there might be Class 5,6,7,... in future, so I need to add in the extra <code>CASE</code> statement again whenever there is different new class exist. Is there anyway that I can optimize my query so that there is no need to have 4 <code>CASE</code> statement for 4 different classes, and yet still can create columns for different classes (when there is a new class, there will be new column for the class as well)?</p>
<h2>Sample Data</h2>
<pre><code>create table qa(
student_id INT,
class varchar(20),
class_end_date date,
enrollment_date date
);
insert into qa (student_id, class, class_end_date, enrollment_date)
values
(1, 'class 1', '2022-03-03', '2022-02-14'),
(1, 'class 3', '2022-06-13', '2022-04-12'),
(1, 'class 4', '2022-07-03', '2022-06-19'),
(2, 'class 1', '2023-03-03', '2022-07-14'),
(2, 'class 2', '2022-08-03', '2022-07-17'),
(4, 'class 4', '2023-03-03', '2022-012-14'),
(4, 'class 2', '2022-04-03', '2022-03-21')
;
</code></pre>
|
[
{
"answer_id": 74576372,
"author": "nnichols",
"author_id": 1191247,
"author_profile": "https://Stackoverflow.com/users/1191247",
"pm_score": 2,
"selected": true,
"text": "SELECT \n student_id,\n GROUP_CONCAT(IF(class = 'class 1', enrollment_date, null)) 'Class 1 Enrolled',\n GROUP_CONCAT(IF(class = 'class 1', class_end_date, null)) 'Class 1 End',\n GROUP_CONCAT(IF(class = 'class 2', enrollment_date, null)) 'Class 2 Enrolled',\n GROUP_CONCAT(IF(class = 'class 2', class_end_date, null)) 'Class 2 End',\n GROUP_CONCAT(IF(class = 'class 3', enrollment_date, null)) 'Class 3 Enrolled',\n GROUP_CONCAT(IF(class = 'class 3', class_end_date, null)) 'Class 3 End',\n GROUP_CONCAT(IF(class = 'class 4', enrollment_date, null)) 'Class 4 Enrolled',\n GROUP_CONCAT(IF(class = 'class 4', class_end_date, null)) 'Class 4 End'\nFROM qa\nGROUP BY student_id;\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15002748/"
] |
74,572,221
|
<p>I've been running into some issues involving React and React Router Dom. For some reason, nothing is showing when I us the nom start command. The browser window opens, but it just display a white screen. Nothing I do seems to work. I think it has something to do with my navigation bar.</p>
<p>My code is as follows:</p>
<p>index.js</p>
<pre><code>import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
</code></pre>
<p>App.js</p>
<pre><code>import { Route, BrowserRouter, Routes } from 'react-router-dom';
import './App.css';
import Navbar from './Components/Navbar';
import Home from './Pages/Home';
import Team from './Pages/Team';
import Demo from './Pages/Demo';
import Footer from './Components/Footer'
function App() {
return (
<>
<BrowserRouter>
<Navbar />
<Routes>
<Route path='/' element={<Home />}/>
<Route path='/team' element={<Team />}/>
<Route path='/demo' element={<Demo />}/>
</Routes>
<Footer />
</BrowserRouter>
</>
);
}
export default App;
</code></pre>
<p>Navbar.js</p>
<pre><code>import React from 'react';
import logo from '../Media/eclipse.png';
import { Link } from 'react-router-dom';
const Navbar = () => {
return (
<div>
<div id="navbar" className="fixed top-0 left-0 right-0 z-50">
<nav className="p-3 bg-transparent md:flex md:items-center
md:justify-between border-0
z-50 max-h-16">
<header className="flex justify-between items-center">
<span className="text-2xl font-bold cursor-pointer">
<img className="h-12 mb-1 inline md:ml-12" src={logo}></img>
<h1 className="pt-5 inline"><a href="#page-1"></a></h1>
</span>
<span className="text-3xl cursor-pointer md:hidden block">
<ion-icon name="menu" onclick="Menu(this)" className="text-white"></ion-icon>
</span>
</header>
<ul className=" list-none md:flex md:items-center z-[-1] md:z-auto md:static absolute
w-full left-0 md:w-auto md:py-0 py-4 md:pl-0 pl-7 md:opacity-100 opacity-0 top-[-400px] transition-all
ease-in duration-500 bg-white md:bg-transparent">
<li className="mx-4 my-6 md:my-0">
<Link to="/" className="text-xl hover:text-orange-500 duration-500 md:text-white text-black
hover:underline">Home</Link>
</li>
<li className="mx-4 my-6 md:my-0">
<Link to="/teams" className="text-xl hover:text-orange-500 duration-500 md:text-white text-black
hover:underline">Team</Link>
</li>
<li className="mx-4 my-6 md:my-0 rounded-xl text-black px-5 flex items-center bg-black">
<Link to="/demopage.html" className="text-xl hover:text-orange-100 text-white
duration-500">Demo</Link>
</li>
</ul>
</nav>
</div>
</div>
)
}
function Menu(e) {
let list = document.querySelector('ul');
e.name === 'menu' ? (e.name = "close", list.classList.add('top-[80px]'), list.classList.add('opacity-100')) : (e.name = "menu", list.classList.remove('top-[80px]'), list.classList.remove('opacity-100'))
}
export default Navbar
</code></pre>
<p>Footer.js</p>
<pre><code>import React from 'react'
const Footer = () => {
return (
<div>Footer</div>
)
}
export default Footer
</code></pre>
<p>Home.js</p>
<pre><code>import React from 'react'
const Home = () => {
return (
<div>
<div className='h-screen w-full bg-neutral-900'>
<div id='landing-page-1'>
<div className='grid grid-cols-12 grid-row-6'>
<div className='col-start-2 col-end-8 row-start-1 row-end-2'>Optimization of Cards</div>
<div className='col-start-8 col-end-11 row-start-1 row-end-2'> Things go here</div>
</div>
</div>
<div id='info-page-2'></div>
<div id='info-page-3'></div>
</div>
</div>
)
}
export default Home
</code></pre>
<p>Team.js</p>
<pre><code>import React from 'react'
const Team = () => {
return (
<div>Team</div>
)
}
export default Team
</code></pre>
<p>Demo.js</p>
<pre><code>import React from 'react'
const Demo = () => {
return (
<div>Demo</div>
)
}
export default Demo
</code></pre>
|
[
{
"answer_id": 74572342,
"author": "oykn",
"author_id": 18080318,
"author_profile": "https://Stackoverflow.com/users/18080318",
"pm_score": 0,
"selected": false,
"text": " import { BrowserRouter } from 'react-router-dom';\n const root = ReactDOM.createRoot(\n document.getElementById('root') as HTMLElement\n);\nroot.render(\n <BrowserRouter>\n <React.StrictMode>\n <App />\n </React.StrictMode>\n </BrowserRouter>\n);\n\nreportWebVitals();\n"
},
{
"answer_id": 74572346,
"author": "Oleg Brazhnichenko",
"author_id": 7028321,
"author_profile": "https://Stackoverflow.com/users/7028321",
"pm_score": 1,
"selected": false,
"text": "const root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(\n <React.StrictMode>\n <App />\n </React.StrictMode>\n);\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13294972/"
] |
74,572,244
|
<p><a href="https://i.stack.imgur.com/THaB8.png" rel="nofollow noreferrer">enter image description here</a>[<a href="https://i.stack.imgur.com/Ba4ld.png" rel="nofollow noreferrer">enter image description here</a>](<a href="https://i.stack.imgur.com/HxY0x.png" rel="nofollow noreferrer">https://i.stack.imgur.com/HxY0x.png</a>)</p>
<p>im new to the mobile development can anyone pleased tell me where did i do wrong?<br />
im trying to access to the list inside the map</p>
|
[
{
"answer_id": 74572342,
"author": "oykn",
"author_id": 18080318,
"author_profile": "https://Stackoverflow.com/users/18080318",
"pm_score": 0,
"selected": false,
"text": " import { BrowserRouter } from 'react-router-dom';\n const root = ReactDOM.createRoot(\n document.getElementById('root') as HTMLElement\n);\nroot.render(\n <BrowserRouter>\n <React.StrictMode>\n <App />\n </React.StrictMode>\n </BrowserRouter>\n);\n\nreportWebVitals();\n"
},
{
"answer_id": 74572346,
"author": "Oleg Brazhnichenko",
"author_id": 7028321,
"author_profile": "https://Stackoverflow.com/users/7028321",
"pm_score": 1,
"selected": false,
"text": "const root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(\n <React.StrictMode>\n <App />\n </React.StrictMode>\n);\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20598850/"
] |
74,572,250
|
<p>I'm trying to split a string ultimately into a 2D array with a semi colon as a delimiter.</p>
<pre><code>var str = "2;poisson
poisson
3; Fromage
6;Monique"
</code></pre>
<p>to</p>
<pre><code>var arr = [2, "poisson
poisson"],
[3," Fromage"],
[6,"Monique"]
</code></pre>
<p>The array is in the format</p>
<pre><code>[int, string that may start with white space and may end with possible new lines]
</code></pre>
<p>The first step would be via regex. However, using <code>(\d+\;\s?)(.)+</code> doesn't grab lines with a new line. <a href="https://regex101.com/r/aLvoAL/1" rel="nofollow noreferrer">Regex101</a>.</p>
<p>I'm a little confused as to how to proceed as the newlines/carriage returns are important and I don't want to lose them. My RegEx Fu is weak today.</p>
|
[
{
"answer_id": 74572396,
"author": "The fourth bird",
"author_id": 5424988,
"author_profile": "https://Stackoverflow.com/users/5424988",
"pm_score": 2,
"selected": false,
"text": "\\b(\\d+);([^]+?)(?=\\n\\s*\\d+;|$)\n \\b (\\d+); ; ( [^]+? ) (?= \\n\\s*\\d+;|$ ) const str = `2;poisson\n poisson\n 3; Fromage\n 6;Monique`;\n\n\nconst regex = /\\b(\\d+);([^]+?)(?=\\n\\s*\\d+;|$)/g;\nconsole.log(Array.from(str.matchAll(regex), m => [m[1], m[2]]))"
},
{
"answer_id": 74577494,
"author": "Peter Thoeny",
"author_id": 7475450,
"author_profile": "https://Stackoverflow.com/users/7475450",
"pm_score": 0,
"selected": false,
"text": ".split() const str = `2;poisson\n poisson\n3; Fromage\n6;Monique`;\nlet result = str.split(/\\n(?! )/).map(line => line.split(/;/));\nconsole.log(JSON.stringify(result)); [[\"2\",\"poisson\\n poisson\"],[\"3\",\" Fromage\"],[\"6\",\"Monique\"]]\n \\n [\\r\\n]+ (?! )"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1654143/"
] |
74,572,269
|
<p>I'm taking an IONIC + Angular course, and I'm having a little problem uploading the apk project to my cell phone, I'm using cordova.
As soon as I connect the cell to the computer and it's time to run the command "ionic cordova run android" it gives some errors, it could be the versions that I have installed on my computer, but I don't have enough knowledge to be sure of that, could help me?</p>
<p>1
<a href="https://i.stack.imgur.com/NkcfY.png" rel="nofollow noreferrer">enter image description here</a>
2
<a href="https://i.stack.imgur.com/XkJci.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>I've tried to run several commands that I've searched on the net but I haven't had good results, it hangs at the very end</p>
<p>I looked for some solutions on the net but it still doesn't work, I think it's something related to the installed versions</p>
|
[
{
"answer_id": 74577290,
"author": "João Marcos Saol",
"author_id": 18373464,
"author_profile": "https://Stackoverflow.com/users/18373464",
"pm_score": 1,
"selected": false,
"text": "ANDROID_SDK_ROOT=/home/username/Android/Sdk (recommended setting)\nANDROID_HOME=/home/username/Android/Sdk (DEPRECATED)\n export ANDROID_SDK_ROOT=$HOME/Android/Sdk\nexport PATH=$PATH:$ANDROID_SDK_ROOT/tools/bin\nexport PATH=$PATH:$ANDROID_SDK_ROOT/platform-tools\nexport PATH=$PATH:$ANDROID_SDK_ROOT/emulator\nexport PATH=$PATH:$ANDROID_SDK_ROOT/build-tools\n source ~/.bashrc\n source ~/.bash_profile\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13764317/"
] |
74,572,294
|
<p>We're in the process of replacing our custom react components with components from the company's design system.
These are web-components and it has been made a react-wrapper to make them work in React.</p>
<p>The element is rendered like this in our app:</p>
<pre><code><custom-button title="" data-test-id="save" disabled mode="primary">
#shadow-root
<button data-mode="primary" size="small" type="button" title="" disabled>Save</button>
</custom-button>
</code></pre>
<p>In Cypress I have tried to check if it is disabled like so:</p>
<pre><code>cy.getByTestId('save').should('be.disabled'); //Doesn't work, but its the way I want to do it
cy.getByTestId('save').find('button').should('be.disabled'); // Works
</code></pre>
<p>The first way doesn't work but its the way i want to do it because thats how all our tests work today.
I want to having having to do the second way because that means we have to handle buttons from our design-system different from regular buttons.</p>
<p>Does anyone know why the first way doesnt work? Even though the <code><custom-button></code> has the <code>disabled</code> attribute applied to it in the DOM?</p>
|
[
{
"answer_id": 74575623,
"author": "jjhelguero",
"author_id": 17917809,
"author_profile": "https://Stackoverflow.com/users/17917809",
"pm_score": 0,
"selected": false,
"text": "custom-button button disabled cy.getByTestId('save').find('button').should('be.disabled')\ncy.getByTestId('save').contains(/save/i).should('be.disabled') // find based on text instead\n"
},
{
"answer_id": 74577297,
"author": "Fody",
"author_id": 16997707,
"author_profile": "https://Stackoverflow.com/users/16997707",
"pm_score": 3,
"selected": true,
"text": "attribute property cy.getByTestId('save').should('be.disabled') disabled disabled custom-button button cy.getByTestId('save').should('have.attr', 'disabled')\n custom-button button cy.getByTestId('save').should($el => {\n return $el.attr('disabled').length > 0 || $el.prop('disabled').length > 0\n})\n .find('button') custom-button"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4533252/"
] |
74,572,373
|
<p>I have the following Array of objects:</p>
<pre><code>let objOperacion = [
{
"OPERACION": {
"ID_OP": 1
},
"GEOJSON": [
{
"type": "Feature",
"properties": {
"ID": 40,
"SUPERFICIE": 572.7
},
}
]
},
{
"OPERACION": {
"ID_OP": 2
},
"GEOJSON": [
{
"type": "Feature",
"properties": {
"ID": 41,
"SUPERFICIE": 572.7
},
}
]
},
{
"OPERACION": {
"ID_OP": 1
},
"GEOJSON": [
{
"type": "Feature",
"properties": {
"ID": 42,
"SUPERFICIE": 572.7
},
}
]
}
]
</code></pre>
<p>I have created a function that when passing an id as parameter, it takes all the objects that have the same id.</p>
<p>I have done it in the following way:</p>
<pre><code>for (var i = 0; i < objOperacion.length; i++) {
if (id === objOperacion[i].feature.properties.ID) {
objOperacion[i].setStyle(styleWorking);
console.log("SAME ID");
} else {
objOperacion[i].setStyle(style);
console.log("DIFFERENT");
}
}
</code></pre>
<p>What I am trying to do is to create another function to catch objects that have the same "ID_OP". But I can't get it.</p>
|
[
{
"answer_id": 74575623,
"author": "jjhelguero",
"author_id": 17917809,
"author_profile": "https://Stackoverflow.com/users/17917809",
"pm_score": 0,
"selected": false,
"text": "custom-button button disabled cy.getByTestId('save').find('button').should('be.disabled')\ncy.getByTestId('save').contains(/save/i).should('be.disabled') // find based on text instead\n"
},
{
"answer_id": 74577297,
"author": "Fody",
"author_id": 16997707,
"author_profile": "https://Stackoverflow.com/users/16997707",
"pm_score": 3,
"selected": true,
"text": "attribute property cy.getByTestId('save').should('be.disabled') disabled disabled custom-button button cy.getByTestId('save').should('have.attr', 'disabled')\n custom-button button cy.getByTestId('save').should($el => {\n return $el.attr('disabled').length > 0 || $el.prop('disabled').length > 0\n})\n .find('button') custom-button"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19672488/"
] |
74,572,379
|
<p>I have a list of residents who have different professions including being a student. However, some have written “Student” or “Overseas Student” or something else with the word student in it. I would like Power Query to search the column for any cell containing “Student” and replace it with “Student” so it removes any other references. Please can someone help?</p>
<p>I have tried to write the formula but no it have been successful.</p>
|
[
{
"answer_id": 74575623,
"author": "jjhelguero",
"author_id": 17917809,
"author_profile": "https://Stackoverflow.com/users/17917809",
"pm_score": 0,
"selected": false,
"text": "custom-button button disabled cy.getByTestId('save').find('button').should('be.disabled')\ncy.getByTestId('save').contains(/save/i).should('be.disabled') // find based on text instead\n"
},
{
"answer_id": 74577297,
"author": "Fody",
"author_id": 16997707,
"author_profile": "https://Stackoverflow.com/users/16997707",
"pm_score": 3,
"selected": true,
"text": "attribute property cy.getByTestId('save').should('be.disabled') disabled disabled custom-button button cy.getByTestId('save').should('have.attr', 'disabled')\n custom-button button cy.getByTestId('save').should($el => {\n return $el.attr('disabled').length > 0 || $el.prop('disabled').length > 0\n})\n .find('button') custom-button"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20598989/"
] |
74,572,397
|
<p>The problem started when I needed to apply conditional formatting to a table with smooth color changes in MS SQL Server Reporting Services (SSRS). It is impossible with standard SSRS functionality. But you can use the table data to smoothly change the color with the Lightness parameter in the HSL color model.</p>
<p>The question is, how to convert HSL to usable in SSRS HEX or RGB color codes using SQL.</p>
<p>No answers were found at Stackoverflow or anywhere else, only for other programming languages</p>
|
[
{
"answer_id": 74572580,
"author": "Roman Udaltsov",
"author_id": 6773185,
"author_profile": "https://Stackoverflow.com/users/6773185",
"pm_score": 0,
"selected": false,
"text": "create function dbo.f_convertHSL (\n @HueDegree numeric(3,0), \n @Saturation numeric(6,3), \n @Lightness numeric(6,3), \n @Format varchar(3) )\nreturns varchar(100)\nas\n\nbegin\n\n declare @HuePercent numeric(6,3),\n @Red numeric(6,3), \n @Green numeric(6,3), \n @Blue numeric(6,3),\n @Temp1 numeric(6,3), \n @Temp2 numeric(6,3),\n @TempR numeric(6,3),\n @TempG numeric(6,3),\n @TempB numeric(6,3), \n @Result varchar(100);\n\n if @Saturation = 0 \n begin\n select @Red = @Lightness * 255,\n @Green = @Lightness * 255,\n @Blue = @Lightness * 255;\n\n if @Format = 'RGB'\n select @Result = cast(cast(@Red as int) as varchar) + ', '\n + cast(cast(@Green as int) as varchar) + ', '\n + cast(cast(@Blue as int) as varchar);\n else if @Format = 'HEX'\n select @Result = '#' + convert(varchar(2), convert(varbinary(1), cast(@Red as int)), 2)\n + convert(varchar(2), convert(varbinary(1), cast(@Green as int)), 2)\n + convert(varchar(2), convert(varbinary(1), cast(@Blue as int)), 2);\n else select @Result = 'Format should be RGB or HEX';\n\n return @Result;\n end;\n\n if @Lightness < 0.5\n select @Temp1 = @Lightness * (1 + @Saturation);\n else\n select @Temp1 = @Lightness + @Saturation - @Lightness * @Saturation;\n\n select @Temp2 = 2 * @Lightness - @Temp1\n , @HuePercent = @HueDegree / 360.0;\n\n select @TempR = @HuePercent + 0.333\n , @TempG = @HuePercent\n , @TempB = @HuePercent - 0.333;\n\n if @TempR < 0 select @TempR = @TempR + 1;\n if @TempR > 1 select @TempR = @TempR - 1;\n if @TempG < 0 select @TempG = @TempG + 1;\n if @TempG > 1 select @TempG = @TempG - 1;\n if @TempB < 0 select @TempB = @TempB + 1;\n if @TempB > 1 select @TempB = @TempB - 1;\n\n if @TempR * 6 < 1 select @Red = @Temp2 + (@Temp1 - @Temp2) * 6 * @TempR\n else if @TempR * 2 < 1 select @Red = @Temp1\n else if @TempR * 3 < 2 select @Red = @Temp2 + (@Temp1 - @Temp2) * (0.666 - @TempR) * 6\n else select @Red = @Temp2;\n\n if @TempG * 6 < 1 select @Green = @Temp2 + (@Temp1 - @Temp2) * 6 * @TempG\n else if @TempG * 2 < 1 select @Green = @Temp1\n else if @TempG * 3 < 2 select @Green = @Temp2 + (@Temp1 - @Temp2) * (0.666 - @TempG) * 6\n else select @Green = @Temp2;\n\n if @TempB * 6 < 1 select @Blue = @Temp2 + (@Temp1 - @Temp2) * 6 * @TempB\n else if @TempB * 2 < 1 select @Blue = @Temp1\n else if @TempB * 3 < 2 select @Blue = @Temp2 + (@Temp1 - @Temp2) * (0.666 - @TempB) * 6\n else select @Blue = @Temp2;\n\n select @Red = round(@Red * 255, 0),\n @Green = round(@Green * 255, 0),\n @Blue = round(@Blue * 255, 0);\n\n if @Format = 'RGB'\n select @Result = cast(cast(@Red as int) as varchar) + ', '\n + cast(cast(@Green as int) as varchar) + ', '\n + cast(cast(@Blue as int) as varchar);\n else if @Format = 'HEX'\n select @Result = '#' + convert(varchar(2), convert(varbinary(1), cast(@Red as int)), 2)\n + convert(varchar(2), convert(varbinary(1), cast(@Green as int)), 2)\n + convert(varchar(2), convert(varbinary(1), cast(@Blue as int)), 2);\n else select @Result = 'Format should be RGB or HEX';\n\n return @Result;\n\nend;\n select dbo.f_convertHSL(24, 0.83, 0.74, 'RGB')\nresult: 244, 178, 134\n select dbo.f_convertHSL(24, 0.83, 0.74, 'HEX')\nresult: #F4B286\n"
},
{
"answer_id": 74573743,
"author": "Larnu",
"author_id": 2029983,
"author_profile": "https://Stackoverflow.com/users/2029983",
"pm_score": 2,
"selected": true,
"text": "CREATE OR ALTER FUNCTION dbo.HSLtoRGB (@H numeric(3,0),@S numeric(4,3), @L numeric(4,3)) \nRETURNS table\nAS RETURN\n SELECT CONVERT(tinyint,ROUND((RGB1.R1+m.m)*255,0)) AS R,\n CONVERT(tinyint,ROUND((RGB1.G1+m.m)*255,0)) AS G,\n CONVERT(tinyint,ROUND((RGB1.B1+m.m)*255,0)) AS B\n FROM (VALUES(@H, @S, @L))HSL(Hue,Saturation,Lightness)\n CROSS APPLY(VALUES((1-ABS((2*HSL.Lightness - 1))) * HSL.Saturation)) C(Chroma)\n CROSS APPLY(VALUES(HSL.Hue/60,C.Chroma * (1 - ABS((HSL.Hue/60) % 2 - 1))))H([H`],X)\n CROSS APPLY(SELECT TOP (1) * --It's unlikely there would be 2 rows, but just incase limit to 1\n FROM (VALUES(C.Chroma,H.X,0,0,1),\n (H.X,C.Chroma,0,1,2),\n (0,C.Chroma,H.X,2,3),\n (0,H.X,C.Chroma,3,4),\n (H.X,0,C.Chroma,4,5),\n (C.Chroma,0,H.X,5,6))V(R1,G1,B1,S,E)\n WHERE V.S <= H.[H`] AND H.[H`] <= V.E\n ORDER BY V.E DESC) RGB1 \n CROSS APPLY (VALUES(HSL.Lightness - (C.Chroma / 2)))m(m);\nGO\nCREATE OR ALTER FUNCTION dbo.HSLtoRGB_HEX (@H numeric(3,0),@S numeric(4,3), @L numeric(4,3)) \nRETURNS table\nAS RETURN\n SELECT CONVERT(binary(3),CONCAT(CONVERT(varchar(2),CONVERT(binary(1),CONVERT(tinyint,ROUND((RGB1.R1+m.m)*255,0))),2),\n CONVERT(varchar(2),CONVERT(binary(1),CONVERT(tinyint,ROUND((RGB1.G1+m.m)*255,0))),2),\n CONVERT(varchar(2),CONVERT(binary(1),CONVERT(tinyint,ROUND((RGB1.B1+m.m)*255,0))),2)),2) AS RGB\n FROM (VALUES(@H, @S, @L))HSL(Hue,Saturation,Lightness)\n CROSS APPLY(VALUES((1-ABS((2*HSL.Lightness - 1))) * HSL.Saturation)) C(Chroma)\n CROSS APPLY(VALUES(HSL.Hue/60,C.Chroma * (1 - ABS((HSL.Hue/60) % 2 - 1))))H([H`],X)\n CROSS APPLY(SELECT TOP(1) * --It's unlikely there would be 2 rows, but just incase limit to 1\n FROM (VALUES(C.Chroma,H.X,0,0,1),\n (H.X,C.Chroma,0,1,2),\n (0,C.Chroma,H.X,2,3),\n (0,H.X,C.Chroma,3,4),\n (H.X,0,C.Chroma,4,5),\n (C.Chroma,0,H.X,5,6))V(R1,G1,B1,S,E)\n WHERE V.S <= H.[H`] AND H.[H`] <= V.E\n ORDER BY V.E DESC) RGB1\n CROSS APPLY (VALUES(HSL.Lightness - (C.Chroma / 2)))m(m);\nGO\n\nSELECT *\nFROM (VALUES(210,.79,.3),\n (24,.83,.74),\n (360,1,1),\n (0,0,0))V(H,S,L)\n CROSS APPLY dbo.HSLtoRGB(V.H, V.S, V.L) RGB\n CROSS APPLY dbo.HSLtoRGB_Hex(V.H, V.S, V.L) RGBhex;\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6773185/"
] |
74,572,412
|
<p>I wanted to develop a Sudoku app. I have created a list for all positions in the game field. To display the fields I used a grid view. However, I have the problem that white lines appear in the grid view and I don't understand why. In the attached image you can see this in more detail.</p>
<p>Here is my code for the grid view:</p>
<pre><code> GridView.builder(
itemCount: gameFields.length,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 9,
),
itemBuilder: (context, index) => Container(
color: Colors.lightGreen,
child: Center(
child: Text("${index + 1}"),
),
),
);
</code></pre>
<p><a href="https://i.stack.imgur.com/mNtzk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mNtzk.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74572580,
"author": "Roman Udaltsov",
"author_id": 6773185,
"author_profile": "https://Stackoverflow.com/users/6773185",
"pm_score": 0,
"selected": false,
"text": "create function dbo.f_convertHSL (\n @HueDegree numeric(3,0), \n @Saturation numeric(6,3), \n @Lightness numeric(6,3), \n @Format varchar(3) )\nreturns varchar(100)\nas\n\nbegin\n\n declare @HuePercent numeric(6,3),\n @Red numeric(6,3), \n @Green numeric(6,3), \n @Blue numeric(6,3),\n @Temp1 numeric(6,3), \n @Temp2 numeric(6,3),\n @TempR numeric(6,3),\n @TempG numeric(6,3),\n @TempB numeric(6,3), \n @Result varchar(100);\n\n if @Saturation = 0 \n begin\n select @Red = @Lightness * 255,\n @Green = @Lightness * 255,\n @Blue = @Lightness * 255;\n\n if @Format = 'RGB'\n select @Result = cast(cast(@Red as int) as varchar) + ', '\n + cast(cast(@Green as int) as varchar) + ', '\n + cast(cast(@Blue as int) as varchar);\n else if @Format = 'HEX'\n select @Result = '#' + convert(varchar(2), convert(varbinary(1), cast(@Red as int)), 2)\n + convert(varchar(2), convert(varbinary(1), cast(@Green as int)), 2)\n + convert(varchar(2), convert(varbinary(1), cast(@Blue as int)), 2);\n else select @Result = 'Format should be RGB or HEX';\n\n return @Result;\n end;\n\n if @Lightness < 0.5\n select @Temp1 = @Lightness * (1 + @Saturation);\n else\n select @Temp1 = @Lightness + @Saturation - @Lightness * @Saturation;\n\n select @Temp2 = 2 * @Lightness - @Temp1\n , @HuePercent = @HueDegree / 360.0;\n\n select @TempR = @HuePercent + 0.333\n , @TempG = @HuePercent\n , @TempB = @HuePercent - 0.333;\n\n if @TempR < 0 select @TempR = @TempR + 1;\n if @TempR > 1 select @TempR = @TempR - 1;\n if @TempG < 0 select @TempG = @TempG + 1;\n if @TempG > 1 select @TempG = @TempG - 1;\n if @TempB < 0 select @TempB = @TempB + 1;\n if @TempB > 1 select @TempB = @TempB - 1;\n\n if @TempR * 6 < 1 select @Red = @Temp2 + (@Temp1 - @Temp2) * 6 * @TempR\n else if @TempR * 2 < 1 select @Red = @Temp1\n else if @TempR * 3 < 2 select @Red = @Temp2 + (@Temp1 - @Temp2) * (0.666 - @TempR) * 6\n else select @Red = @Temp2;\n\n if @TempG * 6 < 1 select @Green = @Temp2 + (@Temp1 - @Temp2) * 6 * @TempG\n else if @TempG * 2 < 1 select @Green = @Temp1\n else if @TempG * 3 < 2 select @Green = @Temp2 + (@Temp1 - @Temp2) * (0.666 - @TempG) * 6\n else select @Green = @Temp2;\n\n if @TempB * 6 < 1 select @Blue = @Temp2 + (@Temp1 - @Temp2) * 6 * @TempB\n else if @TempB * 2 < 1 select @Blue = @Temp1\n else if @TempB * 3 < 2 select @Blue = @Temp2 + (@Temp1 - @Temp2) * (0.666 - @TempB) * 6\n else select @Blue = @Temp2;\n\n select @Red = round(@Red * 255, 0),\n @Green = round(@Green * 255, 0),\n @Blue = round(@Blue * 255, 0);\n\n if @Format = 'RGB'\n select @Result = cast(cast(@Red as int) as varchar) + ', '\n + cast(cast(@Green as int) as varchar) + ', '\n + cast(cast(@Blue as int) as varchar);\n else if @Format = 'HEX'\n select @Result = '#' + convert(varchar(2), convert(varbinary(1), cast(@Red as int)), 2)\n + convert(varchar(2), convert(varbinary(1), cast(@Green as int)), 2)\n + convert(varchar(2), convert(varbinary(1), cast(@Blue as int)), 2);\n else select @Result = 'Format should be RGB or HEX';\n\n return @Result;\n\nend;\n select dbo.f_convertHSL(24, 0.83, 0.74, 'RGB')\nresult: 244, 178, 134\n select dbo.f_convertHSL(24, 0.83, 0.74, 'HEX')\nresult: #F4B286\n"
},
{
"answer_id": 74573743,
"author": "Larnu",
"author_id": 2029983,
"author_profile": "https://Stackoverflow.com/users/2029983",
"pm_score": 2,
"selected": true,
"text": "CREATE OR ALTER FUNCTION dbo.HSLtoRGB (@H numeric(3,0),@S numeric(4,3), @L numeric(4,3)) \nRETURNS table\nAS RETURN\n SELECT CONVERT(tinyint,ROUND((RGB1.R1+m.m)*255,0)) AS R,\n CONVERT(tinyint,ROUND((RGB1.G1+m.m)*255,0)) AS G,\n CONVERT(tinyint,ROUND((RGB1.B1+m.m)*255,0)) AS B\n FROM (VALUES(@H, @S, @L))HSL(Hue,Saturation,Lightness)\n CROSS APPLY(VALUES((1-ABS((2*HSL.Lightness - 1))) * HSL.Saturation)) C(Chroma)\n CROSS APPLY(VALUES(HSL.Hue/60,C.Chroma * (1 - ABS((HSL.Hue/60) % 2 - 1))))H([H`],X)\n CROSS APPLY(SELECT TOP (1) * --It's unlikely there would be 2 rows, but just incase limit to 1\n FROM (VALUES(C.Chroma,H.X,0,0,1),\n (H.X,C.Chroma,0,1,2),\n (0,C.Chroma,H.X,2,3),\n (0,H.X,C.Chroma,3,4),\n (H.X,0,C.Chroma,4,5),\n (C.Chroma,0,H.X,5,6))V(R1,G1,B1,S,E)\n WHERE V.S <= H.[H`] AND H.[H`] <= V.E\n ORDER BY V.E DESC) RGB1 \n CROSS APPLY (VALUES(HSL.Lightness - (C.Chroma / 2)))m(m);\nGO\nCREATE OR ALTER FUNCTION dbo.HSLtoRGB_HEX (@H numeric(3,0),@S numeric(4,3), @L numeric(4,3)) \nRETURNS table\nAS RETURN\n SELECT CONVERT(binary(3),CONCAT(CONVERT(varchar(2),CONVERT(binary(1),CONVERT(tinyint,ROUND((RGB1.R1+m.m)*255,0))),2),\n CONVERT(varchar(2),CONVERT(binary(1),CONVERT(tinyint,ROUND((RGB1.G1+m.m)*255,0))),2),\n CONVERT(varchar(2),CONVERT(binary(1),CONVERT(tinyint,ROUND((RGB1.B1+m.m)*255,0))),2)),2) AS RGB\n FROM (VALUES(@H, @S, @L))HSL(Hue,Saturation,Lightness)\n CROSS APPLY(VALUES((1-ABS((2*HSL.Lightness - 1))) * HSL.Saturation)) C(Chroma)\n CROSS APPLY(VALUES(HSL.Hue/60,C.Chroma * (1 - ABS((HSL.Hue/60) % 2 - 1))))H([H`],X)\n CROSS APPLY(SELECT TOP(1) * --It's unlikely there would be 2 rows, but just incase limit to 1\n FROM (VALUES(C.Chroma,H.X,0,0,1),\n (H.X,C.Chroma,0,1,2),\n (0,C.Chroma,H.X,2,3),\n (0,H.X,C.Chroma,3,4),\n (H.X,0,C.Chroma,4,5),\n (C.Chroma,0,H.X,5,6))V(R1,G1,B1,S,E)\n WHERE V.S <= H.[H`] AND H.[H`] <= V.E\n ORDER BY V.E DESC) RGB1\n CROSS APPLY (VALUES(HSL.Lightness - (C.Chroma / 2)))m(m);\nGO\n\nSELECT *\nFROM (VALUES(210,.79,.3),\n (24,.83,.74),\n (360,1,1),\n (0,0,0))V(H,S,L)\n CROSS APPLY dbo.HSLtoRGB(V.H, V.S, V.L) RGB\n CROSS APPLY dbo.HSLtoRGB_Hex(V.H, V.S, V.L) RGBhex;\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18127602/"
] |
74,572,432
|
<p>If I have lists with x lists and and for example</p>
<pre><code>[[(1,2),(1,4)],[(7,5),(5,4)]]
</code></pre>
<p>How do I get another list that takes the first numbers of all the tuples in the lists and puts them in a list, and then takes the second numbers of all the tuples in the lists and puts them in a second list.how should I get that with 3 for loop</p>
<p>Expected output for the sample:</p>
<pre><code>[(1,1),(7,5)],[(2,4),(5,4)]
</code></pre>
|
[
{
"answer_id": 74572580,
"author": "Roman Udaltsov",
"author_id": 6773185,
"author_profile": "https://Stackoverflow.com/users/6773185",
"pm_score": 0,
"selected": false,
"text": "create function dbo.f_convertHSL (\n @HueDegree numeric(3,0), \n @Saturation numeric(6,3), \n @Lightness numeric(6,3), \n @Format varchar(3) )\nreturns varchar(100)\nas\n\nbegin\n\n declare @HuePercent numeric(6,3),\n @Red numeric(6,3), \n @Green numeric(6,3), \n @Blue numeric(6,3),\n @Temp1 numeric(6,3), \n @Temp2 numeric(6,3),\n @TempR numeric(6,3),\n @TempG numeric(6,3),\n @TempB numeric(6,3), \n @Result varchar(100);\n\n if @Saturation = 0 \n begin\n select @Red = @Lightness * 255,\n @Green = @Lightness * 255,\n @Blue = @Lightness * 255;\n\n if @Format = 'RGB'\n select @Result = cast(cast(@Red as int) as varchar) + ', '\n + cast(cast(@Green as int) as varchar) + ', '\n + cast(cast(@Blue as int) as varchar);\n else if @Format = 'HEX'\n select @Result = '#' + convert(varchar(2), convert(varbinary(1), cast(@Red as int)), 2)\n + convert(varchar(2), convert(varbinary(1), cast(@Green as int)), 2)\n + convert(varchar(2), convert(varbinary(1), cast(@Blue as int)), 2);\n else select @Result = 'Format should be RGB or HEX';\n\n return @Result;\n end;\n\n if @Lightness < 0.5\n select @Temp1 = @Lightness * (1 + @Saturation);\n else\n select @Temp1 = @Lightness + @Saturation - @Lightness * @Saturation;\n\n select @Temp2 = 2 * @Lightness - @Temp1\n , @HuePercent = @HueDegree / 360.0;\n\n select @TempR = @HuePercent + 0.333\n , @TempG = @HuePercent\n , @TempB = @HuePercent - 0.333;\n\n if @TempR < 0 select @TempR = @TempR + 1;\n if @TempR > 1 select @TempR = @TempR - 1;\n if @TempG < 0 select @TempG = @TempG + 1;\n if @TempG > 1 select @TempG = @TempG - 1;\n if @TempB < 0 select @TempB = @TempB + 1;\n if @TempB > 1 select @TempB = @TempB - 1;\n\n if @TempR * 6 < 1 select @Red = @Temp2 + (@Temp1 - @Temp2) * 6 * @TempR\n else if @TempR * 2 < 1 select @Red = @Temp1\n else if @TempR * 3 < 2 select @Red = @Temp2 + (@Temp1 - @Temp2) * (0.666 - @TempR) * 6\n else select @Red = @Temp2;\n\n if @TempG * 6 < 1 select @Green = @Temp2 + (@Temp1 - @Temp2) * 6 * @TempG\n else if @TempG * 2 < 1 select @Green = @Temp1\n else if @TempG * 3 < 2 select @Green = @Temp2 + (@Temp1 - @Temp2) * (0.666 - @TempG) * 6\n else select @Green = @Temp2;\n\n if @TempB * 6 < 1 select @Blue = @Temp2 + (@Temp1 - @Temp2) * 6 * @TempB\n else if @TempB * 2 < 1 select @Blue = @Temp1\n else if @TempB * 3 < 2 select @Blue = @Temp2 + (@Temp1 - @Temp2) * (0.666 - @TempB) * 6\n else select @Blue = @Temp2;\n\n select @Red = round(@Red * 255, 0),\n @Green = round(@Green * 255, 0),\n @Blue = round(@Blue * 255, 0);\n\n if @Format = 'RGB'\n select @Result = cast(cast(@Red as int) as varchar) + ', '\n + cast(cast(@Green as int) as varchar) + ', '\n + cast(cast(@Blue as int) as varchar);\n else if @Format = 'HEX'\n select @Result = '#' + convert(varchar(2), convert(varbinary(1), cast(@Red as int)), 2)\n + convert(varchar(2), convert(varbinary(1), cast(@Green as int)), 2)\n + convert(varchar(2), convert(varbinary(1), cast(@Blue as int)), 2);\n else select @Result = 'Format should be RGB or HEX';\n\n return @Result;\n\nend;\n select dbo.f_convertHSL(24, 0.83, 0.74, 'RGB')\nresult: 244, 178, 134\n select dbo.f_convertHSL(24, 0.83, 0.74, 'HEX')\nresult: #F4B286\n"
},
{
"answer_id": 74573743,
"author": "Larnu",
"author_id": 2029983,
"author_profile": "https://Stackoverflow.com/users/2029983",
"pm_score": 2,
"selected": true,
"text": "CREATE OR ALTER FUNCTION dbo.HSLtoRGB (@H numeric(3,0),@S numeric(4,3), @L numeric(4,3)) \nRETURNS table\nAS RETURN\n SELECT CONVERT(tinyint,ROUND((RGB1.R1+m.m)*255,0)) AS R,\n CONVERT(tinyint,ROUND((RGB1.G1+m.m)*255,0)) AS G,\n CONVERT(tinyint,ROUND((RGB1.B1+m.m)*255,0)) AS B\n FROM (VALUES(@H, @S, @L))HSL(Hue,Saturation,Lightness)\n CROSS APPLY(VALUES((1-ABS((2*HSL.Lightness - 1))) * HSL.Saturation)) C(Chroma)\n CROSS APPLY(VALUES(HSL.Hue/60,C.Chroma * (1 - ABS((HSL.Hue/60) % 2 - 1))))H([H`],X)\n CROSS APPLY(SELECT TOP (1) * --It's unlikely there would be 2 rows, but just incase limit to 1\n FROM (VALUES(C.Chroma,H.X,0,0,1),\n (H.X,C.Chroma,0,1,2),\n (0,C.Chroma,H.X,2,3),\n (0,H.X,C.Chroma,3,4),\n (H.X,0,C.Chroma,4,5),\n (C.Chroma,0,H.X,5,6))V(R1,G1,B1,S,E)\n WHERE V.S <= H.[H`] AND H.[H`] <= V.E\n ORDER BY V.E DESC) RGB1 \n CROSS APPLY (VALUES(HSL.Lightness - (C.Chroma / 2)))m(m);\nGO\nCREATE OR ALTER FUNCTION dbo.HSLtoRGB_HEX (@H numeric(3,0),@S numeric(4,3), @L numeric(4,3)) \nRETURNS table\nAS RETURN\n SELECT CONVERT(binary(3),CONCAT(CONVERT(varchar(2),CONVERT(binary(1),CONVERT(tinyint,ROUND((RGB1.R1+m.m)*255,0))),2),\n CONVERT(varchar(2),CONVERT(binary(1),CONVERT(tinyint,ROUND((RGB1.G1+m.m)*255,0))),2),\n CONVERT(varchar(2),CONVERT(binary(1),CONVERT(tinyint,ROUND((RGB1.B1+m.m)*255,0))),2)),2) AS RGB\n FROM (VALUES(@H, @S, @L))HSL(Hue,Saturation,Lightness)\n CROSS APPLY(VALUES((1-ABS((2*HSL.Lightness - 1))) * HSL.Saturation)) C(Chroma)\n CROSS APPLY(VALUES(HSL.Hue/60,C.Chroma * (1 - ABS((HSL.Hue/60) % 2 - 1))))H([H`],X)\n CROSS APPLY(SELECT TOP(1) * --It's unlikely there would be 2 rows, but just incase limit to 1\n FROM (VALUES(C.Chroma,H.X,0,0,1),\n (H.X,C.Chroma,0,1,2),\n (0,C.Chroma,H.X,2,3),\n (0,H.X,C.Chroma,3,4),\n (H.X,0,C.Chroma,4,5),\n (C.Chroma,0,H.X,5,6))V(R1,G1,B1,S,E)\n WHERE V.S <= H.[H`] AND H.[H`] <= V.E\n ORDER BY V.E DESC) RGB1\n CROSS APPLY (VALUES(HSL.Lightness - (C.Chroma / 2)))m(m);\nGO\n\nSELECT *\nFROM (VALUES(210,.79,.3),\n (24,.83,.74),\n (360,1,1),\n (0,0,0))V(H,S,L)\n CROSS APPLY dbo.HSLtoRGB(V.H, V.S, V.L) RGB\n CROSS APPLY dbo.HSLtoRGB_Hex(V.H, V.S, V.L) RGBhex;\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20599011/"
] |
74,572,442
|
<p>I have a string: <code>[(10.3.4.5:83/001_3CX/asd_43)]</code></p>
<p>From this string I want to get two strings:</p>
<blockquote>
<p>10.3.4.5:83</p>
</blockquote>
<blockquote>
<p>001_3CX/asd_43</p>
</blockquote>
<p>What is the best solution for this?
I'm coding in c#.</p>
|
[
{
"answer_id": 74572665,
"author": "Dominique",
"author_id": 4279155,
"author_profile": "https://Stackoverflow.com/users/4279155",
"pm_score": 0,
"selected": false,
"text": "string test = \"[(10.3.4.5:83/001_3CX/asd_43)]\";\ntest.replace_string_by_character(\"[(\",\"\");\ntest.replace_string_by_character(\")]\",\"\");\n// (current result) test = \"10.3.4.5:83/001_3CX/asd_43\"\nint index = locate_character_inside_string(\"/\",test);\n\nstring first_to_return = substring_basedon_index(test,0,index - 1);\nstring second_to_return = substring_basedon_index(test,index + 1, length(test));\n// (result) first_to_return = \"10.3.4.5:83\";\n// (result) second_to_return = \"001_3CX/asd_43\";\n\n"
},
{
"answer_id": 74572679,
"author": "fubo",
"author_id": 1315444,
"author_profile": "https://Stackoverflow.com/users/1315444",
"pm_score": 2,
"selected": true,
"text": "string input = \"[(10.3.4.5:83/001_3CX/asd_43)]\";\nMatch result = Regex.Match(input, @\"\\[\\((.*?)\\/(.*)\\)\\]\");\nstring first = result.Groups[1].Value; //10.3.4.5:83\nstring second = result.Groups[2].Value; //001_3CX/asd_43\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10454982/"
] |
74,572,453
|
<p>I launch my app in eclipse and works fine and I got the initialization of de entityManagerFactory by default as I wish:</p>
<pre><code>2022-11-28 13:32:58.558 INFO 12176 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
</code></pre>
<p>but when I deploy my app by a runnable jar file it is not launching, I'm sharing this question after much research, here is my pom (I'm extracting the libraries into generated jar):</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.6</version>
</parent>
<groupId>ZpectrumApp</groupId>
<artifactId>ZpectrumApp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>ZpectrumApp</name>
<description>End-Degree project for Spring Boot</description>
<dependencies>
<dependency>
<groupId>org.jcodec</groupId>
<artifactId>jcodec</artifactId>
<version>0.2.3</version>
</dependency>
<dependency>
<groupId>org.jcodec</groupId>
<artifactId>jcodec-javase</artifactId>
<version>0.2.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate.javax.persistence/hibernate-jpa-2.1-api -->
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.2.Final</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180130</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</dependency>
</dependencies>
<properties>
<start-class>ZpectrumApplication.Application</start-class>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
</code></pre>
<p>I thinks it is possible a incompatibility from one spring-boot version to another dependency, but I'm not certain. Also attach the console trace.</p>
<pre><code>ZpectrumApplication: Cannot create inner bean '(inner bean)#71a9b4c7' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#71a9b4c7': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
</code></pre>
|
[
{
"answer_id": 74626835,
"author": "kazeematics",
"author_id": 20399058,
"author_profile": "https://Stackoverflow.com/users/20399058",
"pm_score": 0,
"selected": false,
"text": "<plugin>\n <artifactId>maven-assembly-plugin</artifactId>\n <executions>\n <execution>\n <phase>package</phase>\n <goals>\n <goal>single</goal>\n </goals>\n </execution>\n </executions>\n <configuration>\n <archive>\n <manifest>\n <addClasspath>true</addClasspath>\n <mainClass>com.byteworks.epms.DeviceServiceListener</mainClass>\n </manifest>\n </archive>\n <descriptorRefs>\n <descriptorRef>jar-with-dependencies</descriptorRef>\n </descriptorRefs>\n </configuration>\n</plugin>\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18495770/"
] |
74,572,458
|
<p><a href="https://i.stack.imgur.com/M5IF1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/M5IF1.png" alt="enter image description here" /></a>
Lists of color and names i want to build an app that will change color and text on tap. I want to change the container color and the text which are displayed on a list and randomize both of them. How can i do that?Here i want to change randomize both of them and get on tap
<a href="https://i.stack.imgur.com/Y4IIH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Y4IIH.png" alt="enter image description here" /></a>
<a href="https://i.stack.imgur.com/iLlqs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iLlqs.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74626835,
"author": "kazeematics",
"author_id": 20399058,
"author_profile": "https://Stackoverflow.com/users/20399058",
"pm_score": 0,
"selected": false,
"text": "<plugin>\n <artifactId>maven-assembly-plugin</artifactId>\n <executions>\n <execution>\n <phase>package</phase>\n <goals>\n <goal>single</goal>\n </goals>\n </execution>\n </executions>\n <configuration>\n <archive>\n <manifest>\n <addClasspath>true</addClasspath>\n <mainClass>com.byteworks.epms.DeviceServiceListener</mainClass>\n </manifest>\n </archive>\n <descriptorRefs>\n <descriptorRef>jar-with-dependencies</descriptorRef>\n </descriptorRefs>\n </configuration>\n</plugin>\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,572,488
|
<p>I am trying to add Microsoft Office applications such as excel, word and outlook pinned to taskbar when I run a bat file or a script. reason>> I'm deploying Microsoft Office 2021 on windows 10 , always updated to latest version, once the Office is installed I want the shortcuts of Excel, Word and Outlook to be added to Taskbar, I don't want the shortcuts on desktop, I need them in Taskbar. I deploy over 500 Windows per day.
Office app location is "C:\ProgramData\Microsoft\Windows\Start Menu\Programs".</p>
<p>from what I can find there is no simple CMD command to do it, I preferer not to install any other applications or applets.</p>
|
[
{
"answer_id": 74626835,
"author": "kazeematics",
"author_id": 20399058,
"author_profile": "https://Stackoverflow.com/users/20399058",
"pm_score": 0,
"selected": false,
"text": "<plugin>\n <artifactId>maven-assembly-plugin</artifactId>\n <executions>\n <execution>\n <phase>package</phase>\n <goals>\n <goal>single</goal>\n </goals>\n </execution>\n </executions>\n <configuration>\n <archive>\n <manifest>\n <addClasspath>true</addClasspath>\n <mainClass>com.byteworks.epms.DeviceServiceListener</mainClass>\n </manifest>\n </archive>\n <descriptorRefs>\n <descriptorRef>jar-with-dependencies</descriptorRef>\n </descriptorRefs>\n </configuration>\n</plugin>\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19449139/"
] |
74,572,506
|
<p>I would like to create a program from a function that, given an array made up of a series of numbers and declared a variable with a value, returns true if the value exceeds each of the numbers in array and otherwise returns false.</p>
<pre><code>let array = [5000, 5000, 3]
let value = 2300;
function compare_Values(table,number){
for(let i = 0; i <= table.length; i++){
if(number < table[i]){
var result = "FALSE: failed ";
} else{
var result = "TRUE: if passed";
}
return result
}
}
console.log(compare_Values(array,value))
</code></pre>
<p>I don't know why the result returns <strong>FALSE</strong>. The value does not exceed each of the elements in the table.
Can someone help me? I don't know where is my mistake.</p>
|
[
{
"answer_id": 74572578,
"author": "Marc Simon",
"author_id": 19699404,
"author_profile": "https://Stackoverflow.com/users/19699404",
"pm_score": 0,
"selected": false,
"text": "let array = [5000, 5000, 3]\nlet value = 2300;\n\n\nfunction compare_Values(table,number){\n var result; \n for(let i = 0; i < table.length; i++){ \n if(number < table[i]){ \n result = \"TRUE: if passed\";\n } else{\n result = \"FALSE: failed\";\n return result;\n }\n }\n return result\n}\n\n\n\nconsole.log(compare_Values(array,value))\n"
},
{
"answer_id": 74572712,
"author": "Matheus Cirillo",
"author_id": 9860374,
"author_profile": "https://Stackoverflow.com/users/9860374",
"pm_score": 2,
"selected": true,
"text": "res n function solve(arr, n) {\n let res = true;\n for (let i = 0; i < arr.length && res; i++) {\n res = n <= arr[i];\n }\n\n return res;\n}\n Array.prototype.every() let arr = [5000, 5000, 4000];\nlet n = 2300;\n\nconsole.log(arr.every(v => n <= v));\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20491974/"
] |
74,572,519
|
<p>It's a pity that there are some APIs provided by others that are out of my control and the said APIs return the same type(i.e. <code>uint8_t</code> other than the <code>enum</code> type).</p>
<p>But the meaning is different when the same value is returned by the different APIs. I hope to use overloading to convert the returned value to readable strings.</p>
<p>However, as per this <a href="https://stackoverflow.com/a/10595263/13611002">answer</a>, which says:</p>
<blockquote>
<p>a typedef is just another name for the same type. But you can only overload on different types.</p>
</blockquote>
<p>I thought and thought, and I found a solution. But I think there must be a better one. How?</p>
<p>But when I finish the code snippet below. I am more confused.
<strong>Since <code>Demo::Foo::SampleType</code> and <code>Demo::Bar::SampleType</code>are the same thing, so the overloading should not work. But the code snippet works well! What a surprise!</strong></p>
<p>Here is the demo code snippet for my <a href="https://godbolt.org/z/78n8x1efE" rel="nofollow noreferrer">solution</a>:</p>
<pre><code>#include <iostream>
#include <map>
namespace Demo
{
class Foo
{
public:
using SampleType = uint8_t;
SampleType GetFooData(){return SampleType{1};}
};
class Bar
{
public:
using SampleType = uint8_t;
SampleType GetBarData(){return SampleType{2};}
};
}
//////////////////code above is provided by others/////////////
template <typename T>
void FindAndPrint(const T& val, const std::map<T, std::string>& mp)
{
auto itr = mp.find(static_cast<T>(val));
if(itr != mp.end())
{
std::cout << itr->second;
}
else
{
std::cout << "can't classify";
}
std::cout << std::endl;
}
template <typename ServiceName>
void Print(const typename ServiceName::SampleType& data);
template <>
void Print<Demo::Foo>(const typename Demo::Foo::SampleType& data)
{
enum class Color
{
Blue = 1,
Red = 2,
};
std::map<Color, std::string> mp ={
{Color::Blue, "Blue"},
{Color::Red, "Red"},
};
FindAndPrint(static_cast<Color>(data), mp);
return;
}
template <>
void Print<Demo::Bar>(const typename Demo::Foo::SampleType& data)
{
// similar code like above
// When I write this line, I start to realize my solution is wrong since `Demo::Foo::SampleType` and `Demo::Foo::SampleType`are the same thing!
// But, what a surprise! This code snippet compiles and works well. Why?
enum class Animal
{
Dog = 1,
Cat = 2,
};
std::map<Animal, std::string> mp ={
{Animal::Dog, "Dog"},
{Animal::Cat, "Cat"},
};
FindAndPrint(static_cast<Animal>(data), mp);
return;
}
int main()
{
Demo::Foo foo;
Print<Demo::Foo>(foo.GetFooData());
Demo::Bar bar;
Print<Demo::Bar>(bar.GetBarData());
}
</code></pre>
|
[
{
"answer_id": 74572812,
"author": "Ranoiaetep",
"author_id": 12861639,
"author_profile": "https://Stackoverflow.com/users/12861639",
"pm_score": 2,
"selected": false,
"text": "template <typename ServiceName>\nvoid Print(const typename ServiceName::SampleType& data);\n\ntemplate <>\nvoid Print<Demo::Foo>(const typename Demo::Foo::SampleType& data);\n\ntemplate <>\nvoid Print<Demo::Bar>(const typename Demo::Foo::SampleType& data);\n template<>\nvoid Print<Demo::Foo>(const uint8_t& data);\n Print<Demo::Foo>(...) Print<Demo::Bar>(...) Demo::Foo Demo::Bar"
},
{
"answer_id": 74572880,
"author": "Rulle",
"author_id": 1008794,
"author_profile": "https://Stackoverflow.com/users/1008794",
"pm_score": 1,
"selected": false,
"text": "uint8_t SampleTypeInfo Print template <typename ServiceName>\nvoid Print(const typename ServiceName::SampleType& data) {\n typedef SampleTypeInfo<ServiceName> Info;\n FindAndPrint(Info::decode(data), Info().stringMap);\n}\n SampleTypeInfo template <typename T> struct SampleTypeInfo {};\n\ntemplate <typename T>\nstruct SampleTypeInfoBase {\n typedef T SampleType;\n \n static T decode(uint8_t x) {\n return static_cast<T>(x);\n }\n\n std::map<T, std::string> stringMap;\nprotected:\n void regString(T k, const std::string& v) {\n stringMap[k] = v;\n }\n};\n\ntemplate <>\nstruct SampleTypeInfo<Demo::Foo> : public SampleTypeInfoBase<Color> {\n SampleTypeInfo() {\n regString(Color::Blue, \"blue\");\n regString(Color::Red, \"red\");\n }\n};\n\ntemplate <>\nstruct SampleTypeInfo<Demo::Bar> : public SampleTypeInfoBase<Animal> {\n SampleTypeInfo() {\n regString(Animal::Cat, \"cat\");\n regString(Animal::Dog, \"dog\");\n }\n};\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13611002/"
] |
74,572,564
|
<p>I am very, and by that I mean very new to Python (i know literally nothing). I'm attemtping to create a little game using the turtle module, and following a tutorial I don't see the listen() function working</p>
<p>here's my code
I'm trying to create a controllable character</p>
<pre><code>from turtle import *
#background
Screen().bgcolor("orange")
#player
pl = Turtle()
pl.color('dodgerblue')
pl.shape('turtle')
pl.penup()
def turnleft():
player.left(30)
turtle.listen()
onkeypress(turnleft, "Left")
speed = 1
while True:
pl.forward(speed)
</code></pre>
|
[
{
"answer_id": 74572812,
"author": "Ranoiaetep",
"author_id": 12861639,
"author_profile": "https://Stackoverflow.com/users/12861639",
"pm_score": 2,
"selected": false,
"text": "template <typename ServiceName>\nvoid Print(const typename ServiceName::SampleType& data);\n\ntemplate <>\nvoid Print<Demo::Foo>(const typename Demo::Foo::SampleType& data);\n\ntemplate <>\nvoid Print<Demo::Bar>(const typename Demo::Foo::SampleType& data);\n template<>\nvoid Print<Demo::Foo>(const uint8_t& data);\n Print<Demo::Foo>(...) Print<Demo::Bar>(...) Demo::Foo Demo::Bar"
},
{
"answer_id": 74572880,
"author": "Rulle",
"author_id": 1008794,
"author_profile": "https://Stackoverflow.com/users/1008794",
"pm_score": 1,
"selected": false,
"text": "uint8_t SampleTypeInfo Print template <typename ServiceName>\nvoid Print(const typename ServiceName::SampleType& data) {\n typedef SampleTypeInfo<ServiceName> Info;\n FindAndPrint(Info::decode(data), Info().stringMap);\n}\n SampleTypeInfo template <typename T> struct SampleTypeInfo {};\n\ntemplate <typename T>\nstruct SampleTypeInfoBase {\n typedef T SampleType;\n \n static T decode(uint8_t x) {\n return static_cast<T>(x);\n }\n\n std::map<T, std::string> stringMap;\nprotected:\n void regString(T k, const std::string& v) {\n stringMap[k] = v;\n }\n};\n\ntemplate <>\nstruct SampleTypeInfo<Demo::Foo> : public SampleTypeInfoBase<Color> {\n SampleTypeInfo() {\n regString(Color::Blue, \"blue\");\n regString(Color::Red, \"red\");\n }\n};\n\ntemplate <>\nstruct SampleTypeInfo<Demo::Bar> : public SampleTypeInfoBase<Animal> {\n SampleTypeInfo() {\n regString(Animal::Cat, \"cat\");\n regString(Animal::Dog, \"dog\");\n }\n};\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20599108/"
] |
74,572,600
|
<p>I reload the WildFly server as follows</p>
<pre><code>CliCommandBuilder cliCommandBuilder = ...
cliCommandBuilder
.setCommand(
"reload"
);
Launcher.of(cliCommandBuilder)
.inherit()
.setRedirectErrorStream(true)
.launch();
</code></pre>
<p>And I need to wait for the server to start, because then I will deploy the new content. How can I do this?</p>
<p>I tried use method <code>.waitFor()</code> from <code>java.lang.Process</code></p>
<pre><code>Launcher.of(cliCommandBuilder)
.inherit()
.setRedirectErrorStream(true)
.launch().waitFor();
</code></pre>
<p>But the thread continues to work after shutting down WildFly, not starting</p>
|
[
{
"answer_id": 74603863,
"author": "cam-rod",
"author_id": 19546298,
"author_profile": "https://Stackoverflow.com/users/19546298",
"pm_score": 0,
"selected": false,
"text": "localhost:9990 connect setController"
},
{
"answer_id": 74605778,
"author": "James R. Perkins",
"author_id": 152794,
"author_profile": "https://Stackoverflow.com/users/152794",
"pm_score": 2,
"selected": true,
"text": "reload final CliCommandBuilder commandBuilder = CliCommandBuilder.of(\"/opt/wildfly-27.0.0.Final\")\n .setConnection(\"localhost:9990\")\n .setCommand(\"reload\");\nfinal Process process = Launcher.of(commandBuilder)\n .inherit()\n .setRedirectErrorStream(true)\n .launch();\n\n// Wait for the process to end\nif (!process.waitFor(5, TimeUnit.SECONDS)) {\n throw new RuntimeException(\"The CLI process failed to terminate\");\n}\n\ntry (ModelControllerClient client = ModelControllerClient.Factory.create(\"localhost\", 9990)) {\n while (!ServerHelper.isStandaloneRunning(client)) {\n TimeUnit.MILLISECONDS.sleep(200L);\n }\n if (!Operations.isSuccessfulOutcome(result)) {\n throw new RuntimeException(\"Failed to check state: \" + Operations.getFailureDescription(result).asString());\n }\n System.out.printf(\"Running Mode: %s%n\", Operations.readResult(result).asString());\n}\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19352128/"
] |
74,572,613
|
<p>I'm searching for a way of filling a python dictionary at the same time it is created</p>
<p>I have this simple method that firstly creates a dictionary with all the keys at value 0 and then it reads the string again to fill it</p>
<pre><code>def letter_count(word):
letter_dic = {}
for w in word:
letter_dic[w] = 0
for w in word:
letter_dic[w] += 1
return letter_dic
</code></pre>
<p>The method above should count all the occurrences of each letter in a given string</p>
<p>Input:</p>
<pre><code>"leumooeeyzwwmmirbmf"
</code></pre>
<p>Output:</p>
<pre><code>{'l': 1, 'e': 3, 'u': 1, 'm': 4, 'o': 2, 'y': 1, 'z': 1, 'w': 2, 'i': 1, 'r': 1, 'b': 1, 'f': 1}
</code></pre>
<p>Is there a form of creating and filling the dictionary at the same time without using two loops?</p>
|
[
{
"answer_id": 74572683,
"author": "kosciej16",
"author_id": 3361462,
"author_profile": "https://Stackoverflow.com/users/3361462",
"pm_score": 3,
"selected": true,
"text": "from collections import Counter\n\nletter_dic = Counter(word)\n for w in word:\n if w not in letter_dic: \n letter_dic[w] = 0\n letter_dic[w] += 1\n from collections import defaultdict\n\nletter_dic = defaultdict(int)\nfor w in word:\n letter_dic[w] += 1\n"
},
{
"answer_id": 74572686,
"author": "Matt Pitkin",
"author_id": 1862861,
"author_profile": "https://Stackoverflow.com/users/1862861",
"pm_score": 2,
"selected": false,
"text": "x = \"leumooeeyzwwmmirbmf\"\ny = {l: x.count(l) for l in x}\n"
},
{
"answer_id": 74572744,
"author": "Marcin Orlowski",
"author_id": 1235698,
"author_profile": "https://Stackoverflow.com/users/1235698",
"pm_score": 0,
"selected": false,
"text": "collections from collections import Counter\nsrc = \"leumooeeyzwwmmirbmf\"\nprint(dict(Counter(src))\n {'l': 1, 'e': 3, 'u': 1, 'm': 4, 'o': 2, 'y': 1, 'z': 1, 'w': 2, 'i': 1, 'r': 1, 'b': 1, 'f': 1}\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19665553/"
] |
74,572,638
|
<p>I have a nodejs express web with a mongo db with</p>
<pre><code>const AuthorSchema = new Schema({
first_name: { type: String, required: true, maxLength: 100 },
family_name: { type: String, required: true, maxLength: 100 },
date_of_birth: { type: Date },
date_of_death: { type: Date },
});
</code></pre>
<p>I want to search for an author using a regexp over the first_name + family_name. In other words,
given we have an author with:
...
first_name: 'Alessandro'
family_name: 'Manzoni'
...
I want to match it using all of the search strings:</p>
<p>'Alessandro' or 'ale' or 'manzo' or 'alessandro manzoni' or 'Manzoni Alessandro'</p>
<p>so I wrote this:</p>
<pre><code>const searchRegex = new RegExp(req.body.search_text, 'i');
Author.find({ $where:
function() {
return (searchRegex.test(this.first_name + " " + this.family_name)
|| searchRegex.test(this.family_name + " " + this.first_name) )
}
},"_id").exec(function (err, list_authors) {
</code></pre>
<p>and I got:</p>
<pre><code>MongoServerError: Executor error during find command :: caused by :: ReferenceError: searchRegex is not defined :
@:2:33
</code></pre>
<p>I tried using a $let clause but all I've achieved is getting all of the authors id in the results list.</p>
|
[
{
"answer_id": 74572683,
"author": "kosciej16",
"author_id": 3361462,
"author_profile": "https://Stackoverflow.com/users/3361462",
"pm_score": 3,
"selected": true,
"text": "from collections import Counter\n\nletter_dic = Counter(word)\n for w in word:\n if w not in letter_dic: \n letter_dic[w] = 0\n letter_dic[w] += 1\n from collections import defaultdict\n\nletter_dic = defaultdict(int)\nfor w in word:\n letter_dic[w] += 1\n"
},
{
"answer_id": 74572686,
"author": "Matt Pitkin",
"author_id": 1862861,
"author_profile": "https://Stackoverflow.com/users/1862861",
"pm_score": 2,
"selected": false,
"text": "x = \"leumooeeyzwwmmirbmf\"\ny = {l: x.count(l) for l in x}\n"
},
{
"answer_id": 74572744,
"author": "Marcin Orlowski",
"author_id": 1235698,
"author_profile": "https://Stackoverflow.com/users/1235698",
"pm_score": 0,
"selected": false,
"text": "collections from collections import Counter\nsrc = \"leumooeeyzwwmmirbmf\"\nprint(dict(Counter(src))\n {'l': 1, 'e': 3, 'u': 1, 'm': 4, 'o': 2, 'y': 1, 'z': 1, 'w': 2, 'i': 1, 'r': 1, 'b': 1, 'f': 1}\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20598890/"
] |
74,572,650
|
<p>I am trying to include a search field inside my home page. It works for some of the module field. My problem is when I use a ForeignKey field (correct me please if I am wrong).</p>
<p><em><strong>models.py</strong></em></p>
<pre><code>class Training_Lead(models.Model):
handel_by = models.ForeignKey(UserInstance, on_delete=models.PROTECT)
learning_partner = models.ForeignKey(
Learning_Partner, on_delete=models.PROTECT, blank=False, null=False)
assign_to_trainer = models.ForeignKey(
Trainer, on_delete=models.PROTECT, null=True, blank=True)
course_name = models.CharField(max_length=2000)
lead_type = models.CharField(max_length=2000)
time_zone = models.CharField(choices=(('IST', 'IST'), ('GMT', 'GMT'), ('BST', 'BST'), (
'CET', 'CET'), ('SAST', 'SAST'), ('EST', 'EST'), ('PST', 'PST'), ('MST', 'MST'), ('UTC', 'UTC')), max_length=40, blank=False, null=False)
getting_lead_date = models.DateTimeField(null=True, blank=True)
start_date = models.DateTimeField(null=True, blank=True)
end_date = models.DateTimeField(null=True, blank=True)
lead_status = models.CharField(choices=(('Initial', 'Initial'), ('In Progress', 'In Progress'), ('Follow Up', 'Follow Up'), (
'Cancelled', 'Cancelled'), ('Confirmed', 'Confirmed'), ('PO Received', 'PO Received')), max_length=40, blank=False, null=False)
lead_description = models.CharField(max_length=9000, blank=True, null=True)
def __str__(self):
return str(self.assign_to_trainer)
class Meta:
ordering = ['start_date']
class Trainer(models.Model):
trainer_id = models.AutoField(primary_key=True)
trainer_name = models.CharField(max_length=200, null=False, blank=False)
address = models.CharField(max_length=500, null=False, blank=False)
phone_no = models.CharField(max_length=13, unique=True, null=True, blank=True)
phone_no_optional = models.CharField(max_length=13, null=True, blank=True)
email = models.CharField(max_length=50)
email_optional = models.CharField(max_length=50, null=True, blank=True)
country = models.CharField(max_length=50, null=True, blank=True)
primary_language = models.CharField(max_length=50, null=True, blank=True)
gender = models.CharField(choices=(('Male', 'Male'), ('Female', 'Female')), max_length=30, blank=True, null=True)
trainer_type = models.CharField(choices=(('Corporate Trainer', 'Corporate Trainer'), ('Academic Trainer', 'Academic Trainer')), max_length=30, blank=True, null=True)
trainer_pricing = models.CharField(max_length=1000, null=True, blank=True)
trainer_course_specialization = models.CharField(max_length=5000)
trainer_skill_set = models.CharField(max_length=10000, null=True, blank=True)
trainer_enrolled_with = models.ForeignKey(Learning_Partner, on_delete=models.PROTECT, blank=True, null=True)
trainer_tier = models.CharField(choices=(('1', '1'), ('2', '2'), ('3', '3'), ('4', '4')), max_length=10, null=True, blank=True)
def __str__(self):
return str(self.trainer_name)
</code></pre>
<p><strong>views.py</strong></p>
<pre><code>def report_for_trainer(request):
if request.user.is_authenticated:
user = UserInstance.objects.all()
partner = Learning_Partner.objects.all()
trainer_info = Trainer.objects.all()
trainer = Training_Lead.objects.all()
if request.method == "POST":
start_date = request.POST.get("start_date")
end_date = request.POST.get("end_date")
lead_status = request.POST.get("lead_status", default="")
assign_to_trainer = request.POST.get("assign_to_trainer")
trainers_info = Training_Lead.objects.filter(
start_date__gte=start_date,
end_date__lte=end_date,
lead_status__contains=lead_status,
assign_to_trainer_id__contains=assign_to_trainer,
)
trainer_info_not_active = Training_Lead.objects.exclude(
start_date__gte=start_date,
end_date__lte=end_date,
lead_status__contains=lead_status,
)
df = {"user": user, "partner": partner,"start_date": start_date,"end_date":end_date,"trainer":trainer,"lead_status":lead_status,"assign_to_trainer":assign_to_trainer, "lead_status": lead_status,"trainers_info": trainers_info, "trainer_info": trainer_info, "trainer_info_not_active": trainer_info_not_active}
return render(request, "trainers_for_schedule_date.html", df)
else:
return redirect("router")
</code></pre>
<p><strong>HTML code</strong></p>
<pre><code> <label class="form-label" for="assign_to_trainer">
<h4 style="color: rgb(0, 0, 0);">Assign To Trainer :-</h4>
</label>
<select name="assign_to_trainer" id="assign_to_trainer" multiple>
{% for t in leads %}
<option name="assign_to_trainer" id="assign_to_trainer" value="{{ t.assign_to_trainer_id }}">{{ t.assign_to_trainer }}</option>
{% endfor %}
</select>
</code></pre>
<br>
<p>please help me to solve this</p>
<p>My problem is if I use assign_to_trainer inside the filter query instead of Training_Lead I receive the error:</p>
<p><a href="https://i.stack.imgur.com/gPJD3.png" rel="nofollow noreferrer">enter image description here</a></p>
|
[
{
"answer_id": 74572711,
"author": "Darsh Modi",
"author_id": 12098337,
"author_profile": "https://Stackoverflow.com/users/12098337",
"pm_score": 0,
"selected": false,
"text": "trainers_info = Training_Lead.objects.filter(\n start_date__gte=start_date,\n end_date__lte=end_date,\n lead_status__contains=lead_status,\n assign_to_trainer_id=int(assign_to_trainer),\n )\n"
},
{
"answer_id": 74573890,
"author": "Sunderam Dubey",
"author_id": 17562044,
"author_profile": "https://Stackoverflow.com/users/17562044",
"pm_score": 2,
"selected": true,
"text": "__contains ForeignKey trainers_info = Training_Lead.objects.filter(\n start_date__gte=start_date,\n end_date__lte=end_date,\n lead_status__contains=lead_status,\n assign_to_trainer=assign_to_trainer,\n )\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18265618/"
] |
74,572,654
|
<p>I am a bit stuck in one of the issue lately. I am using thymeleaf to render the html after getting the response. We have a complex JSON which looks like below</p>
<pre><code>{
"lastMonth": 11,
"firstMonth": 9,
"reportData": {
"123456": {
"usageByMonth": {
"9": 233,
"10": 233,
"11": 218
},
"company": "Some Company"
},
6768592": {
"usageByMonth": {
"9": 5,
"10": 5,
"11": 5
},
"companyName": "another company name"
}
}
}
</code></pre>
<p>I want to show these values for each report data in a html table.
I set the context like below.</p>
<pre><code> val reports = repservice.fetchReport(stringy)
val context = Context()
context.setVariable("report", report)
</code></pre>
<p>Since, I am not very good at frontend/thymeleaf I am a bit confused on How I can iterate through this. For example what I am trying to create is a table which looks like this.</p>
<pre><code>|Company|FirstMonth|LastMonth|
|Some Company|233|218|
|another company name|5|5|
</code></pre>
<p>Your suggestions and answers will be highly appreciated.</p>
<p>Note: If you think the question is a bit confusing, please comment on it, I will make it more clear.</p>
<p>Thank you !</p>
|
[
{
"answer_id": 74573145,
"author": "Farukh Khan",
"author_id": 5181689,
"author_profile": "https://Stackoverflow.com/users/5181689",
"pm_score": 1,
"selected": true,
"text": "<table>\n <thead>\n <tr>\n <th>\n Kunde\n </th>\n <th>FirstMonth</th>\n <th>LastMonth</th>\n </tr>\n </thead>\n<tbody>\n <tr th:each=\"reporting: ${report.reportData}\">\n <td th:text=\"${reporting.value.companyName}\"></td>\n <td class=\"tableValue\" th:text=\"${reporting.value.usageByMonth[report.firstMonth]}\"></td>\n <td class=\"tableValue\" th:text=\"${reporting.value.usageByMonth[report.lastMonth]}\"></td>\n </tr>\n\n</table>\n\n"
},
{
"answer_id": 74573224,
"author": "Sascha Doerdelmann",
"author_id": 11934850,
"author_profile": "https://Stackoverflow.com/users/11934850",
"pm_score": 1,
"selected": false,
"text": "context.setVariable(\"reports\", reports)\n <table>\n <thead>\n <tr>\n <th>Company</th>\n <th>FirstMonth</th>\n <th>LastMonth</th>\n </tr>\n </thead>\n <tbody>\n <tr th:each=\"key: ${report[\"reportData\"].keys}\">\n <td th:text=\"${reportData[key][\"companyName\"]}\"></td>\n <td th:text=\"${reportData[key][\"usageByMonth\"][report[\"firstMonth\"].toString()]}\"></td>\n <td th:text=\"${reportData[key][\"usageByMonth\"][report[\"lastMonth\"].toString()]}\"></td>\n </tr>\n </tbody>\n</table>\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5181689/"
] |
74,572,673
|
<p>How can i use sed for pase .rc file? And I need get from resource file blocks STRINGTABLE</p>
<pre><code>...
STRINGTABLE
BEGIN
IDS_ID101 "String1"
IDS_ID102 "String2"
END
...
</code></pre>
<p>and result need output to str_file.h</p>
<pre><code>std::map<int, std::string> m = {
{IDS_ID101, "String1"},
{IDS_ID102, "String2"},
};
</code></pre>
<p>How do I write a command in sed so that I can get this result?</p>
<p>I write this command, but this not help me</p>
<pre><code>sed '/^BEGIN$/{N;N;s/BEGIN\(.*\)END/replaced \1/}/g' ${RC_FILE} > test_rc.h
</code></pre>
|
[
{
"answer_id": 74573145,
"author": "Farukh Khan",
"author_id": 5181689,
"author_profile": "https://Stackoverflow.com/users/5181689",
"pm_score": 1,
"selected": true,
"text": "<table>\n <thead>\n <tr>\n <th>\n Kunde\n </th>\n <th>FirstMonth</th>\n <th>LastMonth</th>\n </tr>\n </thead>\n<tbody>\n <tr th:each=\"reporting: ${report.reportData}\">\n <td th:text=\"${reporting.value.companyName}\"></td>\n <td class=\"tableValue\" th:text=\"${reporting.value.usageByMonth[report.firstMonth]}\"></td>\n <td class=\"tableValue\" th:text=\"${reporting.value.usageByMonth[report.lastMonth]}\"></td>\n </tr>\n\n</table>\n\n"
},
{
"answer_id": 74573224,
"author": "Sascha Doerdelmann",
"author_id": 11934850,
"author_profile": "https://Stackoverflow.com/users/11934850",
"pm_score": 1,
"selected": false,
"text": "context.setVariable(\"reports\", reports)\n <table>\n <thead>\n <tr>\n <th>Company</th>\n <th>FirstMonth</th>\n <th>LastMonth</th>\n </tr>\n </thead>\n <tbody>\n <tr th:each=\"key: ${report[\"reportData\"].keys}\">\n <td th:text=\"${reportData[key][\"companyName\"]}\"></td>\n <td th:text=\"${reportData[key][\"usageByMonth\"][report[\"firstMonth\"].toString()]}\"></td>\n <td th:text=\"${reportData[key][\"usageByMonth\"][report[\"lastMonth\"].toString()]}\"></td>\n </tr>\n </tbody>\n</table>\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16517806/"
] |
74,572,709
|
<p>I've made an Python+Django+git docker container.
Now, I would like to 'Attach to a running container..' with VSCode to develop, i.e. run and debug, a Python app inside.
Is it good idea? Or it is better only setting up VSCode to run app inside the container?
I don't want VSCode make a docker container by itself.
Thanks.</p>
<p>I tried to 'Attach to a running container..' but have got 'error xhr failed...' etc.</p>
|
[
{
"answer_id": 74573101,
"author": "Chris Becke",
"author_id": 27491,
"author_profile": "https://Stackoverflow.com/users/27491",
"pm_score": 0,
"selected": false,
"text": ".devcontainers .devenvironments"
},
{
"answer_id": 74583688,
"author": "Andrey Dmitriev",
"author_id": 20599180,
"author_profile": "https://Stackoverflow.com/users/20599180",
"pm_score": 1,
"selected": false,
"text": "image_create.sh # script to create image to use it local and on the server\n\nimage_dockerfile # dockerfile with script how to create an image\n\ncontainer_create.sh # create named container from image\n\ncontainer_restart.sh # restart existing container\n\ncontainer_stop.sh # stop existing container\n FROM python:3.9.15-slim-bullseye\nUSER root\nRUN pip3 install requests telethon\nRUN apt-get update\nRUN apt-get --assume-yes install git\n docker rmi python_find_a_job:lts\ndocker build . -f python_find_a_job -t python_find_a_job:lts\n docker rm -f python_find_a_job\ndocker run -t -d --name python_find_a_job -i python_find_a_job:lts\ndocker ps -aq\n docker container restart python_find_a_job\ndocker ps -aq\n docker stop python_find_a_job\ndocker ps -aq\n"
},
{
"answer_id": 74612362,
"author": "Andrey Dmitriev",
"author_id": 20599180,
"author_profile": "https://Stackoverflow.com/users/20599180",
"pm_score": 0,
"selected": false,
"text": "version: '3.3'\nservices:\n my_container:\n image: python_find_a_job:lts\n stdin_open: true # docker run -i\n tty: true # docker run -t\n container_name: find_a_job\n network_mode: \"host\"\n volumes:\n - ~/.PYTHON/find_a_job:/opt/find_a_job\n mongodb_container:\n image: mongo:latest\n environment:\n MONGO_INITDB_ROOT_USERNAME: root\n MONGO_INITDB_ROOT_PASSWORD: pass\n network_mode: \"host\"\n ports:\n - 27017:27017\n volumes:\n - mongodb_data_container:/data/db\nvolumes:\n mongodb_data_container:\n docker compose up\n docker compose down\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20599180/"
] |
74,572,715
|
<pre><code>#include <stdio.h>
#include <math.h>
int main()
{
int i;
int j;
int base;
int height;
int side;
int up;
int down;
int output[1001];
for (i = 0; i < 1000; i++)
{
char type = getchar();
if(type == 'P')
{
scanf("%d", &side);
output[i] = side * side;
}
else if (type == 'S')
{
scanf("%d %d", &base, &height);
output[i] = 0.5 * base * height;
}
else if (type == 'T')
{
scanf("%d %d %d", &up, &down, &height);
output[i] = height * (up + down) / 2;
}
else if(type == '0')
{
break;
}
}
for(j = 0; j < i; j++)
{
{
printf("%d\n", output[j]);
}
}
return 0;
}
</code></pre>
<p>What i want is <strong>after i input '0'</strong>, the program <strong>stop asking for input</strong> and then <strong>give the output</strong>. Overall it's working but there's <strong>an error where in every output, there's always have 1 line of '0'.</strong></p>
<p><strong>Sample Input:</strong></p>
<pre><code>P 5
S 10 10
T 10 10 10
0
</code></pre>
<p><strong>Output that i want:</strong></p>
<pre><code>25
50
100
</code></pre>
<p><strong>Output that i have with this code right now:</strong></p>
<pre><code>25
0
50
0
100
0
</code></pre>
<p>I'm guessing it's the</p>
<pre><code>else if(type == '0')
{
break;
}
</code></pre>
<p>that make this error but i'm not sure and i don't know how to fix this</p>
|
[
{
"answer_id": 74572845,
"author": "Oka",
"author_id": 2505965,
"author_profile": "https://Stackoverflow.com/users/2505965",
"pm_score": 0,
"selected": false,
"text": "P 5\\n\nS 10 10\\n\nT 10 10 10\\n\n0\\n\n i i for (i = 0; i < 1000;)\n{ \n char type = getchar(); \n\n if(type == 'P') \n { \n scanf(\"%d\", &side); \n\n output[i++] = side * side; \n } \n else if (type == 'S') \n { \n scanf(\"%d %d\", &base, &height); \n\n output[i++] = 0.5 * base * height; \n } \n else if (type == 'T') \n { \n scanf(\"%d %d %d\", &up, &down, &height); \n\n output[i++] = height * (up + down) / 2; \n } \n else if(type == '0') \n { \n break; \n } \n}\n EOF getchar scanf #include <stdio.h>\n#include <stdlib.h>\n\n#define MAX 1001\n\nint get_int(void)\n{\n int x;\n\n if (1 != scanf(\"%d\", &x))\n exit(EXIT_FAILURE);\n\n return x;\n}\n\nint main(void)\n{\n int i = 0;\n int output[MAX];\n\n while (i < MAX) {\n int type = getchar();\n\n if (EOF == type || '0' == type)\n break;\n\n int value;\n int up, down, height, side;\n\n switch (type) {\n case 'P':\n side = get_int();\n value = side * side;\n break;\n case 'S':\n value = 0.5 * get_int() * get_int();\n break;\n case 'T':\n up = get_int();\n down = get_int();\n height = get_int();\n value = height * (up + down) / 2;\n break;\n default:\n continue;\n }\n\n output[i++] = value;\n }\n\n for (int j = 0; j < i; j++) {\n printf(\"%d\\n\", output[j]);\n }\n}\n"
},
{
"answer_id": 74573124,
"author": "Andreas Wenzel",
"author_id": 12149471,
"author_profile": "https://Stackoverflow.com/users/12149471",
"pm_score": 1,
"selected": false,
"text": "scanf(\"%d\", &side);\nscanf(\"%d %d\", &base, &height);\nscanf(\"%d %d %d\", &up, &down, &height);\n getchar scanf getchar type \\n 10 getchar scanf scanf fgets sscanf #include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint main( void )\n{\n int output[1000];\n char line[200];\n int i;\n\n //attempt to read one line of input per loop iteration\n for ( i = 0; ; i++ ) //infinite loop\n {\n char *p;\n\n //protect against buffer overflow\n if ( i == sizeof output / sizeof *output )\n {\n fprintf( stderr, \"Too many lines!\\n\" );\n exit( EXIT_FAILURE );\n }\n\n //attempt to read one line of input\n if ( fgets( line, sizeof line, stdin ) == NULL )\n {\n fprintf( stderr, \"Error reading input!\\n\" );\n exit( EXIT_FAILURE );\n }\n\n //attempt to find newline character in the line\n p = strchr( line, '\\n' );\n\n //verify that entire line was read and remove the\n //newline character, if it exists\n if ( p == NULL )\n {\n //a missing newline character is probably acceptable\n //when end-of-file has been reached, for example when\n //standard input is being piped from a file.\n if ( !feof( stdin ) )\n {\n fprintf( stderr, \"Line too long for input buffer!\\n\" );\n exit( EXIT_FAILURE );\n }\n }\n else\n {\n //remove the newline character by overwriting it with\n //a terminating null character\n *p = '\\0';\n }\n\n if( line[0] == 'P' )\n {\n int side;\n\n if ( sscanf( line+1, \"%d\", &side ) != 1 )\n {\n fprintf( stderr, \"Error parsing input!\\n\" );\n exit( EXIT_FAILURE );\n }\n\n output[i] = side * side;\n }\n else if ( line[0] == 'S' )\n {\n int base, height;\n\n if ( sscanf( line+1, \"%d %d\", &base, &height ) != 2 )\n {\n fprintf( stderr, \"Error parsing input!\\n\" );\n exit( EXIT_FAILURE );\n }\n\n output[i] = 0.5 * base * height;\n }\n else if ( line[0] == 'T' )\n {\n int up, down, height;\n\n if ( sscanf( line+1, \"%d %d %d\", &up, &down, &height ) != 3 )\n {\n fprintf( stderr, \"Error parsing input!\\n\" );\n exit( EXIT_FAILURE );\n }\n\n output[i] = height * (up + down) / 2;\n }\n else if ( line[0] == '0' )\n {\n //break out of infinite loop\n break;\n }\n }\n \n for ( int j = 0; j < i; j++ )\n {\n printf( \"%d\\n\", output[j] );\n }\n \n return 0;\n}\n 25\n50\n100\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20596587/"
] |
74,572,735
|
<p>I want to add and image into a View (represented by the black square on the example bellow), the view size depends on screens sizes. I also want an <code>overflow: hidden</code> on the bottom of my image if the first view is to small</p>
<p><a href="https://i.stack.imgur.com/touPN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/touPN.png" alt="enter image description here" /></a></p>
<p>If I try on my image :</p>
<pre class="lang-js prettyprint-override"><code> width: '100%',
height: undefined,
aspectRatio: 1,
</code></pre>
<p>my image is centered, and not anchor to the top.</p>
<p>Any solution ?</p>
|
[
{
"answer_id": 74572845,
"author": "Oka",
"author_id": 2505965,
"author_profile": "https://Stackoverflow.com/users/2505965",
"pm_score": 0,
"selected": false,
"text": "P 5\\n\nS 10 10\\n\nT 10 10 10\\n\n0\\n\n i i for (i = 0; i < 1000;)\n{ \n char type = getchar(); \n\n if(type == 'P') \n { \n scanf(\"%d\", &side); \n\n output[i++] = side * side; \n } \n else if (type == 'S') \n { \n scanf(\"%d %d\", &base, &height); \n\n output[i++] = 0.5 * base * height; \n } \n else if (type == 'T') \n { \n scanf(\"%d %d %d\", &up, &down, &height); \n\n output[i++] = height * (up + down) / 2; \n } \n else if(type == '0') \n { \n break; \n } \n}\n EOF getchar scanf #include <stdio.h>\n#include <stdlib.h>\n\n#define MAX 1001\n\nint get_int(void)\n{\n int x;\n\n if (1 != scanf(\"%d\", &x))\n exit(EXIT_FAILURE);\n\n return x;\n}\n\nint main(void)\n{\n int i = 0;\n int output[MAX];\n\n while (i < MAX) {\n int type = getchar();\n\n if (EOF == type || '0' == type)\n break;\n\n int value;\n int up, down, height, side;\n\n switch (type) {\n case 'P':\n side = get_int();\n value = side * side;\n break;\n case 'S':\n value = 0.5 * get_int() * get_int();\n break;\n case 'T':\n up = get_int();\n down = get_int();\n height = get_int();\n value = height * (up + down) / 2;\n break;\n default:\n continue;\n }\n\n output[i++] = value;\n }\n\n for (int j = 0; j < i; j++) {\n printf(\"%d\\n\", output[j]);\n }\n}\n"
},
{
"answer_id": 74573124,
"author": "Andreas Wenzel",
"author_id": 12149471,
"author_profile": "https://Stackoverflow.com/users/12149471",
"pm_score": 1,
"selected": false,
"text": "scanf(\"%d\", &side);\nscanf(\"%d %d\", &base, &height);\nscanf(\"%d %d %d\", &up, &down, &height);\n getchar scanf getchar type \\n 10 getchar scanf scanf fgets sscanf #include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint main( void )\n{\n int output[1000];\n char line[200];\n int i;\n\n //attempt to read one line of input per loop iteration\n for ( i = 0; ; i++ ) //infinite loop\n {\n char *p;\n\n //protect against buffer overflow\n if ( i == sizeof output / sizeof *output )\n {\n fprintf( stderr, \"Too many lines!\\n\" );\n exit( EXIT_FAILURE );\n }\n\n //attempt to read one line of input\n if ( fgets( line, sizeof line, stdin ) == NULL )\n {\n fprintf( stderr, \"Error reading input!\\n\" );\n exit( EXIT_FAILURE );\n }\n\n //attempt to find newline character in the line\n p = strchr( line, '\\n' );\n\n //verify that entire line was read and remove the\n //newline character, if it exists\n if ( p == NULL )\n {\n //a missing newline character is probably acceptable\n //when end-of-file has been reached, for example when\n //standard input is being piped from a file.\n if ( !feof( stdin ) )\n {\n fprintf( stderr, \"Line too long for input buffer!\\n\" );\n exit( EXIT_FAILURE );\n }\n }\n else\n {\n //remove the newline character by overwriting it with\n //a terminating null character\n *p = '\\0';\n }\n\n if( line[0] == 'P' )\n {\n int side;\n\n if ( sscanf( line+1, \"%d\", &side ) != 1 )\n {\n fprintf( stderr, \"Error parsing input!\\n\" );\n exit( EXIT_FAILURE );\n }\n\n output[i] = side * side;\n }\n else if ( line[0] == 'S' )\n {\n int base, height;\n\n if ( sscanf( line+1, \"%d %d\", &base, &height ) != 2 )\n {\n fprintf( stderr, \"Error parsing input!\\n\" );\n exit( EXIT_FAILURE );\n }\n\n output[i] = 0.5 * base * height;\n }\n else if ( line[0] == 'T' )\n {\n int up, down, height;\n\n if ( sscanf( line+1, \"%d %d %d\", &up, &down, &height ) != 3 )\n {\n fprintf( stderr, \"Error parsing input!\\n\" );\n exit( EXIT_FAILURE );\n }\n\n output[i] = height * (up + down) / 2;\n }\n else if ( line[0] == '0' )\n {\n //break out of infinite loop\n break;\n }\n }\n \n for ( int j = 0; j < i; j++ )\n {\n printf( \"%d\\n\", output[j] );\n }\n \n return 0;\n}\n 25\n50\n100\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18371570/"
] |
74,572,757
|
<p>Hello im trying to communicate with my bot discord but its doesnt answer
the bot is online but no answer here the following code :</p>
<pre><code>import discord
client = discord.Client(intents=discord.Intents.default())
client.run("token")
@client.event
async def on_message(message):
if message.content == "ping":
await message.channel.send("pong")
</code></pre>
|
[
{
"answer_id": 74573448,
"author": "Kejax",
"author_id": 20059231,
"author_profile": "https://Stackoverflow.com/users/20059231",
"pm_score": 3,
"selected": true,
"text": "intents.message_content = True\n Message Content Privileged Intents"
},
{
"answer_id": 74574412,
"author": "ARealWant",
"author_id": 13936868,
"author_profile": "https://Stackoverflow.com/users/13936868",
"pm_score": 1,
"selected": false,
"text": "intents=discord.Intents.default() self.message_content intents = discord.Intents.all()\nclient = discord.Client(intents=intents)\n"
},
{
"answer_id": 74582122,
"author": "stijndcl",
"author_id": 13568999,
"author_profile": "https://Stackoverflow.com/users/13568999",
"pm_score": 1,
"selected": false,
"text": "message_content client.run() on_message client.run()"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19386079/"
] |
74,572,759
|
<p>So I have <a href="https://python-reference.readthedocs.io/en/latest/docs/generator/send.html" rel="nofollow noreferrer">the following generator function</a>:</p>
<pre><code>def gen(n=5):
for i in range(n):
n = yield n
for i in gen(3):
print(i)
</code></pre>
<h2>The result:</h2>
<pre><code>3
None
None
</code></pre>
<hr />
<p>I understand the first result of yield is 3. Because I assigned 3 to function argument <code>n</code>. But <strong>where are the <code>None</code> in the second and third yield coming from?</strong> Is it because in the for-loop, <code>yield n</code> returns <code>None</code> and this <code>None</code> is assigned to <code>n</code> in this line: <code>n = yield n</code>?</p>
|
[
{
"answer_id": 74572966,
"author": "Thierry Lathuille",
"author_id": 550094,
"author_profile": "https://Stackoverflow.com/users/550094",
"pm_score": 3,
"selected": true,
"text": "for n None n None"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1516331/"
] |
74,572,771
|
<p>The only thing I need to see in the output is which functions were called.</p>
<p>Input:</p>
<pre><code>ibv_rc_pingpong-759367 [005] 8391981.416466: funcgraph_entry: | ib_enum_all_devs() {
ibv_rc_pingpong-759367 [005] 8391981.416472: funcgraph_entry: + 29.337 us | ib_get_device_fw_str();
ibv_rc_pingpong-759367 [005] 8391981.416504: funcgraph_exit: + 38.787 us | }
ibv_rc_pingpong-759367 [005] 8391981.416543: funcgraph_entry: 1.191 us | ib_enum_all_devs();
ibv_rc_pingpong-759367 [005] 8391981.416621: funcgraph_entry: 1.371 us | ib_device_get_by_index();
ibv_rc_pingpong-759367 [005] 8391981.416624: funcgraph_entry: | ib_get_client_nl_info() {
ibv_rc_pingpong-759367 [005] 8391981.416628: funcgraph_entry: 0.890 us | ib_uverbs_get_nl_info();
ibv_rc_pingpong-759367 [005] 8391981.416630: funcgraph_exit: 6.174 us | }
</code></pre>
<p>The output should look like this:</p>
<pre><code>ib_enum_all_devs() {
ib_get_device_fw_str();
}
ib_enum_all_devs();
ib_device_get_by_index();
ib_get_client_nl_info() {
ib_uverbs_get_nl_info();
}
</code></pre>
<p>This is what I tried:</p>
<pre><code>cat myfile.dat | awk '{print $7}'
</code></pre>
<p>However, this gives me garbage.</p>
|
[
{
"answer_id": 74572843,
"author": "Dominique",
"author_id": 4279155,
"author_profile": "https://Stackoverflow.com/users/4279155",
"pm_score": 3,
"selected": true,
"text": "cat myfile.dat | awk -F \"|\" '{print $2}'\n cat awk -F \"|\" '{print $2}' file.txt\n"
},
{
"answer_id": 74572883,
"author": "anubhava",
"author_id": 548225,
"author_profile": "https://Stackoverflow.com/users/548225",
"pm_score": 2,
"selected": false,
"text": "awk awk -F ' \\\\| ' '{print $NF}' file\n\nib_enum_all_devs() {\n ib_get_device_fw_str();\n}\nib_enum_all_devs();\nib_device_get_by_index();\nib_get_client_nl_info() {\n ib_uverbs_get_nl_info();\n}\n"
},
{
"answer_id": 74573787,
"author": "Daweo",
"author_id": 10785975,
"author_profile": "https://Stackoverflow.com/users/10785975",
"pm_score": 2,
"selected": false,
"text": "AWK file.txt ibv_rc_pingpong-759367 [005] 8391981.416466: funcgraph_entry: | ib_enum_all_devs() {\nibv_rc_pingpong-759367 [005] 8391981.416472: funcgraph_entry: + 29.337 us | ib_get_device_fw_str();\nibv_rc_pingpong-759367 [005] 8391981.416504: funcgraph_exit: + 38.787 us | }\nibv_rc_pingpong-759367 [005] 8391981.416543: funcgraph_entry: 1.191 us | ib_enum_all_devs();\nibv_rc_pingpong-759367 [005] 8391981.416621: funcgraph_entry: 1.371 us | ib_device_get_by_index();\nibv_rc_pingpong-759367 [005] 8391981.416624: funcgraph_entry: | ib_get_client_nl_info() {\nibv_rc_pingpong-759367 [005] 8391981.416628: funcgraph_entry: 0.890 us | ib_uverbs_get_nl_info();\nibv_rc_pingpong-759367 [005] 8391981.416630: funcgraph_exit: 6.174 us | }\n awk '{print substr($0, 84)}' file.txt\n ib_enum_all_devs() {\n ib_get_device_fw_str();\n}\nib_enum_all_devs();\nib_device_get_by_index();\nib_get_client_nl_info() {\n ib_uverbs_get_nl_info();\n}\n substr $0"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8967376/"
] |
74,572,773
|
<p>I am trying to write a program that will let me know if a number has the odd divisor greater than one. Let's n be the number, and x be the divisor. x%2!=0 and x>1;
Code:</p>
<pre><code>import java.util.Scanner;
public class Simple1{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
long n;
for(int i=0; i<t; i++) {
n=sc.nextLong();
if(n<3)System.out.println("NO");
else {
if(n%2!=0)System.out.println("YES");
else {
int ans=0;
for(long j=3; j<=n/2; j+=2) {
if(n%j==0) {
ans=1;
break;
}
}
if(ans==1)System.out.println("YES");
else System.out.println("NO");
}
}
}
}
}
</code></pre>
<p>This java code works fine. But it's not working for a specific input.. and that is n = 1099511627776. If I change the last digit to any int other than 6, then it works fine and gives output. Even numbers greater than that works. But only this number n=1099511627776, when I input this to my program, no terminating happens and no output. Help me to figure out what happens here.</p>
|
[
{
"answer_id": 74573107,
"author": "khelwood",
"author_id": 3890632,
"author_profile": "https://Stackoverflow.com/users/3890632",
"pm_score": 3,
"selected": true,
"text": "1099511627776 2199023255552 549755813888 n long n = sc.nextLong();\nwhile (n > 1 && n % 2 == 0) {\n n /= 2;\n}\nif (n > 1) {\n System.out.println(\"Yes.\");\n} else {\n System.out.println(\"No.\");\n}\n // Powers of 2 have the property that n & (n-1) is zero\nif ((n & (n - 1)) != 0) {\n System.out.println(\"Yes.\"); // Not a power of two, so has an odd factor\n} else {\n System.out.println(\"No.\"); // Is a power of two, so does not have an odd factor\n}\n"
},
{
"answer_id": 74573321,
"author": "matt",
"author_id": 2067492,
"author_profile": "https://Stackoverflow.com/users/2067492",
"pm_score": 1,
"selected": false,
"text": "long number = 1099511627776l;\nlong r = number >> Long.numberOfTrailingZeros(number);\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17030235/"
] |
74,572,809
|
<p>I used one of the given examples here: <a href="https://reactrouter.com/en/v6.3.0/getting-started/overview" rel="nofollow noreferrer">https://reactrouter.com/en/v6.3.0/getting-started/overview</a>, after testing my own code which also didn't appear.</p>
<pre><code>import React from "react";
import { Routes, Route, Outlet } from "react-router-dom";
function App() {
return (
<Routes>
<Route path="invoices" element={<Invoices />}>
<Route path=":invoiceId" element={<Invoice />} />
<Route path="sent" element={<SentInvoices />} />
</Route>
</Routes>
);
}
function Invoices() {
return (
<div>
<h1>Invoices</h1>
<Outlet />
</div>
);
}
function Invoice() {
return <h1>Invoice </h1>;
}
function SentInvoices() {
return <h1>Sent Invoices</h1>;
}
export default App;
</code></pre>
<p>I still don't get anything showing up after running the code, just a white screen.</p>
|
[
{
"answer_id": 74573041,
"author": "evilcore29",
"author_id": 19879044,
"author_profile": "https://Stackoverflow.com/users/19879044",
"pm_score": 2,
"selected": false,
"text": "import React from \"react\";\nimport { BrowserRouter, Routes, Route, Outlet } from \"react-router-dom\";\n\nfunction App() {\n return (\n <BrowserRouter>\n <Routes>\n <Route path=\"invoices\" element={<Invoices />}>\n <Route path=\":invoiceId\" element={<Invoice />} />\n <Route path=\"sent\" element={<SentInvoices />} />\n </Route>\n </Routes>\n </BrowserRouter>\n );\n}\n\nfunction Invoices() {\n return (\n <div>\n <h1>Invoices</h1>\n <Outlet />\n </div>\n );\n}\n\nfunction Invoice() {\n return <h1>Invoice </h1>;\n}\n\nfunction SentInvoices() {\n return <h1>Sent Invoices</h1>;\n}\n\nexport default App;"
},
{
"answer_id": 74573454,
"author": "Ayan Naseer",
"author_id": 20599297,
"author_profile": "https://Stackoverflow.com/users/20599297",
"pm_score": 2,
"selected": true,
"text": "import React from \"react\";\nimport { BrowserRouter, Routes, Route, Outlet } from \"react-router-dom\";\n\nfunction App() {\n return (\n <BrowserRouter>\n <Routes>\n <Route path=\"/invoices\" element={<Invoices />}>\n <Route path=\"/:invoiceId\" element={<Invoice />} />\n <Route path=\"/sent\" element={<SentInvoices />} />\n </BrowserRouter>\n );\n}\n\nfunction Invoices() {\n return (\n <div>\n <h1>Invoices</h1>\n <Outlet />\n </div>\n );\n}\n\nfunction Invoice() {\n return <h1>Invoice </h1>;\n}\n\nfunction SentInvoices() {\n return <h1>Sent Invoices</h1>;\n}\n\nexport default App; import React from \"react\";\nimport { BrowserRouter, Routes, Route, Outlet } from \"react-router-dom\";\n\nfunction App() {\n return (\n <BrowserRouter>\n <Routes>\n <Route path=\"invoices\" element={<Invoices />}>\n <Route path=\":invoiceId\" element={<Invoice />} />\n <Route path=\"sent\" element={<SentInvoices />} />\n </Route>\n </Routes>\n </BrowserRouter>\n );\n}\n\nfunction Invoices() {\n return (\n <div>\n <h1>Invoices</h1>\n <Outlet />\n </div>\n );\n}\n\nfunction Invoice() {\n return <h1>Invoice </h1>;\n}\n\nfunction SentInvoices() {\n return <h1>Sent Invoices</h1>;\n}\n\nexport default App;"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20518918/"
] |
74,572,813
|
<p>I have data in an array of objects as below:</p>
<pre><code>history = [
{item: cake, calories: 120, datetime: 2022-11-16 07:51:26},
{item: chicken, calories: 250, datetime: 2022-11-16 13:48:46},
{item: pizza, calories: 420, datetime: 2022-11-25 11:13:42}
];
</code></pre>
<p>I want to render a div with a heading for the date and group all items with same dates in a list. I am using my map function like below:</p>
<pre><code>function renderHistory () {
let date;
return props.history.map((item, i) => {
const dateAdded = item.datetime.split(" ")[0];
if (date !== dateAdded) {
date = dateAdded;
return (
<>
<div>
<h2>{dateAdded}</h2>
<li>{item.item} - {item.calories} calories</li>
</>
)
}
return (
<>
<li>{item.item} - {item.calories} calories</li>
</div>
</>
)
})
}
</code></pre>
<p>I get an error <code>Expected corresponding JSX closing tag for <div></code></p>
<p>If I return like below the second item gets out of the div.</p>
<pre><code>return props.history.map((item, i) => {
const dateAdded = item.datetime.split(" ")[0];
if (date !== dateAdded) {
date = dateAdded;
return (
<div>
<h2>{dateAdded}</h2>
<li>{item.item} - {item.calories} calories</li>
</div>
)
}
return (
<li>{item.item} - {item.calories} calories</li>
)
})
</code></pre>
<p>How do I put all items with same date in a single div?</p>
|
[
{
"answer_id": 74573041,
"author": "evilcore29",
"author_id": 19879044,
"author_profile": "https://Stackoverflow.com/users/19879044",
"pm_score": 2,
"selected": false,
"text": "import React from \"react\";\nimport { BrowserRouter, Routes, Route, Outlet } from \"react-router-dom\";\n\nfunction App() {\n return (\n <BrowserRouter>\n <Routes>\n <Route path=\"invoices\" element={<Invoices />}>\n <Route path=\":invoiceId\" element={<Invoice />} />\n <Route path=\"sent\" element={<SentInvoices />} />\n </Route>\n </Routes>\n </BrowserRouter>\n );\n}\n\nfunction Invoices() {\n return (\n <div>\n <h1>Invoices</h1>\n <Outlet />\n </div>\n );\n}\n\nfunction Invoice() {\n return <h1>Invoice </h1>;\n}\n\nfunction SentInvoices() {\n return <h1>Sent Invoices</h1>;\n}\n\nexport default App;"
},
{
"answer_id": 74573454,
"author": "Ayan Naseer",
"author_id": 20599297,
"author_profile": "https://Stackoverflow.com/users/20599297",
"pm_score": 2,
"selected": true,
"text": "import React from \"react\";\nimport { BrowserRouter, Routes, Route, Outlet } from \"react-router-dom\";\n\nfunction App() {\n return (\n <BrowserRouter>\n <Routes>\n <Route path=\"/invoices\" element={<Invoices />}>\n <Route path=\"/:invoiceId\" element={<Invoice />} />\n <Route path=\"/sent\" element={<SentInvoices />} />\n </BrowserRouter>\n );\n}\n\nfunction Invoices() {\n return (\n <div>\n <h1>Invoices</h1>\n <Outlet />\n </div>\n );\n}\n\nfunction Invoice() {\n return <h1>Invoice </h1>;\n}\n\nfunction SentInvoices() {\n return <h1>Sent Invoices</h1>;\n}\n\nexport default App; import React from \"react\";\nimport { BrowserRouter, Routes, Route, Outlet } from \"react-router-dom\";\n\nfunction App() {\n return (\n <BrowserRouter>\n <Routes>\n <Route path=\"invoices\" element={<Invoices />}>\n <Route path=\":invoiceId\" element={<Invoice />} />\n <Route path=\"sent\" element={<SentInvoices />} />\n </Route>\n </Routes>\n </BrowserRouter>\n );\n}\n\nfunction Invoices() {\n return (\n <div>\n <h1>Invoices</h1>\n <Outlet />\n </div>\n );\n}\n\nfunction Invoice() {\n return <h1>Invoice </h1>;\n}\n\nfunction SentInvoices() {\n return <h1>Sent Invoices</h1>;\n}\n\nexport default App;"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7085305/"
] |
74,572,847
|
<p>I'm having a weird error. On a component I have, Ref is working correctly.
On a component I've just created, id doesn't. I'm calling it the same way on both.</p>
<pre><code>import { Ref } from 'vue';
const isOpen = ref(false);
</code></pre>
<p>Giving the error:</p>
<blockquote>
<p>Uncaught (in promise) SyntaxError: The requested module '/node_modules/.vite/deps/vue.js?v=f65e1616' does not provide an export named 'Ref'</p>
</blockquote>
<p>I've tried running "npm run build" again, with the following error:</p>
<blockquote>
<p>Non-existent export 'Ref' is imported from
node_modules/vue/dist/vue.runtime.esm-bundler.js</p>
</blockquote>
<p>I don't really know what could be causing this. I work on this project on 2 different computers and I've cloned it a few days ago. I haven't encountered any issues until now</p>
|
[
{
"answer_id": 74573041,
"author": "evilcore29",
"author_id": 19879044,
"author_profile": "https://Stackoverflow.com/users/19879044",
"pm_score": 2,
"selected": false,
"text": "import React from \"react\";\nimport { BrowserRouter, Routes, Route, Outlet } from \"react-router-dom\";\n\nfunction App() {\n return (\n <BrowserRouter>\n <Routes>\n <Route path=\"invoices\" element={<Invoices />}>\n <Route path=\":invoiceId\" element={<Invoice />} />\n <Route path=\"sent\" element={<SentInvoices />} />\n </Route>\n </Routes>\n </BrowserRouter>\n );\n}\n\nfunction Invoices() {\n return (\n <div>\n <h1>Invoices</h1>\n <Outlet />\n </div>\n );\n}\n\nfunction Invoice() {\n return <h1>Invoice </h1>;\n}\n\nfunction SentInvoices() {\n return <h1>Sent Invoices</h1>;\n}\n\nexport default App;"
},
{
"answer_id": 74573454,
"author": "Ayan Naseer",
"author_id": 20599297,
"author_profile": "https://Stackoverflow.com/users/20599297",
"pm_score": 2,
"selected": true,
"text": "import React from \"react\";\nimport { BrowserRouter, Routes, Route, Outlet } from \"react-router-dom\";\n\nfunction App() {\n return (\n <BrowserRouter>\n <Routes>\n <Route path=\"/invoices\" element={<Invoices />}>\n <Route path=\"/:invoiceId\" element={<Invoice />} />\n <Route path=\"/sent\" element={<SentInvoices />} />\n </BrowserRouter>\n );\n}\n\nfunction Invoices() {\n return (\n <div>\n <h1>Invoices</h1>\n <Outlet />\n </div>\n );\n}\n\nfunction Invoice() {\n return <h1>Invoice </h1>;\n}\n\nfunction SentInvoices() {\n return <h1>Sent Invoices</h1>;\n}\n\nexport default App; import React from \"react\";\nimport { BrowserRouter, Routes, Route, Outlet } from \"react-router-dom\";\n\nfunction App() {\n return (\n <BrowserRouter>\n <Routes>\n <Route path=\"invoices\" element={<Invoices />}>\n <Route path=\":invoiceId\" element={<Invoice />} />\n <Route path=\"sent\" element={<SentInvoices />} />\n </Route>\n </Routes>\n </BrowserRouter>\n );\n}\n\nfunction Invoices() {\n return (\n <div>\n <h1>Invoices</h1>\n <Outlet />\n </div>\n );\n}\n\nfunction Invoice() {\n return <h1>Invoice </h1>;\n}\n\nfunction SentInvoices() {\n return <h1>Sent Invoices</h1>;\n}\n\nexport default App;"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18197440/"
] |
74,572,928
|
<p>I have example data as follows:</p>
<pre><code>library(data.table)
dat1 <- fread("code1 code2 code3
A3 B2 C1
A4 B3 C2")
dat2 <- fread("codes
A3
A4
B2
B3")
</code></pre>
<p>I would simply like to replace the codes in <code>dat2</code> with <code>code3</code> from <code>dat1</code>.</p>
<p>Desired output:</p>
<pre><code>dat_out <- fread("codes
C1
C2
C1
C2")
</code></pre>
<p>How should I do this?</p>
|
[
{
"answer_id": 74573195,
"author": "Anoushiravan R",
"author_id": 14314520,
"author_profile": "https://Stackoverflow.com/users/14314520",
"pm_score": 2,
"selected": false,
"text": "library(tidyverse)\n\ndat2 %>% \n inner_join(dat1 %>% pivot_longer(!code3), by = c('codes'='value')) %>%\n select(!name) %>%\n mutate(codes = coalesce(!!!rev(.))) %>%\n select(codes)\n\n codes\n1: C1\n2: C2\n3: C1\n4: C2\n"
},
{
"answer_id": 74573260,
"author": "Maël",
"author_id": 13460602,
"author_profile": "https://Stackoverflow.com/users/13460602",
"pm_score": 3,
"selected": true,
"text": "match `%r%`<- function(x, y) replace(x %% y, x %% y == 0, y)\ndat2[, codes := dat1$code3[match(dat2$codes, unlist(dat1)) %r% nrow(dat1)]]\n\n# codes\n#1: C1\n#2: C2\n#3: C1\n#4: C2\n match unlist dat1 %% nrow(dat1) nrow"
},
{
"answer_id": 74573697,
"author": "ThomasIsCoding",
"author_id": 12158757,
"author_profile": "https://Stackoverflow.com/users/12158757",
"pm_score": 3,
"selected": false,
"text": "melt on = ... data.table dat2[\n melt(dat1, id.var = \"code3\"), \n .(codes = code3),\n on = c(codes = \"value\")\n]\n \n> dat2[melt(dat1, id.var = \"code3\"), .(codes = code3), on = c(codes = \"value\")]\n codes\n1: C1\n2: C2\n3: C1\n4: C2\n melt(dat1, id.var = \"code3\") > melt(dat1, id.var = \"code3\")\n code3 variable value\n1: C1 code1 A3\n2: C2 code1 A4\n3: C1 code2 B2\n4: C2 code2 B3\n"
},
{
"answer_id": 74576785,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 1,
"selected": false,
"text": "dat2[, codes := setNames(rep(dat1$code3, 2), unlist(dat1[, 1:2]))[codes]]\n > dat2\n codes\n <char>\n1: C1\n2: C2\n3: C1\n4: C2\n"
},
{
"answer_id": 74585289,
"author": "B. Christian Kamgang",
"author_id": 10848898,
"author_profile": "https://Stackoverflow.com/users/10848898",
"pm_score": 0,
"selected": false,
"text": "match dat2[, codes := dat1[, rep(code3, 2)[match(codes, c(code1, code2))]]]\n\n codes\n1: C1\n2: C2\n3: C1\n4: C2\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8071608/"
] |
74,572,945
|
<p>I have following string <code>GA1.2.4451363243.9414195136</code> and I want to match <code>4451363243.9414195136</code> using regular expression for python.</p>
<p>I have tried the following which is not working <code>([\d].[\d])$</code></p>
<p>Where am I going wrong here?</p>
|
[
{
"answer_id": 74573003,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": false,
"text": "s = 'GA1.2.4451363243.9414195136'\n\nout = '.'.join(s.rsplit('.', 2)[-2:])\n# '4451363243.9414195136'\n\nimport re\nout = re.search(r'[^.]*\\.[^.]*$', s)\n# <re.Match object; span=(6, 27), match='4451363243.9414195136'>\n [^.] . \\d N = 3\n\nout = '.'.join(s.rsplit('.', N)[-N:])\n# '2.4451363243.9414195136'\n\nout = re.search(fr'[^.]*(?:\\.[^.]*){{{N-1}}}$', s)\n# <re.Match object; span=(4, 27), match='2.4451363243.9414195136'>\n"
},
{
"answer_id": 74573017,
"author": "Jib",
"author_id": 20124358,
"author_profile": "https://Stackoverflow.com/users/20124358",
"pm_score": 2,
"selected": true,
"text": "([0-9]+.[0-9]+)$ >>> import re\n>>> data = \"GA1.2.4451363243.941419513\"\n>>> re.findall(r\"([0-9]+.[0-9]+)$\", data)\n['4451363243.941419513']\n"
},
{
"answer_id": 74573102,
"author": "BSimjoo",
"author_id": 7421566,
"author_profile": "https://Stackoverflow.com/users/7421566",
"pm_score": 2,
"selected": false,
"text": "(?:[\\w\\d]*.){2}(.*)\n import re\ns = 'GA1.2.4451363243.9414195136'\nre.match(r'(?:[\\w\\d]*.){2}(.*)',s).groups()[0] # output: '4451363243.9414195136'\n s.split('.',2)[-1] # output: '4451363243.9414195136'\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/396476/"
] |
74,572,958
|
<p>Hello I have a project for my studies which is to display data on a dashboard that will be more or less modifiable by the user according to his needs.</p>
<p>I wanted to add space between a parameter icon and a "GV" text. I have tried to use justify-content="space-between" in ".panel-1 .panel-header" (CSS file) but the space between the two elements does not appear. I would like to know where my error comes from?</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>@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap');
*{
font-family: 'Poppins', sans-serif;
margin: 0;
padding: 0;
box-sizing: border-box
}
:root{
/* ===== Colors ===== */
--body-color: #E4E9F7;
--sidebar-color: #FFF;
--primary-color: #1c1a1a;
--primary-color-light: #F6F5FF;
--toggle-color: #DDD;
--text-color: #707070;
/* ===== Transition ===== */
--tran-02: all 0.2s ease;
--tran-03: all 0.3s ease;
--tran-04: all 0.4s ease;
--tran-05: all 0.5s ease;
}
body{
height: 100vh;
background: var(--body-color);
}
/*Paramètres de la sidebar*/
.sidebar{
position: fixed;
top: 0;
left: 0;
height:100%;
width: 78px;
background: var(--primary-color);
padding: 6px 14px;
transition: all 0.5s ease;
}
/*Activer l'élargissement de la sidebar*/
.sidebar.active{
width: 240px
}
/*Paramètre du logo*/
.sidebar .logo_content .logo{
color: #FFF;
display: flex;
height: 50px;
width:100%;
align-items: center;
opacity: 0;
pointer-events: none;
}
/*Activation de l'affichage du logo*/
.sidebar.active .logo_content .logo{
opacity: 1;
pointer-events: none;
}
/*?*/
.logo_content .logo i{
font-size: 28px;
margin-right: 5px;
}
/*Paramètre texte logo*/
.logo_content .logo .logo_name{
font-size: 20px;
font-weight: 400;
}
/*Paramètre du bouton d'activation de la sidebar*/
.sidebar #btn{
position: absolute;
color: #FFF;
top: 6px;
left: 50%;
font-size: 20px;
height: 50px;
width: 50px;
text-align: center;
line-height: 50px;
cursor: pointer;
transform: translateX(-50%);
}
/*Activer le déplacement du bouton en mode toggle*/
.sidebar.active #btn{
left:90%;
}
/**/
.sidebar .divider{
margin-top:0px;
font-size: 12px;
text-transform: uppercase;
font-weight: 700;
color: #707070;
text-align: center;
}
.sidebar.active .divider{
margin-top:0px;
font-size: 12px;
text-transform: uppercase;
font-weight: 700;
color: #707070;
text-align: left;
}
/*Paramètre de la liste*/
.sidebar ul{
margin-top: 20px;
}
/*Paramètres pour chaque éléments de la liste*/
.sidebar li{
position: relative;
height: 50px;
width: 100%;
margin: 0 0px;
list-style: none;
line-height:50px ;
}
/*Paramètres des textes de chaque élément*/
.sidebar li a{
color: #FFF;
display: flex;
align-items: center;
text-decoration: none;
transition: all 0.4s ease;
border-radius: 12px;
white-space: nowrap;
}
/*Activer un fond par dessus lors du passage de la souris*/
.sidebar li a:hover{
color: #11101d;
background: #FFF;
}
/*Paramètres des logos*/
.sidebar li a i{
height: 50px;
min-width: 50px;
border-radius: 12px;
line-height: 50px;
text-align: center;
}
/*Désactiver l'affichage des noms*/
.sidebar .links_name{
opacity: 0;
pointer-events: none;
}
/*Activer l'affichage des noms*/
.sidebar.active .links_name{
opacity: 1;
pointer-events: auto;
}
/*Séparation des 2 sous menus*/
.sidebar .menu-bar{
height: calc(100% - 50px);
display: flex;
flex-direction: column;
justify-content: space-between;
}
/*Paramètres de la page des templates*/
.home{
position: relative;
height: 100vh;
left: 78px;
width: calc(100% - 78px);
background: var(--body-color);
transition: var(--tran-05);
}
/*Paramètre texte de la page*/
.home .text{
font-size: 30px;
font-weight: 500;
color: var(--text-color);
padding: 8px 40px;
}
/*Activer le mouvement de la page*/
.sidebar.active ~ .home{
left: 240px;
width: calc(100% - 78px);
}
/*Paramètre d'affichage de la template 1*/
.template-1.active{
display: none;
}
/*Paramétre d'affichage de la template 2*/
.template-2.active{
display: none;
}
/*Paramétre d'affichage de la template 3*/
.template-3.active{
display: none;
}
/*Paramètres de la fenêtre modal*/
.panel-1{
position: fixed;
top: 0;
width: 100vw;
height: 100vh;
}
/*Paramétre titre du panneau*/
.panel-1 .panel-header h1{
position: absolute;
font-size: 12px;
margin-left: 5px;
font-family: Montserrat, sans-serif;
font-weight: 500;
}
/*Paramétre panel header*/
.panel-1 .panel-header{
display: flex;
width: 20%;
height: 3%;
margin-top: 5px;
margin-left: 7px;
border-radius: 5px 5px 0px 0px;
align-items: center;
justify-content: space-between;
padding: 0.1% 0.1%;
background-color: rgb(91, 91, 91);
color: rgb(255, 255, 255);
box-shadow: 0 0 7px rgba(18,18,18,0.5);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'"> -->
<!----===== CSS ===== -->
<link rel="stylesheet" href="style.css">
<!----===== Boxicons CSS ===== -->
<link href='https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css' rel='stylesheet'>
<title>Sail Vision</title>
</head>
<body>
<div class="sidebar">
<div class="logo_content">
<div class="logo">
<i class='bx bx1-c-plus-plus'></i>
<div class="logo_name">SailVision</div>
</div>
<i class='bx bx-menu' id="btn"></i>
</div>
<div class="menu-bar">
<ul class="dash_list">
<li class="divider" data-text="main">.</li>
<li>
<a href="#">
<i class='bx bx-windows'></i>
<span class="links_name">Dashboard n°1</span>
</a>
</li>
<li>
<a href="#">
<i class='bx bx-windows'></i>
<span class="links_name">Dashboard n°2</span>
</a>
</li>
<li>
<a href="#">
<i class='bx bx-windows'></i>
<span class="links_name">Dashboard n°3</span>
</a>
</li>
<li class="divider" data-text="modification">.</li>
<li>
<a href="#">
<i class='bx bx-customize modal-trigger'></i>
<span class="links_name">Template</span>
</a>
</li>
</ul>
<div class="bottom_content">
<li>
<a href="#">
<i class='bx bx-cog modal-trigger-param'></i>
<span class="links_name">Paramètre</span>
</a>
</li>
</div>
</div>
</div>
<div class="home">
<div class="template-1" id="temp1">
<div class="panel-1">
<div class="panel-header">
<h1>GV</h1>
<i class='bx bx-cog'></i>
</div>
<div class="panel-body">
</div>
</div>
</div>
<div class="template-2 active" id='temp2'>Template n°2</div>
<div class="template-3 active" id="temp3">Template n°3</div>
</div>
<script src="script.js"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
<p>Regards.</p>
|
[
{
"answer_id": 74573064,
"author": "Kordys",
"author_id": 20599005,
"author_profile": "https://Stackoverflow.com/users/20599005",
"pm_score": -1,
"selected": false,
"text": "<h1><i class=\"bx bx-cog\"></i> GV</h1>\n"
},
{
"answer_id": 74573575,
"author": "Marcos Randulfe Garrido",
"author_id": 8666620,
"author_profile": "https://Stackoverflow.com/users/8666620",
"pm_score": -1,
"selected": false,
"text": "h1.spaced {\n padding-left: 13px;\n}\n\n<div class=\"panel-header\">\n <h1 class=\"spaced\">GV</h1>\n <i class=\"bx bx-cog\"></i>\n</div>\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74572958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19930293/"
] |
74,573,002
|
<p>The main purpose of my program is to connect to an incoming MQTT channel, and send the data received to my AWS Kinesis Stream called "MyKinesisStream".</p>
<p>Here is my code:</p>
<pre><code>import argparse
import logging
import random
from paho.mqtt import client as mqtt_client
from stream_manager import (
ExportDefinition,
KinesisConfig,
MessageStreamDefinition,
ResourceNotFoundException,
StrategyOnFull,
StreamManagerClient, ReadMessagesOptions,
)
broker = 'localhost'
port = 1883
topic = "clients/test/hello/world"
client_id = f'python-mqtt-{random.randint(0, 100)}'
username = '...'
password = '...'
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()
args = ""
def connect_mqtt() -> mqtt_client:
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Connected to MQTT Broker!")
else:
print("Failed to connect, return code %d\n", rc)
client = mqtt_client.Client(client_id)
client.username_pw_set(username, password)
client.on_connect = on_connect
client.connect(broker, port)
return client
def sendDataToKinesis(
stream_name: str,
kinesis_stream_name: str,
payload,
batch_size: int = None,
):
try:
print("Debug: sendDataToKinesis with params:", stream_name + " | ", kinesis_stream_name, " | ", batch_size)
print("payload:", payload)
print("type payload:", type(payload))
except Exception as e:
print("Error while printing out the parameters", str(e))
logger.exception(e)
try:
# Create a client for the StreamManager
kinesis_client = StreamManagerClient()
# Try deleting the stream (if it exists) so that we have a fresh start
try:
kinesis_client.delete_message_stream(stream_name=stream_name)
except ResourceNotFoundException:
pass
exports = ExportDefinition(
kinesis=[KinesisConfig(
identifier="KinesisExport" + stream_name,
kinesis_stream_name=kinesis_stream_name,
batch_size=batch_size,
)]
)
kinesis_client.create_message_stream(
MessageStreamDefinition(
name=stream_name,
strategy_on_full=StrategyOnFull.OverwriteOldestData,
export_definition=exports
)
)
sequence_no = kinesis_client.append_message(stream_name=stream_name, data=payload)
print(
"Successfully appended message to stream with sequence number ", sequence_no
)
readValue = kinesis_client.read_messages(stream_name, ReadMessagesOptions(min_message_count=1, read_timeout_millis=1000))
print("DEBUG read test: ", readValue)
except Exception as e:
print("Exception while running: " + str(e))
logger.exception(e)
finally:
# Always close the client to avoid resource leaks
print("closing connection")
if kinesis_client:
kinesis_client.close()
def subscribe(client: mqtt_client, args):
def on_message(client, userdata, msg):
print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")
sendDataToKinesis(args.greengrass_stream, args.kinesis_stream, msg.payload, args.batch_size)
client.subscribe(topic)
client.on_message = on_message
def run(args):
mqtt_client_instance = connect_mqtt()
subscribe(mqtt_client_instance, args)
mqtt_client_instance.loop_forever()
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument('--greengrass-stream', required=False, default='...')
parser.add_argument('--kinesis-stream', required=False, default='MyKinesisStream')
parser.add_argument('--batch-size', required=False, type=int, default=500)
return parser.parse_args()
if __name__ == '__main__':
args = parse_args()
run(args)
</code></pre>
<p>(the dotted parts ... are commented out as they are sensitive information, but they are correct values.)</p>
<p>The problem is that it just won't send any data to our kinesis stream. I get the following STDOUT from the run:</p>
<pre><code>2022-11-25T12:13:47.640Z [INFO] (Copier) jp.co.xyz.StreamManagerKinesis: stdout. Connected to MQTT Broker!. {scriptName=services.jp.co.xyz.StreamManagerKinesis.lifecycle.Run, serviceName=jp.co.xyz.StreamManagerKinesis, currentState=RUNNING}
2022-11-25T12:13:47.641Z [INFO] (Copier) jp.co.xyz.StreamManagerKinesis: stdout. Received `{"machineId":2, .... "timestamp":"2022-10-24T12:21:34.8777249Z","value":true}` from `clients/test/hello/world` topic. {scriptName=services.jp.co.xyz.StreamManagerKinesis.lifecycle.Run, serviceName=jp.co.xyz.StreamManagerKinesis, currentState=RUNNING}
2022-11-25T12:13:47.641Z [INFO] (Copier) jp.co.xyz.StreamManagerKinesis: stdout. Debug: sendDataToKinesis with params: test | MyKinesisStream | 100. {scriptName=services.jp.co.xyz.StreamManagerKinesis.lifecycle.Run, serviceName=jp.co.xyz.StreamManagerKinesis, currentState=RUNNING}
2022-11-25T12:13:47.641Z [INFO] (Copier) jp.co.xyz.StreamManagerKinesis: stdout. payload: b'{"machineId":2,... ,"timestamp":"2022-10-24T12:21:34.8777249Z","value":true}'. {scriptName=services.jp.co.xyz.StreamManagerKinesis.lifecycle.Run, serviceName=jp.co.xyz.StreamManagerKinesis, currentState=RUNNING}
2022-11-25T12:13:47.641Z [INFO] (Copier) jp.co.xyz.StreamManagerKinesis: stdout. type payload: <class 'bytes'>. {scriptName=services.jp.co.xyz.StreamManagerKinesis.lifecycle.Run, serviceName=jp.co.xyz.StreamManagerKinesis, currentState=RUNNING}
2022-11-25T12:13:47.641Z [INFO] (Copier) jp.co.xyz.StreamManagerKinesis: stdout. Successfully appended message to stream with sequence number 0. {scriptName=services.jp.co.xyz.StreamManagerKinesis.lifecycle.Run, serviceName=jp.co.xyz.StreamManagerKinesis, currentState=RUNNING}
2022-11-25T12:13:47.641Z [INFO] (Copier) jp.co.xyz.StreamManagerKinesis: stdout. DEBUG read test: [<Class Message. stream_name: 'test', sequence_number: 0, ingest_time: 1669376980985, payload: b'{"machineId":2,"mach'>]. {scriptName=services.jp.co.xyz.StreamManagerKinesis.lifecycle.Run, serviceName=jp.co.xyz.StreamManagerKinesis, currentState=RUNNING}
2022-11-25T12:13:47.641Z [INFO] (Copier) jp.co.xyz.StreamManagerKinesis: stdout. closing connection. {scriptName=services.jp.co.xyz.StreamManagerKinesis.lifecycle.Run, serviceName=jp.co.xyz.StreamManagerKinesis, currentState=RUNNING}
</code></pre>
<p>So we can see that the data arrives from MQTT, the python code executes the append message, and it seems that my kinesis streams have the information as it can read it in the next step... then closes the connection without any error.</p>
<p>But the problem is, that from AWS side, we cannot see the data arriving on the stream:
<a href="https://i.stack.imgur.com/wN5I4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wN5I4.png" alt="screnshot of the aws console" /></a></p>
<p>What can be the problem here? Our greengrass core is configured properly, can be accessed from the AWS, and the Component is running and healthy also:
<a href="https://i.stack.imgur.com/JMJmn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JMJmn.png" alt="Screenshot of IoT Core status" /></a>
<a href="https://i.stack.imgur.com/2qnfn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2qnfn.png" alt="Screenshot of the state if the StreamManager component" /></a></p>
<p><strong>Update:</strong> we managed to get some messages out with the following code:</p>
<pre><code>...
def sendDataToKinesis(
kinesis_client,
stream_name: str,
payload,
):
try:
print("payload:", payload)
print("type payload:", type(payload))
except Exception as e:
print("Error while printing out the parameters", str(e))
logger.exception(e)
try:
sequence_no = kinesis_client.append_message(stream_name=stream_name, data=payload)
print(
"Successfully appended message to stream with sequence number ", sequence_no
)
time.sleep(1)
except Exception as e:
print("Exception while running: " + str(e))
logger.exception(e)
# finally:
# # todo: Always close the client to avoid resource leaks!!!
# print("closing connection")
# if kinesis_client:
# kinesis_client.close()
def subscribe(client: mqtt_client, stream_name: str, args, kinesisClient):
def on_message(client, userdata, msg):
print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")
sendDataToKinesis(kinesisClient, stream_name, msg.payload)
client.subscribe(topic)
client.on_message = on_message
def create_kinensis_client(greengrass_stream, kinesis_stream, batch_size):
# Create a client for the StreamManager
kinesis_client = StreamManagerClient()
# Try deleting the stream (if it exists) so that we have a fresh start
try:
kinesis_client.delete_message_stream(stream_name=greengrass_stream)
except ResourceNotFoundException:
pass
exports = ExportDefinition(
kinesis=[KinesisConfig(
identifier="KinesisExport" + greengrass_stream,
kinesis_stream_name=kinesis_stream,
batch_size=batch_size,
)]
)
kinesis_client.create_message_stream(
MessageStreamDefinition(
name=greengrass_stream,
strategy_on_full=StrategyOnFull.OverwriteOldestData,
export_definition=exports
)
)
print("Debug:created stream with parasm ", greengrass_stream + " | ", kinesis_stream, " | ", batch_size)
return kinesis_client
def run(args):
kinesis_client = create_kinensis_client(args.greengrass_stream, args.kinesis_stream, args.batch_size)
mqtt_client_instance = connect_mqtt()
subscribe(mqtt_client_instance, args.greengrass_stream, args, kinesis_client)
mqtt_client_instance.loop_forever()
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument('--greengrass-stream', required=False, default='SiteWise_Stream_Kinesis')
parser.add_argument('--kinesis-stream', required=False, default='MyKinesisStream')
parser.add_argument('--batch-size', required=False, type=int, default=500)
return parser.parse_args()
if __name__ == '__main__':
args = parse_args()
print(f'args: {args.__dict__}')
run(args)
</code></pre>
<p>In this approach:</p>
<ul>
<li>we create the connection only once</li>
<li>we do not close the connection,</li>
<li>and wait 1 second before moving on after appending the message to the kinesis stream.</li>
</ul>
<p>No need to say that this solution cannot be used in our production environment, but after a lot of random trying, this seems to work somehow. We still need to find the root cause, but it might be a python threading problem? We are out of guesses.</p>
|
[
{
"answer_id": 74573064,
"author": "Kordys",
"author_id": 20599005,
"author_profile": "https://Stackoverflow.com/users/20599005",
"pm_score": -1,
"selected": false,
"text": "<h1><i class=\"bx bx-cog\"></i> GV</h1>\n"
},
{
"answer_id": 74573575,
"author": "Marcos Randulfe Garrido",
"author_id": 8666620,
"author_profile": "https://Stackoverflow.com/users/8666620",
"pm_score": -1,
"selected": false,
"text": "h1.spaced {\n padding-left: 13px;\n}\n\n<div class=\"panel-header\">\n <h1 class=\"spaced\">GV</h1>\n <i class=\"bx bx-cog\"></i>\n</div>\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74573002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3486691/"
] |
74,573,044
|
<p>I have a IExport.txt file with one or more lines of numbers and letters separated by semicolon and a total of 14 columns.<br />
<strong>The file has no headers and i need it to be like this</strong></p>
<pre><code>4;1613000026438;T0011368;1.00;715004978;922105;;101120;;171;Name0;Thing1;Name1;989105
</code></pre>
<p>This is what i <strong>imagine</strong> the file to look like (part of it):</p>
<pre><code>H1 H2 H3 H4 H5 H6 H7 H8
-- ------------- -------- ---- --------- ------ ----- ---
4 1613000026438 T0011368 1.00 715004978 922105
</code></pre>
<p>I need to change the file as follows:<br />
Column 7 to 14 shall be deleted<br />
Value "1.00" in column 4 shall be set to "1"<br />
And the columns shall be reordered like this:</p>
<pre><code>H1 H3 H4 H2 H5 H6
-- -------- -- ------------- --------- ------
4 T0011368 1 1613000026438 715004978 922105
</code></pre>
<p>I need the file in the end like this:</p>
<pre><code>4;T0011368;1;1613000026438;715004978;922105
</code></pre>
<p>I want to change the file as stated above, but without any headers and rename it from "IExport.txt" to "KExport.txt".<br />
<strong>Is there a way to reorder the columns without naming them?</strong></p>
<p>I have edited my question, because i understand i didn't provide enough information and because i don't need the headers anymore.</p>
<p>I would very much appreciate your help.</p>
|
[
{
"answer_id": 74573371,
"author": "Dilly B",
"author_id": 2670623,
"author_profile": "https://Stackoverflow.com/users/2670623",
"pm_score": 1,
"selected": false,
"text": "Import-Csv -Path C:\\temp\\sample.txt -Header 1,2,3,4,5,6 -Delimiter ';'\n"
},
{
"answer_id": 74580093,
"author": "postanote",
"author_id": 9132707,
"author_profile": "https://Stackoverflow.com/users/9132707",
"pm_score": 2,
"selected": false,
"text": "Clear-Host\n'4;1613000026438;T0011368;1.00;715004978;922105;;101120;;171;Name0;Thing1;Name1;989105' | \nConvertFrom-Csv -Delimiter ';' -header H1, H2, H3, H4, H5, H6 | \n# Results\n<#\nH1 : 4\nH2 : 1613000026438\nH3 : T0011368\nH4 : 1.00\nH5 : 715004978\nH6 : 922105\n#>\nSelect-Object -Property @{\n Name = 'Row'\n Expression = {$PSItem.H1} \n}, H3, @{\n Name = 'H4'\n Expression = {($PSItem.H4) -replace '\\.\\d+'} \n}, H2, H5, H6 | \n# Results\n<#\nRow : 4\nH3 : T0011368\nH4 : 1\nH2 : 1613000026438\nH5 : 715004978\nH6 : 922105\n#>\nFormat-Table -AutoSize\n# Results\n<#\nRow H3 H4 H2 H5 H6 \n--- -- -- -- -- -- \n4 T0011368 1 1613000026438 715004978 922105\n#>\n Format-Table Export-csv -Path \"$env:USERPROFILE\\Documents\\KExport.txt\" -NoTypeInformation\nImport-Csv -Path \"$env:USERPROFILE\\Documents\\KExport.txt\"\n"
},
{
"answer_id": 74628743,
"author": "Theo",
"author_id": 9898643,
"author_profile": "https://Stackoverflow.com/users/9898643",
"pm_score": 3,
"selected": true,
"text": "; $fileIn = 'X:\\Somewhere\\IExport.txt'\n$result = Import-Csv -Path $fileIn -Delimiter ';' -Header (1..6 | ForEach-Object { \"H$_\" }) |\n ForEach-Object {\n # reorder the fields, use [int] on H4 and output a semi-colon delimited string\n $_.H1, $_.H3, [int]$_.H4, $_.H2, $_.H5, $_.H6 -join ';'\n }\n# output the new file\n$fileOut = $fileIn -replace 'IExport\\.txt$', 'XExport.txt'\n$result | Set-Content -Path $fileOut\n 4;T0011368;1;1613000026438;715004978;922105\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74573044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20049627/"
] |
74,573,071
|
<p>I made an OCR program using the Python programming language and the tesserOCR library. In the program I have made, I scan all the pictures in a folder and extract the texts in them. But these extracted texts are saved in a single .txt file. How can I save the texts in each image to different .txt files. That is, the texts in each image should be saved as a .txt file named after that image.</p>
<p>`</p>
<pre><code>import tesserocr
from PIL import Image
import glob
import time
import cv2
import numpy as np
Image.MAX_IMAGE_PIXELS = None
api = tesserocr.PyTessBaseAPI(path='D:/Anaconda/Tesseract5/tessdata', lang='tur')
files = glob.glob('C:/Users/Casper/Desktop/OCR/wpp/*')
filesProcessed = []
def extract():
for f, file in enumerate(files):
if f >= 0:
try:
text = ' '
jpegs = glob.glob('C:/Users/Casper/Desktop/OCR/wpp/*')
jpegs = sorted(jpegs)
print(len(jpegs))
for i in jpegs:
pil_image = Image.open(i)
api.SetImage(pil_image)
text = text + api.GetUTF8Text()
filename = file[:-4] + '.txt'
with open(filename, 'w') as n:
n.write(text)
except:
print(f'{file} is a corrupt file')
break
if __name__ == "__main__":
extract()
</code></pre>
<p>`</p>
<p>Texts from all images are saved in the same .txt file. I want it to be saved in different .txt file.</p>
|
[
{
"answer_id": 74573371,
"author": "Dilly B",
"author_id": 2670623,
"author_profile": "https://Stackoverflow.com/users/2670623",
"pm_score": 1,
"selected": false,
"text": "Import-Csv -Path C:\\temp\\sample.txt -Header 1,2,3,4,5,6 -Delimiter ';'\n"
},
{
"answer_id": 74580093,
"author": "postanote",
"author_id": 9132707,
"author_profile": "https://Stackoverflow.com/users/9132707",
"pm_score": 2,
"selected": false,
"text": "Clear-Host\n'4;1613000026438;T0011368;1.00;715004978;922105;;101120;;171;Name0;Thing1;Name1;989105' | \nConvertFrom-Csv -Delimiter ';' -header H1, H2, H3, H4, H5, H6 | \n# Results\n<#\nH1 : 4\nH2 : 1613000026438\nH3 : T0011368\nH4 : 1.00\nH5 : 715004978\nH6 : 922105\n#>\nSelect-Object -Property @{\n Name = 'Row'\n Expression = {$PSItem.H1} \n}, H3, @{\n Name = 'H4'\n Expression = {($PSItem.H4) -replace '\\.\\d+'} \n}, H2, H5, H6 | \n# Results\n<#\nRow : 4\nH3 : T0011368\nH4 : 1\nH2 : 1613000026438\nH5 : 715004978\nH6 : 922105\n#>\nFormat-Table -AutoSize\n# Results\n<#\nRow H3 H4 H2 H5 H6 \n--- -- -- -- -- -- \n4 T0011368 1 1613000026438 715004978 922105\n#>\n Format-Table Export-csv -Path \"$env:USERPROFILE\\Documents\\KExport.txt\" -NoTypeInformation\nImport-Csv -Path \"$env:USERPROFILE\\Documents\\KExport.txt\"\n"
},
{
"answer_id": 74628743,
"author": "Theo",
"author_id": 9898643,
"author_profile": "https://Stackoverflow.com/users/9898643",
"pm_score": 3,
"selected": true,
"text": "; $fileIn = 'X:\\Somewhere\\IExport.txt'\n$result = Import-Csv -Path $fileIn -Delimiter ';' -Header (1..6 | ForEach-Object { \"H$_\" }) |\n ForEach-Object {\n # reorder the fields, use [int] on H4 and output a semi-colon delimited string\n $_.H1, $_.H3, [int]$_.H4, $_.H2, $_.H5, $_.H6 -join ';'\n }\n# output the new file\n$fileOut = $fileIn -replace 'IExport\\.txt$', 'XExport.txt'\n$result | Set-Content -Path $fileOut\n 4;T0011368;1;1613000026438;715004978;922105\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74573071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18065447/"
] |
74,573,109
|
<p>exp1 and exp2
Select * exp 1 gives me:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>exp_2_ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>1</td>
<td>a</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td>b</td>
</tr>
<tr>
<td>3</td>
<td>2</td>
<td>c</td>
</tr>
</tbody>
</table>
</div>
<p>Select * exp 2 gives me:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>name</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>print</td>
</tr>
<tr>
<td>2</td>
<td>no_print</td>
</tr>
</tbody>
</table>
</div>
<p>Now what I want to do is count every id and then print only when number of id's are above average</p>
<p>So in math way it should be something like this
<code>exp_2_id 1 = count 2 exp_2_id 2 = count 1 average = 3/2 = 1.5</code>
Should print only exp_2 id 1 cause it is 2</p>
<p>Hope that someone can explain me how to do it</p>
<p>So as an output I want to have only</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">ID</th>
<th style="text-align: center;">name</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">1</td>
<td style="text-align: center;">print</td>
</tr>
</tbody>
</table>
</div>
|
[
{
"answer_id": 74573371,
"author": "Dilly B",
"author_id": 2670623,
"author_profile": "https://Stackoverflow.com/users/2670623",
"pm_score": 1,
"selected": false,
"text": "Import-Csv -Path C:\\temp\\sample.txt -Header 1,2,3,4,5,6 -Delimiter ';'\n"
},
{
"answer_id": 74580093,
"author": "postanote",
"author_id": 9132707,
"author_profile": "https://Stackoverflow.com/users/9132707",
"pm_score": 2,
"selected": false,
"text": "Clear-Host\n'4;1613000026438;T0011368;1.00;715004978;922105;;101120;;171;Name0;Thing1;Name1;989105' | \nConvertFrom-Csv -Delimiter ';' -header H1, H2, H3, H4, H5, H6 | \n# Results\n<#\nH1 : 4\nH2 : 1613000026438\nH3 : T0011368\nH4 : 1.00\nH5 : 715004978\nH6 : 922105\n#>\nSelect-Object -Property @{\n Name = 'Row'\n Expression = {$PSItem.H1} \n}, H3, @{\n Name = 'H4'\n Expression = {($PSItem.H4) -replace '\\.\\d+'} \n}, H2, H5, H6 | \n# Results\n<#\nRow : 4\nH3 : T0011368\nH4 : 1\nH2 : 1613000026438\nH5 : 715004978\nH6 : 922105\n#>\nFormat-Table -AutoSize\n# Results\n<#\nRow H3 H4 H2 H5 H6 \n--- -- -- -- -- -- \n4 T0011368 1 1613000026438 715004978 922105\n#>\n Format-Table Export-csv -Path \"$env:USERPROFILE\\Documents\\KExport.txt\" -NoTypeInformation\nImport-Csv -Path \"$env:USERPROFILE\\Documents\\KExport.txt\"\n"
},
{
"answer_id": 74628743,
"author": "Theo",
"author_id": 9898643,
"author_profile": "https://Stackoverflow.com/users/9898643",
"pm_score": 3,
"selected": true,
"text": "; $fileIn = 'X:\\Somewhere\\IExport.txt'\n$result = Import-Csv -Path $fileIn -Delimiter ';' -Header (1..6 | ForEach-Object { \"H$_\" }) |\n ForEach-Object {\n # reorder the fields, use [int] on H4 and output a semi-colon delimited string\n $_.H1, $_.H3, [int]$_.H4, $_.H2, $_.H5, $_.H6 -join ';'\n }\n# output the new file\n$fileOut = $fileIn -replace 'IExport\\.txt$', 'XExport.txt'\n$result | Set-Content -Path $fileOut\n 4;T0011368;1;1613000026438;715004978;922105\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74573109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20317241/"
] |
74,573,197
|
<p>I am at the admin user, which is holding the administrator role, but when I add a condition to check if the user is admin or not it will always return false. I can't find the problem.
This is my code:</p>
<p>So this is my roles table:
<a href="https://i.stack.imgur.com/lW4eQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lW4eQ.png" alt="enter image description here" /></a></p>
<p>And this is my users table:
<a href="https://i.stack.imgur.com/RZTV4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RZTV4.png" alt="enter image description here" /></a></p>
<p>I set up the relation in my user model, and a condition in the END OF THE CODE which will check if the user is admin or not:</p>
<pre><code>/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function role() {
return $this->belongsTo('App\Models\Role');
}
public function isAdmin() {
if($this->role->name == 'administrator')
return true;
else
return false;
}
</code></pre>
<p>}</p>
<p>Than I created a middleware which will allow me to go in to the admin page if the user is admin else it will redirect me to the root:
<a href="https://i.stack.imgur.com/YOg1H.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YOg1H.png" alt="enter image description here" /></a></p>
<p>Than at the end I added the route with the controller:
<a href="https://i.stack.imgur.com/QOILY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QOILY.png" alt="enter image description here" /></a></p>
<p>And here is the controller in case you need it:
<a href="https://i.stack.imgur.com/OeYle.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OeYle.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74573414,
"author": "Bandit",
"author_id": 15282343,
"author_profile": "https://Stackoverflow.com/users/15282343",
"pm_score": -1,
"selected": false,
"text": "Route::get('/admin', [AdminController::class, 'index'];\n if (auth()->user()->role->name == 'administrator') {\n return $next($request);\n} else {\n return redirect('/');\n}\n"
},
{
"answer_id": 74576613,
"author": "Gjin Kurtishi",
"author_id": 20337580,
"author_profile": "https://Stackoverflow.com/users/20337580",
"pm_score": 0,
"selected": false,
"text": "return dd(Auth::user()->role->name)\n \"administrator \"\n Auth::user()->role->name == \"administrator\"\n \"administrator \" == \"administrator\"\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74573197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20337580/"
] |
74,573,198
|
<p>I want to return the struct that is declared, and values set inside the <code>initializePlayer()</code> function so I can call it on the main function.<br />
This is a task and we are not allowed to declare global variables (only inside of functions) so I kind of think that I need to declare the <code>struct</code> inside functions—unless it's not a variable(?) I don't really know :(</p>
<p>Here is my code and I can't get it to work</p>
<pre><code>struct Player initializePlayer(int playerNumber)
{
struct Player
{
int position[1][2];
double money;
int propertiesOwned[10];
} player[4];
// Set player's position to starting tile
player[playerNumber].position[0][0] = 5;
player[playerNumber].position[0][1] = 0;
// Set player's default money
player[playerNumber].money = 300000;
// Set player's properties to none
for (int i; i <= 10; i++)
{
player[playerNumber].propertiesOwned[i] = 0;
}
// Player initialized
return player[playerNumber];
}
int main()
{
// Initializes player 1 and 2
struct Player p1 = initializePlayer(1);
struct Player p2 = initializePlayer(2);
return 0;
}
</code></pre>
<p>If I declare the <code>struct</code> to global however, it works just fine.</p>
<p>I want the function to return a struct, on which that struct is declared inside that function</p>
|
[
{
"answer_id": 74573284,
"author": "chrslg",
"author_id": 20037042,
"author_profile": "https://Stackoverflow.com/users/20037042",
"pm_score": 1,
"selected": false,
"text": "Player #include <stdio.h>\n\nstruct Player {\n int pos;\n char name[10];\n};\n\nstruct Player f(){\n struct Player player;\n sprintf(player.name, \"John\");\n player.pos=12;\n printf(\"addr of f's local player: %p\\n\", &player);\n return player;\n}\n\nstruct Player g(){\n struct Player player;\n player.pos=1;\n sprintf(player.name, \"xxxxxxxxx\");\n printf(\"addr of g's local player: %p\\n\", &player);\n return player;\n}\n\nint main(void) {\n\n struct Player p;\n p=f();\n struct Player q=g();\n printf(\"%s %d\\n\", p.name, p.pos);\n\n return 0;\n addr of f's local player: 0x7ffec7aa8ae0\naddr of g's local player: 0x7ffec7aa8ae0\nJohn 12\n main p.name p.pos f g g player player f g f player f f player struct Player [1]"
},
{
"answer_id": 74573287,
"author": "Jabberwocky",
"author_id": 898348,
"author_profile": "https://Stackoverflow.com/users/898348",
"pm_score": 0,
"selected": false,
"text": "struct player struct // declare the struct (this does not declare a global variable)\n\nstruct Player\n{\n int position[1][2];\n double money;\n int propertiesOwned[10];\n};\n\n\n// Now you can use it \nstruct Player initializePlayer(int playerNumber)\n{\n struct Player player[4];\n for (int i; i <= 10; i++)\n i for (int i = 0; i <= 10; i++)\n"
},
{
"answer_id": 74573929,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 3,
"selected": true,
"text": "struct Player initializePlayer(int playerNumber)\n{\n struct Player\n {\n int position[1][2];\n double money;\n int propertiesOwned[10];\n } player[4];\n //...\n struct Player\n {\n int position[1][2];\n double money;\n int propertiesOwned[10];\n };\n void initializePlayer( struct Player *player )\n{\n // Set player's position to starting tile\n player->position[0][0] = 5;\n player->position[0][1] = 0;\n // and so on\n void main int main( void )\n{\n struct Player player[4] = { 0 };\n\n // Initializes player 1 and 2\n initializePlayer( &player[1] );\n initializePlayer( &player[2] );\n\n return 0;\n}\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74573198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20599482/"
] |
74,573,215
|
<p>im new with the web dev thing and im trying to make slideshow, now i wanna put another div under the slideshow that has a paragraph but when i try to do it the paragraph goes over the slideshow.
this picture will explain my problem better i guess.. what i want is the paragraph stay under the slideshow</p>
<p>HTML :</p>
<pre><code><nav class="nav">
<div class="container">
<div class="logo">
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" fill="#FFD60A" class="bi bi-camera-fill"
viewBox="0 0 16 16">
<path d="M10.5 8.5a2.5 2.5 0 1 1-5 0 2.5 2.5 0 0 1 5 0z" />
<path
d="M2 4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2h-1.172a2 2 0 0 1-1.414-.586l-.828-.828A2 2 0 0 0 9.172 2H6.828a2 2 0 0 0-1.414.586l-.828.828A2 2 0 0 1 3.172 4H2zm.5 2a.5.5 0 1 1 0-1 .5.5 0 0 1 0 1zm9 2.5a3.5 3.5 0 1 1-7 0 3.5 3.5 0 0 1 7 0z" />
</svg>
<h1 class="name">Zon Photography</h1>
</div>
<div class="menu">
<a href="" class="is-active">HOME</a>
<a href="#PACKAGES">PACKAGES</a>
<a href="">PHOTOS</a>
<a href="">ABOUT</a>
<a href="">CONTACT US</a>
</div>
<button class="humberger">
<span></span>
<span></span>
<span></span>
</button>
</div>
</nav>
<div class="Slider">
<div class="myslider fade">
<img id="imgslid" src="/Images/1.jpg" style="width:100%">
</div>
<div class="myslider fade">
<img id="imgslid" src="/Images/2.jpg" style="width:100%">
</div>
<div class="myslider fade">
<img id="imgslid" src="/Images/3.jpg" style="width:100%">
</div>
<div class="myslider fade">
<img id="imgslid" src="/Images/4.jpg" style="width:100%">
</div>
<div class="myslider fade">
<img id="imgslid" src="/Images/5.jpg" style="width:100%">
</div>
</div>
<div class="packcontainer">
<p> My paragraph goes here</p>
</div>
</code></pre>
<p>CSS:</p>
<pre><code>*{
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Raleway', sans-serif;
}
.container{
max-width: 1280px;
margin: 0 auto;
display: flex;
align-items: center;
justify-content: space-between;
}
nav{
position: absolute;
top:0;
left: 0;
right: 0;
z-index: 99;
padding: 16px 32px;
}
/* Slide Show Container */
.slider{
position: relative;
background-color: #003566;
}
/* Hide the images by default*/
.myslider{
max-height: 255px;
display: none;
}
/* Fading animation */
.fade {
animation-name: fade;
animation-duration: 0.5s;
}
@keyframes fade {
from {opacity: 0,4}
to {opacity: 1}
}
/* LOGO */
svg{
margin-top: 20px;
}
/* ZON PHOTOGRAPHY */
.name{
display: none;
float: right;
color: #FFC300;
padding: 10px;
transition: 0.4s;
font-size: 35px;
font-family: 'Pacifico', cursive;
}
/* Humberger Container */
.humberger{
display: block;
position: relative;
z-index: 1;
user-select: none;
appearance: none;
border: none;
outline: none;
background: none;
cursor: pointer;
}
/* Humberger Lines */
.humberger span{
display: block;
width: 33px;
height: 4px;
margin-bottom: 5px;
position: relative;
background-color: #FFC300 ;
border-radius: 6px;
z-index: 1;
transform-origin: 0 0;
transition: 0.4s;
}
/* Humberger Transofrmation */
.humberger:hover span:nth-child(2){
transform: translateX(10px);
background-color: #003566;
}
.humberger.is-active span:nth-child(1){
transform: translate(0px, -2px) rotate(45deg);
}
.humberger.is-active span:nth-child(3){
transform: translate(-3px, 3px) rotate(-45deg);
}
.humberger.is-active span:nth-child(2){
opacity: 0;
transform: translateX(15px);
}
.humberger.is-active:hover span{
background-color: #0862b8;
}
/* NAV MENU LIST */
.menu{
display: none;
flex: auto;
justify-content:center;
align-items: center;
margin: 0;
}
.menu a{
color: white;
text-decoration: none;
padding: 15px;
font-weight: bold;
font-size: 18px;
transition: 0.4s;
}
.menu a:hover{
color:#FFC300;
}
/* NAV MENU TRANSFORMATION */
@media (min-width: 768px){
.humberger{
display: none;
}
.menu{
display: flex;
}
.name{
display: flex;
}
#slider ul li img{
width: 100%
}
}
</code></pre>
|
[
{
"answer_id": 74573284,
"author": "chrslg",
"author_id": 20037042,
"author_profile": "https://Stackoverflow.com/users/20037042",
"pm_score": 1,
"selected": false,
"text": "Player #include <stdio.h>\n\nstruct Player {\n int pos;\n char name[10];\n};\n\nstruct Player f(){\n struct Player player;\n sprintf(player.name, \"John\");\n player.pos=12;\n printf(\"addr of f's local player: %p\\n\", &player);\n return player;\n}\n\nstruct Player g(){\n struct Player player;\n player.pos=1;\n sprintf(player.name, \"xxxxxxxxx\");\n printf(\"addr of g's local player: %p\\n\", &player);\n return player;\n}\n\nint main(void) {\n\n struct Player p;\n p=f();\n struct Player q=g();\n printf(\"%s %d\\n\", p.name, p.pos);\n\n return 0;\n addr of f's local player: 0x7ffec7aa8ae0\naddr of g's local player: 0x7ffec7aa8ae0\nJohn 12\n main p.name p.pos f g g player player f g f player f f player struct Player [1]"
},
{
"answer_id": 74573287,
"author": "Jabberwocky",
"author_id": 898348,
"author_profile": "https://Stackoverflow.com/users/898348",
"pm_score": 0,
"selected": false,
"text": "struct player struct // declare the struct (this does not declare a global variable)\n\nstruct Player\n{\n int position[1][2];\n double money;\n int propertiesOwned[10];\n};\n\n\n// Now you can use it \nstruct Player initializePlayer(int playerNumber)\n{\n struct Player player[4];\n for (int i; i <= 10; i++)\n i for (int i = 0; i <= 10; i++)\n"
},
{
"answer_id": 74573929,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 3,
"selected": true,
"text": "struct Player initializePlayer(int playerNumber)\n{\n struct Player\n {\n int position[1][2];\n double money;\n int propertiesOwned[10];\n } player[4];\n //...\n struct Player\n {\n int position[1][2];\n double money;\n int propertiesOwned[10];\n };\n void initializePlayer( struct Player *player )\n{\n // Set player's position to starting tile\n player->position[0][0] = 5;\n player->position[0][1] = 0;\n // and so on\n void main int main( void )\n{\n struct Player player[4] = { 0 };\n\n // Initializes player 1 and 2\n initializePlayer( &player[1] );\n initializePlayer( &player[2] );\n\n return 0;\n}\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74573215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20599504/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.