qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,596,404
<p>I'm cleaning some data and I've been struggling with one thing.</p> <p>I have a dataframe with 7740 rows and 68 columns.</p> <p>Most of the columns contains Nan values.</p> <p>What i'm interested in, is to remove NaN values when it is NaN in those two columns : [SERIAL_ID],[NUMBER_ID]</p> <p>Example :</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>SERIAL_ID</th> <th>NUMBER_ID</th> </tr> </thead> <tbody> <tr> <td>8RY68U4R</td> <td>NaN</td> </tr> <tr> <td>8756ERT5</td> <td>8759321</td> </tr> <tr> <td>NaN</td> <td>NaN</td> </tr> <tr> <td>NaN</td> <td>7896521</td> </tr> <tr> <td>7EY68U4R</td> <td>NaN</td> </tr> <tr> <td>95856ERT5</td> <td>988888</td> </tr> <tr> <td>NaN</td> <td>NaN</td> </tr> <tr> <td>NaN</td> <td>4555555</td> </tr> </tbody> </table> </div> <p>Results</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>SERIAL_ID</th> <th>NUMBER_ID</th> </tr> </thead> <tbody> <tr> <td>8RY68U4R</td> <td>NaN</td> </tr> <tr> <td>8756ERT5</td> <td>8759321</td> </tr> <tr> <td>NaN</td> <td>7896521</td> </tr> <tr> <td>7EY68U4R</td> <td>NaN</td> </tr> <tr> <td>95856ERT5</td> <td>988888</td> </tr> <tr> <td>NaN</td> <td>4555555</td> </tr> </tbody> </table> </div> <p>Removing rows when NaN is in the two columns.</p> <p>I've used the followings to do so :</p> <pre><code>df.dropna(subset=['SERIAL_ID', 'NUMBER_ID'], how='all', inplace=True) </code></pre> <p>When I use this on my dataframe with 68 columns the result I get is this one :</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>SERIAL_ID</th> <th>NUMBER_ID</th> </tr> </thead> <tbody> <tr> <td>NaN</td> <td>NaN</td> </tr> <tr> <td>NaN</td> <td>NaN</td> </tr> <tr> <td>NaN</td> <td>NaN</td> </tr> <tr> <td>NaN</td> <td>7896521</td> </tr> <tr> <td>NaN</td> <td>NaN</td> </tr> <tr> <td>95856ERT5</td> <td>NaN</td> </tr> <tr> <td>NaN</td> <td>NaN</td> </tr> <tr> <td>NaN</td> <td>4555555</td> </tr> </tbody> </table> </div> <p>I tried with a copy of the dataframe with only 3 columns, it is working fine.</p> <p>It is somehow working (I can tel cause I have an identical ID in another column) but remove some of the value, and I have no idea why.</p> <p>Please help I've been struggling the whole day with this. Thanks again.</p>
[ { "answer_id": 74596521, "author": "Panda Kim", "author_id": 20430449, "author_profile": "https://Stackoverflow.com/users/20430449", "pm_score": 2, "selected": true, "text": "boolean indexing df[df[['SERIAL_ID', 'NUMBER_ID']].notnull().any(axis=1)]\n" }, { "answer_id": 74598909, "author": "D.L", "author_id": 7318120, "author_profile": "https://Stackoverflow.com/users/7318120", "pm_score": 0, "selected": false, "text": "boolean import numpy as np\nimport pandas as pd\n\n# sample dataframe\nd = {'SERIAL_ID':['8RY68U4R', '8756ERT5', np.nan, np.nan],\n 'NUMBER_ID':[np.nan, 8759321, np.nan ,7896521]}\ndf = pd.DataFrame(d)\n\n# apply logic to columns\ndf['nans'] = df['NUMBER_ID'].isnull() * df['SERIAL_ID'].isnull()\n\n# filter columns\ndf_filtered = df[df['nans']==False]\nprint(df_filtered)\n\n SERIAL_ID NUMBER_ID nans\n0 8RY68U4R NaN False\n1 8756ERT5 8759321.0 False\n3 NaN 7896521.0 False\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74596404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18975408/" ]
74,596,415
<p>I've got a fixed-width container element that contains several variable-width child elements. I'd like to distribute extra space evenly between those elements. This is easy to do if none of the elements include word-wrapped text. But if the total content is wider than will fit in the container without wrapping, I'm not sure how to distribute space between elements anymore.</p> <p>Here's a repro showing it working great when there's no wrapping, but not if there's wrapped text: <a href="https://codepen.io/justingrant/pen/bGKKJje" rel="nofollow noreferrer">https://codepen.io/justingrant/pen/bGKKJje</a></p> <p>If I use <code>flex-basis: auto</code> (the default) then wrapped items have wide padding and non-wrapped items have no padding. If I use <code>flex-basis: 1px</code> (or any identical width) then items are identical width, so items with wider text have less padding.</p> <p>Instead, I want to distribute extra space evenly between all items, regardless of whether they're wrapped or not. Is this possible?</p> <p>Note that what I <em>don't</em> want to do is assign a fixed padding to all items, because that will overflow the container and tie up lots of extra space. I just want to allocate extra space evenly.</p> <p><a href="https://i.stack.imgur.com/9ohC9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9ohC9.png" alt="enter image description here" /></a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.container { display: flex; flex-direction: column; } .bad { width: 600px; } .good { width: 800px; } ul { display: flex; flex-grow: 1; width: 100%; gap: 20px; padding: 20px; border: 1px solid gray; list-style: none; } li { flex-grow: 1; flex-basis: auto; padding: 10px 0; border: 1px solid red; text-align: center; } ul.basis li { flex-basis: 1px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class='container good'&gt; &lt;label&gt;Works as expected (consistent padding) if nothing wraps&lt;/label&gt; &lt;ul&gt; &lt;li&gt;South Carolina&lt;/li&gt; &lt;li&gt;North Carolina&lt;/li&gt; &lt;li&gt;Virginia&lt;/li&gt; &lt;li&gt;Alaska&lt;/li&gt; &lt;li&gt;District of Columbia&lt;/li&gt; &lt;li&gt;California&lt;/li&gt; &lt;li&gt;Arizona&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div class="container bad"&gt; &lt;label&gt;Not desired (padding varies) using &lt;code&gt;flex-basis: auto&lt;/code&gt;&lt;/label&gt; &lt;ul&gt; &lt;li&gt;South Carolina&lt;/li&gt; &lt;li&gt;North Carolina&lt;/li&gt; &lt;li&gt;Virginia&lt;/li&gt; &lt;li&gt;Alaska&lt;/li&gt; &lt;li&gt;District of Columbia&lt;/li&gt; &lt;li&gt;California&lt;/li&gt; &lt;li&gt;Arizona&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div class="container bad"&gt; &lt;label&gt;Not desired (padding varies) using &lt;code&gt;flex-basis: 1px&lt;/code&gt;&lt;/label&gt; &lt;ul class="basis"&gt; &lt;li&gt;South Carolina&lt;/li&gt; &lt;li&gt;North Carolina&lt;/li&gt; &lt;li&gt;Virginia&lt;/li&gt; &lt;li&gt;Alaska&lt;/li&gt; &lt;li&gt;District of Columbia&lt;/li&gt; &lt;li&gt;California&lt;/li&gt; &lt;li&gt;Arizona&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74596521, "author": "Panda Kim", "author_id": 20430449, "author_profile": "https://Stackoverflow.com/users/20430449", "pm_score": 2, "selected": true, "text": "boolean indexing df[df[['SERIAL_ID', 'NUMBER_ID']].notnull().any(axis=1)]\n" }, { "answer_id": 74598909, "author": "D.L", "author_id": 7318120, "author_profile": "https://Stackoverflow.com/users/7318120", "pm_score": 0, "selected": false, "text": "boolean import numpy as np\nimport pandas as pd\n\n# sample dataframe\nd = {'SERIAL_ID':['8RY68U4R', '8756ERT5', np.nan, np.nan],\n 'NUMBER_ID':[np.nan, 8759321, np.nan ,7896521]}\ndf = pd.DataFrame(d)\n\n# apply logic to columns\ndf['nans'] = df['NUMBER_ID'].isnull() * df['SERIAL_ID'].isnull()\n\n# filter columns\ndf_filtered = df[df['nans']==False]\nprint(df_filtered)\n\n SERIAL_ID NUMBER_ID nans\n0 8RY68U4R NaN False\n1 8756ERT5 8759321.0 False\n3 NaN 7896521.0 False\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74596415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/126352/" ]
74,596,427
<p>I am trying to learn routing by adding routing to a specific page in my healthcare app using angular. When I am trying to fetch data this is error what we are getting:</p> <pre><code>users.component.ts:15 ERROR TypeError: Cannot read properties of undefined (reading 'State') at Object.next (users.component.ts:17:40) at ConsumerObserver.next (Subscriber.js:91:33) at SafeSubscriber._next (Subscriber.js:60:26) at SafeSubscriber.next (Subscriber.js:31:18) at map.js:7:24 at OperatorSubscriber._next (OperatorSubscriber.js:13:21) at OperatorSubscriber.next (Subscriber.js:31:18) at filter.js:6:128 at OperatorSubscriber._next (OperatorSubscriber.js:13:21) at OperatorSubscriber.next (Subscriber.js:31:18) </code></pre> <p>I am writing this code for fetching the value of &quot;data&quot; from <a href="https://i.stack.imgur.com/3pDYy.png" rel="nofollow noreferrer">Data response getting from api</a></p> <pre><code>ngOnInit(): void { //Fetch Users this.userService.getAllUsers() .subscribe( (successResponse)=&gt;{ console.log(successResponse[0].State); }, (errorResponse)=&gt;{ console.log(errorResponse); } ) } </code></pre> <p>This code is giving the output <code>users.component.ts:15 ERROR TypeError: Cannot read properties of undefined (reading 'State')</code> Please help me with this as why the data is not fetching properly? Why is</p> <pre><code>successResponse[0].State </code></pre> <p>not giving the correct output?</p>
[ { "answer_id": 74596521, "author": "Panda Kim", "author_id": 20430449, "author_profile": "https://Stackoverflow.com/users/20430449", "pm_score": 2, "selected": true, "text": "boolean indexing df[df[['SERIAL_ID', 'NUMBER_ID']].notnull().any(axis=1)]\n" }, { "answer_id": 74598909, "author": "D.L", "author_id": 7318120, "author_profile": "https://Stackoverflow.com/users/7318120", "pm_score": 0, "selected": false, "text": "boolean import numpy as np\nimport pandas as pd\n\n# sample dataframe\nd = {'SERIAL_ID':['8RY68U4R', '8756ERT5', np.nan, np.nan],\n 'NUMBER_ID':[np.nan, 8759321, np.nan ,7896521]}\ndf = pd.DataFrame(d)\n\n# apply logic to columns\ndf['nans'] = df['NUMBER_ID'].isnull() * df['SERIAL_ID'].isnull()\n\n# filter columns\ndf_filtered = df[df['nans']==False]\nprint(df_filtered)\n\n SERIAL_ID NUMBER_ID nans\n0 8RY68U4R NaN False\n1 8756ERT5 8759321.0 False\n3 NaN 7896521.0 False\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74596427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20601693/" ]
74,596,479
<p>I have an array like this</p> <pre><code>{ [ { &quot;id&quot;: 1, &quot;name&quot;: &quot;this is book&quot;, }, { &quot;id&quot;: 2, &quot;name&quot;: &quot;this is a test book&quot;, }, { &quot;id&quot;: 3, &quot;name&quot;: &quot;this is a desk&quot;, } ] } </code></pre> <p>Now, for example, I want to return an array that contains the word <code>book</code></p> <p>I have tried the following but failed -</p> <pre><code>let test = this.pro.filter((s: { name: any; })=&gt;s.name===book); </code></pre> <p>I also tried this but it returned the <code>first matching result</code> instead of <code>all matching results</code> -</p> <pre><code>let test = this.pro.filter((s: { name: any; })=&gt;s.name===this is book); </code></pre> <p>Please help with a solution that can yield an array with all items that match the filter condition/s.</p>
[ { "answer_id": 74596631, "author": "Santheep Madhavan", "author_id": 19672487, "author_profile": "https://Stackoverflow.com/users/19672487", "pm_score": 3, "selected": true, "text": "const pro = [\n {\n \"id\": 1,\n \"name\": \"this is book\",\n },\n {\n \"id\": 2,\n \"name\": \"this is a test book\",\n },\n {\n \"id\": 3,\n \"name\": \"this is a desk\",\n }]\n\nlet newArr = pro.filter(item=>{\n if(item.name.indexOf('book') > -1){\n return item;\n }\n})\nconsole.log(newArr);\n" }, { "answer_id": 74596648, "author": "Reaper", "author_id": 10488111, "author_profile": "https://Stackoverflow.com/users/10488111", "pm_score": 2, "selected": false, "text": "let test = b.filter((s)=>s.name.includes('book'));" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74596479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13982646/" ]
74,596,499
<p>In Book model I have 2 methods</p> <p>1 for get book list another for get auth user Favourites book list. Two methods like below</p> <p>For get book list :</p> <pre><code>public function getBooks($id = null) { $query = $this::with(&quot;bookImages&quot;,&quot;author&quot;,&quot;category&quot;)-&gt;withCount(['favourites'])-&gt;orderBy('created_at', 'desc'); return $id ? $query-&gt;findOrFail($id):$query; } </code></pre> <p>For get user fav book list</p> <pre><code>public function getFavList() { return $this::join('favorites', function($query){ $query-&gt;on('books.id','=','favorites.book_id')-&gt;where('favorites.user_id', '=', 1); }) -&gt;with(&quot;bookImages&quot;,&quot;author&quot;,&quot;category&quot;)-&gt;withCount(['favourites'])-&gt;orderBy('created_at', 'desc') ; } </code></pre> <p>In both query <code>with</code> is common. So I'm trying to reuse getBooks method in getFavList method like below</p> <pre><code>public function getFavList() { return $this::join('favorites', function($query){ $query-&gt;on('books.id','=','favorites.book_id')-&gt;where('favorites.user_id', '=', 1); }) ::$this-&gt;getBooks() ; } </code></pre> <p>Here I'm getting <code>Access to undeclared static property Illuminate\Database\Eloquent\Builder::$this</code>. How can I simplify this method ?</p>
[ { "answer_id": 74597254, "author": "Malik", "author_id": 10804565, "author_profile": "https://Stackoverflow.com/users/10804565", "pm_score": 2, "selected": false, "text": "$books = Book::with('author', 'publisher')->get();\n $books = Book::with('author.contacts')->get();\n Advert::with('getBooks.getFavList')->find(1);\n public function getFavBooks()\n{\n return $this->getBooks()->union($this->getFavList()->toBase());\n}\n" }, { "answer_id": 74598197, "author": "Alimon Karim", "author_id": 3081630, "author_profile": "https://Stackoverflow.com/users/3081630", "pm_score": 0, "selected": false, "text": "return $this->getBooks()->join('favorites',function($query){\n $query->on('books.id','=','favorites.book_id')->where('favorites.user_id', '=', 1);\n});\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74596499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10164787/" ]
74,596,514
<p>I am trying to minus or subtract by 1 the academic year of school year with this format, e.g. <code>&quot;2020-2021&quot;</code></p> <p>If it is <code>2020-2021</code>, I would like to change it <code>2019-2020</code>. Is there a way to solve this concern?</p> <p>I considered trying to subtract using a hyphenated expression, but I am pretty stuck.</p> <pre><code>echo &quot;2020-2021&quot;-&quot;1-1&quot;; echo &quot;Result: 2019-2020&quot;; </code></pre>
[ { "answer_id": 74597254, "author": "Malik", "author_id": 10804565, "author_profile": "https://Stackoverflow.com/users/10804565", "pm_score": 2, "selected": false, "text": "$books = Book::with('author', 'publisher')->get();\n $books = Book::with('author.contacts')->get();\n Advert::with('getBooks.getFavList')->find(1);\n public function getFavBooks()\n{\n return $this->getBooks()->union($this->getFavList()->toBase());\n}\n" }, { "answer_id": 74598197, "author": "Alimon Karim", "author_id": 3081630, "author_profile": "https://Stackoverflow.com/users/3081630", "pm_score": 0, "selected": false, "text": "return $this->getBooks()->join('favorites',function($query){\n $query->on('books.id','=','favorites.book_id')->where('favorites.user_id', '=', 1);\n});\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74596514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20413120/" ]
74,596,525
<p>I am stuck at this point. Need to find the closet value near to my input</p> <pre><code>mylist = [1,8,4,88,100] inp=5 </code></pre> <p><strong>My output:</strong> <code>4</code></p> <p>I now using for loop to but need some more efficient way to handle</p> <p>As the<code>inp = 5 -&gt;</code>The nearest value to my input is <code>4.</code> So my output is <code>4 </code></p>
[ { "answer_id": 74596549, "author": "Epsi95", "author_id": 6660638, "author_profile": "https://Stackoverflow.com/users/6660638", "pm_score": 1, "selected": false, "text": "enumerate mylist = [1,8,4,88,100]\n\ninp=5\n\nclosest_val = mylist[min([abs(i-inp), index] for index, i in enumerate(mylist))[-1]] #4\n" }, { "answer_id": 74596609, "author": "accdias", "author_id": 6789321, "author_profile": "https://Stackoverflow.com/users/6789321", "pm_score": 1, "selected": false, "text": "numbers = [1, 8, 4, 88, 100]\nn = 5\ndistances = [abs(n - e) for e in numbers]\nclosest = numbers[distances.index(min(distances))]\n closest 4\n >>> numbers = [1, 8, 6, 4, 88, 100]\n>>> n = 5\n>>> distances = [abs(n - e) for e in numbers]\n>>> closest = numbers[distances.index(min(distances))]\n>>> closest\n6\n\n>>> numbers = [1, 8, 4, 6, 88, 100]\n>>> n = 5\n>>> distances = [abs(n - e) for e in numbers]\n>>> closest = numbers[distances.index(min(distances))]\n>>> closest\n4 \n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74596525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20497816/" ]
74,596,530
<pre><code>public static void main( String[] args ) { try{ String content = &quot;hello&quot;; File file =new File(&quot;d:\\test_appendfile.txt&quot;); if(!file.exists()){ file.createNewFile(); } FileWriter fileWritter = new FileWriter(file.getName(),true); fileWritter.write(content); fileWritter.close(); }catch(IOException e){ e.printStackTrace(); } } </code></pre> <p>Often, like 90% of possibility, there is nothing in &quot;test_appendfile.txt&quot;. However, sometimes, content is successfully written in &quot;test_appendfile.txt&quot;. Why?</p>
[ { "answer_id": 74597290, "author": "Preston", "author_id": 11548316, "author_profile": "https://Stackoverflow.com/users/11548316", "pm_score": 2, "selected": false, "text": "FileWriter fileWritter = new FileWriter(file.getName(),true); FileWriter fileWritter = new FileWriter(file,true);" }, { "answer_id": 74597531, "author": "Stephen C", "author_id": 139985, "author_profile": "https://Stackoverflow.com/users/139985", "pm_score": 2, "selected": false, "text": "file.getName() \"test_appendfile.txt\" \"D://\" \"D://\" \"D:// file close() try close() FileWriter FileWriter flush() close() if (!file.exists()) {\n file.createNewFile();\n }\n new FileWriter(file, true); File FileWriter D:" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74596530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19470144/" ]
74,596,531
<p><a href="https://i.stack.imgur.com/cBKnR.png" rel="nofollow noreferrer">Image clarification: After all processes have been created, a signal will be sent from the previous process following the red arrow </a> I need to create a program in which I fork() multiple processes. Then the child process will randomly send a signal to the child process &quot;next&quot; to it (imagine a graph). From my understanding, I can communicate between the parent process and its child using kill() and their PIDs, but I haven't found a way to do it between child processes. Is it even possible? I'm only allowed to use signals for communication.</p> <p>So far, what I tried is child sending a signal to the parent, with the parent then killing the sibling child process. However, this doesn't work when you increase the number of processes (which is what I need to do) because of all the PIDs I don't have. There's an image above of the steps.</p> <p>Important: I can <strong>only use signals</strong> (no pipes, semaphores and other ICP solutions)</p>
[ { "answer_id": 74597290, "author": "Preston", "author_id": 11548316, "author_profile": "https://Stackoverflow.com/users/11548316", "pm_score": 2, "selected": false, "text": "FileWriter fileWritter = new FileWriter(file.getName(),true); FileWriter fileWritter = new FileWriter(file,true);" }, { "answer_id": 74597531, "author": "Stephen C", "author_id": 139985, "author_profile": "https://Stackoverflow.com/users/139985", "pm_score": 2, "selected": false, "text": "file.getName() \"test_appendfile.txt\" \"D://\" \"D://\" \"D:// file close() try close() FileWriter FileWriter flush() close() if (!file.exists()) {\n file.createNewFile();\n }\n new FileWriter(file, true); File FileWriter D:" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74596531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20620219/" ]
74,596,543
<p>I have a data frame that I need to count the unique items of a certain row. In the example below, I want to label the name for the below function as &quot;NUM_CIK&quot;. What's the best way to assign a name to the groupby column?</p> <p>Current code:</p> <pre><code> cik_groupby_cusip_occur = cik_groupby_cusip_occur.groupby( ['CUSIP'], sort=True)['CIK COMPANY'].size().sort_values(ascending=False) </code></pre> <p>Sample Output:</p> <pre><code>CUSIP 594918104 4560 037833100 4457 023135106 4053 02079K305 3545 478160104 3472 </code></pre> <p><em>Wanted Output:</em></p> <pre><code>CUSIP NUM_CIK 594918104 4560 037833100 4457 023135106 4053 02079K305 3545 478160104 3472 </code></pre>
[ { "answer_id": 74597290, "author": "Preston", "author_id": 11548316, "author_profile": "https://Stackoverflow.com/users/11548316", "pm_score": 2, "selected": false, "text": "FileWriter fileWritter = new FileWriter(file.getName(),true); FileWriter fileWritter = new FileWriter(file,true);" }, { "answer_id": 74597531, "author": "Stephen C", "author_id": 139985, "author_profile": "https://Stackoverflow.com/users/139985", "pm_score": 2, "selected": false, "text": "file.getName() \"test_appendfile.txt\" \"D://\" \"D://\" \"D:// file close() try close() FileWriter FileWriter flush() close() if (!file.exists()) {\n file.createNewFile();\n }\n new FileWriter(file, true); File FileWriter D:" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74596543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19842621/" ]
74,596,570
<p>I'm currently learning the dynamic react route. In my sample code, I have different buttons for each work. When the button is clicked, it must render the <code>WorkDetails</code> component. However, it's not doing that even when I manually change the URL slug. I'm having a hard time figuring out what went wrong.</p> <p>Codesandbox: <a href="https://codesandbox.io/s/dynamic-routes-budulp?file=/src/App.js" rel="nofollow noreferrer">https://codesandbox.io/s/dynamic-routes-budulp?file=/src/App.js</a></p> <p>This is the routes in my App component</p> <pre><code>&lt;BrowserRouter&gt; &lt;Routes&gt; &lt;Route path=&quot;/&quot; element={&lt;Home /&gt;} /&gt; &lt;Route path=&quot;/works&quot; element={&lt;Work data={data} /&gt;}&gt; &lt;Route path=&quot;:slug&quot; element={&lt;WorkDetails /&gt;} /&gt; &lt;/Route&gt; &lt;/Routes&gt; &lt;/BrowserRouter&gt; </code></pre> <p>In my <code>Work</code> component, each button is surrounded with <code>Link</code>. For the path, I used the <code>slug</code> from my array of objects in data file.</p> <pre><code>const Work = ({ data }) =&gt; { return ( &lt;div&gt; &lt;h1&gt;Works&lt;/h1&gt; {data.map(({ id, name, slug }) =&gt; { return ( &lt;div key={id} id={id}&gt; &lt;h2&gt;{name}&lt;/h2&gt; &lt;Link to={slug}&gt; &lt;button&gt;Work Details&lt;/button&gt; &lt;/Link&gt; &lt;/div&gt; ); })} &lt;/div&gt; ); }; </code></pre> <p>data.js</p> <pre><code>let works = [ { id: 1, name: &quot;Work 1&quot;, slug: &quot;work-one&quot;, subtopics: [ { title: &quot;About the project&quot;, description: &quot;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Tempus quam pellentesque nec nam aliquam sem et tortor consequat. Sagittis orci a scelerisque purus semper eget duis at. Sodales neque sodales ut etiam sit amet. Proin sed libero enim sed faucibus turpis in eu mi. Blandit libero volutpat sed cras ornare arcu dui. Urna nunc id cursus metus. Mauris rhoncus aenean vel elit scelerisque mauris pellentesque pulvinar. Curabitur gravida arcu ac tortor. Natoque penatibus et magnis dis parturient montes nascetur. Aliquet porttitor lacus luctus accumsan tortor posuere ac ut. Aenean sed adipiscing diam donec adipiscing.&quot; }, { title: &quot;Process&quot;, description: &quot;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Tempus quam pellentesque nec nam aliquam sem et tortor consequat. Sagittis orci a scelerisque purus semper eget duis at. Sodales neque sodales ut etiam sit amet. Proin sed libero enim sed faucibus turpis in eu mi. Blandit libero volutpat sed cras ornare arcu dui. Urna nunc id cursus metus. Mauris rhoncus aenean vel elit scelerisque mauris pellentesque pulvinar. Curabitur gravida arcu ac tortor. Natoque penatibus et magnis dis parturient montes nascetur. Aliquet porttitor lacus luctus accumsan tortor posuere ac ut. Aenean sed adipiscing diam donec adipiscing.&quot; }, { title: &quot;Result&quot;, description: &quot;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Tempus quam pellentesque nec nam aliquam sem et tortor consequat. Sagittis orci a scelerisque purus semper eget duis at. Sodales neque sodales ut etiam sit amet. Proin sed libero enim sed faucibus turpis in eu mi. Blandit libero volutpat sed cras ornare arcu dui. Urna nunc id cursus metus. Mauris rhoncus aenean vel elit scelerisque mauris pellentesque pulvinar. Curabitur gravida arcu ac tortor. Natoque penatibus et magnis dis parturient montes nascetur. Aliquet porttitor lacus luctus accumsan tortor posuere ac ut. Aenean sed adipiscing diam donec adipiscing.&quot; } ] }, { id: 2, name: &quot;Work 2&quot;, slug: &quot;work-two&quot;, subtopics: [ { title: &quot;About the project&quot;, description: &quot;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Tempus quam pellentesque nec nam aliquam sem et tortor consequat. Sagittis orci a scelerisque purus semper eget duis at. Sodales neque sodales ut etiam sit amet. Proin sed libero enim sed faucibus turpis in eu mi. Blandit libero volutpat sed cras ornare arcu dui. Urna nunc id cursus metus. Mauris rhoncus aenean vel elit scelerisque mauris pellentesque pulvinar. Curabitur gravida arcu ac tortor. Natoque penatibus et magnis dis parturient montes nascetur. Aliquet porttitor lacus luctus accumsan tortor posuere ac ut. Aenean sed adipiscing diam donec adipiscing.&quot; }, { title: &quot;Process&quot;, description: &quot;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Tempus quam pellentesque nec nam aliquam sem et tortor consequat. Sagittis orci a scelerisque purus semper eget duis at. Sodales neque sodales ut etiam sit amet. Proin sed libero enim sed faucibus turpis in eu mi. Blandit libero volutpat sed cras ornare arcu dui. Urna nunc id cursus metus. Mauris rhoncus aenean vel elit scelerisque mauris pellentesque pulvinar. Curabitur gravida arcu ac tortor. Natoque penatibus et magnis dis parturient montes nascetur. Aliquet porttitor lacus luctus accumsan tortor posuere ac ut. Aenean sed adipiscing diam donec adipiscing.&quot; }, { title: &quot;Result&quot;, description: &quot;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Tempus quam pellentesque nec nam aliquam sem et tortor consequat. Sagittis orci a scelerisque purus semper eget duis at. Sodales neque sodales ut etiam sit amet. Proin sed libero enim sed faucibus turpis in eu mi. Blandit libero volutpat sed cras ornare arcu dui. Urna nunc id cursus metus. Mauris rhoncus aenean vel elit scelerisque mauris pellentesque pulvinar. Curabitur gravida arcu ac tortor. Natoque penatibus et magnis dis parturient montes nascetur. Aliquet porttitor lacus luctus accumsan tortor posuere ac ut. Aenean sed adipiscing diam donec adipiscing.&quot; } ] }, { id: 3, name: &quot;Work 3&quot;, slug: &quot;work-three&quot;, subtopics: [ { title: &quot;About the project&quot;, description: &quot;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Tempus quam pellentesque nec nam aliquam sem et tortor consequat. Sagittis orci a scelerisque purus semper eget duis at. Sodales neque sodales ut etiam sit amet. Proin sed libero enim sed faucibus turpis in eu mi. Blandit libero volutpat sed cras ornare arcu dui. Urna nunc id cursus metus. Mauris rhoncus aenean vel elit scelerisque mauris pellentesque pulvinar. Curabitur gravida arcu ac tortor. Natoque penatibus et magnis dis parturient montes nascetur. Aliquet porttitor lacus luctus accumsan tortor posuere ac ut. Aenean sed adipiscing diam donec adipiscing.&quot; }, { title: &quot;Process&quot;, description: &quot;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Tempus quam pellentesque nec nam aliquam sem et tortor consequat. Sagittis orci a scelerisque purus semper eget duis at. Sodales neque sodales ut etiam sit amet. Proin sed libero enim sed faucibus turpis in eu mi. Blandit libero volutpat sed cras ornare arcu dui. Urna nunc id cursus metus. Mauris rhoncus aenean vel elit scelerisque mauris pellentesque pulvinar. Curabitur gravida arcu ac tortor. Natoque penatibus et magnis dis parturient montes nascetur. Aliquet porttitor lacus luctus accumsan tortor posuere ac ut. Aenean sed adipiscing diam donec adipiscing.&quot; }, { title: &quot;Result&quot;, description: &quot;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Tempus quam pellentesque nec nam aliquam sem et tortor consequat. Sagittis orci a scelerisque purus semper eget duis at. Sodales neque sodales ut etiam sit amet. Proin sed libero enim sed faucibus turpis in eu mi. Blandit libero volutpat sed cras ornare arcu dui. Urna nunc id cursus metus. Mauris rhoncus aenean vel elit scelerisque mauris pellentesque pulvinar. Curabitur gravida arcu ac tortor. Natoque penatibus et magnis dis parturient montes nascetur. Aliquet porttitor lacus luctus accumsan tortor posuere ac ut. Aenean sed adipiscing diam donec adipiscing.&quot; } ] }, { id: 4, name: &quot;Work 4&quot;, slug: &quot;work-four&quot;, subtopics: [ { title: &quot;About the project&quot;, description: &quot;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Tempus quam pellentesque nec nam aliquam sem et tortor consequat. Sagittis orci a scelerisque purus semper eget duis at. Sodales neque sodales ut etiam sit amet. Proin sed libero enim sed faucibus turpis in eu mi. Blandit libero volutpat sed cras ornare arcu dui. Urna nunc id cursus metus. Mauris rhoncus aenean vel elit scelerisque mauris pellentesque pulvinar. Curabitur gravida arcu ac tortor. Natoque penatibus et magnis dis parturient montes nascetur. Aliquet porttitor lacus luctus accumsan tortor posuere ac ut. Aenean sed adipiscing diam donec adipiscing.&quot; }, { title: &quot;Process&quot;, description: &quot;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Tempus quam pellentesque nec nam aliquam sem et tortor consequat. Sagittis orci a scelerisque purus semper eget duis at. Sodales neque sodales ut etiam sit amet. Proin sed libero enim sed faucibus turpis in eu mi. Blandit libero volutpat sed cras ornare arcu dui. Urna nunc id cursus metus. Mauris rhoncus aenean vel elit scelerisque mauris pellentesque pulvinar. Curabitur gravida arcu ac tortor. Natoque penatibus et magnis dis parturient montes nascetur. Aliquet porttitor lacus luctus accumsan tortor posuere ac ut. Aenean sed adipiscing diam donec adipiscing.&quot; }, { title: &quot;Result&quot;, description: &quot;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Tempus quam pellentesque nec nam aliquam sem et tortor consequat. Sagittis orci a scelerisque purus semper eget duis at. Sodales neque sodales ut etiam sit amet. Proin sed libero enim sed faucibus turpis in eu mi. Blandit libero volutpat sed cras ornare arcu dui. Urna nunc id cursus metus. Mauris rhoncus aenean vel elit scelerisque mauris pellentesque pulvinar. Curabitur gravida arcu ac tortor. Natoque penatibus et magnis dis parturient montes nascetur. Aliquet porttitor lacus luctus accumsan tortor posuere ac ut. Aenean sed adipiscing diam donec adipiscing.&quot; } ] } ]; </code></pre> <p>On my <code>WorkDetails</code> component, I used the <code>useParams()</code> which I expect to return the <code>slug</code>. Then, I used the <code>slug</code> to find the object with the same <code>slug</code>. The state will then be updated with the found object.</p> <pre><code>const WorkDetails = () =&gt; { const { slug } = useParams(); // Find the object with the same slug as the params. const [work, setWork] = useState(null); let findWork = data.find((d) =&gt; d.slug === slug); if (findWork) { setWork(findWork); } return ( &lt;div&gt; &lt;Link to=&quot;/works&quot;&gt; &lt;button&gt;Back to Works&lt;/button&gt; &lt;/Link&gt; &lt;h1&gt;{work.name}&lt;/h1&gt; {work.subtopic.map((topic) =&gt; { return ( &lt;&gt; &lt;h2&gt;{topic.title}&lt;/h2&gt; &lt;p&gt;{topic.description}&lt;/p&gt; &lt;/&gt; ); })} &lt;/div&gt; ); }; </code></pre>
[ { "answer_id": 74597290, "author": "Preston", "author_id": 11548316, "author_profile": "https://Stackoverflow.com/users/11548316", "pm_score": 2, "selected": false, "text": "FileWriter fileWritter = new FileWriter(file.getName(),true); FileWriter fileWritter = new FileWriter(file,true);" }, { "answer_id": 74597531, "author": "Stephen C", "author_id": 139985, "author_profile": "https://Stackoverflow.com/users/139985", "pm_score": 2, "selected": false, "text": "file.getName() \"test_appendfile.txt\" \"D://\" \"D://\" \"D:// file close() try close() FileWriter FileWriter flush() close() if (!file.exists()) {\n file.createNewFile();\n }\n new FileWriter(file, true); File FileWriter D:" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74596570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15612876/" ]
74,596,590
<p>i am new with coding. i just trying a to code a small game and there seems to be a bug i cant fix. can someone help me</p> <p>This is my script</p> <pre><code>using System.Collections; using System.Collections.Generic; using UnityEngine; public class animation : MonoBehaviour { Animator Ani; public Transform attackPoint; public float attackRange = 0.5f; public LayerMask enemyLayers; void Start() { Ani = GetComponent&lt;Animator&gt;(); } private void Update() { if (Input.GetKeyDown(KeyCode.Space)) { Ani.SetTrigger(&quot;attack&quot;); Collider2D[] hitEnemies = Physics2D.OverlapCircleAll(attackPoint.position, attackRange, enemyLayers); } foreach(Collider2D enemy in hitEnemies) { Debug.Log(&quot;hit&quot; + enemy.name); } } } </code></pre> <p>how can i fix it?</p>
[ { "answer_id": 74597290, "author": "Preston", "author_id": 11548316, "author_profile": "https://Stackoverflow.com/users/11548316", "pm_score": 2, "selected": false, "text": "FileWriter fileWritter = new FileWriter(file.getName(),true); FileWriter fileWritter = new FileWriter(file,true);" }, { "answer_id": 74597531, "author": "Stephen C", "author_id": 139985, "author_profile": "https://Stackoverflow.com/users/139985", "pm_score": 2, "selected": false, "text": "file.getName() \"test_appendfile.txt\" \"D://\" \"D://\" \"D:// file close() try close() FileWriter FileWriter flush() close() if (!file.exists()) {\n file.createNewFile();\n }\n new FileWriter(file, true); File FileWriter D:" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74596590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20620272/" ]
74,596,593
<p>I have a dictionary look like this</p> <p><code>mydict = { 'type' : 'fruit', 'quantity': 20 } </code></p> <p>i wan to print only the 'type' field in the way it is ,like this {'type': 'fruit'}</p> <p>i found this on other website</p> <pre><code>class fruits(dict): def __str__(self): return json.dumps(self) collect = [['apple','grapes']] result = fruits(collect) print(result) </code></pre> <p>is there a simpler way without jsonify it? i also tried .items() method but it print out as (key, value) which i dont wan it to be</p>
[ { "answer_id": 74597290, "author": "Preston", "author_id": 11548316, "author_profile": "https://Stackoverflow.com/users/11548316", "pm_score": 2, "selected": false, "text": "FileWriter fileWritter = new FileWriter(file.getName(),true); FileWriter fileWritter = new FileWriter(file,true);" }, { "answer_id": 74597531, "author": "Stephen C", "author_id": 139985, "author_profile": "https://Stackoverflow.com/users/139985", "pm_score": 2, "selected": false, "text": "file.getName() \"test_appendfile.txt\" \"D://\" \"D://\" \"D:// file close() try close() FileWriter FileWriter flush() close() if (!file.exists()) {\n file.createNewFile();\n }\n new FileWriter(file, true); File FileWriter D:" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74596593", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20527873/" ]
74,596,598
<p>Say that I am getting text from a database that includes #hashtags. I want to add this text to the inner content of a <code>&lt;Post&gt;</code> element. However, I would like to process this text so that the hashtags are wrapped in an <code>&lt;a/&gt;</code> element, so it is not as simple as just including all the plaintext content as a child of Post like <code>&lt;Post&gt;my text here&lt;/Post&gt;</code>.</p> <p>Currently what I am doing is:</p> <pre class="lang-js prettyprint-override"><code>function Post(props: Post) { // ... return( &lt;div&gt; {textPreprocessor(props.text)} &lt;/div&gt; )} //... const textPreprocessor = (content : string) : React.ReactNode =&gt; { // adds hashtags let words = content.split(&quot; &quot;); let htmlString = &quot;&quot; words.forEach(word =&gt; { if(word[0] === &quot;#&quot;) { htmlString += `&lt;a href='hashtag/:${word}'/&gt;${word}&lt;/a&gt; ` } else{ htmlString += `${word} ` } }) return &lt;div dangerouslySetInnerHTML={{__html: htmlString}} /&gt;; } </code></pre> <p>Now this &quot;works&quot;, but it's also extremely dangerous. People can just write whatever HTML/JS they want into the database and it will be executed in the frontend. Is there a safer way to do this?</p>
[ { "answer_id": 74608009, "author": "Null Salad", "author_id": 4382391, "author_profile": "https://Stackoverflow.com/users/4382391", "pm_score": 0, "selected": false, "text": "const sanitizeHTML = (unsanitized : string) : string => {\n const el : HTMLDivElement = document.createElement(\"div\");\n el.innerText = unsanitized;\n return el.innerHTML;\n}\n textPreprocessor const textPreprocessor = (content : string) : React.ReactNode => {\n // adds hashtags\n const sanitized = sanitizeHTML(content)\n const words = content.split(\" \");\n let htmlString = \"\"\n words.forEach(word => {\n if(word[0] === \"#\") {\n htmlString += `<a href='hashtag/:${word}'/>${word}</a> `\n }\n else{\n htmlString += `${word} `\n }\n })\n \n return <div dangerouslySetInnerHTML={{__html: htmlString}} />;\n}\n\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74596598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4382391/" ]
74,596,614
<p>In my flutter project I have a bottomnavigation bar that switches between different pages. When I try to add the same page function to an OnPressed button it only shows the text in default. To get more idea here is the main.dart that links to bottombar:</p> <pre><code> Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), routes: { '/': (context) =&gt; _defaultHome, '/home': (context) =&gt; const BottomBar(), }, ); } </code></pre> <p>Here is the bottom bar:</p> <pre><code>class BottomBar extends StatefulWidget { const BottomBar({Key? key}) : super(key: key); @override State&lt;BottomBar&gt; createState() =&gt; _BottomBarState(); } class _BottomBarState extends State&lt;BottomBar&gt; { int _selectedIndex = 0; static final List&lt;Widget&gt; _widgetOptions = &lt;Widget&gt;[ HomeScreen(), ............................. const User_Profile() ]; void _onItemTapped(int index) { setState(() { _selectedIndex = index; //print('Tapped index is: ${_selectedIndex}'); }); } @override Widget build(BuildContext context) { return Scaffold( body: Center( child: _widgetOptions[_selectedIndex], ), bottomNavigationBar: Column( mainAxisSize: MainAxisSize.min, children: [ BottomNavigationBar( currentIndex: _selectedIndex, onTap: _onItemTapped, ...................................... type: BottomNavigationBarType.fixed, unselectedItemColor: const Color(0xFF526480), items: const [ ................................ BottomNavigationBarItem( icon: Icon(FluentSystemIcons.ic_fluent_person_regular), activeIcon: Icon(FluentSystemIcons.ic_fluent_person_filled), label: &quot;Profile&quot;) ], ), ], ), ); } </code></pre> <p>Now the bottombar is working perfectly fine but when I try to add <code>User_Profile()</code> in a homescreen button the outcome is not showing the same way as when clicking it from the bottonbar button. Here is the homescreen button:</p> <pre><code>GFButton( onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (context) =&gt; const User_Profile())); }, text: snapshot.data![index].name, blockButton: true, ) </code></pre> <p>Here is the outcome when clicking on <code>User_Profile()</code> from bottombar.</p> <p>Here is the outcome when clicking from homescreen.</p> <p>My question why is the outcome different when the same page is clicked from the home screen than the bottom bar. My required outcome is to be the same as thee bottombar.</p> <p>enter image description here</p> <p><a href="https://i.stack.imgur.com/xLxSt.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xLxSt.jpg" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/TyNz6.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TyNz6.jpg" alt="enter image description here" /></a></p>
[ { "answer_id": 74608009, "author": "Null Salad", "author_id": 4382391, "author_profile": "https://Stackoverflow.com/users/4382391", "pm_score": 0, "selected": false, "text": "const sanitizeHTML = (unsanitized : string) : string => {\n const el : HTMLDivElement = document.createElement(\"div\");\n el.innerText = unsanitized;\n return el.innerHTML;\n}\n textPreprocessor const textPreprocessor = (content : string) : React.ReactNode => {\n // adds hashtags\n const sanitized = sanitizeHTML(content)\n const words = content.split(\" \");\n let htmlString = \"\"\n words.forEach(word => {\n if(word[0] === \"#\") {\n htmlString += `<a href='hashtag/:${word}'/>${word}</a> `\n }\n else{\n htmlString += `${word} `\n }\n })\n \n return <div dangerouslySetInnerHTML={{__html: htmlString}} />;\n}\n\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74596614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14574691/" ]
74,596,617
<p>I am really not able to understand that why I get compilation error when in first case while works fine in second case.</p> <pre><code>public class GenericsTest3 { public static &lt;W&gt; void main(String[] args) { List&lt;W&gt; l1 = new ArrayList&lt;String&gt;(); // compilation error: Type mismatch: cannot convert from ArrayList&lt;String&gt; to List&lt;W&gt; doSomething1(new ArrayList&lt;String&gt;()); // works fine } public static &lt;L&gt; L doSomething1(List&lt;L&gt; list) { list.get(0); list.add(list.get(0)); return list.get(1); } } </code></pre> <p>In my understand in both the cases List is defined of type parameter T/W, so why parameterized type <code>new ArrayList&lt;String&gt;()</code> fails in one case while passes in other case.</p>
[ { "answer_id": 74597031, "author": "Christoph Dahlen", "author_id": 20370596, "author_profile": "https://Stackoverflow.com/users/20370596", "pm_score": 1, "selected": false, "text": "List<W> l1 = new ArrayList<String>();\n List<W> l1 = new ArrayList<>();\n doSomething1(new ArrayList<String>());\n" }, { "answer_id": 74597042, "author": "Saurabh", "author_id": 18930205, "author_profile": "https://Stackoverflow.com/users/18930205", "pm_score": 1, "selected": false, "text": "List<W> l1 = new ArrayList<String>();\n <L> L doSomething1(List<L> list) method\n" }, { "answer_id": 74633719, "author": "newacct", "author_id": 86989, "author_profile": "https://Stackoverflow.com/users/86989", "pm_score": 0, "selected": false, "text": "main W W W W String List<W> l1 = new ArrayList<String>(); doSomething1 L doSomething1 L doSomething1 main L L String" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74596617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5111394/" ]
74,596,620
<p>Following <a href="https://stackoverflow.com/questions/73470274/how-can-i-access-forward-the-public-http-request-ip-address-inside-a-docker-co">this question</a>, I edited my gateway container to use the <code>host</code> network mode:</p> <pre><code>services: gateway: ... network_mode: &quot;host&quot; </code></pre> <p>and then the <code>docker compose up -d</code> gives me this:</p> <blockquote> <p>Error response from daemon: failed to add interface veth701c890 to sandbox: error setting interface &quot;veth701c890&quot; IP to 172.26.0.11/16: cannot program address 172.26.0.11/16 in sandbox interface because it conflicts with existing route {Ifindex: 4 Dst: 172.26.0.0/16 Src: 172.26.0.1 Gw: Flags: [] Table: 254</p> </blockquote> <p>I restarted the docker and even the server. No luck.</p> <p>The <code>docker-compose.yml</code> looks like this (only the <code>gateway</code> container has published ports):</p> <pre><code>version: '3.4' services: gateway: image: &lt;ms-yarp&gt; environment: - ASPNETCORE_URLS=https://+:443;http://+:80 ports: - &quot;80:80&quot; - &quot;443:443&quot; volumes: - ./tls/:/tls/ networks: - mynet restart: on-failure orders: image: &lt;registry&gt;/orders environment: - ASPNETCORE_URLS=http://+:80 networks: - mynet restart: on-failure users: image: &lt;registry&gt;/users environment: - ASPNETCORE_URLS=http://+:80 networks: - mynet restart: on-failure smssender: image: &lt;registry&gt;/smssender environment: - ASPNETCORE_URLS=http://+:80 networks: - mynet restart: on-failure logger: image: &lt;registry&gt;/logger environment: - ASPNETCORE_URLS=http://+:80 networks: - mynet restart: on-failure notifications: image: &lt;registry&gt;/notifications environment: - ASPNETCORE_URLS=http://+:80 networks: - mynet restart: on-failure cacheserver: image: &lt;registry&gt;/redis networks: - mynet restart: on-failure ... networks: mynet: </code></pre>
[ { "answer_id": 74597031, "author": "Christoph Dahlen", "author_id": 20370596, "author_profile": "https://Stackoverflow.com/users/20370596", "pm_score": 1, "selected": false, "text": "List<W> l1 = new ArrayList<String>();\n List<W> l1 = new ArrayList<>();\n doSomething1(new ArrayList<String>());\n" }, { "answer_id": 74597042, "author": "Saurabh", "author_id": 18930205, "author_profile": "https://Stackoverflow.com/users/18930205", "pm_score": 1, "selected": false, "text": "List<W> l1 = new ArrayList<String>();\n <L> L doSomething1(List<L> list) method\n" }, { "answer_id": 74633719, "author": "newacct", "author_id": 86989, "author_profile": "https://Stackoverflow.com/users/86989", "pm_score": 0, "selected": false, "text": "main W W W W String List<W> l1 = new ArrayList<String>(); doSomething1 L doSomething1 L doSomething1 main L L String" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74596620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19363672/" ]
74,596,624
<p>I have a text like this</p> <pre><code>EXPRESS blood| muscle| testis| normal| tumor| fetus| adult RESTR_EXPR soft tissue/muscle tissue tumor </code></pre> <p>Right now I want to only extract the last item in EXPRESS line, which is <code>adult</code>.</p> <p>My pattern is:</p> <pre><code>[|](.*?)\n </code></pre> <p>The code goes greedy to <code>muscle| testis| normal| tumor| fetus| adult</code>. Can I know if there is any way to solve this issue?</p>
[ { "answer_id": 74597462, "author": "Vincent Flotron", "author_id": 20436111, "author_profile": "https://Stackoverflow.com/users/20436111", "pm_score": 0, "selected": false, "text": "\\|\\s*([^\\|])*?\\r?\\n\n" }, { "answer_id": 74598061, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 1, "selected": false, "text": "\\|[^\\S\\n]*([^|\\n]*)\\n\n \\| | [^\\S\\n]* ( [^|\\n]* | ) \\n \\|[^\\S\\n]*([^|\\n]*)$\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74596624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17649570/" ]
74,596,663
<p>I've been using Sklearn <code>HistGradientBoostingClassifier</code> to classify some data. My experiment is multi-class classification with single label predictions (20 labels).</p> <p>My experience shows two cases. The first case is the measurement of the accuracy of these algorithms without data augmentation (around unbalanced 3,000 samples). The second case is the measurement of accuracy with data augmentation (around 12,000 unbalanced samples). I am using default parameters.</p> <p>In the first case, the <code>HistGradientBoostingClassifier</code> shows an accuracy of around 86.0%. However, with data augmentation, results show weak accuracy, around 23%.</p> <p>I am wondering if this accuracy was coming from unbalanced datasets, but since there are no features to fix unbalanced datasets for the <code>HistGradientBoostingClassifier</code> algorithm within the Sklearn library, I cannot verify that fact.</p> <p>Do some people have the same kind of problem with large dataset and <code>HistGradientBoostingClassifier</code>?</p> <p>Edit: I tried other algorithms with the same data split, and the results seems normal (accuracy around 5% more w/ data augmentation). I am wondering why I am only getting this with <code>HistGradientBoostingClassifier</code>.</p>
[ { "answer_id": 74597462, "author": "Vincent Flotron", "author_id": 20436111, "author_profile": "https://Stackoverflow.com/users/20436111", "pm_score": 0, "selected": false, "text": "\\|\\s*([^\\|])*?\\r?\\n\n" }, { "answer_id": 74598061, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 1, "selected": false, "text": "\\|[^\\S\\n]*([^|\\n]*)\\n\n \\| | [^\\S\\n]* ( [^|\\n]* | ) \\n \\|[^\\S\\n]*([^|\\n]*)$\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74596663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18163940/" ]
74,596,714
<p>Whenever I use the following codes, the aspect ratio of my square-shaped image (1:1 aspect ratio) changes across different devices (different types of monitors/mobile phones)? When I say changes, on some devices it's a perfect square image as I'd expect but on some devices it becomes a rectangle. Does anyone know how to fix this? I want it to have the original aspect ratio.</p> <blockquote> </blockquote> <pre><code>&lt;div class=&quot;col-xl-3&quot;&gt; &lt;img src=&quot;images/myimg.jpg&quot; style=&quot;width: auto; height: 310px; margin-top: -190px; padding-left: 50px;&quot; class=&quot;img-fluid&quot; alt=&quot;Placeholder image&quot;&gt; &lt;/div&gt; </code></pre> <blockquote> </blockquote> <pre><code>&lt;div class=&quot;col-xl-3&quot;&gt; &lt;img src=&quot;images/myimg.jpg&quot; style=&quot;width: 310px; height: 310px; margin-top: -190px; padding-left: 50px;&quot; class=&quot;img-fluid&quot; alt=&quot;Placeholder image&quot;&gt; &lt;/div&gt; </code></pre> <blockquote> <p>.img-fluid { max-width: 100%, height: auto }</p> </blockquote> <p>It's a static website hosted on github pages.</p> <p>Try different options. I was expecting it to preserve its original aspect ratio.</p>
[ { "answer_id": 74597462, "author": "Vincent Flotron", "author_id": 20436111, "author_profile": "https://Stackoverflow.com/users/20436111", "pm_score": 0, "selected": false, "text": "\\|\\s*([^\\|])*?\\r?\\n\n" }, { "answer_id": 74598061, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 1, "selected": false, "text": "\\|[^\\S\\n]*([^|\\n]*)\\n\n \\| | [^\\S\\n]* ( [^|\\n]* | ) \\n \\|[^\\S\\n]*([^|\\n]*)$\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74596714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20620440/" ]
74,596,758
<p>Here the @Data has a value with apostophe(')s . how do i update or insert a data based on the data value which is having apostophe in a dynamic sql</p> <p>suppose @data has one value abc and another value abc's it throwing error for the second one</p> <p><code>SET @SQL = ' Update '+ @ProcessCode + '_abc SET IS_IGNORING = 1 where Column_Name = '''+ @Column_Name +''' and [DATA] = ''' + @Data + ''' and Table_name = '''+ @Table_Name + '''' </code></p> <p>Generally what i found is a manual process of adding one more apostophe but i am not really sure how to use that in a dynamic sql where not all data in the table is same, few of the data records has got this type of apostophe(')</p>
[ { "answer_id": 74597462, "author": "Vincent Flotron", "author_id": 20436111, "author_profile": "https://Stackoverflow.com/users/20436111", "pm_score": 0, "selected": false, "text": "\\|\\s*([^\\|])*?\\r?\\n\n" }, { "answer_id": 74598061, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 1, "selected": false, "text": "\\|[^\\S\\n]*([^|\\n]*)\\n\n \\| | [^\\S\\n]* ( [^|\\n]* | ) \\n \\|[^\\S\\n]*([^|\\n]*)$\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74596758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20545879/" ]
74,596,760
<p>How to get input in dart on vscode?</p> <p>When I click the &quot;Run&quot; button, it only runs the code on the uneditable-terminal, but when I use the &quot;F5&quot; button to run it, as in Python, it brings an error that I need to do some installation and/or configurations, and it auto-creates a &quot;launch.json&quot; file.</p>
[ { "answer_id": 74597462, "author": "Vincent Flotron", "author_id": 20436111, "author_profile": "https://Stackoverflow.com/users/20436111", "pm_score": 0, "selected": false, "text": "\\|\\s*([^\\|])*?\\r?\\n\n" }, { "answer_id": 74598061, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 1, "selected": false, "text": "\\|[^\\S\\n]*([^|\\n]*)\\n\n \\| | [^\\S\\n]* ( [^|\\n]* | ) \\n \\|[^\\S\\n]*([^|\\n]*)$\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74596760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18722085/" ]
74,596,774
<p>Using tidyverse, I would like to obtain the maximum count of events (e.g., dates) by group. Here is a minimum reproducible example:</p> <p>Data frame:</p> <pre><code>df &lt;- data.frame(id = c(1, 1, 1, 2, 2, 2, 2, 3, 3, 4, 5, 5, 5, 5), event = c(12, 6, 1, 7, 13, 9, 4, 8, 2, 5, 11, 3, 10, 14)) </code></pre> <p>The following code produces the desired output, but seems overly complicated:</p> <pre><code>df %&gt;% group_by(id) %&gt;% mutate(count = n()) %&gt;% ungroup() %&gt;% select(count) %&gt;% slice_max(count, n = 1, with_ties = FALSE) </code></pre> <p>Is there a simpler/better way? The following works, but <code>top_n</code> has been superseded by <code>slice_max</code> and it is <a href="https://dplyr.tidyverse.org/reference/top_n.html" rel="nofollow noreferrer">recommended</a> that the latter be used instead.</p> <pre><code>df %&gt;% count(id) %&gt;% distinct(n) %&gt;% # to remove tied values top_n(1) </code></pre> <p>Any suggestions?</p>
[ { "answer_id": 74597050, "author": "Josh White", "author_id": 20289207, "author_profile": "https://Stackoverflow.com/users/20289207", "pm_score": 2, "selected": false, "text": "table() max() max(table(df$id))\n [1] 4\n df$id %>% \n table() %>% \n max()\n" }, { "answer_id": 74600475, "author": "LeonaRdo", "author_id": 1813268, "author_profile": "https://Stackoverflow.com/users/1813268", "pm_score": 2, "selected": true, "text": "id df %>% \n group_by(id) %>% \n summarise(max_n_events = max(event))\n event id df %>% group_by(id) %>% count() %>% ungroup() %>% summarise(max(n))\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74596774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4476230/" ]
74,596,796
<p>Initially, I am using a mat-slider I need to change the label as per the range. But I don't know how to write JavaScript for different labels can anyone help me as of now I am a Fresher.</p> <p><a href="https://i.stack.imgur.com/v5Etm.png" rel="nofollow noreferrer">mat-slider</a> I need this one</p>
[ { "answer_id": 74597050, "author": "Josh White", "author_id": 20289207, "author_profile": "https://Stackoverflow.com/users/20289207", "pm_score": 2, "selected": false, "text": "table() max() max(table(df$id))\n [1] 4\n df$id %>% \n table() %>% \n max()\n" }, { "answer_id": 74600475, "author": "LeonaRdo", "author_id": 1813268, "author_profile": "https://Stackoverflow.com/users/1813268", "pm_score": 2, "selected": true, "text": "id df %>% \n group_by(id) %>% \n summarise(max_n_events = max(event))\n event id df %>% group_by(id) %>% count() %>% ungroup() %>% summarise(max(n))\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74596796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20293199/" ]
74,596,802
<p>If we assume the loop returns k==0 first (this order is implementation dependent according to the spec). How many times should the loop body run? Once or twice? If twice what should be printed for arr[1]?</p> <pre><code>BEGIN { arr[0] = &quot;zero&quot;; arr[1] = &quot;one&quot;; for (k in arr) { print &quot;key &quot; k &quot; val &quot; arr[k]; delete arr[k+1] } } </code></pre> <pre><code>$ gawk --version GNU Awk 5.1.0, API: 3.0 (GNU MPFR 4.1.0, GNU MP 6.2.1) .... $ gawk 'BEGIN { arr[0] = &quot;zero&quot;; arr[1] = &quot;one&quot;; for (k in arr) { print &quot;key &quot; k &quot; val &quot; arr[k]; delete arr[k+1] } }' key 0 val zero key 1 val </code></pre> <pre><code>$ goawk --version v1.19.0 $ goawk 'BEGIN { arr[0] = &quot;zero&quot;; arr[1] = &quot;one&quot;; for (k in arr) { print &quot;key &quot; k &quot; val &quot; key 0 val zero </code></pre> <p>gnu-awk runs it twice with <code>arr[1] == &quot;&quot;</code> and goawk runs it once. Mawk (mawk 1.3.4 20200120) sorts keys 1,0 but has the same fundamental behavior as gnu-awk, looping twice and print the empty string for the deleted key). What is the posix defined expected behavior of this program?</p> <p>Essentially should keys deleted in past loops appear in future loops?</p>
[ { "answer_id": 74598613, "author": "Ed Morton", "author_id": 1745001, "author_profile": "https://Stackoverflow.com/users/1745001", "pm_score": 3, "selected": true, "text": "gawk BEGIN {\n arr[0] = \"zero\"; \n arr[1] = \"one\"; \n for (k in arr) { \n indices[k]\n }\n for (k in indices) { \n print \"key \" k \" val \" arr[k]; \n delete arr[k+1] \n }\n}\n goawk BEGIN {\n arr[0] = \"zero\"; \n arr[1] = \"one\"; \n for ( k in arr ) {\n indices[k]\n }\n for (k in indices) {\n if ( k in arr ) {\n print \"key \" k \" val \" arr[k]; \n delete arr[k+1] \n }\n }\n}\n for ( k in ... ) delete arr[k+1] arr[] in k 1 0 0 1" }, { "answer_id": 74601312, "author": "RARE Kpop Manifesto", "author_id": 14672114, "author_profile": "https://Stackoverflow.com/users/14672114", "pm_score": -1, "selected": false, "text": "mawk-1 mawk 1.3.4 % mawk 'BEGIN { \n arr[0] = \"zero\";\n arr[1] = \"one\";\n for (k in arr) {\n print \"key \" k \" val \" arr[k];\n delete arr[k+1]\n }\n}'\n key 1 val one <<<<<<\n key 0 val zero \n WHINY_USERS WHINY_USERS= mawk 'BEGIN {\n arr[0] = \"zero\";\n arr[1] = \"one\";\n for (k in arr) {\n print \"key \" k \" val \" arr[k];\n delete arr[k+1]\n }\n}'\nkey 0 val zero\nkey 1 val \n\n% mawk 'BEGIN { \n arr[0] = \"zero\";\n arr[1] = \"one\";\n for (k in arr) {\n print \"key \" k \" val \" arr[k];\n delete arr[k+1]\n }\n}'\nkey 1 val one\nkey 0 val zero\n mawk-2 (beta-1.9.9.6) % mawk2 'BEGIN {\n arr[0] = \"zero\";\n arr[1] = \"one\";\n for (k in arr) {\n print \"key \" k \" val \" arr[k];\n delete arr[k+1]\n }\n}'\nkey 0 val zero\nkey 1 val \n gawk 5.2.0 gawk -e 'BEGIN {\n arr[0] = \"zero\";\n arr[1] = \"one\";\n for (k in arr) {\n print \"key \" k \" val \" arr[k];\n delete arr[k+1]\n }\n}'\nkey 0 val zero\nkey 1 val \n nawk 20200816 % nawk 'BEGIN {\n arr[0] = \"zero\";\n arr[1] = \"one\";\n for (k in arr) {\n print \"key \" k \" val \" arr[k];\n delete arr[k+1]\n }\n}'\nkey 0 val zero\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74596802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12417483/" ]
74,596,819
<p>I am automating app deployments by making use of AWS CLI commands. However, the problem is that when the AWS command is fired and is completed, the next command in the script is not executed. This is because the command returns a JSON and that JSON doesn't display whole at a time. It displays partial and then a <code>--More--</code> prompt appears. Only when the user presses <code>Enter</code> (or may be any other key), then only the rest of the JSON is displayed. If the JSON returned is large, this process (of pressing <code>Enter</code>) is to be repeated many times.</p> <p><strong>Example:</strong></p> <pre><code>aws lambda create-function --function-name testFunction --zip-file fileb://testFunction.zip --handler testFunction.lambda_handler --runtime python3.9 --role arn:aws:iam::413124763983:role/LambdaAccessRole\n\n { &quot;FunctionName&quot;: &quot;testFunction&quot;, &quot;FunctionArn&quot;: &quot;arn:aws:lambda:us-east-1:413124763983:function:testFunction&quot;, &quot;Runtime&quot;: &quot;python3.9&quot;, &quot;Role&quot;: &quot;arn:aws:iam::413124763983:role/LambdaAccessRole&quot;, &quot;Handler&quot;: &quot;testFunction.lambda_handler&quot;, &quot;CodeSize&quot;: 986, &quot;Description&quot;: &quot;&quot;, &quot;Timeout&quot;: 3, &quot;MemorySize&quot;: 128, &quot;LastModified&quot;: &quot;2022-11-28T03:39:11.017+0000&quot;, &quot;CodeSha256&quot;: &quot;moRVatK9khJOLTbPzq8zrGB989nBhfMiV1GCx5pNr2o=&quot;, &quot;Version&quot;: &quot;$LATEST&quot;, -- More -- </code></pre> <p>As can be seen above, there is a <code>--More--</code> prompt at after partial JSON is displayed.</p> <p>How can I avoid this <code>--More--</code> prompt and simply display entire JSON so that next command in the script is executed?</p>
[ { "answer_id": 74598613, "author": "Ed Morton", "author_id": 1745001, "author_profile": "https://Stackoverflow.com/users/1745001", "pm_score": 3, "selected": true, "text": "gawk BEGIN {\n arr[0] = \"zero\"; \n arr[1] = \"one\"; \n for (k in arr) { \n indices[k]\n }\n for (k in indices) { \n print \"key \" k \" val \" arr[k]; \n delete arr[k+1] \n }\n}\n goawk BEGIN {\n arr[0] = \"zero\"; \n arr[1] = \"one\"; \n for ( k in arr ) {\n indices[k]\n }\n for (k in indices) {\n if ( k in arr ) {\n print \"key \" k \" val \" arr[k]; \n delete arr[k+1] \n }\n }\n}\n for ( k in ... ) delete arr[k+1] arr[] in k 1 0 0 1" }, { "answer_id": 74601312, "author": "RARE Kpop Manifesto", "author_id": 14672114, "author_profile": "https://Stackoverflow.com/users/14672114", "pm_score": -1, "selected": false, "text": "mawk-1 mawk 1.3.4 % mawk 'BEGIN { \n arr[0] = \"zero\";\n arr[1] = \"one\";\n for (k in arr) {\n print \"key \" k \" val \" arr[k];\n delete arr[k+1]\n }\n}'\n key 1 val one <<<<<<\n key 0 val zero \n WHINY_USERS WHINY_USERS= mawk 'BEGIN {\n arr[0] = \"zero\";\n arr[1] = \"one\";\n for (k in arr) {\n print \"key \" k \" val \" arr[k];\n delete arr[k+1]\n }\n}'\nkey 0 val zero\nkey 1 val \n\n% mawk 'BEGIN { \n arr[0] = \"zero\";\n arr[1] = \"one\";\n for (k in arr) {\n print \"key \" k \" val \" arr[k];\n delete arr[k+1]\n }\n}'\nkey 1 val one\nkey 0 val zero\n mawk-2 (beta-1.9.9.6) % mawk2 'BEGIN {\n arr[0] = \"zero\";\n arr[1] = \"one\";\n for (k in arr) {\n print \"key \" k \" val \" arr[k];\n delete arr[k+1]\n }\n}'\nkey 0 val zero\nkey 1 val \n gawk 5.2.0 gawk -e 'BEGIN {\n arr[0] = \"zero\";\n arr[1] = \"one\";\n for (k in arr) {\n print \"key \" k \" val \" arr[k];\n delete arr[k+1]\n }\n}'\nkey 0 val zero\nkey 1 val \n nawk 20200816 % nawk 'BEGIN {\n arr[0] = \"zero\";\n arr[1] = \"one\";\n for (k in arr) {\n print \"key \" k \" val \" arr[k];\n delete arr[k+1]\n }\n}'\nkey 0 val zero\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74596819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3722884/" ]
74,596,829
<p>I'm currently learning about the DOM and jQuery different ways to work them. I was asked to put the following information under the (#appendToMe) div: Put the (inStock: true) items in the (.inStock ) class and the (inStock: false) items in the (.notInStock) class. It looks like everything is correct but the output is not the right colors.</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 storeItems = [ { name: 'TV', price: 800.00, inStock: true }, { name: 'Phone', price: 700.00, inStock: false }, { name: 'Game Console', price: 300.00, inStock: true }, { name: 'Smart Watch', price: 200.00, inStock: false }, ]; storeItems.forEach(function(n, i, a) { if (n.inStock == true) { $('p').addClass('inStock'); $('#appendToMe').append('&lt;p&gt;' + n.name + ': ' + n.price + '&lt;/p&gt;'); } if (n.inStock == false) { $('p').addClass('notInStock'); $('#appendToMe').append('&lt;p&gt;' + n.name + ': ' + n.price + ' Not in stock' + '&lt;/p&gt;'); } })</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.inStock, .notInStock { padding: 10px; margin: 10px 0; font-family: Helvetica; } .inStock { background-color: #79f; } .notInStock { background-color: #eff; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;meta name="viewport" content="width=device-width"&gt; &lt;title&gt;repl.it&lt;/title&gt; &lt;link href="style.css" rel="stylesheet" type="text/css" /&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="appendToMe"&gt; &lt;/div&gt; &lt;script src="https://code.jquery.com/jquery-3.5.0.slim.min.js" integrity="sha256-MlusDLJIP1GRgLrOflUQtshyP0TwT/RHXsI1wWGnQhs=" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;script src="script.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74597090, "author": "Giorgi Shalamberidze", "author_id": 20248276, "author_profile": "https://Stackoverflow.com/users/20248276", "pm_score": 2, "selected": true, "text": "const storeItems = [\n {\n name: 'TV',\n price: 800.00,\n inStock: true\n },\n {\n name: 'Phone',\n price: 700.00,\n inStock: false\n },\n {\n name: 'Game Console',\n price: 300.00,\n inStock: true\n },\n\n {\n name: 'Smart Watch',\n price: 200.00,\n inStock: false\n },\n];\n\n\nstoreItems.forEach(function(n, i, a) {\n if (n.inStock == true) {\n //$('p').addClass('inStock');\n $('#appendToMe').append('<p class=\"inStock\">' + n.name + ': ' + n.price \n + \n '</p>');\n }\n if (n.inStock == false) {\n //$('p').addClass('notInStock');\n $('#appendToMe').append('<p class=\"notInStock\">' + n.name + ': ' + \n n.price + ' Not in stock' + '</p>');\n }\n}) .inStock, .notInStock {\n padding: 10px;\n margin: 10px 0;\n font-family: Helvetica;\n}\n\n.inStock {\n background-color: #79f;\n}\n\n.notInStock {\n background-color: #eff;\n} <!DOCTYPE html>\n<html>\n <head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width\">\n <title>repl.it</title>\n <link href=\"style.css\" rel=\"stylesheet\" type=\"text/css\" />\n </head>\n <body>\n <div id=\"appendToMe\">\n </div>\n <script src=\"https://code.jquery.com/jquery-3.5.0.slim.min.js\" integrity=\"sha256-MlusDLJIP1GRgLrOflUQtshyP0TwT/RHXsI1wWGnQhs=\" crossorigin=\"anonymous\"></script>\n <script src=\"script.js\"></script>\n </body>\n</html>" }, { "answer_id": 74597288, "author": "Ha Tai", "author_id": 14036048, "author_profile": "https://Stackoverflow.com/users/14036048", "pm_score": 0, "selected": false, "text": "const storeItems = [\n {\n name: 'TV',\n price: 800.00,\n inStock: true\n },\n {\n name: 'Phone',\n price: 700.00,\n inStock: false\n },\n {\n name: 'Game Console',\n price: 300.00,\n inStock: true\n },\n\n {\n name: 'Smart Watch',\n price: 200.00,\n inStock: false\n },\n ];\n\n\n storeItems.forEach(function (n, i, a) {\n const id = Date.now();\n if (n.inStock == true) {\n $('#appendToMe').append(`<p id=\"${id}-${i}\">` + n.name + ': ' + n.price + '</p>');\n $(`p#${id}-${i}`).addClass('inStock');\n }\n if (n.inStock == false) {\n $('#appendToMe').append(`<p id=\"${id}-${i}\">` + n.name + ': ' + n.price + ' Not in stock' + '</p>');\n $(`p#${id}-${i}`).addClass('notInStock');\n }\n }) <style>\n .inStock,\n .notInStock {\n padding: 10px;\n margin: 10px 0;\n font-family: Helvetica;\n }\n\n .inStock {\n background-color: #79f;\n }\n\n .notInStock {\n background-color: #eff;\n }\n</style> <!DOCTYPE html>\n<html>\n\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width\">\n <title>repl.it</title>\n <link href=\"style.css\" rel=\"stylesheet\" type=\"text/css\" />\n</head>\n\n<body>\n <div id=\"appendToMe\">\n </div>\n <script src=\"https://code.jquery.com/jquery-3.5.0.slim.min.js\"\n integrity=\"sha256-MlusDLJIP1GRgLrOflUQtshyP0TwT/RHXsI1wWGnQhs=\" crossorigin=\"anonymous\"></script>\n <script src=\"script.js\"></script>\n</body>\n\n</html>" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74596829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9277512/" ]
74,596,832
<p>Update</p> <p>I changed the params to receive the data directly from a JSON dump to see if that fixed the JSON load issue. Received a new error:</p> <blockquote> <p>(b'{\n &quot;errorType&quot;: &quot;ValidationMetadataException&quot;,\n &quot;errorMessage&quot;: &quot;The a' b'rgument is null or empty. Provide an argument that is not null or empty, and' b' then try the command again.&quot;,\n &quot;stackTrace&quot;: [\n &quot;at Amazon.Lambda.P' b'owerShellHost.PowerShellFunctionHost.ExecuteFunction(Stream inputStream, ILa' b'mbdaContext context)&quot;,\n &quot;at lambda_method1(Closure , Stream , ILambda' b'Context , Stream )&quot;,\n<br /> &quot;at Amazon.Lambda.RuntimeSupport.Bootstrap.User' b'CodeLoader.Invoke(Stream lambdaData, ILambdaContext lambdaContext, Stream ou' b'tStream) in /src/Repo/Libraries/src/Amazon.Lambda.RuntimeSupport/Bootstrap/U' b'serCodeLoader.cs:line 145&quot;,\n &quot;at Amazon.Lambda.RuntimeSupport.Handler' b'Wrapper.&lt;&gt;c__DisplayClass8_0.b__0(InvocationRequest invoc' b'ation) in /src/Repo/Libraries/src/Amazon.Lambda.RuntimeSupport/Bootstrap/Han' b'dlerWrapper.cs:line 56&quot;,\n &quot;at Amazon.Lambda.RuntimeSupport.LambdaBoot' b'strap.InvokeOnceAsync(CancellationToken cancellationToken) in /src/Repo/Libr' b'aries/src/Amazon.Lambda.RuntimeSupport/Bootstrap/LambdaBootstrap.cs:line 176' b'&quot;\n ]\n}\n')</p> </blockquote> <p>Still having no success with passing in the lambda name. The code has been updated from the previous post.</p> <p>============================================================== ORIGINAL POST</p> <p>I am trying to execute a lambda function through python. I can successfully do it when I hardcode the variables but when I substitute the variables in I am unable to process the lambda.</p> <p>Here is the working sample with hardcoded values:</p> <pre><code>params = {&quot;value1&quot;: &quot;value1-value&quot;, &quot;value2&quot;: &quot;value2-value&quot;, &quot;value3&quot;: &quot;value3-value&quot;} client = boto3.client('lambda') response = client.invoke( FunctionName='MyLambdaFunctionName', InvocationType='RequestResponse', Payload=json.dumps(params).encode(), ) pprint.pp(response['Payload'].read()) </code></pre> <p>The part that fails is when I replace params with variables. The plan is to pass them in, as I call values but right now, I am testing it and setting the values in the function. The variables are listed below:</p> <p><strong>json_data</strong> | <strong>lambdaName</strong> |</p> <pre><code>lambdaName = os.getenv('TF_VAR_lambdaName') value1=&quot;value1-value&quot; value2=&quot;value2-value&quot; value3=&quot;value3-value&quot; data = {&quot;value1&quot;: &quot;value1-value&quot;, &quot;value2&quot;: &quot;value2-value&quot;, &quot;value3&quot;: &quot;value3-value&quot;} params = json.dumps(data) client = boto3.client('lambda') response = client.invoke( FunctionName=lambdaName, InvocationType='RequestResponse', Payload=json.dumps(params).encode(), ) pprint.pp(response['Payload'].read()) </code></pre> <p>The error I get goes away when I hard-code the JSON or the Lambda Function Name.</p> <p>The error log I am getting is listed below:</p> <pre><code>&gt; Traceback (most recent call last): File &gt; &quot;/Users/go/src/github.com/repo/./cleanup/cleanup.py&quot;, line 25, in &gt; &lt;module&gt; &gt; response = client.invoke( File &quot;/Users/Library/Python/3.9/lib/python/site-packages/botocore/client.py&quot;, &gt; line 515, in _api_call &gt; return self._make_api_call(operation_name, kwargs) File &quot;/Users/Library/Python/3.9/lib/python/site-packages/botocore/client.py&quot;, &gt; line 893, in _make_api_call &gt; request_dict = self._convert_to_request_dict( File &quot;/Users/Library/Python/3.9/lib/python/site-packages/botocore/client.py&quot;, &gt; line 964, in _convert_to_request_dict &gt; request_dict = self._serializer.serialize_to_request( File &quot;/Users/Library/Python/3.9/lib/python/site-packages/botocore/validate.py&quot;, &gt; line 381, in serialize_to_request &gt; raise ParamValidationError(report=report.generate_report()) botocore.exceptions.ParamValidationError: Parameter validation failed: &gt; Invalid type for parameter FunctionName, value: None, type: &lt;class &gt; 'NoneType'&gt;, valid types: &lt;class 'str'&gt; </code></pre>
[ { "answer_id": 74597090, "author": "Giorgi Shalamberidze", "author_id": 20248276, "author_profile": "https://Stackoverflow.com/users/20248276", "pm_score": 2, "selected": true, "text": "const storeItems = [\n {\n name: 'TV',\n price: 800.00,\n inStock: true\n },\n {\n name: 'Phone',\n price: 700.00,\n inStock: false\n },\n {\n name: 'Game Console',\n price: 300.00,\n inStock: true\n },\n\n {\n name: 'Smart Watch',\n price: 200.00,\n inStock: false\n },\n];\n\n\nstoreItems.forEach(function(n, i, a) {\n if (n.inStock == true) {\n //$('p').addClass('inStock');\n $('#appendToMe').append('<p class=\"inStock\">' + n.name + ': ' + n.price \n + \n '</p>');\n }\n if (n.inStock == false) {\n //$('p').addClass('notInStock');\n $('#appendToMe').append('<p class=\"notInStock\">' + n.name + ': ' + \n n.price + ' Not in stock' + '</p>');\n }\n}) .inStock, .notInStock {\n padding: 10px;\n margin: 10px 0;\n font-family: Helvetica;\n}\n\n.inStock {\n background-color: #79f;\n}\n\n.notInStock {\n background-color: #eff;\n} <!DOCTYPE html>\n<html>\n <head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width\">\n <title>repl.it</title>\n <link href=\"style.css\" rel=\"stylesheet\" type=\"text/css\" />\n </head>\n <body>\n <div id=\"appendToMe\">\n </div>\n <script src=\"https://code.jquery.com/jquery-3.5.0.slim.min.js\" integrity=\"sha256-MlusDLJIP1GRgLrOflUQtshyP0TwT/RHXsI1wWGnQhs=\" crossorigin=\"anonymous\"></script>\n <script src=\"script.js\"></script>\n </body>\n</html>" }, { "answer_id": 74597288, "author": "Ha Tai", "author_id": 14036048, "author_profile": "https://Stackoverflow.com/users/14036048", "pm_score": 0, "selected": false, "text": "const storeItems = [\n {\n name: 'TV',\n price: 800.00,\n inStock: true\n },\n {\n name: 'Phone',\n price: 700.00,\n inStock: false\n },\n {\n name: 'Game Console',\n price: 300.00,\n inStock: true\n },\n\n {\n name: 'Smart Watch',\n price: 200.00,\n inStock: false\n },\n ];\n\n\n storeItems.forEach(function (n, i, a) {\n const id = Date.now();\n if (n.inStock == true) {\n $('#appendToMe').append(`<p id=\"${id}-${i}\">` + n.name + ': ' + n.price + '</p>');\n $(`p#${id}-${i}`).addClass('inStock');\n }\n if (n.inStock == false) {\n $('#appendToMe').append(`<p id=\"${id}-${i}\">` + n.name + ': ' + n.price + ' Not in stock' + '</p>');\n $(`p#${id}-${i}`).addClass('notInStock');\n }\n }) <style>\n .inStock,\n .notInStock {\n padding: 10px;\n margin: 10px 0;\n font-family: Helvetica;\n }\n\n .inStock {\n background-color: #79f;\n }\n\n .notInStock {\n background-color: #eff;\n }\n</style> <!DOCTYPE html>\n<html>\n\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width\">\n <title>repl.it</title>\n <link href=\"style.css\" rel=\"stylesheet\" type=\"text/css\" />\n</head>\n\n<body>\n <div id=\"appendToMe\">\n </div>\n <script src=\"https://code.jquery.com/jquery-3.5.0.slim.min.js\"\n integrity=\"sha256-MlusDLJIP1GRgLrOflUQtshyP0TwT/RHXsI1wWGnQhs=\" crossorigin=\"anonymous\"></script>\n <script src=\"script.js\"></script>\n</body>\n\n</html>" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74596832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13893988/" ]
74,596,838
<p>I have a React website.<br /> I receive messages like this:</p> <pre><code>useEffect(() =&gt; { socket.on('message', message =&gt; { console.log(message) }) }, [socket]) </code></pre> <p>I send messages like this:</p> <pre><code>socket.emit('chatMessage', { message, id }) </code></pre> <p>Server side:</p> <pre><code>socket.on('chatMessage', ({ message }) =&gt; { socket.broadcast.emit('message', message) }) </code></pre> <p>First time there is 2 message (1 for the user who sent it), the next time there is 4, 6, 8 and so on.</p>
[ { "answer_id": 74596958, "author": "Azzy", "author_id": 2122822, "author_profile": "https://Stackoverflow.com/users/2122822", "pm_score": 3, "selected": true, "text": "useEffect(() => {\n \n let isValidScope = true;\n\n socket.on('message', message => {\n console.log(message)\n // if message received when component unmounts\n // stop executing the code\n if (!isValidScope) { return; };\n\n // if you need to access latest state, props or variables\n // without including them in the depedency array\n // i.e you want to refer the variables without reseting the connection\n // use useRef or some custom solution (link below)\n\n })\n\n return () => {\n // cleanup code, disconnect\n // socket.disconnect()\n isValidScope = false;\n }\n \n}, [socket])\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74596838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20197693/" ]
74,596,858
<pre><code>let index = 10; let jump = 2; for (;;) { // Write Your Code Here let i = index; console.log(i); i -= jump; if (i === jump) { break; } } </code></pre> <p>I think that I know the logic of the code, but I don't understand why it does loop infinitely</p>
[ { "answer_id": 74596912, "author": "Maxwell D. Dorliea", "author_id": 12906648, "author_profile": "https://Stackoverflow.com/users/12906648", "pm_score": 1, "selected": false, "text": "10 i i jump(2) \nlet index = 10;\nlet jump = 2;\nlet i = index;\n\nfor (;;) {\n // Write Your Code Here\n console.log(i);\n i -= jump;\n if (i === jump) {\n break;\n }\n }\n let index = 10;\nlet jump = 2;\n\nfor (;;) {\n // Write Your Code Here\n console.log(i);\n index -= jump;\n if (index === jump) {\n break;\n }\n }\n" }, { "answer_id": 74596922, "author": "codeburst", "author_id": 20164415, "author_profile": "https://Stackoverflow.com/users/20164415", "pm_score": 2, "selected": true, "text": "let index = 10;\nlet jump = 2;\nlet i = index;\n\nfor (;;) {\n // Write Your Code Here\n \n console.log(i);\n i -= jump;\n if (i === jump) {\n break;\n console.log('broken...')\n }\n }\n" }, { "answer_id": 74596975, "author": "Hyde", "author_id": 20620414, "author_profile": "https://Stackoverflow.com/users/20620414", "pm_score": 0, "selected": false, "text": " index = 9 (any odd number);\n jump = 2 (any even number);\n i -= jump; //i will be odd all the time;\n if (i === jump) //odd === even: never match\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74596858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16385537/" ]
74,596,876
<p>I'm trying to populate the courses selectfield in my webapp using data from the database. this is my attempt.</p> <p>this the form `</p> <pre><code>class StudentForm(FlaskForm): idnumber = StringField('ID Number', [validators.DataRequired(), validators.Length(min=9, max=9)]) fname = StringField('First Name', [validators.DataRequired(), validators.Length(max=50)]) mname = StringField('Middle Name', [validators.Length(max=50)]) lname = StringField('Last Name', [validators.DataRequired(), validators.Length(max=50)]) gender = SelectField('Gender', choices=gengen) yearlvl = SelectField('Year Level', choices= year_level) course = SelectField('Course', choices= models.Courses.populate()) submit = SubmitField(&quot;Save&quot;) </code></pre> <p>`</p> <pre><code> @classmethod def populate(cls): curs = mysql.connection.cursor() sql = curs.execute(&quot;SELECT COURSEID from courses&quot;) if sql &gt; 0: result = curs.fetchall() return result </code></pre> <p>'</p> <p>when I run the program i get this error</p> <p>`</p> <pre><code> File &quot;C:\laragon\SISwebapp\webapp\students\forms.py&quot;, line 15, in StudentForm course = SelectField('Course', choices= models.Courses.populate()) File &quot;C:\laragon\SISwebapp\webapp\models.py&quot;, line 87, in populate curs = mysql.connection.cursor() AttributeError: 'NoneType' object has no attribute 'cursor' </code></pre> <p>` I can't seem to figure out whats wrong..</p> <p>edit:</p> <p>This part works fine:</p> <pre><code> def all(cls): cursor = mysql.connection.cursor() sql = &quot;SELECT * from courses&quot; cursor.execute(sql) result = cursor.fetchall() return result </code></pre> <p>It fetches all the data from the database table. However, it doesn't work when selecting only one column. Please bear with me. I'm new to this kind of stuff.</p>
[ { "answer_id": 74596912, "author": "Maxwell D. Dorliea", "author_id": 12906648, "author_profile": "https://Stackoverflow.com/users/12906648", "pm_score": 1, "selected": false, "text": "10 i i jump(2) \nlet index = 10;\nlet jump = 2;\nlet i = index;\n\nfor (;;) {\n // Write Your Code Here\n console.log(i);\n i -= jump;\n if (i === jump) {\n break;\n }\n }\n let index = 10;\nlet jump = 2;\n\nfor (;;) {\n // Write Your Code Here\n console.log(i);\n index -= jump;\n if (index === jump) {\n break;\n }\n }\n" }, { "answer_id": 74596922, "author": "codeburst", "author_id": 20164415, "author_profile": "https://Stackoverflow.com/users/20164415", "pm_score": 2, "selected": true, "text": "let index = 10;\nlet jump = 2;\nlet i = index;\n\nfor (;;) {\n // Write Your Code Here\n \n console.log(i);\n i -= jump;\n if (i === jump) {\n break;\n console.log('broken...')\n }\n }\n" }, { "answer_id": 74596975, "author": "Hyde", "author_id": 20620414, "author_profile": "https://Stackoverflow.com/users/20620414", "pm_score": 0, "selected": false, "text": " index = 9 (any odd number);\n jump = 2 (any even number);\n i -= jump; //i will be odd all the time;\n if (i === jump) //odd === even: never match\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74596876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16356106/" ]
74,596,907
<p>The problem I'm now encourting is that my checkbox isnt being checked when my value returns a value &quot;true&quot;. May I know how I am able to set the checkbox is checked if its true and unchecked if its false.</p> <pre><code> &lt;input type=&quot;checkbox&quot; name=&quot;s1syslog_enabled&quot; id=&quot;s1syslog_enabled&quot; value=&quot;${requestScope.data}&quot;&gt; </code></pre>
[ { "answer_id": 74596912, "author": "Maxwell D. Dorliea", "author_id": 12906648, "author_profile": "https://Stackoverflow.com/users/12906648", "pm_score": 1, "selected": false, "text": "10 i i jump(2) \nlet index = 10;\nlet jump = 2;\nlet i = index;\n\nfor (;;) {\n // Write Your Code Here\n console.log(i);\n i -= jump;\n if (i === jump) {\n break;\n }\n }\n let index = 10;\nlet jump = 2;\n\nfor (;;) {\n // Write Your Code Here\n console.log(i);\n index -= jump;\n if (index === jump) {\n break;\n }\n }\n" }, { "answer_id": 74596922, "author": "codeburst", "author_id": 20164415, "author_profile": "https://Stackoverflow.com/users/20164415", "pm_score": 2, "selected": true, "text": "let index = 10;\nlet jump = 2;\nlet i = index;\n\nfor (;;) {\n // Write Your Code Here\n \n console.log(i);\n i -= jump;\n if (i === jump) {\n break;\n console.log('broken...')\n }\n }\n" }, { "answer_id": 74596975, "author": "Hyde", "author_id": 20620414, "author_profile": "https://Stackoverflow.com/users/20620414", "pm_score": 0, "selected": false, "text": " index = 9 (any odd number);\n jump = 2 (any even number);\n i -= jump; //i will be odd all the time;\n if (i === jump) //odd === even: never match\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74596907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19389184/" ]
74,596,909
<p>I have an express application that I didn't write. Simply the app takes params, calls a cms api with them and it builds dynamically a page using handlebars which it sends in a response.</p> <p>In the request I get a JWT token in a cookie and I need to pass it to every api call now.</p> <p>The logic is however quite extensive and there are lot of functions called between the <code>app.get()</code> and the final function <code>getFromBackend</code> that makes the api call and needs the jwt token. There are also many implementations of it in async handlebars helpers etc.</p> <p>So I was wondering if I do have to pass the value through all of the functions that are called between <code>app.get</code> and the <code>getFromBackend</code> and in the helpers that make api calls. Or if there is a pattern that would allow me to use the value of the request cookie inside the function directly or maybe interject the api call and pass the value to the call.</p> <p>Considering especially that all of the api calls that are made for the req will always have the same jwt token. There are several api calls happening for each req but all of them implement the <code>getFromBackend</code> function.</p>
[ { "answer_id": 74597063, "author": "jfriend00", "author_id": 816620, "author_profile": "https://Stackoverflow.com/users/816620", "pm_score": 1, "selected": false, "text": "response this.token" }, { "answer_id": 74599830, "author": "Sanket", "author_id": 4104812, "author_profile": "https://Stackoverflow.com/users/4104812", "pm_score": 0, "selected": false, "text": "request response request response" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74596909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11521002/" ]
74,596,933
<p>i have a streambuilder to display grid of 3 image, but i get an error about datatype in the streambuilder. 'String' is not a subtype of type 'DateTime', so i use toDate() but the method is not working. before that i get 'TimeStamp' is not a subtype of type 'DateTime' too, is there an easy way for managing datatype from firestore database?</p> <pre><code> final Stream&lt;QuerySnapshot&gt; _constructed = FirebaseFirestore.instance .collection('fotoupload') .orderBy(&quot;createdAt&quot;, descending: true) .snapshots(); Widget gridViewWidget(String docId, String img, String name, int downloads, DateTime date, String postuid, String userImg, String email) { return GridView.count( primary: false, padding: EdgeInsets.all(6), crossAxisSpacing: 1, crossAxisCount: 1, children: [ GestureDetector( onTap: () { //createOwnerDetails }, child: Center( child: Image.network( img, fit: BoxFit.fill, ), ), ), ], ); } @override Widget build(BuildContext context) { // return Image == null ? buildSplashScreen() : buildUploadForm(); return Scaffold(body: StreamBuilder&lt;QuerySnapshot&gt;( stream: _constructed, builder: (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return Center( child: CircularProgressIndicator(), ); } else if (snapshot.connectionState == ConnectionState.active) { print(snapshot.connectionState); print(snapshot.data!.docs); print(snapshot .data!.docs.length); // check all the data and connectionstate if (snapshot.data!.docs.isNotEmpty) { return GridView.builder( itemCount: snapshot.data!.docs.length, gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 3), itemBuilder: (BuildContext context, int index) { return gridViewWidget( snapshot.data!.docs[index].id, snapshot.data!.docs[index]['Image'], snapshot.data!.docs[index]['name'], snapshot.data!.docs[index]['downloads'], snapshot.data!.docs[index]['createdAt'].toDate(),//this is the problem snapshot.data!.docs[index]['postid'], snapshot.data!.docs[index]['userImage'], snapshot.data!.docs[index]['email'], ); }, ); } else { return Center( child: Text( 'There is no tasks', style: TextStyle(fontSize: 20), ), ); } } else { return Center( child: Text( 'Something went wrong', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 30), ), ); } }, ), ); } </code></pre> <p><a href="https://i.stack.imgur.com/4TB5L.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4TB5L.png" alt="Firebase Console" /></a> <a href="https://i.stack.imgur.com/Nt7Od.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Nt7Od.png" alt="Debug Console" /></a></p> <p>i just want to display the data from firestore, is there something wrong from my streambuilder?</p>
[ { "answer_id": 74597052, "author": "manhtuan21", "author_id": 8921450, "author_profile": "https://Stackoverflow.com/users/8921450", "pm_score": 1, "selected": false, "text": "DateTime.fromMicrosecondsSinceEpoch(snapshot.data!.docs[index]['createdAt'])\n" }, { "answer_id": 74604963, "author": "Canada2000", "author_id": 14728030, "author_profile": "https://Stackoverflow.com/users/14728030", "pm_score": 0, "selected": false, "text": "snapshot.data!.docs[index]['createdAt'].toDate(),//this is the problem\n (snapshot.data!.docs[index]['createdAt'] == null) ? null : (snapshot.data!.docs[index]['createdAt'] as Timestamp).toDate()\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74596933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19826650/" ]
74,596,992
<p>After creating my demo github pages. I put following code into the index.html file :</p> <pre><code> &lt;html&gt; &lt;head&gt; &lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot;&gt; &lt;title&gt;My TITLE&lt;/title&gt; &lt;link rel=&quot;icon&quot; type=&quot;image/x-icon&quot; href=&quot;images/icon.ico&quot;&gt; &lt;/head&gt; &lt;body&gt; &lt;iframe src=&quot;2-seconds-silence.mp3&quot; allow=&quot;autoplay&quot; id=&quot;audio&quot; style=&quot;display: none&quot; hidden=&quot;&quot;&gt;&lt;/iframe&gt; &lt;audio id=&quot;player&quot; autoplay loop&gt; &lt;source src=&quot;hello.mp3&quot; type=&quot;audio/mp3&quot;&gt; &lt;/audio&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>However after loading the page by chrome, it didn't run. Is there any way to fix this?</p>
[ { "answer_id": 74597044, "author": "Yamin Shaikh", "author_id": 20620764, "author_profile": "https://Stackoverflow.com/users/20620764", "pm_score": 0, "selected": false, "text": "const audio = document.queryselector(\"#audioId\") window.addEventListener(\"load\",() => {audio.play()})" }, { "answer_id": 74597242, "author": "Ali Bektash", "author_id": 1792984, "author_profile": "https://Stackoverflow.com/users/1792984", "pm_score": 2, "selected": false, "text": "<html>\n <head>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n <title>My TITLE</title>\n <link rel=\"icon\" type=\"image/x-icon\" href=\"images/icon.ico\">\n </head>\n \n <body>\n \n <iframe src=\"2-seconds-silence.mp3\" allow=\"autoplay\" id=\"audio\" style=\"display: none\" hidden=\"\"></iframe>\n\n <script type=\"text/javascript\">\n document.addEventListener('DOMContentLoaded', function() {\n var audioTag = document.createElement(\"AUDIO\");\n\n audioTag.setAttribute(\"src\",\"hello.mp3\");\n\n document.body.appendChild(audioTag);\n }, false);\n </script>\n </body>\n </html>" }, { "answer_id": 74597648, "author": "Faisal Russel", "author_id": 11196516, "author_profile": "https://Stackoverflow.com/users/11196516", "pm_score": 1, "selected": false, "text": "<audio src=\"mysong.mp3\" id=\"my_audio\" loop=\"loop\"></audio>\n<script type=\"text/javascript\">\nwindow.onload=function(){\n document.getElementById(\"my_audio\").play();\n}\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74596992", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15569855/" ]
74,596,998
<p>I know this same question is already asked before. But I have tried the <a href="https://stackoverflow.com/a/46438705/6854117">solution</a> but it's not working for me.</p> <pre><code> $comp_ids = AllowArea::find() -&gt;select(['comp_code']) -&gt;where(['user_id' =&gt; Yii::$app-&gt;user-&gt;id]) -&gt;column(); $ref = (new \yii\db\Query()) -&gt;select([ 'ProductCode', 'ProductNameFull', 'ProductSpec', 'ProductGroup', 'CompanyCode', 'CompanyName' ,'Price', 'PurchasePrice' ])-&gt;from('Product') -&gt;andFilterWhere(['CompanyCode' =&gt; $comp_ids]) -&gt;all(Yii::$app-&gt;sds); </code></pre> <p>It's giving me empty data.</p> <p><strong>Flow</strong> The users are assigned areas and some users are assigned areas with a company. So I want the above query to return me the result whether the condition fails or not.</p> <p><strong>Update 1</strong> The <code>SQL</code> which I am getting is</p> <pre><code>SELECT `ProductCode`, `ProductNameFull`, `ProductSpec`, `ProductGroup`, `CompanyCode`, `CompanyName`, `Price`, `PurchasePrice` FROM `Product` WHERE `CompanyCode` IS NULL </code></pre> <p>Any help would be highly appreciated.</p>
[ { "answer_id": 74597173, "author": "Malik", "author_id": 10804565, "author_profile": "https://Stackoverflow.com/users/10804565", "pm_score": 2, "selected": false, "text": "orFilterWhere()" }, { "answer_id": 74610340, "author": "Евгений", "author_id": 12452318, "author_profile": "https://Stackoverflow.com/users/12452318", "pm_score": 1, "selected": false, "text": "$ref = (new \\yii\\db\\Query())\n ->select([\n 'ProductCode',\n 'ProductNameFull',\n 'ProductSpec',\n 'ProductGroup',\n 'CompanyCode',\n 'CompanyName'\n ,'Price',\n 'PurchasePrice'\n ])->from('Product');\n\nif (!empty($comp_ids)) {\n $ref->andFilterWhere(['CompanyCode' => $comp_ids]);\n}\n\n$ref = $ref->all(Yii::$app->sds);\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74596998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6854117/" ]
74,597,000
<p>Created Custom annotation and add annotation at method level and pass value to Spring-Aspect.</p> <p>springboot: application.properties spring.event.type=TEST</p> <p>Output: PreHook Value|${spring.event.type}</p> <p>I am expecting : TEST</p> <p>Can someone please help how to populate value from properties file and inject to annotation.</p> <pre><code>@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface PreHook { String eventType(); } @Aspect @Component public class ValidationAOP { @Before(&quot;@annotation(com.example.demo.annotation.PreHook)&quot;) public void doAccessCheck(JoinPoint call) { System.out.println(&quot;ValidationAOP.doAccessCheck&quot;); MethodSignature signature = (MethodSignature) call.getSignature(); Method method = signature.getMethod(); PreHook preHook = method.getAnnotation(PreHook.class); System.out.println(&quot;PreHook Value|&quot; + preHook.eventType()); } }` @RestController public class AddController { @GetMapping(&quot;/&quot;) @PreHook(eventType = &quot;${spring.event.type}&quot;) public String test() { System.out.println(&quot;Testcontroller&quot;); return &quot;Welcome Home&quot;; } } </code></pre>
[ { "answer_id": 74597173, "author": "Malik", "author_id": 10804565, "author_profile": "https://Stackoverflow.com/users/10804565", "pm_score": 2, "selected": false, "text": "orFilterWhere()" }, { "answer_id": 74610340, "author": "Евгений", "author_id": 12452318, "author_profile": "https://Stackoverflow.com/users/12452318", "pm_score": 1, "selected": false, "text": "$ref = (new \\yii\\db\\Query())\n ->select([\n 'ProductCode',\n 'ProductNameFull',\n 'ProductSpec',\n 'ProductGroup',\n 'CompanyCode',\n 'CompanyName'\n ,'Price',\n 'PurchasePrice'\n ])->from('Product');\n\nif (!empty($comp_ids)) {\n $ref->andFilterWhere(['CompanyCode' => $comp_ids]);\n}\n\n$ref = $ref->all(Yii::$app->sds);\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20620570/" ]
74,597,006
<p>I was wondering if there was a simple alternative to lambda in my code.</p> <pre><code>def add_attack(self, attack_name): if attack_name in self.known_attacks and attack_name not in self.attacks: try: assert(len(self.attacks) &lt; 4) self.attacks[attack_name] = self.known_attacks.get(attack_name) return True except: #find the min value of self.attacks minval = min(self.attacks.keys(), key=(lambda k: self.attacks[k])) for keys, values in self.attacks.items(): if self.attacks[minval] == values and min(minval, keys) == keys: minval = keys del self.attacks[minval] self.attacks[attack_name] = self.known_attacks.get(attack_name) return True else: return False </code></pre> <p>I'm still learning python, and the lambda function is throwing me off since I haven't learned that much about it yet. Instead of using lambda, can someone help me out with another function to replace lambda? Thanks!</p>
[ { "answer_id": 74597095, "author": "PVTejas _ys_", "author_id": 19726899, "author_profile": "https://Stackoverflow.com/users/19726899", "pm_score": 2, "selected": false, "text": "def return_attacks(self,k):\n return self.attacks[k]\n minval = min(self.attacks.keys(), key=(self.return_attacks))\n lambda x : expr(x) func def func(x):\n return expr(x)\n" }, { "answer_id": 74597319, "author": "Sezai Burak Kantarcı", "author_id": 10618163, "author_profile": "https://Stackoverflow.com/users/10618163", "pm_score": 1, "selected": false, "text": "minval = min(self.attacks.keys(), key=(lambda k: self.attacks[k]))\n min() minval self.attacks.keys() self.attacks[] def find_min_key(self, my_dict):\n return min(my_dict, key= my_dict.get)\n min_val = self.find_min_key(self.attacks)\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20620709/" ]
74,597,017
<p>Given yaml config file that looks like this:</p> <pre><code>key1: key11:value1 key12:value2 key2: key21:value3 </code></pre> <p>How can I convert it in a bash script (preferable with yq) to env vars prefixed with a string? Desired output for <code>env</code>:</p> <pre><code>TF_VAR_key11=value1 TF_VAR_key12=value2 TF_VAR_key21=value3 </code></pre>
[ { "answer_id": 74597095, "author": "PVTejas _ys_", "author_id": 19726899, "author_profile": "https://Stackoverflow.com/users/19726899", "pm_score": 2, "selected": false, "text": "def return_attacks(self,k):\n return self.attacks[k]\n minval = min(self.attacks.keys(), key=(self.return_attacks))\n lambda x : expr(x) func def func(x):\n return expr(x)\n" }, { "answer_id": 74597319, "author": "Sezai Burak Kantarcı", "author_id": 10618163, "author_profile": "https://Stackoverflow.com/users/10618163", "pm_score": 1, "selected": false, "text": "minval = min(self.attacks.keys(), key=(lambda k: self.attacks[k]))\n min() minval self.attacks.keys() self.attacks[] def find_min_key(self, my_dict):\n return min(my_dict, key= my_dict.get)\n min_val = self.find_min_key(self.attacks)\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5720414/" ]
74,597,041
<p>I have an class defined in C# as Servicing and i need to convert this code to Python. So how do i convert the Servicing class to a list datatype in python and then use it in Adjusted class?</p> <pre><code>class Servicing { public long StatementName{ get; set; } public string City{ get; set; } } </code></pre> <p>Now this class is used in another class Adjusted</p> <pre><code>class Adjusted { public List&lt;Servicing&gt; Services{ get; set; } } </code></pre> <p>For Servicing class I can define the constructor like this and then have its setter and getter defined too.</p> <pre><code>class Servicing: def __init__(self): self._StatementName=0.0 self._City= &quot;&quot; </code></pre> <p>But how do I use this Servicing class in a similar way how it is used in Adjusted class?</p>
[ { "answer_id": 74597095, "author": "PVTejas _ys_", "author_id": 19726899, "author_profile": "https://Stackoverflow.com/users/19726899", "pm_score": 2, "selected": false, "text": "def return_attacks(self,k):\n return self.attacks[k]\n minval = min(self.attacks.keys(), key=(self.return_attacks))\n lambda x : expr(x) func def func(x):\n return expr(x)\n" }, { "answer_id": 74597319, "author": "Sezai Burak Kantarcı", "author_id": 10618163, "author_profile": "https://Stackoverflow.com/users/10618163", "pm_score": 1, "selected": false, "text": "minval = min(self.attacks.keys(), key=(lambda k: self.attacks[k]))\n min() minval self.attacks.keys() self.attacks[] def find_min_key(self, my_dict):\n return min(my_dict, key= my_dict.get)\n min_val = self.find_min_key(self.attacks)\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20497575/" ]
74,597,046
<p>Hi I have question about golang micro service via kubernetes container. Example I have 2 deploy of code name A and B.</p> <ol> <li>A have 1 pod do a sent request to create document in B service.</li> <li>B have autoscaling config between 1 - 5 pod waiting for request from A and process to create a document in many collection.</li> </ol> <p>Sometime service A have error &quot;EOF&quot; from service B and I go to check log in service B couldn't find error that makes pod terminate or crashloopbackoff status from kubectl terminal it like service B just stop running this process.</p> <p>I wonder cause of error &quot;EOF&quot; is about autoscaling config in B service in my understanding high traffic to B service have to scale up pod to 5 pod but when traffic go down pod must scale down too.</p> <p>It is possible if any process working in pod that would to scale down it terminated before process success?</p>
[ { "answer_id": 74597095, "author": "PVTejas _ys_", "author_id": 19726899, "author_profile": "https://Stackoverflow.com/users/19726899", "pm_score": 2, "selected": false, "text": "def return_attacks(self,k):\n return self.attacks[k]\n minval = min(self.attacks.keys(), key=(self.return_attacks))\n lambda x : expr(x) func def func(x):\n return expr(x)\n" }, { "answer_id": 74597319, "author": "Sezai Burak Kantarcı", "author_id": 10618163, "author_profile": "https://Stackoverflow.com/users/10618163", "pm_score": 1, "selected": false, "text": "minval = min(self.attacks.keys(), key=(lambda k: self.attacks[k]))\n min() minval self.attacks.keys() self.attacks[] def find_min_key(self, my_dict):\n return min(my_dict, key= my_dict.get)\n min_val = self.find_min_key(self.attacks)\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12942651/" ]
74,597,048
<p>I have two datasets each has around 100 variables that have similar names with some minor differences. The variable names in dataset 1 are, CHILD1xxx child1xxx, and the variable names in dataset 2 are, CHILD2xxx child2xxx</p> <p>For each of the datasets, I want to systematically get rid of the number (i.e.1 or 2) so that the variable names are all CHILDxxx or childxxx.</p> <p>I was thinking about using <strong>str_replace</strong> or <strong>str_replace_all</strong> but wasn't sure what kind of regular expression I would use to capture the above criteria. I would greatly appreciate any insights on this.</p> <p><strong>UPDATES 11/28/22</strong></p> <p>The final working code looks like this for replacing names in the entire dataset, as suggested by @Josh White:</p> <pre><code>colnames(DATASET)&lt;-gsub(&quot;^(child)\\d+(.*)&quot;, &quot;\\1\\2&quot;, colnames(DATASET), ignore.case = TRUE) </code></pre>
[ { "answer_id": 74597125, "author": "Josh White", "author_id": 20289207, "author_profile": "https://Stackoverflow.com/users/20289207", "pm_score": 2, "selected": false, "text": "gsub() \\\\d+ Inf \"\\\\1\\\\2\" x <- c(\"CHILD1xxx\", \"child2yyy\", \"Child23hello\")\ngsub(\"^(child)\\\\d+(.*)\", \"\\\\1\\\\2\", x, ignore.case = TRUE)\n [1] \"CHILDxxx\" \"childyyy\" \"Childhello\"\n gsub(\"\\\\d\", \"\", x)\n [1] \"CHILDxxx\" \"childyyy\" \"Childhello\"\n" }, { "answer_id": 74597216, "author": "Chris Ruehlemann", "author_id": 8039978, "author_profile": "https://Stackoverflow.com/users/8039978", "pm_score": 0, "selected": false, "text": "str_remove \\\\d+ library(stringr)\nstr_remove(x, \"\\\\d+\")\n[1] \"CHILDxxx\" \"childyyy\" \"Childhello\"\n x <- c(\"CHILD1xxx\", \"child2yyy\", \"Child23hello\")\n str_remove rename_with df %>%\n rename_with(~str_remove(., \"\\\\d+\"))\n CHILDxxx childyyy Childhello SomeOther\n1 NA NA NA NA\n df <- data.frame(\n CHILD1xxx = NA,\n child2yyy = NA,\n Child23hello = NA,\n SomeOther = NA\n)\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19080214/" ]
74,597,067
<p>I have this table that shows the same id with different types and every type have the same rank that ordered by start date.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>type</th> <th>start date</th> <th>rank</th> </tr> </thead> <tbody> <tr> <td>111</td> <td>15</td> <td>1/1/22</td> <td>1</td> </tr> <tr> <td>111</td> <td>15</td> <td>1/3/22</td> <td>1</td> </tr> <tr> <td>111</td> <td>15</td> <td>2/04/22</td> <td>1</td> </tr> <tr> <td>111</td> <td>23</td> <td>1/02/22</td> <td>2</td> </tr> <tr> <td>111</td> <td>23</td> <td>1/3/22</td> <td>2</td> </tr> <tr> <td>111</td> <td>25</td> <td>16/03/22</td> <td>3</td> </tr> </tbody> </table> </div> <p>I want to get table that will show only the last row for every rank</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>type</th> <th>start date</th> <th>rank</th> </tr> </thead> <tbody> <tr> <td>111</td> <td>15</td> <td>2/04/22</td> <td>1</td> </tr> <tr> <td>111</td> <td>23</td> <td>1/3/22</td> <td>2</td> </tr> <tr> <td>111</td> <td>25</td> <td>16/03/22</td> <td>3</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74597125, "author": "Josh White", "author_id": 20289207, "author_profile": "https://Stackoverflow.com/users/20289207", "pm_score": 2, "selected": false, "text": "gsub() \\\\d+ Inf \"\\\\1\\\\2\" x <- c(\"CHILD1xxx\", \"child2yyy\", \"Child23hello\")\ngsub(\"^(child)\\\\d+(.*)\", \"\\\\1\\\\2\", x, ignore.case = TRUE)\n [1] \"CHILDxxx\" \"childyyy\" \"Childhello\"\n gsub(\"\\\\d\", \"\", x)\n [1] \"CHILDxxx\" \"childyyy\" \"Childhello\"\n" }, { "answer_id": 74597216, "author": "Chris Ruehlemann", "author_id": 8039978, "author_profile": "https://Stackoverflow.com/users/8039978", "pm_score": 0, "selected": false, "text": "str_remove \\\\d+ library(stringr)\nstr_remove(x, \"\\\\d+\")\n[1] \"CHILDxxx\" \"childyyy\" \"Childhello\"\n x <- c(\"CHILD1xxx\", \"child2yyy\", \"Child23hello\")\n str_remove rename_with df %>%\n rename_with(~str_remove(., \"\\\\d+\"))\n CHILDxxx childyyy Childhello SomeOther\n1 NA NA NA NA\n df <- data.frame(\n CHILD1xxx = NA,\n child2yyy = NA,\n Child23hello = NA,\n SomeOther = NA\n)\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13942179/" ]
74,597,111
<pre><code>views.py import datetime from .filters import MyModelFilter from django.shortcuts import render import pymysql from django.http import HttpResponseRedirect from facligoapp.models import Scrapper from django.db.models import Q from django.utils import timezone import pytz from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger users = &quot;&quot; def index(request): if request.method == &quot;POST&quot;: from_date = request.POST.get(&quot;from_date&quot;) f_date = datetime.datetime.strptime(from_date,'%Y-%m-%d') print(f_date) to_date = request.POST.get(&quot;to_date&quot;) t_date = datetime.datetime.strptime(to_date, '%Y-%m-%d') print(t_date) get_records_by_date = Scrapper.objects.all().filter(Q(start_time__date=f_date)|Q(end_time__date=t_date)) print(get_records_by_date) filtered_dates = MyModelFilter(request.GET,queryset=get_records_by_date) page = request.GET.get('page', 1) paginator = Paginator(filtered_dates.qs, 5) global users try: users = paginator.get_page(page) except PageNotAnInteger: users = paginator.page(1) except EmptyPage: users = paginator.page(paginator.num_pages) else: roles = Scrapper.objects.all() page = request.GET.get('page', 1) paginator = Paginator(roles, 5) try: users = paginator.page(page) except PageNotAnInteger: users = paginator.page(1) except EmptyPage: users = paginator.page(paginator.num_pages) return render(request, &quot;home.html&quot;, {&quot;users&quot;: users}) return render(request, &quot;home.html&quot;, {&quot;users&quot;: users}) filters.py: import django_filters from.models import Scrapper class MyModelFilter(django_filters.FilterSet): class Meta: model = Scrapper # Declare all your model fields by which you will filter # your queryset here: fields = ['start_time', 'end_time'] home.html &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;meta charset=&quot;utf-8&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt; &lt;link href=&quot;http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css&quot; rel=&quot;stylesheet&quot; id=&quot;bootstrap-css&quot;&gt; &lt;script src=&quot;http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js&quot;&gt;&lt;/script&gt; &lt;script src=&quot;http://code.jquery.com/jquery-1.11.1.min.js&quot;&gt;&lt;/script&gt; &lt;body&gt; &lt;style&gt; h2 {text-align: center;} &lt;/style&gt; &lt;h1&gt;Facilgo Completed Jobs&lt;/h1&gt; &lt;form action=&quot;&quot; method=&quot;post&quot;&gt; {% csrf_token %} &lt;label for=&quot;from_date&quot;&gt;From Date:&lt;/label&gt; &lt;input type=&quot;date&quot; id=&quot;from_date&quot; name=&quot;from_date&quot;&gt; &lt;label for=&quot;to_date&quot;&gt;To Date:&lt;/label&gt; &lt;input type=&quot;date&quot; id=&quot;to_date&quot; name=&quot;to_date&quot;&gt; &lt;input type=&quot;submit&quot;&gt;&lt;br&gt; &lt;/form&gt; &lt;div class=&quot;container&quot;&gt; &lt;div class=&quot;row&quot;&gt; &lt;div class=&quot;col-md-12&quot;&gt; &lt;h2&gt;Summary Details&lt;/h2&gt; &lt;table id=&quot;bootstrapdatatable&quot; class=&quot;table table-striped table-bordered&quot; width=&quot;100%&quot;&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;scrapper_id&lt;/th&gt; &lt;th&gt;scrapper_jobs_log_id&lt;/th&gt; &lt;th&gt;external_job_source_id&lt;/th&gt; &lt;th&gt;start_time&lt;/th&gt; &lt;th&gt;end_time&lt;/th&gt; &lt;th&gt;scrapper_status&lt;/th&gt; &lt;th&gt;processed_records&lt;/th&gt; &lt;th&gt;new_records&lt;/th&gt; &lt;th&gt;skipped_records&lt;/th&gt; &lt;th&gt;error_records&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; {% for stud in users %} {% csrf_token %} &lt;tr&gt; &lt;td&gt;{{stud.scrapper_id}}&lt;/td&gt; &lt;td&gt;{{stud.scrapper_jobs_log_id}}&lt;/td&gt; &lt;td&gt;{{stud.external_job_source_id}}&lt;/td&gt; &lt;td&gt;{{stud.start_time}}&lt;/td&gt; &lt;td&gt;{{stud.end_time}}&lt;/td&gt; &lt;td&gt;{{stud.scrapper_status}}&lt;/td&gt; &lt;td&gt;{{stud.processed_records}}&lt;/td&gt; &lt;td&gt;{{stud.new_records}}&lt;/td&gt; &lt;td&gt;{{stud.skipped_records}}&lt;/td&gt; &lt;td&gt;{{stud.error_records}}&lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;/tbody&gt; &lt;/table&gt; {% if users.has_other_pages %} &lt;ul class=&quot;pagination&quot;&gt; {% if users.has_previous %} &lt;li&gt;&lt;a href=&quot;?page={{ users.previous_page_number }}&quot;&gt;«&lt;/a&gt;&lt;/li&gt; {% else %} &lt;li class=&quot;disabled&quot;&gt;&lt;span&gt;«&lt;/span&gt;&lt;/li&gt; {% endif %} {% if user.number|add:'-4' &gt; 1 %} &lt;li&gt;&lt;a href=&quot;?page={{ page_obj.number|add:'-5' }}&quot;&gt;&amp;hellip;&lt;/a&gt;&lt;/li&gt; {% endif %} {% for i in users.paginator.page_range %} {% if users.number == i %} &lt;li class=&quot;active&quot;&gt;&lt;span&gt;{{ i }} &lt;span class=&quot;sr-only&quot;&gt;(current)&lt;/span&gt;&lt;/span&gt;&lt;/li&gt; {% elif i &gt; users.number|add:'-5' and i &lt; users.number|add:'5' %} &lt;li&gt;&lt;a href=&quot;?page={{ i }}&quot;&gt;{{ i }}&lt;/a&gt;&lt;/li&gt; {% endif %} {% endfor %} {% if users.has_next %} &lt;li&gt;&lt;a href=&quot;?page={{ users.next_page_number }}&quot;&gt;»&lt;/a&gt;&lt;/li&gt; {% else %} &lt;li class=&quot;disabled&quot;&gt;&lt;span&gt;»&lt;/span&gt;&lt;/li&gt; {% endif %} &lt;/ul&gt; {% endif %} &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I need to get only the datas which I have filtered et_records_by_date = Scrapper.objects.all().filter(Q(start_time__date=f_date)|Q(end_time__date=t_date)) in pagination. But when I click the next page its showing different datas. Is there any solution to get only the datas for the particular query. When I post the datas the of dates the 1st pages is showing the correct details but when I click page 2 its showing the other datas</p>
[ { "answer_id": 74597125, "author": "Josh White", "author_id": 20289207, "author_profile": "https://Stackoverflow.com/users/20289207", "pm_score": 2, "selected": false, "text": "gsub() \\\\d+ Inf \"\\\\1\\\\2\" x <- c(\"CHILD1xxx\", \"child2yyy\", \"Child23hello\")\ngsub(\"^(child)\\\\d+(.*)\", \"\\\\1\\\\2\", x, ignore.case = TRUE)\n [1] \"CHILDxxx\" \"childyyy\" \"Childhello\"\n gsub(\"\\\\d\", \"\", x)\n [1] \"CHILDxxx\" \"childyyy\" \"Childhello\"\n" }, { "answer_id": 74597216, "author": "Chris Ruehlemann", "author_id": 8039978, "author_profile": "https://Stackoverflow.com/users/8039978", "pm_score": 0, "selected": false, "text": "str_remove \\\\d+ library(stringr)\nstr_remove(x, \"\\\\d+\")\n[1] \"CHILDxxx\" \"childyyy\" \"Childhello\"\n x <- c(\"CHILD1xxx\", \"child2yyy\", \"Child23hello\")\n str_remove rename_with df %>%\n rename_with(~str_remove(., \"\\\\d+\"))\n CHILDxxx childyyy Childhello SomeOther\n1 NA NA NA NA\n df <- data.frame(\n CHILD1xxx = NA,\n child2yyy = NA,\n Child23hello = NA,\n SomeOther = NA\n)\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14855237/" ]
74,597,122
<p>With an int array arr and int i like</p> <pre><code>int i = 0; int[] arr = {11,23,34,45,56}; </code></pre> <p>When I do</p> <pre><code>arr[i++] = arr[i++] + 70; </code></pre> <p>arr after changed [93, 23, 34, 45, 56]</p> <p>Why left side idx doesn't increase? I think that</p> <pre><code>arr[1] = arr[0] + 70; </code></pre> <p>but that is not correct. Why?</p>
[ { "answer_id": 74597191, "author": "Tarik", "author_id": 990750, "author_profile": "https://Stackoverflow.com/users/990750", "pm_score": -1, "selected": false, "text": "arr[i++] = arr[i++] + 70;\n arr[++i] = arr[i-1] + 70;\n" }, { "answer_id": 74597209, "author": "LenglBoy", "author_id": 15702124, "author_profile": "https://Stackoverflow.com/users/15702124", "pm_score": -1, "selected": false, "text": "i++ i+1 i i ++i array[++i] = array[i] + 70;" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16249614/" ]
74,597,147
<p>I have a piece of code that was shipped as part of the XLR8 development platform that formerly used a bundled version (4.8.1) of the avr-gcc/g++ compiler. I tried to use the latest version of avr-g++ included with by my linux distribution (Ubuntu 22.04) which is 5.4.0</p> <p>When running that compiler, I am getting the following error that seems to make sense to me. Here is the error and the chunk of related code below. In the bundled version of avr-g++ that was provided with the XLR8 board, this was not an error. I'm not sure why because it appears that the code below is attempting to place 16 bit words into an array of chars.</p> <p>A couple questions,</p> <ol> <li>Can anyone explain the reason this worked with previous avr-gcc releases and was not considered an error?</li> <li>Because of the use of sizeof in the snippet below to control the for loop terminal count, I think the 16 bit size was supposed to be the data type per element of the array. Is that accurate?</li> <li>If the size of the element was 16 bits, then is the correct fix simply to make that array of type unsigned int rather than char?</li> </ol> <pre><code>/home/rich/.arduino15/packages/alorium/hardware/avr/2.3.0/libraries/XLR8Info/src/XLR8Info.cpp:157:12: error: narrowing conversion of ‘51343u’ from ‘unsigned int’ to ‘char’ inside { } [-Wnarrowing] 0x38BF}; </code></pre> <pre><code>bool XLR8Info::hasICSPVccGndSwap(void) { // List of chip IDs from boards that have Vcc and Gnd swapped on the ICSP header // Chip ID of affected parts are 0x????6E00. Store the ???? part const static char cidTable[] PROGMEM = {0xC88F, 0x08B7, 0xA877, 0xF437, 0x94BF, 0x88D8, 0xB437, 0x94D7, 0x38BF, 0x145F, 0x288F, 0x28CF, 0x543F, 0x0837, 0xA8B7, 0x748F, 0x8477, 0xACAF, 0x14A4, 0x0C50, 0x084F, 0x0810, 0x0CC0, 0x540F, 0x1897, 0x48BF, 0x285F, 0x8C77, 0xE877, 0xE49F, 0x2837, 0xA82F, 0x043F, 0x88BF, 0xF48F, 0x88F7, 0x1410, 0xCC8F, 0xA84F, 0xB808, 0x8437, 0xF4C0, 0xD48F, 0x5478, 0x080F, 0x54D7, 0x1490, 0x88AF, 0x2877, 0xA8CF, 0xB83F, 0x1860, 0x38BF}; uint32_t chipId = getChipId(); for (int i=0;i&lt; sizeof(cidTable)/sizeof(cidTable[0]);i++) { uint32_t cidtoTest = (cidTable[i] &lt;&lt; 16) + 0x6E00; if (chipId == cidtoTest) {return true;} } return false; } </code></pre>
[ { "answer_id": 74598741, "author": "Rev", "author_id": 1790864, "author_profile": "https://Stackoverflow.com/users/1790864", "pm_score": 3, "selected": true, "text": "char hasICSPVccGndSwap false" }, { "answer_id": 74604783, "author": "emacs drives me nuts", "author_id": 1556746, "author_profile": "https://Stackoverflow.com/users/1556746", "pm_score": 1, "selected": false, "text": "cidTable uint16_t avr/pgmspace.h pgm_read_word cidTable[i] << 16 int #include <avr/pgmspace.h>\n\nbool XLR8Info::hasICSPVccGndSwap()\n{\n // List of chip IDs from boards that have Vcc and Gnd swapped on\n // the ICSP header. Chip ID of affected parts are 0x????6E00.\n // Store the ???? part.\n static const uint16_t cidTable[] PROGMEM =\n {\n 0xC88F, 0x08B7, 0xA877, 0xF437, ...\n };\n\n uint32_t chipId = getChipId();\n for (size_t i = 0; i < sizeof(cidTable) / sizeof (*cidTable); ++i)\n {\n uint16_t cid = pgm_read_word (&cidTable[i]);\n uint32_t cidtoTest = ((uint32_t) cid << 16) + 0x6E00;\n if (chipId == cidtoTest)\n return true;\n } \n return false;\n}\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/806065/" ]
74,597,175
<p>I am trying to keep track of the current size of a partition. I am trying to not create wide partitions. It is not necessary for me to have an exact number, but a rough estimate. As part of my plan, I intend to maintain meta data for the actual partition in a 'meta_table' and actual data in a 'data_table'</p> <pre><code>meta_table = CREATE TABLE meta_table (user TEXT, partition_id BIGINT, size BIGINT, PRIMARY KEY(user, partition_id)); data_table = CREATE TABLE data_table (user TEXT, partition_id BIGINT, key TEXT, value TEXT, PRIMARY KEY((user, partition_id), key)); </code></pre> <p>In order to determine whether I have crossed a certain partition size limit (50 Mb) in data_table, I will read meta_table before writing into data_table. In the case that I have crossed size limit, I will create a new partition and maintain it in meta_table while inserting the data into that new partition_id in data_table, else update size of that partition_id in meta_table and insert into same partition_id in data_table.</p> <p>Read:Write ratio is 1. Is this okay ? Or is there any other way to achieve this?</p>
[ { "answer_id": 74598741, "author": "Rev", "author_id": 1790864, "author_profile": "https://Stackoverflow.com/users/1790864", "pm_score": 3, "selected": true, "text": "char hasICSPVccGndSwap false" }, { "answer_id": 74604783, "author": "emacs drives me nuts", "author_id": 1556746, "author_profile": "https://Stackoverflow.com/users/1556746", "pm_score": 1, "selected": false, "text": "cidTable uint16_t avr/pgmspace.h pgm_read_word cidTable[i] << 16 int #include <avr/pgmspace.h>\n\nbool XLR8Info::hasICSPVccGndSwap()\n{\n // List of chip IDs from boards that have Vcc and Gnd swapped on\n // the ICSP header. Chip ID of affected parts are 0x????6E00.\n // Store the ???? part.\n static const uint16_t cidTable[] PROGMEM =\n {\n 0xC88F, 0x08B7, 0xA877, 0xF437, ...\n };\n\n uint32_t chipId = getChipId();\n for (size_t i = 0; i < sizeof(cidTable) / sizeof (*cidTable); ++i)\n {\n uint16_t cid = pgm_read_word (&cidTable[i]);\n uint32_t cidtoTest = ((uint32_t) cid << 16) + 0x6E00;\n if (chipId == cidtoTest)\n return true;\n } \n return false;\n}\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17952301/" ]
74,597,188
<p>I styled my navbar and made transition ease-in-out but it is not working and I do not know why. The ease-in-out animation is not showing whenever I hover over the li a and I cannot find what I did wrong</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>body { margin: 0; } .nav-bar { width: 100vw; background-color: black; } .nav-bar-ul { list-style: none; display: flex; justify-content: flex-end; align-items: center; padding: 1em 0; } li a { text-decoration: none; color: white; padding-right: 3em; position: relative; } li a::after { content: ''; position: absolute; display: block; height: 0.4em; width: 0%; background-color: white; bottom: -1em; transition: all ease-in-out 250ms; } li a :hover::after { width: 60%; } li a:hover { color: white; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div&gt; &lt;div className="nav-bar"&gt; &lt;ul className="nav-bar-ul"&gt; &lt;li&gt;&lt;a href="#"&gt;Logo&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Logo&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Logo&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Logo&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74597608, "author": "Hoargarth", "author_id": 9184970, "author_profile": "https://Stackoverflow.com/users/9184970", "pm_score": 1, "selected": false, "text": "<a> ::after :hover a :hover li a :hover::after li a:hover::after <a> ::after 0% 60% display: inline 0 display: inline-block display: block body {\n margin: 0;\n}\n\n.nav-bar {\n width: 100vw;\n background-color: black;\n}\n\n.nav-bar-ul {\n list-style: none;\n display: flex;\n justify-content: flex-end;\n align-items: center;\n padding: 1em 0;\n}\n\nli a {\n text-decoration: none;\n color: green;\n padding-right: 3em;\n position: relative;\n display: inline-block;\n}\n\nli a::after {\n content: '';\n position: absolute;\n display: block;\n height: 0.4em;\n width: 0%;\n background-color: red;\n bottom: -1em;\n transition: all ease-in-out 250ms;\n}\n\nli a:hover::after {\n width: 60%;\n}\n\nli a:hover {\n color: white;\n} <div>\n <div className=\"nav-bar\">\n <ul className=\"nav-bar-ul\">\n <li><a href=\"#\">Logo</a></li>\n <li><a href=\"#\">Logo</a></li>\n <li><a href=\"#\">Logo</a></li>\n <li><a href=\"#\">Logo</a></li>\n </ul>\n </div>\n</div>" }, { "answer_id": 74599134, "author": "Dhara Rathod", "author_id": 19777338, "author_profile": "https://Stackoverflow.com/users/19777338", "pm_score": 0, "selected": false, "text": " <style>\nbody {\n margin: 0;\n}\n.nav-bar {\n width: 100vw;\n background-color: black;\n}\n.nav-bar-ul {\n list-style: none;\n display: flex;\n justify-content: flex-end;\n align-items: center;\n padding: 1em 0;\n}\n\nli a {\n text-decoration: none;\n color: white;\n padding-right: 3em;\n position: relative;\n}\n\nli a::after {\n content: '';\n position: absolute;\n display: block;\n height: 0.4em;\n width: 0%;\n background-color: white;\n bottom: -1em;\n transition: all ease-in-out 250ms;\n}\n\nli a:hover::after {\n width: 60%;\n}\n\nli>a:hover {\n color: white;\n}\n</style>\n<body>\n<div>\n <div class=\"nav-bar\">\n <ul class=\"nav-bar-ul\">\n <li><a href=\"#\">Logo</a></li>\n <li><a href=\"#\">Logo</a></li>\n <li><a href=\"#\">Logo</a></li>\n <li><a href=\"#\">Logo</a></li>\n </ul>\n </div>\n</div>\n</body>\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20159329/" ]
74,597,201
<p>Trying to make a menu but make it accept only integer for selecting option and loop back when user inputs letter.</p> <p>AppUI.cpp</p> <pre><code>#include &lt;iostream&gt; #include &lt;windows.h&gt; #include &lt;iomanip&gt; #include &lt;string&gt; #include &lt;cstring&gt; #include &lt;algorithm&gt; #include &lt;unistd.h&gt; #include &lt;stdio.h&gt; using namespace std; void AppUI::SearchBook() { system(&quot;CLS&quot;); TitleHeader(); setTxtColor(10); PageTitle(&quot;Search Book&quot;); cout &lt;&lt; &quot;Search books by:&quot; &lt;&lt; endl; cout &lt;&lt; &quot;1. Title&quot; &lt;&lt; endl; cout &lt;&lt; &quot;2. Author&quot; &lt;&lt; endl; cout &lt;&lt; &quot;3. Publication Date&quot; &lt;&lt; endl; cout &lt;&lt; &quot;4. Publisher&quot; &lt;&lt; endl; cout &lt;&lt; &quot;\n0. Go back to main menu&quot; &lt;&lt; endl; } </code></pre> <p>EditBook.cpp</p> <pre><code>#include &lt;iostream&gt; #include &lt;windows.h&gt; #include &lt;iomanip&gt; #include &lt;string&gt; #include &lt;cstring&gt; #include &lt;algorithm&gt; #include &lt;unistd.h&gt; #include &lt;stdio.h&gt; using namespace std; void EditBook::SearchBook() { //variable declarations int Opt; char searchTxt[255]; SearchStart: UI.SearchBook(); cout &lt;&lt; &quot;\nOption: &quot;; cin &gt;&gt; Opt; switch(Opt) { case 0: UI.MainMenu(); break; case 1: system(&quot;CLS&quot;); cout &lt;&lt; &quot;Enter title: &quot;; cin.getline(searchTxt,sizeof(searchTxt)); SearchByTitle(searchTxt); break; case 2: system(&quot;CLS&quot;); cout &lt;&lt; &quot;Enter author name: &quot;; cin.getline(searchTxt,sizeof(searchTxt)); SearchByAuthor(searchTxt); break; case 3: system(&quot;CLS&quot;); cout &lt;&lt; &quot;Enter publication date: &quot;; cin.getline(searchTxt,sizeof(searchTxt)); SearchByPubDate(searchTxt); break; case 4: system(&quot;CLS&quot;); cout &lt;&lt; &quot;Enter publisher: &quot;; cin.getline(searchTxt,sizeof(searchTxt)); SearchByPublisher(searchTxt); break; default: cout &lt;&lt; &quot;Invalid option!&quot;; sleep(1); goto SearchStart; break; } } </code></pre> <p>In the Search book, when I input a digit not available in the options like &quot;5&quot;, it loops back, and lets me enter the correct option. But when I input a letter, like &quot;a&quot; for exmple, it loops back infitely making it display &quot;invalid option&quot; over and over and not letting me input a new option. I was hoping that when I input a letter, which is an invalid option, it would still go back and let me input the correct one, which is a number/integer.</p>
[ { "answer_id": 74597275, "author": "Yunnosch", "author_id": 7733418, "author_profile": "https://Stackoverflow.com/users/7733418", "pm_score": 0, "selected": false, "text": "int int Opt; cin >> Opt;" }, { "answer_id": 74597281, "author": "john", "author_id": 882003, "author_profile": "https://Stackoverflow.com/users/882003", "pm_score": 1, "selected": false, "text": "if (!(cin >> Opt))\n{\n cin.clear(); // clear stream error state\n cin.ignore(100, '\\n'); // ignore any pending input\n goto SearchStart; // loop back\n}\n goto" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14378141/" ]
74,597,212
<p>I'm creating a leaflet map for showing agencies on the map, with markers created dynamically for each agency. Also there is list of agencies which when clicked on each one, the map zooms automatically on the specific marker for that agency. Now I intend to show some agency info inside of a popup on every marker, but this popup shows only when clicked upon the agency card or the marker itself. I've been successful in the latter and popups show when clicked on the markers. But I'm having problems when trying to achieve this by clicking on the agency cards. So, in order to clarify the problem, the path I've chosen is as below:</p> <p>First, my html code for cards:</p> <pre><code> &lt;div class=&quot;card border border-secondary rounded&quot; onclick=&quot;moveMap({{ agency.latitude }}, {{ agency.longitude }}, {{ agency.id }})&quot; style=&quot;cursor: pointer; z-index: 1000&quot;&gt; ... // rest of the html code </code></pre> <p>Since my backend is on django, so I'm using <code>{{}}</code>s.</p> <p>In the <code>moveMap()</code> function, I'm sending <code>agency.latitude</code>, <code>agency.longitude</code> and <code>agency.id</code>, and my javascript code is as below:</p> <pre><code>function moveMap(lat, long, id) { map.flyTo([lat, long], 14, { animate: true, duration: 3.5, }); openPopupByID(id); } </code></pre> <p>Here, after moving map to the proper marker, I'm calling <code>openPopupById()</code> function, which takes <code>id</code> as it's parameter, and the <code>openPopupById()</code> function is as below:</p> <pre><code>function openPopupByID (agency_id) { for (let item in markerList) { if (item[&quot;id&quot;] === agency_id) { item.openPopup(); } } } </code></pre> <p>In this function I'm using <code>markerList</code> which is created as below:</p> <pre><code>let markerList = []; // creating markers using the coorList for (let dataSet of coorList) { let latNumber = parseFloat(dataSet[0]); let longNumber = parseFloat(dataSet[1]); let marker = L.marker(L.latLng(latNumber, longNumber)).addTo(map); // listing agency info inside popups marker.bindPopup(setMarkerInfo(dataSet[2])); //adding each marker to the markerList marker[&quot;id&quot;] = dataSet[2]; markerList.push(marker); } </code></pre> <p><code>coorList</code> is a list of arrays with three values, <code>agency.latitude</code>, <code>agency.longitude</code> and <code>agency.id</code> with indexes of 0, 1 and 2.</p> <p>So I have a <code>markerList</code> which is list of marker objects, and with <code>marker[&quot;id&quot;] = dataSet[2];</code> I've added an <code>id</code> property to the <code>marker</code> object. But in <code>openPopupByID()</code> function, when I'm trying to access the <code>id</code> of a marker, I'm getting <code>undefined</code> message from js console. When I tried to see the structure of the <code>markerList</code> using <code>console.log(markerList)</code>, I get the following: <a href="https://i.stack.imgur.com/jMHeN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jMHeN.png" alt="enter image description here" /></a></p> <p>In which we can clearly see the <code>id</code> property.</p> <p>So, what is my problem? What did I do wrong?</p>
[ { "answer_id": 74597275, "author": "Yunnosch", "author_id": 7733418, "author_profile": "https://Stackoverflow.com/users/7733418", "pm_score": 0, "selected": false, "text": "int int Opt; cin >> Opt;" }, { "answer_id": 74597281, "author": "john", "author_id": 882003, "author_profile": "https://Stackoverflow.com/users/882003", "pm_score": 1, "selected": false, "text": "if (!(cin >> Opt))\n{\n cin.clear(); // clear stream error state\n cin.ignore(100, '\\n'); // ignore any pending input\n goto SearchStart; // loop back\n}\n goto" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4429265/" ]
74,597,235
<p>I was working on a Flutter project. It was running fine till morning. I did not change anything in the code. Suddenly the below error is throwing.</p> <p>I tried all possible solutions like</p> <p><code>invalid caches and restart, flutter clean, flutter pub get</code> But nothing helps.</p> <pre><code> Launching lib/main.dart on sdk gphone64 arm64 in debug mode... Running Gradle task 'assembleDebug'... ERROR:Resource and asset merger: java.lang.NullPointerException java.lang.NullPointerException at com.android.ide.common.resources.NodeUtils.processSingleNodeNamespace(NodeUtils.java:186) at com.android.ide.common.resources.NodeUtils.updateNamespace(NodeUtils.java:147) at com.android.ide.common.resources.NodeUtils.adoptNode(NodeUtils.java:49) at com.android.ide.common.resources.MergedResourceWriter.postWriteAction(MergedResourceWriter.java:543) at com.android.ide.common.resources.MergeWriter.end(MergeWriter.java:46) at com.android.ide.common.resources.MergedResourceWriter.end(MergedResourceWriter.java:199) at com.android.ide.common.resources.DataMerger.mergeData(DataMerger.java:292) at com.android.ide.common.resources.ResourceMerger.mergeData(ResourceMerger.java:385) at com.android.build.gradle.tasks.MergeResources.lambda$doFullTaskAction$1(MergeResources.java:335) at com.android.build.gradle.internal.tasks.Blocks.recordSpan(Blocks.java:51) at com.android.build.gradle.tasks.MergeResources.doFullTaskAction(MergeResources.java:331) at com.android.build.gradle.tasks.MergeResources.doTaskAction(MergeResources.java:390) at com.android.build.gradle.internal.tasks.NewIncrementalTask$taskAction$$inlined$recordTaskAction$1.invoke(BaseTask.kt:66) at com.android.build.gradle.internal.tasks.Blocks.recordSpan(Blocks.java:51) at com.android.build.gradle.internal.tasks.NewIncrementalTask.taskAction(NewIncrementalTask.kt:45) at jdk.internal.reflect.GeneratedMethodAccessor1437.invoke(Unknown Source) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:566) at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:104) at org.gradle.api.internal.project.taskfactory.IncrementalInputsTaskAction.doExecute(IncrementalInputsTaskAction.java:32) at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:51) at org.gradle.api.internal.project.taskfactory.AbstractIncrementalTaskAction.execute(AbstractIncrementalTaskAction.java:25) at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:29) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$2.run(ExecuteActionsTaskExecuter.java:498) at org.gradle.internal.operations.DefaultBuildOperationRunner$1.execute(DefaultBuildOperationRunner.java:29) at org.gradle.internal.operations.DefaultBuildOperationRunner$1.execute(DefaultBuildOperationRunner.java:26) at org.gradle.internal.operations.DefaultBuildOperationRunner$3.execute(DefaultBuildOperationRunner.java:75) at org.gradle.internal.operations.DefaultBuildOperationRunner$3.execute(DefaultBuildOperationRunner.java:68) at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:153) at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:68) at org.gradle.internal.operations.DefaultBuildOperationRunner.run(DefaultBuildOperationRunner.java:56) at org.gradle.internal.operations.DefaultBuildOperationExecutor.lambda$run$1(DefaultBuildOperationExecutor.java:71) at org.gradle.internal.operations.UnmanagedBuildOperationWrapper.runWithUnmanagedSupport(UnmanagedBuildOperationWrapper.java:45) at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:71) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:483) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:466) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.access$300(ExecuteActionsTaskExecuter.java:105) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$TaskExecution.executeWithPreviousOutputFiles(ExecuteActionsTaskExecuter.java:270) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$TaskExecution.execute(ExecuteActionsTaskExecuter.java:248) at org.gradle.internal.execution.steps.ExecuteStep.executeInternal(ExecuteStep.java:83) at org.gradle.internal.execution.steps.ExecuteStep.access$000(ExecuteStep.java:37) at org.gradle.internal.execution.steps.ExecuteStep$1.call(ExecuteStep.java:50) at org.gradle.internal.execution.steps.ExecuteStep$1.call(ExecuteStep.java:47) at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:200) at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:195) at org.gradle.internal.operations.DefaultBuildOperationRunner$3.execute(DefaultBuildOperationRunner.java:75) at org.gradle.internal.operations.DefaultBuildOperationRunner$3.execute(DefaultBuildOperationRunner.java:68) at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:153) at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:68) at org.gradle.internal.operations.DefaultBuildOperationRunner.call(DefaultBuildOperationRunner.java:62) at org.gradle.internal.operations.DefaultBuildOperationExecutor.lambda$call$2(DefaultBuildOperationExecutor.java:76) at org.gradle.internal.operations.UnmanagedBuildOperationWrapper.callWithUnmanagedSupport(UnmanagedBuildOperationWrapper.java:54) at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:76) at org.gradle.internal.execution.steps.ExecuteStep.execute(ExecuteStep.java:47) at org.gradle.internal.execution.steps.ExecuteStep.execute(ExecuteStep.java:37) at org.gradle.internal.execution.steps.RemovePreviousOutputsStep.execute(RemovePreviousOutputsStep.java:68) at org.gradle.internal.execution.steps.RemovePreviousOutputsStep.execute(RemovePreviousOutputsStep.java:38) at org.gradle.internal.execution.steps.ResolveInputChangesStep.execute(ResolveInputChangesStep.java:50) at org.gradle.internal.execution.steps.ResolveInputChangesStep.execute(ResolveInputChangesStep.java:36) at org.gradle.internal.execution.steps.CancelExecutionStep.execute(CancelExecutionStep.java:41) at org.gradle.internal.execution.steps.TimeoutStep.executeWithoutTimeout(TimeoutStep.java:74) at org.gradle.internal.execution.steps.TimeoutStep.execute(TimeoutStep.java:55) at org.gradle.internal.execution.steps.CreateOutputsStep.execute(CreateOutputsStep.java:51) at org.gradle.internal.execution.steps.CreateOutputsStep.execute(CreateOutputsStep.java:29) at org.gradle.internal.execution.steps.CaptureStateAfterExecutionStep.execute(CaptureStateAfterExecutionStep.java:54) at org.gradle.internal.execution.steps.CaptureStateAfterExecutionStep.execute(CaptureStateAfterExecutionStep.java:35) at org.gradle.internal.execution.steps.BroadcastChangingOutputsStep.execute(BroadcastChangingOutputsStep.java:60) at org.gradle.internal.execution.steps.BroadcastChangingOutputsStep.execute(BroadcastChangingOutputsStep.java:27) at org.gradle.internal.execution.steps.BuildCacheStep.executeWithoutCache(BuildCacheStep.java:174) at org.gradle.internal.execution.steps.BuildCacheStep.execute(BuildCacheStep.java:74) at org.gradle.internal.execution.steps.BuildCacheStep.execute(BuildCacheStep.java:45) at org.gradle.internal.execution.steps.StoreExecutionStateStep.execute(StoreExecutionStateStep.java:40) at org.gradle.internal.execution.steps.StoreExecutionStateStep.execute(StoreExecutionStateStep.java:29) at org.gradle.internal.execution.steps.RecordOutputsStep.execute(RecordOutputsStep.java:36) at org.gradle.internal.execution.steps.RecordOutputsStep.execute(RecordOutputsStep.java:22) at org.gradle.internal.execution.steps.SkipUpToDateStep.executeBecause(SkipUpToDateStep.java:99) at org.gradle.internal.execution.steps.SkipUpToDateStep.lambda$execute$0(SkipUpToDateStep.java:92) at java.base/java.util.Optional.map(Optional.java:265) at org.gradle.internal.execution.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:52) at org.gradle.internal.execution.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:36) at org.gradle.internal.execution.steps.ResolveChangesStep.execute(ResolveChangesStep.java:84) at org.gradle.internal.execution.steps.ResolveChangesStep.execute(ResolveChangesStep.java:41) at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsFinishedStep.execute(MarkSnapshottingInputsFinishedStep.java:37) at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsFinishedStep.execute(MarkSnapshottingInputsFinishedStep.java:27) at org.gradle.internal.execution.steps.ResolveCachingStateStep.execute(ResolveCachingStateStep.java:91) at org.gradle.internal.execution.steps.ResolveCachingStateStep.execute(ResolveCachingStateStep.java:49) at org.gradle.internal.execution.steps.CaptureStateBeforeExecutionStep.execute(CaptureStateBeforeExecutionStep.java:78) at org.gradle.internal.execution.steps.CaptureStateBeforeExecutionStep.execute(CaptureStateBeforeExecutionStep.java:49) at org.gradle.internal.execution.steps.ValidateStep.execute(ValidateStep.java:105) at org.gradle.internal.execution.steps.ValidateStep.execute(ValidateStep.java:50) at org.gradle.internal.execution.steps.SkipEmptyWorkStep.lambda$execute$2(SkipEmptyWorkStep.java:86) at java.base/java.util.Optional.orElseGet(Optional.java:369) at org.gradle.internal.execution.steps.SkipEmptyWorkStep.execute(SkipEmptyWorkStep.java:86) at org.gradle.internal.execution.steps.SkipEmptyWorkStep.execute(SkipEmptyWorkStep.java:32) at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsStartedStep.execute(MarkSnapshottingInputsStartedStep.java:38) at org.gradle.internal.execution.steps.LoadExecutionStateStep.execute(LoadExecutionStateStep.java:43) at org.gradle.internal.execution.steps.LoadExecutionStateStep.execute(LoadExecutionStateStep.java:31) at org.gradle.internal.execution.steps.AssignWorkspaceStep.lambda$execute$0(AssignWorkspaceStep.java:40) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$TaskExecution$2.withWorkspace(ExecuteActionsTaskExecuter.java:283) at org.gradle.internal.execution.steps.AssignWorkspaceStep.execute(AssignWorkspaceStep.java:40) at org.gradle.internal.execution.steps.AssignWorkspaceStep.execute(AssignWorkspaceStep.java:30) at org.gradle.internal.execution.steps.IdentityCacheStep.execute(IdentityCacheStep.java:37) at org.gradle.internal.execution.steps.IdentityCacheStep.execute(IdentityCacheStep.java:27) at org.gradle.internal.execution.steps.IdentifyStep.execute(IdentifyStep.java:49) at org.gradle.internal.execution.steps.IdentifyStep.execute(IdentifyStep.java:35) at org.gradle.internal.execution.impl.DefaultExecutionEngine$1.execute(DefaultExecutionEngine.java:76) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeIfValid(ExecuteActionsTaskExecuter.java:184) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:173) at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:109) at org.gradle.api.internal.tasks.execution.FinalizePropertiesTaskExecuter.execute(FinalizePropertiesTaskExecuter.java:46) at org.gradle.api.internal.tasks.execution.ResolveTaskExecutionModeExecuter.execute(ResolveTaskExecutionModeExecuter.java:51) at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:57) at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:56) at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:36) at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.executeTask(EventFiringTaskExecuter.java:77) at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:55) at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:52) at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:200) at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:195) at org.gradle.internal.operations.DefaultBuildOperationRunner$3.execute(DefaultBuildOperationRunner.java:75) at org.gradle.internal.operations.DefaultBuildOperationRunner$3.execute(DefaultBuildOperationRunner.java:68) at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:153) at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:68) at org.gradle.internal.operations.DefaultBuildOperationRunner.call(DefaultBuildOperationRunner.java:62) at org.gradle.internal.operations.DefaultBuildOperationExecutor.lambda$call$2(DefaultBuildOperationExecutor.java:76) at org.gradle.internal.operations.UnmanagedBuildOperationWrapper.callWithUnmanagedSupport(UnmanagedBuildOperationWrapper.java:54) at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:76) at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:52) at org.gradle.execution.plan.LocalTaskNodeExecutor.execute(LocalTaskNodeExecutor.java:74) at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:408) at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:395) at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:388) at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:374) at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.lambda$run$0(DefaultPlanExecutor.java:127) at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.execute(DefaultPlanExecutor.java:191) at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.executeNextNode(DefaultPlanExecutor.java:182) at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.run(DefaultPlanExecutor.java:124) at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64) at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56) at java.base/java.lang.Thread.run(Thread.java:829) </code></pre>
[ { "answer_id": 74597275, "author": "Yunnosch", "author_id": 7733418, "author_profile": "https://Stackoverflow.com/users/7733418", "pm_score": 0, "selected": false, "text": "int int Opt; cin >> Opt;" }, { "answer_id": 74597281, "author": "john", "author_id": 882003, "author_profile": "https://Stackoverflow.com/users/882003", "pm_score": 1, "selected": false, "text": "if (!(cin >> Opt))\n{\n cin.clear(); // clear stream error state\n cin.ignore(100, '\\n'); // ignore any pending input\n goto SearchStart; // loop back\n}\n goto" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5197712/" ]
74,597,253
<p>I am trying to do the following, I want to replace only the first &quot;T_&quot; from a string value. However with REPLACE, it will replace all the &quot;T_&quot; occurrences</p> <pre><code>REPLACE('T_DEV_ABCT_FACT_SALEST_TEST', 'T_') </code></pre> <p>Is there any other way of doing this so that it replace only and only the first occurrence ?</p> <p>Thank You,</p>
[ { "answer_id": 74597328, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 1, "selected": false, "text": "WITH t AS (\n SELECT 'T_DEV_ABCT_FACT_SALEST_TEST' AS val\n)\n\nSELECT val, REGEXP_REPLACE(val, '^T_', 'F_') AS val_out\nFROM t;\n\n-- T_DEV_ABCT_FACT_SALEST_TEST, F_DEV_ABCT_FACT_SALEST_TEST\n" }, { "answer_id": 74606770, "author": "Simeon Pilgrim", "author_id": 43992, "author_profile": "https://Stackoverflow.com/users/43992", "pm_score": 0, "selected": false, "text": "SELECT \n column1 as val\n ,REPLACE(val, 'T_', 'x') as first_try\n ,REGEXP_REPLACE(val, '^T_', 'x') AS only_first_token\n ,REGEXP_REPLACE(val, 'T_', 'x', 1, 1) AS first_t_only\n ,POSITION('T_', val) as pos\n ,INSERT(val, POSITION('T_', val),iff(POSITION('T_', val) > 0, 2,0), 'x') as insert_hack\nFROM VALUES\n ('T_LINE_START_WITH_T'),\n ('LINE_NOT_START_WITH_T'),\n ('LINE_NO_TEE_UNDERSCORE')\n ;\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15480313/" ]
74,597,270
<p>I am a beginner of nodejs with angular.i creating a simple crud application using nodejs with angular.i can add and delete and view records well.but i couldn't update the records. when i make the changes on the form and click submit button i got the error was i checked through the console.</p> <pre><code>Failed to load resource: net::ERR_CONNECTION_REFUSED :9002/user/update/undefined:1 </code></pre> <p>at the same time node js server stop and give error on the command prompt .</p> <pre><code>node:internal/process/promises:246 triggerUncaughtException(err, true /* fromPromise */); ^ [UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason &quot;false&quot;.] { code: 'ERR_UNHANDLED_REJECTION' </code></pre> <p>}</p> <p>what i tried so far i attached below.please solve the problem.</p> <pre><code>import { HttpClient } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-employeecrud', templateUrl: './employeecrud.component.html', styleUrls: ['./employeecrud.component.scss'] }) export class EmployeecrudComponent implements OnInit { EmployeeArray : any[] = []; isResultLoaded = false; isUpdateFormActive = false; first_name: string =&quot;&quot;; last_name: string =&quot;&quot;; email: string =&quot;&quot;; password: string =&quot;&quot;; currentEmployeeID = &quot;&quot;; setUpdate(data: any) { this.first_name = data.first_name; this.last_name = data.last_name; this.email = data.email; this.password = data.password; this.currentEmployeeID = data.id; } UpdateRecords() { let bodyData = { &quot;first_name&quot; : this.first_name, &quot;last_name&quot; : this.last_name, &quot;email&quot; : this.email, &quot;password&quot; : this.password, }; this.http.patch(&quot;http://localhost:9002/user/update&quot;+ &quot;/&quot;+this.currentEmployeeID,bodyData).subscribe((resultData: any)=&gt; { console.log(resultData); alert(&quot;Employee Registered Updateddd&quot;) // this.getAllEmployee(); }); } save() { if(this.currentEmployeeID == '') { this.register(); } else { this.UpdateRecords(); } } setDelete(data: any) { this.http.delete(&quot;http://localhost:9002/user/remove&quot;+ &quot;/&quot;+ data.id).subscribe((resultData: any)=&gt; { console.log(resultData); alert(&quot;Employee Deletedddd&quot;) this.getAllEmployee(); }); } } </code></pre> <p>}</p> <p>Node js Update Function</p> <pre><code>module.exports.updateOneUserDBService = (id,userDetais) =&gt; { console.log(userDetais); return new Promise(function myFn(resolve, reject) { userModel.findByIdAndUpdate(id,userDetais, function returnData(error, result) { if(error) { reject(false); } else { resolve(result); } }); }); } </code></pre>
[ { "answer_id": 74597509, "author": "Fabian Strathaus", "author_id": 17298437, "author_profile": "https://Stackoverflow.com/users/17298437", "pm_score": 2, "selected": true, "text": "setUpdate(data: any) this.currentEmployeeID = data.id; data.id" }, { "answer_id": 74597530, "author": "islam elbadawy", "author_id": 8652329, "author_profile": "https://Stackoverflow.com/users/8652329", "pm_score": 0, "selected": false, "text": "setUpdate() let bodyData = {\n first_name: this.first_name,\n last_name: this.last_name,\n email: this.email,\n password: this.password,\n};\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20090016/" ]
74,597,274
<p><a href="https://i.stack.imgur.com/5Ytj0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5Ytj0.png" alt="enter image description here" /></a></p> <p>I want to perform click on add to kart button action, but this same DOM code is used in 30 more items only product name is different which is in text.</p> <p>I want to perform click on add to kart button action, but this same DOM code is used in 30 more items only product name is different which is in text.</p>
[ { "answer_id": 74597509, "author": "Fabian Strathaus", "author_id": 17298437, "author_profile": "https://Stackoverflow.com/users/17298437", "pm_score": 2, "selected": true, "text": "setUpdate(data: any) this.currentEmployeeID = data.id; data.id" }, { "answer_id": 74597530, "author": "islam elbadawy", "author_id": 8652329, "author_profile": "https://Stackoverflow.com/users/8652329", "pm_score": 0, "selected": false, "text": "setUpdate() let bodyData = {\n first_name: this.first_name,\n last_name: this.last_name,\n email: this.email,\n password: this.password,\n};\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20590427/" ]
74,597,316
<p>I setup a GitHub Actions workflow which connects to my Linux production machine via SSH using RSA keypair (the setting looks a bit like <a href="https://zellwk.com/blog/github-actions-deploy/" rel="nofollow noreferrer">this tutorial</a>, except I'm trying to create a dedicated Linux user for that, looks to me like it would be the good practice here).</p> <p>On my Linux machine, I did:</p> <ul> <li>created a dedicated user <code>github</code> with its RSA keypair</li> <li>made the <code>github</code> user part of the group <code>www-data</code></li> <li>change the permissions recursively of the web projects folder to 772 (users part of the <code>www-data</code> group can read, write and execute)</li> </ul> <p>On the GitHub repo side I set up the secrets <code>SSH_PRIVATE_KEY</code>, <code>SSH_HOST</code> and <code>SSH_USER</code> (which is <code>github</code>).</p> <p>The GitHub Actions workflow file (the interesting steps of the workflow) look like this:</p> <pre><code> - name: Install SSH key uses: shimataro/ssh-key-action@v2 with: key: ${{ secrets.SSH_PRIVATE_KEY }} name: id_rsa known_hosts: ${{ secrets.SSH_HOST }} - name: Adding known hosts run: ssh-keyscan -H ${{ secrets.SSH_HOST }} &gt;&gt; ~/.ssh/known_hosts - name: Copy repository to server with rsync run: rsync -avz ./ ${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}:/home/www/my_project/ --usermap=github:www-data </code></pre> <p>When I rsync the project folder with the <code>github</code>user and its keypair from my local machine project folder to <code>/home/www/my_project/</code>on my production server just for a test, everything works fine.</p> <p>However, when I push on the repo and the GitHub Actions workflow is executed, the rsync steps fails on many files with the following errors on many files of my project: <code>rsync: [generator] failed to set times on &quot;/home/www/my_project/app/templates/en&quot;: Operation not permitted (1)</code></p> <p>Why?</p>
[ { "answer_id": 74597509, "author": "Fabian Strathaus", "author_id": 17298437, "author_profile": "https://Stackoverflow.com/users/17298437", "pm_score": 2, "selected": true, "text": "setUpdate(data: any) this.currentEmployeeID = data.id; data.id" }, { "answer_id": 74597530, "author": "islam elbadawy", "author_id": 8652329, "author_profile": "https://Stackoverflow.com/users/8652329", "pm_score": 0, "selected": false, "text": "setUpdate() let bodyData = {\n first_name: this.first_name,\n last_name: this.last_name,\n email: this.email,\n password: this.password,\n};\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4417586/" ]
74,597,394
<p>For a task I had to write a programm the programm functions nicely so I dont have a problem there. But I have to use input() and than I have to prove if the type is correct. I only needs integer but the type of input(5) is a str. Althought I need a int. But if use int(input()) thats also dont work because I want that my programm says this is a str or a float and because of this we cant move on. So that the programm now this is a number or not</p> <p>I did try with only input() that were all Strings regardless of the content and i know why this is so but I dont like it. Then I tried int(input()) but this only works if I use actually only numbers. But I have also to type in strings and floats and then the programm should only say it is the wrong type but shouldnt print out an error message</p>
[ { "answer_id": 74597452, "author": "rtoth", "author_id": 20589189, "author_profile": "https://Stackoverflow.com/users/20589189", "pm_score": 0, "selected": false, "text": "s = input()\n\n\ntry:\n print(int(s))\n\nexcept:\n print(\"not int\")\n" }, { "answer_id": 74597570, "author": "Usman Arshad", "author_id": 20582506, "author_profile": "https://Stackoverflow.com/users/20582506", "pm_score": -1, "selected": true, "text": "eval val = input()\ntry:\n val = eval(val)\nexcept NameError:\n pass\n if isinstance(val, int):\n print(\"This is integer\")\n\nif isinstance(val, float):\n print(\"This is float\")\n\nif isinstance(val, str):\n print(\"This is string\")\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20621010/" ]
74,597,397
<p>I know i can create a wordlist using programms like 'crunch' but i wanted to use python in hopes of learning something new.</p> <p>so I'm doing this CTF where i need a wordlist of numbers from 1 to maybe 10,000 or more. all the wordlists in Seclists have at least 3 zeroes in front of them, i dont want to use those files because i need to hash each entry through md5. if there are zeros in front of a numbers the hash differs from the same number without any zeros in front of it.</p> <p>i need each numbers in its own line, starting with 1 to however many lines or number i want.</p> <p>I feel like there may be a github gist for this out there but i havnt been looking long or hard enough to find one. if you have a link for one pls let me know!</p>
[ { "answer_id": 74597524, "author": "GaëtanLF", "author_id": 14820215, "author_profile": "https://Stackoverflow.com/users/14820215", "pm_score": 1, "selected": true, "text": ".csv def generate(min=0,max=10000):\n '''\n Generates a wordlist of numbers from min to max.\n '''\n r = range(min,max+1,1)\n with open('myWordlist.csv','a') as file:\n for i in r:\n file.write(f'{i}\\n')\n \ngenerate()\n" }, { "answer_id": 74598305, "author": "Maverick S.", "author_id": 14482205, "author_profile": "https://Stackoverflow.com/users/14482205", "pm_score": 1, "selected": false, "text": "#!/usr/bin/python3\n\ndef generate():\n\n n = 10000\n print(\"\\n\".join(str(v) for v in range(1, n + 1)))\ngenerate()\n\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14482205/" ]
74,597,431
<p>when i use this code first time ,it create the table but i want to use this code again and again but second time when i use it ,it will drop the table but does not create table again . kindly help me to correct the code according to my requirement.</p> <pre><code> set serverout on DECLARE table_or_view_does_not_exist exception; pragma exception_init(table_or_view_does_not_exist,-00942); ddl_qry VARCHAR2 (200); ddl_table varchar2(200); r_emp SYS.ODCINUMBERLIST := SYS.ODCINUMBERLIST(); v_array SYS.ODCIVARCHAR2LIST := SYS.ODCIVARCHAR2LIST('ACCT_ID', 'PARENT_ACCT_ID', 'CUST_ID', 'ACCT_NAME', 'BILLING_CYCLE_TYPE', 'PAID_FLAG', 'BILL_DELIVER_METHOD'); BEGIN ddl_qry:='Drop Table Accnt_Profile_Spcl'; EXECUTE IMMEDIATE ddl_qry; exception when table_or_view_does_not_exist then dbms_output.put_line('There is no error'); GOTO end_point; &lt;&lt;end_point&gt;&gt; ddl_table := 'create table Accnt_Profile_Spcl( column_name varchar2(50), spcl_char_count number)'; EXECUTE IMMEDIATE ddl_table; dbms_output.put_line('Table has been created'); ---------DBMS_OUTPUT.ENABLE; FOR i IN 1..v_array.COUNT LOOP r_emp.EXTEND; EXECUTE IMMEDIATE 'SELECT /*+parallel(16)*/ COUNT(*) FROM account_profile WHERE NOT REGEXP_LIKE('||v_array(i)||',''[A-Za-z0-9.]'')' INTO r_emp(i); if r_emp(i)&lt;&gt;0 then -----------dbms_output.put_line(v_array(i) || ': ' || r_emp(i)); execute immediate 'insert into Accnt_Profile_Spcl values (:param1,:param2)' using v_array(i), r_emp(i); end if; END LOOP; END; </code></pre>
[ { "answer_id": 74597575, "author": "Littlefoot", "author_id": 9097906, "author_profile": "https://Stackoverflow.com/users/9097906", "pm_score": 2, "selected": false, "text": "SQL> declare\n 2 l_cnt number;\n 3 begin\n 4 select count(*) into l_cnt\n 5 from user_tables\n 6 where table_name = 'ACCNT_PROFILE_SPCL';\n 7\n 8 if l_cnt = 1 then\n 9 execute immediate 'drop table ACCNT_PROFILE_SPCL';\n 10\n 11 dbms_output.put_line('Table dropped');\n 12 end if;\n 13\n 14 execute immediate 'create table ACCNT_PROFILE_SPCL ' ||\n 15 ' (column_name varchar2(50),' ||\n 16 ' spcl_char_count number)';\n 17\n 18 dbms_output.put_line('Table created');\n 19 end;\n 20 /\nTable dropped\nTable created\n\nPL/SQL procedure successfully completed.\n\nSQL> /\nTable dropped\nTable created\n\nPL/SQL procedure successfully completed.\n\nSQL>\n" }, { "answer_id": 74598335, "author": "MT0", "author_id": 1509264, "author_profile": "https://Stackoverflow.com/users/1509264", "pm_score": 1, "selected": false, "text": "DECLARE\n ddl_qry VARCHAR2 (200);\n ddl_table varchar2(200);\n r_emp SYS.ODCINUMBERLIST := SYS.ODCINUMBERLIST();\n v_array SYS.ODCIVARCHAR2LIST := SYS.ODCIVARCHAR2LIST('ACCT_ID',\n'PARENT_ACCT_ID',\n'CUST_ID',\n'ACCT_NAME',\n'BILLING_CYCLE_TYPE',\n'PAID_FLAG',\n'BILL_DELIVER_METHOD');\nBEGIN\n DECLARE\n table_or_view_does_not_exist EXCEPTION;\n PRAGMA EXCEPTION_INIT(table_or_view_does_not_exist,-00942);\n BEGIN\n ddl_qry:='Drop Table Accnt_Profile_Spcl';\n EXECUTE IMMEDIATE ddl_qry; \n EXCEPTION\n WHEN table_or_view_does_not_exist THEN\n dbms_output.put_line('There is no error');\n END;\n\n ddl_table := 'create table Accnt_Profile_Spcl(\n column_name varchar2(50),\n spcl_char_count number)';\n EXECUTE IMMEDIATE ddl_table;\n dbms_output.put_line('Table has been created');\n\n FOR i IN 1..v_array.COUNT LOOP\n r_emp.EXTEND;\n EXECUTE IMMEDIATE\n 'SELECT /*+parallel(16)*/ COUNT(*) FROM account_profile WHERE NOT REGEXP_LIKE('||v_array(i)||',''[A-Za-z0-9.]'')' \n INTO r_emp(i);\n\n if r_emp(i)<>0 then\n execute immediate 'insert into Accnt_Profile_Spcl values (:param1,:param2)' using v_array(i), r_emp(i);\n end if;\n END LOOP;\nEND;\n/\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16825853/" ]
74,597,433
<p>Is it possible to add Await inside new promise ?</p> <p>Originally, I don't need to put a await before making any request to the server. But one day, the server requires every request to have a token before sending out.</p> <p>Let's take an example of the code</p> <pre><code>export const countries = (data: IData) =&gt; { const countryRequests = getRequests(data) const countryResponse = countryRequests?.reduce((countryResponse, request) =&gt; { const countryResponses = new Promise((resolve, reject) =&gt; { instance .post(`/country`, request) .then(data =&gt; { resolve(data) }) .catch(err =&gt; { reject(err) }) }) return [...countryResponse, countryResponses] }, []) return countryResponse } </code></pre> <p>new code( putting async into the callback of promise):</p> <pre><code>export const countries = (data: IData) =&gt; { const countryRequests = getRequests(data) const countryResponse = countryRequests?.reduce((countryResponse, request) =&gt; { const countryResponses = new Promise(async (resolve, reject) =&gt; { //add async here await addAccessToken() // add header into token before sending the requests instance .post(`/country`, request) .then(data =&gt; { resolve(data) }) .catch(err =&gt; { reject(err) }) }) return [...countryResponse, countryResponses] }, []) return countryResponse } </code></pre> <p>addToken function:</p> <pre><code>export const addAccessToken = async () =&gt; { const accessToken = await instance.get&lt;IAccessToken&gt;( '/access_token' ) const { access_token } = accessToken.data instance.defaults.headers.common['Authorization'] = `Be ${access_token}` } </code></pre> <p>But then I got a error below</p> <p><strong>Promise executor functions should not be async.(no-async-promise-executor)</strong></p> <p>How can I get rid of the error?</p> <p>-------------- new changes---------</p> <pre><code>export const countries = async (data: IData) =&gt; { const countryRequests = getRequests(data) await addAccessToken() const countryResponse = countryRequests?.reduce((countryResponse, request) =&gt; { const countryResponses = instance .post(`/country`, request) //------- May I ask, if it is successful call, then this will autmactically equvlanet to calling resolve (data) in my previosu code? .catch(err =&gt; { console.error(err) }) return [...countryResponse, countryResponses] }, []) return countryResponse } </code></pre> <p>added new prmosie.all part</p> <pre><code>const countryResponses = countries(data) //set content for api 1 Promise.all([...countryResponses]) .then(values =&gt; { const countryResponsesResult = values.map((value, _index) =&gt; { return value.data.result ? value.data.result : [] }) //Set content for api 1 props.setProjection({ kind: 'success', payload: { data: countryResponsesResult, }, }) }) .catch(_error =&gt; { //Set content for api 1 props.setProjection({ kind: 'fail', payload: { error: new Error(_error.message), }, }) }) </code></pre>
[ { "answer_id": 74597553, "author": "Marios", "author_id": 20229075, "author_profile": "https://Stackoverflow.com/users/20229075", "pm_score": 3, "selected": true, "text": "export const countries = async (data: IData) => {\n\nawait addAccessToken()\nconst countryResponses = await instance.post(`/country`, request)\n//your code//\n await then export const countries = (data: IData) => {\n\naddAccessToken()\n .then((data)=>{\n const countryResponses = instance.post(`/country`, \n request)\n })\n .then(//your code//)\n" }, { "answer_id": 74600851, "author": "Ae Leung", "author_id": 19586543, "author_profile": "https://Stackoverflow.com/users/19586543", "pm_score": 1, "selected": false, "text": "export const countries = (data: IData)=> {\n const countryRequests = getRequests(data)\n const countryResponse = countryRequests?.reduce((countryResponse, request) => {\n // return promise\n const countryResponses = new Promise((resolve, reject) => {\n addAccessToken().then(()=>{\n instance\n .post(`/country`, request)\n .then(data => {\n // change the returned propmise state into resolved\n resolve(data)\n })\n .catch(err => {\n reject(err)\n })\n })\n\n })\n //return the whole set of simlationCalls promise. When all promise is resolved, promise all will be notified and excute whatever it needs to execute\n return [...countryResponse, countryResponses]\n }, [])\n\n return countryResponse\n}\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19586543/" ]
74,597,438
<p>I'm trying to configure firewalld on my VPS server and I'm trying to open a port for my postgresql server.</p> <p>So far, I have done the following:</p> <pre><code>sudo firewall-cmd --new-zone=postgresqlrule --permanent sudo firewall-cmd --reload sudo firewall-cmd --permanent --zone=postgresqlrule --add-port=5432/tcp sudo firewall-cmd --reload </code></pre> <p>How do I use <code>--add-source</code> to add a wildcard for all ips?</p> <pre><code>sudo firewall-cmd --permanent --zone=postgresqlrule --add-source= * </code></pre> <p>The above returns the following error:</p> <pre><code>[root@centos-s-1vcpu-512mb-10gb-sfo3-01 ~]# sudo firewall-cmd --permanent --zone=postgresqlrule --add-source= * usage: see firewall-cmd man page firewall-cmd: error: unrecognized arguments: mysql80-community-release-el9-1.noarch.rpm steam-game-scraper </code></pre> <p>I basically have to give some classmates access to this database, but I don't want to have to find out each of their IPs. I couldn't find anything related to opening connections to all IPs online.</p>
[ { "answer_id": 74597553, "author": "Marios", "author_id": 20229075, "author_profile": "https://Stackoverflow.com/users/20229075", "pm_score": 3, "selected": true, "text": "export const countries = async (data: IData) => {\n\nawait addAccessToken()\nconst countryResponses = await instance.post(`/country`, request)\n//your code//\n await then export const countries = (data: IData) => {\n\naddAccessToken()\n .then((data)=>{\n const countryResponses = instance.post(`/country`, \n request)\n })\n .then(//your code//)\n" }, { "answer_id": 74600851, "author": "Ae Leung", "author_id": 19586543, "author_profile": "https://Stackoverflow.com/users/19586543", "pm_score": 1, "selected": false, "text": "export const countries = (data: IData)=> {\n const countryRequests = getRequests(data)\n const countryResponse = countryRequests?.reduce((countryResponse, request) => {\n // return promise\n const countryResponses = new Promise((resolve, reject) => {\n addAccessToken().then(()=>{\n instance\n .post(`/country`, request)\n .then(data => {\n // change the returned propmise state into resolved\n resolve(data)\n })\n .catch(err => {\n reject(err)\n })\n })\n\n })\n //return the whole set of simlationCalls promise. When all promise is resolved, promise all will be notified and excute whatever it needs to execute\n return [...countryResponse, countryResponses]\n }, [])\n\n return countryResponse\n}\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18349632/" ]
74,597,447
<p>I need to remove some initial zeros from a field (it appears as an alphanumeric one in the DB) like this:</p> <pre><code>cod_acometida 000000000003391901 000000000008271401 000000000007696901 000000000005504701 000000000002298401 000000000000332701 000000000013942801 </code></pre> <p>It's a variable number of characters but they are always zeros at the beginning of the string. I'm new at SAS, not sure if RegEx is applicable.</p> <p>I'm using Enterprise Guide 7.15.</p> <p>Thanks in advance.</p>
[ { "answer_id": 74597553, "author": "Marios", "author_id": 20229075, "author_profile": "https://Stackoverflow.com/users/20229075", "pm_score": 3, "selected": true, "text": "export const countries = async (data: IData) => {\n\nawait addAccessToken()\nconst countryResponses = await instance.post(`/country`, request)\n//your code//\n await then export const countries = (data: IData) => {\n\naddAccessToken()\n .then((data)=>{\n const countryResponses = instance.post(`/country`, \n request)\n })\n .then(//your code//)\n" }, { "answer_id": 74600851, "author": "Ae Leung", "author_id": 19586543, "author_profile": "https://Stackoverflow.com/users/19586543", "pm_score": 1, "selected": false, "text": "export const countries = (data: IData)=> {\n const countryRequests = getRequests(data)\n const countryResponse = countryRequests?.reduce((countryResponse, request) => {\n // return promise\n const countryResponses = new Promise((resolve, reject) => {\n addAccessToken().then(()=>{\n instance\n .post(`/country`, request)\n .then(data => {\n // change the returned propmise state into resolved\n resolve(data)\n })\n .catch(err => {\n reject(err)\n })\n })\n\n })\n //return the whole set of simlationCalls promise. When all promise is resolved, promise all will be notified and excute whatever it needs to execute\n return [...countryResponse, countryResponses]\n }, [])\n\n return countryResponse\n}\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11030842/" ]
74,597,450
<p>I have a .tex file named a.tex containing many lines of texts like in the following example:</p> <pre><code>\begin{pycode} Some text right here, let's say Text 1A: like: There are #cat and #dog. \end{pycode} Some text right here, let's say Text 1B: like: One day the #dog tried to run away. \begin{pycode} Some text right here, let's say Text 2A: like: There are #cat and #dog and #pig. \end{pycode} Some text right here, let's say Text 2B: like: There is #something here. </code></pre> <p>I want to replace any # by &quot;the number of the mentioned Text&quot;, for example, the sentence &quot;There are #cat and #dog.&quot; should be turned to &quot;This is a 1dog and 1cat.&quot; because it is in Text 1A. And &quot;One day the #dog tried to run away.&quot; is turned to &quot;One day the 1dog tried to run away.&quot; And &quot;There are #cat and #dog and #pig.&quot; is changed to &quot;There are 2cat and 2dog and 2pig.&quot;, and so on.</p> <p>The output is a .tex file with this change applied to the whole document.</p> <p>So what I want is:</p> <pre><code>\begin{pycode} Some text right here, let's say Text 1A: like: There are 1cat and 1dog. \end{pycode} Some text right here, let's say Text 1B: like: One day the 1dog tried to run away. \begin{pycode} Some text right here, let's say Text 2A: like: There are 2cat and 2dog and 2pig. \end{pycode} Some text right here, let's say Text 2B: like: There is 2something here. </code></pre> <hr /> <p>I don't have a minimal work on this. My idea is to search and replace by going from the first line. For example, if we see &quot;begin{pycode}&quot; then s = s+1 (for some counting variable s) and search # then replace it by s until we meet the next &quot;begin{pycode}&quot;.</p> <p>I am searching a solution in this way but still need time to come to a solution.</p> <p>Thank for any help.</p>
[ { "answer_id": 74599234, "author": "Nikol Stoyanova", "author_id": 9851216, "author_profile": "https://Stackoverflow.com/users/9851216", "pm_score": -1, "selected": false, "text": "sed -e 's/searchFor/replaceWith/g' filename\n sed -e 's/#/'$i'/g' a.tex > output.tex\n sed -i 's/#/'$i'/g' a.tex\n" }, { "answer_id": 74599775, "author": "Ed Morton", "author_id": 1745001, "author_profile": "https://Stackoverflow.com/users/1745001", "pm_score": 2, "selected": true, "text": "$ awk '/\\\\begin[{]pycode}/{s++} {gsub(/#/,s); print}' a.tex\n\\begin{pycode}\n\nSome text right here, let's say Text 1A: like: There are 1cat and 1dog.\n\n\\end{pycode}\n\nSome text right here, let's say Text 1B: like: One day the 1dog tried to run away.\n\n\n\\begin{pycode}\n\nSome text right here, let's say Text 2A: like: There are 2cat and 2dog and 2pig.\n\n\\end{pycode}\n\nSome text right here, let's say Text 2B: like: There is 2something here.\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20621003/" ]
74,597,479
<p>I had to change something in my gradle.build file, now I get an error. I think I know where the problem is, but I am not able to solve.</p> <p>This is the error:</p> <p><code>Duplicate class androidx.lifecycle.ViewModelLazy found in modules lifecycle-viewmodel-2.5.1-runtime (androidx.lifecycle:lifecycle-viewmodel:2.5.1) and lifecycle-viewmodel-ktx-2.3.1-runtime (androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1) Duplicate class androidx.lifecycle.ViewTreeViewModelKt found in modules lifecycle-viewmodel-2.5.1-runtime (androidx.lifecycle:lifecycle-viewmodel:2.5.1) and lifecycle-viewmodel-ktx-2.3.1-runtime (androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1) </code></p> <p>What I have tried so far:</p> <pre><code>configurations.implementation { exclude group: 'androidx.lifecycle' , module:'lifecycle-viewmodel-2.5.1-runtime' } </code></pre> <p>But honestly, I have no clue what I do - my experience is Java not gradle</p>
[ { "answer_id": 74599234, "author": "Nikol Stoyanova", "author_id": 9851216, "author_profile": "https://Stackoverflow.com/users/9851216", "pm_score": -1, "selected": false, "text": "sed -e 's/searchFor/replaceWith/g' filename\n sed -e 's/#/'$i'/g' a.tex > output.tex\n sed -i 's/#/'$i'/g' a.tex\n" }, { "answer_id": 74599775, "author": "Ed Morton", "author_id": 1745001, "author_profile": "https://Stackoverflow.com/users/1745001", "pm_score": 2, "selected": true, "text": "$ awk '/\\\\begin[{]pycode}/{s++} {gsub(/#/,s); print}' a.tex\n\\begin{pycode}\n\nSome text right here, let's say Text 1A: like: There are 1cat and 1dog.\n\n\\end{pycode}\n\nSome text right here, let's say Text 1B: like: One day the 1dog tried to run away.\n\n\n\\begin{pycode}\n\nSome text right here, let's say Text 2A: like: There are 2cat and 2dog and 2pig.\n\n\\end{pycode}\n\nSome text right here, let's say Text 2B: like: There is 2something here.\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20621041/" ]
74,597,491
<p>I can make a <code>growing underline effect</code> which will grow to full width and then shrink to its origin:</p> <pre><code>&lt;a href=&quot;#&quot; class=&quot;group font-normal&quot;&gt; Home &lt;span class=&quot;block max-w-0 group-hover:max-w-full transition-all h-0.5 bg-slate-200&quot;/&gt; &lt;/a&gt; </code></pre> <p>How do I create a similar effect but with the <code>underline</code> exiting to the right like in version 1 of this <a href="https://tympanus.net/Development/LineHoverStyles/" rel="nofollow noreferrer">demo</a></p>
[ { "answer_id": 74597890, "author": "Sarkar", "author_id": 13741787, "author_profile": "https://Stackoverflow.com/users/13741787", "pm_score": 0, "selected": false, "text": "<button class=\"relative py-1 after:absolute after:bottom-0 after:left-0 after:w-full after:scale-x-0 hover:after:scale-x-100 after:transition-all after:origin-left after:h-[2px] after:bg-black\">Hover Me</button>\n <button class=\"relative py-1 after:absolute after:bottom-0 after:left-0 after:w-full after:scale-x-0 hover:after:scale-x-100 after:transition-all after:origin-right after:h-[2px] after:bg-black\">Hover Me</button>\n origin-[direction]" }, { "answer_id": 74598482, "author": "Ihar Aliakseyenka", "author_id": 14305076, "author_profile": "https://Stackoverflow.com/users/14305076", "pm_score": 2, "selected": true, "text": "<a href=\"#\" class=\"hover:before:scale-x-100 hover:before:origin-left relative before:w-full before:h-1 before:origin-right before:transition-transform before:duration-300 before:scale-x-0 before:bg-red-500 before:absolute before:left-0 before:bottom-0 \">\n Hover me\n</a>\n transform-origin before:origin-right hover:before:origin-left\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7826511/" ]
74,597,504
<p>I have a community list as the following <code>list_community</code>. How do I edit the code below to make the community visible?</p> <pre><code>from igraph import * list_community = [['A', 'B', 'C', 'D'],['E','F','G'],['G', 'H','I','J']] list_nodes = ['A', 'B', 'C', 'D','E','F','G','H','I','J'] tuple_edges = [('A','B'),('A','C'),('A','D'),('B','C'),('B','D'), ('C','D'),('C','E'), ('E','F'),('E','G'),('F','G'),('G','H'), ('G','I'), ('G','J'),('H','I'),('H','J'),('I','J'),] # Make a graph g_test = Graph() g_test.add_vertices(list_nodes) g_test.add_edges(tuple_edges) # Plot layout = g_test.layout(&quot;kk&quot;) g.vs[&quot;name&quot;] = list_nodes visual_style = {} visual_style[&quot;vertex_label&quot;] = g.vs[&quot;name&quot;] visual_style[&quot;layout&quot;] = layout ig.plot(g_test, **visual_style) </code></pre> <p><a href="https://i.stack.imgur.com/9KvrO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9KvrO.png" alt="enter image description here" /></a></p> <p>I would like a plot that visualizes the community as shown below.</p> <p><a href="https://i.stack.imgur.com/6yZVM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6yZVM.png" alt="enter image description here" /></a></p> <p>I can also do this by using a module other than igraph. Thank you.</p>
[ { "answer_id": 74612374, "author": "Frodnar", "author_id": 15534441, "author_profile": "https://Stackoverflow.com/users/15534441", "pm_score": 2, "selected": true, "text": "plt.fill() import networkx as nx\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib import cm\n\ndef sort_xy(x, y):\n\n x0 = np.mean(x)\n y0 = np.mean(y)\n\n r = np.sqrt((x-x0)**2 + (y-y0)**2)\n\n angles = np.where((y-y0) > 0, np.arccos((x-x0)/r), 2*np.pi-np.arccos((x-x0)/r))\n\n mask = np.argsort(angles)\n\n x_sorted = x[mask]\n y_sorted = y[mask]\n\n return x_sorted, y_sorted\n\nG = nx.karate_club_graph()\n\npos = nx.spring_layout(G, seed=42)\nfig, ax = plt.subplots(figsize=(8, 10))\nnx.draw(G, pos=pos, with_labels=True)\n\ncommunities = nx.community.louvain_communities(G)\n\nalpha = 0.5\nedge_padding = 10\ncolors = cm.get_cmap('viridis', len(communities))\n\nfor i, comm in enumerate(communities):\n\n if len(comm) == 1:\n cir = plt.Circle((pos[comm.pop()]), edge_padding / 100, alpha=alpha, color=colors(i))\n ax.add_patch(cir)\n\n elif len(comm) == 2:\n comm_pos = {k: pos[k] for k in comm}\n coords = [a for a in zip(*comm_pos.values())]\n x, y = coords[0], coords[1]\n plt.plot(x, y, linewidth=edge_padding, linestyle=\"-\", alpha=alpha, color=colors(i))\n\n else:\n comm_pos = {k: pos[k] for k in comm}\n coords = [a for a in zip(*comm_pos.values())]\n x, y = sort_xy(np.array(coords[0]), np.array(coords[1]))\n plt.fill(x, y, alpha=alpha, facecolor=colors(i), \n edgecolor=colors(i), # set to None to remove edge padding\n linewidth=edge_padding)\n" }, { "answer_id": 74628651, "author": "Vincent Traag", "author_id": 767411, "author_profile": "https://Stackoverflow.com/users/767411", "pm_score": 2, "selected": false, "text": "igraph VertexCover mark_groups VertexCover g_test.vs.find clusters = [[g_test.vs.find(name=v).index for v in cl] for cl in list_community]\ncover = ig.VertexCover(g_test, clusters)\n ig.plot(cover,\n mark_groups=True,\n palette=ig.RainbowPalette(3))\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13882652/" ]
74,597,508
<p>I'm having problem during repo sync. Error is lke below</p> <pre><code>fatal: unable to find remote helper for 'https' </code></pre> <p>So I searched and found that I don't have <strong>git-remote-http</strong>* and <strong>git-remote-https</strong>* at git/usr/local/libexec/git-core (git --exec-path output).</p> <p>I tried to install refering to this <a href="https://confluence.atlassian.com/bitbucketserverkb/unable-to-find-remote-helper-for-https-during-git-fetch-clone-1071830596.html" rel="nofollow noreferrer">link</a></p> <pre><code>$ wget https://github.com/git/git/archive/v2.17.1.tar.gz -O git-2.17.1.tar.gz $ tar -zxf git-2.22.0.tar.gz $ cd git-2.17.1 $ make configure $ ./configure -prefix=/usr/local $ make install </code></pre> <p>But after install is done, still no git-remote-http and still failure with the sync.</p> <p>How can I install <strong>git-remote-http?</strong> My git version is 2.17.1 and curl version is 7.58.0.</p>
[ { "answer_id": 74612374, "author": "Frodnar", "author_id": 15534441, "author_profile": "https://Stackoverflow.com/users/15534441", "pm_score": 2, "selected": true, "text": "plt.fill() import networkx as nx\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib import cm\n\ndef sort_xy(x, y):\n\n x0 = np.mean(x)\n y0 = np.mean(y)\n\n r = np.sqrt((x-x0)**2 + (y-y0)**2)\n\n angles = np.where((y-y0) > 0, np.arccos((x-x0)/r), 2*np.pi-np.arccos((x-x0)/r))\n\n mask = np.argsort(angles)\n\n x_sorted = x[mask]\n y_sorted = y[mask]\n\n return x_sorted, y_sorted\n\nG = nx.karate_club_graph()\n\npos = nx.spring_layout(G, seed=42)\nfig, ax = plt.subplots(figsize=(8, 10))\nnx.draw(G, pos=pos, with_labels=True)\n\ncommunities = nx.community.louvain_communities(G)\n\nalpha = 0.5\nedge_padding = 10\ncolors = cm.get_cmap('viridis', len(communities))\n\nfor i, comm in enumerate(communities):\n\n if len(comm) == 1:\n cir = plt.Circle((pos[comm.pop()]), edge_padding / 100, alpha=alpha, color=colors(i))\n ax.add_patch(cir)\n\n elif len(comm) == 2:\n comm_pos = {k: pos[k] for k in comm}\n coords = [a for a in zip(*comm_pos.values())]\n x, y = coords[0], coords[1]\n plt.plot(x, y, linewidth=edge_padding, linestyle=\"-\", alpha=alpha, color=colors(i))\n\n else:\n comm_pos = {k: pos[k] for k in comm}\n coords = [a for a in zip(*comm_pos.values())]\n x, y = sort_xy(np.array(coords[0]), np.array(coords[1]))\n plt.fill(x, y, alpha=alpha, facecolor=colors(i), \n edgecolor=colors(i), # set to None to remove edge padding\n linewidth=edge_padding)\n" }, { "answer_id": 74628651, "author": "Vincent Traag", "author_id": 767411, "author_profile": "https://Stackoverflow.com/users/767411", "pm_score": 2, "selected": false, "text": "igraph VertexCover mark_groups VertexCover g_test.vs.find clusters = [[g_test.vs.find(name=v).index for v in cl] for cl in list_community]\ncover = ig.VertexCover(g_test, clusters)\n ig.plot(cover,\n mark_groups=True,\n palette=ig.RainbowPalette(3))\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16477827/" ]
74,597,567
<p>I am struggling to have VS code suggest the list of keys for the below snippet. Could you please help me to get the keys autopopulate?</p> <pre><code>const myVar : Record&lt;string, string&gt; = { key1: 'val1', } myVar.key2 = &quot;val2&quot;, myVar.key3 = &quot;val3&quot;; myVar. //doesn't populate the keys </code></pre>
[ { "answer_id": 74597624, "author": "Garuno", "author_id": 5625089, "author_profile": "https://Stackoverflow.com/users/5625089", "pm_score": 2, "selected": true, "text": "Record interface MyInterface {\n key1: string;\n key2: string;\n key3: string;\n}\n\nconst myVar : MyInterface = {\n key1: 'val1',\n key2: '',\n key3: '',\n }\n myVar.key2 = \"val2\":\n myVar.key3 = \"val3\";\n" }, { "answer_id": 74597765, "author": "captain-yossarian from Ukraine", "author_id": 8495254, "author_profile": "https://Stackoverflow.com/users/8495254", "pm_score": 2, "selected": false, "text": "myVar Record<...> satisfies Record<string, string> myVar const myVar: Record<string, string> = {\n key1: 'val1',\n\n}\nmyVar.key2 = \"val2\",\nmyVar.key3 = \"val3\";\n\nfunction mutate<\n Obj extends { [prop: string]: string },\n Key extends string,\n Value extends string\n>(obj: Obj, key: Key, value: Value): asserts obj is Obj & Record<Key, Value> {\n Object.assign(obj, { [key]: value })\n}\n\nmutate(myVar, 'key1', 'val2')\n\nmyVar.key1 // val2\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6303421/" ]
74,597,581
<p>I am converting milliseconds into ZonedDateTime</p> <pre><code>Long lEpochMilliSeconds = 1668415926445; System.out.println(ZonedDateTime.ofInstant(Instant.ofEpochMilli(lEpochMilliSeconds),ZoneId.of(&quot;UTC&quot;)); </code></pre> <p>It gives output:</p> <pre><code>2022-10-28T12:59:34.939Z[UTC] </code></pre> <p>I don't want the time zone &quot;[UTC]&quot; part in my output. I need my out to be like this in ZonedDateTime format:</p> <pre><code>2022-10-28T12:59:34.939Z </code></pre> <p>I need the <strong>forma</strong>t in <strong>ZonedDateTime</strong> only <strong>not string</strong>, as I will be returning the value &amp; use it somewhere else</p>
[ { "answer_id": 74597634, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "ZonedDateTime int Instant ZonedDateTime ZonedDateTime Instant" }, { "answer_id": 74597746, "author": "Sai T", "author_id": 18306210, "author_profile": "https://Stackoverflow.com/users/18306210", "pm_score": 1, "selected": false, "text": "ZonedDateTime.ofInstant(Instant.ofEpochMilli(lEpochMilliSeconds), ZoneOffset.UTC);\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18306210/" ]
74,597,600
<p>I am trying to run this code:</p> <pre><code>wb=openpyxl.load_workbook('Output_Report_v16.xlsm',read_only=False,keep_vba=True) sheets=wb.sheetnames sheet_InputData_Overview=wb [sheets[7]] img=openpyxl.drawing.image.Image('Eink_Liq.png') sheet_InputData_Overview.add_image(ws.cell(2,28)) wb.save('Output_Report_v16.xlsm') </code></pre> <p>When python runs the last line of code this error arises:</p> <p>'Cell' object has no attribute '_id'</p> <p>The excel file contains VBA which should not be changed or deleted.</p> <p>Do you have any idea what may be wrong with this code?</p>
[ { "answer_id": 74597647, "author": "Ngô Văn Quyền", "author_id": 6308667, "author_profile": "https://Stackoverflow.com/users/6308667", "pm_score": -1, "selected": false, "text": "ws[cell].style = Style(font=Font(color=Color(colors.RED))) \n" }, { "answer_id": 74598252, "author": "moken", "author_id": 13664137, "author_profile": "https://Stackoverflow.com/users/13664137", "pm_score": 2, "selected": true, "text": "...\nwb=openpyxl.load_workbook('Output_Report_v16.xlsm',read_only=False,keep_vba=True)\nsheets=wb.sheetnames\nsheet_InputData_Overview=wb [sheets[7]]\n\nimg=openpyxl.drawing.image.Image('Eink_Liq.png')\n\n### This line is wrong and references 'ws' object not defined\n# sheet_InputData_Overview.add_image(ws.cell(2,28))\n\n### Set the position for the image in the sheet\nimg.anchor = sheet_InputData_Overview.cell(row=2, column=28).coordinate\n### Add the image 'img' to the sheet\nsheet_InputData_Overview.add_image(img)\n\n\nwb.save('Output_Report_v16.xlsm')\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17425489/" ]
74,597,695
<p>I have a dataframe with dates saved in one column and the corresponding time zone in another, both in character format. The dates are local dates in the respective timezone noted in the timezone column, not UTC.</p> <pre><code>data_frame = data.frame(eventid = c(1:4), start = c(&quot;2021-05-05 01:04:34&quot;, &quot;2021-03-06 03:14:44&quot;, &quot;2021-03-11 07:22:48&quot;, &quot;2021-02-02 11:54:56&quot;) , start_timezone = c(&quot;Europe/Berlin&quot;, &quot;Europe/Berlin&quot;, &quot;Europe/Berlin&quot;, &quot;Indian/Maldives&quot;) ) </code></pre> <p>I need to convert the date column into datetime objects that take the differing timezones into account, but feeding the text timezone to any function has not worked for me, e.g.</p> <pre><code>data_frame %&gt;% rowwise() %&gt;% mutate(start_in_zone= as.POSIXct(start, tz = start_timezone)) </code></pre> <p>How would I approach this ?</p>
[ { "answer_id": 74597844, "author": "Benson_YoureFired", "author_id": 11636794, "author_profile": "https://Stackoverflow.com/users/11636794", "pm_score": 1, "selected": false, "text": "lubridate with_tz() library(lubridate)\nlibrary(dplyr)\n\n\ndf %>% \n mutate(l_start = ymd_hms(start)) %>% \n group_by(start_timezone) %>% \n mutate(start_local = with_tz(l_start, start_timezone)) %>% \n select(-l_start)\n\n\n# A tibble: 4 x 4\n# Groups: start_timezone [2]\n eventid start start_timezone start_local \n <int> <chr> <chr> <dttm> \n1 1 2021-05-05 01:04:34 Europe/Berlin 2021-05-05 03:04:34\n2 2 2021-03-06 03:14:44 Europe/Berlin 2021-03-06 04:14:44\n3 3 2021-03-11 07:22:48 Europe/Berlin 2021-03-11 08:22:48\n4 4 2021-02-02 11:54:56 Indian/Maldives 2021-02-02 12:54:56\n\n" }, { "answer_id": 74597892, "author": "Ronak Shah", "author_id": 3962914, "author_profile": "https://Stackoverflow.com/users/3962914", "pm_score": 1, "selected": false, "text": "as_datetime library(dplyr)\nlibrary(lubridate)\n\ndata_frame %>%\n rowwise() %>%\n mutate(UTC_time= as_datetime(start, tz = start_timezone) %>% \n as_datetime(tz = 'UTC')) %>%\n ungroup\n\n# eventid start start_timezone UTC_time \n# <int> <chr> <chr> <dttm> \n#1 1 2021-05-05 01:04:34 Europe/Berlin 2021-05-04 23:04:34\n#2 2 2021-03-06 03:14:44 Europe/Berlin 2021-03-06 02:14:44\n#3 3 2021-03-11 07:22:48 Europe/Berlin 2021-03-11 06:22:48\n#4 4 2021-02-02 11:54:56 Indian/Maldives 2021-02-02 06:54:56\n" }, { "answer_id": 74605938, "author": "Chris", "author_id": 794450, "author_profile": "https://Stackoverflow.com/users/794450", "pm_score": 0, "selected": false, "text": "on_tzs <- structure(list(eventid = 1:4, start = c(\"2021-05-05 01:04:34\", \n\"2021-03-06 03:14:44\", \"2021-03-11 07:22:48\", \"2021-02-02 11:54:56\"\n), start_timezone = c(\"Europe/Berlin\", \"Europe/Berlin\", \"Europe/Berlin\", \n\"Indian/Maldives\")), class = \"data.frame\", row.names = c(NA, \n-4L))\n $start_in_zone on_tzs['start_in_zone'] <- NA_character_ \nclass(on_tzs$start_in_zone) <- c(\"POSIXct\", \"POSIXt\")\nclass(on_tzs$start_in_zone)\n[1] \"POSIXct\" \"POSIXt\"\n for (i in 1:4) {\non_tzs$start_in_zone[i] <- strftime(x = on_tzs$start[i], format = '%Y-%m-%d %H:%m:%OS', tz = on_tzs$start_timezone[i], usetz = TRUE)\n }\non_tzs\n eventid start start_timezone start_in_zone\n1 1 2021-05-05 01:04:34 Europe/Berlin 2021-05-05 01:05:34\n2 2 2021-03-06 03:14:44 Europe/Berlin 2021-03-06 03:03:44\n3 3 2021-03-11 07:22:48 Europe/Berlin 2021-03-11 07:03:48\n4 4 2021-02-02 11:54:56 Indian/Maldives 2021-02-02 11:02:56\n print(on_tzs$start_in_zone)\n[1] \"2021-05-05 01:05:34 CEST\" \"2021-03-06 03:03:44 CET\" \n[3] \"2021-03-11 07:03:48 CET\" \"2021-02-02 11:02:56 CET\"\n # an argument seems to be developing for using `lubridate` to preserve sanity\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8252498/" ]
74,597,716
<p>I have data that look like this.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>company_name</th> <th>new_company_status</th> </tr> </thead> <tbody> <tr> <td>A Co.,Ltd</td> <td>Yes</td> </tr> <tr> <td>B. Inc</td> <td>No</td> </tr> <tr> <td>PT XYZ</td> <td>No</td> </tr> <tr> <td>PT DFE, Tbk.</td> <td>Yes</td> </tr> <tr> <td>A Co.,Ltd</td> <td>Yes</td> </tr> <tr> <td>PT DFE, Tbk.</td> <td>Yes</td> </tr> </tbody> </table> </div> <p>I want to create a function in python to check every unique company name from 'company_name' column and compare the 'new_company_status', if the 'new_company_status' is &quot;Yes&quot; for every unique company name, it will count as 1 and iterate to get the total number of new company.</p> <p>So far this is the code that I write: `</p> <pre><code>def new_comp(DataFrame): comp_list = df['Company_Name'].values.tolist uniq_comp = set(comp_list) for x in uniq_comp: if df['Status_New_Company'] == &quot;Yes&quot;: uniq_comp += 1 print('New Companies: ', uniq_comp) </code></pre> <p>`</p> <p>Can anyone help me to complete and/or revise the code? I expect the output is integer to define the total of new company. Thank u in advance.</p>
[ { "answer_id": 74597725, "author": "jezrael", "author_id": 2901002, "author_profile": "https://Stackoverflow.com/users/2901002", "pm_score": 0, "selected": false, "text": "company_name new_company_status Yes N = len(set(df.loc[df['new_company_status'].eq('Yes'), 'company_name']))\n Yes company_name sum df1 = (df['new_company_status'].eq('Yes')\n .groupby(df['company_name'])\n .sum()\n .reset_index(name='countYes'))\n" }, { "answer_id": 74597734, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 1, "selected": false, "text": "# keep one company of each\nm1 = ~df['company_name'].duplicated()\n# is this a yes?\nm2 = df['new_company_status'].eq('Yes')\n\n# count cases for which both conditions are True\nout = (m1&m2).sum()\n 2 groupby.any out = (df['new_company_status']\n .eq('Yes')\n .groupby(df['company_name']).any()\n .sum()\n)\n 2" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16254019/" ]
74,597,749
<p>If I have two inputs like the following</p> <pre><code>&lt;input type=&quot;text&quot; name=&quot;id&quot;&gt; &lt;input type=&quot;text&quot; name=&quot;name&quot;&gt; </code></pre> <p>Then it is possible to get values in array on backend like this array(&quot;id&quot;=&gt;&quot;name&quot;)</p> <p>If it is possible then how it can be done?</p>
[ { "answer_id": 74597830, "author": "Yohann Daniel Carter", "author_id": 4849739, "author_profile": "https://Stackoverflow.com/users/4849739", "pm_score": 0, "selected": false, "text": "<form name=\"form\" action=\"\" method=\"post\">\n<input type=\"text\" name=\"id\">\n<input type=\"text\" name=\"name\">\n<input type=\"submit\" name=\"submit_button\" \n value=\"Send\"/>\n</form>\n <?php\n$array = [$_POST['id'] => $_POST['name']];\n" }, { "answer_id": 74600734, "author": "Ajju Bhai", "author_id": 20580686, "author_profile": "https://Stackoverflow.com/users/20580686", "pm_score": 2, "selected": true, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n <title>Document</title>\n</head>\n\n<body>\n <form method=\"post\">\n <input type=\"text\" name=\"id[]\">\n <input type=\"text\" name=\"name[]\">\n <input type=\"submit\" name=\"submit\" value=\"submit\">\n </form>\n</body>\n\n</html>\n\n<?php\n if(isset($_POST['submit']))\n {\n $combineArr = array_combine($_POST['id'], $_POST['name']);\n print_r($combineArr);\n }\n?>\n Array ( [id] => name )\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14878765/" ]
74,597,750
<p>I want to save the loop result into a csv file or dataframe; the below code just writes the tweets to the console.</p> <pre><code>j =1 sortedDF = tweets_df.sort_values(by = ['Polarity']) for i in range (0, sortedDF.shape[0]): if(sortedDF['Analysis'][i] == 'Positive'): print(str(j)+')'+ sortedDF['transalted'][i]) print() j = j+1 </code></pre>
[ { "answer_id": 74597830, "author": "Yohann Daniel Carter", "author_id": 4849739, "author_profile": "https://Stackoverflow.com/users/4849739", "pm_score": 0, "selected": false, "text": "<form name=\"form\" action=\"\" method=\"post\">\n<input type=\"text\" name=\"id\">\n<input type=\"text\" name=\"name\">\n<input type=\"submit\" name=\"submit_button\" \n value=\"Send\"/>\n</form>\n <?php\n$array = [$_POST['id'] => $_POST['name']];\n" }, { "answer_id": 74600734, "author": "Ajju Bhai", "author_id": 20580686, "author_profile": "https://Stackoverflow.com/users/20580686", "pm_score": 2, "selected": true, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n <title>Document</title>\n</head>\n\n<body>\n <form method=\"post\">\n <input type=\"text\" name=\"id[]\">\n <input type=\"text\" name=\"name[]\">\n <input type=\"submit\" name=\"submit\" value=\"submit\">\n </form>\n</body>\n\n</html>\n\n<?php\n if(isset($_POST['submit']))\n {\n $combineArr = array_combine($_POST['id'], $_POST['name']);\n print_r($combineArr);\n }\n?>\n Array ( [id] => name )\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6267862/" ]
74,597,779
<p>i was trying to solve a problem i had in a code that should draw text from a text file on a picture. the problem i had is that the program stack all the text on each other in every picture after the first picture(2,3,4,5). i can't explain what's the problem so i'll just leave a photo (<a href="https://i.stack.imgur.com/nkY2O.png" rel="nofollow noreferrer">https://i.stack.imgur.com/nkY2O.png</a>)</p> <pre><code>#vars f = open(&quot;text.txt&quot;,&quot;r&quot;) img = Image.open(&quot;testpic.jpg&quot;) draw = ImageDraw.Draw(img) img_center = (215,190) fnt = ImageFont.truetype('arial.ttf',32) #code for i in range(1,6): img_txt = (f.readline()) draw.text(img_center, img_txt, font=fnt, stroke_fill=(0, 0, 0)) img.save('Image'+str(i)+'.png') </code></pre> <p>i tried to change the image text to f.readlines() but the problem was still there.</p>
[ { "answer_id": 74597830, "author": "Yohann Daniel Carter", "author_id": 4849739, "author_profile": "https://Stackoverflow.com/users/4849739", "pm_score": 0, "selected": false, "text": "<form name=\"form\" action=\"\" method=\"post\">\n<input type=\"text\" name=\"id\">\n<input type=\"text\" name=\"name\">\n<input type=\"submit\" name=\"submit_button\" \n value=\"Send\"/>\n</form>\n <?php\n$array = [$_POST['id'] => $_POST['name']];\n" }, { "answer_id": 74600734, "author": "Ajju Bhai", "author_id": 20580686, "author_profile": "https://Stackoverflow.com/users/20580686", "pm_score": 2, "selected": true, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n <title>Document</title>\n</head>\n\n<body>\n <form method=\"post\">\n <input type=\"text\" name=\"id[]\">\n <input type=\"text\" name=\"name[]\">\n <input type=\"submit\" name=\"submit\" value=\"submit\">\n </form>\n</body>\n\n</html>\n\n<?php\n if(isset($_POST['submit']))\n {\n $combineArr = array_combine($_POST['id'], $_POST['name']);\n print_r($combineArr);\n }\n?>\n Array ( [id] => name )\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20621225/" ]
74,597,850
<p>I am dealing with some code that performs RC4 encryption algorithm with some params passed into the function. From there I am trying to append the generated hash to an empty string but have failed with a few of my attempts. I had seen the use of <code>snprintf()</code> but how could I go about converting the code below to save what gets printed to a string?</p> <pre><code> for (size_t i = 0, len = strlen(plaintext); i &lt; len; i++) { printf(&quot;|x%02hhx| &quot;, hash[i]); } </code></pre>
[ { "answer_id": 74598021, "author": "KamilCuk", "author_id": 9072753, "author_profile": "https://Stackoverflow.com/users/9072753", "pm_score": 3, "selected": false, "text": "#include <iomanip>\n#include <iostream>\n#include <sstream>\n#include <cstring>\n\nint main() {\n char plaintext[] = \"12345\";\n char hash[] = \"123\\xf0\\x0f\";\n std::stringstream out;\n for (size_t i = 0, len = strlen(plaintext); i < len; i++) {\n out << \"|x\"\n << std::setfill('0') << std::setw(2) << std::setbase(16)\n // ok, maybe this is the reason.\n << 0xff & hash[i]\n << \"| \";\n }\n std::cout << out.str();\n}\n" }, { "answer_id": 74598053, "author": "fabian", "author_id": 2991525, "author_profile": "https://Stackoverflow.com/users/2991525", "pm_score": 0, "selected": false, "text": "std::string::data std::snprintf template<class...Args>\nstd::string PrintFToString(char const* format, Args...args)\n{\n std::string result;\n char c;\n int requiredSize = std::snprintf(&c, 1, format, args...);\n if (requiredSize < 0)\n {\n throw std::runtime_error(\"error with snprintf\");\n }\n\n result.resize(requiredSize);\n\n int writtenSize = std::snprintf(result.data(), requiredSize+1, format, args...);\n assert(writtenSize == requiredSize);\n\n return result;\n}\n\ntemplate<class...Args>\nvoid AppendPrintFToString(std::string& target, char const* format, Args...args)\n{\n char c;\n int requiredSize = std::snprintf(&c, 1, format, args...);\n if (requiredSize < 0)\n {\n throw std::runtime_error(\"error with snprintf\");\n }\n\n auto const oldSize = target.size();\n target.resize(oldSize + requiredSize);\n\n int writtenSize = std::snprintf(target.data() + oldSize, requiredSize+1, format, args...);\n assert(writtenSize == requiredSize);\n}\n\nint main() {\n std::cout << PrintFToString(\"|x%02hhx| \", 33) << '\\n';\n\n std::string output;\n for (int i = 0; i != 64; ++i)\n {\n AppendPrintFToString(output, \"|x%02hhx| \", i);\n output.push_back('\\n');\n }\n\n std::cout << output;\n}\n std::snprintf" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19002577/" ]
74,597,895
<p>Below query is running smoothly if I remove order by. Any insights why it is not accepting transformed data in order by ?</p> <p><a href="https://i.stack.imgur.com/wbUoq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wbUoq.png" alt="enter image description here" /></a></p> <p>Code for your reference:</p> <pre><code>select date(creation_date) , count(*) from bigquery-public-data.stackoverflow.post_links group by date(creation_date) order by date(creation_date) </code></pre>
[ { "answer_id": 74599239, "author": "Rathish Kumar B", "author_id": 2156784, "author_profile": "https://Stackoverflow.com/users/2156784", "pm_score": 3, "selected": true, "text": "SELECT DATE(creation_date), COUNT(*) FROM bigquery-public-data.stackoverflow.post_links\nGROUP BY DATE(creation_date)\nORDER BY 1 DESC LIMIT 10\n SELECT DATE(creation_date) AS crdate, COUNT(*) FROM bigquery-public-data.stackoverflow.post_links\nGROUP BY crdate\nORDER BY crdate DESC LIMIT 10\n" }, { "answer_id": 74600955, "author": "kiran mathew", "author_id": 17258510, "author_profile": "https://Stackoverflow.com/users/17258510", "pm_score": 1, "selected": false, "text": "date(creation_date) functional output Example using ordinals: select date(creation_date) , count(*) from bigquery-public-data.stackoverflow.post_links\ngroup by 1 order by 1;\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3511840/" ]
74,597,981
<p>I am using the docker-ejabberd/ecs container as a XMPP server and the <a href="https://metacpan.org/pod/Net::XMPP" rel="nofollow noreferrer">Net::XMPP perl client</a> My ejabberd.yml looks like this:</p> <pre><code> hosts: - jabber-gw.foobar.me loglevel: debug ca_file: /etc/ssl/certs/ca-certificates.crt acme: ca_url: https://ca.foobar.local:8000/acme/acme/directory auto: false cert_type: rsa listen: - port: 5222 ip: &quot;0.0.0.0&quot; module: ejabberd_c2s max_stanza_size: 65536 shaper: c2s_shaper access: c2s starttls_required: true - port: 5223 ip: &quot;0.0.0.0&quot; tls: true module: ejabberd_c2s shaper: c2s_shaper access: c2s starttls_required: true - port: 5269 ip: &quot;0.0.0.0&quot; module: ejabberd_s2s_in max_stanza_size: 65536 - port: 5443 ip: &quot;0.0.0.0&quot; module: ejabberd_http tls: true request_handlers: /admin: ejabberd_web_admin /api: mod_http_api /bosh: mod_bosh /captcha: ejabberd_captcha /upload: mod_http_upload /ws: ejabberd_http_ws - port: 5280 ip: &quot;0.0.0.0&quot; module: ejabberd_http request_handlers: /admin: ejabberd_web_admin /.well-known/acme-challenge: ejabberd_acme - port: 3478 ip: &quot;0.0.0.0&quot; transport: udp module: ejabberd_stun use_turn: true ## The server's public IPv4 address: # turn_ipv4_address: &quot;203.0.113.3&quot; ## The server's public IPv6 address: # turn_ipv6_address: &quot;2001:db8::3&quot; - port: 1883 ip: &quot;0.0.0.0&quot; module: mod_mqtt backlog: 1000 s2s_use_starttls: optional acl: local: user_regexp: &quot;&quot; loopback: ip: - 127.0.0.0/8 - ::1/128 </code></pre> <p>My ejabberd client perl code looks like this:</p> <pre><code> #!/usr/bin/perl use strict; use warnings; use Net::XMPP qw( Client ); if ($#ARGV &lt; 4) { print &quot;\nperl client.pl &lt;server&gt; &lt;port&gt; &lt;username&gt; &lt;password&gt; &lt;resource&gt; \n\n&quot;; exit(0); } my $server = $ARGV[0]; my $port = $ARGV[1]; my $username = $ARGV[2]; my $password = $ARGV[3]; my $resource = $ARGV[4]; $SIG{HUP} = \&amp;Stop; $SIG{KILL} = \&amp;Stop; $SIG{TERM} = \&amp;Stop; $SIG{INT} = \&amp;Stop; my $Connection = new Net::XMPP::Client( debug =&gt; &quot;stdout&quot;, debuglevel =&gt; 2 ); $Connection-&gt;SetCallBacks(message=&gt;\&amp;InMessage, presence=&gt;\&amp;InPresence, iq=&gt;\&amp;InIQ); my $status = $Connection-&gt;Connect(hostname=&gt;$server, port=&gt;$port, tls=&gt;1, srv=&gt;&quot;jabber-gw.foobar.me&quot;, ssl_ca_path=&gt;&quot;/etc/ssl/certs/&quot; ); if (!(defined($status))) { print &quot;ERROR: Jabber server is down or connection was not allowed.\n&quot;; print &quot; ($!)\n&quot;; exit(0); } my @result = $Connection-&gt;AuthSend(username=&gt;$username, password=&gt;$password, resource=&gt;$resource); if ($result[0] ne &quot;ok&quot;) { print &quot;ERROR: Authorization failed: $result[0] - $result[1]\n&quot;; exit(0); } print &quot;Logged in to $server:$port...\n&quot;; $Connection-&gt;RosterGet(); print &quot;Getting Roster to tell server to send presence info...\n&quot;; $Connection-&gt;PresenceSend(); print &quot;Sending presence to tell world that we are logged in...\n&quot;; while(defined($Connection-&gt;Process())) { } print &quot;ERROR: The connection was killed...\n&quot;; exit(0); sub Stop { print &quot;Exiting...\n&quot;; $Connection-&gt;Disconnect(); exit(0); } </code></pre> <blockquote> <p>I can successfully obtain an ACME cert for my host, then add the ca root cert to the clients ssl_ca_path. I then register the client on the server with ejabberdclt instructions. When i try to connect the client to the server, i see **Nodeprep failed **in the server logs:</p> </blockquote> <pre><code> 2022-11-28 05:35:44.211915+00:00 [info] (&lt;0.974.0&gt;) Accepted connection 192.168.11.19:44198 -&gt; 192.168.32.4:5222 2022-11-28 05:35:44.212589+00:00 [notice] (tcp|&lt;0.974.0&gt;) Received XML on stream = &lt;&lt;&quot;&lt;?xml version='1.0'?&gt;&lt;stream:stream version='1.0' xmlns:stream='http://etherx.jabber.org/streams' xmlns='jabber:client' to='jabber-gw.foobar.me' from='OMVonHP.foobar.me' xml:lang='en' &gt;&quot;&gt;&gt; .. omitted .. 2022-11-28 05:35:44.310551+00:00 [notice] (tls|&lt;0.974.0&gt;) Received XML on stream = &lt;&lt;&quot;&lt;response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'&gt;&lt;/response&gt;&quot;&gt;&gt; 2022-11-28 05:35:44.310855+00:00 [debug] Running hook c2s_handle_recv: mod_stream_mgmt:c2s_handle_recv/3 2022-11-28 05:35:44.311055+00:00 [debug] Running hook c2s_auth_result: ejabberd_c2s:process_auth_result/3 2022-11-28 05:35:44.311249+00:00 [warning] (tls|&lt;0.974.0&gt;) Failed c2s DIGEST-MD5 authentication from 192.168.11.19: Nodeprep failed 2022-11-28 05:35:44.311422+00:00 [debug] Running hook c2s_auth_result: mod_fail2ban:c2s_auth_result/3 2022-11-28 05:35:44.311667+00:00 [notice] (tls|&lt;0.974.0&gt;) Send XML on stream = &lt;&lt;&quot;&lt;failure xmlns='urn:ietf:params:xml:ns:xmpp-sasl'&gt;&lt;not-authorized/&gt;&lt;text xml:lang='en'&gt;Nodeprep failed&lt;/text&gt;&lt;/failure&gt;&quot;&gt;&gt; 2022-11-28 05:35:44.311953+00:00 [debug] Running hook c2s_handle_send: mod_push:c2s_stanza/3 2022-11-28 05:35:44.314781+00:00 [debug] Running hook c2s_terminated: mod_pubsub:on_user_offline/2 2022-11-28 05:35:44.315136+00:00 [debug] Running hook c2s_terminated: ejabberd_c2s:process_terminated/2 2022-11-28 05:35:44.315395+00:00 [notice] (tls|&lt;0.974.0&gt;) Send XML on stream = &lt;&lt;&quot;&lt;/stream:stream&gt;&quot;&gt;&gt; </code></pre> <p>and in the client logs:</p> <pre><code>DMyODMwZg==) XML::Stream: Node: _handle_close: sid(6607014926489030516) sax(XML::Stream::Parser=HASH(0x55e0c0b3e700)) tag(challenge) XML::Stream: Node: _handle_close: check( 0 ) XML::Stream: Node: _handle_close: check2( -1 ) XML::Stream: Send: (&lt;response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'&gt;&lt;/response&gt;) XML::Stream: Process: block(0) XMPP::Conn: AuthSASL: haven't authed yet... let's wait. XMPP::Conn: Process: timeout(1) XML::Stream: Read: buff(&lt;failure xmlns='urn:ietf:params:xml:ns:xmpp-sasl'&gt;&lt;not-authorized/&gt;&lt;text xml:lang='en'&gt;Nodeprep failed&lt;/text&gt;&lt;/failure&gt;) XMPP::Conn: AuthSASL: Authentication failed. ERROR: Authorization failed: error - not-authorized </code></pre> <p>I cant find anywhere what Nodeprep failed means? Would appreciate some help thanks.</p>
[ { "answer_id": 74599239, "author": "Rathish Kumar B", "author_id": 2156784, "author_profile": "https://Stackoverflow.com/users/2156784", "pm_score": 3, "selected": true, "text": "SELECT DATE(creation_date), COUNT(*) FROM bigquery-public-data.stackoverflow.post_links\nGROUP BY DATE(creation_date)\nORDER BY 1 DESC LIMIT 10\n SELECT DATE(creation_date) AS crdate, COUNT(*) FROM bigquery-public-data.stackoverflow.post_links\nGROUP BY crdate\nORDER BY crdate DESC LIMIT 10\n" }, { "answer_id": 74600955, "author": "kiran mathew", "author_id": 17258510, "author_profile": "https://Stackoverflow.com/users/17258510", "pm_score": 1, "selected": false, "text": "date(creation_date) functional output Example using ordinals: select date(creation_date) , count(*) from bigquery-public-data.stackoverflow.post_links\ngroup by 1 order by 1;\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597981", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20411673/" ]
74,597,991
<p><code>constexpr</code> might run functions at compilation time. Is there a way to force it to compilation time only?</p> <p>Sample code:</p> <pre><code>constexpr int BUILD(int i) { static_assert(0 == i); i++; return i; } enum Events { FIRST = BUILD(0) }; </code></pre> <p>The compilation error:<br /> <code>Error[Pe028]: expression must have a constant value</code></p> <p><strong>[Edit]</strong> Another example to explain the rationale:</p> <pre><code>constexpr int BUILD(int a, int b, int c, int d) { static_assert(a &lt; b); static_assert(b &lt; c); static_assert(c &lt; d); static_assert(d &lt; 10); return a+b+c+d; } enum Events { FIRST = BUILD(0, 4, 6, 9), //numbers are defined manually SECOND = BUILD(2, 3, 7, 8), THIRD = BUILD(0, 1, 2, 3), }; </code></pre>
[ { "answer_id": 74598274, "author": "Enlico", "author_id": 5825294, "author_profile": "https://Stackoverflow.com/users/5825294", "pm_score": 1, "selected": false, "text": "constexpr constexpr constexpr int i = 3;\nf(3)\n f void f(int x)\n x constexpr x static_assert static constexpr bool int BUILD(int i)\n{\n /*runtime*/assert(0 == i);\n i++;\n return i;\n}\n template<int i>\nstruct BUILD_impl {\n static_assert(0 == i);\n constexpr static bool value = i + 1;\n};\ntemplate<int i>\nconstexpr bool BUILD = BUILD_impl<i>::value;\n BUILD<0> BUILD(0)" }, { "answer_id": 74598322, "author": "463035818_is_not_a_number", "author_id": 4117728, "author_profile": "https://Stackoverflow.com/users/4117728", "pm_score": 2, "selected": false, "text": "i 0 template <int i, bool = true>\nstruct BUILD;\n\ntemplate <int i>\nstruct BUILD<i, i==0> { static constexpr int value = 0;};\n\nenum Events\n{\n FIRST = BUILD<0>::value,\n ERROR = BUILD<1>::value\n};\n FIRST ERROR <source>:15:23: error: incomplete type 'BUILD<1>' used in nested name specifier\n 15 | ERROR = BUILD<1>::value\n | ^~~~~\n" }, { "answer_id": 74598358, "author": "Rulle", "author_id": 1008794, "author_profile": "https://Stackoverflow.com/users/1008794", "pm_score": 0, "selected": false, "text": "assert static_assert constexpr my_constexpr_assert void my_assert_fail() {} // NOT Constexpr\n#define my_constexpr_assert(expr) if (!(expr)) {my_assert_fail();}\n constexpr int BUILD(int a, int b, int c, int d) {\n my_constexpr_assert(a < b);\n my_constexpr_assert(b < c);\n my_constexpr_assert(c < d);\n my_constexpr_assert(d < 10);\n return a+b+c+d;\n}\n\nenum Events {\n FIRST = BUILD(0, 4, 6, 9),\n SECOND = BUILD(2, 3, 7, 8),\n THIRD = BUILD(0, 1, 2, 3)\n};\n THIRD = BUILD(0, 1, 0, 3) main.cpp:2:63: error: call to non-‘constexpr’ function ‘void my_assert_fail()’\n 2 | #define my_constexpr_assert(expr) if (!(expr)) {my_assert_fail();}\n | ~~~~~~~~~~~~~~^~\nmain.cpp:6:3: note: in expansion of macro ‘my_constexpr_assert’\n 6 | my_constexpr_assert(b < c);\n b < c my_constexpr_assert assert <cassert> abort(); my_assert_fail" }, { "answer_id": 74598389, "author": "fabian", "author_id": 2991525, "author_profile": "https://Stackoverflow.com/users/2991525", "pm_score": 1, "selected": false, "text": "static_assert namespace Impl\n{\n\nconstexpr int CalculateBuild(int a, int b, int c, int d)\n{\n return a+b+c+d;\n}\n\ntemplate<int a, int b, int c, int d>\nstruct BuildHelper\n{\n static constexpr int value = CalculateBuild(a,b,c,d);\n\n static_assert(a < b, \"a < b violated\");\n static_assert(b < c, \"b < c violated\");\n static_assert(c < d, \"c < d violated\");\n static_assert(d < 10, \"d < 10 violated\");\n};\n\ntemplate<int a, int b, int c, int d>\nconstexpr int BUILD = BuildHelper<a,b,c,d>::value;\n\n}\n\nusing Impl::BUILD;\n\nenum Events\n{\n FIRST = BUILD<0, 4, 6, 9>, //numbers are defined manually\n SECOND = BUILD<2, 3, 7, 8>,\n THIRD = BUILD<0, 1, 2, 3>,\n\n // ERROR = BUILD<1, 2, 3, 10>\n\n // uncommenting the above yields something like\n //\n // static_assert failed: 'd < 10 violated'\n //\n // along with some information about which template specialization is responsible\n};\n\n" }, { "answer_id": 74598926, "author": "Bob__", "author_id": 4944425, "author_profile": "https://Stackoverflow.com/users/4944425", "pm_score": 1, "selected": false, "text": "throw consteval int BUILD(int a, int b, int c, int d)\n{\n if ( not (a < b) ) throw \"a should be less than b\"; \n if ( not (b < c) ) throw \"b should be less than c\"; \n if ( not (c < d) ) throw \"c should be less than d\"; \n if ( not (d < 10) ) throw \"d should be less than 10\"; \n\n return a+b+c+d;\n}\n\nenum Events\n{\n FIRST = BUILD(0, 4, 6, 9), \n SECOND = BUILD(2, 3, 7, 8),\n THIRD = BUILD(0, 1, 2, 3),\n// ERROR_A = BUILD(5, 4, 6, 9),\n// ERROR_B = BUILD(2, 7, 3, 8),\n// ERROR_C = BUILD(0, 1, 4, 3),\n// ERROR_D = BUILD(0, 1, 2, 13)\n};\n <source>:18:15: error: expression is not an integral constant expression\n ERROR_C = BUILD(0, 1, 4, 3),\n ^~~~~~~~~~~~~~~~~\n<source>:5:24: note: subexpression not valid in a constant expression\n if ( not (c < d) ) throw \"c should be less than d\"; \n ^\n<source>:18:15: note: in call to 'BUILD(0, 1, 4, 3)'\n ERROR_C = BUILD(0, 1, 4, 3),\n ^\n1 error generated.\n constexpr" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74597991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1591924/" ]
74,598,000
<p>I need a SQL query which will fetch me the list of products which has different values for a same id and product is of table A and Id and values are of table B and both the tables can be joined by column name prod_id</p> <p><a href="https://i.stack.imgur.com/m4Hgg.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/m4Hgg.jpg" alt="enter image description here" /></a></p> <p>Output I want:</p> <ul> <li>List item</li> </ul> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>product</th> </tr> </thead> <tbody> <tr> <td>abc</td> </tr> </tbody> </table> </div> <p>So in output I want only the product abc because it has different values for their respective id and I don’t need xyz because it has same values for their respective id</p> <p>I tried but I’m not getting what I want as mentioned above</p>
[ { "answer_id": 74598047, "author": "juergen d", "author_id": 575376, "author_profile": "https://Stackoverflow.com/users/575376", "pm_score": 1, "selected": false, "text": "select distinct product\nfrom your_table\ngroup by product, id\nhaving count(distinct values) > 1\n" }, { "answer_id": 74606572, "author": "d r", "author_id": 19023353, "author_profile": "https://Stackoverflow.com/users/19023353", "pm_score": 0, "selected": false, "text": "WITH\n tbl_a AS\n (\n Select 1 \"PROD_ID\", 'abc' \"PRODUCT\" From DUAL Union All\n Select 9 \"PROD_ID\", 'xyz' \"PRODUCT\" From DUAL\n ),\n tbl_b AS\n (\n Select 1 \"PROD_ID\", '10' \"ID\", 345678 \"VALS\" From DUAL Union All\n Select 1 \"PROD_ID\", '10' \"ID\", 345678 \"VALS\" From DUAL Union All\n Select 1 \"PROD_ID\", '14' \"ID\", 458292 \"VALS\" From DUAL Union All\n Select 1 \"PROD_ID\", '13' \"ID\", 629351 \"VALS\" From DUAL Union All\n Select 1 \"PROD_ID\", '13' \"ID\", 629354 \"VALS\" From DUAL Union All\n \n Select 9 \"PROD_ID\", '10' \"ID\", 375281 \"VALS\" From DUAL Union All\n Select 9 \"PROD_ID\", '10' \"ID\", 375281 \"VALS\" From DUAL Union All\n Select 9 \"PROD_ID\", '12' \"ID\", 826292 \"VALS\" From DUAL Union All\n Select 9 \"PROD_ID\", '12' \"ID\", 826292 \"VALS\" From DUAL \n )\n Select\n a.PRODUCT\nFrom\n tbl_a a\nInner Join\n tbl_b b ON(b.PROD_ID = a.PROD_ID)\nGroup By\n a.PRODUCT, b.ID\nHaving\n Count(DISTINCT b.VALS) > 1\n--\n-- Result:\n-- PRODUCT\n-- -------\n-- abc \n\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74598000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20581146/" ]
74,598,005
<p>I'm new with Dataframe. I would like to kwon how (if possible) can I merge 2 Dataframes with multiple match For example</p> <pre><code>[df1] date ZipCode Weather 2022-11-25 00:00:00 123456 34 2022-11-25 00:00:15 123456 35 2022-11-25 00:00:30 123456 36 </code></pre> <pre><code>[df2] date ZipCode host 2022-11-25 00:00:00 123456 host1 2022-11-25 00:00:00 123456 host2 2022-11-25 00:00:00 123456 host3 2022-11-25 00:00:15 123456 host1 2022-11-25 00:00:30 123456 host2 2022-11-25 00:00:30 123456 host3 </code></pre> <p>Expected results:</p> <pre><code>date ZipCode host Weather 2022-11-25 00:00:00 123456 host1 34 2022-11-25 00:00:00 123456 host2 34 2022-11-25 00:00:00 123456 host3 34 2022-11-25 00:00:15 123456 host1 35 2022-11-25 00:00:30 123456 host2 36 2022-11-25 00:00:30 123456 host3 36 </code></pre> <p>My objetive is assign weather measures to each host. I have weather measurements every 15 minutes for one ZipCode (One line) By the other hand, I have several host KPIs for one time and one ZipCode (multiples lines)</p> <p>Can I perfomr this activity with Dataframes?</p> <p>Thanks in advance!</p>
[ { "answer_id": 74598047, "author": "juergen d", "author_id": 575376, "author_profile": "https://Stackoverflow.com/users/575376", "pm_score": 1, "selected": false, "text": "select distinct product\nfrom your_table\ngroup by product, id\nhaving count(distinct values) > 1\n" }, { "answer_id": 74606572, "author": "d r", "author_id": 19023353, "author_profile": "https://Stackoverflow.com/users/19023353", "pm_score": 0, "selected": false, "text": "WITH\n tbl_a AS\n (\n Select 1 \"PROD_ID\", 'abc' \"PRODUCT\" From DUAL Union All\n Select 9 \"PROD_ID\", 'xyz' \"PRODUCT\" From DUAL\n ),\n tbl_b AS\n (\n Select 1 \"PROD_ID\", '10' \"ID\", 345678 \"VALS\" From DUAL Union All\n Select 1 \"PROD_ID\", '10' \"ID\", 345678 \"VALS\" From DUAL Union All\n Select 1 \"PROD_ID\", '14' \"ID\", 458292 \"VALS\" From DUAL Union All\n Select 1 \"PROD_ID\", '13' \"ID\", 629351 \"VALS\" From DUAL Union All\n Select 1 \"PROD_ID\", '13' \"ID\", 629354 \"VALS\" From DUAL Union All\n \n Select 9 \"PROD_ID\", '10' \"ID\", 375281 \"VALS\" From DUAL Union All\n Select 9 \"PROD_ID\", '10' \"ID\", 375281 \"VALS\" From DUAL Union All\n Select 9 \"PROD_ID\", '12' \"ID\", 826292 \"VALS\" From DUAL Union All\n Select 9 \"PROD_ID\", '12' \"ID\", 826292 \"VALS\" From DUAL \n )\n Select\n a.PRODUCT\nFrom\n tbl_a a\nInner Join\n tbl_b b ON(b.PROD_ID = a.PROD_ID)\nGroup By\n a.PRODUCT, b.ID\nHaving\n Count(DISTINCT b.VALS) > 1\n--\n-- Result:\n-- PRODUCT\n-- -------\n-- abc \n\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74598005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4210317/" ]
74,598,017
<pre class="lang-js prettyprint-override"><code>rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /{document=**} { allow read, write: if true; } } } </code></pre> <p>These are my firestore rules. As you can see, I am allowing read/write access to everyone. However, when I run the app, I get an error &quot;<em><strong>[cloud_firestore/permission-denied] The caller does not have permission to execute the specified operation.</strong></em>&quot;</p> <p>I don't understand. Which part should I check?</p>
[ { "answer_id": 74598047, "author": "juergen d", "author_id": 575376, "author_profile": "https://Stackoverflow.com/users/575376", "pm_score": 1, "selected": false, "text": "select distinct product\nfrom your_table\ngroup by product, id\nhaving count(distinct values) > 1\n" }, { "answer_id": 74606572, "author": "d r", "author_id": 19023353, "author_profile": "https://Stackoverflow.com/users/19023353", "pm_score": 0, "selected": false, "text": "WITH\n tbl_a AS\n (\n Select 1 \"PROD_ID\", 'abc' \"PRODUCT\" From DUAL Union All\n Select 9 \"PROD_ID\", 'xyz' \"PRODUCT\" From DUAL\n ),\n tbl_b AS\n (\n Select 1 \"PROD_ID\", '10' \"ID\", 345678 \"VALS\" From DUAL Union All\n Select 1 \"PROD_ID\", '10' \"ID\", 345678 \"VALS\" From DUAL Union All\n Select 1 \"PROD_ID\", '14' \"ID\", 458292 \"VALS\" From DUAL Union All\n Select 1 \"PROD_ID\", '13' \"ID\", 629351 \"VALS\" From DUAL Union All\n Select 1 \"PROD_ID\", '13' \"ID\", 629354 \"VALS\" From DUAL Union All\n \n Select 9 \"PROD_ID\", '10' \"ID\", 375281 \"VALS\" From DUAL Union All\n Select 9 \"PROD_ID\", '10' \"ID\", 375281 \"VALS\" From DUAL Union All\n Select 9 \"PROD_ID\", '12' \"ID\", 826292 \"VALS\" From DUAL Union All\n Select 9 \"PROD_ID\", '12' \"ID\", 826292 \"VALS\" From DUAL \n )\n Select\n a.PRODUCT\nFrom\n tbl_a a\nInner Join\n tbl_b b ON(b.PROD_ID = a.PROD_ID)\nGroup By\n a.PRODUCT, b.ID\nHaving\n Count(DISTINCT b.VALS) > 1\n--\n-- Result:\n-- PRODUCT\n-- -------\n-- abc \n\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74598017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10518324/" ]
74,598,076
<p>I want to pass encrypted ids of object in Response, therefore I used AES. now I want accept the encrypted pk which is a path 'xx/xxxx/xxxx', and decrypt it first thing in the view.</p> <p>`</p> <pre><code>import base64, re from Crypto.Cipher import AES from Crypto import Random from django.conf import settings import codecs # make utf8mb4 recognizable. codecs.register(lambda name: codecs.lookup('utf8') if name == 'utf8mb4' else None) class AESCipher: def __init__(self, key, blk_sz): self.key = key self.blk_sz = blk_sz def encrypt( self, raw ): # raw is the main value if raw is None or len(raw) == 0: raise NameError(&quot;No value given to encrypt&quot;) raw = raw + '\0' * (self.blk_sz - len(raw) % self.blk_sz) raw = raw.encode('utf8mb4') # Initialization vector to avoid same encrypt for same strings. iv = Random.new().read( AES.block_size ) cipher = AES.new( self.key.encode('utf8mb4'), AES.MODE_CFB, iv ) return base64.b64encode( iv + cipher.encrypt( raw ) ).decode('utf8mb4') def decrypt( self, enc ): # enc is the encrypted value if enc is None or len(enc) == 0: raise NameError(&quot;No value given to decrypt&quot;) enc = base64.b64decode(enc) iv = enc[:16] # AES.MODE_CFB that allows bigger length or latin values cipher = AES.new(self.key.encode('utf8mb4'), AES.MODE_CFB, iv ) return re.sub(b'\x00*$', b'', cipher.decrypt( enc[16:])).decode('utf8mb4') </code></pre> <p>`</p> <p>I tried to accept path:pk in the url and decrypt that pk in the get_queryset() but the response of any function is that the object not found `</p> <pre><code>path('&lt;path:pk&gt;/detail/',ProductDetailUpdateDelete.as_view(),name='product-detail'), </code></pre> <p><code>and override the get_queryset</code></p> <pre><code> </code></pre> <p>class ProductDetailUpdateDelete(generics.RetrieveUpdateDestroyAPIView):</p> <pre><code>serializer_class=ProductSerializer def get_queryset(self): pk = aes.decrypt(str(self.kwargs['pk'])) product=Product.objects.filter(pk=int(pk)) return product </code></pre> <pre><code> </code></pre> <p>`</p> <p>this returns the object and I can access all the information, but all the operations (GET,PUT,DEL) return not found. so how can I pass the object id to the functions and I want a way to decrypt the pk beofre invoking any function in order to pass pk without overriding every function</p>
[ { "answer_id": 74598690, "author": "Uzzal H. Mohammad", "author_id": 16020090, "author_profile": "https://Stackoverflow.com/users/16020090", "pm_score": 1, "selected": false, "text": "def get_object(self):\n pk = aes.decrypt(str(self.kwargs['pk']))\n product=Product.objects.filter(pk=int(pk))\n return product.first()\n" }, { "answer_id": 74614081, "author": "Omar Nasser", "author_id": 10412586, "author_profile": "https://Stackoverflow.com/users/10412586", "pm_score": 0, "selected": false, "text": "def get_object(self):\n pk = aes.decrypt(str(self.kwargs['pk']))\n product=Product.objects.filter(pk=int(pk))\n return product\n def get_object(self):\n pk = aes.decrypt(str(self.kwargs['pk']))\n product=Product.objects.filter(pk=int(pk))\n return product[0]\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74598076", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10412586/" ]
74,598,092
<p>Hello everyone i have some problem with Encoding.. i want convert utf-16 to utf-8 i founded many code but didn't work.. I hope help me.. Thanks</p> <p>This text =&gt;</p> <p>'\x04\x1a\x040\x04@\x04B\x040\x00 \x00*\x003\x003\x000\x001\x00:\x00 \x000\x001\x00.\x001\x001\x00.\x002\x000\x002\x002\x00 \x001\x004\x00:\x001\x000\x00,\x00 \x04?\x04&gt;\x04?\x04&gt;\x04;\x04=\x045\x04=\x048\x045\x00 \x003\x003\x00.\x003\x003\x00 \x00T\x00J\x00S\x00.\x00 \x00 \x04\x14\x04&gt;\x04A\x04B\x04C\x04?\x04=\x04&gt;\x00 \x003\x002\x002\x003'</p> <p>#I tryed this</p> <pre><code> string v = Regex.Unescape(text); </code></pre> <h1>get result like</h1> <p>♦→♦0♦@♦B♦0 *3301: 01.11.2022 14:10, ♦?♦&gt;♦?♦&gt;♦;♦=♦5♦=♦8♦5 33.33 TJS. ♦¶♦&gt;♦A♦B♦C♦?♦=♦&gt; 3223</p> <p>and continue</p> <pre><code> public static string Utf16ToUtf8(string utf16String) { // Get UTF16 bytes and convert UTF16 bytes to UTF8 bytes byte[] utf16Bytes = Encoding.Unicode.GetBytes(utf16String); byte[] utf8Bytes = Encoding.Convert(Encoding.Unicode, Encoding.UTF8, utf16Bytes); // Return UTF8 bytes as ANSI string return Encoding.Default.GetString(utf8Bytes); } </code></pre> <p>don't worked</p> <p>I need result like this</p> <p>Карта *4411: 01.11.2022 14:10, пополнение 33.33 TJS. Доступно 3223</p>
[ { "answer_id": 74598575, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": true, "text": "\\x \\\\ using System.Text;\n\nclass Program\n{\n static void Main()\n {\n string logText = @\"\\x04\\x1a\\x040\\x04@\\x04B\\x040\\x00 \\x00*\\x003\\x003\\x000\\x001\\x00:\\x00 \\x000\\x001\\x00.\\x001\\x001\\x00.\\x002\\x000\\x002\\x002\\x00 \\x001\\x004\\x00:\\x001\\x000\\x00,\\x00 \\x04?\\x04>\\x04?\\x04>\\x04;\\x04=\\x045\\x04=\\x048\\x045\\x00 \\x003\\x003\\x00.\\x003\\x003\\x00 \\x00T\\x00J\\x00S\\x00.\\x00 \\x00 \\x04\\x14\\x04>\\x04A\\x04B\\x04C\\x04?\\x04=\\x04>\\x00 \\x003\\x002\\x002\\x003\";\n\n byte[] utf16 = DecodeLogText(logText);\n string text = Encoding.BigEndianUnicode.GetString(utf16);\n Console.WriteLine(text);\n }\n\n static byte[] DecodeLogText(string logText)\n {\n List<byte> bytes = new List<byte>();\n for (int i = 0; i < logText.Length; i++)\n {\n if (logText[i] == '\\\\')\n {\n if (i == logText.Length - 1)\n {\n throw new Exception(\"Trailing backslash\");\n }\n switch (logText[i + 1])\n {\n case 'x':\n if (i >= logText.Length - 3)\n {\n throw new Exception(\"Not enough data for \\\\x escape sequence\");\n }\n // This is horribly inefficient, but never mind.\n bytes.Add(Convert.ToByte(logText.Substring(i + 2, 2), 16));\n // Consume the x and hex\n i += 3;\n break;\n case '\\\\':\n bytes.Add((byte) '\\\\');\n // Consume the extra backslash\n i++;\n break;\n // TODO: Any other escape sequences?\n default:\n throw new Exception(\"Unknown escape sequence\");\n }\n }\n else\n {\n bytes.Add((byte) logText[i]);\n }\n }\n return bytes.ToArray();\n }\n}\n" }, { "answer_id": 74598823, "author": "Miles Morales", "author_id": 20621511, "author_profile": "https://Stackoverflow.com/users/20621511", "pm_score": -1, "selected": false, "text": "string reg = Regex.Unescape(text2);\n\nbyte[] ascii = Encoding.BigEndianUnicode.GetBytes(reg);\nbyte[] utf8 = Encoding.Convert(Encoding.BigEndianUnicode, Encoding.UTF8, ascii);\n\nConsole.WriteLine(Encoding.BigEndianUnicode.GetString(utf8));\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74598092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20621511/" ]
74,598,113
<p>I got errors when updating my flutter version to 3.3.8. All of textbutton class has these errors. Actually, I just need to use elevatedButton but Im curious what is the correct syntax if we want to use textbutton?</p> <p><a href="https://i.stack.imgur.com/63zS5.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/63zS5.jpg" alt="enter image description here" /></a></p>
[ { "answer_id": 74598575, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": true, "text": "\\x \\\\ using System.Text;\n\nclass Program\n{\n static void Main()\n {\n string logText = @\"\\x04\\x1a\\x040\\x04@\\x04B\\x040\\x00 \\x00*\\x003\\x003\\x000\\x001\\x00:\\x00 \\x000\\x001\\x00.\\x001\\x001\\x00.\\x002\\x000\\x002\\x002\\x00 \\x001\\x004\\x00:\\x001\\x000\\x00,\\x00 \\x04?\\x04>\\x04?\\x04>\\x04;\\x04=\\x045\\x04=\\x048\\x045\\x00 \\x003\\x003\\x00.\\x003\\x003\\x00 \\x00T\\x00J\\x00S\\x00.\\x00 \\x00 \\x04\\x14\\x04>\\x04A\\x04B\\x04C\\x04?\\x04=\\x04>\\x00 \\x003\\x002\\x002\\x003\";\n\n byte[] utf16 = DecodeLogText(logText);\n string text = Encoding.BigEndianUnicode.GetString(utf16);\n Console.WriteLine(text);\n }\n\n static byte[] DecodeLogText(string logText)\n {\n List<byte> bytes = new List<byte>();\n for (int i = 0; i < logText.Length; i++)\n {\n if (logText[i] == '\\\\')\n {\n if (i == logText.Length - 1)\n {\n throw new Exception(\"Trailing backslash\");\n }\n switch (logText[i + 1])\n {\n case 'x':\n if (i >= logText.Length - 3)\n {\n throw new Exception(\"Not enough data for \\\\x escape sequence\");\n }\n // This is horribly inefficient, but never mind.\n bytes.Add(Convert.ToByte(logText.Substring(i + 2, 2), 16));\n // Consume the x and hex\n i += 3;\n break;\n case '\\\\':\n bytes.Add((byte) '\\\\');\n // Consume the extra backslash\n i++;\n break;\n // TODO: Any other escape sequences?\n default:\n throw new Exception(\"Unknown escape sequence\");\n }\n }\n else\n {\n bytes.Add((byte) logText[i]);\n }\n }\n return bytes.ToArray();\n }\n}\n" }, { "answer_id": 74598823, "author": "Miles Morales", "author_id": 20621511, "author_profile": "https://Stackoverflow.com/users/20621511", "pm_score": -1, "selected": false, "text": "string reg = Regex.Unescape(text2);\n\nbyte[] ascii = Encoding.BigEndianUnicode.GetBytes(reg);\nbyte[] utf8 = Encoding.Convert(Encoding.BigEndianUnicode, Encoding.UTF8, ascii);\n\nConsole.WriteLine(Encoding.BigEndianUnicode.GetString(utf8));\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74598113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16363643/" ]
74,598,144
<p>So I was making project and when I try to get the parameter from class parent its say <code>NaN</code> while the other is <code>true</code>. Here the code:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>class transportasi {//class parent constructor(nama,roda,pintu){ this.nama = nama this.roda = roda this.pintu = pintu } } class mobil extends transportasi{//Class Children constructor(roda,lampu){ super(roda)//the problem this.lampu = lampu } jmlahfeature(){ return this.lampu + this.roda } } const mobil1 = new mobil(2,4)//the problem //I cant fill the value of roda only lampu console.log("Hasil Perhitungan Feature mobil : " + mobil1.jmlahfeature())</code></pre> </div> </div> </p> <p>I want it so I can fill the value of parameter <code>roda</code>. So it doesn't say <code>NaN</code> in console.</p>
[ { "answer_id": 74598575, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": true, "text": "\\x \\\\ using System.Text;\n\nclass Program\n{\n static void Main()\n {\n string logText = @\"\\x04\\x1a\\x040\\x04@\\x04B\\x040\\x00 \\x00*\\x003\\x003\\x000\\x001\\x00:\\x00 \\x000\\x001\\x00.\\x001\\x001\\x00.\\x002\\x000\\x002\\x002\\x00 \\x001\\x004\\x00:\\x001\\x000\\x00,\\x00 \\x04?\\x04>\\x04?\\x04>\\x04;\\x04=\\x045\\x04=\\x048\\x045\\x00 \\x003\\x003\\x00.\\x003\\x003\\x00 \\x00T\\x00J\\x00S\\x00.\\x00 \\x00 \\x04\\x14\\x04>\\x04A\\x04B\\x04C\\x04?\\x04=\\x04>\\x00 \\x003\\x002\\x002\\x003\";\n\n byte[] utf16 = DecodeLogText(logText);\n string text = Encoding.BigEndianUnicode.GetString(utf16);\n Console.WriteLine(text);\n }\n\n static byte[] DecodeLogText(string logText)\n {\n List<byte> bytes = new List<byte>();\n for (int i = 0; i < logText.Length; i++)\n {\n if (logText[i] == '\\\\')\n {\n if (i == logText.Length - 1)\n {\n throw new Exception(\"Trailing backslash\");\n }\n switch (logText[i + 1])\n {\n case 'x':\n if (i >= logText.Length - 3)\n {\n throw new Exception(\"Not enough data for \\\\x escape sequence\");\n }\n // This is horribly inefficient, but never mind.\n bytes.Add(Convert.ToByte(logText.Substring(i + 2, 2), 16));\n // Consume the x and hex\n i += 3;\n break;\n case '\\\\':\n bytes.Add((byte) '\\\\');\n // Consume the extra backslash\n i++;\n break;\n // TODO: Any other escape sequences?\n default:\n throw new Exception(\"Unknown escape sequence\");\n }\n }\n else\n {\n bytes.Add((byte) logText[i]);\n }\n }\n return bytes.ToArray();\n }\n}\n" }, { "answer_id": 74598823, "author": "Miles Morales", "author_id": 20621511, "author_profile": "https://Stackoverflow.com/users/20621511", "pm_score": -1, "selected": false, "text": "string reg = Regex.Unescape(text2);\n\nbyte[] ascii = Encoding.BigEndianUnicode.GetBytes(reg);\nbyte[] utf8 = Encoding.Convert(Encoding.BigEndianUnicode, Encoding.UTF8, ascii);\n\nConsole.WriteLine(Encoding.BigEndianUnicode.GetString(utf8));\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74598144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20621576/" ]
74,598,156
<p>I need to read a single column from db table as a list of values. I tried to do that with following line of code:</p> <pre><code>ids_list = (pd.read_sql_query(q, db_internal.connection)).values.tolist() </code></pre> <p>when I use the <code>values.tolist()</code> it does what documentation says, that is turns the df into list of lists:</p> <pre><code>[['0x0043Fcb34e7470130fDe28198571DeE092c70Bd7'], ['0x00f93fBf00F97170B6cf295DC58888073CB5c2b8'], ['0x01FE650EF2f8e2982295489AE6aDc1413bF6011F'], ['0x0212133321479B183637e52942564162bCc37C1D']] </code></pre> <p>Because I am reading single column, I would like to transform it into list of values, not list of lists:</p> <pre><code> ['0x0043Fcb34e7470130fDe28198571DeE092c70Bd7', '0x00f93fBf00F97170B6cf295DC58888073CB5c2b8', '0x01FE650EF2f8e2982295489AE6aDc1413bF6011F', '0x0212133321479B183637e52942564162bCc37C1D'] </code></pre> <p>What would be a way to do that? I keep on finding solutions that are focused on list of lists</p>
[ { "answer_id": 74598188, "author": "cout", "author_id": 16204952, "author_profile": "https://Stackoverflow.com/users/16204952", "pm_score": 2, "selected": false, "text": "[i for i in ids_list[0]]\n" }, { "answer_id": 74598202, "author": "Prabhas Kumar", "author_id": 20603322, "author_profile": "https://Stackoverflow.com/users/20603322", "pm_score": 2, "selected": true, "text": "ids_list = list(i[0] for i in (pd.read_sql_query(q, db_internal.connection)).values.tolist())\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74598156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18366377/" ]
74,598,169
<p>In my app I have the following models:</p> <pre><code>class Category(BaseStampModel): cat_id = models.AutoField(primary_key=True, verbose_name='Cat Id') category = models.CharField(max_length=55, verbose_name='Category') class MasterList(BaseStampModel): master_list_id = models.AutoField(primary_key=True, verbose_name='Master List Id') mast_list_category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, verbose_name='Category') # Other fields ... </code></pre> <p>My BaseModel looks like this:</p> <pre><code>class BaseStampModel(models.Model): created_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='%(class)s_created', blank=True, null=True, on_delete=models.SET_NULL, verbose_name='Created by') created_on = models.DateTimeField(auto_now_add = True, null=True, blank=True) </code></pre> <p>With this I am able to display the model objects and create/update instances.</p> <p>In my view, when I want to retrieve the <code>verbose_name</code> from model &quot;<strong>Category</strong>&quot; using:</p> <pre><code>`model_fields = [(f.verbose_name, f.name) for f in Category._meta.get_fields()]` </code></pre> <p>I am getting the following error in my browser:</p> <blockquote> <p>AttributeError: 'ManyToOneRel' object has no attribute 'verbose_name'</p> </blockquote> <p>If I remove the the FK relationship from the field <code>mast_list_category</code> (make it a simple <code>CharField</code>) I don't get the error.</p> <p>Gone through <em>millions of pages</em>, but no solution yet.</p> <p>Any <strong>help</strong> is much appreciated.</p>
[ { "answer_id": 74598188, "author": "cout", "author_id": 16204952, "author_profile": "https://Stackoverflow.com/users/16204952", "pm_score": 2, "selected": false, "text": "[i for i in ids_list[0]]\n" }, { "answer_id": 74598202, "author": "Prabhas Kumar", "author_id": 20603322, "author_profile": "https://Stackoverflow.com/users/20603322", "pm_score": 2, "selected": true, "text": "ids_list = list(i[0] for i in (pd.read_sql_query(q, db_internal.connection)).values.tolist())\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74598169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18916973/" ]
74,598,190
<p>I'm doing this as a challenge for myself. My problem is that when I click on the button, the content pane appears plain even if the <code>JPanel</code> has components in it.</p> <p>I've tried adding the components on the frame but I get an error: &gt;Cannot read field &quot;parent&quot; because &quot;comp&quot; is null.</p> <p>I've tried other layout on <code>JFrame</code> and <code>JPanel</code> and still it didn't show.</p> <p>Here's the full code:</p> <pre class="lang-java prettyprint-override"><code>import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.DecimalFormat; public class test implements ActionListener{ public static void main(String [] args) { new test(); } static JPanel mainPanel, cubePanel; static JFrame frame; static Container container = new Container(); static JLabel calculatorFor; static JButton sphereButton, rightCylinderButton, rightConeButton, rectangularPrismButton, triangularPrismButton, cubeButton, squarePyramidButton, rectangularPyramidButton, ellipsoidButton, tetrahedronButton ,backToPreviousFrameButton; static Font font = new Font(null, Font.PLAIN, 30); static JLabel enterValueForEdge; static JTextField edgeTextField; static JTextArea surfaceAreaTextArea, surfaceAreaFormulaTextArea, surfaceAreaSolutionTextArea; static JButton calculateButton; static double edge; static DecimalFormat surfaceAreaDecimal; public test(){ frame = new JFrame(&quot;Calculating for Surface Area&quot;); calculatorFor = new JLabel(&quot;Calculator for the Surface Area of:&quot;); calculatorFor.setSize(600, 40); calculatorFor.setLocation(100, 50); calculatorFor.setFont(font); calculatorFor.setFocusable(false); sphereButton = new JButton(&quot;Sphere &quot;); sphereButton.setSize(400, 40); sphereButton.setLocation(100, 100); sphereButton.setFont(font); sphereButton.addActionListener(this); sphereButton.setFocusable(false); rightCylinderButton = new JButton(&quot;Right Cylinder&quot;); rightCylinderButton.setSize(400, 40); rightCylinderButton.setLocation(100, 150); rightCylinderButton.setFont(font); rightCylinderButton.addActionListener(this); rightCylinderButton.setFocusable(false); rightConeButton = new JButton(&quot;Right Cone&quot;); rightConeButton.setSize(400, 40); rightConeButton.setLocation(100, 200); rightConeButton.setFont(font); rightConeButton.addActionListener(this); rightConeButton.setFocusable(false); rectangularPrismButton = new JButton(&quot;Rectangular Prism&quot;); rectangularPrismButton.setSize(400, 40); rectangularPrismButton.setLocation(100, 250); rectangularPrismButton.setFont(font); rectangularPrismButton.addActionListener(this); rectangularPrismButton.setFocusable(false); triangularPrismButton = new JButton(&quot;Triangular Prism&quot;); triangularPrismButton.setSize(400, 40); triangularPrismButton.setLocation(100, 300); triangularPrismButton.setFont(font); triangularPrismButton.addActionListener(this); triangularPrismButton.setFocusable(false); cubeButton = new JButton(&quot;Cube&quot;); cubeButton.setSize(400, 40); cubeButton.setLocation(100, 350); cubeButton.setFont(font); cubeButton.addActionListener(this); cubeButton.setFocusable(false); squarePyramidButton = new JButton(&quot;Square Pyramid&quot;); squarePyramidButton.setSize(400, 40); squarePyramidButton.setLocation(100, 400); squarePyramidButton.setFont(font); squarePyramidButton.addActionListener(this); squarePyramidButton.setFocusable(false); rectangularPyramidButton = new JButton(&quot;Rectangular Pyramid&quot;); rectangularPyramidButton.setSize(400, 40); rectangularPyramidButton.setLocation(100, 450); rectangularPyramidButton.setFont(font); rectangularPyramidButton.addActionListener(this); rectangularPyramidButton.setFocusable(false); ellipsoidButton = new JButton(&quot;Ellipsoid&quot;); ellipsoidButton.setSize(400, 40); ellipsoidButton.setLocation(100, 500); ellipsoidButton.setFont(font); ellipsoidButton.addActionListener(this); ellipsoidButton.setFocusable(false); tetrahedronButton = new JButton(&quot;Tetrahedron&quot;); tetrahedronButton.setSize(400, 40); tetrahedronButton.setLocation(100, 550); tetrahedronButton.setFont(font); tetrahedronButton.addActionListener(this); tetrahedronButton.setFocusable(false); backToPreviousFrameButton = new JButton(&quot;Back&quot;); backToPreviousFrameButton.setSize(100, 40); backToPreviousFrameButton.setLocation(900, 600); backToPreviousFrameButton.setFont(font); backToPreviousFrameButton.addActionListener(this); backToPreviousFrameButton.setFocusable(false); mainPanel = new JPanel(); mainPanel.setBounds(0, 0, 1080, 720); mainPanel.setLayout(null); mainPanel.setBackground(Color.decode(&quot;#FAF7FC&quot;)); mainPanel.add(calculatorFor); mainPanel.add(sphereButton); mainPanel.add(rightCylinderButton); mainPanel.add(rightConeButton); mainPanel.add(rectangularPrismButton); mainPanel.add(triangularPrismButton); mainPanel.add(cubeButton); mainPanel.add(squarePyramidButton); mainPanel.add(rectangularPyramidButton); mainPanel.add(ellipsoidButton); mainPanel.add(tetrahedronButton); mainPanel.add(backToPreviousFrameButton); frame.getContentPane().add(mainPanel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setBackground(Color.decode(&quot;#FAF7FC&quot;)); frame.setLayout(new BorderLayout()); frame.setSize(1080,720); frame.setResizable(false); frame.setVisible(true); frame.setLocationRelativeTo(null); } public void cubePanel(){ enterValueForEdge = new JLabel(&quot;Enter Edge:&quot;); enterValueForEdge.setSize(200, 40); enterValueForEdge.setLocation(100, 50); enterValueForEdge.setFont(font); enterValueForEdge.setFocusable(false); edgeTextField = new JTextField(); edgeTextField.setSize(400, 40); edgeTextField.setLocation(300, 50); edgeTextField.setFont(font); calculateButton = new JButton(&quot;Calculate&quot;); calculateButton.setSize(200, 40); calculateButton.setLocation(100, 100); calculateButton.setFont(font); calculateButton.addActionListener(this); calculateButton.setFocusable(false); surfaceAreaFormulaTextArea = new JTextArea(&quot;SA = 6a²&quot;); surfaceAreaFormulaTextArea.setSize(400, 40); surfaceAreaFormulaTextArea.setLocation(100, 150); surfaceAreaFormulaTextArea.setFont(font); surfaceAreaFormulaTextArea.setEditable(false); surfaceAreaTextArea = new JTextArea(&quot;SA: &quot;); surfaceAreaTextArea.setSize(500, 40); surfaceAreaTextArea.setLocation(100, 200); surfaceAreaTextArea.setFont(font); surfaceAreaTextArea.setEditable(false); surfaceAreaSolutionTextArea = new JTextArea(); surfaceAreaSolutionTextArea.setSize(900, 80); surfaceAreaSolutionTextArea.setLocation(100, 250); surfaceAreaSolutionTextArea.setFont(font); surfaceAreaSolutionTextArea.setEditable(false); surfaceAreaSolutionTextArea.setLineWrap(true); backToPreviousFrameButton = new JButton(&quot;Back&quot;); backToPreviousFrameButton.setSize(100, 40); backToPreviousFrameButton.setLocation(900, 600); backToPreviousFrameButton.setFont(font); backToPreviousFrameButton.addActionListener(this); backToPreviousFrameButton.setFocusable(false); cubePanel = new JPanel(); cubePanel.setBounds(0, 0, 1080, 720); cubePanel.setLayout(null); cubePanel.setBackground(Color.decode(&quot;#FAF7FC&quot;)); container = new Container(); cubePanel.add(enterValueForEdge); cubePanel.add(edgeTextField); cubePanel.add(calculateButton); cubePanel.add(surfaceAreaFormulaTextArea); cubePanel.add(surfaceAreaTextArea); cubePanel.add(surfaceAreaSolutionTextArea); cubePanel.add(backToPreviousFrameButton); container.add(cubePanel); container.setLayout(null); container.setBackground(Color.decode(&quot;#FAF7FH&quot;)); } @Override public void actionPerformed(ActionEvent e) { if(e.getSource() == sphereButton){ new sphereFrame(); frame.dispose(); } if(e.getSource() == rightCylinderButton){ new rightCylinderFrame(); frame.dispose(); } if(e.getSource() == rightConeButton){ new rightConeFrame(); frame.dispose(); } if(e.getSource() == rectangularPrismButton){ new rectangularPrismFrame(); frame.dispose(); } if(e.getSource() == triangularPrismButton){ new triangularPrismFrame(); frame.dispose(); } if(e.getSource() == cubeButton){ frame.getContentPane().removeAll(); frame.add(cubePanel); frame.repaint(); frame.revalidate(); System.out.println(&quot;Remove&quot;); frame.getContentPane().add(container); } } </code></pre>
[ { "answer_id": 74598475, "author": "vimlesh kumar pandey", "author_id": 20613235, "author_profile": "https://Stackoverflow.com/users/20613235", "pm_score": -1, "selected": false, "text": "import javax.swing.*;\nimport java.awt.*;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.text.DecimalFormat;\n\npublic class Test2 implements ActionListener {\n\n public static void main(String[] args) {\n new Test2();\n }\n\n static JPanel mainPanel, cubePanel;\n static JFrame frame;\n static Container container = new Container();\n static JLabel calculatorFor;\n static JButton sphereButton, rightCylinderButton, rightConeButton, rectangularPrismButton, triangularPrismButton,\n cubeButton, squarePyramidButton, rectangularPyramidButton, ellipsoidButton, tetrahedronButton, backToPreviousFrameButton;\n static Font font = new Font(null, Font.PLAIN, 30);\n static JLabel enterValueForEdge;\n static JTextField edgeTextField;\n static JTextArea surfaceAreaTextArea, surfaceAreaFormulaTextArea, surfaceAreaSolutionTextArea;\n static JButton calculateButton;\n static double edge;\n static DecimalFormat surfaceAreaDecimal;\n\n public Test2() {\n frame = new JFrame(\"Calculating for Surface Area\");\n\n calculatorFor = new JLabel(\"Calculator for the Surface Area of:\");\n calculatorFor.setSize(600, 40);\n calculatorFor.setLocation(100, 50);\n calculatorFor.setFont(font);\n calculatorFor.setFocusable(false);\n\n sphereButton = new JButton(\"Sphere \");\n sphereButton.setSize(400, 40);\n sphereButton.setLocation(100, 100);\n sphereButton.setFont(font);\n sphereButton.addActionListener(this);\n sphereButton.setFocusable(false);\n\n rightCylinderButton = new JButton(\"Right Cylinder\");\n rightCylinderButton.setSize(400, 40);\n rightCylinderButton.setLocation(100, 150);\n rightCylinderButton.setFont(font);\n rightCylinderButton.addActionListener(this);\n rightCylinderButton.setFocusable(false);\n\n rightConeButton = new JButton(\"Right Cone\");\n rightConeButton.setSize(400, 40);\n rightConeButton.setLocation(100, 200);\n rightConeButton.setFont(font);\n rightConeButton.addActionListener(this);\n rightConeButton.setFocusable(false);\n\n rectangularPrismButton = new JButton(\"Rectangular Prism\");\n rectangularPrismButton.setSize(400, 40);\n rectangularPrismButton.setLocation(100, 250);\n rectangularPrismButton.setFont(font);\n rectangularPrismButton.addActionListener(this);\n rectangularPrismButton.setFocusable(false);\n\n triangularPrismButton = new JButton(\"Triangular Prism\");\n triangularPrismButton.setSize(400, 40);\n triangularPrismButton.setLocation(100, 300);\n triangularPrismButton.setFont(font);\n triangularPrismButton.addActionListener(this);\n triangularPrismButton.setFocusable(false);\n\n cubeButton = new JButton(\"Cube\");\n cubeButton.setSize(400, 40);\n cubeButton.setLocation(100, 350);\n cubeButton.setFont(font);\n cubeButton.addActionListener(this);\n cubeButton.setFocusable(false);\n\n squarePyramidButton = new JButton(\"Square Pyramid\");\n squarePyramidButton.setSize(400, 40);\n squarePyramidButton.setLocation(100, 400);\n squarePyramidButton.setFont(font);\n squarePyramidButton.addActionListener(this);\n squarePyramidButton.setFocusable(false);\n\n rectangularPyramidButton = new JButton(\"Rectangular Pyramid\");\n rectangularPyramidButton.setSize(400, 40);\n rectangularPyramidButton.setLocation(100, 450);\n rectangularPyramidButton.setFont(font);\n rectangularPyramidButton.addActionListener(this);\n rectangularPyramidButton.setFocusable(false);\n\n ellipsoidButton = new JButton(\"Ellipsoid\");\n ellipsoidButton.setSize(400, 40);\n ellipsoidButton.setLocation(100, 500);\n ellipsoidButton.setFont(font);\n ellipsoidButton.addActionListener(this);\n ellipsoidButton.setFocusable(false);\n\n tetrahedronButton = new JButton(\"Tetrahedron\");\n tetrahedronButton.setSize(400, 40);\n tetrahedronButton.setLocation(100, 550);\n tetrahedronButton.setFont(font);\n tetrahedronButton.addActionListener(this);\n tetrahedronButton.setFocusable(false);\n\n backToPreviousFrameButton = new JButton(\"Back\");\n backToPreviousFrameButton.setSize(100, 40);\n backToPreviousFrameButton.setLocation(900, 600);\n backToPreviousFrameButton.setFont(font);\n backToPreviousFrameButton.addActionListener(this);\n backToPreviousFrameButton.setFocusable(false);\n\n mainPanel = new JPanel();\n mainPanel.setBounds(0, 0, 1080, 720);\n mainPanel.setLayout(null);\n mainPanel.setBackground(Color.decode(\"#FAF7FC\"));\n\n mainPanel.add(calculatorFor);\n mainPanel.add(sphereButton);\n mainPanel.add(rightCylinderButton);\n mainPanel.add(rightConeButton);\n mainPanel.add(rectangularPrismButton);\n mainPanel.add(triangularPrismButton);\n mainPanel.add(cubeButton);\n mainPanel.add(squarePyramidButton);\n mainPanel.add(rectangularPyramidButton);\n mainPanel.add(ellipsoidButton);\n mainPanel.add(tetrahedronButton);\n mainPanel.add(backToPreviousFrameButton);\n\n frame.getContentPane().add(mainPanel);\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.getContentPane().setBackground(Color.decode(\"#FAF7FC\"));\n frame.setLayout(new BorderLayout());\n frame.setSize(1080, 720);\n frame.setResizable(false);\n frame.setVisible(true);\n frame.setLocationRelativeTo(null);\n }\n\n public Container cubePanel() {\n\n enterValueForEdge = new JLabel(\"Enter Edge:\");\n enterValueForEdge.setSize(200, 40);\n enterValueForEdge.setLocation(100, 50);\n enterValueForEdge.setFont(font);\n enterValueForEdge.setFocusable(false);\n\n edgeTextField = new JTextField();\n edgeTextField.setSize(400, 40);\n edgeTextField.setLocation(300, 50);\n edgeTextField.setFont(font);\n\n calculateButton = new JButton(\"Calculate\");\n calculateButton.setSize(200, 40);\n calculateButton.setLocation(100, 100);\n calculateButton.setFont(font);\n calculateButton.addActionListener(this);\n calculateButton.setFocusable(false);\n\n surfaceAreaFormulaTextArea = new JTextArea(\"SA = 6a²\");\n surfaceAreaFormulaTextArea.setSize(400, 40);\n surfaceAreaFormulaTextArea.setLocation(100, 150);\n surfaceAreaFormulaTextArea.setFont(font);\n surfaceAreaFormulaTextArea.setEditable(false);\n\n surfaceAreaTextArea = new JTextArea(\"SA: \");\n surfaceAreaTextArea.setSize(500, 40);\n surfaceAreaTextArea.setLocation(100, 200);\n surfaceAreaTextArea.setFont(font);\n surfaceAreaTextArea.setEditable(false);\n\n surfaceAreaSolutionTextArea = new JTextArea();\n surfaceAreaSolutionTextArea.setSize(900, 80);\n surfaceAreaSolutionTextArea.setLocation(100, 250);\n surfaceAreaSolutionTextArea.setFont(font);\n surfaceAreaSolutionTextArea.setEditable(false);\n surfaceAreaSolutionTextArea.setLineWrap(true);\n\n backToPreviousFrameButton = new JButton(\"Back\");\n backToPreviousFrameButton.setSize(100, 40);\n backToPreviousFrameButton.setLocation(900, 600);\n backToPreviousFrameButton.setFont(font);\n backToPreviousFrameButton.addActionListener(this);\n backToPreviousFrameButton.setFocusable(false);\n\n cubePanel = new JPanel();\n cubePanel.setBounds(0, 0, 1080, 720);\n cubePanel.setLayout(null);\n cubePanel.setBackground(Color.decode(\"#FAF7FC\"));\n\n container = new Container();\n\n cubePanel.add(enterValueForEdge);\n cubePanel.add(edgeTextField);\n cubePanel.add(calculateButton);\n cubePanel.add(surfaceAreaFormulaTextArea);\n cubePanel.add(surfaceAreaTextArea);\n cubePanel.add(surfaceAreaSolutionTextArea);\n cubePanel.add(backToPreviousFrameButton);\n\n container.add(cubePanel);\n container.setLayout(null);\n container.setBackground(Color.getColor(\"#FAF7FH\"));\n return container;\n }\n\n @Override\n public void actionPerformed(ActionEvent e) {\n\n if (e.getSource() == sphereButton) {\n new sphereFrame();\n frame.dispose();\n }\n\n if (e.getSource() == rightCylinderButton) {\n new rightCylinderFrame();\n frame.dispose();\n }\n\n if (e.getSource() == rightConeButton) {\n new rightConeFrame();\n frame.dispose();\n }\n\n if (e.getSource() == rectangularPrismButton) {\n new rectangularPrismFrame();\n frame.dispose();\n }\n\n if (e.getSource() == triangularPrismButton) {\n //new triangularPrismFrame();\n frame.dispose();\n }\n\n if (e.getSource() == cubeButton) {\n frame.getContentPane().removeAll();\n frame.add(cubePanel());\n frame.repaint();\n frame.revalidate();\n System.out.println(\"Remove\");\n frame.getContentPane().add(container);\n }\n }\n}\n" }, { "answer_id": 74603952, "author": "Gilbert Le Blanc", "author_id": 300257, "author_profile": "https://Stackoverflow.com/users/300257", "pm_score": 1, "selected": true, "text": "SwingUtilities invokeLater JFrame BorderLayout JPanel JPanel JPanels CardLayout JFrames JPanels JPanel JPanels JPanel FlowLayout JPanel GridLayout JButtons JPanels JPanels JPanel JPanel GridBagLayout JPanel ActionListener JButtons JPanel ActionListener for JButtons import java.awt.BorderLayout;\nimport java.awt.CardLayout;\nimport java.awt.FlowLayout;\nimport java.awt.Font;\nimport java.awt.GridBagConstraints;\nimport java.awt.GridBagLayout;\nimport java.awt.GridLayout;\nimport java.awt.Insets;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\n\nimport javax.swing.BorderFactory;\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JPanel;\nimport javax.swing.JTextField;\nimport javax.swing.SwingUtilities;\n\npublic class CardLayoutGUI implements Runnable {\n\n public static void main(String[] args) {\n SwingUtilities.invokeLater(new CardLayoutGUI());\n }\n\n private CardLayout cardLayout;\n\n private JTextField edgeTextField, surfaceAreaSolutionTextField;\n\n private JPanel mainPanel;\n\n @Override\n public void run() {\n JFrame frame = new JFrame(\"Calculating for Surface Area\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n this.mainPanel = createMainPanel();\n frame.add(mainPanel, BorderLayout.CENTER);\n\n frame.pack();\n frame.setLocationByPlatform(true);\n frame.setVisible(true);\n }\n\n private JPanel createMainPanel() {\n cardLayout = new CardLayout();\n JPanel panel = new JPanel(cardLayout);\n panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));\n\n panel.add(createStartPanel(), \"Start\");\n panel.add(createCubeCalculationPanel(), \"Cube\");\n\n return panel;\n }\n\n private JPanel createStartPanel() {\n JPanel panel = new JPanel(new BorderLayout());\n panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));\n\n panel.add(createTitlePanel(), BorderLayout.NORTH);\n panel.add(createButtonPanel(), BorderLayout.CENTER);\n\n return panel;\n }\n\n private JPanel createTitlePanel() {\n JPanel panel = new JPanel(new FlowLayout());\n panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));\n Font font = new Font(Font.DIALOG, Font.PLAIN, 36);\n\n JLabel label = new JLabel(\"Calculator for the Surface Area of:\");\n label.setFont(font);\n panel.add(label);\n\n return panel;\n }\n\n private JPanel createButtonPanel() {\n String[] text = { \"Sphere\", \"Right Cylinder\", \"Right Cone\",\n \"Rectangular Prism\", \"Triangular Prism\", \"Cube\",\n \"Square Pyramid\", \"Rectangular Pyramid\", \"Ellipsoid\",\n \"Tetrahedron\" };\n JPanel panel = new JPanel(new GridLayout(0, 3, 5, 5));\n panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));\n Font font = new Font(null, Font.PLAIN, 24);\n ButtonListener listener = new ButtonListener();\n\n for (String s : text) {\n JButton button = new JButton(s);\n button.addActionListener(listener);\n button.setFont(font);\n panel.add(button);\n }\n\n return panel;\n }\n\n private JPanel createCubeCalculationPanel() {\n JPanel panel = new JPanel(new GridBagLayout());\n panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));\n Font titleFont = new Font(null, Font.PLAIN, 32);\n Font font = new Font(null, Font.PLAIN, 16);\n\n GridBagConstraints gbc = new GridBagConstraints();\n gbc.anchor = GridBagConstraints.LINE_START;\n gbc.fill = GridBagConstraints.HORIZONTAL;\n gbc.insets = new Insets(0, 5, 5, 5);\n gbc.weighty = 1.0;\n\n gbc.gridwidth = 2;\n gbc.gridx = 0;\n gbc.gridy = 0;\n JLabel label = new JLabel(\"SA = 6a²\");\n label.setFont(titleFont);\n panel.add(label, gbc);\n\n gbc.gridwidth = 1;\n gbc.gridy++;\n label = new JLabel(\"Edge:\");\n label.setFont(font);\n panel.add(label, gbc);\n\n gbc.gridx++;\n edgeTextField = new JTextField(10);\n edgeTextField.setFont(font);\n panel.add(edgeTextField, gbc);\n\n gbc.gridx = 0;\n gbc.gridy++;\n label = new JLabel(\"SA:\");\n label.setFont(font);\n panel.add(label, gbc);\n\n gbc.gridx++;\n surfaceAreaSolutionTextField = new JTextField(10);\n surfaceAreaSolutionTextField.setFont(font);\n surfaceAreaSolutionTextField.setEditable(false);\n panel.add(surfaceAreaSolutionTextField, gbc);\n\n gbc.gridwidth = 2;\n gbc.gridx = 0;\n gbc.gridy++;\n JButton calculateButton = new JButton(\"Calculate\");\n calculateButton.addActionListener(event -> {\n double edge = Double.valueOf(edgeTextField.getText());\n double sa = 6.0 * edge * edge;\n surfaceAreaSolutionTextField.setText(Double.toString(sa));\n });\n calculateButton.setFont(font);\n panel.add(calculateButton, gbc);\n\n gbc.gridy++;\n JButton backButton = new JButton(\"Back\");\n backButton.addActionListener(event -> {\n cardLayout.show(mainPanel, \"Start\");\n });\n backButton.setFont(font);\n panel.add(backButton, gbc);\n\n return panel;\n }\n\n public class ButtonListener implements ActionListener {\n\n @Override\n public void actionPerformed(ActionEvent event) {\n JButton button = (JButton) event.getSource();\n String text = button.getText();\n cardLayout.show(mainPanel, text);\n }\n\n }\n\n}\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74598190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19690501/" ]
74,598,198
<p>When we show Interstitial ads, App open ad is also displayed each time. it means display twice ads 1 interstitial and another one is App open. some times it going to in infinite loop, App open ads not close.</p>
[ { "answer_id": 74598289, "author": "Umesh Rajput", "author_id": 19842804, "author_profile": "https://Stackoverflow.com/users/19842804", "pm_score": 0, "selected": false, "text": "});}\n" }, { "answer_id": 74650748, "author": "Umesh Rajput", "author_id": 19842804, "author_profile": "https://Stackoverflow.com/users/19842804", "pm_score": -1, "selected": true, "text": "The problem is interstitial popping up is considered as native android element and it causes flutter app to change its lifecycle to inactive and after you close the native view interstitial the flutter app come back to life and it changes its lifecycle to resumed so your code calls the show app open ads immediately.\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74598198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19842804/" ]
74,598,269
<p>I have a dictionary that looks like this:</p> <pre><code>pris = {'äpplen': [12,13,15,16,17], 'bananer': [14,17,18,19], 'citroner': [20,13,14,15,16], 'hallon': [23,34,45,46,57], 'kokos': [12,45,67,89]} </code></pre> <p>an another:</p> <pre><code>t={'äpplen', 'bananer', 'hallon'} </code></pre> <p>What I'm trying to do is to create a new dictionary with only the elements in t.</p> <pre><code>New_dictionary= {'äpplen': [12,13,15,16,17], 'bananer': [14,17,18,19], 'hallon': [23,34,45,46,57]} </code></pre> <p>So far, I've done this: I tried to remove the not desired keys in dictionary pris, but I get all the elements that I don't want. I tried with append, etc, but it doesn't work.</p> <pre><code>for e in t: if e is not pris: del pris[e] print(pris) </code></pre> <pre><code>&gt;&gt;&gt; {'citroner': [20, 13, 14, 15, 16], 'kokos': [12, 45, 67, 89]} </code></pre> <p>Can someone help me?</p>
[ { "answer_id": 74598417, "author": "j c", "author_id": 11973491, "author_profile": "https://Stackoverflow.com/users/11973491", "pm_score": 0, "selected": false, "text": "new_d = dict()\nfor key in t:\n if key in pris:\n new_d[key] = pris[key]\n new_d = {key:pris[key] for key in t if key in pris}\n" }, { "answer_id": 74634797, "author": "Rakesh Chintha", "author_id": 2340382, "author_profile": "https://Stackoverflow.com/users/2340382", "pm_score": 0, "selected": false, "text": "new_dict = {}\nfor e in t:\n if e in pris.keys():\n new_dict[e] = pris[e]\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74598269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20621702/" ]
74,598,297
<p>What I wanted to do, is to loop through each row. If the category is &quot;HR contacts&quot; and it's number is smaller than 500 then keep it. Otherwise only keep 500 as part of it. My code is:</p> <pre class="lang-py prettyprint-override"><code>cntByUserNm['keep #'] = np.nan cntByUserNm['rest #'] = np.nan for index, row in cntByUserNm.iterrows(): print(row['Owner Name'], row['source']) if row['source'] == 'HR': if row['total number'] &lt;= 500: row['keep #'] = row['total number'] row['rest #'] = 0 else: row['keep #'] = 500 row['rest #'] = row['total number'] - 500 </code></pre> <p>But this seems doesn't work, all of the <code>keep #</code> and <code>rest #</code> still remains <code>nan</code>. How to fix this?</p> <pre class="lang-py prettyprint-override"><code>for i in range(0, len(cntByUserNm)): print(cntByUserNm.iloc[i]['Owner Name'], cntByUserNm.iloc[i]['blizday source']) if cntByUserNm.iloc[i]['blizday source'] == mainCat: if cntByUserNm.iloc[i][befCnt] &lt;= destiNum: cntByUserNm.iloc[i]['keep #'] = cntByUserNm.iloc[i][befCnt] cntByUserNm.iloc[i]['rest #'] = 0 else: cntByUserNm.iloc[i]['keep #'] = destiNum cntByUserNm.iloc[i]['rest #'] = cntByUserNm.iloc[i][befCnt] - destiNum``` </code></pre>
[ { "answer_id": 74598621, "author": "wavetitan", "author_id": 19069334, "author_profile": "https://Stackoverflow.com/users/19069334", "pm_score": 3, "selected": true, "text": ".loc for index, row in cntByUserNm.iterrows():\n print(row['Owner Name'], row['source'])\n if row['source'] == 'HR':\n if row['total number'] <= 500:\n cntByUserNm.loc[index, 'keep #'] = row['total number']\n cntByUserNm.loc[index, 'rest #'] = 0\n else:\n cntByUserNm.loc[index, 'keep #'] = 500\n cntByUserNm.loc[index, 'rest #'] = row['total number'] - 500\n keep # rest # .iloc keep_idx = df.columns.get_loc('keep #')\nrest_idx = df.columns.get_loc('rest #')\nfor index, row in cntByUserNm.iterrows():\n print(row['Owner Name'], row['source'])\n if row['source'] == 'HR':\n if row['total number'] <= 500:\n cntByUserNm.iloc[index, keep_idx] = row['total number']\n cntByUserNm.iloc[index, rest_idx] = 0\n else:\n cntByUserNm.iloc[index, keep_idx] = 500\n cntByUserNm.iloc[index, rest_idx] = row['total number'] - 500\n" }, { "answer_id": 74598684, "author": "Prabhas Kumar", "author_id": 20603322, "author_profile": "https://Stackoverflow.com/users/20603322", "pm_score": 1, "selected": false, "text": "keep_idx = df.columns.get_loc('keep #')\nrest_idx = df.columns.get_loc('rest #')\nfor index, row in cntByUserNm.iterrows():\n print(row['Owner Name'], row['source'])\n if row['source'] == 'HR':\n if row['total number'] <= 500:\n cntByUserNm.iloc[index, keep_idx] = row['total number']\n cntByUserNm.iloc[index, rest_idx] = 0\n else:\n cntByUserNm.iloc[index, keep_idx] = 500\n cntByUserNm.iloc[index, rest_idx] = row['total number'] - 500\n\n" }, { "answer_id": 74598702, "author": "DoreenBZ", "author_id": 6054532, "author_profile": "https://Stackoverflow.com/users/6054532", "pm_score": 2, "selected": false, "text": "cntByUserNm['keep #'] = np.nan\ncntByUserNm['rest #'] = np.nan\nmask = (cntByUserNm.loc[:, 'source'] == 'HR') & (cntByUserNm.loc[:, 'total number'] <= 500)\ncntByUserNm.loc[mask, 'keep #'] = cntByUserNm.loc[mask, 'total number']\ncntByUserNm.loc[mask, 'rest #'] = 0\ncntByUserNm.loc[~mask, 'keep #'] = 500\ncntByUserNm.loc[~mask, 'rest #'] = cntByUserNm.loc[~mask, 'total number'] - 500\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74598297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8416071/" ]
74,598,300
<p>I have a list as:</p> <pre><code>['Title', 'Text', 'Title', 'Title', 'Text', 'Title', 'Text', 'List', 'Text', 'Title', 'Text', 'Text'] </code></pre> <p>I want every element to be connected to element 'Title&quot; before the element. For example, Text at index 1 is connected to Title at index 0, Title at index 2 would not be connected to any element, because it has another title after it. Text at index 4 is connected to title 3, similarly Text at position 10,11 will be connected to Title at index 9.</p> <p>This is the expected output:</p> <pre><code>{1:0,4:3,6:5,7:5,8:5,10:9,11:9} </code></pre> <p>How can I do that?</p>
[ { "answer_id": 74598391, "author": "3dSpatialUser", "author_id": 5775358, "author_profile": "https://Stackoverflow.com/users/5775358", "pm_score": -1, "selected": false, "text": "x = ['Title', 'Text', 'Title', 'Title', 'Text', 'Title', 'Text', 'List', 'Text', 'Title', 'Text', 'Text']\nd = {}\nfor i, ele in enumerate(x):\n if ele != 'Title':\n d[i] = i - x[:i+1][::-1].index('Title')\n\n>>> print(d)\n>>> {1: 0, 4: 3, 6: 5, 7: 5, 8: 5, 10: 9, 11: 9}\n\n#oneliner:\n{i: i-x[:i+1][::-1].index('Title') for i, ele in enumerate(x) if ele != 'Title'}\n\n" }, { "answer_id": 74598397, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 4, "selected": true, "text": "l = ['Title', 'Text', 'Title', 'Title', 'Text', 'Title', 'Text', 'List', 'Text', 'Title', 'Text', 'Text']\n\nlast = -1\nout = {}\nfor i, v in enumerate(l):\n if v == 'Title':\n last = i\n else:\n out[i] = last\nprint(out)\n {1: 0, 4: 3, 6: 5, 7: 5, 8: 5, 10: 9, 11: 9}" }, { "answer_id": 74598666, "author": "R. Baraiya", "author_id": 13888486, "author_profile": "https://Stackoverflow.com/users/13888486", "pm_score": -1, "selected": false, "text": "Title x= ['Title', 'Text', 'Title', 'Title', 'Text', 'Title', 'Text', 'List', 'Text', 'Title', 'Text', 'Text']\n\n{i:[j for j, v in enumerate(x[:i]) if v==x[0]][-1] for i,v in enumerate(x) if v!=x[0]}\n {1: 0, 4: 3, 6: 5, 7: 5, 8: 5, 10: 9, 11: 9}\n" }, { "answer_id": 74604253, "author": "JL Peyret", "author_id": 1394353, "author_profile": "https://Stackoverflow.com/users/1394353", "pm_score": 0, "selected": false, "text": ":= prev = -1\nli = ['Title', 'Text', 'Title', 'Title', 'Text', 'Title', 'Text', 'List', 'Text', 'Title', 'Text', 'Text']\nli2 = {ix:prev\n for ix, v \n in enumerate(li) \n\n if\n\n #this first part is always True because of the +77\n # why 77 rather than say 1? to avoid -1+1 => 0 if first is Text\n #but it only stores prev on Title values using the walrus `:=`\n ((prev:= (ix if v == \"Title\" else prev))+77) \n\n #we only want the Text Values\n and v == \"Text\" \n}\n\nprint(f\"{li2=}\")\n\n\n li2={1: 0, 4: 3, 6: 5, 8: 5, 10: 9, 11: 9}\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74598300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11170350/" ]
74,598,302
<p>In Power Query i have a column which, for example looks like this</p> <p>9h8m4s</p> <p>this means 9 hours, 8 minute and 4 second. the challenge now is that i want to convert this value in the column to be the sum up of the hour, minute and second to be only second which actually equals to 32884 seconds.</p> <p>and ideas about how to convert it in PowerQuery for Power Bi?</p>
[ { "answer_id": 74598374, "author": "Peter", "author_id": 7108589, "author_profile": "https://Stackoverflow.com/users/7108589", "pm_score": 1, "selected": false, "text": "let\n Source = Table.FromValue(\"9h8m4s\"),\n #\"Added Custom1\" = Table.AddColumn(\n Source, \"Seconds\", each \n Number.FromText(Text.BeforeDelimiter([Value],\"h\")) * 3600 \n + Number.FromText(Text.BetweenDelimiters([Value], \"h\", \"m\")) * 60 \n + Number.FromText(Text.BetweenDelimiters([Value], \"m\", \"s\"))\n ),\n #\"Changed Type\" = Table.TransformColumnTypes(\n #\"Added Custom1\",{{\"Seconds\", type number}})\nin\n #\"Changed Type\"\n" }, { "answer_id": 74598378, "author": "David Bacci", "author_id": 18345037, "author_profile": "https://Stackoverflow.com/users/18345037", "pm_score": 3, "selected": true, "text": "let\n Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText(\"i45WssywyDUpVoqNBQA=\", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Column1 = _t]),\n #\"Changed Type\" = Table.TransformColumnTypes(Source,{{\"Column1\", type text}}),\n #\"Added Custom\" = Table.AddColumn(#\"Changed Type\", \"Custom\",\n each let\n h = Number.FromText(Text.BeforeDelimiter([Column1],\"h\")),\n m = Number.FromText(Text.BetweenDelimiters([Column1],\"h\",\"m\")),\n s = Number.FromText(Text.BetweenDelimiters([Column1],\"m\",\"s\"))\n in (h*60*60)+(m*60)+s)\nin\n #\"Added Custom\"\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74598302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11657343/" ]
74,598,306
<p>I'm trying to return a Vector from a function. This happens in a loop and I need the values to exist outside of the loop. Since I perform the return multiple times and I only need the unique values, I thought I use a HashSet for this, in which I insert and then try to get a reference to the value in the next line.</p> <p>I need a reference to the value in multiple other datastructures and don't want to duplicate the actual values. The values don't need to be mutable.</p> <h1>What I tried</h1> <pre><code>use std::collections::HashSet; fn main() { let mut vec: Vec&lt;&amp;str&gt; = Vec::new(); let mut books = HashSet::new(); for i in 0..5 { // This could be a function call, which returns a vector of objects, which should all be // stored centrally and uniquely in a HashSet books.insert(&quot;A Dance With Dragons&quot;.to_string()); let mut reference: &amp;str = books.get(&quot;A Dance With Dragons&quot;).unwrap(); // This would be done for multiple &quot;refering&quot; datastructures vec.push(reference); } } </code></pre> <h1>What I was expecting</h1> <p>Getting a pointer to the String in the HashSet for future use.</p> <h1>What actually happens</h1> <pre><code>error[E0502]: cannot borrow `books` as mutable because it is also borrowed as immutable --&gt; src/main.rs:10:9 | 10 | books.insert(&quot;A Dance With Dragons&quot;.to_string()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here 11 | 12 | let mut reference: &amp;str = books.get(&quot;A Dance With Dragons&quot;).unwrap(); | --------------------------------- immutable borrow occurs here 13 | // This would be done for multiple &quot;refering&quot; datastructures 14 | vec.push(reference); | ------------------- immutable borrow later used here For more information about this error, try `rustc --explain E0502`. warning: `set_test` (bin &quot;set_test&quot;) generated 2 warnings error: could not compile `set_test` due to previous error; 2 warnings emitted </code></pre> <p>I think I'm missing a very obvious solution to this...</p> <p>Thanks in advance for helping.</p>
[ { "answer_id": 74598374, "author": "Peter", "author_id": 7108589, "author_profile": "https://Stackoverflow.com/users/7108589", "pm_score": 1, "selected": false, "text": "let\n Source = Table.FromValue(\"9h8m4s\"),\n #\"Added Custom1\" = Table.AddColumn(\n Source, \"Seconds\", each \n Number.FromText(Text.BeforeDelimiter([Value],\"h\")) * 3600 \n + Number.FromText(Text.BetweenDelimiters([Value], \"h\", \"m\")) * 60 \n + Number.FromText(Text.BetweenDelimiters([Value], \"m\", \"s\"))\n ),\n #\"Changed Type\" = Table.TransformColumnTypes(\n #\"Added Custom1\",{{\"Seconds\", type number}})\nin\n #\"Changed Type\"\n" }, { "answer_id": 74598378, "author": "David Bacci", "author_id": 18345037, "author_profile": "https://Stackoverflow.com/users/18345037", "pm_score": 3, "selected": true, "text": "let\n Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText(\"i45WssywyDUpVoqNBQA=\", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Column1 = _t]),\n #\"Changed Type\" = Table.TransformColumnTypes(Source,{{\"Column1\", type text}}),\n #\"Added Custom\" = Table.AddColumn(#\"Changed Type\", \"Custom\",\n each let\n h = Number.FromText(Text.BeforeDelimiter([Column1],\"h\")),\n m = Number.FromText(Text.BetweenDelimiters([Column1],\"h\",\"m\")),\n s = Number.FromText(Text.BetweenDelimiters([Column1],\"m\",\"s\"))\n in (h*60*60)+(m*60)+s)\nin\n #\"Added Custom\"\n" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74598306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20621279/" ]
74,598,312
<p>I need to create a quiz by parsing a JSON file. The checked answers must be stored in the local storage.</p> <p>The JSON code:</p> <pre><code>{ &quot;quiz&quot;: { &quot;q1&quot;: { &quot;question&quot;: &quot;Which one is correct team name in NBA?&quot;, &quot;options&quot;: [ &quot;New York Bulls&quot;, &quot;Los Angeles Kings&quot;, &quot;Golden State Warriros&quot;, &quot;Huston Rocket&quot; ], &quot;answer&quot;: &quot;Huston Rocket&quot; }, &quot;q2&quot;: { &quot;question&quot;: &quot;'Namaste' is a traditional greeting in which Asian language?&quot;, &quot;options&quot;: [ &quot;Hindi&quot;, &quot;Mandarin&quot;, &quot;Nepalese&quot;, &quot;Thai&quot; ], &quot;answer&quot;: &quot;Hindi&quot; }, &quot;q3&quot;: { &quot;question&quot;: &quot;The Spree river flows through which major European capital city?&quot;, &quot;options&quot;: [ &quot;Berlin&quot;, &quot;Paris&quot;, &quot;Rome&quot;, &quot;London&quot; ], &quot;answer&quot;: &quot;Berlin&quot; }, &quot;q4&quot;: { &quot;question&quot;: &quot;Which famous artist had both a 'Rose Period' and a 'Blue Period'?&quot;, &quot;options&quot;: [ &quot;Pablo Picasso&quot;, &quot;Vincent van Gogh&quot;, &quot;Salvador Dalí&quot;, &quot;Edgar Degas&quot; ], &quot;answer&quot;: &quot;Pablo Picasso&quot; } } } </code></pre> <p>The code is below:</p> <pre><code>&lt;div id=&quot;container&quot;&gt;&lt;/div&gt; &lt;input type =&quot;submit&quot; name =&quot;submit&quot; value = &quot;Submit answers&quot; onclick = &quot;results()&quot;&gt; &lt;script&gt; let data = {&quot;quiz&quot;: {&quot;q1&quot;: {&quot;question&quot;: &quot;Which one is correct team name in NBA?&quot;, &quot;options&quot;: [&quot;New York Bulls&quot;, &quot;Los Angeles Kings&quot;, &quot;Golden State Warriros&quot;, &quot;Huston Rocket&quot;], &quot;answer&quot;: &quot;Huston Rocket&quot;}, &quot;q2&quot;: {&quot;question&quot;: &quot;'Namaste' is a traditional greeting in which Asian language?&quot;, &quot;options&quot;: [&quot;Hindi&quot;, &quot;Mandarin&quot;, &quot;Nepalese&quot;, &quot;Thai&quot;], &quot;answer&quot;: &quot;Hindi&quot;}, &quot;q3&quot;: {&quot;question&quot;: &quot;The Spree river flows through which major European capital city?&quot;, &quot;options&quot;: [&quot;Berlin&quot;, &quot;Paris&quot;, &quot;Rome&quot;, &quot;London&quot;], &quot;answer&quot;: &quot;Berlin&quot;}, &quot;q4&quot;: {&quot;question&quot;: &quot;Which famous artist had both a 'Rose Period' and a 'Blue Period'?&quot;, &quot;options&quot;: [&quot;Pablo Picasso&quot;, &quot;Vincent van Gogh&quot;, &quot;Salvador Daly&quot;, &quot;Edgar Degas&quot;], &quot;answer&quot;: &quot;Pablo Picasso&quot;}}}; let list = document.createElement(&quot;ul&quot;); for (let questionId in data[&quot;quiz&quot;]) { let item = document.createElement(&quot;node&quot;); let question = document.createElement(&quot;strong&quot;); question.innerHTML = questionId + &quot;: &quot; + data[&quot;quiz&quot;][questionId][&quot;question&quot;]; item.appendChild(question); list.appendChild(item); let sublist = document.createElement(&quot;ul&quot;); item.appendChild(sublist); for (let option of data[&quot;quiz&quot;][questionId][&quot;options&quot;]) { item = document.createElement(&quot;input&quot;); item.type = &quot;radio&quot;; item.name = data[&quot;quiz&quot;][questionId]; var label = document.createElement(&quot;label&quot;); label.htmlFor = &quot;options&quot;; label.appendChild(document.createTextNode(data[&quot;quiz&quot;][questionId][&quot;options&quot;])); var br = document.createElement('br'); sublist.appendChild(item); document.getElementById(&quot;container&quot;).appendChild(label); document.getElementById(&quot;container&quot;).appendChild(br); } } document.getElementById(&quot;container&quot;).appendChild(list); function results () { var score = 0; if (data[&quot;quiz&quot;][questionId][&quot;answer&quot;].checked) { score++; } } localStorage.setItem(&quot;answers&quot;,&quot;score&quot;); &lt;/script&gt; </code></pre> <p>I should get this:</p> <p><a href="https://i.stack.imgur.com/V3t4Y.png" rel="nofollow noreferrer">enter image description here</a></p> <p>Instead I got this, no matter how many times I rewrite the code:</p> <p><a href="https://i.stack.imgur.com/8YrLA.png" rel="nofollow noreferrer">enter image description here</a></p> <p>Whay am I doing wrong?</p> <p>Thank you very much for your help,</p> <p>Mary.</p>
[ { "answer_id": 74599070, "author": "Professor Abronsius", "author_id": 3603681, "author_profile": "https://Stackoverflow.com/users/3603681", "pm_score": 1, "selected": false, "text": "document.createElement(\"node\") node let data = {\n \"quiz\": {\n \"q1\": {\n \"question\": \"Which one is correct team name in NBA?\",\n \"options\": [\"New York Bulls\", \"Los Angeles Kings\", \"Golden State Warriros\", \"Huston Rocket\"],\n \"answer\": \"Huston Rocket\"\n },\n \"q2\": {\n \"question\": \"'Namaste' is a traditional greeting in which Asian language?\",\n \"options\": [\"Hindi\", \"Mandarin\", \"Nepalese\", \"Thai\"],\n \"answer\": \"Hindi\"\n },\n \"q3\": {\n \"question\": \"The Spree river flows through which major European capital city?\",\n \"options\": [\"Berlin\", \"Paris\", \"Rome\", \"London\"],\n \"answer\": \"Berlin\"\n },\n \"q4\": {\n \"question\": \"Which famous artist had both a 'Rose Period' and a 'Blue Period'?\",\n \"options\": [\"Pablo Picasso\", \"Vincent van Gogh\", \"Salvador Daly\", \"Edgar Degas\"],\n \"answer\": \"Pablo Picasso\"\n }\n }\n};\n\n// utility prototype to shuffle an array\nArray.prototype.shuffle=()=>{\n let i = this.length;\n while (i > 0) {\n let n = Math.floor(Math.random() * i);\n i--;\n let t = this[i];\n this[i] = this[n];\n this[n] = t;\n }\n return this;\n};\n\n\nlet list = document.createElement(\"ul\");\n\nObject.keys(data.quiz).forEach((q, index) => {\n // the individual record\n let obj = data.quiz[q];\n \n // add the `li` item & set the question number as data-attribute\n let question = document.createElement(\"li\");\n question.textContent = obj.question;\n question.dataset.question = index + 1;\n question.id = q;\n\n // randomise the answers\n obj.options.shuffle();\n\n // Process all the answers - add new radio & label\n Object.keys(obj.options).forEach(key => {\n let option = obj.options[key];\n let label = document.createElement('label');\n label.dataset.text = option;\n\n let cbox = document.createElement('input');\n cbox.type = 'radio';\n cbox.name = q;\n cbox.value = option;\n \n // add the new items\n label.appendChild(cbox);\n question.appendChild(label);\n });\n \n // add the question\n list.appendChild(question);\n});\n\n// add the list to the DOM\ndocument.getElementById('container').appendChild(list);\n\n\n\n// Process the checked radio buttons to determine score.\ndocument.querySelector('input[type=\"button\"]').addEventListener('click', e => {\n let score = 0;\n let keys = Object.keys(data.quiz);\n \n document.querySelectorAll('[type=\"radio\"]:checked').forEach((radio, index) => {\n if( radio.value === data.quiz[ keys[index] ].answer ) score++;\n });\n \n console.log('%d/%d', score, keys.length);\n localStorage.setItem(\"answers\", score);\n}) #container>ul>li {\n font-weight: bold\n}\n\n#container>ul>li>label {\n display: block;\n padding: 0.1rem;\n font-weight: normal;\n}\n\n#container>ul>li>label:after {\n content: attr(data-text);\n}\n\n#container>ul>li:before {\n content: 'Question 'attr(data-question)': ';\n color: blue\n} <div id=\"container\"></div>\n<input type=\"button\" value=\"Submit answers\" />" }, { "answer_id": 74599085, "author": "Yogi", "author_id": 943435, "author_profile": "https://Stackoverflow.com/users/943435", "pm_score": 1, "selected": false, "text": "let data = {\"quiz\": {\"q1\": {\"question\": \"Which one is correct team name in NBA?\", \"options\": [\"New York Bulls\", \"Los Angeles Kings\", \"Golden State Warriros\", \"Huston Rocket\"], \"answer\": \"Huston Rocket\"}, \"q2\": {\"question\": \"'Namaste' is a traditional greeting in which Asian language?\", \"options\": [\"Hindi\", \"Mandarin\", \"Nepalese\", \"Thai\"], \"answer\": \"Hindi\"}, \"q3\": {\"question\": \"The Spree river flows through which major European capital city?\", \"options\": [\"Berlin\", \"Paris\", \"Rome\", \"London\"], \"answer\": \"Berlin\"}, \"q4\": {\"question\": \"Which famous artist had both a 'Rose Period' and a 'Blue Period'?\", \"options\": [\"Pablo Picasso\", \"Vincent van Gogh\", \"Salvador Daly\", \"Edgar Degas\"], \"answer\": \"Pablo Picasso\"}}};\n\n\nlet list = document.createElement(\"ul\");\nfor (let questionId in data[\"quiz\"]) {\n let item = document.createElement(\"node\");\n let question = document.createElement(\"strong\");\n question.innerHTML = questionId + \": \" + data[\"quiz\"][questionId][\"question\"];\n item.appendChild(question);\n list.appendChild(item);\n let sublist = document.createElement(\"ul\");\n item.appendChild(sublist);\n \n // The problem is here in this nested loop \n \n for (let option of data[\"quiz\"][questionId][\"options\"]) {\n\n item = document.createElement(\"input\");\n item.type = \"radio\";\n item.name = data[\"quiz\"][questionId];\n var label = document.createElement(\"label\");\n label.htmlFor = \"options\";\n \n // remove 1 \n // label.appendChild(document.createTextNode(data[\"quiz\"][questionId][\"options\"]));\n \n // add 1\n label.appendChild(document.createTextNode(option));\n \n var br = document.createElement('br');\n sublist.appendChild(item);\n \n \n // remove 2\n //document.getElementById(\"container\").appendChild(label);\n //document.getElementById(\"container\").appendChild(br);\n \n // add 2\n sublist.appendChild(label);\n sublist.appendChild(br);\n \n }\n \n \n \n \n \n}\ndocument.getElementById(\"container\").appendChild(list);\n\nfunction results() {\n var score = 0;\n if (data[\"quiz\"][questionId][\"answer\"].checked) {\n score++;\n }\n}\n\n// Removed because snippets don't allow localStorage\n// localStorage.setItem(\"answers\", \"score\"); <div id=\"container\"></div>\n<input type=\"submit\" name=\"submit\" value=\"Submit answers\" onclick=\"results()\">" }, { "answer_id": 74599335, "author": "Dream Bold", "author_id": 12743692, "author_profile": "https://Stackoverflow.com/users/12743692", "pm_score": 0, "selected": false, "text": "<div id=\"container\"></div>\n<input type=\"submit\" name=\"submit\" value=\"Submit answers\" onclick=\"results()\">\n<script>\n let data = {\n \"quiz\": {\n \"q1\": {\n \"question\": \"Which one is correct team name in NBA?\",\n \"options\": [\"New York Bulls\", \"Los Angeles Kings\", \"Golden State Warriros\", \"Huston Rocket\"],\n \"answer\": \"Huston Rocket\"\n },\n \"q2\": {\n \"question\": \"'Namaste' is a traditional greeting in which Asian language?\",\n \"options\": [\"Hindi\", \"Mandarin\", \"Nepalese\", \"Thai\"],\n \"answer\": \"Hindi\"\n },\n \"q3\": {\n \"question\": \"The Spree river flows through which major European capital city?\",\n \"options\": [\"Berlin\", \"Paris\", \"Rome\", \"London\"],\n \"answer\": \"Berlin\"\n },\n \"q4\": {\n \"question\": \"Which famous artist had both a 'Rose Period' and a 'Blue Period'?\",\n \"options\": [\"Pablo Picasso\", \"Vincent van Gogh\", \"Salvador Daly\", \"Edgar Degas\"],\n \"answer\": \"Pablo Picasso\"\n }\n }\n };\n data = data.quiz;\n let list = document.createElement(\"ul\");\n for (let questionId in data) {\n let item = document.createElement(\"node\");\n let question = document.createElement(\"strong\");\n let i = Object.keys(data).indexOf(questionId) + 1;\n question.innerHTML = \"Question\" + i + \": \" + questionId[\"question\"];\n item.appendChild(question);\n list.appendChild(item);\n let sublist = document.createElement(\"ul\");\n item.appendChild(sublist);\n for (let option of data[questionId][\"options\"]) {\n item = document.createElement(\"input\");\n item.type = \"radio\";\n item.name = questionId;\n var label = document.createElement(\"label\");\n label.htmlFor = option;\n label.appendChild(document.createTextNode(option));\n var br = document.createElement('br');\n sublist.appendChild(item);\n sublist.appendChild(label);\n sublist.appendChild(br);\n }\n }\n document.getElementById(\"container\").appendChild(list);\n\n function results() {\n var score = 0;\n if (data[questionId][\"answer\"].checked) {\n score++;\n }\n }\n //localStorage.setItem(\"answers\", \"score\");\n</script>" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74598312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20480411/" ]
74,598,313
<p>can someone help me tune the MySQL performances for my WordPress site? I just want to make sure everything is optimized to the maximum. Thanks!</p> <p>Server details:</p> <p>CentOS v7.9</p> <p>Apache / PHP (It's a WordPress site)</p> <p>vCPU/s:1 vCPU</p> <p>RAM:2048.00 MB</p> <p>Storage: 64 GB NVMe</p> <p>Database size: Around 60MB</p> <p>MySQL Tuner:</p> <pre><code>-------- Log file Recommendations ------------------------------------------------------------------ [OK] Log file /var/log/mysqld.log exists [--] Log file: /var/log/mysqld.log (5M) [OK] Log file /var/log/mysqld.log is not empty [OK] Log file /var/log/mysqld.log is smaller than 32 Mb [OK] Log file /var/log/mysqld.log is readable. [!!] /var/log/mysqld.log contains 4563 warning(s). [!!] /var/log/mysqld.log contains 1322 error(s). [--] 135 start(s) detected in /var/log/mysqld.log [--] 1) 2022-11-28 8:37:10 0 [Note] /usr/sbin/mysqld: ready for connections. [--] 2) 2022-11-28 8:37:09 0 [Note] /usr/sbin/mysqld: ready for connections. [--] 3) 2022-11-27 8:55:24 0 [Note] /usr/sbin/mysqld: ready for connections. [--] 4) 2022-11-27 8:50:27 0 [Note] /usr/sbin/mysqld: ready for connections. [--] 5) 2022-11-27 8:46:18 0 [Note] /usr/sbin/mysqld: ready for connections. [--] 6) 2022-11-27 8:34:09 0 [Note] /usr/sbin/mysqld: ready for connections. [--] 7) 2022-11-27 8:34:07 0 [Note] /usr/sbin/mysqld: ready for connections. [--] 8) 2022-11-27 8:34:02 0 [Note] /usr/sbin/mysqld: ready for connections. [--] 9) 2022-11-27 8:33:14 140012789491904 [Note] /usr/sbin/mysqld: ready for connections. [--] 10) 2022-11-27 8:33:12 140338477058240 [Note] /usr/sbin/mysqld: ready for connections. [--] 60 shutdown(s) detected in /var/log/mysqld.log [--] 1) 2022-11-28 8:37:10 0 [Note] /usr/sbin/mysqld: Shutdown complete [--] 2) 2022-11-27 8:50:26 0 [Note] /usr/sbin/mysqld: Shutdown complete [--] 3) 2022-11-27 8:46:18 0 [Note] /usr/sbin/mysqld: Shutdown complete [--] 4) 2022-11-27 8:34:08 0 [Note] /usr/sbin/mysqld: Shutdown complete [--] 5) 2022-11-27 8:34:06 0 [Note] /usr/sbin/mysqld: Shutdown complete [--] 6) 2022-11-27 8:33:34 140012513359616 [Note] /usr/sbin/mysqld: Shutdown complete [--] 7) 2022-11-27 8:33:14 140338206811904 [Note] /usr/sbin/mysqld: Shutdown complete [--] 8) 2022-11-27 8:33:12 140442772428544 [Note] /usr/sbin/mysqld: Shutdown complete [--] 9) 2022-11-27T08:32:27.508361Z 0 [Note] /usr/sbin/mysqld: Shutdown complete [--] 10) 2022-11-26T18:54:46.107607Z 0 [Note] /usr/sbin/mysqld: Shutdown complete -------- Storage Engine Statistics ----------------------------------------------------------------- [--] Status: +Aria +CSV +InnoDB +MEMORY +MRG_MyISAM +MyISAM +PERFORMANCE_SCHEMA +SEQUENCE [--] Data in MyISAM tables: 169.2M (Tables: 137) [!!] InnoDB is enabled but isn't being used [OK] Total fragmented tables: 0 -------- Analysis Performance Metrics -------------------------------------------------------------- [--] innodb_stats_on_metadata: OFF [OK] No stat updates during querying INFORMATION_SCHEMA. -------- Views Metrics ----------------------------------------------------------------------------- -------- Triggers Metrics -------------------------------------------------------------------------- -------- Routines Metrics -------------------------------------------------------------------------- -------- Security Recommendations ------------------------------------------------------------------ [OK] There are no anonymous accounts for any database users [OK] All database users have passwords assigned [!!] There is no basic password file list! -------- CVE Security Recommendations -------------------------------------------------------------- [--] Skipped due to --cvefile option undefined -------- Performance Metrics ----------------------------------------------------------------------- [--] Up for: 25m 30s (14K q [9.314 qps], 271 conn, TX: 138M, RX: 1M) [--] Reads / Writes: 99% / 1% [--] Binary logging is disabled [--] Physical Memory : 1.8G [--] Max MySQL memory : 13.8G [--] Other process memory: 0B [--] Total buffers: 938.0M global + 264.7M per thread (50 max threads) [--] Performance_schema Max memory usage: 0B [--] Galera GCache Max memory usage: 0B [!!] Maximum reached memory usage: 9.7G (540.65% of installed RAM) [!!] Maximum possible memory usage: 13.8G (771.06% of installed RAM) [!!] Overall possible memory usage with other process exceeded memory [OK] Slow queries: 3% (482/14K) [OK] Highest usage of available connections: 68% (34/50) [OK] Aborted connections: 0.74% (2/271) [!!] CPanel and Flex system skip-name-resolve should be on [OK] Query cache is disabled by default due to mutex contention on multiprocessor machines. [OK] Sorts requiring temporary tables: 0% (0 temp sorts / 4K sorts) [!!] Joins performed without indexes: 11 [!!] Temporary tables created on disk: 70% (1K on disk / 1K total) [OK] Thread cache hit rate: 78% (58 created / 271 connections) [!!] Table cache hit rate: 5% (17K hits / 326K requests) [OK] table_definition_cache (400) is greater than number of tables (304) [OK] Open file limit used: 0% (311/40K) [OK] Table locks acquired immediately: 100% (15K immediate / 15K locks) -------- Performance schema ------------------------------------------------------------------------ [!!] Performance_schema should be activated. [--] Sys schema is not installed. -------- ThreadPool Metrics ------------------------------------------------------------------------ [--] ThreadPool stat is disabled. -------- MyISAM Metrics ---------------------------------------------------------------------------- [!!] Key buffer used: 18.2% (46.7M used / 256.0M cache) [OK] Key buffer size / total MyISAM indexes: 256.0M/10.2M [OK] Read Key buffer hit rate: 98.6% (195K cached / 2K reads) [!!] Write Key buffer hit rate: 91.7% (484 cached / 444 writes) -------- InnoDB Metrics ---------------------------------------------------------------------------- [--] InnoDB is enabled. [!!] No tables are Innodb [--] InnoDB Thread Concurrency: 0 [OK] InnoDB File per table is activated [OK] InnoDB buffer pool / data size: 512.0M / 0B [OK] Ratio InnoDB log file size / InnoDB Buffer pool size: 64.0M * 2/512.0M should be equal to 25% [OK] InnoDB buffer pool instances: 1 [--] Number of InnoDB Buffer Pool Chunk: 4 for 1 Buffer Pool Instance(s) [OK] Innodb_buffer_pool_size aligned with Innodb_buffer_pool_chunk_size &amp; Innodb_buffer_pool_instances [!!] InnoDB Read buffer efficiency: 82.98% (2554 hits / 3078 total) [!!] InnoDB Write Log efficiency: 0% (1 hits / 0 total) [OK] InnoDB log waits: 0.00% (0 waits / 1 writes) -------- Aria Metrics ------------------------------------------------------------------------------ [--] Aria Storage Engine is enabled. [OK] Aria pagecache size / total Aria indexes: 128.0M/0B [!!] Aria pagecache hit rate: 90.8% (10K cached / 1K reads) -------- TokuDB Metrics ---------------------------------------------------------------------------- [--] TokuDB is disabled. -------- XtraDB Metrics ---------------------------------------------------------------------------- [--] XtraDB is disabled. -------- Galera Metrics ---------------------------------------------------------------------------- [--] Galera is disabled. -------- Replication Metrics ----------------------------------------------------------------------- [--] Galera Synchronous replication: NO [--] No replication slave(s) for this server. [--] Binlog format: MIXED [--] XA support enabled: ON [--] Semi synchronous replication Master: OFF [--] Semi synchronous replication Slave: OFF [--] This is a standalone server -------- Recommendations --------------------------------------------------------------------------- General recommendations: Check warning line(s) in /var/log/mysqld.log file Check error line(s) in /var/log/mysqld.log file Add skip-innodb to MySQL configuration to disable InnoDB MySQL was started within the last 24 hours: recommendations may be inaccurate Reduce your overall MySQL memory footprint for system stability Dedicate this server to your database for highest performance. name resolution is enabled due to cPanel doesn't support this disabled. We will suggest raising the 'join_buffer_size' until JOINs not using indexes are found. See https://dev.mysql.com/doc/internals/en/join-buffer-size.html (specially the conclusions at the bottom of the page). When making adjustments, make tmp_table_size/max_heap_table_size equal Reduce your SELECT DISTINCT queries which have no LIMIT clause Increase table_open_cache gradually to avoid file descriptor limits Read this before increasing table_open_cache over 64: Read this before increasing for MariaDB https://mariadb.com/kb/en/library/optimizing-table_open_cache/ This is MyISAM only table_cache scalability problem, InnoDB not affected. For more details see: https://bugs.mysql.com/bug.php?id=49177 This bug already fixed in MySQL 5.7.9 and newer MySQL versions. Beware that open_files_limit (40000) variable should be greater than table_open_cache (1024) Performance schema should be activated for better diagnostics Consider installing Sys schema from https://github.com/mysql/mysql-sys for MySQL Variables to adjust: *** MySQL's maximum memory usage is dangerously high *** *** Add RAM before increasing MySQL buffer variables *** skip-name-resolve=0 join_buffer_size (&gt; 4.0M, or always use indexes with JOINs) tmp_table_size (&gt; 32M) max_heap_table_size (&gt; 32M) table_open_cache (&gt; 1024) performance_schema=ON key_buffer_size (~ 48M) </code></pre> <p>My.CNF</p> <pre><code> [mysqld] performance-schema=0 # Disabling symbolic-links is recommended to prevent assorted security risks symbolic-links=0 datadir=/var/lib/mysql socket=/var/lib/mysql/mysql.sock log-error=/var/log/mysqld.log # pid-file=/var/run/mysqld/mysqld.pid innodb_buffer_pool_size = 512M innodb_log_files_in_group = 2 innodb_flush_log_at_trx_commit = 1 innodb_log_file_size = 64M # innodb_additional_mem_pool_size = 32M innodb_buffer_pool_instances = 1 innodb_log_buffer_size = 10M max_connections = 50 wait_timeout = 3600 interactive_timeout = 3600 join_buffer_size = 4M sort_buffer_size = 4M read_rnd_buffer_size = 4M key_buffer_size = 256M max_allowed_packet=268435456 read_rnd_buffer_size = 256K thread_cache_size = 8 open_files_limit=40000 table_open_cache = 1024 default-storage-engine = MyISAM innodb_file_per_table = 1 query_cache_type = 0 query_cache_limit = 0 query_cache_size = 0 max_heap_table_size = 32M tmp_table_size = 32M </code></pre> <p>Specifically, how do I reduce the &quot;MySQL's maximum memory usage&quot; and &quot;Temporary tables created on disk&quot;, because I feel those are terribly wrong?</p>
[ { "answer_id": 74599070, "author": "Professor Abronsius", "author_id": 3603681, "author_profile": "https://Stackoverflow.com/users/3603681", "pm_score": 1, "selected": false, "text": "document.createElement(\"node\") node let data = {\n \"quiz\": {\n \"q1\": {\n \"question\": \"Which one is correct team name in NBA?\",\n \"options\": [\"New York Bulls\", \"Los Angeles Kings\", \"Golden State Warriros\", \"Huston Rocket\"],\n \"answer\": \"Huston Rocket\"\n },\n \"q2\": {\n \"question\": \"'Namaste' is a traditional greeting in which Asian language?\",\n \"options\": [\"Hindi\", \"Mandarin\", \"Nepalese\", \"Thai\"],\n \"answer\": \"Hindi\"\n },\n \"q3\": {\n \"question\": \"The Spree river flows through which major European capital city?\",\n \"options\": [\"Berlin\", \"Paris\", \"Rome\", \"London\"],\n \"answer\": \"Berlin\"\n },\n \"q4\": {\n \"question\": \"Which famous artist had both a 'Rose Period' and a 'Blue Period'?\",\n \"options\": [\"Pablo Picasso\", \"Vincent van Gogh\", \"Salvador Daly\", \"Edgar Degas\"],\n \"answer\": \"Pablo Picasso\"\n }\n }\n};\n\n// utility prototype to shuffle an array\nArray.prototype.shuffle=()=>{\n let i = this.length;\n while (i > 0) {\n let n = Math.floor(Math.random() * i);\n i--;\n let t = this[i];\n this[i] = this[n];\n this[n] = t;\n }\n return this;\n};\n\n\nlet list = document.createElement(\"ul\");\n\nObject.keys(data.quiz).forEach((q, index) => {\n // the individual record\n let obj = data.quiz[q];\n \n // add the `li` item & set the question number as data-attribute\n let question = document.createElement(\"li\");\n question.textContent = obj.question;\n question.dataset.question = index + 1;\n question.id = q;\n\n // randomise the answers\n obj.options.shuffle();\n\n // Process all the answers - add new radio & label\n Object.keys(obj.options).forEach(key => {\n let option = obj.options[key];\n let label = document.createElement('label');\n label.dataset.text = option;\n\n let cbox = document.createElement('input');\n cbox.type = 'radio';\n cbox.name = q;\n cbox.value = option;\n \n // add the new items\n label.appendChild(cbox);\n question.appendChild(label);\n });\n \n // add the question\n list.appendChild(question);\n});\n\n// add the list to the DOM\ndocument.getElementById('container').appendChild(list);\n\n\n\n// Process the checked radio buttons to determine score.\ndocument.querySelector('input[type=\"button\"]').addEventListener('click', e => {\n let score = 0;\n let keys = Object.keys(data.quiz);\n \n document.querySelectorAll('[type=\"radio\"]:checked').forEach((radio, index) => {\n if( radio.value === data.quiz[ keys[index] ].answer ) score++;\n });\n \n console.log('%d/%d', score, keys.length);\n localStorage.setItem(\"answers\", score);\n}) #container>ul>li {\n font-weight: bold\n}\n\n#container>ul>li>label {\n display: block;\n padding: 0.1rem;\n font-weight: normal;\n}\n\n#container>ul>li>label:after {\n content: attr(data-text);\n}\n\n#container>ul>li:before {\n content: 'Question 'attr(data-question)': ';\n color: blue\n} <div id=\"container\"></div>\n<input type=\"button\" value=\"Submit answers\" />" }, { "answer_id": 74599085, "author": "Yogi", "author_id": 943435, "author_profile": "https://Stackoverflow.com/users/943435", "pm_score": 1, "selected": false, "text": "let data = {\"quiz\": {\"q1\": {\"question\": \"Which one is correct team name in NBA?\", \"options\": [\"New York Bulls\", \"Los Angeles Kings\", \"Golden State Warriros\", \"Huston Rocket\"], \"answer\": \"Huston Rocket\"}, \"q2\": {\"question\": \"'Namaste' is a traditional greeting in which Asian language?\", \"options\": [\"Hindi\", \"Mandarin\", \"Nepalese\", \"Thai\"], \"answer\": \"Hindi\"}, \"q3\": {\"question\": \"The Spree river flows through which major European capital city?\", \"options\": [\"Berlin\", \"Paris\", \"Rome\", \"London\"], \"answer\": \"Berlin\"}, \"q4\": {\"question\": \"Which famous artist had both a 'Rose Period' and a 'Blue Period'?\", \"options\": [\"Pablo Picasso\", \"Vincent van Gogh\", \"Salvador Daly\", \"Edgar Degas\"], \"answer\": \"Pablo Picasso\"}}};\n\n\nlet list = document.createElement(\"ul\");\nfor (let questionId in data[\"quiz\"]) {\n let item = document.createElement(\"node\");\n let question = document.createElement(\"strong\");\n question.innerHTML = questionId + \": \" + data[\"quiz\"][questionId][\"question\"];\n item.appendChild(question);\n list.appendChild(item);\n let sublist = document.createElement(\"ul\");\n item.appendChild(sublist);\n \n // The problem is here in this nested loop \n \n for (let option of data[\"quiz\"][questionId][\"options\"]) {\n\n item = document.createElement(\"input\");\n item.type = \"radio\";\n item.name = data[\"quiz\"][questionId];\n var label = document.createElement(\"label\");\n label.htmlFor = \"options\";\n \n // remove 1 \n // label.appendChild(document.createTextNode(data[\"quiz\"][questionId][\"options\"]));\n \n // add 1\n label.appendChild(document.createTextNode(option));\n \n var br = document.createElement('br');\n sublist.appendChild(item);\n \n \n // remove 2\n //document.getElementById(\"container\").appendChild(label);\n //document.getElementById(\"container\").appendChild(br);\n \n // add 2\n sublist.appendChild(label);\n sublist.appendChild(br);\n \n }\n \n \n \n \n \n}\ndocument.getElementById(\"container\").appendChild(list);\n\nfunction results() {\n var score = 0;\n if (data[\"quiz\"][questionId][\"answer\"].checked) {\n score++;\n }\n}\n\n// Removed because snippets don't allow localStorage\n// localStorage.setItem(\"answers\", \"score\"); <div id=\"container\"></div>\n<input type=\"submit\" name=\"submit\" value=\"Submit answers\" onclick=\"results()\">" }, { "answer_id": 74599335, "author": "Dream Bold", "author_id": 12743692, "author_profile": "https://Stackoverflow.com/users/12743692", "pm_score": 0, "selected": false, "text": "<div id=\"container\"></div>\n<input type=\"submit\" name=\"submit\" value=\"Submit answers\" onclick=\"results()\">\n<script>\n let data = {\n \"quiz\": {\n \"q1\": {\n \"question\": \"Which one is correct team name in NBA?\",\n \"options\": [\"New York Bulls\", \"Los Angeles Kings\", \"Golden State Warriros\", \"Huston Rocket\"],\n \"answer\": \"Huston Rocket\"\n },\n \"q2\": {\n \"question\": \"'Namaste' is a traditional greeting in which Asian language?\",\n \"options\": [\"Hindi\", \"Mandarin\", \"Nepalese\", \"Thai\"],\n \"answer\": \"Hindi\"\n },\n \"q3\": {\n \"question\": \"The Spree river flows through which major European capital city?\",\n \"options\": [\"Berlin\", \"Paris\", \"Rome\", \"London\"],\n \"answer\": \"Berlin\"\n },\n \"q4\": {\n \"question\": \"Which famous artist had both a 'Rose Period' and a 'Blue Period'?\",\n \"options\": [\"Pablo Picasso\", \"Vincent van Gogh\", \"Salvador Daly\", \"Edgar Degas\"],\n \"answer\": \"Pablo Picasso\"\n }\n }\n };\n data = data.quiz;\n let list = document.createElement(\"ul\");\n for (let questionId in data) {\n let item = document.createElement(\"node\");\n let question = document.createElement(\"strong\");\n let i = Object.keys(data).indexOf(questionId) + 1;\n question.innerHTML = \"Question\" + i + \": \" + questionId[\"question\"];\n item.appendChild(question);\n list.appendChild(item);\n let sublist = document.createElement(\"ul\");\n item.appendChild(sublist);\n for (let option of data[questionId][\"options\"]) {\n item = document.createElement(\"input\");\n item.type = \"radio\";\n item.name = questionId;\n var label = document.createElement(\"label\");\n label.htmlFor = option;\n label.appendChild(document.createTextNode(option));\n var br = document.createElement('br');\n sublist.appendChild(item);\n sublist.appendChild(label);\n sublist.appendChild(br);\n }\n }\n document.getElementById(\"container\").appendChild(list);\n\n function results() {\n var score = 0;\n if (data[questionId][\"answer\"].checked) {\n score++;\n }\n }\n //localStorage.setItem(\"answers\", \"score\");\n</script>" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74598313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11586432/" ]
74,598,327
<p>examples:</p> <p><code>api.ts</code></p> <pre class="lang-js prettyprint-override"><code>export const getStuffs = async (term:string): Promise&lt;Stuff[]&gt; =&gt; { const stuffs = await getStuffsFromDB(term); return stuffs; } </code></pre> <p><code>mock_api.ts</code></p> <pre class="lang-js prettyprint-override"><code>export const getStuffs = async (term:string): Promise&lt;Stuff[]&gt; =&gt; { const stuffs = [ { ... hardcoded stuff } ]; return stuffs; } </code></pre> <p>is there a way to add in a CI/CD test to compare that the two provided example module above are equal in type input/output: <code>(term:string):Promise&lt;stuff[]&gt;</code> ?</p> <p>The objective is to automatically remind devs to always replicate the exported methods in <code>api.ts</code> to be mocked in <code>mock_api.ts</code></p>
[ { "answer_id": 74599070, "author": "Professor Abronsius", "author_id": 3603681, "author_profile": "https://Stackoverflow.com/users/3603681", "pm_score": 1, "selected": false, "text": "document.createElement(\"node\") node let data = {\n \"quiz\": {\n \"q1\": {\n \"question\": \"Which one is correct team name in NBA?\",\n \"options\": [\"New York Bulls\", \"Los Angeles Kings\", \"Golden State Warriros\", \"Huston Rocket\"],\n \"answer\": \"Huston Rocket\"\n },\n \"q2\": {\n \"question\": \"'Namaste' is a traditional greeting in which Asian language?\",\n \"options\": [\"Hindi\", \"Mandarin\", \"Nepalese\", \"Thai\"],\n \"answer\": \"Hindi\"\n },\n \"q3\": {\n \"question\": \"The Spree river flows through which major European capital city?\",\n \"options\": [\"Berlin\", \"Paris\", \"Rome\", \"London\"],\n \"answer\": \"Berlin\"\n },\n \"q4\": {\n \"question\": \"Which famous artist had both a 'Rose Period' and a 'Blue Period'?\",\n \"options\": [\"Pablo Picasso\", \"Vincent van Gogh\", \"Salvador Daly\", \"Edgar Degas\"],\n \"answer\": \"Pablo Picasso\"\n }\n }\n};\n\n// utility prototype to shuffle an array\nArray.prototype.shuffle=()=>{\n let i = this.length;\n while (i > 0) {\n let n = Math.floor(Math.random() * i);\n i--;\n let t = this[i];\n this[i] = this[n];\n this[n] = t;\n }\n return this;\n};\n\n\nlet list = document.createElement(\"ul\");\n\nObject.keys(data.quiz).forEach((q, index) => {\n // the individual record\n let obj = data.quiz[q];\n \n // add the `li` item & set the question number as data-attribute\n let question = document.createElement(\"li\");\n question.textContent = obj.question;\n question.dataset.question = index + 1;\n question.id = q;\n\n // randomise the answers\n obj.options.shuffle();\n\n // Process all the answers - add new radio & label\n Object.keys(obj.options).forEach(key => {\n let option = obj.options[key];\n let label = document.createElement('label');\n label.dataset.text = option;\n\n let cbox = document.createElement('input');\n cbox.type = 'radio';\n cbox.name = q;\n cbox.value = option;\n \n // add the new items\n label.appendChild(cbox);\n question.appendChild(label);\n });\n \n // add the question\n list.appendChild(question);\n});\n\n// add the list to the DOM\ndocument.getElementById('container').appendChild(list);\n\n\n\n// Process the checked radio buttons to determine score.\ndocument.querySelector('input[type=\"button\"]').addEventListener('click', e => {\n let score = 0;\n let keys = Object.keys(data.quiz);\n \n document.querySelectorAll('[type=\"radio\"]:checked').forEach((radio, index) => {\n if( radio.value === data.quiz[ keys[index] ].answer ) score++;\n });\n \n console.log('%d/%d', score, keys.length);\n localStorage.setItem(\"answers\", score);\n}) #container>ul>li {\n font-weight: bold\n}\n\n#container>ul>li>label {\n display: block;\n padding: 0.1rem;\n font-weight: normal;\n}\n\n#container>ul>li>label:after {\n content: attr(data-text);\n}\n\n#container>ul>li:before {\n content: 'Question 'attr(data-question)': ';\n color: blue\n} <div id=\"container\"></div>\n<input type=\"button\" value=\"Submit answers\" />" }, { "answer_id": 74599085, "author": "Yogi", "author_id": 943435, "author_profile": "https://Stackoverflow.com/users/943435", "pm_score": 1, "selected": false, "text": "let data = {\"quiz\": {\"q1\": {\"question\": \"Which one is correct team name in NBA?\", \"options\": [\"New York Bulls\", \"Los Angeles Kings\", \"Golden State Warriros\", \"Huston Rocket\"], \"answer\": \"Huston Rocket\"}, \"q2\": {\"question\": \"'Namaste' is a traditional greeting in which Asian language?\", \"options\": [\"Hindi\", \"Mandarin\", \"Nepalese\", \"Thai\"], \"answer\": \"Hindi\"}, \"q3\": {\"question\": \"The Spree river flows through which major European capital city?\", \"options\": [\"Berlin\", \"Paris\", \"Rome\", \"London\"], \"answer\": \"Berlin\"}, \"q4\": {\"question\": \"Which famous artist had both a 'Rose Period' and a 'Blue Period'?\", \"options\": [\"Pablo Picasso\", \"Vincent van Gogh\", \"Salvador Daly\", \"Edgar Degas\"], \"answer\": \"Pablo Picasso\"}}};\n\n\nlet list = document.createElement(\"ul\");\nfor (let questionId in data[\"quiz\"]) {\n let item = document.createElement(\"node\");\n let question = document.createElement(\"strong\");\n question.innerHTML = questionId + \": \" + data[\"quiz\"][questionId][\"question\"];\n item.appendChild(question);\n list.appendChild(item);\n let sublist = document.createElement(\"ul\");\n item.appendChild(sublist);\n \n // The problem is here in this nested loop \n \n for (let option of data[\"quiz\"][questionId][\"options\"]) {\n\n item = document.createElement(\"input\");\n item.type = \"radio\";\n item.name = data[\"quiz\"][questionId];\n var label = document.createElement(\"label\");\n label.htmlFor = \"options\";\n \n // remove 1 \n // label.appendChild(document.createTextNode(data[\"quiz\"][questionId][\"options\"]));\n \n // add 1\n label.appendChild(document.createTextNode(option));\n \n var br = document.createElement('br');\n sublist.appendChild(item);\n \n \n // remove 2\n //document.getElementById(\"container\").appendChild(label);\n //document.getElementById(\"container\").appendChild(br);\n \n // add 2\n sublist.appendChild(label);\n sublist.appendChild(br);\n \n }\n \n \n \n \n \n}\ndocument.getElementById(\"container\").appendChild(list);\n\nfunction results() {\n var score = 0;\n if (data[\"quiz\"][questionId][\"answer\"].checked) {\n score++;\n }\n}\n\n// Removed because snippets don't allow localStorage\n// localStorage.setItem(\"answers\", \"score\"); <div id=\"container\"></div>\n<input type=\"submit\" name=\"submit\" value=\"Submit answers\" onclick=\"results()\">" }, { "answer_id": 74599335, "author": "Dream Bold", "author_id": 12743692, "author_profile": "https://Stackoverflow.com/users/12743692", "pm_score": 0, "selected": false, "text": "<div id=\"container\"></div>\n<input type=\"submit\" name=\"submit\" value=\"Submit answers\" onclick=\"results()\">\n<script>\n let data = {\n \"quiz\": {\n \"q1\": {\n \"question\": \"Which one is correct team name in NBA?\",\n \"options\": [\"New York Bulls\", \"Los Angeles Kings\", \"Golden State Warriros\", \"Huston Rocket\"],\n \"answer\": \"Huston Rocket\"\n },\n \"q2\": {\n \"question\": \"'Namaste' is a traditional greeting in which Asian language?\",\n \"options\": [\"Hindi\", \"Mandarin\", \"Nepalese\", \"Thai\"],\n \"answer\": \"Hindi\"\n },\n \"q3\": {\n \"question\": \"The Spree river flows through which major European capital city?\",\n \"options\": [\"Berlin\", \"Paris\", \"Rome\", \"London\"],\n \"answer\": \"Berlin\"\n },\n \"q4\": {\n \"question\": \"Which famous artist had both a 'Rose Period' and a 'Blue Period'?\",\n \"options\": [\"Pablo Picasso\", \"Vincent van Gogh\", \"Salvador Daly\", \"Edgar Degas\"],\n \"answer\": \"Pablo Picasso\"\n }\n }\n };\n data = data.quiz;\n let list = document.createElement(\"ul\");\n for (let questionId in data) {\n let item = document.createElement(\"node\");\n let question = document.createElement(\"strong\");\n let i = Object.keys(data).indexOf(questionId) + 1;\n question.innerHTML = \"Question\" + i + \": \" + questionId[\"question\"];\n item.appendChild(question);\n list.appendChild(item);\n let sublist = document.createElement(\"ul\");\n item.appendChild(sublist);\n for (let option of data[questionId][\"options\"]) {\n item = document.createElement(\"input\");\n item.type = \"radio\";\n item.name = questionId;\n var label = document.createElement(\"label\");\n label.htmlFor = option;\n label.appendChild(document.createTextNode(option));\n var br = document.createElement('br');\n sublist.appendChild(item);\n sublist.appendChild(label);\n sublist.appendChild(br);\n }\n }\n document.getElementById(\"container\").appendChild(list);\n\n function results() {\n var score = 0;\n if (data[questionId][\"answer\"].checked) {\n score++;\n }\n }\n //localStorage.setItem(\"answers\", \"score\");\n</script>" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74598327", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4954055/" ]
74,598,349
<p>I have a string which needs to be converted to <code>JSONObject</code>, I added the dependency, but I'm getting error, which I'm not able to figure out. I have the following dependency:</p> <pre><code>&lt;!-- https://mvnrepository.com/artifact/org.json/json --&gt; &lt;dependency&gt; &lt;groupId&gt;org.json&lt;/groupId&gt; &lt;artifactId&gt;json&lt;/artifactId&gt; &lt;version&gt;20220924&lt;/version&gt; &lt;/dependency&gt; </code></pre> <pre><code>String s =&quot;{name=Alex, sex=male}&quot;; JSONObject obj = new JSONObject(s); System.out.println(obj.get(&quot;name&quot;)); </code></pre> <p>I'm getting an exception:</p> <pre><code>org.json.JSONException: Expected a ':' after a key at line 5 </code></pre>
[ { "answer_id": 74598543, "author": "chamal", "author_id": 10354667, "author_profile": "https://Stackoverflow.com/users/10354667", "pm_score": 1, "selected": false, "text": "s : = \\ String s = \"{\\\"name\\\":\\\"Alex\\\",\\\"sex\\\":\\\"male\\\"}\";\n" }, { "answer_id": 74599418, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 3, "selected": true, "text": ": String.replace() String s =\"{name=Alex, sex=male}\";\n \nJSONObject obj = new JSONObject(s.replace('=', ':'));\n \nSystem.out.println(obj.get(\"name\"));\n Alex\n \"" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74598349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20562483/" ]
74,598,368
<p>I am developing a website on the stack: React, redux, typescript. I can't output a nested array with data from a data object in JSON My code:</p> <p>app.tsx</p> <pre><code>const App: React.FC = () =&gt; { const {tasks, loading, error} = useTypedSelector(state =&gt; state.task) const dispatch: Dispatch&lt;any&gt; = useDispatch() useEffect(() =&gt; { dispatch(fetchTasks()) }, []) if (loading) { return &lt;h1&gt;Идет загрузка...&lt;/h1&gt; } if (error) { return &lt;h1&gt;{error}&lt;/h1&gt; } return ( &lt;div className=&quot;Gant_Container&quot;&gt; &lt;div&gt; &lt;p className=&quot;Project_Period&quot;&gt;{Object.values(tasks)[0]} / {Object.values(tasks)[1]}&lt;/p&gt; &lt;/div&gt; &lt;div&gt; {Object.values(tasks).map((task, id) =&gt; { return (&lt;div key={id}&gt; {task.id} {task.title} {chart.start} {chart.end} &lt;/div&gt;) })} &lt;/div&gt; &lt;/div&gt; ); }; export default Gantt_Container; </code></pre> <p>store/index.ts</p> <pre><code>export const store = createStore(rootReducer, applyMiddleware(thunk)) </code></pre> <p>reducers/index.ts</p> <pre><code>export const rootReducer = combineReducers({ task: taskReducer, }) export type RootState = ReturnType&lt;typeof rootReducer&gt; </code></pre> <p>reducers/taskReducer.tsx</p> <pre><code>const initialState: TaskState = { tasks: [], loading: false, error: null } export const taskReducer = (state = initialState, action: TaskAction): TaskState =&gt; { switch (action.type) { case TaskActionTypes.FETCH_TASKS: return {loading: true, error: null, tasks: []} case TaskActionTypes.FETCH_TASKS_SUCCESS: return {loading: false, error: null, tasks: action.payload} case TaskActionTypes.FETCH_TASKS_ERROR: return {loading: false, error: action.payload, tasks: []} default: return state } } </code></pre> <p>action-creators/task.ts</p> <pre><code>export const fetchTasks = () =&gt; { return async (dispatch: Dispatch&lt;TaskAction&gt;) =&gt; { try { dispatch({type: TaskActionTypes.FETCH_TASKS}) const response = await axios.get(&quot;&quot;) // The data is coming from the backend, I have hidden the data dispatch({type: TaskActionTypes.FETCH_TASKS_SUCCESS, payload: response.data}) } catch (e) { dispatch({ type: TaskActionTypes.FETCH_TASKS_ERROR, payload: 'Произошла ошибка при загрузке данных' }) } } } </code></pre> <p>types/task.ts</p> <pre><code>export interface TaskState { tasks: any[]; loading: boolean; error: null | string; } export enum TaskActionTypes { FETCH_TASKS = 'FETCH_TASKS', FETCH_TASKS_SUCCESS = 'FETCH_TASKS_SUCCESS', FETCH_TASKS_ERROR = 'FETCH_TASKS_ERROR' } interface FetchTasksAction { type: TaskActionTypes.FETCH_TASKS; } interface FetchTasksSuccessAction { type: TaskActionTypes.FETCH_TASKS_SUCCESS; payload: any[] } interface FetchTasksErrorAction { type: TaskActionTypes.FETCH_TASKS_ERROR; payload: string; } export type TaskAction = FetchTasksAction | FetchTasksSuccessAction | FetchTasksErrorAction </code></pre> <p>useTypedSelector.ts</p> <pre><code>export const useTypedSelector: TypedUseSelectorHook&lt;RootState&gt; = useSelector </code></pre> <p>.json</p> <pre><code>{ &quot;name&quot;: &quot;Project&quot;, &quot;data&quot;: &quot;2022&quot;, &quot;task&quot;: { &quot;id&quot;: 1, &quot;title&quot;: &quot;Apple&quot;, &quot;start&quot;: &quot;2021&quot;, &quot;end&quot;: &quot;2022&quot;, &quot;sub&quot;: [ { &quot;id&quot;: 2, &quot;title&quot;: &quot;tomato&quot;, &quot;start&quot;: &quot;2021&quot;, &quot;end&quot;: &quot;2022&quot;, &quot;sub&quot;: [ { &quot;id&quot;: 3, &quot;title&quot;: &quot;Orange&quot;, &quot;start&quot;: &quot;2019&quot;, &quot;end&quot;: &quot;2020&quot;, &quot;sub&quot;: [ { &quot;id&quot;: 4, &quot;title&quot;: &quot;Banana&quot;, &quot;start&quot;: &quot;2022&quot;, &quot;end&quot;: &quot;2022&quot;, &quot;sub&quot;: [ { &quot;id&quot;: 5, &quot;title&quot;: &quot;Strawberry&quot;, &quot;start&quot;: &quot;2015&quot;, &quot;end&quot;: &quot;2018&quot; }, { &quot;id&quot;: 6, &quot;title&quot;: &quot;cherry&quot;, &quot;period_start&quot;: &quot;2001, &quot;period_end&quot;: &quot;2003&quot; } ] } ] } ] } ] } } </code></pre> <p>Unfortunately I am not able to edit this json file.</p> <p>I can output all the data before sub, and after I can't output them. I need to output absolutely all the data from json.</p> <p>I have tried many ways from the internet, but I have not succeeded</p>
[ { "answer_id": 74598474, "author": "KALrious", "author_id": 18657175, "author_profile": "https://Stackoverflow.com/users/18657175", "pm_score": -1, "selected": false, "text": "const GanttContainer: React.FC = () => {\n const {tasks, loading, error} = useTypedSelector(state => state.task)\n const dispatch: Dispatch<any> = useDispatch()\n\n\n useEffect(() => {\n dispatch(fetchTasks())\n }, [])\n\n if (loading) {\n return <h1>Идет загрузка...</h1>\n }\n if (error) {\n return <h1>{error}</h1>\n }\n\n return (\n ....\n {Object.keys(tasks).map((taskKeys, id) => {\n return (\n <div key={id}>\n {tasks[taskKeys]}\n </div>)\n ....\n );\n};\n\nexport default GanttContainer; <script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js\"></script>" }, { "answer_id": 74601113, "author": "Priyen Mehta", "author_id": 19431815, "author_profile": "https://Stackoverflow.com/users/19431815", "pm_score": 2, "selected": true, "text": "const obj = {\n name: 'Project',\n data: '2022',\n task: {\n id: 1,\n title: 'Apple',\n start: '2021',\n end: '2022',\n sub: [{\n id: 2,\n title: 'tomato',\n start: '2021',\n end: '2022',\n sub: [{\n id: 3,\n title: 'Orange',\n start: '2019',\n end: '2020',\n sub: [{\n id: 4,\n title: 'Banana',\n start: '2022',\n end: '2022',\n sub: [{\n id: 5,\n title: 'Strawberry',\n start: '2015',\n end: '2018',\n },\n {\n id: 6,\n title: 'cherry',\n start: '2001',\n end: '2003',\n },\n ],\n }, ],\n }, ],\n }, ],\n },\n};\n\nconst arr = [];\n\nconst foo = (task) => {\n if (!task.id) return;\n arr.push({\n id: task.id,\n title: task.title,\n start: task.start,\n end: task.end,\n });\n\n if (task.sub && task.sub.length > 0) task.sub.forEach(item => foo(item));\n};\n\nfoo(obj.task);\n\nconsole.log('>>>>> arr : ', arr);" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74598368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20588930/" ]
74,598,372
<p>I was curious about how I could make <strong>a normal button</strong>, with a &quot;selected&quot; style or animation.<br> <code>&lt;button&gt; I'm a button &lt;/button&gt;</code></p> <p>When you use <strong>Radiobuttons</strong>, you can see clearly that you have a selected style whenever you click on the button.<br> <code>&lt;input type=&quot;radio&quot;&gt;</code></p> <p><a href="https://i.stack.imgur.com/FPd4Z.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FPd4Z.gif" alt="Example" /></a></p> <p>Now is the question, is it possible to have a selected style or animation (Not a click/hover animation) for the last button that you clicked (Without obviously having to use radiobuttons/checkbox).</p> <p>If so, how does one make this?</p> <p><a href="https://jsfiddle.net/JulianDotExe/bq9vydpe/75/" rel="nofollow noreferrer">JSFiddle if you want to use the code that I used in the GIF</a></p> <p>I haven't found a lot of articles about this, or maybe just haven't looked good enough, anyways, maybe you people know how to do this?</p>
[ { "answer_id": 74598474, "author": "KALrious", "author_id": 18657175, "author_profile": "https://Stackoverflow.com/users/18657175", "pm_score": -1, "selected": false, "text": "const GanttContainer: React.FC = () => {\n const {tasks, loading, error} = useTypedSelector(state => state.task)\n const dispatch: Dispatch<any> = useDispatch()\n\n\n useEffect(() => {\n dispatch(fetchTasks())\n }, [])\n\n if (loading) {\n return <h1>Идет загрузка...</h1>\n }\n if (error) {\n return <h1>{error}</h1>\n }\n\n return (\n ....\n {Object.keys(tasks).map((taskKeys, id) => {\n return (\n <div key={id}>\n {tasks[taskKeys]}\n </div>)\n ....\n );\n};\n\nexport default GanttContainer; <script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js\"></script>" }, { "answer_id": 74601113, "author": "Priyen Mehta", "author_id": 19431815, "author_profile": "https://Stackoverflow.com/users/19431815", "pm_score": 2, "selected": true, "text": "const obj = {\n name: 'Project',\n data: '2022',\n task: {\n id: 1,\n title: 'Apple',\n start: '2021',\n end: '2022',\n sub: [{\n id: 2,\n title: 'tomato',\n start: '2021',\n end: '2022',\n sub: [{\n id: 3,\n title: 'Orange',\n start: '2019',\n end: '2020',\n sub: [{\n id: 4,\n title: 'Banana',\n start: '2022',\n end: '2022',\n sub: [{\n id: 5,\n title: 'Strawberry',\n start: '2015',\n end: '2018',\n },\n {\n id: 6,\n title: 'cherry',\n start: '2001',\n end: '2003',\n },\n ],\n }, ],\n }, ],\n }, ],\n },\n};\n\nconst arr = [];\n\nconst foo = (task) => {\n if (!task.id) return;\n arr.push({\n id: task.id,\n title: task.title,\n start: task.start,\n end: task.end,\n });\n\n if (task.sub && task.sub.length > 0) task.sub.forEach(item => foo(item));\n};\n\nfoo(obj.task);\n\nconsole.log('>>>>> arr : ', arr);" } ]
2022/11/28
[ "https://Stackoverflow.com/questions/74598372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20165430/" ]