qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,651,056
<p>I have an array of stocks with each stock having 3 properties. I want to get the price property from the array and find out the highest/lowest price and return the object with highest/lowest price.</p> <pre><code>'use strict'; const stocks = [ { company: 'Splunk', symbol: 'SPLK', price: 137.55 }, { company: 'Microsoft', symbol: 'MSFT', price: 232.04 }, { company: 'Oracle', symbol: 'ORCL', price: 67.08 }, { company: 'Snowflake', symbol: 'SNOW', price: 235.8 }, { company: 'Teradata', symbol: 'TDC', price: 44.98 } ]; </code></pre> <p>I want to get price for each object in stocks and return the object with the highest price as max and return the object with lowest price as min.</p> <pre><code>// Function for highest/lowest price function findStockByPrice(stocks) { const max = Math.max.apply(null, stocks.price); const min = Math.min.apply(null, stocks.price); if (max === true) { return stocks } else if (min === true) { return stocks } } </code></pre> <p>I am trying to use Math.max() but I am getting ReferenceError: max is not defined.</p>
[ { "answer_id": 74651273, "author": "Abra", "author_id": 2164365, "author_profile": "https://Stackoverflow.com/users/2164365", "pm_score": 1, "selected": false, "text": "java.time.format.DateTimeFormatter Locale Exception in thread \"main\" java.time.format.DateTimeParseException: Text 'Wed Dec 26 11:11:59 SGT 2022' could not be parsed: Conflict found: Field DayOfWeek 1 differs from DayOfWeek 3 derived from 2022-12-26\n ZonedDateTime import java.time.ZonedDateTime;\nimport java.time.format.DateTimeFormatter;\nimport java.util.Locale;\n\npublic class Doctor {\n\n public static void main(String[] args) {\n String raw = \"Mon Dec 26 11:11:59 SGT 2022\";\n DateTimeFormatter dtf = DateTimeFormatter.ofPattern(\"EEE MMM dd HH:mm:ss z yyyy\", Locale.ENGLISH);\n ZonedDateTime zdt = ZonedDateTime.parse(raw, dtf);\n System.out.println(zdt);\n }\n}\n 2022-12-26T11:11:59+08:00[Asia/Singapore]\n ZonedDateTime java.sql.Date java.sql.Date d = java.sql.Date.valueOf(zdt.toLocalDate());\n zdt" }, { "answer_id": 74651799, "author": "TANIMUL ISLAM", "author_id": 18262004, "author_profile": "https://Stackoverflow.com/users/18262004", "pm_score": 2, "selected": false, "text": "String LocalDate import java.util.Locale;\nimport java.time.LocalDate;\nimport java.time.format.DateTimeFormatter;\n\npublic class Test {\n\n public static void main(String[] args) {\n String raw = \"Mon Dec 26 11:11:59 SGT 2022\";\n DateTimeFormatter dtf = DateTimeFormatter.ofPattern(\"EEE MMM dd HH:mm:ss z yyyy\", Locale.ENGLISH);\n\n // Your required format\n DateTimeFormatter formatter = DateTimeFormatter.ofPattern(\"d/MM/yyyy\");\n\n LocalDate dateTime = LocalDate.parse(raw, dtf);\n\n System.out.println(formatter.format(dateTime));\n }\n}\n 26/12/2022\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20445050/" ]
74,651,069
<p>I have the following code snippet. I'm not sure how to clean up all subscriptions or if I made any mistakes. Please help to improve it.</p> <p>I'm using it within an Angular service to initialize my application.</p> <pre><code> destroy$ = new Subject(); loadData() : void { const loadData1 = this.store.select(selector); // first sets loading to true, then to false const loadData2 = this.store.select(selector); // first sets loading to true, then to false const loadData3 = this.store.select(selector); // first sets loading to true, then to false combineLatest([loadData1, loadData2, loadData3]) .pipe(takeUntil(this.destroy$)) .subscribe(data =&gt; { const a = data[0]; const b = data[1]; const c = data[2]; ... if (a.loadedSuccessfully &amp;&amp; b.loadedSuccessfully &amp;&amp; c.loadedSuccessfully) { ... // do something with the data ... // clean up this.destroy$.next(true); this.destroy$.complete(); } } }); } </code></pre> <p><strong>Questions:</strong></p> <p>(1) Did I make any mistakes?</p> <p>(2) How can I improve it?</p> <p>(3) What about the Observables loadData1-3. There is no subscription in the beginning. So the following line does not create a memory leak, right?</p> <pre><code>*const loadData1 = this.store.select(selector);* </code></pre> <p>Does combineLatest create the subscriptions for loadData1-3 and unsbscribe it?</p>
[ { "answer_id": 74651273, "author": "Abra", "author_id": 2164365, "author_profile": "https://Stackoverflow.com/users/2164365", "pm_score": 1, "selected": false, "text": "java.time.format.DateTimeFormatter Locale Exception in thread \"main\" java.time.format.DateTimeParseException: Text 'Wed Dec 26 11:11:59 SGT 2022' could not be parsed: Conflict found: Field DayOfWeek 1 differs from DayOfWeek 3 derived from 2022-12-26\n ZonedDateTime import java.time.ZonedDateTime;\nimport java.time.format.DateTimeFormatter;\nimport java.util.Locale;\n\npublic class Doctor {\n\n public static void main(String[] args) {\n String raw = \"Mon Dec 26 11:11:59 SGT 2022\";\n DateTimeFormatter dtf = DateTimeFormatter.ofPattern(\"EEE MMM dd HH:mm:ss z yyyy\", Locale.ENGLISH);\n ZonedDateTime zdt = ZonedDateTime.parse(raw, dtf);\n System.out.println(zdt);\n }\n}\n 2022-12-26T11:11:59+08:00[Asia/Singapore]\n ZonedDateTime java.sql.Date java.sql.Date d = java.sql.Date.valueOf(zdt.toLocalDate());\n zdt" }, { "answer_id": 74651799, "author": "TANIMUL ISLAM", "author_id": 18262004, "author_profile": "https://Stackoverflow.com/users/18262004", "pm_score": 2, "selected": false, "text": "String LocalDate import java.util.Locale;\nimport java.time.LocalDate;\nimport java.time.format.DateTimeFormatter;\n\npublic class Test {\n\n public static void main(String[] args) {\n String raw = \"Mon Dec 26 11:11:59 SGT 2022\";\n DateTimeFormatter dtf = DateTimeFormatter.ofPattern(\"EEE MMM dd HH:mm:ss z yyyy\", Locale.ENGLISH);\n\n // Your required format\n DateTimeFormatter formatter = DateTimeFormatter.ofPattern(\"d/MM/yyyy\");\n\n LocalDate dateTime = LocalDate.parse(raw, dtf);\n\n System.out.println(formatter.format(dateTime));\n }\n}\n 26/12/2022\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6034899/" ]
74,651,075
<p>how to open a file using R? I am thinking about a function like <code>file.open(...)</code>, what it does is like double-click a file to open it. However, I did not find any function doing that. Is it possible to use R to open a file? I am using Windows system.</p>
[ { "answer_id": 74651084, "author": "iDoMnCi", "author_id": 10850031, "author_profile": "https://Stackoverflow.com/users/10850031", "pm_score": 3, "selected": true, "text": "file.show() \"myfile.txt\" file.show(\"myfile.txt\")" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5736676/" ]
74,651,078
<p>Basically, I am trying to get my title and navbar vertically and horizontally centered with the title on top, but no matter what I do the navbar will not go under page title. They are just stacked horizontally. I've tried line breaks and everything else I can, and It still won't work how I want it to. I know it's possible because I've seen it before on multiple occasions.</p> <p>Page HTML:</p> <pre class="lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;./home.css&quot;&gt; &lt;title&gt;comatose&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div id=&quot;main&quot;&gt; &lt;div class=&quot;subheader&quot;&gt;&lt;h1 id=&quot;title&quot;&gt;&lt;strong&gt;PAGE TITLE&lt;/strong&gt;&lt;/h1&gt;&lt;/div&gt; &lt;nav&gt; &lt;ul&gt; &lt;li class=&quot;navlink&quot;&gt;&lt;a href=&quot;#About&quot;&gt;About&lt;/a&gt;&lt;/li&gt; &lt;li class=&quot;navlink&quot;&gt;&lt;a href=&quot;#Invite&quot;&gt;Community&lt;/a&gt;&lt;/li&gt; &lt;li class=&quot;navlink&quot;&gt;&lt;a href=&quot;#Devs&quot;&gt;Developers&lt;/a&gt;&lt;/li&gt; &lt;li class=&quot;navlink&quot;&gt;&lt;a href=&quot;#Contact&quot;&gt;Contact&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Page CSS:</p> <pre class="lang-css prettyprint-override"><code>@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@600&amp;display=swap'); @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400&amp;display=swap'); body { height: 100vh; width: 100vw; margin: 0; padding: 0; } #main { display: flex; align-items: center; justify-content: center; height: 100vh; } #title { color: black; font-size: 50px; font-family: 'Montserrat', sans-serif; } .navlink { display: inline-block; padding: 5px; list-style: none; } .navlink a { font-size: 20px; font-family: 'Poppins', sans-serif; text-decoration: none; color: black; } </code></pre> <p>I want all of the navlinks to be below the &quot;PAGE TITLE&quot; header. I'm pretty sure it doesn't, but if it helps any: I use VSCode. Edit - Also, I am new to web development so sorry if I did anything incorrectly.</p>
[ { "answer_id": 74651084, "author": "iDoMnCi", "author_id": 10850031, "author_profile": "https://Stackoverflow.com/users/10850031", "pm_score": 3, "selected": true, "text": "file.show() \"myfile.txt\" file.show(\"myfile.txt\")" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20662592/" ]
74,651,093
<p>I searched a while but couldn't find the answer that I want. I am have a very simple question, how to get rid of the empty objects from Map.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const friuts = [{ apple: 'red', banana: 1 }, { apple: 'green', banana: 1 }, { apple: 'yellow', banana: 3 } ] const newObject = friuts.map(e =&gt; ({ ...e.banana === 1 ? { apple: e.apple } : [] }) ) console.log(newObject)</code></pre> </div> </div> </p> <p>If you check the console.log it contains an empty object at the end</p> <pre><code>[ { &quot;apple&quot;: &quot;red&quot; }, { &quot;apple&quot;: &quot;green&quot; }, {} &lt;--- empty ] </code></pre> <p>Also I tried <code>undefined</code> or below code, but just can't get rid of the empty objects.</p> <pre><code>...e.banana === 1 &amp;&amp; { apple: e.apple } </code></pre> <p>I understand this can be easily done by using other methods like <code>filter</code>. However, I am learning <code>Map</code>, so I'd like to learn how to get rid of the empty objects from map.</p> <p>Sorry for if the question has been asked before. I will remove the question if it is duplicated.</p>
[ { "answer_id": 74651167, "author": "iDoMnCi", "author_id": 10850031, "author_profile": "https://Stackoverflow.com/users/10850031", "pm_score": 2, "selected": true, "text": "const fruits = [{\n apple: 'red',\n banana: 1\n },\n {\n apple: 'green',\n banana: 1\n },\n {\n apple: 'yellow',\n banana: 3\n }\n];\n\nconst newObject = fruits\n .map(e => ({ ...e.banana === 1 ? { apple: e.apple } : {} }))\n .filter(e => Object.keys(e).length > 0);\n\nconsole.log(newObject);" }, { "answer_id": 74654793, "author": "Suhail Qureshi", "author_id": 20308649, "author_profile": "https://Stackoverflow.com/users/20308649", "pm_score": 0, "selected": false, "text": "const newObject = friuts.map(e => {\nreturn e.banana === 1 ? { apple: e.apple } : {}\n}).filter(e => Object.keys(e).length > 0)\n\n\nconsole.log(newObject)\n" }, { "answer_id": 74656285, "author": "Bergi", "author_id": 1048572, "author_profile": "https://Stackoverflow.com/users/1048572", "pm_score": 0, "selected": false, "text": "map filter flatMap const fruits = [\n {\n apple: 'red',\n banana: 1\n },\n {\n apple: 'green',\n banana: 1\n },\n {\n apple: 'yellow',\n banana: 3\n },\n]\n\nconsole.log(fruits.filter(e =>\n e.banana === 1\n).map(e =>\n ({\n apple: e.apple\n })\n));\n\nconsole.log(fruits.flatMap(e =>\n e.banana === 1\n ? [{\n apple: e.apple\n }]\n : []\n));" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1166137/" ]
74,651,103
<p>How can I call &quot;willChangeValue&quot; when using swift Task/await without the following warning showing up?</p> <p><em>Instance method 'willChangeValue' is unavailable from asynchronous contexts; Only notify of changes to a key in a synchronous context. Notifying changes across suspension points has undefined behavior.; this is an error in Swift 6</em></p> <pre><code> @objc dynamic var localFilesTitle: String { get { return &quot;\(localTitle)(\(localFiles.count))&quot; } set { } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. Task { await initialise() self.isInitialised = true let local = await self.getLocalFiles() DebugLog(&quot;Found \(local.count) local files&quot;) for file in local.filter({!$0.isDirectory}) { DebugLog(&quot; \(file.name),\(file.size),\(file.modifiedDate)&quot;) } self.willChangeValue(forKey: &quot;localFilesTitle&quot;) self.localFiles.append(contentsOf: local.filter({!$0.isDirectory})) self.didChangeValue(forKey: &quot;localFilesTitle&quot;) // let remote = await self.getRemoteFiles() // // self.awsFiles = remote } } </code></pre>
[ { "answer_id": 74653698, "author": "jrturton", "author_id": 852828, "author_profile": "https://Stackoverflow.com/users/852828", "pm_score": 1, "selected": true, "text": "await MainActor.run { \n self.willChangeValue(forKey: \"localFilesTitle\")\n self.localFiles.append(contentsOf: local.filter({!$0.isDirectory}))\n self.didChangeValue(forKey: \"localFilesTitle\") \n}\n" }, { "answer_id": 74653837, "author": "vauxhall", "author_id": 4691224, "author_profile": "https://Stackoverflow.com/users/4691224", "pm_score": 0, "selected": false, "text": "MainActor async override func viewDidLoad() {\n super.viewDidLoad()\n Task {\n /*\n async code here\n */\n\n await myMethod()\n } \n}\n\n@MainActor private func myMethod() {\n willChangeValue(forKey: \"localFilesTitle\")\n localFiles.append(contentsOf: local.filter({!$0.isDirectory}))\n didChangeValue(forKey: \"localFilesTitle\")\n}\n" }, { "answer_id": 74659854, "author": "Rob", "author_id": 1271826, "author_profile": "https://Stackoverflow.com/users/1271826", "pm_score": 1, "selected": false, "text": "willChangeValue didChangeValue dynamic dynamic class ViewController: NSViewController { // or UIViewController, as appropriate\n\n @objc dynamic var localFilesTitle: String = \"\"\n\n var localTitle: String = \"\"\n\n var localFiles: [FileWrapper] = [] {\n didSet {\n localFilesTitle = \"\\(localTitle) (\\(localFiles.count))\"\n }\n }\n\n override func viewDidLoad() {\n super.viewDidLoad()\n\n Task {\n localTitle = \"Foo\"\n let localDirectories = await self.getLocalFiles()\n .filter { $0.isDirectory }\n\n localFiles.append(contentsOf: localDirectories)\n }\n }\n}\n localFiles dynamic keyPathsForValuesAffectingValue localFilesTitle localFiles class ViewController: NSViewController {\n\n @objc dynamic var localFilesTitle: String { \"\\(localTitle) (\\(localFiles.count))\" }\n\n var localTitle: String = \"\"\n\n @objc dynamic var localFiles: [FileWrapper] = []\n\n override func viewDidLoad() { \n // same as above ...\n }\n\n override class func keyPathsForValuesAffectingValue(forKey key: String) -> Set<String> {\n guard key == #keyPath(localFilesTitle) else {\n return super.keyPathsForValuesAffectingValue(forKey: key)\n }\n\n return [#keyPath(localFiles)]\n }\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2567126/" ]
74,651,117
<p>I was trying to open and read through a P5 .pgm (grayscale) file, then extract the least-significant-bit from each pixel. I tried to get the LSB of every pixel, so one bit bit per byte of the image.So it would take 8 image bytes/pixels to extract 1 byte of hidden text.Then, I would be able to get one byte of the hidden message and create a character. (using the ASCII values)</p> <p>I also have to display the hidden message.</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;ctype.h&gt; //Clear PGM (XV) comments. void pgmCommentClear(FILE *disk){ unsigned char ch; fread(&amp;ch, 1, 1, disk); if (ch != '#') { fseek(disk, -1, SEEK_CUR); return; } do { while (ch != '\n') fread(&amp;ch, 1, 1, disk); } while (ch == '#'); pgmCommentClear(disk); } //Read PGM formatted image (1D array). unsigned char *PGM_FILE_READ_1D(char *FileName, int *Width, int *Height, int *color) { int pmax; char ch; char type[3]; unsigned char *Image; FILE *disk; if ((disk = fopen(FileName, &quot;rb&quot;)) == NULL) { return NULL; } fscanf(disk, &quot;%s&quot;, type); if (!strcmp(type, &quot;P6&quot;)) *color = 1; else *color = 0; fread(&amp;ch, 1, 1, disk); pgmCommentClear(disk); fscanf(disk, &quot;%d&quot;, Width); fscanf(disk, &quot;%d&quot;, Height); fscanf(disk, &quot;%d&quot;, &amp;pmax); fread(&amp;ch, 1, 1, disk); if (*color == 1) { Image = (unsigned char *)calloc(*Height * *Width * 3, sizeof(unsigned char)); fread(Image, 1, (*Height * *Width * 3), disk); } else { Image = (unsigned char *)calloc(*Height * *Width, sizeof(unsigned char)); fread(Image, 1, (*Height * *Width), disk); } fclose(disk); return Image; } //function to convert binary to decimal int BinaryToDec(int array[]) { int decimal=0; int m=1; for(int i=7; i&gt;=0; i--){ decimal+= array[i]*m; m *= 2; } if(array[0] == 1) decimal *= -1; printf(&quot;decimal: %d\n&quot;, decimal); return decimal; } void DecToBinary(int dec){ int binary[8]; for(int i=0; i&lt;=8; i++){ if(dec &amp; (1 &lt;&lt; i)) binary[i] = 1; else binary[i] = 0; } printf(&quot;binaryform:&quot;); for(int i=7; i&gt;=0; i--){ printf(&quot;%d&quot;, binary[i]); } printf(&quot;\n&quot;); } int main(void){ char *fileName = &quot;hw10.pgm&quot;; int Width, Height, color; unsigned char *Image; Image = PGM_FILE_READ_1D(fileName, &amp;Width, &amp;Height, &amp;color); //int size = Width*Height; int size = 50; int array[8]; int xCount =0; for(int i=0; i&lt;size; i++){ int mask=1; for(int k=0; k&lt;8; k++){ array[k] = Image[i]&amp;mask; mask&lt;&lt;1; } printf(&quot;Image: %d\n&quot;, Image[i]); DecToBinary(Image[i]); BinaryToDec(array); } } </code></pre> <p>I have got this so far. To prevent going through too many pixels, it should stop after reading <code>xxx</code> from the file. I am still confused about how to display the uncovered characters.</p> <pre><code>Image: 214 binaryform:11010110 decimal: 0 Image: 213 binaryform:11010101 decimal: -255 Image: 208 binaryform:11010000 decimal: 0 Image: 214 binaryform:11010110 decimal: 0 Image: 215 </code></pre> <p>I have this as output(for the first few iterations,I didn't include all of them).</p> <p>How would I extract the LSBs, group them and then find the hidden text? I am just stuck on what to do next and would appreciate any suggestions.</p>
[ { "answer_id": 74651226, "author": "heystewart", "author_id": 13738949, "author_profile": "https://Stackoverflow.com/users/13738949", "pm_score": 2, "selected": true, "text": " // We will have (at most) size/8 bytes in the final text\n for(int i=0; i<size/8; i++){\n // Process eight image bits in a row\n int accum = 0;\n for(int k=0; k<8; k++){\n // Shift the current contents (multiply by 2)\n // and add in the new bit. This will reconstruct\n // a byte\n accum = (accum << 1) + (Image[i*8+k] & 1);\n }\n // the resulting byte is the next character of your hidden\n // text\n printf(\"%c\", accum);\n } \n printf(\"\\n\");\n" }, { "answer_id": 74651949, "author": "Support Ukraine", "author_id": 4386427, "author_profile": "https://Stackoverflow.com/users/4386427", "pm_score": 0, "selected": false, "text": "Image[i] & 1\n (LSB_a << 7) | (LSB_b << 6) | (LSB_c << 5) | ....\n putchar #include <stdio.h>\n#include <assert.h>\n\n\nint main(void) \n{\n unsigned char Image[] = {0x46, 0x51, 0x4a, 0x5c, 0x42, 0x10, 0xaa, 0xa1,\n 0xfe, 0x7b, 0x86, 0x18, 0x54, 0x2a, 0xa3, 0x60,\n 0x3c, 0x1d, 0x24, 0x9a, 0x06, 0x60, 0xa9, 0x75};\n \n size_t sz = sizeof Image / sizeof Image[0];\n assert(sz % 8 == 0);\n \n for (size_t i = 0; i < sz; i += 8)\n {\n int res = (Image[i] & 1) << 7 |\n (Image[i+1] & 1) << 6 |\n (Image[i+2] & 1) << 5 |\n (Image[i+3] & 1) << 4 |\n (Image[i+4] & 1) << 3 |\n (Image[i+5] & 1) << 2 |\n (Image[i+6] & 1) << 1 |\n (Image[i+7] & 1);\n\n putchar(res);\n }\n \n return 0;\n}\n ABC\n int res = 0;\n for (int k=0; k<8; ++k)\n {\n res |= (Image[i+k] & 1) << (7-k);\n }\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17566468/" ]
74,651,157
<p>I am making a program that asks how many players are playing, and then asks to input the names of those players. Then, I want it to print a random player, but I can't figure it out how.</p> <p>The code right now prints a random letter from the last name given, I think:</p> <pre class="lang-py prettyprint-override"><code>import random player_numberCount = input(&quot;How many players are there: &quot;) player_number = int(player_numberCount) for i in range(player_number): ask_player = input(&quot;name the players: &quot;) print(random.choice(ask_player)) </code></pre>
[ { "answer_id": 74651189, "author": "accdias", "author_id": 6789321, "author_profile": "https://Stackoverflow.com/users/6789321", "pm_score": 2, "selected": false, "text": "from random import choice\n\nnumber_of_players = int(input(\"How many players are there: \"))\nplayers = []\n\nfor _ in range(number_of_players):\n players.append(input(\"name the players: \"))\n\nprint(choice(players))\n" }, { "answer_id": 74651195, "author": "John Gordon", "author_id": 494134, "author_profile": "https://Stackoverflow.com/users/494134", "pm_score": 0, "selected": false, "text": "ask_player players = []\nfor i in range(player_number):\n players.append(input(\"Player name: \"))\n\nprint(random.choice(players))\n" }, { "answer_id": 74651205, "author": "JustMe", "author_id": 14188847, "author_profile": "https://Stackoverflow.com/users/14188847", "pm_score": 1, "selected": true, "text": "import random\n\nplayer_numberCount = input(\"How many players are there: \")\nplayer_number = int(player_numberCount)\n\nplayers = []\nfor i in range(player_number):\n players.append(input(f\"name player {i + 1}: \"))\n\nprint(random.choice(players))\n" }, { "answer_id": 74657075, "author": "Nilanjan Kumar", "author_id": 10047578, "author_profile": "https://Stackoverflow.com/users/10047578", "pm_score": 0, "selected": false, "text": "import random\n\nplayer_number = int(input(\"How many players are there: \"))\nplayer_list = []\n\n\nfor _ in range(player_number):\n ask_player = input(\"name the players: \")\n player_list.append(ask_player)\n\nprint(player_list[random.randint(0, player_number)])\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18106010/" ]
74,651,215
<p>I'm working on a captcha solver and I need to use ffmpeg, though nothing works. Windows 10 user.</p> <p>Warning when running the code for the first time:</p> <pre><code>C:\Users\user\AppData\Roaming\Python\Python310\site-packages\pydub\utils.py:170: RuntimeWarning: Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work warn(&quot;Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work&quot;, RuntimeWarning) </code></pre> <p>Then, when I tried running the script anyway and it required ffprobe, I got the following error:</p> <pre><code>C:\Users\user\AppData\Roaming\Python\Python310\site-packages\pydub\utils.py:198: RuntimeWarning: Couldn't find ffprobe or avprobe - defaulting to ffprobe, but may not work warn(&quot;Couldn't find ffprobe or avprobe - defaulting to ffprobe, but may not work&quot;, RuntimeWarning) Traceback (most recent call last): File &quot;D:\Scripts\captcha\main.py&quot;, line 164, in &lt;module&gt; main() File &quot;D:\Scripts\captcha\main.py&quot;, line 155, in main captchaSolver() File &quot;D:\Scripts\captcha\main.py&quot;, line 106, in captchaSolver sound = pydub.AudioSegment.from_mp3( File &quot;C:\Users\user\AppData\Roaming\Python\Python310\site-packages\pydub\audio_segment.py&quot;, line 796, in from_mp3 return cls.from_file(file, 'mp3', parameters=parameters) File &quot;C:\Users\user\AppData\Roaming\Python\Python310\site-packages\pydub\audio_segment.py&quot;, line 728, in from_file info = mediainfo_json(orig_file, read_ahead_limit=read_ahead_limit) File &quot;C:\Users\user\AppData\Roaming\Python\Python310\site-packages\pydub\utils.py&quot;, line 274, in mediainfo_json res = Popen(command, stdin=stdin_parameter, stdout=PIPE, stderr=PIPE) File &quot;C:\Program Files\Python310\lib\subprocess.py&quot;, line 966, in __init__ self._execute_child(args, executable, preexec_fn, close_fds, File &quot;C:\Program Files\Python310\lib\subprocess.py&quot;, line 1435, in _execute_child hp, ht, pid, tid = _winapi.CreateProcess(executable, args, FileNotFoundError: [WinError 2] The system cannot find the file specified </code></pre> <p>I tried downloading it normally, editing environment variables, pasting them in the same folder as the script, installing with pip, tested ffmpeg manually to see if it works and indeed it converted a mkv to mp4, however my script has no intention of running</p>
[ { "answer_id": 74651189, "author": "accdias", "author_id": 6789321, "author_profile": "https://Stackoverflow.com/users/6789321", "pm_score": 2, "selected": false, "text": "from random import choice\n\nnumber_of_players = int(input(\"How many players are there: \"))\nplayers = []\n\nfor _ in range(number_of_players):\n players.append(input(\"name the players: \"))\n\nprint(choice(players))\n" }, { "answer_id": 74651195, "author": "John Gordon", "author_id": 494134, "author_profile": "https://Stackoverflow.com/users/494134", "pm_score": 0, "selected": false, "text": "ask_player players = []\nfor i in range(player_number):\n players.append(input(\"Player name: \"))\n\nprint(random.choice(players))\n" }, { "answer_id": 74651205, "author": "JustMe", "author_id": 14188847, "author_profile": "https://Stackoverflow.com/users/14188847", "pm_score": 1, "selected": true, "text": "import random\n\nplayer_numberCount = input(\"How many players are there: \")\nplayer_number = int(player_numberCount)\n\nplayers = []\nfor i in range(player_number):\n players.append(input(f\"name player {i + 1}: \"))\n\nprint(random.choice(players))\n" }, { "answer_id": 74657075, "author": "Nilanjan Kumar", "author_id": 10047578, "author_profile": "https://Stackoverflow.com/users/10047578", "pm_score": 0, "selected": false, "text": "import random\n\nplayer_number = int(input(\"How many players are there: \"))\nplayer_list = []\n\n\nfor _ in range(player_number):\n ask_player = input(\"name the players: \")\n player_list.append(ask_player)\n\nprint(player_list[random.randint(0, player_number)])\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19552290/" ]
74,651,227
<p>I created table.</p> <pre><code>CREATE TABLE test_tab( ID INT, FIRSTNAME VARCHAR(40), TS TIMESTAMP) </code></pre> <p>And insert values into it.</p> <pre><code>INSERT INTO test_tab (ID, FIRSTNAME, TS) VALUES (1, 'Jhon', '2018-06-05 00:11:56'); INSERT INTO test_tab (ID, FIRSTNAME, TS) VALUES (2, 'Jhon', '2018-06-15 00:14:56'); INSERT INTO test_tab (ID, FIRSTNAME, TS) VALUES (3, 'Jhon', '2018-06-19 00:10:56'); INSERT INTO test_tab (ID, FIRSTNAME, TS) VALUES (4, 'Mike', '2018-06-05 00:10:56'); INSERT INTO test_tab (ID, FIRSTNAME, TS) VALUES (5, 'Mike', '2018-06-15 00:10:56'); INSERT INTO test_tab (ID, FIRSTNAME, TS) VALUES (6, 'Mike', '2018-06-20 00:10:56'); INSERT INTO test_tab (ID, FIRSTNAME, TS) VALUES (7, 'Lis', '2018-06-05 00:13:56'); INSERT INTO test_tab (ID, FIRSTNAME, TS) VALUES (8, 'Lis', '2018-06-15 00:17:56'); INSERT INTO test_tab (ID, FIRSTNAME, TS) VALUES (9, 'Lis', '2018-06-21 00:10:56'); </code></pre> <p>I need to delete rows so that only one row exist for one first name, leave row with maximum TS. It is the example of my request. How can I delete it?</p> <pre><code>SELECT DISTINCT firstname FROM test_tab GROUP BY firstname HAVING COUNT(firstname) &gt; 1 union select firstname from test_tab where ts = (select max(ts) from test_tab) </code></pre>
[ { "answer_id": 74651189, "author": "accdias", "author_id": 6789321, "author_profile": "https://Stackoverflow.com/users/6789321", "pm_score": 2, "selected": false, "text": "from random import choice\n\nnumber_of_players = int(input(\"How many players are there: \"))\nplayers = []\n\nfor _ in range(number_of_players):\n players.append(input(\"name the players: \"))\n\nprint(choice(players))\n" }, { "answer_id": 74651195, "author": "John Gordon", "author_id": 494134, "author_profile": "https://Stackoverflow.com/users/494134", "pm_score": 0, "selected": false, "text": "ask_player players = []\nfor i in range(player_number):\n players.append(input(\"Player name: \"))\n\nprint(random.choice(players))\n" }, { "answer_id": 74651205, "author": "JustMe", "author_id": 14188847, "author_profile": "https://Stackoverflow.com/users/14188847", "pm_score": 1, "selected": true, "text": "import random\n\nplayer_numberCount = input(\"How many players are there: \")\nplayer_number = int(player_numberCount)\n\nplayers = []\nfor i in range(player_number):\n players.append(input(f\"name player {i + 1}: \"))\n\nprint(random.choice(players))\n" }, { "answer_id": 74657075, "author": "Nilanjan Kumar", "author_id": 10047578, "author_profile": "https://Stackoverflow.com/users/10047578", "pm_score": 0, "selected": false, "text": "import random\n\nplayer_number = int(input(\"How many players are there: \"))\nplayer_list = []\n\n\nfor _ in range(player_number):\n ask_player = input(\"name the players: \")\n player_list.append(ask_player)\n\nprint(player_list[random.randint(0, player_number)])\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20503658/" ]
74,651,235
<p>I want to select an image from the gallery and display it at the bottom of the container when the container is clicked using image_picker. But <strong>'The argument type 'File?' can't be assigned to the parameter type 'File'. '</strong> error occurs. I searched hard for an answer on Google and StackOverFlow, but couldn't solve it. What should I do?</p> <p>This is my code:</p> <pre><code>import 'dart:io'; import 'package:flutter/material.dart'; import '../../../constants.dart'; import 'package:get/get.dart'; import 'package:image_picker/image_picker.dart'; class UploadFishingVesselImages extends StatefulWidget { const UploadFishingVesselImages({Key? key}) : super(key: key); @override State&lt;UploadFishingVesselImages&gt; createState() =&gt; _UploadFishingVesselImagesState(); } class _UploadFishingVesselImagesState extends State&lt;UploadFishingVesselImages&gt; { File? _image; final _picker = ImagePicker(); Future choiceImage() async { var pickedImage = await _picker.pickImage(source: ImageSource.gallery); if (pickedImage == null) return null; setState(() { _image = File(pickedImage.path); }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: baseColor10, elevation: 0, leading: IconButton( onPressed: () { Get.back(); }, icon: Icon(Icons.arrow_back), color: baseColor50, ), title: Text( '선박판매등록', style: TextStyle( color: baseColor50, fontFamily: 'semi-bold', fontSize: titleMedium, ), ), ), body: GestureDetector( onTap: () =&gt; FocusManager.instance.primaryFocus?.unfocus(), child: SingleChildScrollView( child: SafeArea( child: Padding( padding: const EdgeInsets.all(16.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ TopBar(context), marginHeight32, buildTextColumn(), Row( children: [ GestureDetector( onTap: () async { await choiceImage(); }, child: Expanded( child: Container( height: 90, width: MediaQuery.of(context).size.width * 0.3, decoration: BoxDecoration( color: baseColor20, ), ), ), ), SizedBox(width: 10), Expanded( child: Container( height: 90, width: MediaQuery.of(context).size.width * 0.3, decoration: BoxDecoration( color: baseColor20, ), ), ), SizedBox(width: 10), Expanded( child: Container( height: 90, width: MediaQuery.of(context).size.width * 0.3, decoration: BoxDecoration( color: baseColor20, ), ), ), ], ), // Error occurs. 'The argument type 'File?' can't be assigned // to the parameter type 'File'. Image.file(_image), ], ), ), ), ), ), floatingActionButton: Visibility( visible: MediaQuery.of(context).viewInsets.bottom == 0, child: FloatingActionButton( backgroundColor: primaryColor50, foregroundColor: baseColor10, focusColor: primaryColor50, onPressed: () {}, child: Icon( Icons.arrow_forward_ios_rounded, ), ), ), ); } // 상단 텍스트 Column buildTextColumn() { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( '사진 등록', style: TextStyle( color: baseColor50, fontSize: titleMedium, fontFamily: 'semi-bold', ), ), marginHeight4, Text( '판매선박의 사진을 등록해주세요.(최대 20장)' '\n다양하고 선명한 사진을 올릴 경우, 판매 확률이 더욱 높아집니다.', style: TextStyle( fontSize: bodySmall, ), ), marginHeight32, ], ); } // 상단바 Column TopBar(BuildContext context) { return Column( children: [ Row( children: [ Expanded( child: Container( height: 3, color: baseColor30, width: MediaQuery.of(context).size.width * 0.2, ), ), Expanded( child: Container( height: 3, color: baseColor30, width: MediaQuery.of(context).size.width * 0.2, ), ), Expanded( child: Container( height: 3, color: baseColor30, width: MediaQuery.of(context).size.width * 0.2, ), ), Expanded( child: Container( height: 3, color: primaryColor50, width: MediaQuery.of(context).size.width * 0.2, ), ), Expanded( child: Container( height: 3, color: baseColor30, width: MediaQuery.of(context).size.width * 0.2, ), ), ], ), marginHeight4, Row( children: [ Expanded( child: Container( child: Center( child: Text( '선박정보', style: TextStyle( fontFamily: 'medium', fontSize: labelSmall, color: baseColor30, ), ), ), ), ), Expanded( child: Container( child: Center( child: Text( '옵션', style: TextStyle( fontFamily: 'medium', fontSize: labelSmall, color: baseColor30, ), ), ), ), ), Expanded( child: Container( child: Center( child: Text( '설명등록', style: TextStyle( fontFamily: 'medium', fontSize: labelSmall, color: baseColor30, ), ), ), ), ), Expanded( child: Container( child: Center( child: Text( '사진등록', style: TextStyle( fontFamily: 'medium', fontSize: labelSmall, color: primaryColor50, ), ), ), ), ), Expanded( child: Container( child: Center( child: Text( '결제', style: TextStyle( fontFamily: 'medium', fontSize: labelSmall, color: baseColor30, ), ), ), ), ), ], ), ], ); } } </code></pre>
[ { "answer_id": 74651189, "author": "accdias", "author_id": 6789321, "author_profile": "https://Stackoverflow.com/users/6789321", "pm_score": 2, "selected": false, "text": "from random import choice\n\nnumber_of_players = int(input(\"How many players are there: \"))\nplayers = []\n\nfor _ in range(number_of_players):\n players.append(input(\"name the players: \"))\n\nprint(choice(players))\n" }, { "answer_id": 74651195, "author": "John Gordon", "author_id": 494134, "author_profile": "https://Stackoverflow.com/users/494134", "pm_score": 0, "selected": false, "text": "ask_player players = []\nfor i in range(player_number):\n players.append(input(\"Player name: \"))\n\nprint(random.choice(players))\n" }, { "answer_id": 74651205, "author": "JustMe", "author_id": 14188847, "author_profile": "https://Stackoverflow.com/users/14188847", "pm_score": 1, "selected": true, "text": "import random\n\nplayer_numberCount = input(\"How many players are there: \")\nplayer_number = int(player_numberCount)\n\nplayers = []\nfor i in range(player_number):\n players.append(input(f\"name player {i + 1}: \"))\n\nprint(random.choice(players))\n" }, { "answer_id": 74657075, "author": "Nilanjan Kumar", "author_id": 10047578, "author_profile": "https://Stackoverflow.com/users/10047578", "pm_score": 0, "selected": false, "text": "import random\n\nplayer_number = int(input(\"How many players are there: \"))\nplayer_list = []\n\n\nfor _ in range(player_number):\n ask_player = input(\"name the players: \")\n player_list.append(ask_player)\n\nprint(player_list[random.randint(0, player_number)])\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19443112/" ]
74,651,250
<p>I am trying to write a simple python program to read a log file and extract specific values I have the following log line I want to look out for</p> <pre><code>2022-12-02 13:13:10.539 [metrics-writer-1] [INFO ] metrics - type=GAUGE, name=Topic.myTopic1.TotalIncomingBytes.Count, value=20725269 </code></pre> <p>I have many topics such as <code>myTopic2</code>, <code>myTopic3</code> etc</p> <p>I want to be able to detect all such lines which show the total incoming bytes for various topics and extract the value. Is there any easy and efficient way to do so ? basically I want to be able to detect the following pattern</p> <pre><code>2022-12-02 13:13:10.539 [metrics-writer-1] [INFO ] metrics - type=GAUGE, name=Topic.${}.TotalIncomingBytes.Count, value=${} </code></pre> <p>Ignoring the timestamp ofcourse</p>
[ { "answer_id": 74651313, "author": "Tim Roberts", "author_id": 1883316, "author_profile": "https://Stackoverflow.com/users/1883316", "pm_score": 0, "selected": false, "text": "data = \"\"\"\\\n2022-12-02 13:13:10.539 [metrics-writer-1] [INFO ] metrics - type=GAUGE, name=Topic.myTopic1.TotalIncomingBytes.Count, value=20725269\n2022-12-02 13:13:10.539 [metrics-writer-1] [INFO ] metrics - type=GAUGE, name=Topic.myTopic1.TotalIncomingBytes.Count, value=20725269\n2022-12-02 13:13:10.539 [metrics-writer-1] [INFO ] metrics - type=GAUGE, name=Topic.myTopic1.TotalIncomingBytes.Count, value=20725269\n\"\"\"\n\ncounts = {}\n\nfor line in data.splitlines():\n if '[INFO ] metrics' in line:\n parts = line.split(' - ')\n parts = parts[1].split(', ')\n dct = {}\n for part in parts:\n key,val = part.split('=')\n dct[key] = val\n if dct['name'] not in counts:\n counts[dct['name']] = int(dct['value'])\n else:\n counts[dct['name']] += int(dct['value'])\n\nprint(counts)\n {'Topic.myTopic1.TotalIncomingBytes.Count': 62175807}\n \npattern = re.compile(r\".* - type=([^,]*), name=([^,]*), value=([^,]*)\")\ncounts = {}\n\nfor line in data.splitlines():\n if '[INFO ] metrics' in line:\n parts = pattern.match(line)\n if parts[2] not in counts:\n counts[parts[2]] = int(parts[3])\n else:\n counts[parts[2]] += int(parts[3])\n\nprint(counts)\n" }, { "answer_id": 74651400, "author": "Ouroborus", "author_id": 367865, "author_profile": "https://Stackoverflow.com/users/367865", "pm_score": 2, "selected": true, "text": "resultLines = []\nresultSums = {}\nwith open('recent.logs') as f:\n for idx, line in enumerate(f):\n pieces = line.rsplit('.TotalIncomingBytes.Count, value=', 1)\n if len(pieces) != 2: continue\n\n value = pieces[1]\n\n pieces = pieces[0].rsplit(' [metrics-writer-1] [INFO ] metrics - type=GAUGE, name=Topic.', 1)\n if len(pieces) != 2: continue\n\n topic = pieces[1]\n value = int(value)\n\n resultLines.append({\n 'idx': idx,\n 'line': line,\n 'topic': topic,\n 'value': value,\n })\n\n if topic not in resultSums:\n resultSums[topic] = 0\n resultSums[topic] = resultSums[topic] + value\n\nfor topic, value in resultSums.iteritems():\n print(topic, value)\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16452929/" ]
74,651,255
<p>I am new to Angular and I just started learning it recently. I came across the concept of Databinding in Angular. I was able to understand the syntax and stuff but there were some questions that I couldn't find an answer for. These are the queries I had:</p> <ol> <li><p>When we export a class from the component TS file, we can use the class properties in HTML file. For eg: Databinding a class property to a HTML element works. But how does this HTML element know the class or the class attribute? How does the HTML file have access to it?</p> </li> <li><p>Why exactly are we exporting a class for a component to be used? Is the component a class too? If yes, then wehen we use the component are we calling that class and this leads to rendering the HTML and CSS mentioned in the component?</p> </li> </ol> <p>Please let me know.</p>
[ { "answer_id": 74651313, "author": "Tim Roberts", "author_id": 1883316, "author_profile": "https://Stackoverflow.com/users/1883316", "pm_score": 0, "selected": false, "text": "data = \"\"\"\\\n2022-12-02 13:13:10.539 [metrics-writer-1] [INFO ] metrics - type=GAUGE, name=Topic.myTopic1.TotalIncomingBytes.Count, value=20725269\n2022-12-02 13:13:10.539 [metrics-writer-1] [INFO ] metrics - type=GAUGE, name=Topic.myTopic1.TotalIncomingBytes.Count, value=20725269\n2022-12-02 13:13:10.539 [metrics-writer-1] [INFO ] metrics - type=GAUGE, name=Topic.myTopic1.TotalIncomingBytes.Count, value=20725269\n\"\"\"\n\ncounts = {}\n\nfor line in data.splitlines():\n if '[INFO ] metrics' in line:\n parts = line.split(' - ')\n parts = parts[1].split(', ')\n dct = {}\n for part in parts:\n key,val = part.split('=')\n dct[key] = val\n if dct['name'] not in counts:\n counts[dct['name']] = int(dct['value'])\n else:\n counts[dct['name']] += int(dct['value'])\n\nprint(counts)\n {'Topic.myTopic1.TotalIncomingBytes.Count': 62175807}\n \npattern = re.compile(r\".* - type=([^,]*), name=([^,]*), value=([^,]*)\")\ncounts = {}\n\nfor line in data.splitlines():\n if '[INFO ] metrics' in line:\n parts = pattern.match(line)\n if parts[2] not in counts:\n counts[parts[2]] = int(parts[3])\n else:\n counts[parts[2]] += int(parts[3])\n\nprint(counts)\n" }, { "answer_id": 74651400, "author": "Ouroborus", "author_id": 367865, "author_profile": "https://Stackoverflow.com/users/367865", "pm_score": 2, "selected": true, "text": "resultLines = []\nresultSums = {}\nwith open('recent.logs') as f:\n for idx, line in enumerate(f):\n pieces = line.rsplit('.TotalIncomingBytes.Count, value=', 1)\n if len(pieces) != 2: continue\n\n value = pieces[1]\n\n pieces = pieces[0].rsplit(' [metrics-writer-1] [INFO ] metrics - type=GAUGE, name=Topic.', 1)\n if len(pieces) != 2: continue\n\n topic = pieces[1]\n value = int(value)\n\n resultLines.append({\n 'idx': idx,\n 'line': line,\n 'topic': topic,\n 'value': value,\n })\n\n if topic not in resultSums:\n resultSums[topic] = 0\n resultSums[topic] = resultSums[topic] + value\n\nfor topic, value in resultSums.iteritems():\n print(topic, value)\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16890522/" ]
74,651,287
<p>I have a function that returns a double. Any real number is a valid output. I'm using nan's to signal errors. I am error checking this way.</p> <pre><code>double foo(); const auto error1 = std::nan(&quot;1&quot;); const auto error2 = std::nan(&quot;2&quot;); const auto error3 = std::nan(&quot;3&quot;); bool bit_equal(double d1, double d2) { return *reinterpret_cast&lt;long long*&gt;(&amp;d1) == *reinterpret_cast&lt;long long*&gt;(&amp;d2); } const auto value = foo(); if(std::isnan(value)) { if (bit_equal(value, error1)) /*handle error1*/; else if (bit_equal(value, error1)) /*handle error2*/; else if (bit_equal(value, error1)) /*handle error3*/; else /*handle default error*/; } else /*use value normally*/; </code></pre> <p>Alternatively, if the compiler support has caught up, I can write it this way</p> <pre><code>double foo(); constexpr auto error1 = std::nan(&quot;1&quot;); constexpr auto error2 = std::nan(&quot;2&quot;); constexpr auto error3 = std::nan(&quot;3&quot;); constexpr bool bit_equal(double d1, double d2) { return std::bit_cast&lt;long long&gt;(d1) == std::bit_cast&lt;long long&gt;(d2); } const auto value = foo(); if(std::isnan(value)) { if (bit_equal(value, error1)) /*handle error1*/; else if (bit_equal(value, error1)) /*handle error2*/; else if (bit_equal(value, error1)) /*handle error3*/; else /*handle default error*/; } else /*use value normally*/; </code></pre> <p>Or even</p> <pre><code>double foo(); constexpr auto error1 = std::bit_cast&lt;long long&gt;(std::nan(&quot;1&quot;)); constexpr auto error2 = std::bit_cast&lt;long long&gt;(std::nan(&quot;2&quot;)); constexpr auto error3 = std::bit_cast&lt;long long&gt;(std::nan(&quot;3&quot;)); const auto value = foo(); if(std::isnan(value)) { switch(std::bit_cast&lt;long long&gt;(value)) { case error1: /*handle error1*/; break; case error1: /*handle error2*/; break; case error1: /*handle error3*/; break; default: /*handle default error*/; } } else /*use value normally*/; </code></pre> <p>I have to do this because comparing nan's with == always returns false.</p> <ol> <li>Is there a standard function to perform this comparison in C++?</li> <li>Are any of these 3 alternatives better than the others? Although the last option seems the most succinct, it requires me to do <code>return std::bit_cast&lt;double&gt;(error1);</code> inside <code>foo()</code> rather than just <code>return error1;</code>.</li> <li>Is there a better design where I can avoid using nan as an error value?</li> </ol>
[ { "answer_id": 74654280, "author": "Homer512", "author_id": 17167312, "author_profile": "https://Stackoverflow.com/users/17167312", "pm_score": 1, "selected": false, "text": "nan(const char*) double foo();\ndouble foo(std::nothrow_t) noexcept;\n\ndouble bar()\n{\n try {\n double x = foo();\n } except(const std::domain_error&) {\n error();\n }\n double y;\n if(std::isnan(y = foo(std::nothrow)))\n error();\n}\n double foo(Error* error=nullptr) struct Error\n{\n int errcode;\n operator bool() const noexcept\n { return errcode; }\n\n /** throw std::domain_error with error message */\n [[noreturn]] void raise() const;\n\n void check() const\n {\n if(errcode)\n raise();\n }\n}\ndouble foo(Error* err=nullptr) noexcept;\n\ndouble bar()\n{\n Error err;\n double x;\n x = foo(); // just continue on NaN\n if(std::isnan(x = foo()))\n return x; // abort without error explanation\n if(std::isnan(x = foo(&err)))\n err.raise(); // raise exception\n return x;\n}\n std::variant<double, Error> std::expected std::pair<double, Error> Error get_result_or_throw_error() template<class T>\nstruct Result\n{\n T result;\n Error err;\n\n Result() = default;\n explicit constexpr Result(T result) noexcept\n : result(result),\n err() // set to 0\n {}\n explicit constexpr Result(Error err, T result=NAN) noexcept\n : result(result),\n err(err)\n {}\n operator bool() const noexcept\n { return err; }\n\n T check() const\n {\n err.check(); // may throw\n return result;\n }\n bool unpack(T& out) const noexcept\n {\n if(err)\n return false;\n out = result;\n return true;\n }\n};\n\nResult<double> foo() noexcept;\n\ndouble bar()\n{\n double x = foo().check(); // throw on error\n double y = foo().result; // ignore error. Continue with NaN\n}\nResult<double> baz() noexcept\n{\n Result<double> rtrn;\n double x;\n if(! (rtrn = foo()).unpack(x))\n return rtrn; // propagate error\n rtrn.result = x + 1.; // continue operation\n return rtrn;\n}\n Result Error Error struct Error\n{\n int errcode;\n bool use_message;\n std::string message;\n};\n std::variant std::expected Result Result std::pair Result Result Result Result std::complex<double> Result Error [[nodiscard]] struct Error\n{\n std::string* message;\nprivate:\n [[noreturn]] static void raise_and_delete_msg(std::string*);\npublic:\n /*\n * Note: clang needs always_inline to generate efficient\n * code here. GCC is fine\n */\n [[noreturn, gnu::always_inline]] void raise() const\n { raise_and_delete_msg(message); }\n\n void discard() const noexcept\n { delete message; }\n\n operator bool() const noexcept\n { return message != nullptr; }\n\n void check() const\n {\n if(message)\n raise();\n }\n};\n\ntemplate<class T>\nclass Result\n{\n T result;\n Error err;\npublic:\n constexpr Result()\n : result(),\n err()\n {}\n explicit Result(T result)\n : result(std::move(result)),\n err()\n {}\n /** Takes ownerhip of message. Will delete */\n explicit Result(std::unique_ptr<std::string>&& message)\n : err(Error{message.release()})\n {}\n Result(std::unique_ptr<std::string>&& message, T invalid)\n : result(std::move(invalid)),\n err(Error{message.release()})\n {}\n T unchecked() noexcept\n {\n err.discard();\n return std::move(result);\n }\n T checked()\n {\n err.check();\n return std::move(result);\n }\n bool unpack(T& out) noexcept\n {\n if(err) {\n err.discard();\n return false;\n }\n out = std::move(result);\n return true;\n }\n};\n\n[[nodiscard]] Result<double> foo();\n\ndouble bar()\n{\n return foo().checked() + 1.;\n}\n sizeof(Error) [[nodiscard]] Error Result Error" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20662705/" ]
74,651,297
<p>I am using Angular 15. I want to get the property values from an array of objects, use the values to do calculation and then map them in the frontend. I had tried 3 different ways, I still can't get what I want but I think I am very close. The only difference between these 3 methods is, the .subscribe at the end of the codes. Please give me a hit of what to do.</p> <pre><code>export class LeftPanelComponent implements OnInit objects: Objects[] = []; density: Array&lt;Number&gt;=[]; </code></pre> <p>Method 1:</p> <pre><code>getObjects(): void { this.restService.getObjects() .subscribe((objects: any) =&gt; { this.objects = objects; const promise$ = from(objects); promise$ .pipe(map((obj:any) =&gt; ((obj.mass)/(obj.height * obj.length * obj.width)))) .subscribe((value) =&gt; console.log(`Emitted Values: `, value)); })); </code></pre> <p>Outcome 1:</p> <pre><code>Emitted Values: 253.96825396825395 Emitted Values: 4.444444444444445 Emitted Values: 666.6666666666665 Emitted Values: 200 Emitted Values: 166.66666666666669 Emitted Values: 1666.6666666666667 </code></pre> <p>It maps all the values in the console, so I am trying to map those numbers in the frontend.</p> <p>Method 2:</p> <pre><code>getObjects(): void { this.restService.getObjects() .subscribe((objects: any) =&gt; { this.objects = objects; const promise$ = from(objects); promise$ .pipe(map((obj:any) =&gt; ((obj.mass)/(obj.height * obj.length * obj.width)))) .subscribe((value:any) =&gt; { this.density = value }); }); </code></pre> <p>Outcome 2:</p> <pre><code>Name Density Van 1666.6666666666667 Pine tree 1666.6666666666667 Snake 1666.6666666666667 Giraffe 1666.6666666666667 Sheet of paper 1666.6666666666667 Television 1666.6666666666667 </code></pre> <p>The table in the frontend only showing the value of the last density item.</p> <p>Method 3:</p> <pre><code>getObjects(): void { this.restService.getObjects() .subscribe((objects: any) =&gt; { this.objects = objects; const promise$ = from(objects); promise$ .pipe(map((obj:any) =&gt; ((obj.mass)/(obj.height * obj.length * obj.width)))) .subscribe(((value:any) =&gt; { for(let i=0; i&lt;value.length; i++) { this.density[i] = value; } })); </code></pre> <p>Outcome 3: It doesn't do anything in the frontend.</p>
[ { "answer_id": 74654280, "author": "Homer512", "author_id": 17167312, "author_profile": "https://Stackoverflow.com/users/17167312", "pm_score": 1, "selected": false, "text": "nan(const char*) double foo();\ndouble foo(std::nothrow_t) noexcept;\n\ndouble bar()\n{\n try {\n double x = foo();\n } except(const std::domain_error&) {\n error();\n }\n double y;\n if(std::isnan(y = foo(std::nothrow)))\n error();\n}\n double foo(Error* error=nullptr) struct Error\n{\n int errcode;\n operator bool() const noexcept\n { return errcode; }\n\n /** throw std::domain_error with error message */\n [[noreturn]] void raise() const;\n\n void check() const\n {\n if(errcode)\n raise();\n }\n}\ndouble foo(Error* err=nullptr) noexcept;\n\ndouble bar()\n{\n Error err;\n double x;\n x = foo(); // just continue on NaN\n if(std::isnan(x = foo()))\n return x; // abort without error explanation\n if(std::isnan(x = foo(&err)))\n err.raise(); // raise exception\n return x;\n}\n std::variant<double, Error> std::expected std::pair<double, Error> Error get_result_or_throw_error() template<class T>\nstruct Result\n{\n T result;\n Error err;\n\n Result() = default;\n explicit constexpr Result(T result) noexcept\n : result(result),\n err() // set to 0\n {}\n explicit constexpr Result(Error err, T result=NAN) noexcept\n : result(result),\n err(err)\n {}\n operator bool() const noexcept\n { return err; }\n\n T check() const\n {\n err.check(); // may throw\n return result;\n }\n bool unpack(T& out) const noexcept\n {\n if(err)\n return false;\n out = result;\n return true;\n }\n};\n\nResult<double> foo() noexcept;\n\ndouble bar()\n{\n double x = foo().check(); // throw on error\n double y = foo().result; // ignore error. Continue with NaN\n}\nResult<double> baz() noexcept\n{\n Result<double> rtrn;\n double x;\n if(! (rtrn = foo()).unpack(x))\n return rtrn; // propagate error\n rtrn.result = x + 1.; // continue operation\n return rtrn;\n}\n Result Error Error struct Error\n{\n int errcode;\n bool use_message;\n std::string message;\n};\n std::variant std::expected Result Result std::pair Result Result Result Result std::complex<double> Result Error [[nodiscard]] struct Error\n{\n std::string* message;\nprivate:\n [[noreturn]] static void raise_and_delete_msg(std::string*);\npublic:\n /*\n * Note: clang needs always_inline to generate efficient\n * code here. GCC is fine\n */\n [[noreturn, gnu::always_inline]] void raise() const\n { raise_and_delete_msg(message); }\n\n void discard() const noexcept\n { delete message; }\n\n operator bool() const noexcept\n { return message != nullptr; }\n\n void check() const\n {\n if(message)\n raise();\n }\n};\n\ntemplate<class T>\nclass Result\n{\n T result;\n Error err;\npublic:\n constexpr Result()\n : result(),\n err()\n {}\n explicit Result(T result)\n : result(std::move(result)),\n err()\n {}\n /** Takes ownerhip of message. Will delete */\n explicit Result(std::unique_ptr<std::string>&& message)\n : err(Error{message.release()})\n {}\n Result(std::unique_ptr<std::string>&& message, T invalid)\n : result(std::move(invalid)),\n err(Error{message.release()})\n {}\n T unchecked() noexcept\n {\n err.discard();\n return std::move(result);\n }\n T checked()\n {\n err.check();\n return std::move(result);\n }\n bool unpack(T& out) noexcept\n {\n if(err) {\n err.discard();\n return false;\n }\n out = std::move(result);\n return true;\n }\n};\n\n[[nodiscard]] Result<double> foo();\n\ndouble bar()\n{\n return foo().checked() + 1.;\n}\n sizeof(Error) [[nodiscard]] Error Result Error" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16984566/" ]
74,651,340
<p>I have multiple functions that pass data from one to another. I moved one of the functions to the backend and receive data as API with Axios. Now I cannot manage to assign data from Axios to some local variable. Simple code would be like:</p> <pre><code>function function1() { axios({get, url}) .then(response =&gt; { globalVariable = response.data; function2(globalVariable); } function function2(globalVariable) { const local = globalVariable; return local; } </code></pre> <p>And then inside of function3, I want to do:</p> <pre><code>function function3() { const from_local = function2() from_local } </code></pre> <p>When I try this I receive <code>undefined</code> result. Please help.</p>
[ { "answer_id": 74654280, "author": "Homer512", "author_id": 17167312, "author_profile": "https://Stackoverflow.com/users/17167312", "pm_score": 1, "selected": false, "text": "nan(const char*) double foo();\ndouble foo(std::nothrow_t) noexcept;\n\ndouble bar()\n{\n try {\n double x = foo();\n } except(const std::domain_error&) {\n error();\n }\n double y;\n if(std::isnan(y = foo(std::nothrow)))\n error();\n}\n double foo(Error* error=nullptr) struct Error\n{\n int errcode;\n operator bool() const noexcept\n { return errcode; }\n\n /** throw std::domain_error with error message */\n [[noreturn]] void raise() const;\n\n void check() const\n {\n if(errcode)\n raise();\n }\n}\ndouble foo(Error* err=nullptr) noexcept;\n\ndouble bar()\n{\n Error err;\n double x;\n x = foo(); // just continue on NaN\n if(std::isnan(x = foo()))\n return x; // abort without error explanation\n if(std::isnan(x = foo(&err)))\n err.raise(); // raise exception\n return x;\n}\n std::variant<double, Error> std::expected std::pair<double, Error> Error get_result_or_throw_error() template<class T>\nstruct Result\n{\n T result;\n Error err;\n\n Result() = default;\n explicit constexpr Result(T result) noexcept\n : result(result),\n err() // set to 0\n {}\n explicit constexpr Result(Error err, T result=NAN) noexcept\n : result(result),\n err(err)\n {}\n operator bool() const noexcept\n { return err; }\n\n T check() const\n {\n err.check(); // may throw\n return result;\n }\n bool unpack(T& out) const noexcept\n {\n if(err)\n return false;\n out = result;\n return true;\n }\n};\n\nResult<double> foo() noexcept;\n\ndouble bar()\n{\n double x = foo().check(); // throw on error\n double y = foo().result; // ignore error. Continue with NaN\n}\nResult<double> baz() noexcept\n{\n Result<double> rtrn;\n double x;\n if(! (rtrn = foo()).unpack(x))\n return rtrn; // propagate error\n rtrn.result = x + 1.; // continue operation\n return rtrn;\n}\n Result Error Error struct Error\n{\n int errcode;\n bool use_message;\n std::string message;\n};\n std::variant std::expected Result Result std::pair Result Result Result Result std::complex<double> Result Error [[nodiscard]] struct Error\n{\n std::string* message;\nprivate:\n [[noreturn]] static void raise_and_delete_msg(std::string*);\npublic:\n /*\n * Note: clang needs always_inline to generate efficient\n * code here. GCC is fine\n */\n [[noreturn, gnu::always_inline]] void raise() const\n { raise_and_delete_msg(message); }\n\n void discard() const noexcept\n { delete message; }\n\n operator bool() const noexcept\n { return message != nullptr; }\n\n void check() const\n {\n if(message)\n raise();\n }\n};\n\ntemplate<class T>\nclass Result\n{\n T result;\n Error err;\npublic:\n constexpr Result()\n : result(),\n err()\n {}\n explicit Result(T result)\n : result(std::move(result)),\n err()\n {}\n /** Takes ownerhip of message. Will delete */\n explicit Result(std::unique_ptr<std::string>&& message)\n : err(Error{message.release()})\n {}\n Result(std::unique_ptr<std::string>&& message, T invalid)\n : result(std::move(invalid)),\n err(Error{message.release()})\n {}\n T unchecked() noexcept\n {\n err.discard();\n return std::move(result);\n }\n T checked()\n {\n err.check();\n return std::move(result);\n }\n bool unpack(T& out) noexcept\n {\n if(err) {\n err.discard();\n return false;\n }\n out = std::move(result);\n return true;\n }\n};\n\n[[nodiscard]] Result<double> foo();\n\ndouble bar()\n{\n return foo().checked() + 1.;\n}\n sizeof(Error) [[nodiscard]] Error Result Error" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10180757/" ]
74,651,347
<p>So Am unable to make a search function i want to get a variable from search field and show the results that matched but am constantly getting this error variable undefined when i try to console.log it in the node server Edit-- i have already changed the axios.post to axios.get</p> <pre><code>app.get(`/search/`, (req, res) =&gt; { let {name} =req.body var Desc = name console.log(name) var Op= Desc+'%' const q = &quot;SELECT * FROM taric where Description LIKE ? &quot;; con.query(q,[Op], (err, search) =&gt; { if (err) { console.log(err); return res.json(err); } console.log(search); return res.json(search); }); </code></pre> <p>});</p>
[ { "answer_id": 74651465, "author": "Sujit Libi", "author_id": 4935491, "author_profile": "https://Stackoverflow.com/users/4935491", "pm_score": 1, "selected": false, "text": "POST POST GET GET axios.get(`your_endpoint_route_goes_here`);\n axios.post(`your_endpoint_route_goes_here`, requestBodyObj);\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20528880/" ]
74,651,348
<p>Expected output is 'not detected' but I get 'no error' on get and post. Why?</p> <p>index.html</p> <pre><code>{% if error %} &lt;p&gt;{{ error }}&lt;/p&gt; {% else %} &lt;p&gt;no error&lt;/p&gt; {% endif %} </code></pre> <p>main.py</p> <pre><code>@app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'GET': print('get') return render_template('index.html') elif request.method == 'POST': print('post') post_data = request.get_json(force=True) if post_data['message'] == False: print('false') print('not detected') return render_template('index.html', error='not detected') </code></pre> <p>edit:</p> <p>not sure if this is what's causing the errors.</p> <p>script.js</p> <pre><code>window.onload = (event) =&gt; { if (!window.ethereum) { console.log('error - not detected'); fetch(`${window.origin}/`, { method: 'POST', headers: {'content-type': 'application/json'}, body: JSON.stringify({ 'message': false }) }); } else { console.log('detected'); } }; </code></pre>
[ { "answer_id": 74654409, "author": "Matthias", "author_id": 5272567, "author_profile": "https://Stackoverflow.com/users/5272567", "pm_score": 0, "selected": false, "text": "curl.exe --header \"Content-Type: application/json\" -d '{\\\"message\\\":false}' http://localhost:5000\n <p>not detected</p>\n" }, { "answer_id": 74662085, "author": "akdev", "author_id": 2065831, "author_profile": "https://Stackoverflow.com/users/2065831", "pm_score": 2, "selected": true, "text": "fetch fetch(`${window.origin}/`, {\n method: 'POST',\n headers: {'content-type': 'application/json'},\n body: JSON.stringify({\n 'message': false\n })\n})\n.then((response) => response.json())\n.then((data) => {\n console.log('Success:', data);\n})\n.catch((error) => {\n console.error('Error:', error);\n});\n json from flask import jsonify\n\n...\n if post_data['message'] == False:\n print('false')\n print('not detected')\n return jsonify(error='not detected')\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7764497/" ]
74,651,354
<p>Example : (101,Julie,Hapert,Pam,23932)</p> <p>Output should be : (101,&quot;Julie&quot;,&quot;Hapert&quot;,&quot;Pam&quot;,23932)</p>
[ { "answer_id": 74654409, "author": "Matthias", "author_id": 5272567, "author_profile": "https://Stackoverflow.com/users/5272567", "pm_score": 0, "selected": false, "text": "curl.exe --header \"Content-Type: application/json\" -d '{\\\"message\\\":false}' http://localhost:5000\n <p>not detected</p>\n" }, { "answer_id": 74662085, "author": "akdev", "author_id": 2065831, "author_profile": "https://Stackoverflow.com/users/2065831", "pm_score": 2, "selected": true, "text": "fetch fetch(`${window.origin}/`, {\n method: 'POST',\n headers: {'content-type': 'application/json'},\n body: JSON.stringify({\n 'message': false\n })\n})\n.then((response) => response.json())\n.then((data) => {\n console.log('Success:', data);\n})\n.catch((error) => {\n console.error('Error:', error);\n});\n json from flask import jsonify\n\n...\n if post_data['message'] == False:\n print('false')\n print('not detected')\n return jsonify(error='not detected')\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20168194/" ]
74,651,359
<p>I have implemented a TabLayout (which uses fragments) in my bottom sheet toolbar that has buttons which should affect the Main Activity. How do I pass the button clicks from the fragments in my TabLayout to the Main Activity?</p> <p>I'm stuck and I don't know where to start.</p>
[ { "answer_id": 74654409, "author": "Matthias", "author_id": 5272567, "author_profile": "https://Stackoverflow.com/users/5272567", "pm_score": 0, "selected": false, "text": "curl.exe --header \"Content-Type: application/json\" -d '{\\\"message\\\":false}' http://localhost:5000\n <p>not detected</p>\n" }, { "answer_id": 74662085, "author": "akdev", "author_id": 2065831, "author_profile": "https://Stackoverflow.com/users/2065831", "pm_score": 2, "selected": true, "text": "fetch fetch(`${window.origin}/`, {\n method: 'POST',\n headers: {'content-type': 'application/json'},\n body: JSON.stringify({\n 'message': false\n })\n})\n.then((response) => response.json())\n.then((data) => {\n console.log('Success:', data);\n})\n.catch((error) => {\n console.error('Error:', error);\n});\n json from flask import jsonify\n\n...\n if post_data['message'] == False:\n print('false')\n print('not detected')\n return jsonify(error='not detected')\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20392587/" ]
74,651,473
<p>I have data as follows:</p> <pre><code>myvec &lt;- c(&quot;Some 1 sentence...113_the answer&quot;, &quot;Some 3 sentence...1_the answer&quot;) </code></pre> <p>I would like to remove the three consecutrive dots and the following number from these strings, how should I do this?</p> <p>I could do:</p> <pre><code>myvec &lt;- gsub(&quot;\\...&quot;, &quot;&quot;, myvec) </code></pre> <p>And then remove the numbers with regex, but this is a bit unsafe for my data (as there might be more numbers in the string that I need to keep as in the created example).</p> <p>How should I remove the exact combination of three dots and a number?</p>
[ { "answer_id": 74654409, "author": "Matthias", "author_id": 5272567, "author_profile": "https://Stackoverflow.com/users/5272567", "pm_score": 0, "selected": false, "text": "curl.exe --header \"Content-Type: application/json\" -d '{\\\"message\\\":false}' http://localhost:5000\n <p>not detected</p>\n" }, { "answer_id": 74662085, "author": "akdev", "author_id": 2065831, "author_profile": "https://Stackoverflow.com/users/2065831", "pm_score": 2, "selected": true, "text": "fetch fetch(`${window.origin}/`, {\n method: 'POST',\n headers: {'content-type': 'application/json'},\n body: JSON.stringify({\n 'message': false\n })\n})\n.then((response) => response.json())\n.then((data) => {\n console.log('Success:', data);\n})\n.catch((error) => {\n console.error('Error:', error);\n});\n json from flask import jsonify\n\n...\n if post_data['message'] == False:\n print('false')\n print('not detected')\n return jsonify(error='not detected')\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8071608/" ]
74,651,480
<p>How can I make clickable link of url's in my content?</p> <p>Imagine you have piece of code <code>{{post.caption}}</code> and it returns one paragraph, something like this:</p> <blockquote> <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Numquam sunt nostrum nihil, illum nam ipsam at, ratione, <a href="https://google.com" rel="nofollow noreferrer">https://google.com</a> officia aperiam excepturi odio adipisci cum quo minus quibusdam laborum debitis voluptatibus temporibus.</p> </blockquote> <p>I want <code>https://google.com</code> to be linked automatically.</p> <p><strong>any suggestion?</strong></p> <p><strong>Update</strong></p> <p>I've just noticed that caption data for line brakes uses <code>\n\n</code> and <code>\n</code> and it's attached to the url's in texts so basically is some like this:</p> <blockquote> <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Numquam sunt\n\nnostrum nihil, illum nam ipsam at, ratione,\n\nhttps://google.com officia\n\naperiam excepturi odio adipisci cum quo minus quibusdam laborum debitis voluptatibus temporibus.</p> </blockquote> <p>could it be the reason why answers below didn't work?</p>
[ { "answer_id": 74654409, "author": "Matthias", "author_id": 5272567, "author_profile": "https://Stackoverflow.com/users/5272567", "pm_score": 0, "selected": false, "text": "curl.exe --header \"Content-Type: application/json\" -d '{\\\"message\\\":false}' http://localhost:5000\n <p>not detected</p>\n" }, { "answer_id": 74662085, "author": "akdev", "author_id": 2065831, "author_profile": "https://Stackoverflow.com/users/2065831", "pm_score": 2, "selected": true, "text": "fetch fetch(`${window.origin}/`, {\n method: 'POST',\n headers: {'content-type': 'application/json'},\n body: JSON.stringify({\n 'message': false\n })\n})\n.then((response) => response.json())\n.then((data) => {\n console.log('Success:', data);\n})\n.catch((error) => {\n console.error('Error:', error);\n});\n json from flask import jsonify\n\n...\n if post_data['message'] == False:\n print('false')\n print('not detected')\n return jsonify(error='not detected')\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8490993/" ]
74,651,496
<p>I have been trying to fix a problem while running python files in VSCode. I have a directory with a program <code>my_program.py</code> that imports a module <code>personal_functions.py</code> from a folder <code>packages_i_made</code>.</p> <pre><code>project ├── .env └── folder_a ├── my_program.py my_packages ├── __init__.py └── packages_i_made ├── __init__.py └── personal_functions.py </code></pre> <hr /> <p><code>my_program.py</code> contains:</p> <pre><code>from packages_i_made import personal_functions as pf </code></pre> <p>When typing this import line, the text autocompletes. Previously autocomplete didn't work and imports failed with the module not being recognized, which is why I added the <code>.env</code> file which contains <code>PYTHONPATH=&quot;C:/Users/user_1/my_packages&quot;</code> . I also updated the workspace settings with a path to the <code>.env</code> file.</p> <p>I hoped this would fix my import issue, but imports still fail as before when running the file:</p> <pre><code>Traceback (most recent call last): File &quot;c:\Users\user_1\...\...\project\folder_a\my_program.py&quot;, line 1, in &lt;module&gt; from packages_i_made import personal_functions as pf ModuleNotFoundError: No module named 'packages_i_made' </code></pre> <p>I'm an utter beginner to programming, but my interpretation of the issue is this: As far as I can tell, Pylance can see the <code>my_packages</code> directory and recognize the packages inside it. However, the python interpreter fails to recognize the path to <code>my_packages</code>. If it's important, the <code>my_packages</code> directory is in my system path. I've been banging my head against this for days. Any help is appreciated.</p>
[ { "answer_id": 74651919, "author": "JialeDu", "author_id": 19133920, "author_profile": "https://Stackoverflow.com/users/19133920", "pm_score": 2, "selected": true, "text": "sys.path.append import sys\nsys.path.append(\"C:/Users/user_1/my_packages\")\n\nfrom packages_i_made import personal_functions as pf\n .env \"python.analysis.extraPaths\"" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19935694/" ]
74,651,503
<p>i try to add two cookies in php file...but when i excute one the other is deleted</p> <p>here is the code:</p> <pre><code>&lt;?php if (isset($_COOKIE[&quot;background&quot;])) { echo &quot;&lt;style&gt; body { background-color:&quot;. $_COOKIE[&quot;background&quot;] . &quot;}&lt;/style&gt;&quot;; } if (isset($_COOKIE[&quot;username&quot;])) { echo &quot;&lt;h1&gt; &quot; . $_COOKIE[&quot;username&quot;] . &quot;&lt;/h1&gt;&quot;; } </code></pre> <pre><code>if ($_SERVER[&quot;REQUEST_METHOD&quot;] == &quot;POST&quot;) { setcookie(&quot;username&quot;,$_POST[&quot;username&quot;],strtotime(&quot;+1 day&quot;)); setcookie(&quot;background&quot;, $_POST[&quot;bg-color&quot;] , strtotime(&quot;+1 year&quot;)); header(&quot;location: &quot; . $_SERVER[&quot;REQUEST_URI&quot;] ,false); exit(); } ?&gt; </code></pre>
[ { "answer_id": 74651919, "author": "JialeDu", "author_id": 19133920, "author_profile": "https://Stackoverflow.com/users/19133920", "pm_score": 2, "selected": true, "text": "sys.path.append import sys\nsys.path.append(\"C:/Users/user_1/my_packages\")\n\nfrom packages_i_made import personal_functions as pf\n .env \"python.analysis.extraPaths\"" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15109567/" ]
74,651,506
<p>I'm trying to create an admin page for <code>my project</code> including <code>app1</code> and <code>app2</code></p> <pre><code>myproject settings.py urls.py admin.py app1 app2 </code></pre> <p>In <code>myproject/urls.py</code></p> <pre><code>urlpatterns = [ path('admin/', admin.site.urls), path('app1/', include('app1.urls')), path('app2/', include('app2.urls')), ] </code></pre> <p>In <code>myproject/admin.py</code></p> <pre><code>from django.contrib import admin from app1.models import User from app2.models import Manager, Employee, Task, Template admin.site.register(User) admin.site.register(Manager) admin.site.register(Employee) admin.site.register(Task) admin.site.register(Template) </code></pre> <p>Why doesn't my admin page import any models at all? Thanks!</p>
[ { "answer_id": 74651919, "author": "JialeDu", "author_id": 19133920, "author_profile": "https://Stackoverflow.com/users/19133920", "pm_score": 2, "selected": true, "text": "sys.path.append import sys\nsys.path.append(\"C:/Users/user_1/my_packages\")\n\nfrom packages_i_made import personal_functions as pf\n .env \"python.analysis.extraPaths\"" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11696515/" ]
74,651,540
<p>After some years developing web apps using ruby on rails, I decided to give Django a try, however it seems that I'm missing something, which is how to structure large project, or any project in general.</p> <p>For example, in rails we have a models folder which contains model classes, each in a separate ruby file, a controllers folder which contains controller classes, again each in a separate ruby file.</p> <p>However, in Django it split the project into independent apps, which can be installed independently in other Django project, each app has a models.py file which contains all the models classes, a views.py file which contain all the views functions.</p> <p>But then how to group functions in views like rails? That is one controller per each model.</p> <p>In general how to structure my project when it contains one large app that can't be separated into multiple independent apps? I want for example to have a view index function for each model, but how to do this if all functions are in one file?</p> <p>If my project is about selling cars for example. I should have index function that maps to /cars, another index function to map to /users, etc...</p> <p>I searched the web but couldn't find a suitable answer.</p> <p>It is unclear to me how to structure Django app, so any help will be appreciated.</p>
[ { "answer_id": 74651919, "author": "JialeDu", "author_id": 19133920, "author_profile": "https://Stackoverflow.com/users/19133920", "pm_score": 2, "selected": true, "text": "sys.path.append import sys\nsys.path.append(\"C:/Users/user_1/my_packages\")\n\nfrom packages_i_made import personal_functions as pf\n .env \"python.analysis.extraPaths\"" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15327464/" ]
74,651,542
<p>I'm in the process of learning how to make fetch api calls and return an array with a list of certain usernames. In the below code that I've written, the array that I was looking for seems to have been generated fine. However, when I try using .forEach() method on the array, it just does not seem to work. If I change the array contents to simple numbers like 1,2,3 etc, the .forEach() method seems to work as expected. Please let me know what am I missing out here? Thanks!</p> <pre><code>function getUsers() { let returnArray = []; fetch(&quot;https://api.github.com/users&quot;) .then((data) =&gt; data.json()) .then((data) =&gt; { data.forEach((item) =&gt; { returnArray.push(item.login); }); }); return returnArray; } function createListItem(text) { let li = document.createElement(&quot;li&quot;); li.textConent = text; return li; } function addUsersToDOM() { let body = document.getElementById(&quot;my-body&quot;); namesArray = getUsers(); console.log(namesArray); //Getting an array with the text elements namesArray.forEach((item) =&gt; { console.log(item); // Console log of individual text elements not working }); } addUsersToDOM(); </code></pre> <p>If I change the array contents to simple numbers like 1,2,3 etc, the .forEach() method seems to work as expected.</p>
[ { "answer_id": 74651678, "author": "Carsten Massmann", "author_id": 2610061, "author_profile": "https://Stackoverflow.com/users/2610061", "pm_score": 1, "selected": false, "text": "addUsersToDOM() async function getUsers(){\n return fetch(\"https://api.github.com/users\")\n .then(data => data.json())\n .then(data => data.map(item=>item.login));\n}\n\nasync function addUsersToDOM() {\n namesArray = await getUsers();\n console.log(namesArray);\n}\n\naddUsersToDOM(); .forEach() .map() .then() function getUsers(){\n return fetch(\"https://api.github.com/users\")\n .then(data => data.json())\n .then(data => data.map(item=>item.login));\n}\n\nfunction addUsersToDOM() {\n getUsers().then(console.log);\n}\n\naddUsersToDOM(); getUsers()" }, { "answer_id": 74651699, "author": "gureenkov56", "author_id": 18470572, "author_profile": "https://Stackoverflow.com/users/18470572", "pm_score": 0, "selected": false, "text": "function getUsers() {\n let returnArray = [];\n // return Promise\n return fetch(\"https://api.github.com/users\")\n .then((data) => data.json())\n .then((data) => {\n data.forEach((item) => {\n returnArray.push(item.login);\n });\n // return result by API\n return returnArray;\n });\n\n\n}\n\nfunction createListItem(text) {\n let li = document.createElement(\"li\");\n li.textConent = text;\n return li;\n}\n\n// async before function\nasync function addUsersToDOM() {\n let body = document.getElementById(\"my-body\");\n\n // await for waiting result\n namesArray = await getUsers();\n console.log('namesArray', namesArray); //Getting an array with the text elements\n\n namesArray.forEach((item) => {\n console.log(item); // Console log of individual text elements not working\n });\n}\n\naddUsersToDOM();" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19985072/" ]
74,651,550
<p>I am trying to add certain values from certain Brand from certain Month by using .groupby, but I keep getting the same Error: KeyError: ('Acura', '1', '2020')</p> <p>This Values Do exist in the file i am importing:</p> <pre><code>ANIO ID_MES MARCA MODELO UNI_VEH 2020 1 Acura ILX 6 2020 1 Acura Mdx 19 2020 1 Acura Rdx 78 2020 1 Acura TLX 7 2020 1 Honda Accord- 195 2020 1 Honda BR-V 557 2020 1 Honda Civic 693 2020 1 Honda CR-V 2095 </code></pre> <hr /> <pre><code>import pandas as pd import matplotlib.pyplot as plt df = pd.read_excel(&quot;HondaAcuraSales.xlsx&quot;) def sumMonthValues (year, brand): count = 1 sMonthSum = [] if anio == 2022: months = 10 else: months = 12 while count &lt;= months: month = 1 monthS = str(mes) BmY = df.groupby([&quot;BRAND&quot;,&quot;ID_MONTH&quot;,&quot;YEAR&quot;]) honda = BmY.get_group((brand, monthS, year)) sales = honda[&quot;UNI_SOL&quot;].sum() sMonthSum += [sales] month = month + 1 return sumasMes year = 2020 brand = ('Acura') chuck = sumMonthValues (year, brand) print (chuck) </code></pre> <p>Is there something wrong regarding how am i grouping the data?</p>
[ { "answer_id": 74651678, "author": "Carsten Massmann", "author_id": 2610061, "author_profile": "https://Stackoverflow.com/users/2610061", "pm_score": 1, "selected": false, "text": "addUsersToDOM() async function getUsers(){\n return fetch(\"https://api.github.com/users\")\n .then(data => data.json())\n .then(data => data.map(item=>item.login));\n}\n\nasync function addUsersToDOM() {\n namesArray = await getUsers();\n console.log(namesArray);\n}\n\naddUsersToDOM(); .forEach() .map() .then() function getUsers(){\n return fetch(\"https://api.github.com/users\")\n .then(data => data.json())\n .then(data => data.map(item=>item.login));\n}\n\nfunction addUsersToDOM() {\n getUsers().then(console.log);\n}\n\naddUsersToDOM(); getUsers()" }, { "answer_id": 74651699, "author": "gureenkov56", "author_id": 18470572, "author_profile": "https://Stackoverflow.com/users/18470572", "pm_score": 0, "selected": false, "text": "function getUsers() {\n let returnArray = [];\n // return Promise\n return fetch(\"https://api.github.com/users\")\n .then((data) => data.json())\n .then((data) => {\n data.forEach((item) => {\n returnArray.push(item.login);\n });\n // return result by API\n return returnArray;\n });\n\n\n}\n\nfunction createListItem(text) {\n let li = document.createElement(\"li\");\n li.textConent = text;\n return li;\n}\n\n// async before function\nasync function addUsersToDOM() {\n let body = document.getElementById(\"my-body\");\n\n // await for waiting result\n namesArray = await getUsers();\n console.log('namesArray', namesArray); //Getting an array with the text elements\n\n namesArray.forEach((item) => {\n console.log(item); // Console log of individual text elements not working\n });\n}\n\naddUsersToDOM();" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20610124/" ]
74,651,579
<p>I am reusing the same code for clearing the screen many times in my program, and I thought about turning it into a class, but I still don't get how classes work and how to properly make one.</p> <p>My code to clear buttons and other controls is as follows:</p> <pre><code> List&lt;RichTextBox&gt; _richTextBoxes = this.Controls.OfType&lt;RichTextBox&gt;().ToList(); List&lt;Button&gt; _buttons = this.Controls.OfType&lt;Button&gt;().ToList(); List&lt;Label&gt; _labels = this.Controls.OfType&lt;Label&gt;().ToList(); List&lt;TextBox&gt; _textBoxes = this.Controls.OfType&lt;TextBox&gt;().ToList(); foreach (var rich in _richTextBoxes) { this.Controls.Remove(rich); } foreach (var button in _buttons) { this.Controls.Remove(button); } foreach (var label in _labels) { this.Controls.Remove(label); } foreach (var textBox in _textBoxes) { this.Controls.Remove(textBox); } </code></pre>
[ { "answer_id": 74651678, "author": "Carsten Massmann", "author_id": 2610061, "author_profile": "https://Stackoverflow.com/users/2610061", "pm_score": 1, "selected": false, "text": "addUsersToDOM() async function getUsers(){\n return fetch(\"https://api.github.com/users\")\n .then(data => data.json())\n .then(data => data.map(item=>item.login));\n}\n\nasync function addUsersToDOM() {\n namesArray = await getUsers();\n console.log(namesArray);\n}\n\naddUsersToDOM(); .forEach() .map() .then() function getUsers(){\n return fetch(\"https://api.github.com/users\")\n .then(data => data.json())\n .then(data => data.map(item=>item.login));\n}\n\nfunction addUsersToDOM() {\n getUsers().then(console.log);\n}\n\naddUsersToDOM(); getUsers()" }, { "answer_id": 74651699, "author": "gureenkov56", "author_id": 18470572, "author_profile": "https://Stackoverflow.com/users/18470572", "pm_score": 0, "selected": false, "text": "function getUsers() {\n let returnArray = [];\n // return Promise\n return fetch(\"https://api.github.com/users\")\n .then((data) => data.json())\n .then((data) => {\n data.forEach((item) => {\n returnArray.push(item.login);\n });\n // return result by API\n return returnArray;\n });\n\n\n}\n\nfunction createListItem(text) {\n let li = document.createElement(\"li\");\n li.textConent = text;\n return li;\n}\n\n// async before function\nasync function addUsersToDOM() {\n let body = document.getElementById(\"my-body\");\n\n // await for waiting result\n namesArray = await getUsers();\n console.log('namesArray', namesArray); //Getting an array with the text elements\n\n namesArray.forEach((item) => {\n console.log(item); // Console log of individual text elements not working\n });\n}\n\naddUsersToDOM();" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20583505/" ]
74,651,587
<p>I’m new here. I wanted to sum all the values inside a dictionary, but my values are all strings, I don’t know how to convert the strings to integers… I really appreciate if anyone can help with it!</p> <p>Here’s the dictionary with code:</p> <pre><code>dic1 = dict() dic1 = {'2012-03-06':['1','4','5'],'2012-03-12':['7','3','10']} for i in dic1: print(i,’,’,sum(dic1[i])) </code></pre> <p>I want the output to be like this:</p> <p><code>2012-03-06, 10</code> <code>2012-03-12, 20</code></p>
[ { "answer_id": 74651621, "author": "Usman Arshad", "author_id": 20582506, "author_profile": "https://Stackoverflow.com/users/20582506", "pm_score": 2, "selected": false, "text": "map dic1 = {'2012-03-06':['1','4','5'],'2012-03-12':['7','3','10']}\n\nresult_dict = {key: sum(map(int, value)) for key, value in dic1.items()}\nprint(result_dict)\n {'2012-03-06': 10, '2012-03-12': 20}\n dic1 = {'2012-03-06':['1','3','5'],'2012-03-12':['7','3','10']}\nfor key, value in dic1.items():\n print(f\"{key}, {sum(map(int, value))}\")\n 2012-03-06, 10\n2012-03-12, 20\n" }, { "answer_id": 74651649, "author": "Jason Lee", "author_id": 15876496, "author_profile": "https://Stackoverflow.com/users/15876496", "pm_score": -1, "selected": true, "text": "dic1 = dict() \ndic1 = {'2012-03-06':['1','4','5'],'2012-03-12':['7','3','10']} \nfor i in dic1: \n print(i+','+ str(sum(map(int, dic1[i]))))\n map(func,iter)" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20663143/" ]
74,651,599
<p>What currently I have is this:</p> <pre><code> example: Joi.boolean() .required() .invalid(false) .label('Disclaimer Checkbox'), </code></pre> <p>and the output which I am getting is &quot;Disclaimer checkbox contains invalid value&quot;.</p> <p>What I need is label which contain only message which I wrote not &quot;contains invalid value&quot;</p>
[ { "answer_id": 74651629, "author": "sai reddy", "author_id": 18832149, "author_profile": "https://Stackoverflow.com/users/18832149", "pm_score": 1, "selected": false, "text": " a: Joi.string()\n .min(2)\n .max(10)\n .required()\n .messages({\n 'string.base': `\"a\" should be a type of 'text'`,\n 'string.empty': `\"a\" cannot be an empty field`,\n 'string.min': `\"a\" should have a minimum length of {#limit}`,\n 'any.required': `\"a\" is a required field`\n })\n});\n" }, { "answer_id": 74651875, "author": "AhmiiMec", "author_id": 20663314, "author_profile": "https://Stackoverflow.com/users/20663314", "pm_score": 0, "selected": false, "text": "bodyValidation: Joi.integer()\n .min(1997)\n .max(2022)\n .regex(/[0-9],{4}/)\n .required()\n .messages({\n 'integer.base': `Entered data should be an integer`,\n 'integer.regex': `Entered field is not an year`,\n 'integer.min': `Entered Year is less than 1997`,\n 'any.required': `Entry is required`\n })\n});\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10035101/" ]
74,651,606
<p>I have a NodeJS/Express app that is using Handlebars for templates.</p> <p>All of the templates and partials load fine except where I am returning data from an Express API.</p> <p>The data is returned and I can see it in the Chrome debugger.</p> <p>In this template, I am defining the HTML in a script and compiling it in JS.</p> <p>Here is the template HTML:</p> <pre><code>&lt;script id=&quot;search-result-template&quot; type=&quot;text/x-handlebars&quot;&gt; &lt;div&gt;String&lt;/div&gt; {{#each patient}} &lt;div&gt; {{cp_first_name}} &lt;/div&gt; {{!-- {{&gt; searchresultpartial}} --}} {{/each}} &lt;/script&gt; </code></pre> <p>The actual page is quite a bit more structured but I've narrowed it down to this for debugging.</p> <p>Here is the code that compiles the template:</p> <pre><code>let patientSearchButton = document.getElementById('patient-search-execute'); patientSearchButton.addEventListener(&quot;click&quot;, async function (e) { e.preventDefault(); let patientSearchFirstname = document.getElementById('patient-search-firstname') let cp_first_name = patientSearchFirstname.value; let url = baseURL + 'patientsearchquery/' + cp_first_name; const response = await fetch(url, { method: 'get', headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json' } }); var data = response.json(); let patientList = await data; patient = patientList; if (response.status === 200) { let patientSearchResultTemplate = document.querySelector(&quot;#search-result-template&quot;).innerHTML; let patientSearchResultTemplateFunction = Handlebars.compile(patientSearchResultTemplate); let patientSearchResultTemplateObject = patientSearchResultTemplateFunction(patient); let contentPartial = document.getElementById('patient-search-table'); contentPartial.innerHTML = patientSearchResultTemplateObject; if (Handlebars.Utils.isArray(patient)) { console.log(&quot;Array&quot;); } else { console.log(&quot;Not&quot;); } console.log(patient); } else { alert(&quot;HTTP-Error: &quot; + response.status); } }); </code></pre> <p>I can see the data from the API and I'm verifying that Handlebars sees it as an Array.</p> <p>It seems to break when it enters the #each helper.</p> <p>I've tried to shift the context with ../ and I've tried every variation I can think of the coax the data into the template.</p> <p>I was concerned that being in an event handler tied to a button click, that the &quot;this&quot; context was breaking. I moved the code outside of the event handler and &quot;this&quot; seemed to be correct in Chrome but the behavior did not change.</p> <p>Here is the array data in Chrome: <a href="https://i.stack.imgur.com/SFzi8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SFzi8.png" alt="array data in chrome" /></a></p> <p>When paused on a breakpoint in Chrome, I can see that the patient data is present when being passed to the template.</p> <p>I know it's something dumb but my head hurts from banging it against the wall.</p> <p>This has happened on two different templates. Granted, they were similar, but I've tried numerous variations and it still isn't loading.</p> <p>Thanks for any help you might offer.</p> <p>Does anybody see anything obvious?</p> <p>Addendum:</p> <p>I changed the code to pass the property and I can see it in Chrome now. <a href="https://i.stack.imgur.com/k3gBX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/k3gBX.png" alt="array with patients property" /></a></p> <p>It still doesn't show up in Handlebars.</p> <p>this.patients shows the data in the console. Why won't it render the variable?</p>
[ { "answer_id": 74652260, "author": "76484", "author_id": 3397771, "author_profile": "https://Stackoverflow.com/users/3397771", "pm_score": 2, "selected": true, "text": "{{#each patient}} patient patient #each patient let patientSearchResultTemplateObject = patientSearchResultTemplateFunction(patient);\n let patientSearchResultTemplateObject = patientSearchResultTemplateFunction({ patient: patient });\n let patientSearchResultTemplateObject = patientSearchResultTemplateFunction({ patient });\n patient" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16285100/" ]
74,651,609
<p>I am using the directive to validate the mobile number input</p> <pre><code>import { Directive, ElementRef, HostListener, Input } from '@angular/core'; @Directive({ selector: '[mobileNumber]' }) export class MobileNumberDirective { @Input() public value: any; constructor(private el: ElementRef) { } @HostListener('keypress', ['$event']) onKeyDown(event: KeyboardEvent) { var inp = String.fromCharCode(event.keyCode); if (/[0-9]/.test(inp)) { return true; } else { if (event.keyCode == 8 || (event.keyCode == 43 &amp;&amp; this.value == '')) { return true; } else { event.preventDefault(); return false; } } } } </code></pre> <p>The input field is this :</p> <pre><code>&lt;input type=&quot;text&quot; placeholder=&quot;Search Mobile&quot; autocomplete=&quot;off&quot; [value]=&quot;'1111199999'&quot; mobileNumber /&gt; </code></pre> <p>here, the [value] is not working when the directive is applied but working fine without it.</p>
[ { "answer_id": 74652260, "author": "76484", "author_id": 3397771, "author_profile": "https://Stackoverflow.com/users/3397771", "pm_score": 2, "selected": true, "text": "{{#each patient}} patient patient #each patient let patientSearchResultTemplateObject = patientSearchResultTemplateFunction(patient);\n let patientSearchResultTemplateObject = patientSearchResultTemplateFunction({ patient: patient });\n let patientSearchResultTemplateObject = patientSearchResultTemplateFunction({ patient });\n patient" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14390338/" ]
74,651,616
<p>I have a mouseover (hover) state I’m trying to work out. I have a set of anchors, and I’m wrapping each letter in a span and assigning a color to each from an array. What I’m looking to do is on mouseover, assign a color to each span again repeatedly in a sequence (from the array), like a constantly animating color sequence across each letter of a word.</p> <p>Updated: Currently the current anchor cycles (with help from Andrew Shearer I ended up targeting the current instead of all anchors), but not each individual cycling to its next color ... it’s working but a bit weird.</p> <p><a href="https://i.stack.imgur.com/GyGiQ.gif" rel="nofollow noreferrer">A simple visual of what I’m trying to do</a></p> <p>My start below:</p> <pre><code>var colors = [ &quot;red&quot;, &quot;lightsalmon&quot;, &quot;violet&quot;, &quot;skyblue&quot;]; $('a').each(function (index) { var characters = $(this).text().split(&quot;&quot;); $this = $(this); $this.empty(); $.each(characters, function (i, el) { $this.append(`&lt;span style=&quot;color: ${colors[i % colors.length]}&quot;&gt;${el}&lt;/span&gt;`); }); }); $('a').on('mouseover', function () { var span = $(this).find('span'); intervalId = setInterval(function () { color = colors.shift(); span.each(function (i) { $(this).next().attr(&quot;style&quot;, `color:${colors[i % colors.length]}`); }); colors.push(color); }, 500); }).on('mouseleave', function () { clearInterval(intervalId); }); </code></pre> <p><a href="https://jsfiddle.net/34bj70tn/" rel="nofollow noreferrer">https://jsfiddle.net/34bj70tn/</a></p>
[ { "answer_id": 74652260, "author": "76484", "author_id": 3397771, "author_profile": "https://Stackoverflow.com/users/3397771", "pm_score": 2, "selected": true, "text": "{{#each patient}} patient patient #each patient let patientSearchResultTemplateObject = patientSearchResultTemplateFunction(patient);\n let patientSearchResultTemplateObject = patientSearchResultTemplateFunction({ patient: patient });\n let patientSearchResultTemplateObject = patientSearchResultTemplateFunction({ patient });\n patient" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20663172/" ]
74,651,626
<p>I have tried this solution. But I am not receiving any output. Can someone please point out my error.</p> <pre><code>def num_case(str): z=0 j=0 for i in str: if i.isupper(): z=z+1 return z elif i.islower(): j=j+1 return j else: pass print('upper case:', z) print('lowercase:', j) num_case('The quick Brow Fox') </code></pre>
[ { "answer_id": 74652260, "author": "76484", "author_id": 3397771, "author_profile": "https://Stackoverflow.com/users/3397771", "pm_score": 2, "selected": true, "text": "{{#each patient}} patient patient #each patient let patientSearchResultTemplateObject = patientSearchResultTemplateFunction(patient);\n let patientSearchResultTemplateObject = patientSearchResultTemplateFunction({ patient: patient });\n let patientSearchResultTemplateObject = patientSearchResultTemplateFunction({ patient });\n patient" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14064726/" ]
74,651,691
<p>Print all details of the 16th order placed by each customer if any.</p> <p>How to print exact 16th Order?</p> <pre><code>SELECT COUNT(orderId) FROM orders GROUP BY CustomerID ORDER BY CustomerID; </code></pre>
[ { "answer_id": 74652260, "author": "76484", "author_id": 3397771, "author_profile": "https://Stackoverflow.com/users/3397771", "pm_score": 2, "selected": true, "text": "{{#each patient}} patient patient #each patient let patientSearchResultTemplateObject = patientSearchResultTemplateFunction(patient);\n let patientSearchResultTemplateObject = patientSearchResultTemplateFunction({ patient: patient });\n let patientSearchResultTemplateObject = patientSearchResultTemplateFunction({ patient });\n patient" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20663282/" ]
74,651,693
<blockquote> <p>A query that compares the LAG value and fills the sub column with data if there is a difference?</p> </blockquote> <pre><code>WITH A AS ( SELECT 'GOLD' AS Title, 1 AS RNUM, 555.4 AS VALUE1, null AS DIFF, null AS LAG FROM DUAL UNION ALL SELECT 'GOLD' AS Title, 2 AS RNUM, 555.4 AS VALUE1, 0 AS DIFF, 555.4 AS LAG FROM DUAL UNION ALL SELECT 'GOLD' AS Title, 3 AS RNUM, 555.4 AS VALUE1, 0 AS DIFF, 555.4 AS LAG FROM DUAL UNION ALL SELECT 'GOLD' AS Title, 4 AS RNUM, 556 AS VALUE1, 0.6 AS DIFF, 555.4 AS LAG FROM DUAL UNION ALL SELECT 'GOLD' AS Title, 5 AS RNUM, 556 AS VALUE1, 0 AS DIFF, 556 AS LAG FROM DUAL UNION ALL SELECT 'GOLD' AS Title, 6 AS RNUM, 556 AS VALUE1, 0 AS DIFF, 556 AS LAG FROM DUAL UNION ALL SELECT 'GOLD' AS Title, 7 AS RNUM, 556.7 AS VALUE1, 0.7 AS DIFF, 556 AS LAG FROM DUAL UNION ALL SELECT 'GOLD' AS Title, 8 AS RNUM, 556.7 AS VALUE1, 0 AS DIFF,556.7 AS LAG FROM DUAL UNION ALL SELECT 'GOLD' AS Title, 9 AS RNUM, 557.3 AS VALUE1, 0.6 AS DIFF, 556.7 AS LAG FROM DUAL UNION ALL SELECT 'SILVER' AS Title, 1 AS RNUM, 400.3 AS VALUE1, null AS DIFF, null AS LAG FROM DUAL UNION ALL SELECT 'SILVER' AS Title, 2 AS RNUM, 401.3 AS VALUE1, 1.0 AS DIFF, 400.3 AS LAG FROM DUAL UNION ALL SELECT 'SILVER' AS Title, 3 AS RNUM, 401.3 AS VALUE1, 0 AS DIFF, 401.3 AS LAG FROM DUAL UNION ALL SELECT 'SILVER' AS Title, 4 AS RNUM, 401.3 AS VALUE1, 0 AS DIFF, 401.3 AS LAG FROM DUAL UNION ALL SELECT 'SILVER' AS Title, 5 AS RNUM, 402.2 AS VALUE1, 0.9 AS DIFF, 401.3 AS LAG FROM DUAL UNION ALL SELECT 'SILVER' AS Title, 6 AS RNUM, 403.2 AS VALUE1, 1.0 AS DIFF, 402.2 AS LAG FROM DUAL ) </code></pre> <blockquote> <p>Using A, I want to get the same result as B.</p> </blockquote> <p>If the data in the DIFF column is greater than 0 (or according to a condition), I want to fill the value in the AccMaxNo column with the RNUM value in the DIFF column.</p> <pre><code> A </code></pre> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Title</th> <th>RNUM</th> <th>VALUE1</th> <th>DIFF</th> <th>LAG</th> <th>AccMaxNo</th> </tr> </thead> <tbody> <tr> <td>GOLD</td> <td>1</td> <td>555.4</td> <td>null</td> <td>null</td> <td></td> </tr> <tr> <td>GOLD</td> <td>2</td> <td>555.4</td> <td>0</td> <td>555.4</td> <td></td> </tr> <tr> <td>GOLD</td> <td>3</td> <td>555.4</td> <td>0</td> <td>555.4</td> <td></td> </tr> <tr> <td>GOLD</td> <td>4</td> <td>556</td> <td>0.6</td> <td>555.4</td> <td></td> </tr> <tr> <td>GOLD</td> <td>5</td> <td>556</td> <td>0</td> <td>556</td> <td></td> </tr> <tr> <td>GOLD</td> <td>6</td> <td>556</td> <td>0</td> <td>556</td> <td></td> </tr> <tr> <td>GOLD</td> <td>7</td> <td>556.7</td> <td>0.7</td> <td>556</td> <td></td> </tr> <tr> <td>GOLD</td> <td>8</td> <td>556.7</td> <td>0</td> <td>556.7</td> <td></td> </tr> <tr> <td>GOLD</td> <td>9</td> <td>557.3</td> <td>0.6</td> <td>556.7</td> <td></td> </tr> <tr> <td>SILVER</td> <td>1</td> <td>400.3</td> <td>null</td> <td>null</td> <td></td> </tr> <tr> <td>SILVER</td> <td>2</td> <td>401.3</td> <td>1.0</td> <td>400.3</td> <td></td> </tr> <tr> <td>SILVER</td> <td>3</td> <td>401.3</td> <td>0</td> <td>401.3</td> <td></td> </tr> <tr> <td>SILVER</td> <td>4</td> <td>401.3</td> <td>0</td> <td>401.3</td> <td></td> </tr> <tr> <td>SILVER</td> <td>5</td> <td>402.2</td> <td>0.9</td> <td>401.3</td> <td></td> </tr> <tr> <td>SILVER</td> <td>6</td> <td>403.2</td> <td>1.0</td> <td>402.2</td> <td></td> </tr> </tbody> </table> </div> <pre><code>QUERY B </code></pre> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Title</th> <th>RNUM</th> <th>VALUE1</th> <th>DIFF</th> <th>LAG</th> <th>AccMaxNo</th> </tr> </thead> <tbody> <tr> <td>GOLD</td> <td>1</td> <td>555.4</td> <td>null</td> <td>null</td> <td><strong>4</strong></td> </tr> <tr> <td>GOLD</td> <td>2</td> <td>555.4</td> <td>0</td> <td>555.4</td> <td><strong>4</strong></td> </tr> <tr> <td>GOLD</td> <td>3</td> <td>555.4</td> <td>0</td> <td>555.4</td> <td><strong>4</strong></td> </tr> <tr> <td><strong>GOLD</strong></td> <td><strong>4</strong></td> <td>556</td> <td><strong>0.6</strong></td> <td>555.4</td> <td><strong>4</strong></td> </tr> <tr> <td>GOLD</td> <td>5</td> <td>556</td> <td>0</td> <td>556</td> <td><strong>7</strong></td> </tr> <tr> <td>GOLD</td> <td>6</td> <td>556</td> <td>0</td> <td>556</td> <td><strong>7</strong></td> </tr> <tr> <td><strong>GOLD</strong></td> <td><strong>7</strong></td> <td>556.7</td> <td><strong>0.7</strong></td> <td>556</td> <td><strong>7</strong></td> </tr> <tr> <td>GOLD</td> <td>8</td> <td>556.7</td> <td>0</td> <td>556.7</td> <td><strong>9</strong></td> </tr> <tr> <td><strong>GOLD</strong></td> <td><strong>9</strong></td> <td>557.3</td> <td><strong>0.6</strong></td> <td>556.7</td> <td><strong>9</strong></td> </tr> <tr> <td>SILVER</td> <td>1</td> <td>400.3</td> <td>null</td> <td>null</td> <td><strong>2</strong></td> </tr> <tr> <td><strong>SILVER</strong></td> <td><strong>2</strong></td> <td>401.3</td> <td><strong>1.0</strong></td> <td>400.3</td> <td><strong>2</strong></td> </tr> <tr> <td>SILVER</td> <td>3</td> <td>401.3</td> <td>0</td> <td>401.3</td> <td><strong>5</strong></td> </tr> <tr> <td>SILVER</td> <td>4</td> <td>401.3</td> <td>0</td> <td>401.3</td> <td><strong>5</strong></td> </tr> <tr> <td><strong>SILVER</strong></td> <td><strong>5</strong></td> <td>402.2</td> <td><strong>0.9</strong></td> <td>401.3</td> <td><strong>5</strong></td> </tr> <tr> <td><strong>SILVER</strong></td> <td><strong>6</strong></td> <td>403.2</td> <td><strong>1.0</strong></td> <td>402.2</td> <td><strong>6</strong></td> </tr> </tbody> </table> </div>
[ { "answer_id": 74653670, "author": "MT0", "author_id": 1509264, "author_profile": "https://Stackoverflow.com/users/1509264", "pm_score": 1, "selected": false, "text": "MATCH_RECOGNIZE SELECT title,\n rnum,\n value1,\n value1 - lag AS diff,\n lag,\n MAX(rnum) OVER (PARTITION BY title, mno) AS accmaxno\nFROM table_name\nMATCH_RECOGNIZE(\n PARTITION BY title\n ORDER BY rnum\n MEASURES\n PREV(value1) AS lag,\n MATCH_NUMBER() AS mno\n ALL ROWS PER MATCH\n PATTERN ((^ first_row | same_value)* any_row)\n DEFINE\n same_value AS PREV(value1) = value1\n)\n CREATE TABLE table_name (Title, RNUM, VALUE1) AS\nSELECT 'GOLD', 1, 555.4 FROM DUAL UNION ALL\nSELECT 'GOLD', 2, 555.4 FROM DUAL UNION ALL\nSELECT 'GOLD', 3, 555.4 FROM DUAL UNION ALL\nSELECT 'GOLD', 4, 556 FROM DUAL UNION ALL\nSELECT 'GOLD', 5, 556 FROM DUAL UNION ALL\nSELECT 'GOLD', 6, 556 FROM DUAL UNION ALL\nSELECT 'GOLD', 7, 556.7 FROM DUAL UNION ALL\nSELECT 'GOLD', 8, 556.7 FROM DUAL UNION ALL\nSELECT 'GOLD', 9, 557.3 FROM DUAL UNION ALL\nSELECT 'SILVER', 1, 400.3 FROM DUAL UNION ALL\nSELECT 'SILVER', 2, 401.3 FROM DUAL UNION ALL\nSELECT 'SILVER', 3, 401.3 FROM DUAL UNION ALL\nSELECT 'SILVER', 4, 401.3 FROM DUAL UNION ALL\nSELECT 'SILVER', 5, 402.2 FROM DUAL UNION ALL\nSELECT 'SILVER', 6, 403.2 FROM DUAL;\n" }, { "answer_id": 74656660, "author": "Mahamoutou", "author_id": 13619116, "author_profile": "https://Stackoverflow.com/users/13619116", "pm_score": 0, "selected": false, "text": "SELECT a.*\n , FIRST_VALUE( \n CASE WHEN NULLIF(diff, 0) IS NOT NULL THEN rnum ELSE NULL END \n ) IGNORE NULLS OVER(\n PARTITION BY title ORDER BY rnum \n ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING\n ) AccMaxNo\nFROM A\n;\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14298339/" ]
74,651,695
<p>Im creating a project where the area or volume of certain shapes are calculated using dropdown menus in java. I don't have any errors when compiling however I'm getting the message that &quot;Unlikely argument type for equals(): String seems to be unrelated to String[]&quot;. As stated, it complies fine, but when running it allows area/volume to be selected, but it does not reach the next option pane to select the shapes.</p> <p>The message appears on: if (choices.equals(&quot;Area&quot;)) and : if (choices.equals(&quot;Volume&quot;))</p> <p>`</p> <pre><code>import javax.swing.JOptionPane; public class Shapes { public static void main(String[] args) { //Dropdown menu for area and volume String[] choices = {&quot;Area&quot;, &quot;Volume&quot;}; String question = (String) JOptionPane.showInputDialog(null, &quot;What would you like to calculate?&quot;, &quot;Shapes&quot;, JOptionPane.QUESTION_MESSAGE, null, choices, choices[0]); System.out.println(question); if (choices.equals(&quot;Area&quot;)) { //user chooses area String[] choices2D = {&quot;triangle&quot;, &quot;parallelogram&quot;, &quot;rectangle&quot;, &quot;trapezoid&quot;, &quot;circle&quot;}; String question2D = (String) JOptionPane.showInputDialog(null, &quot;What shape will you choose?&quot;, &quot;Shapes&quot;, JOptionPane.QUESTION_MESSAGE, null, choices2D, choices2D[0]); System.out.println(question2D); } //user chooses volume if (choices.equals(&quot;Volume&quot;)) { String[] choices3D = {&quot;cone&quot;, &quot;cylinder&quot;, &quot;rectanglular prism&quot;, &quot;trapezoid prism&quot;, &quot;sphere&quot;}; String question3D = (String) JOptionPane.showInputDialog(null, &quot;What figure will you choose?&quot;, &quot;Shapes&quot;, JOptionPane.QUESTION_MESSAGE, null, choices3D, choices3D[0]); System.out.println(question3D); } } } </code></pre> <p>`</p> <p>I originally had the options linked to a switch but would keep running into errors, after changing it to an if statement it will compile but not run properly.</p>
[ { "answer_id": 74651823, "author": "tquadrat", "author_id": 1554195, "author_profile": "https://Stackoverflow.com/users/1554195", "pm_score": 2, "selected": true, "text": "choices.equals(…) question question.equals(…) import javax.swing.JOptionPane;\npublic class Shapes \n{\n public static void main(String... args)\n {\n //Dropdown menu for area and volume\n String[] choices = {\"Area\", \"Volume\"};\n String question = (String) JOptionPane.showInputDialog( null, \n \"What would you like to calculate?\",\n \"Shapes\", \n JOptionPane.QUESTION_MESSAGE, \n null,\n choices,\n choices[0]) ;\n System.out.println(question);\n\n switch( question )\n {\n case \"Area\":\n {\n //user chooses area\n String[] choices2D = {\"triangle\", \"parallelogram\", \"rectangle\", \"trapezoid\", \"circle\"};\n String question2D = (String) JOptionPane.showInputDialog( null,\n \"What shape will you choose?\",\n \"Shapes\", \n JOptionPane.QUESTION_MESSAGE, \n null,\n choices2D,\n choices2D[0] );\n System.out.println( question2D );\n break;\n }\n\n case \"Volume\":\n {\n //user chooses volume\n String[] choices3D = {\"cone\", \"cylinder\", \"rectanglular prism\", \"trapezoid prism\", \"sphere\"};\n String question3D = (String) JOptionPane.showInputDialog( null, \n \"What figure will you choose?\",\n \"Shapes\", \n JOptionPane.QUESTION_MESSAGE, \n null,\n choices3D,\n choices3D[0] );\n System.out.println( question3D );\n break;\n }\n }\n }\n}\n switch-case enum" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20663178/" ]
74,651,755
<p>In fresh openfeign library (version 3.1.3) there is a check in <a href="https://github.com/spring-cloud/spring-cloud-openfeign/blob/v3.1.3/spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/annotation/PathVariableParameterProcessor.java#L52" rel="nofollow noreferrer">PathVariableParameterProcessor</a>, that verifies, that arguments with <code>@PathVariable</code> annotation should have name attribute filled. Similar check exists in RequestParamParameterProcessor.</p> <p>In <a href="https://docs.spring.io/spring-cloud-openfeign/docs/current/reference/html" rel="nofollow noreferrer">openfeign official documentation</a> there is no sign of that rule, there are examples with both named and unnamed annotations</p> <p>In <a href="https://github.com/spring-cloud/spring-cloud-netflix/issues/861" rel="nofollow noreferrer">one of the issues</a> of spring-cloud-netflix library (that as I heard is an openfeign's predecessor) people also recommend just declare names of parameters.</p> <p>In my project I had declared openfeign interfaces without explicitly specified parameter names (e.g. <code>@PathVariable String someId</code>), and it was working until now. Now I get exception coming from check stated above.</p> <pre><code>... org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.mycompany.client.MyClient': Unexpected exception during bean creation; nested exception is java.lang.IllegalStateException: PathVariable annotation was empty on param 0. ... Caused by: java.lang.IllegalStateException: PathVariable annotation was empty on param 0. at feign.Util.checkState(Util.java:122) at org.springframework.cloud.openfeign.annotation.PathVariableParameterProcessor.processArgument(PathVariableParameterProcessor.java:52) at org.springframework.cloud.openfeign.support.SpringMvcContract.processAnnotationsOnParameter(SpringMvcContract.java:280) at feign.Contract$BaseContract.parseAndValidateMetadata(Contract.java:126) at org.springframework.cloud.openfeign.support.SpringMvcContract.parseAndValidateMetadata(SpringMvcContract.java:193) at feign.Contract$BaseContract.parseAndValidateMetadata(Contract.java:65) at feign.ReflectiveFeign$ParseHandlersByName.apply(ReflectiveFeign.java:151) at feign.ReflectiveFeign.newInstance(ReflectiveFeign.java:49) at feign.Feign$Builder.target(Feign.java:268) at org.springframework.cloud.openfeign.DefaultTargeter.target(DefaultTargeter.java:30) at org.springframework.cloud.openfeign.FeignClientFactoryBean.getTarget(FeignClientFactoryBean.java:451) at org.springframework.cloud.openfeign.FeignClientFactoryBean.getObject(FeignClientFactoryBean.java:402) at org.springframework.cloud.openfeign.FeignClientsRegistrar.lambda$registerFeignClient$0(FeignClientsRegistrar.java:235) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.obtainFromSupplier(AbstractAutowireCapableBeanFactory.java:1249) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1191) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ... 130 more </code></pre> <p>Client interface api example</p> <pre><code> @GetMapping(&quot;/{entityType}/{entityId}&quot;) List&lt;Document&gt; getDocs( @PathVariable String entityType, @PathVariable String entityId, @RequestParam(required = false) String ownerId, @RequestParam(required = false) String q); </code></pre> <p>Can somebody explain, is it really mandatory routine to write names yourself, or is there another way to automate it?</p>
[ { "answer_id": 74651823, "author": "tquadrat", "author_id": 1554195, "author_profile": "https://Stackoverflow.com/users/1554195", "pm_score": 2, "selected": true, "text": "choices.equals(…) question question.equals(…) import javax.swing.JOptionPane;\npublic class Shapes \n{\n public static void main(String... args)\n {\n //Dropdown menu for area and volume\n String[] choices = {\"Area\", \"Volume\"};\n String question = (String) JOptionPane.showInputDialog( null, \n \"What would you like to calculate?\",\n \"Shapes\", \n JOptionPane.QUESTION_MESSAGE, \n null,\n choices,\n choices[0]) ;\n System.out.println(question);\n\n switch( question )\n {\n case \"Area\":\n {\n //user chooses area\n String[] choices2D = {\"triangle\", \"parallelogram\", \"rectangle\", \"trapezoid\", \"circle\"};\n String question2D = (String) JOptionPane.showInputDialog( null,\n \"What shape will you choose?\",\n \"Shapes\", \n JOptionPane.QUESTION_MESSAGE, \n null,\n choices2D,\n choices2D[0] );\n System.out.println( question2D );\n break;\n }\n\n case \"Volume\":\n {\n //user chooses volume\n String[] choices3D = {\"cone\", \"cylinder\", \"rectanglular prism\", \"trapezoid prism\", \"sphere\"};\n String question3D = (String) JOptionPane.showInputDialog( null, \n \"What figure will you choose?\",\n \"Shapes\", \n JOptionPane.QUESTION_MESSAGE, \n null,\n choices3D,\n choices3D[0] );\n System.out.println( question3D );\n break;\n }\n }\n }\n}\n switch-case enum" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2185612/" ]
74,651,756
<p>Could someone enlighten me where I'm going wrong.</p> <p>I can't convert the byte array produced from the hash sum function by casting with string, I have to use Sprintf.</p> <p>Here is a snippet of the code:</p> <pre><code>f, _ := os.Open(filename) hash := md5.New() io.Copy(hash, f) hashStringGood := fmt.Sprintf(&quot;%x&quot;, hash.Sum(nil)) hashStringJunk := string(hash.Sum(nil)[:]) </code></pre> <p>hasStringGood would result in <code>d41d8cd98f00b204e9800998ecf8427e</code> hashStringJunk would result in <code>��ُ�� ���B~</code></p>
[ { "answer_id": 74651841, "author": "Burak Serdar", "author_id": 11923999, "author_profile": "https://Stackoverflow.com/users/11923999", "pm_score": 1, "selected": false, "text": "fmt.Sprintf" }, { "answer_id": 74652394, "author": "chuckx", "author_id": 373815, "author_profile": "https://Stackoverflow.com/users/373815", "pm_score": 3, "selected": true, "text": "%x fmt fmt %s the uninterpreted bytes of the string or slice\n%q a double-quoted string safely escaped with Go syntax\n%x base 16, lower-case, two characters per byte\n encoding package main\n\nimport (\n \"crypto/md5\"\n \"encoding/base64\"\n \"encoding/hex\"\n \"fmt\"\n)\n\nfunc main() {\n hash := md5.Sum([]byte(\"input to be hashed\"))\n fmt.Printf(\"Using %%s verb: %s\\n\", hash)\n fmt.Printf(\"Using %%q verb: %q\\n\", hash)\n fmt.Printf(\"Using %%x verb: %x\\n\", hash)\n\n hexHash := hex.EncodeToString(hash[:])\n fmt.Printf(\"Converted to a hex-encoded string: %s\\n\", hexHash)\n\n base64Hash := base64.StdEncoding.EncodeToString(hash[:])\n fmt.Printf(\"Converted to a base64-encoded string: %s\\n\", base64Hash)\n}\n Using %s verb: �����Q���6���5�\nUsing %q verb: \"\\x8d\\xa8\\xf1\\xf8\\x06\\xd3Q\\x9d\\xa1\\xe46\\xdb\\xfb\\x9f5\\xd7\"\nUsing %x verb: 8da8f1f806d3519da1e436dbfb9f35d7\nConverted to a hex-encoded string: 8da8f1f806d3519da1e436dbfb9f35d7\nConverted to a base64-encoded string: jajx+AbTUZ2h5Dbb+5811w==\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8652908/" ]
74,651,759
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>let count = 0; let counter = document.querySelector("#number-el"); let btns = document.querySelectorAll(".btn"); let decreaseEl = document.querySelector(".decrease-el"); let increaseEl = document.querySelector(".increase-el"); btns.forEach(function(btn) { btn.addEventListener("click", function() { if (decreaseEl) { count--; console.log(count); } else if (increaseEl) { count++; } else { count = 0; } if (count &lt; 0) { counter.style.color = "green"; } if (count &gt; 0) { counter.style.color = "red"; } if (count === 0) { counter.style.color = "yellow"; } counter.textContent = count; }); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="container"&gt; &lt;div&gt; &lt;p id="counter-el"&gt;COUNTER &lt;div id="number-el"&gt;0&lt;/div&gt; &lt;/p&gt; &lt;button class="btn increase-el"&gt;INCREASE&lt;/button&gt; &lt;button class="btn reset-el"&gt;RESET&lt;/button&gt; &lt;button class="btn decrease-el"&gt;DECREASE&lt;/button&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>It's a program to perform a counter which increases, decreases, and reset the count from 0, but the output that I am getting is only increasing with a negative sign</p> <p>i access classes inside if statement directly. is it possible to directly access classes without using event objects.</p>
[ { "answer_id": 74651841, "author": "Burak Serdar", "author_id": 11923999, "author_profile": "https://Stackoverflow.com/users/11923999", "pm_score": 1, "selected": false, "text": "fmt.Sprintf" }, { "answer_id": 74652394, "author": "chuckx", "author_id": 373815, "author_profile": "https://Stackoverflow.com/users/373815", "pm_score": 3, "selected": true, "text": "%x fmt fmt %s the uninterpreted bytes of the string or slice\n%q a double-quoted string safely escaped with Go syntax\n%x base 16, lower-case, two characters per byte\n encoding package main\n\nimport (\n \"crypto/md5\"\n \"encoding/base64\"\n \"encoding/hex\"\n \"fmt\"\n)\n\nfunc main() {\n hash := md5.Sum([]byte(\"input to be hashed\"))\n fmt.Printf(\"Using %%s verb: %s\\n\", hash)\n fmt.Printf(\"Using %%q verb: %q\\n\", hash)\n fmt.Printf(\"Using %%x verb: %x\\n\", hash)\n\n hexHash := hex.EncodeToString(hash[:])\n fmt.Printf(\"Converted to a hex-encoded string: %s\\n\", hexHash)\n\n base64Hash := base64.StdEncoding.EncodeToString(hash[:])\n fmt.Printf(\"Converted to a base64-encoded string: %s\\n\", base64Hash)\n}\n Using %s verb: �����Q���6���5�\nUsing %q verb: \"\\x8d\\xa8\\xf1\\xf8\\x06\\xd3Q\\x9d\\xa1\\xe46\\xdb\\xfb\\x9f5\\xd7\"\nUsing %x verb: 8da8f1f806d3519da1e436dbfb9f35d7\nConverted to a hex-encoded string: 8da8f1f806d3519da1e436dbfb9f35d7\nConverted to a base64-encoded string: jajx+AbTUZ2h5Dbb+5811w==\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19569602/" ]
74,651,766
<p>I am trying to create docker containers and I was trying to 1 for MySql and another for Spring io. The DB container is running OK but the spring boot container comes at a point and exits. I have searched and tried many thing but I can't seem to be able to solve it, the thing that I concluded that it seems that something is wrong with the database environment or aplication.properties or maybe it could be somewhere else. I would be so grateful if someone could guide me to the solution.</p> <p>application.properties:</p> <pre><code>spring.datasource.url=jdbc:mysql://DB_containerfile:3306/phase2?useSSL=false&amp;allowPublicKeyRetrieval=true&amp;serverTimezone=UTC spring.datasource.username=testuser spring.datasource.password= testuser@123 spring.jpa.hibernate.ddl-auto=update spring.datasource.driver-class-name= com.mysql.cj.jdbc.Driver </code></pre> <p>dockerfile:</p> <pre><code>FROM openjdk:17 ADD target/springboot-crud-api-0.0.1-SNAPSHOT.jar app.jar ENTRYPOINT [&quot;java&quot;,&quot;-jar&quot;,&quot;app.jar&quot;] </code></pre> <p>docker-compose.yml:</p> <pre><code>version: '3.8' services: DB_containerfile: image: mysql:latest container_name: DB_containerfile environment: - MYSQL_ROOT_PASSWORD=//////////// - MYSQL_DATABASE=phase2 - MYSQL_USER=testuser - MYSQL_PASSWORD=testuser@123 backend_containerfile: image: backend_image container_name: backend_containerfile ports: - 8080:8080 build: context: ./ dockerfile: Dockerfile depends_on: - DB_containerfile </code></pre> <p>NOTE: I assigned the password that I enter when I write this command on the cmd &quot;mysql -u root -p&quot; to MYSQL_ROOT_PASSWORD</p> <p>Spring boot log:</p> <pre><code>backend_containerfile | 2022-12-02 06:02:54.757 WARN 1 --- [ main] com.zaxxer.hikari.util.DriverDataSource : Registered driver with driverClassName=com.mysql.jdbc.Driver was not found, trying direct instantiation. backend_containerfile | 2022-12-02 06:02:56.040 ERROR 1 --- [ main] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Exception during pool initialization. backend_containerfile | backend_containerfile | java.sql.SQLNonTransientConnectionException: Public Key Retrieval is not allowed backend_containerfile | at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:110) ~[mysql-connector-j-8.0.31.jar!/:8.0.31] backend_containerfile | at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-j-8.0.31.jar!/:8.0.31] backend_containerfile | at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:828) ~[mysql-connector-j-8.0.31.jar!/:8.0.31] backend_containerfile | at com.mysql.cj.jdbc.ConnectionImpl.&lt;init&gt;(ConnectionImpl.java:448) ~[mysql-connector-j-8.0.31.jar!/:8.0.31] backend_containerfile | at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:241) ~[mysql-connector-j-8.0.31.jar!/:8.0.31] backend_containerfile | at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:198) ~[mysql-connector-j-8.0.31.jar!/:8.0.31]backend_containerfile | at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138) ~[HikariCP-4.0.3.jar!/:na] backend_containerfile | at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:364) ~[HikariCP-4.0.3.jar!/:na] backend_containerfile | at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:206) ~[HikariCP-4.0.3.jar!/:na] backend_containerfile | at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:476) ~[HikariCP-4.0.3.jar!/:na] backend_containerfile | at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:561) ~[HikariCP-4.0.3.jar!/:na] backend_containerfile | at com.zaxxer.hikari.pool.HikariPool.&lt;init&gt;(HikariPool.java:115) ~[HikariCP-4.0.3.jar!/:na] backend_containerfile | at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112) ~[HikariCP-4.0.3.jar!/:na] backend_containerfile | at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122) ~[hibernate-core-5.6.12.Final.jar!/:5.6.12.Final] </code></pre> <p>What I tried: 1)I tried docker volume prune. 2)I tried removing the</p> <pre><code>- MYSQL_USER=testuser - MYSQL_PASSWORD=testuser@123 spring.datasource.username=testuser spring.datasource.password= testuser@123\` </code></pre> <p>and only going with</p> <pre><code>- MYSQL_ROOT_PASSWORD=//////////// </code></pre> <p>3)I tried both</p> <pre><code>spring.datasource.driver-class-name= com.mysql.cj.jdbc.Driver spring.datasource.driver-class-name= com.mysql.jdbc.Driver </code></pre> <p>4)I put allowPublicKeyRetrieval=true in spring.datasource.url And many other thing I tried but the result remained the same.</p> <p>Sorry, for the long question but I really tried to figure out the problem by myself but now I need someone's insight. And thank you.</p>
[ { "answer_id": 74651841, "author": "Burak Serdar", "author_id": 11923999, "author_profile": "https://Stackoverflow.com/users/11923999", "pm_score": 1, "selected": false, "text": "fmt.Sprintf" }, { "answer_id": 74652394, "author": "chuckx", "author_id": 373815, "author_profile": "https://Stackoverflow.com/users/373815", "pm_score": 3, "selected": true, "text": "%x fmt fmt %s the uninterpreted bytes of the string or slice\n%q a double-quoted string safely escaped with Go syntax\n%x base 16, lower-case, two characters per byte\n encoding package main\n\nimport (\n \"crypto/md5\"\n \"encoding/base64\"\n \"encoding/hex\"\n \"fmt\"\n)\n\nfunc main() {\n hash := md5.Sum([]byte(\"input to be hashed\"))\n fmt.Printf(\"Using %%s verb: %s\\n\", hash)\n fmt.Printf(\"Using %%q verb: %q\\n\", hash)\n fmt.Printf(\"Using %%x verb: %x\\n\", hash)\n\n hexHash := hex.EncodeToString(hash[:])\n fmt.Printf(\"Converted to a hex-encoded string: %s\\n\", hexHash)\n\n base64Hash := base64.StdEncoding.EncodeToString(hash[:])\n fmt.Printf(\"Converted to a base64-encoded string: %s\\n\", base64Hash)\n}\n Using %s verb: �����Q���6���5�\nUsing %q verb: \"\\x8d\\xa8\\xf1\\xf8\\x06\\xd3Q\\x9d\\xa1\\xe46\\xdb\\xfb\\x9f5\\xd7\"\nUsing %x verb: 8da8f1f806d3519da1e436dbfb9f35d7\nConverted to a hex-encoded string: 8da8f1f806d3519da1e436dbfb9f35d7\nConverted to a base64-encoded string: jajx+AbTUZ2h5Dbb+5811w==\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17683987/" ]
74,651,790
<p>Trying to update the carType value from another component.Updated value only working inside the callFun fucntion. Not able to get outside of the callFun function. I am trying to get the updated value inside callFlag function. But it is not working. So, how to resolve this issue using service.</p> <p>compone.component.html:</p> <pre><code>export class ComponeComponent implements OnInit { constructor() {} carType = false; ngOnInit() {} callFun(flag: any) { this.carType = flag; console.log(this.carType); } callFlag() { alert(this.carType); } } </code></pre> <p>compthree.component.html:</p> <pre><code>export class CompthreeComponent implements OnInit { constructor(public onecomp: ComponeComponent) {} ngOnInit() { this.onecomp.callFun(true); } } </code></pre> <p>Demo: <a href="https://stackblitz.com/edit/angular-ivy-dxk3m9?file=src%2Fapp%2Fcompone%2Fcompone.component.ts" rel="nofollow noreferrer">https://stackblitz.com/edit/angular-ivy-dxk3m9?file=src%2Fapp%2Fcompone%2Fcompone.component.ts</a></p>
[ { "answer_id": 74652046, "author": "renaud H", "author_id": 7032224, "author_profile": "https://Stackoverflow.com/users/7032224", "pm_score": 0, "selected": false, "text": "export class ChildComponent {\n @Output() $buttonClicked = new EventEmitter<boolean>();\n\n public click(): void {\n this.$buttonClicked.emit(true);\n }\n}\n //////parent.component.html\n<child-selector\n ($buttonClicked)=callFun($event)>\n</child-selector>\n//////parent.component.ts\n...\nexport class ParentComponent {\n public callFun(value: boolean): void {\n this.carType = flag; \n }\n}\n" }, { "answer_id": 74652192, "author": "Eliseo", "author_id": 8558186, "author_profile": "https://Stackoverflow.com/users/8558186", "pm_score": 1, "selected": false, "text": " //in CompthreeComponent\n @ViewChild(ComptwoComponent) twocomp:ComptwoComponent\n\n //in ComptwoComponent\n@ViewChild(ComponeComponent) onecomp:ComponeComponent\n ngAfterViewInit() {\n this.twocomp.onecomp.callFun(true);\n }\n" }, { "answer_id": 74652241, "author": "Antonio Vida", "author_id": 3713193, "author_profile": "https://Stackoverflow.com/users/3713193", "pm_score": 2, "selected": true, "text": "ComponeComponent ...\n carTypeChanged$ = new Subject<boolean>();\n\n constructor() {}\n\n getCarTypeChanged() {\n return this.carTypeChanged$.asObservable();\n }\n\n setCarTypeChanged(value: boolean) {\n this.carTypeChanged$.next(value);\n }\n ...\n this.appService\n .getCarTypeChanged()\n .pipe(delay(0))\n .subscribe((value) => {\n this.carType = value;\n });\n CompthreeComponent this.appService.setCarTypeChanged(true);\n" }, { "answer_id": 74652297, "author": "N.F.", "author_id": 4052858, "author_profile": "https://Stackoverflow.com/users/4052858", "pm_score": 0, "selected": false, "text": "@Input() <app-comp*** [carType]=\"value\"> import { Component, OnInit, Input } from '@angular/core';\n\n@Component({\n selector: 'app-compone',\n templateUrl: './compone.component.html',\n styleUrls: ['./compone.component.css'],\n})\nexport class ComponeComponent implements OnInit {\n constructor() {}\n\n @Input() carType = false;\n ngOnInit() {}\n\n callFun(flag: any) {\n this.carType = flag;\n console.log(this.carType);\n }\n\n callFlag() {\n alert(this.carType);\n }\n}\n <app-compone [carType]=\"carType\"></app-compone>\n import { Component, OnInit, Input } from '@angular/core';\n\n@Component({\n selector: 'app-comptwo',\n templateUrl: './comptwo.component.html',\n styleUrls: ['./comptwo.component.css'],\n})\nexport class ComptwoComponent implements OnInit {\n @Input() carType = false;\n\n constructor() {}\n\n ngOnInit() {}\n}\n <app-comptwo [carType]=\"true\"></app-comptwo>\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19099386/" ]
74,651,872
<pre><code>useEffect(() =&gt; { const maybeHandler = (event: MouseEvent) =&gt; { menuData.forEach((el) =&gt; { if (el.hasActiveDropdown &amp;&amp; event.clientY &gt; 50) { handleCloseDropDown(); // handleDropDown('0'); } }); }; document.addEventListener('mousedown', maybeHandler); return () =&gt; document.removeEventListener('mousedown', maybeHandler); }, [handleCloseDropDown, menuData]); </code></pre> <p>I am used this useEffect to handle mulltip dropdowns in navbar component, navbar has fix height 50px so my logic is whenver use click outside the navbar the drop downs all are close.</p> <p>I am unadble to test in JEST this clientY propery</p>
[ { "answer_id": 74652046, "author": "renaud H", "author_id": 7032224, "author_profile": "https://Stackoverflow.com/users/7032224", "pm_score": 0, "selected": false, "text": "export class ChildComponent {\n @Output() $buttonClicked = new EventEmitter<boolean>();\n\n public click(): void {\n this.$buttonClicked.emit(true);\n }\n}\n //////parent.component.html\n<child-selector\n ($buttonClicked)=callFun($event)>\n</child-selector>\n//////parent.component.ts\n...\nexport class ParentComponent {\n public callFun(value: boolean): void {\n this.carType = flag; \n }\n}\n" }, { "answer_id": 74652192, "author": "Eliseo", "author_id": 8558186, "author_profile": "https://Stackoverflow.com/users/8558186", "pm_score": 1, "selected": false, "text": " //in CompthreeComponent\n @ViewChild(ComptwoComponent) twocomp:ComptwoComponent\n\n //in ComptwoComponent\n@ViewChild(ComponeComponent) onecomp:ComponeComponent\n ngAfterViewInit() {\n this.twocomp.onecomp.callFun(true);\n }\n" }, { "answer_id": 74652241, "author": "Antonio Vida", "author_id": 3713193, "author_profile": "https://Stackoverflow.com/users/3713193", "pm_score": 2, "selected": true, "text": "ComponeComponent ...\n carTypeChanged$ = new Subject<boolean>();\n\n constructor() {}\n\n getCarTypeChanged() {\n return this.carTypeChanged$.asObservable();\n }\n\n setCarTypeChanged(value: boolean) {\n this.carTypeChanged$.next(value);\n }\n ...\n this.appService\n .getCarTypeChanged()\n .pipe(delay(0))\n .subscribe((value) => {\n this.carType = value;\n });\n CompthreeComponent this.appService.setCarTypeChanged(true);\n" }, { "answer_id": 74652297, "author": "N.F.", "author_id": 4052858, "author_profile": "https://Stackoverflow.com/users/4052858", "pm_score": 0, "selected": false, "text": "@Input() <app-comp*** [carType]=\"value\"> import { Component, OnInit, Input } from '@angular/core';\n\n@Component({\n selector: 'app-compone',\n templateUrl: './compone.component.html',\n styleUrls: ['./compone.component.css'],\n})\nexport class ComponeComponent implements OnInit {\n constructor() {}\n\n @Input() carType = false;\n ngOnInit() {}\n\n callFun(flag: any) {\n this.carType = flag;\n console.log(this.carType);\n }\n\n callFlag() {\n alert(this.carType);\n }\n}\n <app-compone [carType]=\"carType\"></app-compone>\n import { Component, OnInit, Input } from '@angular/core';\n\n@Component({\n selector: 'app-comptwo',\n templateUrl: './comptwo.component.html',\n styleUrls: ['./comptwo.component.css'],\n})\nexport class ComptwoComponent implements OnInit {\n @Input() carType = false;\n\n constructor() {}\n\n ngOnInit() {}\n}\n <app-comptwo [carType]=\"true\"></app-comptwo>\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17822267/" ]
74,651,876
<pre><code> here is my service method public Employee updateByEmployeeIdAndFirstName(Long employeeId, String firstName, Employee employeesDetails){ Employee updateEmployee = employeeRepository.findByEmployeeIdAndFirstName(employeeId, firstName).get(0); if (employeesDetails.getFirstName() != null ) { updateEmployee.setFirstName(employeesDetails.getFirstName()); } if (employeesDetails.getLastName() != null ) { updateEmployee.setLastName(employeesDetails.getLastName()); } if (employeesDetails.getEmail() != null ) { updateEmployee.setEmail(employeesDetails.getEmail()); } if (employeesDetails.getPhoneNumber() != null ) { updateEmployee.setPhoneNumber(employeesDetails.getPhoneNumber()); } if (employeesDetails.getHireDate() != null ) { updateEmployee.setHireDate(employeesDetails.getHireDate()); } if (employeesDetails.getJob() != null ) { updateEmployee.setJob(employeesDetails.getJob()); } if (employeesDetails.getSalary() != null ) { updateEmployee.setSalary(employeesDetails.getSalary()); } if (employeesDetails.getCommissionPct() != null ) { updateEmployee.setCommissionPct(employeesDetails.getCommissionPct()); } if (employeesDetails.getManager() != null ) { updateEmployee.setManager(employeesDetails.getManager()); } if (employeesDetails.getDepartment() != null ) { updateEmployee.setDepartment(employeesDetails.getDepartment()); } employeeRepository.save(updateEmployee); return updateEmployee; } here is my mapping method </code></pre> <p>@PutMapping(path = &quot;/update&quot;) public ResponseEntity updateEmployee(@RequestParam(&quot;id&quot;) Long employeeId, @RequestParam(&quot;firstName&quot;) String firstName, @RequestBody Employee employeesDetails) {<br /> return ResponseEntity.ok(employeeService.updateByEmployeeIdAndFirstName(employeeId, firstName, employeesDetails)); }</p> <pre><code> </code></pre> <p>i want to make my update method more flexible with looping so no need to use a lot of if</p>
[ { "answer_id": 74652337, "author": "Pekinek", "author_id": 5198144, "author_profile": "https://Stackoverflow.com/users/5198144", "pm_score": 1, "selected": false, "text": "Optional.ofNullable(employeesDetails.getEmail()).ifPresent(updateEmployee::setEmail);\n" }, { "answer_id": 74652658, "author": "prtrichor", "author_id": 20273388, "author_profile": "https://Stackoverflow.com/users/20273388", "pm_score": 0, "selected": false, "text": " Field[] fields = employeesDetails.getClass().getDeclaredFields();\n for (int i = 0; i < fields.length; i++) {\n fields[i].setAccessible(true);\n Object value = fields[i].get(employeesDetails);\n fields[i].set(updateEmployee, value);\n System.out.println(fields[i].get(updateEmployee));\n }\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20663370/" ]
74,651,878
<p>Let's say I have this model:</p> <pre><code>public enum State { Valid = 1, Invalid = 2 } public class Person { public string Name { get; set; } public State state { get; set; } } </code></pre> <p>And this controller action:</p> <pre><code>[HttpPost] public object SavePerson([FromBody] Person person) { return person; } </code></pre> <p>If I send this JSON, everything works just fine:</p> <pre><code>{ &quot;name&quot;: &quot;John&quot;, &quot;state&quot;: 1 } </code></pre> <p>However, if I change the <code>&quot;state&quot;: 1</code> to an invalid enumeration like <code>&quot;state&quot;: &quot;&quot;</code> or <code>&quot;state&quot;: &quot;1&quot;</code>, then the <code>person</code> parameter would be null.</p> <p>In other words, if I send a JSON that is <strong>partially</strong> valid, ASP.NET Core ignores all fields.</p> <p>How can I configure ASP.NET Core to at least extract the valid fields from the body?</p>
[ { "answer_id": 74652810, "author": "Ziv Weissman", "author_id": 4162955, "author_profile": "https://Stackoverflow.com/users/4162955", "pm_score": 1, "selected": false, "text": " static void Main(string[] args)\n {\n //This should be run on startup code (there are other ways to do that as well - you can put this settings only on controllers etc...)\n JsonConvert.DefaultSettings = () => new JsonSerializerSettings\n {\n Error = HandleDeserializationError\n };\n\n var jsonStr = \"{\\\"name\\\": \\\"John\\\",\\\"state\\\": \\\"\\\" }\";\n var person = JsonConvert.DeserializeObject<Person>(jsonStr); \n\n Console.WriteLine(JsonConvert.SerializeObject(person)); //{\"Name\":\"John\",\"state\":0}\n }\n\n public static void HandleDeserializationError(object sender, ErrorEventArgs args)\n {\n var error = args.ErrorContext.Error.Message;\n args.ErrorContext.Handled = true;\n }\n public void ConfigureServices(IServiceCollection services)\n {\n //look for services.AddControllers() -> or add it if it does not exist\n services.AddControllers()\n .AddMvcOptions(options =>\n {\n //... might have options here\n })\n //this is what you need to add\n .AddNewtonsoftJson(options =>\n {\n options.SerializerSettings.Error = HandleDeserializationError\n });\n }\n" }, { "answer_id": 74652939, "author": "Nileksh Dhimer", "author_id": 6262661, "author_profile": "https://Stackoverflow.com/users/6262661", "pm_score": 0, "selected": false, "text": "public State? state { get; set; }\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16473956/" ]
74,651,891
<p>I have a requirement to customize the contributor role at Azure Subscription level, such that, people added to that customized contributor role can NOT view or read the data from the storage account (under that subscription).</p> <p>This is how i'm doing this:</p> <p>Step1 <a href="https://i.stack.imgur.com/rgoKE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rgoKE.png" alt=" Clone Subscription contributor Basic" /></a></p> <p>Step2 <a href="https://i.stack.imgur.com/pckKP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pckKP.png" alt="Permission" /></a></p> <p>Step3 ( Actions shows * ) <a href="https://i.stack.imgur.com/Aek1F.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Aek1F.png" alt="JSON" /></a></p> <p><a href="https://i.stack.imgur.com/zLnNW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zLnNW.png" alt="Review and Create" /></a></p> <p><a href="https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles#contributor" rel="nofollow noreferrer">This</a> MSFT link does NOT show me the JSON details that can be removed or added so that the read access to the storage account can be <strong>blocked</strong>.</p> <p>Hence, I'm trying below ways to customize this (two assignable scopes to cover subscription as well as block viewing the storage data):</p> <p><a href="https://i.stack.imgur.com/0qUZE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0qUZE.png" alt="2 assignable scope" /></a></p> <p>Note, The idea is to People need a contributor role to manage the subscription. However, they <em>MUST NOT</em> view the data from the storage under this particular subscription.</p> <p>I think this is not the right approach. Are there any other ways to achieve this? Thanks.</p>
[ { "answer_id": 74652810, "author": "Ziv Weissman", "author_id": 4162955, "author_profile": "https://Stackoverflow.com/users/4162955", "pm_score": 1, "selected": false, "text": " static void Main(string[] args)\n {\n //This should be run on startup code (there are other ways to do that as well - you can put this settings only on controllers etc...)\n JsonConvert.DefaultSettings = () => new JsonSerializerSettings\n {\n Error = HandleDeserializationError\n };\n\n var jsonStr = \"{\\\"name\\\": \\\"John\\\",\\\"state\\\": \\\"\\\" }\";\n var person = JsonConvert.DeserializeObject<Person>(jsonStr); \n\n Console.WriteLine(JsonConvert.SerializeObject(person)); //{\"Name\":\"John\",\"state\":0}\n }\n\n public static void HandleDeserializationError(object sender, ErrorEventArgs args)\n {\n var error = args.ErrorContext.Error.Message;\n args.ErrorContext.Handled = true;\n }\n public void ConfigureServices(IServiceCollection services)\n {\n //look for services.AddControllers() -> or add it if it does not exist\n services.AddControllers()\n .AddMvcOptions(options =>\n {\n //... might have options here\n })\n //this is what you need to add\n .AddNewtonsoftJson(options =>\n {\n options.SerializerSettings.Error = HandleDeserializationError\n });\n }\n" }, { "answer_id": 74652939, "author": "Nileksh Dhimer", "author_id": 6262661, "author_profile": "https://Stackoverflow.com/users/6262661", "pm_score": 0, "selected": false, "text": "public State? state { get; set; }\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1837976/" ]
74,651,911
<p>I am having a headache with the error mentioned in the title. I am using react-native-gifted-charts (<a href="https://www.npmjs.com/package/react-native-gifted-charts/v/1.0.3" rel="nofollow noreferrer">https://www.npmjs.com/package/react-native-gifted-charts/v/1.0.3</a>) The charts works perfectly in ios but in Android it keeps crushing and throwing &quot;Invariant Violation: requireNativeComponent: &quot;RNSVGSvgViewAndroid&quot; was not found in the UIManager.&quot; First I thought it was a problem of my code as it worked for Android before,but even I reverse the code the error continues. I am using using yarn as a pack manager and Expo Managed Workflow. The dependencies are the following.</p> <pre><code>&quot;react-native&quot;: &quot;0.70.5&quot;, &quot;react-native-gifted-charts&quot;: &quot;^1.2.42&quot;, &quot;react-native-linear-gradient&quot;: &quot;2.6.2&quot;, &quot;react-native-svg&quot;: &quot;12.1.0&quot;, </code></pre> <p>■Things I tried</p> <ol> <li>I removed the node modules and ran yarn again ← didn't work</li> <li>I changed the versions of react-native-svg as I read in the article below sometimes this kind of errors happens beacause of the missmatch of the versions.← didn't work <a href="https://github.com/Abhinandan-Kushwaha/react-native-gifted-charts/issues/263" rel="nofollow noreferrer">https://github.com/Abhinandan-Kushwaha/react-native-gifted-charts/issues/263</a></li> <li>I removed react-native-gifted-charts react-native-linear-gradient react-native-svg and yarn added again to see if it solves the problem. ← didn't work</li> <li>At the end, to confirm my code is not the problem I deleted all the code and made a simple barChart example to see if it works (sample code below) ← didn't work</li> </ol> <pre><code>import React, { useState } from &quot;react&quot;; import { View, StyleSheet, Text, TouchableOpacity, ScrollView } from &quot;react-native&quot;; import type { NativeStackScreenProps } from &quot;@react-navigation/native-stack&quot;; import { MainStackParamList } from &quot;../types/navigation&quot;; import dayjs from &quot;dayjs&quot;; import { BarChart, LineChart, PieChart } from &quot;react-native-gifted-charts&quot;; import { useSelector } from &quot;react-redux&quot;; import { RootState } from &quot;../store&quot;; export const StatisticsScreen: React.FC&lt;Props&gt; = () =&gt; { const data=[ {value:50}, {value:80}, {value:90}, {value:70} ] return ( &lt;BarChart data={data} /&gt; ); }; </code></pre> <p>P.S I also ran yarn cache clean hoping it was the cache but didn't help...</p>
[ { "answer_id": 74652582, "author": "JSONCMD", "author_id": 20629269, "author_profile": "https://Stackoverflow.com/users/20629269", "pm_score": 0, "selected": false, "text": "npm install react-native-svg-transformer --save \n" }, { "answer_id": 74652813, "author": "Asifiwe Ebenezer", "author_id": 16121728, "author_profile": "https://Stackoverflow.com/users/16121728", "pm_score": 2, "selected": false, "text": "react-native-heroicons react-native-svg npx expo install react-native-svg" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20663257/" ]
74,651,918
<p>I'm trying to create a program with Javascript that prints two random numbers and calculates their sum. It should be really easy, but for some reason I can't get the program to work. I've got the program to print random numbers, but I can't get it to add the numbers together. What am I doing wrong?</p> <pre><code> &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset=&quot;utf-8&quot;&gt; &lt;/head&gt; &lt;body&gt; &lt;p id=&quot;myBtn&quot;&gt;&lt;/p&gt; &lt;p id=&quot;number1&quot;&gt;&lt;/p&gt; &lt;p id=&quot;number2&quot;&gt;&lt;/p&gt; &lt;button id=&quot;myBtn&quot; onclick=&quot;myFunction()&quot;&gt;Get random number&lt;/button&gt; &lt;script&gt; var allNumbers = 0; function myFunction() { num1 = document.getElementById(&quot;number1&quot;).innerHTML = Math.floor(Math.random() * (7 - 1) + 1); num2 = document.getElementById(&quot;number2&quot;).innerHTML = Math.floor(Math.random() * (7 - 1) + 1); var inTotal = num1 + num2; var allNumbers =+ inTotal; } document.write(allNumbers); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "answer_id": 74652582, "author": "JSONCMD", "author_id": 20629269, "author_profile": "https://Stackoverflow.com/users/20629269", "pm_score": 0, "selected": false, "text": "npm install react-native-svg-transformer --save \n" }, { "answer_id": 74652813, "author": "Asifiwe Ebenezer", "author_id": 16121728, "author_profile": "https://Stackoverflow.com/users/16121728", "pm_score": 2, "selected": false, "text": "react-native-heroicons react-native-svg npx expo install react-native-svg" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20663356/" ]
74,651,923
<p>the expected out put was</p> <pre><code>1 1 2 2 3 3 4 4 5 5 </code></pre> <p>but the output I got is</p> <pre><code>1 1 2 2 3 3 4 4 5 5 </code></pre> <pre><code>for num in numlist: print(num) print(num,end=' ') </code></pre> <p>I tried to execute this python code in python interpreter and got the wrong output</p>
[ { "answer_id": 74652047, "author": "Ita", "author_id": 20347147, "author_profile": "https://Stackoverflow.com/users/20347147", "pm_score": 1, "selected": false, "text": "print end print print end end 1st print NEWLINE\n2nd print SPACE 1st print NEWLINE\n2nd print SPACE 1st print NEWLINE\n...\n" }, { "answer_id": 74652600, "author": "Cobra", "author_id": 17580381, "author_profile": "https://Stackoverflow.com/users/17580381", "pm_score": 0, "selected": false, "text": "for num in numlist:\n print(num, num)\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20663471/" ]
74,651,930
<p>I have a table :</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>value</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>A</td> </tr> <tr> <td>1</td> <td>B</td> </tr> <tr> <td>1</td> <td>C</td> </tr> <tr> <td>2</td> <td>A</td> </tr> <tr> <td>2</td> <td>B</td> </tr> <tr> <td>3</td> <td>A</td> </tr> </tbody> </table> </div> <p>my goal is to have the table where I have only IDs that have A,B,C present per id,</p> <p>in this case it is:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> </tr> </thead> <tbody> <tr> <td>1</td> </tr> </tbody> </table> </div> <p>how to construct the SQL query for that ?</p>
[ { "answer_id": 74651983, "author": "ElapsedSoul", "author_id": 3053899, "author_profile": "https://Stackoverflow.com/users/3053899", "pm_score": 0, "selected": false, "text": "exists select id from ${table} a where value = 'A' \nand exists (select 1 from ${table} b where a.id = b.id and b.value = 'B')\nand exists (select 1 from ${table} c where a.id = c.id and b.value = 'C')\n id" }, { "answer_id": 74651988, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 2, "selected": true, "text": "SELECT id\nFROM yourTable\nWHERE value IN ('A', 'B', 'C')\nGROUP BY id\nHAVING COUNT(DISTINCT value) = 3;\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4416877/" ]
74,651,950
<p>I want to initialise and print a 2-D array in two separate functions, but i don't really know if i am doing this correctly.</p> <p>I wrote 2 functions: <code>int** matrix_initialization(int n, int m)</code> and <code>int print_matrix(int n1, int n2, int **a);</code></p> <p>In the first function i have to arguments: int n - the number of rows and int m - the number of cols. In this function i initialise a pointer to the pointer <code>int **matrix = NULL;</code> Then i allocate memory to it, and giving this 2-D array random values.</p> <p>Is that okay that the type of the <code>int** matrix_initialization(int n, int m)</code> function is <code>int **</code> ?</p> <p>The second function is <code>int print_matrix(int n1, int n2, int** a)</code> and there are some problems, the main is that it is not working. I have three arguments <code>int n1</code> - rows, <code>int n2</code> - cols, <code>int** a</code> a pointer to the pointer. This function is to print matrix.</p> <p>Here is my code:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;locale.h&gt; #include &lt;stdlib.h&gt; #include &lt;time.h&gt; int** matrix_initialization(int n, int m) { int** matrix = NULL; matrix = (int**)malloc(n * sizeof(n)); if (matrix != NULL) { if (matrix != NULL) { for (int i = 0; i &lt; m; i++) { *(matrix + i) = (int*)malloc(m * sizeof(m)); } for (int i = 0; i &lt; n; i++) { for (int j = 0; j &lt; m; j++) { matrix[i][j] = rand() % 20 - 5; } } } } return matrix; } int print_matrix(int n1, int n2, int** a) { for (int i = 0; i &lt; n1; i++) { for (int j = 0; j &lt; n2; j++) { printf(&quot;%d\t&quot;, a[i][j]); } printf(&quot;\n&quot;); } } int main() { srand(time(NULL)); int N, M, **a; scanf_s(&quot;%d %d&quot;, &amp;N, &amp;M); a = matrix_initialization(N, M); print_matrix(N, M, a); } </code></pre>
[ { "answer_id": 74652007, "author": "Some programmer dude", "author_id": 440558, "author_profile": "https://Stackoverflow.com/users/440558", "pm_score": 0, "selected": false, "text": "malloc(n * sizeof(n))\n malloc(n * sizeof(int))\n n int sizeof(int) == sizeof(int *) malloc(n * sizeof(int*))\n malloc(n * sizeof *matrix)\n int for (int i = 0; i < m; i++)\n n m n == m // Iterating over an array of n elements\nfor (int i = 0; i < n; i++)\n malloc m int malloc free *(matrix + i) matrix[i]" }, { "answer_id": 74652183, "author": "Lundin", "author_id": 584518, "author_profile": "https://Stackoverflow.com/users/584518", "pm_score": 1, "selected": false, "text": "matrix = (int**)malloc(n * sizeof(n)); n size_t int* int matrix = malloc(n * sizeof(*matrix)) for (int i = 0; i < m; i++) n matrix *(matrix + i) matrix[i] n m n1 n2 _s int main() int main (void) #include <stdio.h>\n#include <stdlib.h>\n#include <time.h> \n\nvoid* matrix_initialization (int n, int m)\n{\n int (*matrix)[m] = malloc( sizeof(int[n][m]) );\n if (matrix != NULL)\n {\n for (int i = 0; i < n; i++)\n {\n for (int j = 0; j < m; j++)\n {\n matrix[i][j] = rand() % 20 - 5;\n }\n }\n }\n return matrix;\n}\n\nvoid print_matrix (int n, int m, int a[n][m])\n{\n for (int i = 0; i < n; i++)\n {\n for (int j = 0; j < n; j++)\n {\n printf(\"%d\\t\", a[i][j]);\n }\n printf(\"\\n\");\n }\n}\n\nint main (void)\n{ \n srand(time(NULL)); \n int N, M;\n scanf(\"%d %d\", &N, &M);\n int (*a)[M];\n a = matrix_initialization(N, M);\n print_matrix(N, M, a);\n free(a);\n}\n" }, { "answer_id": 74654117, "author": "MFeng", "author_id": 20558711, "author_profile": "https://Stackoverflow.com/users/20558711", "pm_score": -1, "selected": false, "text": "#include <stdio.h>\n#include <locale.h>\n#include <stdlib.h>\n#include <time.h>\n\nint** matrix_initialization(int n, int m)\n{\n int** matrix = NULL;\n //matrix = (int**)malloc(n * sizeof(n));\n matrix = (int**)malloc(n * sizeof(int *));\n\n if (matrix != NULL)\n {\n for (int i = 0; i < n; i++)//here is n,not m\n {\n matrix[i] = (int*)malloc(m * sizeof(int));\n }\n\n for (int i = 0; i < n; i++)\n {\n for (int j = 0; j < m; j++)\n {\n matrix[i][j] = rand() % 20 - 5;\n }\n }\n }\n\n return matrix;\n}\n\nint print_matrix(int n1, int n2, int** a)\n{\n for (int i = 0; i < n1; i++)\n {\n for (int j = 0; j < n2; j++)\n {\n printf(\"%d\\t\", a[i][j]);\n }\n printf(\"\\n\");\n }\n return 0;\n}\n\nint main()\n{\n srand(time(NULL));\n int N, M, **a,i;\n scanf(\"%d %d\", &N, &M);\n a = matrix_initialization(N, M);\n print_matrix(N, M, a);\n //free all the memory\n for (i = 0; i<N; i++) {\n free(a[i]);\n }\n free(a);\n return 0;\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20276903/" ]
74,651,997
<p>I am trying to get a specific category products by category slug.I have Color model,Product model and product variation model in shop app.</p> <pre><code>class Colour(models.Model): title = models.CharField(max_length=100) color_code = models.CharField(max_length=50,null=True) </code></pre> <pre><code>class Product(models.Model): product_name = models.CharField(max_length=100,unique=True) slug = models.SlugField(max_length=100,unique=True) content = RichTextUploadingField() price = models.IntegerField() images = models.ImageField(upload_to='photos/products') is_available = models.BooleanField(default=True) category = models.ForeignKey(Category, on_delete=models.CASCADE,related_name=&quot;procat&quot;) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) is_featured = models.BooleanField() </code></pre> <pre><code>class ProductVaraiant(models.Model): product = models.ForeignKey(Product,on_delete=models.CASCADE) color = models.ForeignKey(Colour,on_delete=models.CASCADE,blank=True, null=True) size = models.ForeignKey(Size, on_delete=models.CASCADE,blank=True, null=True) brand = models.ForeignKey(Brand,on_delete=models.CASCADE,blank=True, null=True) amount_in_stock = models.IntegerField() class Meta: constraints = [ models.UniqueConstraint( fields=['product', 'color', 'size','brand'], name='unique_prod_color_size_combo' </code></pre> <pre><code></code></pre> <p>In my views.py,</p> <pre><code>def shop(request,category_slug=None): categories = None products = None if category_slug != None: categories = get_object_or_404(Category,slug = category_slug) products = Product.objects.filter(category=categories,is_available=True).order_by('id') variation = ProductVaraiant.objects.filter(product__category = categories) print(variation) # color = color.objects.all() products_count = products.count() else: products = Product.objects.all().filter(is_available=True).order_by('id') products_count = products.count() variation = ProductVaraiant.objects.all() print(variation) context = { 'products' : products, 'products_count' : products_count, 'variation' : variation } return render(request,'shop/shop.html',context) </code></pre> <p>my category model,</p> <pre><code>class Category(MPTTModel): parent = TreeForeignKey('self',blank=True,null=True,related_name='children',on_delete=models.CASCADE) category_name = models.CharField(max_length=200,unique=True) category_img = models.ImageField(upload_to='photos/categories',blank=True) slug = models.SlugField(max_length=100,unique=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def img_preview(self): return mark_safe('&lt;img src = &quot;{url}&quot; width = &quot;50&quot; height = &quot;50&quot;/&gt;'.format( url = self.category_img.url )) def __str__(self): return self.category_name class Meta: verbose_name_plural = 'categories' class MPTTMeta: order_insertion_by = ['category_name'] </code></pre> <p>what i am trying to get is like i have 3 child category..Each category will have product of any color.So,if i filter product by category,color will be shown in sidebar of that category products without avoid getting duplicates as many product may have same color.So,i am getting same color multiple times.If i need to use distinct(),how to use it in query that will remove duplicate color based on product category.I tried this in template</p> <pre><code> </code></pre> <pre><code> &lt;form&gt; &lt;div class=&quot;custom-control custom-checkbox d-flex align-items-center justify-content-between mb-3&quot;&gt; &lt;input type=&quot;checkbox&quot; class=&quot;custom-control-input&quot; checked id=&quot;color-all&quot;&gt; &lt;label class=&quot;custom-control-label&quot; for=&quot;price-all&quot;&gt;All Color&lt;/label&gt; &lt;span class=&quot;badge border font-weight-normal&quot;&gt;1000&lt;/span&gt; &lt;/div&gt; {% for i in variation %} {% ifchanged i.color %} &lt;div class=&quot;custom-control custom-checkbox d-flex align-items-center justify-content-between mb-3&quot;&gt; &lt;input type=&quot;checkbox&quot; class=&quot;custom-control-input filter-checkbox&quot; id=&quot;{{i.color.id}}&quot; data-filter=&quot;color&quot;&gt; &lt;label class=&quot;custom-control-label&quot; for=&quot;{{i.color.id}}&quot;&gt;{{i.color}}&lt;/label&gt; &lt;span class=&quot;badge border font-weight-normal&quot;&gt;150&lt;/span&gt; &lt;/div&gt; {% endifchanged %} {% endfor %} &lt;/form&gt; </code></pre> <pre><code> </code></pre> <p>But,it just remove duplicate of last iteration.How to avoid getting duplicates for all color?</p>
[ { "answer_id": 74652007, "author": "Some programmer dude", "author_id": 440558, "author_profile": "https://Stackoverflow.com/users/440558", "pm_score": 0, "selected": false, "text": "malloc(n * sizeof(n))\n malloc(n * sizeof(int))\n n int sizeof(int) == sizeof(int *) malloc(n * sizeof(int*))\n malloc(n * sizeof *matrix)\n int for (int i = 0; i < m; i++)\n n m n == m // Iterating over an array of n elements\nfor (int i = 0; i < n; i++)\n malloc m int malloc free *(matrix + i) matrix[i]" }, { "answer_id": 74652183, "author": "Lundin", "author_id": 584518, "author_profile": "https://Stackoverflow.com/users/584518", "pm_score": 1, "selected": false, "text": "matrix = (int**)malloc(n * sizeof(n)); n size_t int* int matrix = malloc(n * sizeof(*matrix)) for (int i = 0; i < m; i++) n matrix *(matrix + i) matrix[i] n m n1 n2 _s int main() int main (void) #include <stdio.h>\n#include <stdlib.h>\n#include <time.h> \n\nvoid* matrix_initialization (int n, int m)\n{\n int (*matrix)[m] = malloc( sizeof(int[n][m]) );\n if (matrix != NULL)\n {\n for (int i = 0; i < n; i++)\n {\n for (int j = 0; j < m; j++)\n {\n matrix[i][j] = rand() % 20 - 5;\n }\n }\n }\n return matrix;\n}\n\nvoid print_matrix (int n, int m, int a[n][m])\n{\n for (int i = 0; i < n; i++)\n {\n for (int j = 0; j < n; j++)\n {\n printf(\"%d\\t\", a[i][j]);\n }\n printf(\"\\n\");\n }\n}\n\nint main (void)\n{ \n srand(time(NULL)); \n int N, M;\n scanf(\"%d %d\", &N, &M);\n int (*a)[M];\n a = matrix_initialization(N, M);\n print_matrix(N, M, a);\n free(a);\n}\n" }, { "answer_id": 74654117, "author": "MFeng", "author_id": 20558711, "author_profile": "https://Stackoverflow.com/users/20558711", "pm_score": -1, "selected": false, "text": "#include <stdio.h>\n#include <locale.h>\n#include <stdlib.h>\n#include <time.h>\n\nint** matrix_initialization(int n, int m)\n{\n int** matrix = NULL;\n //matrix = (int**)malloc(n * sizeof(n));\n matrix = (int**)malloc(n * sizeof(int *));\n\n if (matrix != NULL)\n {\n for (int i = 0; i < n; i++)//here is n,not m\n {\n matrix[i] = (int*)malloc(m * sizeof(int));\n }\n\n for (int i = 0; i < n; i++)\n {\n for (int j = 0; j < m; j++)\n {\n matrix[i][j] = rand() % 20 - 5;\n }\n }\n }\n\n return matrix;\n}\n\nint print_matrix(int n1, int n2, int** a)\n{\n for (int i = 0; i < n1; i++)\n {\n for (int j = 0; j < n2; j++)\n {\n printf(\"%d\\t\", a[i][j]);\n }\n printf(\"\\n\");\n }\n return 0;\n}\n\nint main()\n{\n srand(time(NULL));\n int N, M, **a,i;\n scanf(\"%d %d\", &N, &M);\n a = matrix_initialization(N, M);\n print_matrix(N, M, a);\n //free all the memory\n for (i = 0; i<N; i++) {\n free(a[i]);\n }\n free(a);\n return 0;\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74651997", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20217121/" ]
74,652,010
<p>Getting the internal error when i try to import the maven project from my local machine. <img src="https://i.stack.imgur.com/KjamX.png" alt="Internal error" /></p> <p>Should import successfully.</p>
[ { "answer_id": 74652007, "author": "Some programmer dude", "author_id": 440558, "author_profile": "https://Stackoverflow.com/users/440558", "pm_score": 0, "selected": false, "text": "malloc(n * sizeof(n))\n malloc(n * sizeof(int))\n n int sizeof(int) == sizeof(int *) malloc(n * sizeof(int*))\n malloc(n * sizeof *matrix)\n int for (int i = 0; i < m; i++)\n n m n == m // Iterating over an array of n elements\nfor (int i = 0; i < n; i++)\n malloc m int malloc free *(matrix + i) matrix[i]" }, { "answer_id": 74652183, "author": "Lundin", "author_id": 584518, "author_profile": "https://Stackoverflow.com/users/584518", "pm_score": 1, "selected": false, "text": "matrix = (int**)malloc(n * sizeof(n)); n size_t int* int matrix = malloc(n * sizeof(*matrix)) for (int i = 0; i < m; i++) n matrix *(matrix + i) matrix[i] n m n1 n2 _s int main() int main (void) #include <stdio.h>\n#include <stdlib.h>\n#include <time.h> \n\nvoid* matrix_initialization (int n, int m)\n{\n int (*matrix)[m] = malloc( sizeof(int[n][m]) );\n if (matrix != NULL)\n {\n for (int i = 0; i < n; i++)\n {\n for (int j = 0; j < m; j++)\n {\n matrix[i][j] = rand() % 20 - 5;\n }\n }\n }\n return matrix;\n}\n\nvoid print_matrix (int n, int m, int a[n][m])\n{\n for (int i = 0; i < n; i++)\n {\n for (int j = 0; j < n; j++)\n {\n printf(\"%d\\t\", a[i][j]);\n }\n printf(\"\\n\");\n }\n}\n\nint main (void)\n{ \n srand(time(NULL)); \n int N, M;\n scanf(\"%d %d\", &N, &M);\n int (*a)[M];\n a = matrix_initialization(N, M);\n print_matrix(N, M, a);\n free(a);\n}\n" }, { "answer_id": 74654117, "author": "MFeng", "author_id": 20558711, "author_profile": "https://Stackoverflow.com/users/20558711", "pm_score": -1, "selected": false, "text": "#include <stdio.h>\n#include <locale.h>\n#include <stdlib.h>\n#include <time.h>\n\nint** matrix_initialization(int n, int m)\n{\n int** matrix = NULL;\n //matrix = (int**)malloc(n * sizeof(n));\n matrix = (int**)malloc(n * sizeof(int *));\n\n if (matrix != NULL)\n {\n for (int i = 0; i < n; i++)//here is n,not m\n {\n matrix[i] = (int*)malloc(m * sizeof(int));\n }\n\n for (int i = 0; i < n; i++)\n {\n for (int j = 0; j < m; j++)\n {\n matrix[i][j] = rand() % 20 - 5;\n }\n }\n }\n\n return matrix;\n}\n\nint print_matrix(int n1, int n2, int** a)\n{\n for (int i = 0; i < n1; i++)\n {\n for (int j = 0; j < n2; j++)\n {\n printf(\"%d\\t\", a[i][j]);\n }\n printf(\"\\n\");\n }\n return 0;\n}\n\nint main()\n{\n srand(time(NULL));\n int N, M, **a,i;\n scanf(\"%d %d\", &N, &M);\n a = matrix_initialization(N, M);\n print_matrix(N, M, a);\n //free all the memory\n for (i = 0; i<N; i++) {\n free(a[i]);\n }\n free(a);\n return 0;\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19616469/" ]
74,652,066
<p>So I am trying to make a regex match for strings of the form: <code>&quot;catalog.schema.'tablename'&quot;</code> .</p> <p>The output I am looking for is just <code>catalog.schema.'tablename'</code> leaving out the quotes at the end position.</p> <p>Can anyone help me out</p> <p>I tried to do it with the expression <code>/(?!^|.$)+[^\s]/</code> which leaves out the end quotes but matches each character.</p> <p>So I modified it to <code>/(?!^|.$)+[^\s]+/g</code> . This matches the whole sentence but doesn't ignore the end quote.</p>
[ { "answer_id": 74652007, "author": "Some programmer dude", "author_id": 440558, "author_profile": "https://Stackoverflow.com/users/440558", "pm_score": 0, "selected": false, "text": "malloc(n * sizeof(n))\n malloc(n * sizeof(int))\n n int sizeof(int) == sizeof(int *) malloc(n * sizeof(int*))\n malloc(n * sizeof *matrix)\n int for (int i = 0; i < m; i++)\n n m n == m // Iterating over an array of n elements\nfor (int i = 0; i < n; i++)\n malloc m int malloc free *(matrix + i) matrix[i]" }, { "answer_id": 74652183, "author": "Lundin", "author_id": 584518, "author_profile": "https://Stackoverflow.com/users/584518", "pm_score": 1, "selected": false, "text": "matrix = (int**)malloc(n * sizeof(n)); n size_t int* int matrix = malloc(n * sizeof(*matrix)) for (int i = 0; i < m; i++) n matrix *(matrix + i) matrix[i] n m n1 n2 _s int main() int main (void) #include <stdio.h>\n#include <stdlib.h>\n#include <time.h> \n\nvoid* matrix_initialization (int n, int m)\n{\n int (*matrix)[m] = malloc( sizeof(int[n][m]) );\n if (matrix != NULL)\n {\n for (int i = 0; i < n; i++)\n {\n for (int j = 0; j < m; j++)\n {\n matrix[i][j] = rand() % 20 - 5;\n }\n }\n }\n return matrix;\n}\n\nvoid print_matrix (int n, int m, int a[n][m])\n{\n for (int i = 0; i < n; i++)\n {\n for (int j = 0; j < n; j++)\n {\n printf(\"%d\\t\", a[i][j]);\n }\n printf(\"\\n\");\n }\n}\n\nint main (void)\n{ \n srand(time(NULL)); \n int N, M;\n scanf(\"%d %d\", &N, &M);\n int (*a)[M];\n a = matrix_initialization(N, M);\n print_matrix(N, M, a);\n free(a);\n}\n" }, { "answer_id": 74654117, "author": "MFeng", "author_id": 20558711, "author_profile": "https://Stackoverflow.com/users/20558711", "pm_score": -1, "selected": false, "text": "#include <stdio.h>\n#include <locale.h>\n#include <stdlib.h>\n#include <time.h>\n\nint** matrix_initialization(int n, int m)\n{\n int** matrix = NULL;\n //matrix = (int**)malloc(n * sizeof(n));\n matrix = (int**)malloc(n * sizeof(int *));\n\n if (matrix != NULL)\n {\n for (int i = 0; i < n; i++)//here is n,not m\n {\n matrix[i] = (int*)malloc(m * sizeof(int));\n }\n\n for (int i = 0; i < n; i++)\n {\n for (int j = 0; j < m; j++)\n {\n matrix[i][j] = rand() % 20 - 5;\n }\n }\n }\n\n return matrix;\n}\n\nint print_matrix(int n1, int n2, int** a)\n{\n for (int i = 0; i < n1; i++)\n {\n for (int j = 0; j < n2; j++)\n {\n printf(\"%d\\t\", a[i][j]);\n }\n printf(\"\\n\");\n }\n return 0;\n}\n\nint main()\n{\n srand(time(NULL));\n int N, M, **a,i;\n scanf(\"%d %d\", &N, &M);\n a = matrix_initialization(N, M);\n print_matrix(N, M, a);\n //free all the memory\n for (i = 0; i<N; i++) {\n free(a[i]);\n }\n free(a);\n return 0;\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18954455/" ]
74,652,095
<p>I've had a Typescript react project I've been working on for the past couple of months. Everything worked fine until yesterday when I run <code>npm audit fix</code> and <code>npm audit fix --force</code> to fix some security errors I honestly did not understand where or what caused them.</p> <p>That broke my application and after running <code>npm install</code> and <code>npm clean-install</code> I am getting this error</p> <pre><code>./src/Components/SearchForm.tsx 214:33 Module parse failed: Unexpected token (214:33) You may need an appropriate loader to handle this file type. | className: &quot;w-[25%] bg-gray-100 border py-2 px-4 rounded-lg cursor-pointer&quot;, | onClick: function onClick() { &gt; departureDateInput.current?.focus(); | }, | __self: _this, </code></pre> <p>After some research, I found an answer that I should remove the <code>?</code> in my Typescript projects. For example this line <code>departureDateInput.current?.focus();</code> should be <code>departureDateInput.current.focus();</code></p> <p>While this works my project is quite huge and I honestly don't want to find all of them and fix them manually.</p> <p>An answer on a similar question on stack overflow claimed i need to make some settings on <code>webpack</code>and or <code>babel</code>. I have never worked with babel or webpack explicitly on my own so i dont even know how to start on that.</p> <p>I dont know if this helps but here is my <code>tsconfig.json</code></p> <pre><code>{ &quot;compilerOptions&quot;: { &quot;target&quot;: &quot;es5&quot;, &quot;lib&quot;: [&quot;dom&quot;, &quot;dom.iterable&quot;, &quot;esnext&quot;], &quot;allowJs&quot;: true, &quot;skipLibCheck&quot;: true, &quot;esModuleInterop&quot;: true, &quot;allowSyntheticDefaultImports&quot;: true, &quot;strict&quot;: true, &quot;forceConsistentCasingInFileNames&quot;: true, &quot;noFallthroughCasesInSwitch&quot;: true, &quot;module&quot;: &quot;esnext&quot;, &quot;moduleResolution&quot;: &quot;node&quot;, &quot;resolveJsonModule&quot;: true, &quot;isolatedModules&quot;: true, &quot;noEmit&quot;: true, &quot;jsx&quot;: &quot;react-jsx&quot;, &quot;suppressImplicitAnyIndexErrors&quot;: true }, &quot;include&quot;: [&quot;src&quot;] } </code></pre> <p>Please help.</p>
[ { "answer_id": 74652268, "author": "Andrew Shearer", "author_id": 10688837, "author_profile": "https://Stackoverflow.com/users/10688837", "pm_score": 0, "selected": false, "text": "\"target\": \"es5\" tsconfig.json {\n \"compilerOptions\": {\n \"target\": \"es2020\",\n // ...\n },\n \"include\": [\"src\"]\n}\n" }, { "answer_id": 74653153, "author": "AmohPrince", "author_id": 16018684, "author_profile": "https://Stackoverflow.com/users/16018684", "pm_score": 2, "selected": true, "text": "npm install react-scripts@latest\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16018684/" ]
74,652,100
<p>So i am creating a javascript searchbar that uses a fetch command to fetch data from a server. This server is not my own and i just used it as a template. This script works fine.But what i want to do is replace the fetch api with my own</p> <p><a href="https://i.stack.imgur.com/ibMuL.png" rel="nofollow noreferrer">Demonstation of code</a></p> <pre><code>const userCardTemplate = document.querySelector(&quot;[data-user-template]&quot;) const categoriesSearch = document.querySelector(&quot;[data-user-cards-container]&quot;) const searchInput = document.querySelector(&quot;[data-search]&quot;) let users = [] searchInput.addEventListener(&quot;input&quot;, e =&gt; { const value = e.target.value.toLowerCase() users.forEach(user =&gt; { const isVisible = user.name.toLowerCase().includes(value) || user.email.toLowerCase().includes(value) user.element.classList.toggle(&quot;hide&quot;, !isVisible) }) }) fetch(&quot;https://jsonplaceholder.typicode.com/users&quot;) .then(res =&gt; res.json()) .then(data =&gt; { users = data.map(user =&gt; { const card = userCardTemplate.content.cloneNode(true).children[0] const header = card.querySelector(&quot;[data-header]&quot;) const body = card.querySelector(&quot;[data-body]&quot;) header.textContent = user.name body.textContent = user.email categoriesSearch.append(card) return { name: user.name, email: user.email, element: card} }) }) </code></pre> <p>I think ive made my own fetch api via github which follows.</p> <p><a href="https://gist.github.com/UllestReal/09ca3d968dda94535e8fc25b998a6ce5#file-gistfile1-txt" rel="nofollow noreferrer">https://gist.github.com/UllestReal/09ca3d968dda94535e8fc25b998a6ce5#file-gistfile1-txt</a></p> <p>But when i replace the first template api with my own, it wont fetch the code. Can someone tell me what im doing wrong?</p> <p>I just wrote everything in one go it was alot easier. Just look above for my entire problem</p>
[ { "answer_id": 74654108, "author": "Konrad", "author_id": 5089567, "author_profile": "https://Stackoverflow.com/users/5089567", "pm_score": 0, "selected": false, "text": "Raw const url = 'https://gist.githubusercontent.com/UllestReal/09ca3d968dda94535e8fc25b998a6ce5/raw/705e7b335cd24e382c15e851ea8888fbdc9cdae4/gistfile1.txt'\nfetch(url).then(res => res.json()).then(console.log)" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20663572/" ]
74,652,169
<p>Just starting to use R and am feeling a bit confused. Suppose I have three columns</p> <pre><code>data = data.frame(id=c(101, 102, 103),column1=c(2, 4, 9), column2=c(3, 4, 2), column3=c(5, 15, 7)) </code></pre> <p>How can I create a new column (e.g., colmean) that is the mean of the two columns closest in value? I thought about doing a bunch of ifelse statements, but that seemed unnecessarily messy.</p> <p>In this case, for instance, <code>colmean=c(2.5, 4, 8)</code>.</p>
[ { "answer_id": 74652463, "author": "Sotos", "author_id": 5635580, "author_profile": "https://Stackoverflow.com/users/5635580", "pm_score": 2, "selected": false, "text": "findClosest() findClosest <- function(x, n) {\n x <- sort(x)\n x[seq.int(which.min(diff(x, lag = n - 1L)), length.out = n)]\n }\n\n\ncolMeans(apply(data[-1], 1, function(i)findClosest(i, 2)))\n#[1] 2.5 4.0 8.0\n" }, { "answer_id": 74652476, "author": "Marc in the box", "author_id": 1199289, "author_profile": "https://Stackoverflow.com/users/1199289", "pm_score": 0, "selected": false, "text": "data = data.frame(id=c(101, 102, 103),column1=c(2, 4, 9), \n column2=c(3, 4, 2), column3=c(5, 15, 7))\n\n\ndata$colmean <- NaN # set up empty column for results\nfor(i in seq(nrow(data))){\n data.i <- data[i,-1] # get ith row\n d <- as.matrix(dist(c(data.i))) # get distances between values\n diag(d) <- NaN # replace diagonal of distance matrix with NaN\n hit <- which.min(d) # identify value of lowest distance\n pos <- c(row(d)[hit], col(d)[hit]) # get the position (i.e. the values that are closest)\n data$colmean[i] <- mean(unlist(data.i[pos])) # calculate mean\n}\n\ndata\n# id column1 column2 column3 colmean\n# 1 101 2 3 5 2.5\n# 2 102 4 4 15 4.0\n# 3 103 9 2 7 8.0\n" }, { "answer_id": 74652764, "author": "Limey", "author_id": 13434871, "author_profile": "https://Stackoverflow.com/users/13434871", "pm_score": 0, "selected": false, "text": "library(tidyverse)\n\ndata %>%\n # Add the means of smallest pairwise differences to the input data\n bind_cols(\n data %>% \n # Make the data tidy (and hence independent of the number of \"column\"s)\n pivot_longer(starts_with(\"column\")) %>% \n # For each id/row (replace with rowwise() if appropriate)\n group_by(id) %>% \n group_map(\n function(.x, .y) {\n # Form a tibble of all pairwise ciombinations of values\n as_tibble(t(combn(.x$value, 2))) %>% \n # Calculate pairwise differences\n mutate(difference = abs(V1 - V2)) %>% \n # Find the smallest pairwise difference\n arrange(difference) %>% \n head(1) %>% \n # Calculate the mean of this pair\n pivot_longer(starts_with(\"V\")) %>% \n summarise(colmean=mean(value))\n }\n ) %>% \n # Convert list of values to column\n bind_rows()\n )\n\n id column1 column2 column3 colmean\n1 101 2 3 5 2.5\n2 102 4 4 15 4.0\n3 103 9 2 7 8.0\n" }, { "answer_id": 74656648, "author": "jblood94", "author_id": 9463489, "author_profile": "https://Stackoverflow.com/users/9463489", "pm_score": 0, "selected": false, "text": "Rfast library(Rfast)\n\nfClosest <- function(m, n) {\n m <- colSort(t(m))\n matrix(\n m[\n sequence(\n rep(n, ncol(m)),\n seq(0, nrow(m)*(ncol(m) - 1), nrow(m)) + colMins(diff(m, lag = n - 1))\n )\n ],\n ncol(m), n, TRUE\n )\n}\n\nm <- matrix(sample(10, 24, 1), 4)\nm\n#> [,1] [,2] [,3] [,4] [,5] [,6]\n#> [1,] 4 2 6 2 5 3\n#> [2,] 3 4 7 3 4 7\n#> [3,] 4 2 7 6 10 2\n#> [4,] 8 1 10 8 2 9\nfClosest(m, 3L)\n#> [,1] [,2] [,3]\n#> [1,] 2 2 3\n#> [2,] 3 3 4\n#> [3,] 2 2 4\n#> [4,] 8 8 9\nrowMeans(fClosest(m, 3L))\n#> [1] 2.333333 3.333333 2.666667 8.333333\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8425343/" ]
74,652,171
<p>I have i project with speech-to-text in react native, and now the problem in with speech Vloume, how to make average value from this function?</p> <pre><code> const onSpeechVolumeChanged = (e) =&gt; { console.log(e); setPitch(e.value); }; </code></pre> <p>And the log in the console is:</p> <pre><code>{&quot;value&quot;: -2} LOG {&quot;value&quot;: -0.440000057220459} LOG {&quot;value&quot;: 0.7599999904632568} LOG {&quot;value&quot;: 1.3600001335144043} LOG {&quot;value&quot;: -0.440000057220459} LOG {&quot;value&quot;: -1.7599999904632568} LOG {&quot;value&quot;: -2} LOG {&quot;value&quot;: 0.2799999713897705} LOG {&quot;value&quot;: 1} LOG {&quot;value&quot;: 2.440000057220459} LOG {&quot;value&quot;: 2.8000001907348633} LOG {&quot;value&quot;: 5.920000076293945} </code></pre> <p>There is a codem with makes speech to text. And y take here a NaN</p> <pre><code> let [started, setStarted] = useState(false); let [results, setResults] = useState([]); const [voiceData, setVoiceData] = useState([]) } useEffect(() =&gt; { Voice.onSpeechError = onSpeechError; Voice.onSpeechResults = onSpeechResults; Voice.onSpeechVolumeChanged = onSpeechVolumeChanged; return () =&gt; { Voice.destroy().then(Voice.removeAllListeners); } }, []); const startSpeechToText = async () =&gt; { await Voice.start(&quot;ru&quot;); setStarted(true); }; const onSpeechVolumeChanged = (e) =&gt; { setVoiceData({...voiceData, volume: e.value}); }; const stopSpeechToText = async () =&gt; { await Voice.stop(); setStarted(false); }; const onSpeechResults = (result) =&gt; { var allValue = result.value var theBestOption = allValue[Object.keys(allValue).pop()] setResults(theBestOption) console.log(theBestOption) let sum = 0; let count = 0; for (let i = 0; i &lt; voiceData.length; i++) { sum += voiceData[i]; count++; } let average = sum / count; console.log(average) }; const onSpeechError = (error) =&gt; { console.log(error); }; </code></pre> <p>Here takes an NuN</p>
[ { "answer_id": 74652463, "author": "Sotos", "author_id": 5635580, "author_profile": "https://Stackoverflow.com/users/5635580", "pm_score": 2, "selected": false, "text": "findClosest() findClosest <- function(x, n) {\n x <- sort(x)\n x[seq.int(which.min(diff(x, lag = n - 1L)), length.out = n)]\n }\n\n\ncolMeans(apply(data[-1], 1, function(i)findClosest(i, 2)))\n#[1] 2.5 4.0 8.0\n" }, { "answer_id": 74652476, "author": "Marc in the box", "author_id": 1199289, "author_profile": "https://Stackoverflow.com/users/1199289", "pm_score": 0, "selected": false, "text": "data = data.frame(id=c(101, 102, 103),column1=c(2, 4, 9), \n column2=c(3, 4, 2), column3=c(5, 15, 7))\n\n\ndata$colmean <- NaN # set up empty column for results\nfor(i in seq(nrow(data))){\n data.i <- data[i,-1] # get ith row\n d <- as.matrix(dist(c(data.i))) # get distances between values\n diag(d) <- NaN # replace diagonal of distance matrix with NaN\n hit <- which.min(d) # identify value of lowest distance\n pos <- c(row(d)[hit], col(d)[hit]) # get the position (i.e. the values that are closest)\n data$colmean[i] <- mean(unlist(data.i[pos])) # calculate mean\n}\n\ndata\n# id column1 column2 column3 colmean\n# 1 101 2 3 5 2.5\n# 2 102 4 4 15 4.0\n# 3 103 9 2 7 8.0\n" }, { "answer_id": 74652764, "author": "Limey", "author_id": 13434871, "author_profile": "https://Stackoverflow.com/users/13434871", "pm_score": 0, "selected": false, "text": "library(tidyverse)\n\ndata %>%\n # Add the means of smallest pairwise differences to the input data\n bind_cols(\n data %>% \n # Make the data tidy (and hence independent of the number of \"column\"s)\n pivot_longer(starts_with(\"column\")) %>% \n # For each id/row (replace with rowwise() if appropriate)\n group_by(id) %>% \n group_map(\n function(.x, .y) {\n # Form a tibble of all pairwise ciombinations of values\n as_tibble(t(combn(.x$value, 2))) %>% \n # Calculate pairwise differences\n mutate(difference = abs(V1 - V2)) %>% \n # Find the smallest pairwise difference\n arrange(difference) %>% \n head(1) %>% \n # Calculate the mean of this pair\n pivot_longer(starts_with(\"V\")) %>% \n summarise(colmean=mean(value))\n }\n ) %>% \n # Convert list of values to column\n bind_rows()\n )\n\n id column1 column2 column3 colmean\n1 101 2 3 5 2.5\n2 102 4 4 15 4.0\n3 103 9 2 7 8.0\n" }, { "answer_id": 74656648, "author": "jblood94", "author_id": 9463489, "author_profile": "https://Stackoverflow.com/users/9463489", "pm_score": 0, "selected": false, "text": "Rfast library(Rfast)\n\nfClosest <- function(m, n) {\n m <- colSort(t(m))\n matrix(\n m[\n sequence(\n rep(n, ncol(m)),\n seq(0, nrow(m)*(ncol(m) - 1), nrow(m)) + colMins(diff(m, lag = n - 1))\n )\n ],\n ncol(m), n, TRUE\n )\n}\n\nm <- matrix(sample(10, 24, 1), 4)\nm\n#> [,1] [,2] [,3] [,4] [,5] [,6]\n#> [1,] 4 2 6 2 5 3\n#> [2,] 3 4 7 3 4 7\n#> [3,] 4 2 7 6 10 2\n#> [4,] 8 1 10 8 2 9\nfClosest(m, 3L)\n#> [,1] [,2] [,3]\n#> [1,] 2 2 3\n#> [2,] 3 3 4\n#> [3,] 2 2 4\n#> [4,] 8 8 9\nrowMeans(fClosest(m, 3L))\n#> [1] 2.333333 3.333333 2.666667 8.333333\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20589275/" ]
74,652,190
<p>I'm new to firebase and am trying to search the title of the product using <strong>queryStartingAtValue</strong>. in my firebase JSON and code below, I have a few levels to travel. it look like -&gt; /item/(section name: clothing,games etc)/autoID/(product name, price) I was able to receive the results using for-loops all the way down until finding the specific string but it doesn't look good. I was wondering if <strong>queryStartingAtValue</strong> can shorten the trips looping through a child within the child or at least how to properly use <strong>queryStartingAtValue</strong> much appreciated for help!! thanks</p> <p>SWIFT</p> <pre><code>Database.database().reference().child(&quot;item&quot;).queryStarting(atValue:&quot;Adidas&quot;).observeSingleEvent(of: .value) { (snapshot) in for snap in snapshot.children { if let snap = snap as? DataSnapshot { if let childItem = snap.value! as? [String: Any] { for key in childItem { if let item = key.value as? [String: Any] { if let title = item[&quot;Title&quot;] as? String { if title.contains(&quot;adidas&quot;) { print(&quot;found&quot;) } } } } } } } } </code></pre> <p>Firebase JSON</p> <pre><code>{ &quot;item&quot;: { &quot;Clothing&quot;: { &quot;-NFrGoNiI4zX-QBgEwkf&quot;: { &quot;Price&quot;: 345, &quot;Title&quot;: &quot;Adidas&quot;, &quot;availableQty&quot;: &quot;100&quot; } }, &quot;Games&quot;: { &quot;-NFrGdmdV4FOBI34EnOW&quot;: { &quot;Price&quot;: 199, &quot;Title&quot;: &quot;Overwatch Platinum Pack&quot;, &quot;availableQty&quot;: &quot;100&quot; }, &quot;-NGL4vk1GC80ojMgZNik&quot;: { &quot;Price&quot;: 66, &quot;Title&quot;: &quot;Overwatch 2&quot;, &quot;availableQty&quot;: &quot;100&quot; } } } } </code></pre>
[ { "answer_id": 74657877, "author": "Frank van Puffelen", "author_id": 209103, "author_profile": "https://Stackoverflow.com/users/209103", "pm_score": 1, "selected": false, "text": "startAt endAt startAfter endAfter equalTo Title Database.database().reference()\n .child(\"item\")\n .queryOrdered(byChild: \"Title\") // \n .queryStarting(atValue:\"Adidas\")\n .observeSingleEvent(of: .value) { (snapshot) in\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5929213/" ]
74,652,196
<p>i am at this error for some hours now, and i cant resolve it by myself.</p> <p>this is the code:</p> <pre><code> </code></pre> <p>$repeated_entry = Product_Market::where('produto_id', '=', $product-&gt;id) -&gt;where('market_id', '=', $market-&gt;id)-&gt;get();</p> <pre><code> $repeated_entry_update = Product_Market::where('produto_id', '=', $product-&gt;id) -&gt;where('market_id', '=', $market-&gt;id); if($repeated_entry-&gt;count()) { $repeated_entry_update-&gt;update(['amount_requested' =&gt; $repeated_entry-&gt;amount_requested + $request-&gt;product_amount, 'amount_left' =&gt; $repeated_entry-&gt;amount_requested + $request-&gt;product_amount, ]); } else { product_market::create(['produto_id' =&gt; $product['id'], 'market_id' =&gt; $market['id'], //saves the info ghatered to the product_market relationship 'amount_requested' =&gt; $request-&gt;product_amount, //table 'amount_left' =&gt; $request-&gt;product_amount, 'amount_sold' =&gt; '0' ]); } </code></pre> <pre><code> </code></pre> <p>the error says Property [amount_requested] does not exist on this collection instance. but it does exist</p> <p>if i put a &quot;DD($repeated_entry);&quot; before the first if, to see the collection i get this</p> <p><a href="https://i.stack.imgur.com/O63S7.png" rel="nofollow noreferrer">enter image description here</a></p> <p>i can see the &quot;amount_requested&quot; RIGHT THERE, it is indeed in the collection, it might be completly obvious, and i just need some sleep, but i thought of asking for some help, (and dont mind the quality of the code, i am a noobie trying to learn)</p> <p>ive tried other ways to get to the value in the collection, but it needs to stay a collection to work with the rest of the code, and i am expecting to sleep and maybe i undestand something in the morning that i cant see rn, sorry for the dumb question</p>
[ { "answer_id": 74657877, "author": "Frank van Puffelen", "author_id": 209103, "author_profile": "https://Stackoverflow.com/users/209103", "pm_score": 1, "selected": false, "text": "startAt endAt startAfter endAfter equalTo Title Database.database().reference()\n .child(\"item\")\n .queryOrdered(byChild: \"Title\") // \n .queryStarting(atValue:\"Adidas\")\n .observeSingleEvent(of: .value) { (snapshot) in\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20663667/" ]
74,652,205
<p>I'm trying to get google form as json. I get all questions and it's type. I want the validation of the form I want form validation tooo how to Include form validations Is it possible to get all validations from google form</p> <pre><code>fetch(` https://forms.googleapis.com/v1/forms/${id}`, { method: 'GET', headers: { 'Authorization': `Bearer ${token}` } }) </code></pre> <p>response look like this and I want validation info too</p> <pre><code> &quot;formId&quot;: &quot;....&quot;, &quot;info&quot;: { &quot;title&quot;: &quot;Event feedback&quot;, &quot;description&quot;: &quot;Thank you for participating in our event. We hope you had as much fun attending as we did organizing it.\n\nWe want to hear your feedback so we can keep improving our logistics and content. Please fill this quick survey and let us know your thoughts (your answers will be anonymous).&quot;, &quot;documentTitle&quot;: &quot;Event Feedback&quot; }, &quot;revisionId&quot;: &quot;00000004&quot;, &quot;responderUri&quot;: &quot;....&quot;, &quot;items&quot;: [ { &quot;itemId&quot;: &quot;....&quot;, &quot;title&quot;: &quot;How satisfied were you with the event?&quot;, &quot;questionItem&quot;: { &quot;question&quot;: { &quot;questionId&quot;: &quot;...&quot;, &quot;required&quot;: true, &quot;scaleQuestion&quot;: { &quot;low&quot;: 1, &quot;high&quot;: 5, &quot;lowLabel&quot;: &quot;Not very&quot;, &quot;highLabel&quot;: &quot;Very much&quot; } } } }, { &quot;itemId&quot;: &quot;....&quot;, &quot;title&quot;: &quot;How relevant and helpful do you think it was for your job?&quot;, &quot;questionItem&quot;: { &quot;question&quot;: { &quot;questionId&quot;: &quot;....&quot;, &quot;required&quot;: true, &quot;scaleQuestion&quot;: { &quot;low&quot;: 1, &quot;high&quot;: 5, &quot;lowLabel&quot;: &quot;Not very&quot;, &quot;highLabel&quot;: &quot;Very much&quot; } } } }, { &quot;itemId&quot;: &quot;....&quot;, &quot;questionGroupItem&quot;: { &quot;questions&quot;: [ { &quot;questionId&quot;: &quot;....&quot;, &quot;required&quot;: true, &quot;rowQuestion&quot;: { &quot;title&quot;: &quot;Accommodation&quot; } },] } } ] } ``` </code></pre> <p>I need form validation in response data</p>
[ { "answer_id": 74652283, "author": "Muhammad Salman", "author_id": 15715337, "author_profile": "https://Stackoverflow.com/users/15715337", "pm_score": 1, "selected": false, "text": "GET https://forms.googleapis.com/v1/forms/${id}/questions/${questionId}\nAuthorization: Bearer ${token}\n" }, { "answer_id": 74657905, "author": "Muhammad Salman", "author_id": 15715337, "author_profile": "https://Stackoverflow.com/users/15715337", "pm_score": 0, "selected": false, "text": "const forms = google.forms({version: 'v1', auth});\nconst response = await forms.forms.get({\n formId: FORM_ID\n});\n\nconsole.log(response.data.items);\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20663757/" ]
74,652,211
<pre><code>package webdriverbasic; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class Webdriverbasicclass { public static void main(String[] args) { System.setProperty(&quot;webdriver.chrome.driver&quot;,&quot;C:\\Users\\Sammy\\Downloads\\chromedriver_win32\\chromedriver.exe&quot;); WebDriver driver=new ChromeDriver(); } } </code></pre> <pre><code>Exception in thread &quot;main&quot; java.lang.NoClassDefFoundError: org/openqa/selenium/chrome/ChromeDriver at webdriver/webdriverbasic.Webdriverbasicclass.main(Webdriverbasicclass.java:10) Caused by: java.lang.ClassNotFoundException: org.openqa.selenium.chrome.ChromeDriver at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641) at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188) at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521) ... 1 more </code></pre> <p><a href="https://i.stack.imgur.com/DrMGD.png" rel="nofollow noreferrer">exception in thread main java lang noclassdeffounderror</a></p> <p>its my first program in eclipse with selenium and i got this error and not able to invoke the browser</p>
[ { "answer_id": 74652283, "author": "Muhammad Salman", "author_id": 15715337, "author_profile": "https://Stackoverflow.com/users/15715337", "pm_score": 1, "selected": false, "text": "GET https://forms.googleapis.com/v1/forms/${id}/questions/${questionId}\nAuthorization: Bearer ${token}\n" }, { "answer_id": 74657905, "author": "Muhammad Salman", "author_id": 15715337, "author_profile": "https://Stackoverflow.com/users/15715337", "pm_score": 0, "selected": false, "text": "const forms = google.forms({version: 'v1', auth});\nconst response = await forms.forms.get({\n formId: FORM_ID\n});\n\nconsole.log(response.data.items);\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20663571/" ]
74,652,242
<p>I've defined a template function that receives std::function. and I want to send a member function. that works fine (example: test2) How can I rewrite it so std::function receives any number of argument? (test3)</p> <p>another question - can this be done without the std::bind?</p> <pre><code>struct Cls { int foo() { return 11; } }; template&lt;typename T&gt; void test2(std::function&lt;T()&gt; func) {} template&lt;typename T, typename... Args&gt; void test3(std::function&lt;T(Args... args)&gt; func, Args&amp;&amp;... args) {} int main() { Cls ccc; test2&lt;int&gt;(std::bind(&amp;Cls::foo, ccc)); // Ok test3&lt;int&gt;(std::bind(&amp;Cls::foo, ccc)); // does not compile! } </code></pre> <p>This is the error I receive:</p> <pre><code>no matching function for call to ‘test3&lt;int&gt;(std::_Bind_helper&lt;false, int (Cls::*)(), Cls&amp;&gt;::type)’ 34 | test3&lt;int&gt;(std::bind(&amp;Cls::foo, ccc)); </code></pre>
[ { "answer_id": 74652495, "author": "Miles Budnek", "author_id": 4151599, "author_profile": "https://Stackoverflow.com/users/4151599", "pm_score": 4, "selected": true, "text": "std::bind std::function test3 std::function template <typename Func, typename... Args>\nvoid test3(Func&& func, Args&&... args)\n{}\n std::bind std::function std::bind std::invoke std::invoke struct Cls\n{\n int foo() { return 11; }\n};\n\ntemplate <typename Func, typename... Args>\nvoid test3(Func&& func, Args&&... args)\n{\n std::invoke(std::forward<Func>(func), std::forward<Args>(args)...);\n}\n\nvoid bar(double, int) {}\n\nint main()\n{\n Cls ccc;\n\n test3(bar, 3.14, 42); // Works with a raw function pointer\n test3(&Cls::foo, ccc); // Works with a pointer to member function\n test3([](int){}, 42); // Works with other callable types, like a lambda\n}\n" }, { "answer_id": 74652538, "author": "Jason Liam", "author_id": 12002570, "author_profile": "https://Stackoverflow.com/users/12002570", "pm_score": 0, "selected": false, "text": "std::bind struct Cls\n{\n int foo() { return 11; }\n\n int func(int, double)\n {\n return 4;\n }\n};\n\n\ntemplate<typename className, typename... Param,typename Ret, typename... Args> \nvoid test4(Ret (className::*ptrFunc)(Param... param),className& Object, Args... args)\n{\n (Object.*ptrFunc)(args...);\n\n //std::invoke(ptrFunc, Object, args...); //WITH C++17\n\n}\nint main()\n{\n Cls ccc;\n\n \n test4(&Cls::foo, ccc); //works \n test4(&Cls::func, ccc, 4,5); //works \n}\n std::invoke (Object.*ptrFunc)(args...); std::invoke(ptrFunc, Object, args...); //WITH C++17\n std::invoke" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/595599/" ]
74,652,258
<p>I am trying to press a the download on this page</p> <p><a href="https://data.unwomen.org/data-portal/sdg?annex=All&amp;finic%5B%5D=SUP_1_1_IPL_P&amp;flocat%5B%5D=478&amp;flocat%5B%5D=174&amp;flocat%5B%5D=818&amp;flocat%5B%5D=504&amp;flocat%5B%5D=729&amp;flocat%5B%5D=788&amp;flocat%5B%5D=368&amp;flocat%5B%5D=400&amp;flocat%5B%5D=275&amp;flocat%5B%5D=760&amp;fys%5B%5D=2015&amp;fyr%5B%5D=2030&amp;fca%5BALLAGE%5D=ALLAGE&amp;fca%5B" rel="nofollow noreferrer">https://data.unwomen.org/data-portal/sdg?annex=All&amp;finic[]=SUP_1_1_IPL_P&amp;flocat[]=478&amp;flocat[]=174&amp;flocat[]=818&amp;flocat[]=504&amp;flocat[]=729&amp;flocat[]=788&amp;flocat[]=368&amp;flocat[]=400&amp;flocat[]=275&amp;flocat[]=760&amp;fys[]=2015&amp;fyr[]=2030&amp;fca[ALLAGE]=ALLAGE&amp;fca[</a>&lt;15Y]=&lt;15Y&amp;fca[15%2B]=15%2B&amp;fca[15-24]=15-24&amp;fca[25-34]=25-34&amp;fca[35-54]=35-54&amp;fca[55%2B]=55%2B&amp;tab=table</p> <p>i am using python selenium with firefox and this is what i tried:</p> <pre><code>driver.set_page_load_timeout(30) driver.get(url) time.sleep(1) WebDriverWait(driver, timeout=20).until(EC.presence_of_element_located((By.ID, 'SDG-Indicator-Dashboard'))) time.sleep(1) download_div = driver.find_element(By.CLASS_NAME, 'float-buttons-wrap') buttons = download_div.find_elements(By.TAG_NAME, 'button') buttons_attributes = [i.get_attribute('title') for i in buttons] download_button_index = buttons_attributes.index('Download') buttons[download_button_index].location_once_scrolled_into_view buttons[download_button_index].click()``` i keep getting the same error: ElementNotInteractableException: Message: Element &lt;button class=&quot;btn btn-outline-light btn-icons&quot; type=&quot;button&quot;&gt; could not be scrolled into view eventho i am getting the correct element and i tried using js like this: ```driver.execute_script(&quot;return arguments[0].scrollIntoView(true);&quot;, element)``` also did not work. </code></pre>
[ { "answer_id": 74652419, "author": "AbiSaran", "author_id": 7671727, "author_profile": "https://Stackoverflow.com/users/7671727", "pm_score": 2, "selected": false, "text": "driver.get(\"https://data.unwomen.org/data-portal/sdg?annex=All&finic[]=SUP_1_1_IPL_P&flocat[]=478&flocat[]=174&flocat[]=818&flocat[]=504&flocat[]=729&flocat[]=788&flocat[]=368&flocat[]=400&flocat[]=275&flocat[]=760&fys[]=2015&fyr[]=2030&fca[ALLAGE]=ALLAGE&fca[<15Y]=<15Y&fca[15%2B]=15%2B&fca[15-24]=15-24&fca[25-34]=25-34&fca[35-54]=35-54&fca[55%2B]=55%2B&tab=table\")\ndriver.implicitly_wait(15)\ntime.sleep(2)\ndownload_btn = driver.find_element(By.XPATH, \"(.//button[@type='button' and @title='Download'])[2]\")\ndownload_btn.location_once_scrolled_into_view\ntime.sleep(1)\ndownload_btn.click()\n" }, { "answer_id": 74652501, "author": "Meelad Ghazipour", "author_id": 16762372, "author_profile": "https://Stackoverflow.com/users/16762372", "pm_score": 0, "selected": false, "text": "try/catch xpath xpath" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16727862/" ]
74,652,269
<p>I have the multiple sheets in a single workbook.</p> <p>The first sheet is having summary details:</p> <p><a href="https://i.stack.imgur.com/6WQ6f.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6WQ6f.png" alt="enter image description here" /></a></p> <p>Other sheets are like details as show below:</p> <p><a href="https://i.stack.imgur.com/VexPs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VexPs.png" alt="enter image description here" /></a></p> <p>I want to get total count <code>name</code> occurred in all the sheets in workbook.</p> <p>Expected output should be:</p> <p><a href="https://i.stack.imgur.com/TRp7t.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TRp7t.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74652360, "author": "Jos Woolley", "author_id": 17007704, "author_profile": "https://Stackoverflow.com/users/17007704", "pm_score": 2, "selected": false, "text": "=SUMPRODUCT(COUNTIF(INDIRECT(\"'\"&SheetList&\"'!A:A\"),B2)) column A B2 B3 B4" }, { "answer_id": 74652650, "author": "JvdV", "author_id": 9758194, "author_profile": "https://Stackoverflow.com/users/9758194", "pm_score": 3, "selected": true, "text": "=SUM(--(TOCOL(Sheet2:Sheet3!A:A,1)=B2))\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4268241/" ]
74,652,275
<p>A bit lowly a query but here goes: bash shell script. POSIX, Mint 21</p> <p>I just want one/any (mp3) file from a directory. As a sample. In normal execution, a full run, the code would be such</p> <pre><code>for f in *.mp3 do #statements done </code></pre> <p>This works fine but if I wanted to sample just one file of such an array/glob (?) without looping, how might I do that? I don't care which file, just that it is an mp3 from the directory I am working in. Should I just start this for-loop and then exit(break) after one statement, or is there a neater way more tailored-for-the-job way?</p> <pre><code>for f in *.mp3 do #statement break done </code></pre> <p>Ta (can not believe how dopey I feel asking this one, my forehead will hurt when I see the answers )</p>
[ { "answer_id": 74653883, "author": "Ljm Dullaart", "author_id": 6908895, "author_profile": "https://Stackoverflow.com/users/6908895", "pm_score": -1, "selected": false, "text": "for f in *.mp3 do\n f=$(ls *.mp3|head)\nstatement\n f=$(ls *.mp3|sort -R | tail -1)\n" }, { "answer_id": 74655209, "author": "M. Nejat Aydin", "author_id": 13809001, "author_profile": "https://Stackoverflow.com/users/13809001", "pm_score": 1, "selected": false, "text": "mp3file=\nfor f in *.mp3; do\n if [ -f \"$f\" ]; then\n mp3file=$f\n break\n fi\ndone\n# At this point, the variable mp3file contains a filename which\n# represents a regular file (or a symbolic link) with the .mp3\n# extension, or empty string if there is no such a file.\n" }, { "answer_id": 74657799, "author": "petrus4", "author_id": 2953345, "author_profile": "https://Stackoverflow.com/users/2953345", "pm_score": -1, "selected": false, "text": "ls *.mp3 | tr ' ' '\\n' | sed -n '1p'\n" }, { "answer_id": 74661873, "author": "pjh", "author_id": 4154375, "author_profile": "https://Stackoverflow.com/users/4154375", "pm_score": 2, "selected": true, "text": "find .mp3 mp3file=$(find . -maxdepth 1 -mindepth 1 -name '*.mp3' -printf '%f' -quit)\n -maxdepth 1 -mindepth 1 -printf '%f' foo.mp3 -print ./foo.mp3 -quit find : *.mp3\nmp3file=$_\n : *.mp3 : .mp3 : mp3file=$_ mp3file : .mp3 $mp3file [[ -e $mp3file ]] .mp3" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1065168/" ]
74,652,332
<p>I have a list of fasta may be used, but some of them may also not be used, so I hope to use snakemake to index fastq if need</p> <p>I bulit a yaml file like this</p> <pre><code># config.yaml reference_genome: fa1: &quot;path/to/genome&quot; fa2: &quot;...&quot; fa3: &quot;...&quot; ... </code></pre> <p>and I write a snakemake like this</p> <pre><code>configfile: &quot;config.yaml&quot; rule all: input: expand('{reference_genome}.{type}', reference_genome=['fa1', 'fa2', 'fa3'], type=['amb', 'ann', 'pac']) rule index: input: #reference_genomeFile ref_genome=lambda wildcards:config['reference_genome'][wildcards.reference_genome] output: expand('{reference_genome}.{type}', reference_genome={reference_genome}, type=['amb', 'ann', 'pac']) log: 'log/rule_index_{reference_genome}.log' shell: &quot;bwa index -a bwtsw {input.ref_genome} &gt; {log} 2&gt;&amp;1&quot; </code></pre> <p>I hope snakemake can monitor the index file <code>(amb, ann, pac)</code>, but this script will raise follow error:</p> <pre><code>name 'reference_genome' is not defined File &quot;/public/...&quot;, line ..., in &lt;module&gt; </code></pre> <p>update: base on @dariober's answer: if we runing with following config.yaml</p> <pre><code>reference_genome: fa1: &quot;genome_1.fa&quot; fa2: &quot;genome_2.fa&quot; fa3: &quot;genome_3.fa&quot; </code></pre> <p>I expect the output is</p> <pre><code>genome_1.fa.{amb, ann, pac} genome_2.fa.{amb, ann, pac} genome_3.fa.{amb, ann, pac} </code></pre> <p>If we use following workaround</p> <pre><code>rule all: input: expand('{reference_genome}.{type}', reference_genome=['fa1', 'fa2', 'fa3'], type=['amb', 'ann', 'pac']) rule index: input: #reference_genomeFile ref_genome=lambda wildcards:config['reference_genome'][wildcards.reference_genome] output: expand('{{reference_genome}}.{type}', type=['amb', 'ann', 'pac']) log: 'log/rule_index_{reference_genome}.log' shell: &quot;bwa index -a bwtsw {input.ref_genome} &gt; {log} 2&gt;&amp;1&quot; </code></pre> <p>we will get</p> <pre><code>$ snakemake -s snakemake_test.smk --configfile config.yaml </code></pre> <pre><code># for reference_name is fa1 [Fri Dec 2 17:56:29 2022] rule index: input: genome_1.fa output: fa1.amb, fa1.ann, fa1.pac log: log/rule_index_fa1.log jobid: 1 wildcards: reference_genome=fa1 ... </code></pre> <p>Thats not my expected output</p> <p>the output is fa1.amb, fa1.ann, fa1.pac, but I wanted output is genome_1.fa.amb, genome_1.fa.ann, genome_1.fa.pac</p>
[ { "answer_id": 74653883, "author": "Ljm Dullaart", "author_id": 6908895, "author_profile": "https://Stackoverflow.com/users/6908895", "pm_score": -1, "selected": false, "text": "for f in *.mp3 do\n f=$(ls *.mp3|head)\nstatement\n f=$(ls *.mp3|sort -R | tail -1)\n" }, { "answer_id": 74655209, "author": "M. Nejat Aydin", "author_id": 13809001, "author_profile": "https://Stackoverflow.com/users/13809001", "pm_score": 1, "selected": false, "text": "mp3file=\nfor f in *.mp3; do\n if [ -f \"$f\" ]; then\n mp3file=$f\n break\n fi\ndone\n# At this point, the variable mp3file contains a filename which\n# represents a regular file (or a symbolic link) with the .mp3\n# extension, or empty string if there is no such a file.\n" }, { "answer_id": 74657799, "author": "petrus4", "author_id": 2953345, "author_profile": "https://Stackoverflow.com/users/2953345", "pm_score": -1, "selected": false, "text": "ls *.mp3 | tr ' ' '\\n' | sed -n '1p'\n" }, { "answer_id": 74661873, "author": "pjh", "author_id": 4154375, "author_profile": "https://Stackoverflow.com/users/4154375", "pm_score": 2, "selected": true, "text": "find .mp3 mp3file=$(find . -maxdepth 1 -mindepth 1 -name '*.mp3' -printf '%f' -quit)\n -maxdepth 1 -mindepth 1 -printf '%f' foo.mp3 -print ./foo.mp3 -quit find : *.mp3\nmp3file=$_\n : *.mp3 : .mp3 : mp3file=$_ mp3file : .mp3 $mp3file [[ -e $mp3file ]] .mp3" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20240835/" ]
74,652,336
<p>I have a JavaScript list of objects with rows of varying dynamic fields that I wish to simply. For an input list:</p> <pre><code>{ A: a1, B: &quot;b1&quot; }, { A: a2, B: &quot;b2&quot; }, { C: c1, D: &quot;d1&quot; }, { C: c2, D: &quot;d2&quot; } </code></pre> <p>I wish the output list to be:</p> <pre><code>{ A: a1, B: &quot;b1&quot;, C: c1, D: &quot;d1&quot;}, { A: a2, B: &quot;b2&quot;, C: c2, D: &quot;d2&quot;} </code></pre> <p>where A,B, C &amp; D are dynamic fields at runtime</p> <p>I've explored using .reduce &amp; .map but could use some assistance.</p>
[ { "answer_id": 74652413, "author": "Andrew Shearer", "author_id": 10688837, "author_profile": "https://Stackoverflow.com/users/10688837", "pm_score": 0, "selected": false, "text": ".map() .reduce() for of function convertArray(arr) {\n const result = [];\n let currentObject = {};\n\n for (const elem of arr) {\n for (const key in elem) {\n currentObject[key] = elem[key];\n }\n\n result.push(currentObject);\n }\n\n return result;\n}\n\nconst arr = [\n { A: \"a1\", B: \"b1\" },\n { A: \"a2\", B: \"b2\" },\n { C: \"c1\", D: \"d1\" },\n { C: \"c2\", D: \"d2\" },\n];\n\nconst result = convertArray(arr);\n\nconsole.log(result);" }, { "answer_id": 74652844, "author": "Amirhossein", "author_id": 11342834, "author_profile": "https://Stackoverflow.com/users/11342834", "pm_score": 1, "selected": false, "text": "const data = [\n { A: \"a1\", B: \"b1\" },\n { A: \"a2\", B: \"b2\" },\n { C: \"c1\", D: \"d1\" },\n { C: \"c2\", D: \"d2\" }\n];\n\nconst resultObject = {};\ndata.forEach((item) => {\n Object.keys(item).forEach((key) => {\n const value = item[key];\n const numberValue = value.slice(1);\n resultObject[numberValue] = {...resultObject[numberValue], [key]: value};\n });\n});\n\nconst resultArray = Object.values(resultObject).map((value) => value);\nconsole.log(resultArray);" }, { "answer_id": 74652923, "author": "mplungjan", "author_id": 295783, "author_profile": "https://Stackoverflow.com/users/295783", "pm_score": 1, "selected": true, "text": "const groups = data.reduce((acc, cur, i) => {\n const curKeys = Object.keys(cur);\n if (i === 0) { // first time. This can be shortened but makes it harder to read\n curKeys.forEach(key => acc.keys[key] = 0);\n acc.result.push(cur);\n return acc;\n }\n Object.entries(cur).forEach((entry) => { // loop each entry\n const [key, val] = entry;\n let idx = acc.keys[key];\n if ((idx ?? undefined) === undefined) { // do we have a key stored?\n acc.keys[key] = 0;\n idx = 0;\n } else {\n acc.keys[key] = ++idx; // increase the index of the found letter\n if (idx > acc.result.length) acc.result.push({});\n }\n acc.result[idx] = { ...acc.result[idx], ...({ [key]: val }) };\n })\n return acc;\n\n}, { keys: {}, result: [] })[\"result\"];\n\nconsole.log(groups) <script>\n const data = [{\n A: \"a1\",\n B: \"b1\"\n },\n {\n A: \"a2\",\n B: \"b2\"\n },\n {\n C: \"c1\",\n D: \"d1\"\n },\n {\n C: \"c2\",\n D: \"d2\"\n },\n {\n C: \"c3\",\n D: \"d3\"\n }\n ];\n</script>" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20663709/" ]
74,652,346
<p>I have two tables I need to join these table and there is a possibility that joined table might return duplicate rows but there is column updated date which will be unique so I need to fetch record from these tables and get distinct records from second table</p> <p>Table-1</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th><strong>Id</strong></th> <th><strong>AccountKey</strong></th> </tr> </thead> <tbody> <tr> <td>1</td> <td>12</td> </tr> <tr> <td>2</td> <td>13</td> </tr> </tbody> </table> </div> <p>Table-2</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th><strong>Rolekey</strong></th> <th><strong>Account Key</strong></th> <th>**Date **</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>12</td> <td>2-12-2022</td> </tr> <tr> <td>2</td> <td>12</td> <td>1-12-2022</td> </tr> <tr> <td>3</td> <td>13</td> <td>1-12-2022</td> </tr> </tbody> </table> </div> <p>In the above table I except the result as below Expections:-</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Id</th> <th>AccountKey</th> <th>Date</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>12</td> <td>2-12-2022</td> </tr> <tr> <td>2</td> <td>13</td> <td>1-12-2022</td> </tr> </tbody> </table> </div> <p>But I am getting all the rows means 3, below is what I tried</p> <pre><code>select table1.id,table1.accountkey,table2.date from table1 table1 JOIN table2 table2 ON table1.accountkey=table2.accountkey </code></pre>
[ { "answer_id": 74652470, "author": "learning", "author_id": 12458846, "author_profile": "https://Stackoverflow.com/users/12458846", "pm_score": 3, "selected": true, "text": "SELECT a.id, a.accountKey, MAX(b.cdate)\nFROM table1 a\nJOIN table2 b ON a.accountKey = b.accountKey\nGROUP BY a.id, a.accountKey\n" }, { "answer_id": 74652521, "author": "PeterClemmensen", "author_id": 4044936, "author_profile": "https://Stackoverflow.com/users/4044936", "pm_score": 0, "selected": false, "text": "drop table if exists one;\ndrop table if exists two;\n\ncreate table one\n(\n ID [Int]\n, AccountKey [Int]\n)\n;\n\ninsert into one\nvalues (1, 12)\n , (2, 13)\n;\n\ncreate table two\n(\n Rolekey [Int]\n, AccountKey [Int]\n, Date [Date]\n)\n;\n\ninsert into two\nvalues (1, 12, '2022-12-02')\n , (2, 12, '2022-12-01')\n , (3, 13, '2022-12-01')\n;\n\nselect one.id\n , one.AccountKey\n , max(Date) as Date\nfrom one, two\nwhere one.AccountKey = two.AccountKey\ngroup by one.id\n , one.AccountKey\n;\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16406283/" ]
74,652,349
<p>I am new in flutter, how to set width and height OutlineButton in Flutter, i have to try input width and height inside OutlineButton but got some errors. this is my code :</p> <pre><code>OutlinedButton( //width: AppSize.DIMEN_230, style: OutlinedButton.styleFrom( side: BorderSide( width: 2.0, color: Colors.black12, ), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ),), onPressed: () { showDatePicker( context: context, initialDate: DateTime.now(), firstDate: DateTime(1880), lastDate: DateTime(2050), ); }, child: Text(&quot;YYYY/MM/DD HH:MM:SS&quot;, style: textStyleW400S16.copyWith( fontStyle: FontStyle.italic, color: Colors.black54, ), ), ), </code></pre> <p>Is it correct? Is there another way to do it?</p>
[ { "answer_id": 74652470, "author": "learning", "author_id": 12458846, "author_profile": "https://Stackoverflow.com/users/12458846", "pm_score": 3, "selected": true, "text": "SELECT a.id, a.accountKey, MAX(b.cdate)\nFROM table1 a\nJOIN table2 b ON a.accountKey = b.accountKey\nGROUP BY a.id, a.accountKey\n" }, { "answer_id": 74652521, "author": "PeterClemmensen", "author_id": 4044936, "author_profile": "https://Stackoverflow.com/users/4044936", "pm_score": 0, "selected": false, "text": "drop table if exists one;\ndrop table if exists two;\n\ncreate table one\n(\n ID [Int]\n, AccountKey [Int]\n)\n;\n\ninsert into one\nvalues (1, 12)\n , (2, 13)\n;\n\ncreate table two\n(\n Rolekey [Int]\n, AccountKey [Int]\n, Date [Date]\n)\n;\n\ninsert into two\nvalues (1, 12, '2022-12-02')\n , (2, 12, '2022-12-01')\n , (3, 13, '2022-12-01')\n;\n\nselect one.id\n , one.AccountKey\n , max(Date) as Date\nfrom one, two\nwhere one.AccountKey = two.AccountKey\ngroup by one.id\n , one.AccountKey\n;\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20388273/" ]
74,652,361
<pre><code>function sendMail() { var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheetByName(&quot;Pending Tasks&quot;); var lr = sheet.getLastRow(); var range = sheet.getRange(2,1,lr-1,10).getValues(); for(var i = 0; i&lt;range.filter(String).length; i++){ for(var j = 0; j&lt;range[i].filter(String).length; j++){ var timestamp = range[i][0]; Logger.log(range[i],[j]); } } } </code></pre> <p>In the below code it prints the same row 10 times because I have selected 10 columns in range, if I select 2 columns it prints 2 rows at a time.</p>
[ { "answer_id": 74652661, "author": "doubleunary", "author_id": 13045193, "author_profile": "https://Stackoverflow.com/users/13045193", "pm_score": 1, "selected": false, "text": "for condition Logger.log(range[i],[j]); forEach() function sendMail() {\n const ss = SpreadsheetApp.getActive();\n const values = ss.getRange('Pending Tasks!A2:J').getValues();\n values.forEach((row, rowIndex) => {\n const timestamp = row[0];\n row.forEach((value, columnIndex) => {\n if (value !== '') {\n console.log({ 'timestamp': timestamp, 'value': value, 'row': rowIndex + 1, 'column': columnIndex + 1 });\n }\n });\n });\n}\n" }, { "answer_id": 74653790, "author": "Deepak Raj", "author_id": 9425257, "author_profile": "https://Stackoverflow.com/users/9425257", "pm_score": 0, "selected": false, "text": "function sendMail() {\n\n var ss = SpreadsheetApp.getActiveSpreadsheet();\n var sheet = ss.getSheetByName(\"Pending Tasks\");\n var lr = sheet.getLastRow();\n var range = sheet.getRange(2,1,lr-1,10).getValues();\n var range2 = sheet.getRange(2,1,lr-1,1).getValues();\n for(var i = 0; i<range2.filter(String).length; i++){\n for(var j = 0; j<range2[i].filter(String).length; j++){ \n var name = range[i][9];\n if(name == \"Nitish\"){\n Logger.log(range[i],[j]);\n }\n }\n }\n \n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9425257/" ]
74,652,369
<p>I have a dataframe in which one column contains day and its time, I want to put that each day and its time in its respective column.</p> <p>I have put a '$' in each day to either split or use it to put it in its respective column.</p> <pre><code>import pandas as pd data = [{'timings' : 'Friday 10 am - 6:30 pm$Saturday 10am-6:30pm$Sunday Closed$Monday 10am-6:30pm$Tuesday 10am-6:30pm$Wednesday 10am-6:30pm$Thursday 10am-6:30pm', 'monday':'','tuesday':'','wednesday':'','thursday':'','friday':'','saturday':'','sunday':'' }] df = pd.DataFrame.from_dict(data) </code></pre> <p>For e.g.: Data contains df['timing'] = &quot;friday 10 am, saturday 6:30pm&quot;, then in df['friday'] = '10 am' and df['saturday'] = '6:30pm'.</p> <p>I dont know how to put it in words.</p> <p>Please me solve this problem.</p>
[ { "answer_id": 74652661, "author": "doubleunary", "author_id": 13045193, "author_profile": "https://Stackoverflow.com/users/13045193", "pm_score": 1, "selected": false, "text": "for condition Logger.log(range[i],[j]); forEach() function sendMail() {\n const ss = SpreadsheetApp.getActive();\n const values = ss.getRange('Pending Tasks!A2:J').getValues();\n values.forEach((row, rowIndex) => {\n const timestamp = row[0];\n row.forEach((value, columnIndex) => {\n if (value !== '') {\n console.log({ 'timestamp': timestamp, 'value': value, 'row': rowIndex + 1, 'column': columnIndex + 1 });\n }\n });\n });\n}\n" }, { "answer_id": 74653790, "author": "Deepak Raj", "author_id": 9425257, "author_profile": "https://Stackoverflow.com/users/9425257", "pm_score": 0, "selected": false, "text": "function sendMail() {\n\n var ss = SpreadsheetApp.getActiveSpreadsheet();\n var sheet = ss.getSheetByName(\"Pending Tasks\");\n var lr = sheet.getLastRow();\n var range = sheet.getRange(2,1,lr-1,10).getValues();\n var range2 = sheet.getRange(2,1,lr-1,1).getValues();\n for(var i = 0; i<range2.filter(String).length; i++){\n for(var j = 0; j<range2[i].filter(String).length; j++){ \n var name = range[i][9];\n if(name == \"Nitish\"){\n Logger.log(range[i],[j]);\n }\n }\n }\n \n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20357722/" ]
74,652,373
<p>I am working on a project the requirement is to store some encrypted data in the database. What is the preferred fieldtype of Django model for storing encrypted data?</p> <p>I am currently using CharField, however, I am not sure if this is the best approach. Also, should BinaryField be an option?</p>
[ { "answer_id": 74652661, "author": "doubleunary", "author_id": 13045193, "author_profile": "https://Stackoverflow.com/users/13045193", "pm_score": 1, "selected": false, "text": "for condition Logger.log(range[i],[j]); forEach() function sendMail() {\n const ss = SpreadsheetApp.getActive();\n const values = ss.getRange('Pending Tasks!A2:J').getValues();\n values.forEach((row, rowIndex) => {\n const timestamp = row[0];\n row.forEach((value, columnIndex) => {\n if (value !== '') {\n console.log({ 'timestamp': timestamp, 'value': value, 'row': rowIndex + 1, 'column': columnIndex + 1 });\n }\n });\n });\n}\n" }, { "answer_id": 74653790, "author": "Deepak Raj", "author_id": 9425257, "author_profile": "https://Stackoverflow.com/users/9425257", "pm_score": 0, "selected": false, "text": "function sendMail() {\n\n var ss = SpreadsheetApp.getActiveSpreadsheet();\n var sheet = ss.getSheetByName(\"Pending Tasks\");\n var lr = sheet.getLastRow();\n var range = sheet.getRange(2,1,lr-1,10).getValues();\n var range2 = sheet.getRange(2,1,lr-1,1).getValues();\n for(var i = 0; i<range2.filter(String).length; i++){\n for(var j = 0; j<range2[i].filter(String).length; j++){ \n var name = range[i][9];\n if(name == \"Nitish\"){\n Logger.log(range[i],[j]);\n }\n }\n }\n \n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12165050/" ]
74,652,407
<p>I try to initialise my database in Java by running testdb.sql file</p> <pre><code>private static Connection con; private static void initConenction() throws SQLException{ //Getting the connection String url = &quot;jdbc:mysql://localhost:3306/testDB?allowMultiQueries=true&quot;; final String userName = &quot;root&quot;; final String password = &quot;mypassword&quot;; try { con = DriverManager.getConnection(url, userName, password); System.out.println(&quot;Connection established!&quot;); } catch (SQLException e) { e.printStackTrace(); throw e; } }` </code></pre> <pre class="lang-java prettyprint-override"><code>private static void initDatabase() throws SQLException, IOException { try{ Statement stmt = con.createStatement(); String sqlStr = Files.readString(Paths.get(&quot;src/testdb.sql&quot;)); stmt.execute(sqlStr); System.out.println(&quot;Database initialization completed!&quot;); } catch (IOException e) { System.out.format(&quot;I/O error: %s%n&quot;, e); throw e; }catch (SQLException e){ e.printStackTrace(); throw e; } } </code></pre> <p>And here is the testdb.sql</p> <pre class="lang-sql prettyprint-override"><code>CREATE DATABASE IF NOT EXISTS testDB; USE testDB; CREATE TABLE USERS( userType VARCHAR(50) not null, userName VARCHAR(100) not null, password VARCHAR(100) not null, primary key(userName) ); </code></pre> <p>I ran the SQL exactly the same in MySQL bench and it works, but why when I try to do it in java it fails and warns error in SQL syntax? Here is the error message:</p> <blockquote> <p>java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CREATE TABLE USERS( userType VARCHAR(50) not null, userName VARCHAR(100)' at line 3</p> </blockquote> <p>I expect to create table in database by codes in Java</p>
[ { "answer_id": 74652620, "author": "Ivan Dong", "author_id": 20458097, "author_profile": "https://Stackoverflow.com/users/20458097", "pm_score": 0, "selected": false, "text": " ScriptRunner sr = new ScriptRunner(con);\n Reader sqlFile = new BufferedReader(new FileReader(Paths.get(\"src/testdb.sql\")))\n sr.runScript(sqlFile);\n" }, { "answer_id": 74652730, "author": "Mark Rotteveel", "author_id": 466862, "author_profile": "https://Stackoverflow.com/users/466862", "pm_score": 2, "selected": false, "text": "allowMultiQueries USE Connection.setCatalog Connection.setCatalog() USE" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9012992/" ]
74,652,410
<p>Here is the HTML code:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.container { max-width: 120rem; margin: 0 auto; padding: 0 3.2rem; } .grid { display: grid; column-gap: 6.4rem; row-gap: 8.6rem; } .grid-2-cols { grid-template-columns: 1fr 1fr; } .grid-center { align-items: center; justify-content: center; } .step-img { width: 35%; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="container grid grid-2-cols grid-center"&gt; &lt;div class="step-text-box"&gt; &lt;p&gt;01&lt;/p&gt; &lt;p&gt;Tell us what you like (and what not)&lt;/p&gt; &lt;p&gt; Never again waste time thinking about what to eat! Omnifood AI will create a 100% personalized weekly meal plan just for you. It makes sure you get the nutrients and vitamins you need, no matter what diet you follow! &lt;/p&gt; &lt;/div&gt; &lt;div class="step-img-box"&gt; &lt;img src="https://i.ibb.co/1JJVhy2/app-screen-1.png" alt="Omnifood iPhone app" class="step-img" /&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>In .grid-center selector, align-items works properly, but justify-content just does not work</p> <p>Why is this and how to solve it? Can anyone solve my puzzle?</p>
[ { "answer_id": 74652490, "author": "talkkis", "author_id": 20597903, "author_profile": "https://Stackoverflow.com/users/20597903", "pm_score": 0, "selected": false, "text": "display: flex; align-items: center margin: 0 auto;" }, { "answer_id": 74652500, "author": "Nick", "author_id": 10289517, "author_profile": "https://Stackoverflow.com/users/10289517", "pm_score": 2, "selected": true, "text": ".grid-center{\n display: flex;\n align-items: center;\n justify-content: center;\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20525500/" ]
74,652,411
<p><strong>Minimal reproducible code:</strong></p> <pre class="lang-dart prettyprint-override"><code>void main() async { final prefs = await SharedPreferences.getInstance(); await prefs.setString('key', null); // Error } </code></pre> <p>How can I set a <code>null</code> value in <a href="https://pub.dev/packages/shared_preferences" rel="nofollow noreferrer"><code>shared_preferences</code></a></p> <hr /> <p><strong>Note:</strong> I'm not looking for workarounds like, instead of <code>null</code>, use an empty string <code>''</code> and then check for it.</p>
[ { "answer_id": 74652490, "author": "talkkis", "author_id": 20597903, "author_profile": "https://Stackoverflow.com/users/20597903", "pm_score": 0, "selected": false, "text": "display: flex; align-items: center margin: 0 auto;" }, { "answer_id": 74652500, "author": "Nick", "author_id": 10289517, "author_profile": "https://Stackoverflow.com/users/10289517", "pm_score": 2, "selected": true, "text": ".grid-center{\n display: flex;\n align-items: center;\n justify-content: center;\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12483095/" ]
74,652,423
<p><strong>Example:</strong></p> <pre><code>n = 5 x = 3.5 Output: array([3.5, 3.5, 3.5, 3.5, 3.5]) </code></pre> <p><strong>My code:</strong></p> <pre><code>import numpy as np def init_all_x(n, x): np.all = [x]*n return np.all init_all_x(5, 3.5) </code></pre> <p><strong>My question:</strong></p> <p>Why init_all_x(5, 3.5).shape cannot run?</p> <p>If my code is wrong, what is the correct code? Thank you!</p>
[ { "answer_id": 74652490, "author": "talkkis", "author_id": 20597903, "author_profile": "https://Stackoverflow.com/users/20597903", "pm_score": 0, "selected": false, "text": "display: flex; align-items: center margin: 0 auto;" }, { "answer_id": 74652500, "author": "Nick", "author_id": 10289517, "author_profile": "https://Stackoverflow.com/users/10289517", "pm_score": 2, "selected": true, "text": ".grid-center{\n display: flex;\n align-items: center;\n justify-content: center;\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20422327/" ]
74,652,466
<p>I am trying to accomplish the following task using VBA:</p> <ol> <li>Rename the word document(.docx) to Zip(.zip) so that I can make changes in xml</li> <li>extract, Zip content</li> <li>goto the word folder</li> <li>Open and edit the document.xml file</li> <li>Search using the following regular expression: w:date=&quot;[\d\W]\w[\d\W]\w&quot;</li> </ol> <ul> <li>Replace it with nothing.</li> <li>This regular expression will match all XML timestamp attributes and remove them from the document.xml file.</li> </ul> <ol start="6"> <li>save the changes of document.xml file</li> <li>reZip files in the folder</li> <li>rename zip back to docx so that it becomes a Word document again</li> </ol> <p>So far, I have gone to 5th step and stuck, as I don't know the correct way to open and manipulate xml.</p> <ul> <li>I don't want to open it in plan text</li> <li>also don't want to spoil the xml.</li> </ul> <p>therefore I am looking for a way to open xml and remove specific text using vba without hurting xml.</p> <p>the VBA code is as follows:</p> <pre><code>Sub Rename_Zip_Unzip() Dim FSO As FileSystemObject Dim oApp As Shell Dim oDocPath, myZip Dim oDocName, oDocTemp, oDocEx, AP, oDocZip Dim oDocXML As String Dim oDocUnzip As String With Application.FileDialog(msoFileDialogFilePicker) .AllowMultiSelect = False .Filters.Clear .InitialFileName = ActiveDocument.Path .Filters.Add &quot;Word files&quot;, &quot;*.doc*&quot;, 1 If .Show = True Then If .SelectedItems.Count &gt; 0 Then oDocPath = .SelectedItems(1) Else MsgBox &quot;no valid selection&quot; Exit Sub End If End If End With If oDocPath = &quot;&quot; Then Beep Exit Sub End If Set FSO = CreateObject(&quot;Scripting.FileSystemObject&quot;) AP = Application.PathSeparator oDocName = FSO.GetFileName(oDocPath) oDocEx = FSO.GetExtensionName(oDocPath) oDocZip = Replace(oDocPath, AP &amp; oDocName, AP &amp; &quot;oDocZip.zip&quot;) 'copy and rename FSO.CopyFile oDocPath, oDocZip Set oApp = CreateObject(&quot;Shell.Application&quot;) oDocUnzip = Replace(oDocPath, AP &amp; oDocName, AP &amp; &quot;oDocUnzip&quot;) FileCompress.UnZip oDocZip, oDocUnzip, True oDocXML = Replace(oDocPath, AP &amp; oDocName, AP &amp; &quot;oDocUnzip\word\document.xml&quot;) Set xDoc = Nothing Application.StatusBar = &quot; Loading xml!!! &quot; &amp; oDocXML If Dir(oDocXML) = &quot;&quot; Then MsgBox &quot;File or folder path is not correct.&quot; &amp; vbNewLine &amp; oDocXML, vbOKOnly + vbCritical Exit Sub End If Load_xml oDocXML ' I tried to open it in word to replace text using wildcard, but it fails to open. On Error Resume Next Set xDoc = Documents.Open(oDocXML, Visible:=True) If xDoc Is Nothing Then MsgBox &quot;Cannot open:&quot; &amp; vbCr &amp; oDocXML &amp; vbNewLine &amp; &quot;Please check the Name of Folder and File.&quot;, vbExclamation Exit Sub End If Beep End Sub </code></pre> <p>I need to open and make changes in xml using following function:</p> <pre><code>Function Load_xml(xml As String) ' Get file name ... Dim oDoc As New MSXML2.DOMDocument60 Dim xMetricNames As IXMLDOMNodeList Dim xMetricName As IXMLDOMElement Dim xMetrics As IXMLDOMNode Dim xMetric As IXMLDOMElement Dim mtID As String, mtName As String, mtValue As String ' Load from file oDoc.Load xml ' Select needed nodes Set xMetrics = oDoc.SelectSingleNode(&quot;//project/checkpoints/checkpoint/files/file/metrics&quot;) Set xMetricNames = oDoc.SelectNodes(&quot;//project/metric_names/metric_name&quot;) For Each xMetricName In xMetricNames mtName = xMetricName.TEXT mtID = xMetricName.getAttribute(&quot;id&quot;) mtValue = xMetrics.SelectSingleNode(&quot;metric[@id='&quot; &amp; mtID &amp; &quot;']&quot;).TEXT 'here to delete the part of specific xml Next Set oDoc = Nothing End Function </code></pre> <p><strong>let say if I use open xml as simple text, what should be the correct pattern to replace the date and time?</strong></p>
[ { "answer_id": 74655015, "author": "William Walseth", "author_id": 901290, "author_profile": "https://Stackoverflow.com/users/901290", "pm_score": 0, "selected": false, "text": "Set xMetricNames = oDoc.SelectNodes(\"//project/metric_names/metric_name\")\n xMetricNames.removeAll()\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6236294/" ]
74,652,467
<p>I want something like that</p> <pre><code> `ifdef N_O &gt; N_I `define GREATER 1 `else `define LESSER 1 `endif </code></pre> <p>But cannot do. Any solution or reading?</p> <p>I tried hard to do this but could not do it.</p>
[ { "answer_id": 74655015, "author": "William Walseth", "author_id": 901290, "author_profile": "https://Stackoverflow.com/users/901290", "pm_score": 0, "selected": false, "text": "Set xMetricNames = oDoc.SelectNodes(\"//project/metric_names/metric_name\")\n xMetricNames.removeAll()\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20225187/" ]
74,652,493
<p>the code below displays a list after loading data from a backend, how can I cause the values ​​to be removed from the list and the table to be updated</p> <p><strong>React Code:</strong></p> <pre><code>import React, { Component } from &quot;react&quot;; import { fileuploadbolla } from &quot;../../services/file&quot;; import Table from &quot;react-bootstrap/Table&quot;; import { Button } from &quot;reactstrap&quot;; function TableArticoli(props) { return ( &lt;Table striped bordered hover editable&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;N° riga&lt;/th&gt; &lt;th&gt;Codice&lt;/th&gt; &lt;th&gt;Descrizione&lt;/th&gt; &lt;th&gt;Prezzo&lt;/th&gt; &lt;th&gt;Quantita&lt;/th&gt; &lt;th&gt;Totale&lt;/th&gt; &lt;th&gt;Edit&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; {props.list.map((item, i) =&gt; { return [ &lt;tr&gt; &lt;td&gt;{i}&lt;/td&gt; &lt;td&gt;{item.codart}&lt;/td&gt; &lt;td&gt;{item.descrizione}&lt;/td&gt; &lt;td&gt;{item.prezzo}&lt;/td&gt; &lt;td&gt;{item.prezzolistino}&lt;/td&gt; &lt;td&gt;{Number(item.prezzolistino) * Number(item.prezzo)}&lt;/td&gt; &lt;td&gt; &lt;Button size=&quot;xs&quot; color=&quot;danger&quot;&gt; Elimina &lt;/Button&gt; &lt;/td&gt; &lt;/tr&gt;, ]; })} &lt;/tbody&gt; &lt;/Table&gt; ); } class UploadFileBolla extends Component { constructor(props) { super(props); this.state = { image_file: null, image_preview: &quot;&quot;, listarticoli: [], }; } handleImagePreview = (e) =&gt; { let image_as_base64 = URL.createObjectURL(e.target.files[0]); let image_as_files = e.target.files[0]; this.setState({ image_preview: image_as_base64, image_file: image_as_files, }); }; handleSubmitFile = async () =&gt; { if (this.state.image_file !== null) { let formData = new FormData(); formData.append(&quot;file&quot;, this.state.image_file); var listarticoli = await fileuploadbolla(formData, &quot;SONEPAR&quot;); this.setState({ listarticoli: listarticoli.data }); } }; render() { return ( &lt;div&gt; &lt;input type=&quot;file&quot; onChange={this.handleImagePreview} /&gt; &lt;label&gt;Upload file&lt;/label&gt; &lt;input type=&quot;submit&quot; onClick={this.handleSubmitFile} value=&quot;Submit&quot; /&gt; {this.state.listarticoli.length &gt; 0 ? &lt;TableArticoli list={this.state.listarticoli} /&gt; : &lt;&gt;&lt;/&gt;} &lt;/div&gt; ); } } export default UploadFileBolla; </code></pre>
[ { "answer_id": 74652606, "author": "Andrew Shearer", "author_id": 10688837, "author_profile": "https://Stackoverflow.com/users/10688837", "pm_score": 1, "selected": false, "text": "import React, { useState } from \"react\";\nimport { fileuploadbolla } from \"../../services/file\";\nimport Table from \"react-bootstrap/Table\";\nimport { Button } from \"reactstrap\";\n\nfunction TableArticoli({ list, onDelete }) {\n return (\n <Table striped bordered hover editable>\n <thead>\n <tr>\n <th>N° riga</th>\n <th>Codice</th>\n <th>Descrizione</th>\n <th>Prezzo</th>\n <th>Quantita</th>\n <th>Totale</th>\n <th>Edit</th>\n </tr>\n </thead>\n <tbody>\n {list.map((item, i) => {\n return [\n <tr>\n <td>{i}</td>\n <td>{item.codart}</td>\n <td>{item.descrizione}</td>\n <td>{item.prezzo}</td>\n <td>{item.prezzolistino}</td>\n <td>{Number(item.prezzolistino) * Number(item.prezzo)}</td>\n <td>\n <Button size=\"xs\" color=\"danger\" onClick={() => onDelete(item)}>\n Elimina\n </Button>\n </td>\n </tr>,\n ];\n })}\n </tbody>\n </Table>\n );\n}\n\nfunction UploadFileBolla() {\n const [imageFile, setImageFile] = useState(null);\n const [listarticoli, setListarticoli] = useState([]);\n\n const handleImagePreview = (e) => {\n let imageAsFiles = e.target.files[0];\n\n setImageFile(imageAsFiles);\n };\n\n const handleSubmitFile = async () => {\n if (imageFile !== null) {\n let formData = new FormData();\n formData.append(\"file\", imageFile);\n var listarticoli = await fileuploadbolla(formData, \"SONEPAR\");\n setListarticoli(listarticoli.data);\n }\n };\n\n const handleDelete = (item) => {\n // create a copy of the list\n let list = [...listarticoli];\n\n // find the index of the item to be deleted\n let index = list.indexOf(item);\n\n // remove the item from the list\n list.splice(index, 1);\n\n // update the state with the new list\n setListarticoli(list);\n };\n\n return (\n <div>\n <input type=\"file\" onChange={handleImagePreview} />\n <label>Upload file</label>\n <input type=\"submit\" onClick={handleSubmitFile} value=\"Submit\" />\n {listarticoli.length > 0 ? (\n <TableArticoli list={listarticoli} onDelete={handleDelete} />\n ) : (\n <></>\n )}\n </div>\n );\n}\n" }, { "answer_id": 74652728, "author": "Dream Bold", "author_id": 12743692, "author_profile": "https://Stackoverflow.com/users/12743692", "pm_score": 0, "selected": false, "text": "...\n<Button size=\"xs\" color=\"danger\" onClick={e => this.handleDelete(index,e)}>\n Elimina\n</Button>\n...\n \n handleDelete = (index, e) => {\n this.setState({...,\n listarticoli: this.listarticoli.filter((v, i) => i !== index));\n });\n \n" }, { "answer_id": 74652806, "author": "armful", "author_id": 20664163, "author_profile": "https://Stackoverflow.com/users/20664163", "pm_score": 2, "selected": true, "text": "TableArticoli import React, { Component } from \"react\";\nimport { fileuploadbolla } from \"../../services/file\";\nimport Table from \"react-bootstrap/Table\";\nimport { Button } from \"reactstrap\";\n\nfunction TableArticoli(props) {\n return (\n <Table striped bordered hover editable>\n <thead>\n <tr>\n <th>N° riga</th>\n <th>Codice</th>\n <th>Descrizione</th>\n <th>Prezzo</th>\n <th>Quantita</th>\n <th>Totale</th>\n <th>Edit</th>\n </tr>\n </thead>\n <tbody>\n {props.list.map((item, i) => {\n return [\n <tr>\n <td>{i}</td>\n <td>{item.codart}</td>\n <td>{item.descrizione}</td>\n <td>{item.prezzo}</td>\n <td>{item.prezzolistino}</td>\n <td>{Number(item.prezzolistino) * Number(item.prezzo)}</td>\n <td>\n <Button size=\"xs\" color=\"danger\" onClick={() => props.onDelete(item.codart)}>\n Elimina\n </Button>\n </td>\n </tr>,\n ];\n })}\n </tbody>\n </Table>\n );\n}\n\nclass UploadFileBolla extends Component {\n constructor(props) {\n super(props);\n this.state = {\n image_file: null,\n image_preview: \"\",\n listarticoli: [],\n };\n }\n\n // Method to handle the deletion of an item from the list\n handleDelete = (codart) => {\n // Find the index of the item in the list\n const index = this.state.listarticoli.findIndex((item) => item.codart === codart);\n\n // Create a copy of the list\n const newList = [...this.state.listarticoli];\n\n // Remove the item from the list\n newList.splice(index, 1);\n\n // Update the state with the new list\n this.setState({ listarticoli: newList });\n }\n\n handleImagePreview = (e) => {\n let image_as_base64 = URL.createObjectURL(e.target.files[0]);\n let image_as_files = e.target.files[0];\n\n this.setState({\n image_preview: image_as_base64,\n image_file: image_as_files,\n });\n };\n\n handleSubmitFile = async ()\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10278268/" ]
74,652,513
<p>I have two Objects with unknown keys I want to merge into a new object that has a type and all keys not part of that type should be omitted.</p> <p>To make a practical example: I have URL query parameters (exposed and editable by the user) and cookie values which I want to merge. I want to omit all unwanted parameters to just the ones I allow/need (defined by a type)</p> <pre><code>type RequestAdditionalParameters = { session?: string | null; searchInput?: string | null; id?: string | null; } //I use a generic because RequestAdditionalParameters actually has multiple possible //types, but I think that shouldn't matter export const mergeParameters = &lt;T extends RequestAdditionalParameters&gt;( cookies: Record&lt;string, string | null&gt;, queryParams: Record&lt;string, string | null&gt; ): T =&gt; { const allowedParams: T = { ...cookies, ...queryParams }; return allowedParams; }; const additionalParameters = mergeParameters&lt;SearchParameters&gt;( { session, id }, { searchInput, anotherParam } ); result = { session: 'kjn33fbf4fkl3w3ff3f3ffuu', searchInput: 'stackoverflow', id: '345644783', anotherParam: 'should not be here', } expectedResult = { session: 'kjn33fbf4fkl3w3ff3f3ffuu', searchInput: 'stackoverflow', id: '345644783', } </code></pre> <p>If I log the output, I still get unwanted kesa that are not part of the type</p> <p>How can I achieve this?</p>
[ { "answer_id": 74654467, "author": "Romain TAILLANDIER", "author_id": 2355088, "author_profile": "https://Stackoverflow.com/users/2355088", "pm_score": 2, "selected": true, "text": "const requestAdditionalParametersKeys = [\"session\", \"searchInput\", \"id\"] as const;\ntype RequestAdditionalParametersKeys = typeof requestAdditionalParametersKeys[number];\ntype RequestAdditionalParameters = { [key in RequestAdditionalParametersKeys]?: string | null };\n\n// inherits is done like this : \nconst searchParametersKeys = [...requestAdditionalParametersKeys, \"search\"] as const;\ntype SearchParametersKeys = typeof searchParametersKeys[number];\ntype SearchParameters = { [key in SearchParametersKeys]?: string | null };\n\n\nconst mergeParameters = <T extends RequestAdditionalParameters, K extends keyof T>(\n allAllowedKeysOfT: Array<string>,\n cookies: Record<string, string | null>,\n queryParams: Record<string, string | null>\n): T => {\n const allowedParamsCandidate = { ...cookies, ...queryParams };\n const result: { [key in keyof T]?: string | null } = {}; \n for (const key in allowedParamsCandidate) {\n if (allowedParamsCandidate[key] != null)\n if (allAllowedKeysOfT.includes(key)) {\n result[key as K] = allowedParamsCandidate[key];\n }\n }\n return result as T;\n};\n\nconst additionalParameters = mergeParameters<SearchParameters, keyof SearchParameters>(\n searchParametersKeys as unknown as string[],\n { session: 'kjn33fbf4fkl3w3ff3f3ffuu', id: '345644783' },\n { searchInput: 'stackoverflow', anotherParam: 'should not be here' }\n);\n\nconsole.log(JSON.stringify(additionalParameters, null, 2))\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3775690/" ]
74,652,533
<p>I've started getting to grips with flex and as soon as I think I have a solid understanding and tried to implement it I find it's not working.</p> <p>The main issue is the <code>justify-content: space-evenly</code> inside my <code>ul</code> isn't taking any effect and I can't see why. From everything I've looked at this is correct and should work, I've even seen people using this in tutorials within the same structure.</p> <p>I placed a border around the element to make sure there is space for it to take up. I've tried different flex properties, they wont work either. Am I doing something do disable flex?</p> <p>Any ideas what I'm doing wrong here?</p> <p><a href="https://i.stack.imgur.com/hetI3m.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hetI3m.png" alt="Example" /></a></p> <p><strong>CSS</strong></p> <pre class="lang-css prettyprint-override"><code>h1 { font-size: 6em; text-align: center; } nav { font-size: 1.5em; display: flex; justify-content: space-between; } ul { border: 1px solid red; display: flex; flex-grow: 1; justify-content: space-evenly; max-width: 50%; } ul,li { display: inline; margin: 0; padding: 0; } </code></pre> <p><strong>HTML</strong></p> <pre class="lang-html prettyprint-override"><code>&lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt; &lt;title&gt;Media Queries&lt;/title&gt; &lt;link href=&quot;https://fonts.googleapis.com/css2?family=Open+Sans:wght@300&amp;display=swap&quot; rel=&quot;stylesheet&quot;&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;app.css&quot;&gt; &lt;/head&gt; &lt;body&gt; &lt;nav&gt; &lt;a href=&quot;#home&quot;&gt;Home&lt;/a&gt; &lt;ul&gt; &lt;li&gt; &lt;a href=&quot;#Home&quot;&gt;Learn More&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href=&quot;#Home&quot;&gt;About&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href=&quot;#Home&quot;&gt;Contact&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;a href=&quot;#signup&quot;&gt;Sign Up&lt;/a&gt; &lt;/nav&gt; &lt;h1&gt;Flex Box &lt;/h1&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "answer_id": 74652596, "author": "jerry", "author_id": 20493210, "author_profile": "https://Stackoverflow.com/users/20493210", "pm_score": 0, "selected": false, "text": "<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>Media Queries</title>\n <link\n href=\"https://fonts.googleapis.com/css2?family=Open+Sans:wght@300&display=swap\"\n rel=\"stylesheet\"\n />\n\n <link rel=\"stylesheet\" href=\"app.css\" />\n </head>\n\n <style>\n h1 {\n font-size: 6em;\n text-align: center;\n }\n nav {\n font-size: 1.5em;\n display: flex;\n justify-content: space-between;\n }\n\n ul {\n border: 1px solid red;\n max-width: 50%;\n }\n\n ul,\n li {\n display: inline;\n margin: 0;\n padding: 0;\n }\n\n ul {\n display: flex;\n flex-grow: 1;\n justify-content: space-evenly;\n }\n </style>\n\n <body>\n <nav>\n <a href=\"#home\">Home</a>\n <ul>\n <li>\n <a href=\"#Home\">Learn More</a>\n </li>\n <li>\n <a href=\"#Home\">About</a>\n </li>\n <li>\n <a href=\"#Home\">Contact</a>\n </li>\n </ul>\n <a href=\"#signup\">Sign Up</a>\n </nav>\n <h1>Flex Box</h1>\n </body>\n</html>" }, { "answer_id": 74652609, "author": "Jawad Ul Hassan", "author_id": 16140334, "author_profile": "https://Stackoverflow.com/users/16140334", "pm_score": 1, "selected": false, "text": "ul,li {\n margin: 0;\n padding: 0;\n}\n" }, { "answer_id": 74652619, "author": "Pratik Dev", "author_id": 15908339, "author_profile": "https://Stackoverflow.com/users/15908339", "pm_score": 0, "selected": false, "text": "display: flex display: inline list-style: none h1 {\n font-size: 6em;\n text-align: center;\n}\nnav {\n font-size: 1.5em;\n display: flex;\n justify-content: space-between;\n}\n\nul {\n border: 1px solid red;\n display: flex;\n flex-grow: 1;\n justify-content: space-evenly;\n max-width: 50%;\n}\n\nul,li {\n /* -- remove the below line. you're over-writing the display of ul\n display: inline;\n */\n \n /* -- add this below line to get rid of the bullet points */\n list-style: none;\n \n margin: 0;\n padding: 0;\n} <html lang=\"en\">\n\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Media Queries</title>\n <link href=\"https://fonts.googleapis.com/css2?family=Open+Sans:wght@300&display=swap\" rel=\"stylesheet\">\n\n <link rel=\"stylesheet\" href=\"app.css\">\n</head>\n\n<body>\n <nav>\n <a href=\"#home\">Home</a>\n <ul>\n\n <li>\n <a href=\"#Home\">Learn More</a>\n </li>\n <li>\n <a href=\"#Home\">About</a>\n </li>\n <li>\n <a href=\"#Home\">Contact</a>\n </li>\n\n </ul>\n <a href=\"#signup\">Sign Up</a>\n </nav>\n <h1>Flex Box\n</h1>\n\n</body>\n\n</html>" }, { "answer_id": 74652632, "author": "Hoargarth", "author_id": 9184970, "author_profile": "https://Stackoverflow.com/users/9184970", "pm_score": 1, "selected": true, "text": "display: flex ul ul ul,li display: inline ul {\n display: flex;\n ...\n}\n\nul,li {\n display: inline;\n ...\n}\n ul ul padding: 0; ul space-evenly h1 {\n font-size: 6em;\n text-align: center;\n}\nnav {\n font-size: 1.5em;\n display: flex;\n justify-content: space-between;\n}\n\nul {\n border: 1px solid red;\n display: flex;\n flex-grow: 1;\n justify-content: space-evenly;\n max-width: 50%;\n padding: 0;\n}\n\nli {\n display: inline;\n margin: 0;\n padding: 0;\n} <html lang=\"en\">\n\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Media Queries</title>\n <link href=\"https://fonts.googleapis.com/css2?family=Open+Sans:wght@300&display=swap\" rel=\"stylesheet\">\n\n <link rel=\"stylesheet\" href=\"app.css\">\n</head>\n\n<body>\n <nav>\n <a href=\"#home\">Home</a>\n <ul>\n\n <li>\n <a href=\"#Home\">Learn More</a>\n </li>\n <li>\n <a href=\"#Home\">About</a>\n </li>\n <li>\n <a href=\"#Home\">Contact</a>\n </li>\n\n </ul>\n <a href=\"#signup\">Sign Up</a>\n </nav>\n <h1>Flex Box\n</h1>\n\n</body>" }, { "answer_id": 74652645, "author": "Akash Sarker", "author_id": 20655816, "author_profile": "https://Stackoverflow.com/users/20655816", "pm_score": 0, "selected": false, "text": "ul {\n border: 1px solid red;\n display: flex !important;\n flex-grow: 1;\n justify-content: space-evenly;\n max-width: 50%;\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19127509/" ]
74,652,567
<p>Hi is there a way to select a value filtered with multiple parameter with flux language in influx db : Exemple in sql : select val1 from tab1,tab2,tab3 where val2.tab2&gt;30 and val3.tab&gt;6 . Is this possible in flux language ? Thanks</p> <p>For now I only grab every value that I need and I filtered myself on Java but the problem is that java take too many time to filtering values.</p> <pre><code>HashMap&lt;String,Float&gt; drivepumpchargepresshash = inConn.queryData(clientRead,drivepumpchargepress,camu3,vibrateur01,prev,now,null); HashMap&lt;String,Float&gt; hydOilTempHash = inConn.queryData(clientRead, hydOilTemp, hydOilTempGroup, vibrateur01, prev, now,null); HashMap&lt;String,Float&gt; engSpeedHash = inConn.queryData(clientRead, engSpeed, ecc1, vibrateur01, prev, now,null); HashMap&lt;String,Float&gt; wheelBasedVehicleSpeedHash = inConn.queryData(clientRead, wheelBasedVehicleSpeed, ccvs1, vibrateur01, prev, now,null); //Query data ArrayList&lt;Float&gt; filteredList = new ArrayList&lt;Float&gt;(); HashMap&lt;String,HashMap&lt;String,Float&gt;&gt; outerMap = new HashMap&lt;String, HashMap&lt;String,Float&gt;&gt;(); // storing as : key : date , value : [key:para_name , value: para_value] float max,min,maxmin,mean,standard_deviation; //initalise calculation variable for(String date : drivepumpchargepresshash.keySet()) {//If contain a value at this date if(engSpeedHash.containsKey(date) &amp;&amp; wheelBasedVehicleSpeedHash.containsKey(date) &amp;&amp; hydOilTempHash.containsKey(date)) { HashMap&lt;String, Float&gt; innerMap = new HashMap&lt;String,Float&gt;(); innerMap.put(drivepumpchargepress, drivepumpchargepresshash.get(date)); innerMap.put(engSpeed, engSpeedHash.get(date)); innerMap.put(wheelBasedVehicleSpeed, wheelBasedVehicleSpeedHash.get(date)); //Stocking all data innerMap.put(hydOilTemp, hydOilTempHash.get(date)); outerMap.put(date, innerMap); } } </code></pre>
[ { "answer_id": 74652596, "author": "jerry", "author_id": 20493210, "author_profile": "https://Stackoverflow.com/users/20493210", "pm_score": 0, "selected": false, "text": "<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>Media Queries</title>\n <link\n href=\"https://fonts.googleapis.com/css2?family=Open+Sans:wght@300&display=swap\"\n rel=\"stylesheet\"\n />\n\n <link rel=\"stylesheet\" href=\"app.css\" />\n </head>\n\n <style>\n h1 {\n font-size: 6em;\n text-align: center;\n }\n nav {\n font-size: 1.5em;\n display: flex;\n justify-content: space-between;\n }\n\n ul {\n border: 1px solid red;\n max-width: 50%;\n }\n\n ul,\n li {\n display: inline;\n margin: 0;\n padding: 0;\n }\n\n ul {\n display: flex;\n flex-grow: 1;\n justify-content: space-evenly;\n }\n </style>\n\n <body>\n <nav>\n <a href=\"#home\">Home</a>\n <ul>\n <li>\n <a href=\"#Home\">Learn More</a>\n </li>\n <li>\n <a href=\"#Home\">About</a>\n </li>\n <li>\n <a href=\"#Home\">Contact</a>\n </li>\n </ul>\n <a href=\"#signup\">Sign Up</a>\n </nav>\n <h1>Flex Box</h1>\n </body>\n</html>" }, { "answer_id": 74652609, "author": "Jawad Ul Hassan", "author_id": 16140334, "author_profile": "https://Stackoverflow.com/users/16140334", "pm_score": 1, "selected": false, "text": "ul,li {\n margin: 0;\n padding: 0;\n}\n" }, { "answer_id": 74652619, "author": "Pratik Dev", "author_id": 15908339, "author_profile": "https://Stackoverflow.com/users/15908339", "pm_score": 0, "selected": false, "text": "display: flex display: inline list-style: none h1 {\n font-size: 6em;\n text-align: center;\n}\nnav {\n font-size: 1.5em;\n display: flex;\n justify-content: space-between;\n}\n\nul {\n border: 1px solid red;\n display: flex;\n flex-grow: 1;\n justify-content: space-evenly;\n max-width: 50%;\n}\n\nul,li {\n /* -- remove the below line. you're over-writing the display of ul\n display: inline;\n */\n \n /* -- add this below line to get rid of the bullet points */\n list-style: none;\n \n margin: 0;\n padding: 0;\n} <html lang=\"en\">\n\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Media Queries</title>\n <link href=\"https://fonts.googleapis.com/css2?family=Open+Sans:wght@300&display=swap\" rel=\"stylesheet\">\n\n <link rel=\"stylesheet\" href=\"app.css\">\n</head>\n\n<body>\n <nav>\n <a href=\"#home\">Home</a>\n <ul>\n\n <li>\n <a href=\"#Home\">Learn More</a>\n </li>\n <li>\n <a href=\"#Home\">About</a>\n </li>\n <li>\n <a href=\"#Home\">Contact</a>\n </li>\n\n </ul>\n <a href=\"#signup\">Sign Up</a>\n </nav>\n <h1>Flex Box\n</h1>\n\n</body>\n\n</html>" }, { "answer_id": 74652632, "author": "Hoargarth", "author_id": 9184970, "author_profile": "https://Stackoverflow.com/users/9184970", "pm_score": 1, "selected": true, "text": "display: flex ul ul ul,li display: inline ul {\n display: flex;\n ...\n}\n\nul,li {\n display: inline;\n ...\n}\n ul ul padding: 0; ul space-evenly h1 {\n font-size: 6em;\n text-align: center;\n}\nnav {\n font-size: 1.5em;\n display: flex;\n justify-content: space-between;\n}\n\nul {\n border: 1px solid red;\n display: flex;\n flex-grow: 1;\n justify-content: space-evenly;\n max-width: 50%;\n padding: 0;\n}\n\nli {\n display: inline;\n margin: 0;\n padding: 0;\n} <html lang=\"en\">\n\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Media Queries</title>\n <link href=\"https://fonts.googleapis.com/css2?family=Open+Sans:wght@300&display=swap\" rel=\"stylesheet\">\n\n <link rel=\"stylesheet\" href=\"app.css\">\n</head>\n\n<body>\n <nav>\n <a href=\"#home\">Home</a>\n <ul>\n\n <li>\n <a href=\"#Home\">Learn More</a>\n </li>\n <li>\n <a href=\"#Home\">About</a>\n </li>\n <li>\n <a href=\"#Home\">Contact</a>\n </li>\n\n </ul>\n <a href=\"#signup\">Sign Up</a>\n </nav>\n <h1>Flex Box\n</h1>\n\n</body>" }, { "answer_id": 74652645, "author": "Akash Sarker", "author_id": 20655816, "author_profile": "https://Stackoverflow.com/users/20655816", "pm_score": 0, "selected": false, "text": "ul {\n border: 1px solid red;\n display: flex !important;\n flex-grow: 1;\n justify-content: space-evenly;\n max-width: 50%;\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20664026/" ]
74,652,569
<p>I have a modal with my inputs, I'm using Bootstrap modal with jQuery some validation code to validate my form on submit, my problem is that when I close the modal and then I open the modal again the messages from validation still there, so my question is, how can I reset or hide those messages when I close the modal?</p> <p>Here is the Javascript code:</p> <pre><code> $(document).ready(function() { $('#addForm').validate({ rules: { name: { required: true, }, mobile_no: { required: true, }, address: { required: true, }, email_address: { required: true, }, }, messages: { name: { required: 'Please Enter Supplier Name', }, mobile_no: { required: 'Please Enter Supplier mobile number', }, address: { required: 'Please Enter Supplier address', }, email_address: { required: 'Please Enter Supplier email', }, }, errorElement: 'span', errorPlacement: function(error, element) { error.addClass('invalid-feedback'); element.closest('.form-group').append(error); }, highlight: function(element, errorClass, validClass) { $(element).addClass('is-invalid'); }, unhighlight: function(element, errorClass, validClass) { $(element).removeClass('is-invalid'); }, }); }); </code></pre> <p>Here is the code in Bootstrap modal:</p> <pre><code>&lt;!-- Modal --&gt; &lt;div class=&quot;modal fade&quot; id=&quot;exampleModal&quot; tabindex=&quot;-1&quot; role=&quot;dialog&quot; aria-labelledby=&quot;exampleModalLabel&quot; aria-hidden=&quot;true&quot;&gt; &lt;div class=&quot;modal-dialog&quot; role=&quot;document&quot;&gt; &lt;div class=&quot;modal-content&quot;&gt; &lt;div class=&quot;modal-header&quot;&gt; &lt;h5 class=&quot;modal-title&quot; id=&quot;exampleModalLabel&quot;&gt;Add Supplier&lt;/h5&gt; &lt;button type=&quot;button&quot; class=&quot; btn btn-danger btn btn-sm close&quot; data-dismiss=&quot;modal&quot; aria-label=&quot;Close&quot;&gt; &lt;span aria-hidden=&quot;true&quot;&gt;&amp;times;&lt;/span&gt; &lt;/button&gt; &lt;/div&gt; &lt;form id=&quot;addForm&quot; method=&quot;POST&quot; action=&quot;{{ route('supplier.store') }}&quot;&gt; @csrf &lt;div class=&quot;modal-body&quot;&gt; &lt;!-- name --&gt; &lt;div class=&quot;col-md-12 &quot;&gt; &lt;div class=&quot;mb-3 position-relative form-group&quot;&gt; &lt;input class=&quot;form-control&quot; type=&quot;text&quot; autocomplete=&quot;name&quot; placeholder=&quot;Supplier Name&quot; id=&quot;name&quot; name=&quot;name&quot; value=&quot;&quot;&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- mobile number --&gt; &lt;div class=&quot;col-md-12 &quot;&gt; &lt;div class=&quot;mb-3 position-relative form-group&quot;&gt; &lt;input class=&quot;form-control &quot; type=&quot;number&quot; autocomplete=&quot;mobile_no&quot; placeholder=&quot;Mobile Number&quot; id=&quot;mobile_no&quot; name=&quot;mobile_no&quot; value=&quot;&quot;&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- email --&gt; &lt;div class=&quot;col-md-12 &quot;&gt; &lt;div class=&quot;mb-3 position-relative form-group&quot;&gt; &lt;input class=&quot;form-control &quot; type=&quot;email&quot; placeholder=&quot;Email&quot; id=&quot;email_address&quot; name=&quot;email_address&quot; value=&quot;&quot;&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;col-md-12 &quot;&gt; &lt;div class=&quot;mb-3 position-relative form-group&quot;&gt; &lt;input class=&quot;form-control&quot; type=&quot;text&quot; autocomplete=&quot;address&quot; placeholder=&quot;Address&quot; id=&quot;address&quot; name=&quot;address&quot; value=&quot;&quot;&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;modal-footer&quot;&gt; &lt;button type=&quot;button&quot; class=&quot;btn btn-secondary close&quot; data-dismiss=&quot;modal&quot; onclick=&quot;a()&quot;&gt;Close&lt;/button&gt; &lt;button type=&quot;submit&quot; class=&quot;btn btn-primary&quot;&gt;Add Supplier&lt;/button&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Code in <code>index.php</code>:</p> <pre><code>&lt;div style=&quot;float: right&quot;&gt;&lt;button type=&quot;button &quot; class=&quot;btn btn-primary&quot; data-toggle=&quot;modal&quot; data-target=&quot;#exampleModal&quot; &gt;Add Supplier&lt;/button&gt;&lt;/div&gt;&lt;br&gt;&lt;br&gt; </code></pre>
[ { "answer_id": 74652596, "author": "jerry", "author_id": 20493210, "author_profile": "https://Stackoverflow.com/users/20493210", "pm_score": 0, "selected": false, "text": "<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>Media Queries</title>\n <link\n href=\"https://fonts.googleapis.com/css2?family=Open+Sans:wght@300&display=swap\"\n rel=\"stylesheet\"\n />\n\n <link rel=\"stylesheet\" href=\"app.css\" />\n </head>\n\n <style>\n h1 {\n font-size: 6em;\n text-align: center;\n }\n nav {\n font-size: 1.5em;\n display: flex;\n justify-content: space-between;\n }\n\n ul {\n border: 1px solid red;\n max-width: 50%;\n }\n\n ul,\n li {\n display: inline;\n margin: 0;\n padding: 0;\n }\n\n ul {\n display: flex;\n flex-grow: 1;\n justify-content: space-evenly;\n }\n </style>\n\n <body>\n <nav>\n <a href=\"#home\">Home</a>\n <ul>\n <li>\n <a href=\"#Home\">Learn More</a>\n </li>\n <li>\n <a href=\"#Home\">About</a>\n </li>\n <li>\n <a href=\"#Home\">Contact</a>\n </li>\n </ul>\n <a href=\"#signup\">Sign Up</a>\n </nav>\n <h1>Flex Box</h1>\n </body>\n</html>" }, { "answer_id": 74652609, "author": "Jawad Ul Hassan", "author_id": 16140334, "author_profile": "https://Stackoverflow.com/users/16140334", "pm_score": 1, "selected": false, "text": "ul,li {\n margin: 0;\n padding: 0;\n}\n" }, { "answer_id": 74652619, "author": "Pratik Dev", "author_id": 15908339, "author_profile": "https://Stackoverflow.com/users/15908339", "pm_score": 0, "selected": false, "text": "display: flex display: inline list-style: none h1 {\n font-size: 6em;\n text-align: center;\n}\nnav {\n font-size: 1.5em;\n display: flex;\n justify-content: space-between;\n}\n\nul {\n border: 1px solid red;\n display: flex;\n flex-grow: 1;\n justify-content: space-evenly;\n max-width: 50%;\n}\n\nul,li {\n /* -- remove the below line. you're over-writing the display of ul\n display: inline;\n */\n \n /* -- add this below line to get rid of the bullet points */\n list-style: none;\n \n margin: 0;\n padding: 0;\n} <html lang=\"en\">\n\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Media Queries</title>\n <link href=\"https://fonts.googleapis.com/css2?family=Open+Sans:wght@300&display=swap\" rel=\"stylesheet\">\n\n <link rel=\"stylesheet\" href=\"app.css\">\n</head>\n\n<body>\n <nav>\n <a href=\"#home\">Home</a>\n <ul>\n\n <li>\n <a href=\"#Home\">Learn More</a>\n </li>\n <li>\n <a href=\"#Home\">About</a>\n </li>\n <li>\n <a href=\"#Home\">Contact</a>\n </li>\n\n </ul>\n <a href=\"#signup\">Sign Up</a>\n </nav>\n <h1>Flex Box\n</h1>\n\n</body>\n\n</html>" }, { "answer_id": 74652632, "author": "Hoargarth", "author_id": 9184970, "author_profile": "https://Stackoverflow.com/users/9184970", "pm_score": 1, "selected": true, "text": "display: flex ul ul ul,li display: inline ul {\n display: flex;\n ...\n}\n\nul,li {\n display: inline;\n ...\n}\n ul ul padding: 0; ul space-evenly h1 {\n font-size: 6em;\n text-align: center;\n}\nnav {\n font-size: 1.5em;\n display: flex;\n justify-content: space-between;\n}\n\nul {\n border: 1px solid red;\n display: flex;\n flex-grow: 1;\n justify-content: space-evenly;\n max-width: 50%;\n padding: 0;\n}\n\nli {\n display: inline;\n margin: 0;\n padding: 0;\n} <html lang=\"en\">\n\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Media Queries</title>\n <link href=\"https://fonts.googleapis.com/css2?family=Open+Sans:wght@300&display=swap\" rel=\"stylesheet\">\n\n <link rel=\"stylesheet\" href=\"app.css\">\n</head>\n\n<body>\n <nav>\n <a href=\"#home\">Home</a>\n <ul>\n\n <li>\n <a href=\"#Home\">Learn More</a>\n </li>\n <li>\n <a href=\"#Home\">About</a>\n </li>\n <li>\n <a href=\"#Home\">Contact</a>\n </li>\n\n </ul>\n <a href=\"#signup\">Sign Up</a>\n </nav>\n <h1>Flex Box\n</h1>\n\n</body>" }, { "answer_id": 74652645, "author": "Akash Sarker", "author_id": 20655816, "author_profile": "https://Stackoverflow.com/users/20655816", "pm_score": 0, "selected": false, "text": "ul {\n border: 1px solid red;\n display: flex !important;\n flex-grow: 1;\n justify-content: space-evenly;\n max-width: 50%;\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8701694/" ]
74,652,586
<p>I wanted to create a gene like twisty rotating effect purely with HTML and CSS. I can animate the the whole div to rotate but I couldn't figure out how to make it rotate horizontally gradually from bottom to top. Is this possible through pure HTML and CSS? If it is possible, any ideas how to do this?</p>
[ { "answer_id": 74652596, "author": "jerry", "author_id": 20493210, "author_profile": "https://Stackoverflow.com/users/20493210", "pm_score": 0, "selected": false, "text": "<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>Media Queries</title>\n <link\n href=\"https://fonts.googleapis.com/css2?family=Open+Sans:wght@300&display=swap\"\n rel=\"stylesheet\"\n />\n\n <link rel=\"stylesheet\" href=\"app.css\" />\n </head>\n\n <style>\n h1 {\n font-size: 6em;\n text-align: center;\n }\n nav {\n font-size: 1.5em;\n display: flex;\n justify-content: space-between;\n }\n\n ul {\n border: 1px solid red;\n max-width: 50%;\n }\n\n ul,\n li {\n display: inline;\n margin: 0;\n padding: 0;\n }\n\n ul {\n display: flex;\n flex-grow: 1;\n justify-content: space-evenly;\n }\n </style>\n\n <body>\n <nav>\n <a href=\"#home\">Home</a>\n <ul>\n <li>\n <a href=\"#Home\">Learn More</a>\n </li>\n <li>\n <a href=\"#Home\">About</a>\n </li>\n <li>\n <a href=\"#Home\">Contact</a>\n </li>\n </ul>\n <a href=\"#signup\">Sign Up</a>\n </nav>\n <h1>Flex Box</h1>\n </body>\n</html>" }, { "answer_id": 74652609, "author": "Jawad Ul Hassan", "author_id": 16140334, "author_profile": "https://Stackoverflow.com/users/16140334", "pm_score": 1, "selected": false, "text": "ul,li {\n margin: 0;\n padding: 0;\n}\n" }, { "answer_id": 74652619, "author": "Pratik Dev", "author_id": 15908339, "author_profile": "https://Stackoverflow.com/users/15908339", "pm_score": 0, "selected": false, "text": "display: flex display: inline list-style: none h1 {\n font-size: 6em;\n text-align: center;\n}\nnav {\n font-size: 1.5em;\n display: flex;\n justify-content: space-between;\n}\n\nul {\n border: 1px solid red;\n display: flex;\n flex-grow: 1;\n justify-content: space-evenly;\n max-width: 50%;\n}\n\nul,li {\n /* -- remove the below line. you're over-writing the display of ul\n display: inline;\n */\n \n /* -- add this below line to get rid of the bullet points */\n list-style: none;\n \n margin: 0;\n padding: 0;\n} <html lang=\"en\">\n\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Media Queries</title>\n <link href=\"https://fonts.googleapis.com/css2?family=Open+Sans:wght@300&display=swap\" rel=\"stylesheet\">\n\n <link rel=\"stylesheet\" href=\"app.css\">\n</head>\n\n<body>\n <nav>\n <a href=\"#home\">Home</a>\n <ul>\n\n <li>\n <a href=\"#Home\">Learn More</a>\n </li>\n <li>\n <a href=\"#Home\">About</a>\n </li>\n <li>\n <a href=\"#Home\">Contact</a>\n </li>\n\n </ul>\n <a href=\"#signup\">Sign Up</a>\n </nav>\n <h1>Flex Box\n</h1>\n\n</body>\n\n</html>" }, { "answer_id": 74652632, "author": "Hoargarth", "author_id": 9184970, "author_profile": "https://Stackoverflow.com/users/9184970", "pm_score": 1, "selected": true, "text": "display: flex ul ul ul,li display: inline ul {\n display: flex;\n ...\n}\n\nul,li {\n display: inline;\n ...\n}\n ul ul padding: 0; ul space-evenly h1 {\n font-size: 6em;\n text-align: center;\n}\nnav {\n font-size: 1.5em;\n display: flex;\n justify-content: space-between;\n}\n\nul {\n border: 1px solid red;\n display: flex;\n flex-grow: 1;\n justify-content: space-evenly;\n max-width: 50%;\n padding: 0;\n}\n\nli {\n display: inline;\n margin: 0;\n padding: 0;\n} <html lang=\"en\">\n\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Media Queries</title>\n <link href=\"https://fonts.googleapis.com/css2?family=Open+Sans:wght@300&display=swap\" rel=\"stylesheet\">\n\n <link rel=\"stylesheet\" href=\"app.css\">\n</head>\n\n<body>\n <nav>\n <a href=\"#home\">Home</a>\n <ul>\n\n <li>\n <a href=\"#Home\">Learn More</a>\n </li>\n <li>\n <a href=\"#Home\">About</a>\n </li>\n <li>\n <a href=\"#Home\">Contact</a>\n </li>\n\n </ul>\n <a href=\"#signup\">Sign Up</a>\n </nav>\n <h1>Flex Box\n</h1>\n\n</body>" }, { "answer_id": 74652645, "author": "Akash Sarker", "author_id": 20655816, "author_profile": "https://Stackoverflow.com/users/20655816", "pm_score": 0, "selected": false, "text": "ul {\n border: 1px solid red;\n display: flex !important;\n flex-grow: 1;\n justify-content: space-evenly;\n max-width: 50%;\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3382461/" ]
74,652,590
<p>I have this array of all users:</p> <pre><code>let allUsers = [ { id: 1, name: &quot;Mike&quot; }, { id: 2, name: &quot;John&quot; }, { id: 3, name: &quot;Kim&quot; }, { id: 4, name: &quot;Mike&quot; } ]; </code></pre> <p>Now I have array of batches. Each batch has its own users array.</p> <pre><code>const userBatches = [ { &quot;batchId&quot;: 1, &quot;users&quot;: [ { id: 5, name: &quot;Max&quot; }, { id: 2, name: &quot;Simon&quot; } ] }, { &quot;batchId&quot;: 2, &quot;users&quot;: [ { id: 6, name: &quot;Max&quot; }, { id: 7, name: &quot;Conor&quot; } ] }, { &quot;batchId&quot;: 3, &quot;users&quot;: [ { id: 3, name: &quot;Norman&quot; } ] } ] </code></pre> <p>Here I want to push only those users that does not exists in allUsers array. (on the basis of user id not name)</p> <p>In simple words allUsers should contain the unique users. No duplicates.</p> <p>Expected response of allUsers:</p> <pre><code>[ { id: 1, name: &quot;Mike&quot; }, { id: 2, name: &quot;John&quot; }, { id: 3, name: &quot;Kim&quot; }, { id: 4, name: &quot;Mike&quot; }, { id: 5, name: &quot;Max&quot; }, { id: 6, name: &quot;Max&quot; }, { id: 7 name: &quot;Conor&quot; } ] </code></pre> <p>Here is the attached code snippet:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>let allUsers = [ { id: 1, name: "Mike" }, { id: 2, name: "John" }, { id: 3, name: "Kim" }, { id: 4, name: "Mike" } ]; const userBatches = [ { "batchId": 1, "users": [ { id: 5, name: "Max" }, { id: 2, name: "Simon" } ] }, { "batchId": 2, "users": [ { id: 6, name: "Max" }, { id: 7, name: "Conor" } ] }, { "batchId": 3, "users": [ { id: 3, name: "Norman" } ] } ]; userBatches.forEach((batch) =&gt; { console.log(batch) // if batch users does not exists allUsers array then add these users to allUsers array });</code></pre> </div> </div> </p>
[ { "answer_id": 74652692, "author": "Layhout", "author_id": 17308201, "author_profile": "https://Stackoverflow.com/users/17308201", "pm_score": 0, "selected": false, "text": "let allUsers = [{\n id: 1,\n name: \"Mike\"\n },\n {\n id: 2,\n name: \"John\"\n },\n {\n id: 3,\n name: \"Kim\"\n },\n {\n id: 4,\n name: \"Mike\"\n }\n];\n\nconst userBatches = [{\n \"batchId\": 1,\n \"users\": [{\n id: 5,\n name: \"Max\"\n },\n {\n id: 2,\n name: \"Simon\"\n }\n ]\n },\n {\n \"batchId\": 2,\n \"users\": [{\n id: 6,\n name: \"Max\"\n },\n {\n id: 7,\n name: \"Conor\"\n }\n ]\n },\n {\n \"batchId\": 3,\n \"users\": [{\n id: 3,\n name: \"Norman\"\n }]\n }\n];\n\nuserBatches.forEach(ub => {\n ub.users.forEach(ubu => {\n if (!allUsers.some(au => au.id === ubu.id)) allUsers.push(ubu)\n })\n})\n\nconsole.log(allUsers);" }, { "answer_id": 74652696, "author": "Harun Yilmaz", "author_id": 1331040, "author_profile": "https://Stackoverflow.com/users/1331040", "pm_score": 0, "selected": false, "text": "Array.some() let allUsers = [{\n id: 1,\n name: \"Mike\"\n },\n {\n id: 2,\n name: \"John\"\n },\n {\n id: 3,\n name: \"Kim\"\n },\n {\n id: 4,\n name: \"Mike\"\n }\n];\n\nconst userBatches = [{\n \"batchId\": 1,\n \"users\": [{\n id: 5,\n name: \"Max\"\n },\n {\n id: 2,\n name: \"Simon\"\n }\n ]\n },\n {\n \"batchId\": 2,\n \"users\": [{\n id: 6,\n name: \"Max\"\n },\n {\n id: 7,\n name: \"Conor\"\n }\n ]\n },\n {\n \"batchId\": 3,\n \"users\": [{\n id: 3,\n name: \"Norman\"\n }]\n }\n];\n\nuserBatches.forEach((batch) => {\n batch.users.forEach(user => {\n if (!allUsers.some(u => u.id === user.id)) {\n allUsers.push(user)\n }\n })\n});\n\nconsole.log(allUsers) Array.forEach() Array.filter() let allUsers = [{\n id: 1,\n name: \"Mike\"\n },\n {\n id: 2,\n name: \"John\"\n },\n {\n id: 3,\n name: \"Kim\"\n },\n {\n id: 4,\n name: \"Mike\"\n }\n];\n\nconst userBatches = [{\n \"batchId\": 1,\n \"users\": [{\n id: 5,\n name: \"Max\"\n },\n {\n id: 2,\n name: \"Simon\"\n }\n ]\n },\n {\n \"batchId\": 2,\n \"users\": [{\n id: 6,\n name: \"Max\"\n },\n {\n id: 7,\n name: \"Conor\"\n }\n ]\n },\n {\n \"batchId\": 3,\n \"users\": [{\n id: 3,\n name: \"Norman\"\n }]\n }\n];\n\nuserBatches.forEach((batch) => {\n allUsers = [...allUsers, ...batch.users.filter(user => !allUsers.some(u => u.id === user.id))]\n});\n\nconsole.log(allUsers)" }, { "answer_id": 74652717, "author": "AltDan", "author_id": 1269103, "author_profile": "https://Stackoverflow.com/users/1269103", "pm_score": 2, "selected": false, "text": "const uniqueUsers = userBatches.flatMap(batch => batch.users)\n .filter(user => !allUsers.some(u => u.id === user.id))\n .concat(allUsers);\n\nconsole.log(uniqueUsers);\n\n// Output: [\n// { id: 1, name: 'Mike' },\n// { id: 2, name: 'John' },\n// { id: 3, name: 'Kim' },\n// { id: 4, name: 'Mike' },\n// { id: 5, name: 'Max' },\n// { id: 6, name: 'Max' },\n// { id: 7, name: 'Conor' }\n// ]\n" }, { "answer_id": 74653074, "author": "gog", "author_id": 3494774, "author_profile": "https://Stackoverflow.com/users/3494774", "pm_score": 0, "selected": false, "text": "id=>user uniqueUsers = [...new Map([\n ...allUsers.map(u => [u.id, u]),\n ...userBatches.flatMap(b => b.users).map(u => [u.id, u])\n]).values()];\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3924832/" ]
74,652,597
<p>In laravel 9 I have table pivot table defined :</p> <pre><code> Schema::create('article_vote', function (Blueprint $table) { $table-&gt;id(); $table-&gt;foreignId('article_id')-&gt;references('id')-&gt;on('articles')-&gt;onUpdate('RESTRICT')-&gt;onDelete('CASCADE'); $table-&gt;foreignId('vote_id')-&gt;references('id')-&gt;on('votes')-&gt;onUpdate('RESTRICT')-&gt;onDelete('CASCADE'); $table-&gt;unique(['vote_id', 'article_id'], 'article_vote_vote_id_article_id_index'); ... }); </code></pre> <p>and having in both models methods with belongsToMany I can refer articles of a vote as : $voteArticles = $vote-&gt;articles;</p> <p>When I want to add some more data I do</p> <pre><code>$vote-&gt;articles()-&gt;attach($articleId, $data); </code></pre> <p>But if in database there are already data with article_id / vote_id I got Duplicate entry error.</p> <p>In which way I can check that such data in article_vote already exists ?</p> <p>Thanks!</p>
[ { "answer_id": 74652683, "author": "jrcamatog", "author_id": 11165788, "author_profile": "https://Stackoverflow.com/users/11165788", "pm_score": 0, "selected": false, "text": "syncWithoutDetaching attach $vote->articles()->syncWithoutDetaching([$articleId => $data]);\n" }, { "answer_id": 74652746, "author": "snsakib", "author_id": 9611676, "author_profile": "https://Stackoverflow.com/users/9611676", "pm_score": 1, "selected": false, "text": "wherePivot votes articles article_vote $voteArticles = $vote->articles()->wherePivot('article_id', $articleId)->wherePivot('vote_id', $voteId)->get();\nif ($voteArticles->isEmpty()) {\n // The pivot record does not exist, so you can add it here\n $vote->articles()->attach($articleId, $data);\n}\n\n wherePivot article_id vote_id" }, { "answer_id": 74652788, "author": "Taron", "author_id": 11079803, "author_profile": "https://Stackoverflow.com/users/11079803", "pm_score": 2, "selected": true, "text": "if (!$vote->articles()->where('article_id', $articleId)->exists()) {\n $vote->articles()->attach($articleId, $data);\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10873713/" ]
74,652,655
<p>Error message:</p> <p><code>/bin/sh: can't open 'usr/local/bin/entrypoint.sh': No such file or directory</code></p> <p>exited with code 2</p> <p>This is my DOCKERFILE</p> <pre class="lang-bash prettyprint-override"><code>FROM node:18-alpine as builder COPY package*.json . COPY . /app RUN npx prisma generate RUN yarn RUN yarn build # RUN echo $PWD # RUN echo $PWD/bin/sh COPY docker/entrypoint.sh /usr/local/bin/entrypoint.sh ENTRYPOINT [&quot;/bin/sh&quot;, &quot;/usr/local/bin/entrypoint.sh&quot;] </code></pre> <p>Also how do I debug by:</p> <ul> <li>Logging to the console to debug when docker file runs? I tried RUN echo $PWD to see where I am, but nothing printed.</li> <li>Seeing how the docker file structure looks like when the container has exited</li> </ul>
[ { "answer_id": 74652683, "author": "jrcamatog", "author_id": 11165788, "author_profile": "https://Stackoverflow.com/users/11165788", "pm_score": 0, "selected": false, "text": "syncWithoutDetaching attach $vote->articles()->syncWithoutDetaching([$articleId => $data]);\n" }, { "answer_id": 74652746, "author": "snsakib", "author_id": 9611676, "author_profile": "https://Stackoverflow.com/users/9611676", "pm_score": 1, "selected": false, "text": "wherePivot votes articles article_vote $voteArticles = $vote->articles()->wherePivot('article_id', $articleId)->wherePivot('vote_id', $voteId)->get();\nif ($voteArticles->isEmpty()) {\n // The pivot record does not exist, so you can add it here\n $vote->articles()->attach($articleId, $data);\n}\n\n wherePivot article_id vote_id" }, { "answer_id": 74652788, "author": "Taron", "author_id": 11079803, "author_profile": "https://Stackoverflow.com/users/11079803", "pm_score": 2, "selected": true, "text": "if (!$vote->articles()->where('article_id', $articleId)->exists()) {\n $vote->articles()->attach($articleId, $data);\n}\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5860306/" ]
74,652,669
<p>I want to write a C# code from UML Diagram as shown below. However, I come across this attribute &quot;age: Integer{0&lt;=age&lt;=150}&quot;. I will circle for you. May I know what it means? and How can we convert it to C# code? <a href="https://i.stack.imgur.com/DAtH5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DAtH5.png" alt="C#" /></a></p>
[ { "answer_id": 74653389, "author": "qwerty_so", "author_id": 3379653, "author_profile": "https://Stackoverflow.com/users/3379653", "pm_score": 2, "selected": false, "text": "<constraint> ::= ‘{‘ [ <name> ‘:’ ] <boolean-expression> ‘ }’" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17239329/" ]
74,652,671
<p>I have a multi-index data set with 100 cases, and each case has 5 questions. Each question was scored by 2 raters.</p> <pre><code>case question rater1 rater2 1 1 1 1 1 2 1 0 1 3 1 1 1 4 1 1 1 5 0 0 2 1 0 1 2 2 1 1 2 3 1 1 2 4 1 0 2 5 0 0 3 1 0 0 3 2 1 0 3 3 1 1 3 4 1 1 3 5 0 1 ... </code></pre> <p>I want to sum question 1, 2, 3 in each case as 6; question 4, 5 in each case as 7; question 1~5 in each case as 8. Then insert the value at the end of each case, such as</p> <pre><code>case question rater1 rater2 1 1 1 1 1 2 1 0 1 3 1 1 1 4 1 1 1 5 0 0 1 6 3 2 1 7 1 1 1 8 4 3 2 1 0 1 2 2 1 1 2 3 1 1 2 4 1 0 2 5 0 0 2 6 2 3 2 7 1 0 2 8 3 3 3 1 0 0 3 2 1 0 3 3 1 1 3 4 1 1 3 5 0 1 3 6 2 1 3 7 1 2 3 8 3 3 ... </code></pre> <p>I am unsure how to achieve it.</p>
[ { "answer_id": 74653055, "author": "Allan Cameron", "author_id": 12500315, "author_profile": "https://Stackoverflow.com/users/12500315", "pm_score": 1, "selected": false, "text": "library(dplyr)\n\ndf %>%\n group_by(case) %>%\n summarize(rater1 = c(rater1, \n sum(rater1[question %in% 1:3]),\n sum(rater1[question %in% 4:5]),\n sum(rater1)),\n rater2 = c(rater2, \n sum(rater2[question %in% 1:3]),\n sum(rater2[question %in% 4:5]),\n sum(rater2)),\n question = 1:8, .groups = 'drop') %>%\n select(1, 4, 2, 3) %>%\n as.data.frame()\n#> case question rater1 rater2\n#> 1 1 1 1 1\n#> 2 1 2 1 0\n#> 3 1 3 1 1\n#> 4 1 4 1 1\n#> 5 1 5 0 0\n#> 6 1 6 3 2\n#> 7 1 7 1 1\n#> 8 1 8 4 3\n#> 9 2 1 0 1\n#> 10 2 2 1 1\n#> 11 2 3 1 1\n#> 12 2 4 1 0\n#> 13 2 5 0 0\n#> 14 2 6 2 3\n#> 15 2 7 1 0\n#> 16 2 8 3 3\n#> 17 3 1 0 0\n#> 18 3 2 1 0\n#> 19 3 3 1 1\n#> 20 3 4 1 1\n#> 21 3 5 0 1\n#> 22 3 6 2 1\n#> 23 3 7 1 2\n#> 24 3 8 3 3\n" }, { "answer_id": 74653125, "author": "Limey", "author_id": 13434871, "author_profile": "https://Stackoverflow.com/users/13434871", "pm_score": 3, "selected": true, "text": "library(tidyverse)\n\naddSummaryRow <- function(data, qFilter, newIndex) {\n data %>%\n bind_rows(\n data %>% \n pivot_longer(starts_with(\"rater\")) %>% \n filter(question %in% qFilter) %>% \n group_by(case, name) %>% \n summarise(value=sum(value), .groups=\"drop\") %>% \n pivot_wider(id_cols=c(case), names_from=name, values_from=value) %>% \n mutate(question=newIndex)\n ) %>%\n arrange(case, question)\n}\n\nd %>% \n addSummaryRow(1:3, 6) %>% \n addSummaryRow(4:5, 7) %>% \n addSummaryRow(1:5, 8)\n# A tibble: 24 × 4\n case question rater1 rater2\n <int> <dbl> <int> <int>\n 1 1 1 1 1\n 2 1 2 1 0\n 3 1 3 1 1\n 4 1 4 1 1\n 5 1 5 0 0\n 6 1 6 3 2\n 7 1 7 1 1\n 8 1 8 4 3\n 9 2 1 0 1\n10 2 2 1 1\n# … with 14 more rows\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20081864/" ]
74,652,690
<p>i need help with my app since iam new to flutter. so i have a button that suppossed to have a text inside it, but when i run my app, the text isnt inside the button, i dont know how to fix this. so here is my app when i run it:</p> <p><a href="https://i.stack.imgur.com/P36wn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/P36wn.png" alt="enter image description here" /></a></p> <p>i use MyButton for the button and text, here is my botton code</p> <pre><code> _addTaskBar(){ return Container( margin: const EdgeInsets.only(left: 20, right: 20, top: 5), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Container( margin: const EdgeInsets.symmetric(horizontal: 20), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(DateFormat.yMMMMd().format(DateTime.now()), style: subHeadingStyle, ), Text(&quot;Today&quot;, style: headingStyle, ) ], ), ), MyButton(label: &quot;Add Reminder&quot;, onTap: ()=&gt;Get.to(AddReminderPage())) ], ), ); } </code></pre> <p>here is my MyButton code</p> <pre><code>import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:medreminder/Reminder/ui/theme.dart'; class MyButton extends StatelessWidget { final String label; final Function()? onTap; const MyButton({super.key, required this.label, required this.onTap}); @override Widget build(BuildContext context) { return GestureDetector( onTap: onTap, child:Container( width: 100, height: 50, decoration: BoxDecoration( borderRadius: BorderRadius.circular(20), color: Color(0xFFFB7B8E), ), child: Text( label, style: TextStyle( color: Colors.white, ), ), ) , ); } } </code></pre> <p>any help would mean so much to me. thankyou</p>
[ { "answer_id": 74653055, "author": "Allan Cameron", "author_id": 12500315, "author_profile": "https://Stackoverflow.com/users/12500315", "pm_score": 1, "selected": false, "text": "library(dplyr)\n\ndf %>%\n group_by(case) %>%\n summarize(rater1 = c(rater1, \n sum(rater1[question %in% 1:3]),\n sum(rater1[question %in% 4:5]),\n sum(rater1)),\n rater2 = c(rater2, \n sum(rater2[question %in% 1:3]),\n sum(rater2[question %in% 4:5]),\n sum(rater2)),\n question = 1:8, .groups = 'drop') %>%\n select(1, 4, 2, 3) %>%\n as.data.frame()\n#> case question rater1 rater2\n#> 1 1 1 1 1\n#> 2 1 2 1 0\n#> 3 1 3 1 1\n#> 4 1 4 1 1\n#> 5 1 5 0 0\n#> 6 1 6 3 2\n#> 7 1 7 1 1\n#> 8 1 8 4 3\n#> 9 2 1 0 1\n#> 10 2 2 1 1\n#> 11 2 3 1 1\n#> 12 2 4 1 0\n#> 13 2 5 0 0\n#> 14 2 6 2 3\n#> 15 2 7 1 0\n#> 16 2 8 3 3\n#> 17 3 1 0 0\n#> 18 3 2 1 0\n#> 19 3 3 1 1\n#> 20 3 4 1 1\n#> 21 3 5 0 1\n#> 22 3 6 2 1\n#> 23 3 7 1 2\n#> 24 3 8 3 3\n" }, { "answer_id": 74653125, "author": "Limey", "author_id": 13434871, "author_profile": "https://Stackoverflow.com/users/13434871", "pm_score": 3, "selected": true, "text": "library(tidyverse)\n\naddSummaryRow <- function(data, qFilter, newIndex) {\n data %>%\n bind_rows(\n data %>% \n pivot_longer(starts_with(\"rater\")) %>% \n filter(question %in% qFilter) %>% \n group_by(case, name) %>% \n summarise(value=sum(value), .groups=\"drop\") %>% \n pivot_wider(id_cols=c(case), names_from=name, values_from=value) %>% \n mutate(question=newIndex)\n ) %>%\n arrange(case, question)\n}\n\nd %>% \n addSummaryRow(1:3, 6) %>% \n addSummaryRow(4:5, 7) %>% \n addSummaryRow(1:5, 8)\n# A tibble: 24 × 4\n case question rater1 rater2\n <int> <dbl> <int> <int>\n 1 1 1 1 1\n 2 1 2 1 0\n 3 1 3 1 1\n 4 1 4 1 1\n 5 1 5 0 0\n 6 1 6 3 2\n 7 1 7 1 1\n 8 1 8 4 3\n 9 2 1 0 1\n10 2 2 1 1\n# … with 14 more rows\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20229067/" ]
74,652,726
<p>I have a search bar component Search.jsx</p> <pre><code>import { useEffect, useState } from 'react' export default function Search() { const [query, setQuery] = useState('') return ( &lt;div className={styles.container}&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;https://fonts.googleapis.com/icon?family=Material+Icons&quot;&gt;&lt;/link&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;https://fonts.googleapis.com/css?family=Inter&quot; /&gt; &lt;form className={styles.search_bar} action=&quot;&quot;&gt; &lt;input type=&quot;text&quot; placeholder=&quot;e.g. Adobo&quot; onChange={event =&gt; setQuery(event.target.value)} /&gt; &lt;button&gt;&lt;i className=&quot;material-icons&quot;&gt;search&lt;/i&gt;&lt;/button&gt; &lt;/form&gt; &lt;/div&gt; ) } </code></pre> <p>and I want to filter the results that show up in my Card.jsx</p> <pre><code>import styles from &quot;./Card.module.css&quot;; import { useEffect, useState } from 'react' export default function Card() { const [menus, setMenus] = useState([]) useEffect(() =&gt; { fetch(&quot;https://api.jsonbin.io/v3/b/63863ca77966e84526cf79f9&quot;) .then((res) =&gt; res.json()) .then((data) =&gt; { setMenus(data) }) }, []) return ( &lt;div className= {styles.card_container}&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;https://fonts.googleapis.com/css?family=Inter&quot; /&gt; {menus.record?.map( menu =&gt; ( &lt;div className={styles.container}&gt; &lt;div key ={menu.title} className={styles.img_container}&gt; &lt;img className={styles.card_img} src={menu.image} alt=&quot;Food Image&quot;/&gt; &lt;/div&gt; &lt;h1 className={styles.card_title}&gt;{menu.title}&lt;/h1&gt; &lt;h1 className={styles.card_body}&gt; {menu.body} &lt;/h1&gt; &lt;h1 className={styles.card_price}&gt;{menu.price}&lt;/h1&gt; &lt;button className={styles.card_button}&gt; Add to Order &lt;/button&gt; &lt;/div&gt; ))} &lt;/div&gt; ) } </code></pre> <p>I tried using the filter method but I really don't know how to implement it between two components.</p>
[ { "answer_id": 74652860, "author": "armful", "author_id": 20664163, "author_profile": "https://Stackoverflow.com/users/20664163", "pm_score": 0, "selected": false, "text": "Card Search Search Card Search onSubmit query query Card filteredMenus query Card menus" }, { "answer_id": 74653063, "author": "Amirhossein", "author_id": 11342834, "author_profile": "https://Stackoverflow.com/users/11342834", "pm_score": 0, "selected": false, "text": "export const CardContext = React.createContext();\nexport function CardProvider({ children }) {\n const [menus, setMenus] = useState([]);\n\n return (\n <CardContext.Provider value={{menus, setMenus}}>\n { children }\n </CardContext.Provider>\n )\n}\n const { menus, setMenus } = useContext(CardContext);\n const { menus, setMenus } = useContext(CardContext);\n\nconst handleSearch = () => {\n let newMenus = [...menus];\n newMenus.record = newMenus.record.filter((menuRecord) => menuRecord.title.includes(query));\n setMenus(newMenus);\n}\n <button onClick={handleSearch}><i className=\"material-icons\">search</i></button>\n" }, { "answer_id": 74653086, "author": "Jonathan Wieben", "author_id": 7879109, "author_profile": "https://Stackoverflow.com/users/7879109", "pm_score": 2, "selected": true, "text": "query Card query query setQuery function App() {\n const [query, setQuery] = useState('')\n\n return (\n <div>\n <Card query={query} />\n <Search query={query} setQuery={setQuery} />\n </div>\n )\n}\n Search function Search({ query, setQuery }) {\n Card function Card({ query }) {\n ...\n {menus.record?.filter(el => /* some filtering with query */).map\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15913974/" ]
74,652,727
<p>I have an array of <code>FormGroup</code>s which all holds one <code>FormControl</code> called <code>checked</code> which is represented as a checkbox input in the template.</p> <p>This array <code>formGroups$</code> is computed from another <code>Observable</code> called <code>items$</code>.</p> <pre class="lang-js prettyprint-override"><code>// component.ts constructor(private fb: FormBuilder) {} items$ = of([{ whatever: 'not used' }, { something: 'doesnt matter' }]); // doesn't work! formGroups$: Observable&lt;FormGroup&lt;{ checked: FormControl&lt;boolean&gt; }&gt;[]&gt; = this.items$.pipe( map((items) =&gt; { const array: FormGroup[] = []; for (const item of items) { const formGroup = this.fb.group({}); formGroup.addControl('checked', new FormControl(false)); array.push(formGroup); } return array; }) ); allChecked$: Observable&lt;boolean&gt; = this.formGroups$.pipe( switchMap((formGroups) =&gt; { const valueChangesArray: Observable&lt;boolean&gt;[] = []; formGroups.forEach((formGroup) =&gt; { valueChangesArray.push( formGroup .get('checked') .valueChanges.pipe(startWith(formGroup.get('checked').value)) ); }); return combineLatest(valueChangesArray); }), map((checkedValues) =&gt; { console.log(checkedValues); for (const isChecked of checkedValues) { if (!isChecked) { return false; } } return true; }) ); </code></pre> <pre class="lang-html prettyprint-override"><code>&lt;!-- component.html --&gt; &lt;ng-container *ngFor=&quot;let formGroup of formGroups$ | async; index as i&quot;&gt; &lt;label&gt; &lt;input type=&quot;checkbox&quot; [formControl]=&quot;formGroup.controls.checked&quot; /&gt; {{ i }} &lt;/label&gt; &lt;/ng-container&gt; &lt;p&gt;allChecked: {{ allChecked$ | async }}&lt;/p&gt; </code></pre> <p>Example see also in Stackblitz: <a href="https://stackblitz.com/edit/angular-ivy-xfpywy?file=src%2Fapp%2Fapp.component.ts" rel="nofollow noreferrer">https://stackblitz.com/edit/angular-ivy-xfpywy?file=src%2Fapp%2Fapp.component.ts</a></p> <p>Now when I try to compute if all those checkboxes are checked with <code>allChecked$</code>, which combines all Observables from each <code>FormGroup</code>s <code>formControl.valueChanges</code>, the <code>map</code> in there only gets triggered once and not as expected every time the value of a Checkbox changes:</p> <p><a href="https://i.stack.imgur.com/PGJSC.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PGJSC.gif" alt="enter image description here" /></a></p> <p>If I change <code>formGroup$</code> to a simpler static solution, the value <code>allChecked$</code> is computed correctly every time:</p> <pre class="lang-js prettyprint-override"><code> // works! formGroups$: Observable&lt;FormGroup&lt;{ checked: FormControl&lt;boolean&gt; }&gt;[]&gt; = of([ new FormGroup({ checked: new FormControl(false), }), new FormGroup({ checked: new FormControl(true), }), ]); </code></pre> <p>You can easily reproduce it in this StackBlitz: <a href="https://stackblitz.com/edit/angular-ivy-xfpywy?file=src%2Fapp%2Fapp.component.ts" rel="nofollow noreferrer">https://stackblitz.com/edit/angular-ivy-xfpywy?file=src%2Fapp%2Fapp.component.ts</a></p> <p>How do I compute this boolean <code>allChecked$</code> with an array of dynamically created <code>FormGroup</code>s?</p>
[ { "answer_id": 74652903, "author": "snsakib", "author_id": 9611676, "author_profile": "https://Stackoverflow.com/users/9611676", "pm_score": 0, "selected": false, "text": "of items$ of formGroups$ from of from formGroups$ items$ from // component.ts\nconstructor(private fb: FormBuilder) {}\n\nitems$ = from([[{ whatever: 'not used' }, { something: 'doesnt matter' }]]);\n\nformGroups$: Observable<FormGroup<{ checked: FormControl<boolean> }>[]> =\n this.items$.pipe(\n map((items) => {\n const array: FormGroup[] = [];\n for (const item of items) {\n const formGroup = this.fb.group({});\n formGroup.addControl('checked', new FormControl(false));\n array.push(formGroup);\n }\n return array;\n })\n );\n\nallChecked$: Observable<boolean> = this.formGroups$.pipe(\n switchMap((formGroups) => {\n const valueChangesArray: Observable<boolean>[] = [];\n formGroups.forEach((formGroup) => {\n valueChangesArray.push(\n formGroup\n .get('checked')\n .valueChanges.pipe(startWith(formGroup.get('checked').value))\n );\n });\n return combineLatest(valueChangesArray);\n }),\n map((checkedValues) => {\n console.log(checkedValues);\n for (const isChecked of checkedValues) {\n if (!isChecked) {\n return false;\n }\n }\n return true;\n })\n);\n\n" }, { "answer_id": 74653064, "author": "Eliseo", "author_id": 8558186, "author_profile": "https://Stackoverflow.com/users/8558186", "pm_score": 1, "selected": false, "text": "forms:any[]=[] \n formGroups$ =\n this.items$.pipe(\n ...\n ,\n tap(res=>{\n this.forms[this.forms.length]=res\n })\n {{forms[0]==forms[1]}} formGroups$ =\n this.items$.pipe(\n ...\n ,\n sharedReply(1)\n)\n allChecked$: Observable<boolean>;\n formGroups$: Observable<FormGroup<{ checked: FormControl<boolean> }>[]> =\n this.items$.pipe(\n map((items) => {\n const array: FormGroup[] = [];\n for (const item of items) {\n const formGroup = this.fb.group({});\n formGroup.addControl('checked', new FormControl(false));\n array.push(formGroup);\n }\n return array;\n }),\n tap((formGroups: any[]) => { //here we create the Observable\n //see that \"formGroups\" are your array of FormGroups\n\n const valueChangesArray: Observable<boolean>[] = [];\n formGroups.forEach((formGroup) => {\n valueChangesArray.push(\n formGroup\n .get('checked')\n .valueChanges.pipe(startWith(formGroup.get('checked').value))\n );\n });\n this.allChecked$ = combineLatest(valueChangesArray).pipe(\n map((checkedValues) => {\n for (const isChecked of checkedValues) {\n if (!isChecked) {\n return false;\n }\n }\n return true;\n })\n );\n })\n );\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7987318/" ]
74,652,761
<p>I have the following tibble:</p> <pre><code>df &lt;- tibble( x = c(5, 5), Column_1 = c(0.5, 0.5), Column_2 = c(0.75, 0.75)) </code></pre> <p>I would like to create two new columns, which are the product of column x and Column_1 and x and Column_2 respectively. These columns should be named ABC_1 and ABC_2.</p> <p>I tried the following code:</p> <pre><code>df &lt;- mutate(df, across(starts_with(&quot;Column_&quot;), function(y) y * x, .names = paste0(&quot;ABC&quot;, gsub(&quot;Column_&quot;, &quot;&quot;, &quot;{.col}&quot;)) )) </code></pre> <p>However, this resulted in the following table:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>x</th> <th>Column_1</th> <th>Column_2</th> <th>ABCColumn_1</th> <th>ABCColumn_2</th> </tr> </thead> <tbody> <tr> <td>5</td> <td>0.5</td> <td>0.75</td> <td>2.5</td> <td>3.75</td> </tr> <tr> <td>5</td> <td>0.5</td> <td>0.75</td> <td>2.5</td> <td>3.75</td> </tr> </tbody> </table> </div> <p>The resulting columns are now named ABCColumn_1 and ABCColumn_2. Somehow creating a substring with gsub did not work. My desired output is:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>x</th> <th>Column_1</th> <th>Column_2</th> <th>ABC_1</th> <th>ABC_2</th> </tr> </thead> <tbody> <tr> <td>5</td> <td>0.5</td> <td>0.75</td> <td>2.5</td> <td>3.75</td> </tr> <tr> <td>5</td> <td>0.5</td> <td>0.75</td> <td>2.5</td> <td>3.75</td> </tr> </tbody> </table> </div> <p>Any ideas how I can elegantly solve this problem? In reality, the number of columns is variable, so I cannot hardcode 1 and 2 into my script.</p> <p>EDIT: Sorry, my generic columns names were not well chosen. I chose a different one to show that the old and the new column names should not be related in any way except for the number.</p>
[ { "answer_id": 74652903, "author": "snsakib", "author_id": 9611676, "author_profile": "https://Stackoverflow.com/users/9611676", "pm_score": 0, "selected": false, "text": "of items$ of formGroups$ from of from formGroups$ items$ from // component.ts\nconstructor(private fb: FormBuilder) {}\n\nitems$ = from([[{ whatever: 'not used' }, { something: 'doesnt matter' }]]);\n\nformGroups$: Observable<FormGroup<{ checked: FormControl<boolean> }>[]> =\n this.items$.pipe(\n map((items) => {\n const array: FormGroup[] = [];\n for (const item of items) {\n const formGroup = this.fb.group({});\n formGroup.addControl('checked', new FormControl(false));\n array.push(formGroup);\n }\n return array;\n })\n );\n\nallChecked$: Observable<boolean> = this.formGroups$.pipe(\n switchMap((formGroups) => {\n const valueChangesArray: Observable<boolean>[] = [];\n formGroups.forEach((formGroup) => {\n valueChangesArray.push(\n formGroup\n .get('checked')\n .valueChanges.pipe(startWith(formGroup.get('checked').value))\n );\n });\n return combineLatest(valueChangesArray);\n }),\n map((checkedValues) => {\n console.log(checkedValues);\n for (const isChecked of checkedValues) {\n if (!isChecked) {\n return false;\n }\n }\n return true;\n })\n);\n\n" }, { "answer_id": 74653064, "author": "Eliseo", "author_id": 8558186, "author_profile": "https://Stackoverflow.com/users/8558186", "pm_score": 1, "selected": false, "text": "forms:any[]=[] \n formGroups$ =\n this.items$.pipe(\n ...\n ,\n tap(res=>{\n this.forms[this.forms.length]=res\n })\n {{forms[0]==forms[1]}} formGroups$ =\n this.items$.pipe(\n ...\n ,\n sharedReply(1)\n)\n allChecked$: Observable<boolean>;\n formGroups$: Observable<FormGroup<{ checked: FormControl<boolean> }>[]> =\n this.items$.pipe(\n map((items) => {\n const array: FormGroup[] = [];\n for (const item of items) {\n const formGroup = this.fb.group({});\n formGroup.addControl('checked', new FormControl(false));\n array.push(formGroup);\n }\n return array;\n }),\n tap((formGroups: any[]) => { //here we create the Observable\n //see that \"formGroups\" are your array of FormGroups\n\n const valueChangesArray: Observable<boolean>[] = [];\n formGroups.forEach((formGroup) => {\n valueChangesArray.push(\n formGroup\n .get('checked')\n .valueChanges.pipe(startWith(formGroup.get('checked').value))\n );\n });\n this.allChecked$ = combineLatest(valueChangesArray).pipe(\n map((checkedValues) => {\n for (const isChecked of checkedValues) {\n if (!isChecked) {\n return false;\n }\n }\n return true;\n })\n );\n })\n );\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13824985/" ]
74,652,785
<p>i have a data set with 37 columns and 230k rows</p> <p>i am trying using seaborn to histogram every column</p> <p>i have not yet cleaned my data</p> <p>here is my code</p> <pre><code>for i in X.columns: plt.figure() ax = sns.histplot(data=df,x=i) </code></pre> <p>i got also this <code>File C:\ProgramData\Anaconda3\lib\site-packages\numpy\core\function_base.py:135 in linspace y = _nx.arange(0, num, dtype=dt).reshape((-1,) + (1,) * ndim(delta))</code></p> <p>any solution for this please</p>
[ { "answer_id": 74652903, "author": "snsakib", "author_id": 9611676, "author_profile": "https://Stackoverflow.com/users/9611676", "pm_score": 0, "selected": false, "text": "of items$ of formGroups$ from of from formGroups$ items$ from // component.ts\nconstructor(private fb: FormBuilder) {}\n\nitems$ = from([[{ whatever: 'not used' }, { something: 'doesnt matter' }]]);\n\nformGroups$: Observable<FormGroup<{ checked: FormControl<boolean> }>[]> =\n this.items$.pipe(\n map((items) => {\n const array: FormGroup[] = [];\n for (const item of items) {\n const formGroup = this.fb.group({});\n formGroup.addControl('checked', new FormControl(false));\n array.push(formGroup);\n }\n return array;\n })\n );\n\nallChecked$: Observable<boolean> = this.formGroups$.pipe(\n switchMap((formGroups) => {\n const valueChangesArray: Observable<boolean>[] = [];\n formGroups.forEach((formGroup) => {\n valueChangesArray.push(\n formGroup\n .get('checked')\n .valueChanges.pipe(startWith(formGroup.get('checked').value))\n );\n });\n return combineLatest(valueChangesArray);\n }),\n map((checkedValues) => {\n console.log(checkedValues);\n for (const isChecked of checkedValues) {\n if (!isChecked) {\n return false;\n }\n }\n return true;\n })\n);\n\n" }, { "answer_id": 74653064, "author": "Eliseo", "author_id": 8558186, "author_profile": "https://Stackoverflow.com/users/8558186", "pm_score": 1, "selected": false, "text": "forms:any[]=[] \n formGroups$ =\n this.items$.pipe(\n ...\n ,\n tap(res=>{\n this.forms[this.forms.length]=res\n })\n {{forms[0]==forms[1]}} formGroups$ =\n this.items$.pipe(\n ...\n ,\n sharedReply(1)\n)\n allChecked$: Observable<boolean>;\n formGroups$: Observable<FormGroup<{ checked: FormControl<boolean> }>[]> =\n this.items$.pipe(\n map((items) => {\n const array: FormGroup[] = [];\n for (const item of items) {\n const formGroup = this.fb.group({});\n formGroup.addControl('checked', new FormControl(false));\n array.push(formGroup);\n }\n return array;\n }),\n tap((formGroups: any[]) => { //here we create the Observable\n //see that \"formGroups\" are your array of FormGroups\n\n const valueChangesArray: Observable<boolean>[] = [];\n formGroups.forEach((formGroup) => {\n valueChangesArray.push(\n formGroup\n .get('checked')\n .valueChanges.pipe(startWith(formGroup.get('checked').value))\n );\n });\n this.allChecked$ = combineLatest(valueChangesArray).pipe(\n map((checkedValues) => {\n for (const isChecked of checkedValues) {\n if (!isChecked) {\n return false;\n }\n }\n return true;\n })\n );\n })\n );\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20110385/" ]
74,652,847
<p>wring this batch of code and geting syntax exxor what seems to be the problem File &quot;&quot;, line 2 if color == 1: color_sq = ^ SyntaxError: invalid syntax</p> <pre><code>def calc_color(data, color=None): if color == 1: color_sq = ['#dadaebFF','#bcbddcF0','#9e9ac8F0', '#807dbaF0','#6a51a3F0','#54278fF0']; colors = 'Purples'; elif color == 2: color_sq = ['#c7e9b4','#7fcdbb','#41b6c4', '#1d91c0','#225ea8','#253494']; colors = 'YlGnBu'; elif color == 3: color_sq = ['#f7f7f7','#d9d9d9','#bdbdbd', '#969696','#636363','#252525']; colors = 'Greys'; elif color == 9: color_sq = ['#ff0000','#ff0000','#ff0000', '#ff0000','#ff0000','#ff0000'] else: color_sq = ['#ffffd4','#fee391','#fec44f', '#fe9929','#d95f0e','#993404']; colors = 'YlOrBr'; new_data, bins = pd.qcut(data, 6, retbins=True, labels=list(range(6))) color_ton = [] for val in new_data: color_ton.append(color_sq[val]) if color != 9: colors = sns.color_palette(colors, n_colors=6) sns.palplot(colors, 0.6); for i in range(6): print (&quot;\n&quot;+str(i+1)+': '+str(int(bins[i]))+ &quot; =&gt; &quot;+str(int(bins[i+1])-1), end =&quot; &quot;) print(&quot;\n\n 1 2 3 4 5 6&quot;) return color_ton, bins; </code></pre>
[ { "answer_id": 74652903, "author": "snsakib", "author_id": 9611676, "author_profile": "https://Stackoverflow.com/users/9611676", "pm_score": 0, "selected": false, "text": "of items$ of formGroups$ from of from formGroups$ items$ from // component.ts\nconstructor(private fb: FormBuilder) {}\n\nitems$ = from([[{ whatever: 'not used' }, { something: 'doesnt matter' }]]);\n\nformGroups$: Observable<FormGroup<{ checked: FormControl<boolean> }>[]> =\n this.items$.pipe(\n map((items) => {\n const array: FormGroup[] = [];\n for (const item of items) {\n const formGroup = this.fb.group({});\n formGroup.addControl('checked', new FormControl(false));\n array.push(formGroup);\n }\n return array;\n })\n );\n\nallChecked$: Observable<boolean> = this.formGroups$.pipe(\n switchMap((formGroups) => {\n const valueChangesArray: Observable<boolean>[] = [];\n formGroups.forEach((formGroup) => {\n valueChangesArray.push(\n formGroup\n .get('checked')\n .valueChanges.pipe(startWith(formGroup.get('checked').value))\n );\n });\n return combineLatest(valueChangesArray);\n }),\n map((checkedValues) => {\n console.log(checkedValues);\n for (const isChecked of checkedValues) {\n if (!isChecked) {\n return false;\n }\n }\n return true;\n })\n);\n\n" }, { "answer_id": 74653064, "author": "Eliseo", "author_id": 8558186, "author_profile": "https://Stackoverflow.com/users/8558186", "pm_score": 1, "selected": false, "text": "forms:any[]=[] \n formGroups$ =\n this.items$.pipe(\n ...\n ,\n tap(res=>{\n this.forms[this.forms.length]=res\n })\n {{forms[0]==forms[1]}} formGroups$ =\n this.items$.pipe(\n ...\n ,\n sharedReply(1)\n)\n allChecked$: Observable<boolean>;\n formGroups$: Observable<FormGroup<{ checked: FormControl<boolean> }>[]> =\n this.items$.pipe(\n map((items) => {\n const array: FormGroup[] = [];\n for (const item of items) {\n const formGroup = this.fb.group({});\n formGroup.addControl('checked', new FormControl(false));\n array.push(formGroup);\n }\n return array;\n }),\n tap((formGroups: any[]) => { //here we create the Observable\n //see that \"formGroups\" are your array of FormGroups\n\n const valueChangesArray: Observable<boolean>[] = [];\n formGroups.forEach((formGroup) => {\n valueChangesArray.push(\n formGroup\n .get('checked')\n .valueChanges.pipe(startWith(formGroup.get('checked').value))\n );\n });\n this.allChecked$ = combineLatest(valueChangesArray).pipe(\n map((checkedValues) => {\n for (const isChecked of checkedValues) {\n if (!isChecked) {\n return false;\n }\n }\n return true;\n })\n );\n })\n );\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20621132/" ]
74,652,852
<p>In a spare-time project of mine, I'm implementing a duplex transcoding framework. The most essential functions I'm writing are <code>Read</code> and <code>Write</code> functions, which are to be called on different threads, to exchange data like Unix Pipe/FIFO.</p> <p>Because they're on different threads, I need to be sure that they're properly synchronized, and that my use of synchronization APIs are correct.</p> <p>When encountering EOF, I call <code>pthread_{condvar,mutex}_destroy</code> functions to destroy 2 condition variables and 1 mutex. The 2 condvars are used to blocks the read and write call respectively, until input/output space are available; the mutex is the big mutex that protects the entire duplex object.</p> <p>The questions are:</p> <ol> <li><p>Is it safe to signal a condition variable after it had been destroyed?</p> </li> <li><p>Is it safe to unlock a mutex after it had been destroyed?</p> </li> <li><p>Are there similar guarantees on other threading APIs (such as C11 Threads and C++ Threads)?</p> </li> </ol>
[ { "answer_id": 74653067, "author": "doron", "author_id": 232918, "author_profile": "https://Stackoverflow.com/users/232918", "pm_score": 1, "selected": false, "text": "join" }, { "answer_id": 74672217, "author": "John Bollinger", "author_id": 2402272, "author_profile": "https://Stackoverflow.com/users/2402272", "pm_score": 3, "selected": true, "text": "pthread_cond_init() pthread_mutex_init()" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6230282/" ]
74,652,858
<p>my code goes through quite a large number of arrays where everything is sorted so that it is in the right place. It flies 3 times through the input data to sort everything well, which causes empty arrays to appear. I try to delete them with the following code, but in some cases the code leaves me 1 empty array</p> <p>The following code works correctly in most cases, but in some cases 1 array is left undeleted</p> <pre><code>chartTypeData.forEach((item: any, index: any) =&gt; { if (item.length === 0) { chartTypeData.splice(index, 1); } }); </code></pre> <p>Full code:</p> <pre><code>for (let i = 0; i &lt; chartType.length; i++) { const chartItem = chartsData?.product?.data[0].attributes.product_charts.data; for (let j = 0; j &lt; chartCategory.length; j++) { for (let k = 0; k &lt; country.length; k++) { chartTypeData.push( chartItem.filter((item: any) =&gt; { return ( item.attributes.type === chartType[i] &amp;&amp; item.attributes.chartCategory === chartCategory[j] &amp;&amp; item.attributes.country === country[k] ); }) ); } chartTypeData[i].sort((a: any, b: any) =&gt; { return new Date(a.attributes.date).getTime() - new Date(b.attributes.date).getTime(); }); } } chartTypeData.forEach((item: any, index: any) =&gt; { if (item.length === 0) { chartTypeData.splice(index, 1); } }); </code></pre>
[ { "answer_id": 74653067, "author": "doron", "author_id": 232918, "author_profile": "https://Stackoverflow.com/users/232918", "pm_score": 1, "selected": false, "text": "join" }, { "answer_id": 74672217, "author": "John Bollinger", "author_id": 2402272, "author_profile": "https://Stackoverflow.com/users/2402272", "pm_score": 3, "selected": true, "text": "pthread_cond_init() pthread_mutex_init()" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13613817/" ]
74,652,871
<p>I am trying to access packages outside of the current package using setup.py. My project structure looks like this.</p> <pre><code>Example1/ |-- submodule1/ | |-- __init__.py | |-- main/ | |-- __init__.py | |-- hello.py | |-- setup.py |-- submodule2/ | |-- __init__.py | |-- main/ | |-- __init__.py | |-- world.py | |-- setup.py |-- submodule3/ | |-- __init__.py | |-- main/ | |-- __init__.py | |-- sample.py | |-- setup.py |-- utils/ | |-- __init__.py | |-- util_code1.py | |-- util_code2.py </code></pre> <p>I am trying to include utils package dir in setup.py of submodules.</p> <p>here is how my setup.py looks</p> <pre><code>setup( name='sample_package', description='my test wheel', #packages=find_packages(), packages=['main', '../../utils'] entry_points={ 'group_1': 'module1=Example1.main.hello:method1' } ], include_package_data=True, ) </code></pre> <p>When I run command inside any of submodule <code>python setup.py bdist_wheel</code> to create a wheel for any submodule I am getting the following error.</p> <pre><code>error: package directory '../../utils' does not exist </code></pre>
[ { "answer_id": 74678105, "author": "Ange Loron", "author_id": 4617824, "author_profile": "https://Stackoverflow.com/users/4617824", "pm_score": -1, "selected": false, "text": "package_dir={\n 'main': 'main',\n 'utils': '../../utils'\n}\n setup(\n name='sample_package',\n description='my test wheel',\n #packages=find_packages(), \n packages=['main', 'utils'],\n package_dir={\n 'main': 'main',\n 'utils': '../../utils'\n },\n entry_points={\n 'group_1': 'module1=Example1.main.hello:method1'\n }\n ],\n include_package_data=True,\n)\n" }, { "answer_id": 74678944, "author": "Khaoz-07", "author_id": 20171262, "author_profile": "https://Stackoverflow.com/users/20171262", "pm_score": 0, "selected": false, "text": "setup(\n name='sample_package',\n description='my test wheel',\n #packages=find_packages(), \n packages=['main', 'utils']\n entry_points={\n 'group_1': 'module1=Example1.main.hello:method1'\n }\n ],\n include_package_data=True,\n)\n from setuptools import find_packages\n\nsetup(\n name='sample_package',\n description='my test wheel',\n packages=find_packages(), \n entry_points={\n 'group_1': 'module1=Example1.main.hello:method1'\n }\n ],\n include_package_data=True,\n)\n" }, { "answer_id": 74680970, "author": "zeefxd", "author_id": 20683957, "author_profile": "https://Stackoverflow.com/users/20683957", "pm_score": 0, "selected": false, "text": "#It looks like you are trying to include the utils package in the setup.py file of your submodules. However, the way you have specified the package in the setup function is incorrect.\n\n#To include a package in your setup.py file, you need to specify the package name and its path relative to the setup.py file. In your case, the utils package is located at ../../utils, but this is not a valid package name. Instead, you need to specify the package name, which is utils, and its relative path, which is ../../utils.\n\n#Here is how you can fix this error:\n\nsetup(\n name='sample_package',\n description='my test wheel',\n #packages=find_packages(), \n packages=['main', 'utils'],\n package_dir={'utils': '../../utils'},\n entry_points={\n 'group_1': 'module1=Example1.main.hello:method1'\n }\n ],\n include_package_data=True,\n)\n#The package_dir parameter specifies the package name and its relative path, so that the setup.py script knows where to find the package.\n\n#You can then run the python setup.py bdist_wheel command to build the wheel for your submodule.\n" } ]
2022/12/02
[ "https://Stackoverflow.com/questions/74652871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6014418/" ]