qid
int64
4
22.2M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,365,495
<p>I am porting the Matlab code to Python. In Matlab, indices start at 1, but in python, they start at 0. Is there any way to set the first index as 1 through a command line flag?</p> <p>It will be very useful for programming during index iteration.</p>
[ { "answer_id": 74365544, "author": "zccafa3", "author_id": 20435907, "author_profile": "https://Stackoverflow.com/users/20435907", "pm_score": -1, "selected": false, "text": "for i in range(1, end + 1):\n" }, { "answer_id": 74365683, "author": "jsbueno", "author_id": 108205, "author_profile": "https://Stackoverflow.com/users/108205", "pm_score": 1, "selected": false, "text": "__getitem__" }, { "answer_id": 74365691, "author": "Michael M.", "author_id": 13376511, "author_profile": "https://Stackoverflow.com/users/13376511", "pm_score": 1, "selected": false, "text": "list" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74365495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13646589/" ]
74,365,565
<p>I'm opening a discord channel and busy looping reading messages from it with the below statement to get the elements:</p> <pre><code>List&lt;org.openqa.WebElement&gt; ret = driver.findElement(By.tagName(&quot;main&quot;)) // driver = WebDriver .findElements(By.tagName(&quot;li&quot;)) .stream() .filter(message -&gt; message.getAttribute(&quot;id&quot;) != null &amp;&amp; message.getAttribute(&quot;id&quot;).contains(&quot;chat-messages&quot;)) .toList(); </code></pre> <p>There are about 40 messages by default shown on the page, and it takes 5-6 seconds for every read. It is unacceptably long. I read that when there are no matches, findElements has an implicit wait time, but that is not the case here as there are elements returned in every read. Any idea what is causing this delay and how to improve it?</p> <p>Update: From the first answer I received, I tried</p> <pre><code>List&lt;WebElement&gt; ret = driver.findElements(By.xpath(&quot;//main//li[contains(@id,'chat-messages')]&quot;)); </code></pre> <p>At first it appeared like it was fast but soon I realized it must have been some temporary thing. It is taking just as long as before.</p> <p>Update: Shamefully upon some debugging I found out that the driver.findElements is not the one taking several seconds, it only takes under 20 millis, but I have some code reading attributes from the remote web element of all of the returned elements, which is what is causing the delay. I have restructured the code now that it only has the read the attributes of the last message returned from findElements, and maintain its timestamp for identifying new messages next time.</p>
[ { "answer_id": 74371671, "author": "Easty77", "author_id": 2070127, "author_profile": "https://Stackoverflow.com/users/2070127", "pm_score": 2, "selected": true, "text": "List<WebElement> ret = driver.findElements(By.xpath(\"//main//li[contains(@id,'chat-messages')]\"));\n" }, { "answer_id": 74419558, "author": "Đorđe Zeljić", "author_id": 1291664, "author_profile": "https://Stackoverflow.com/users/1291664", "pm_score": 0, "selected": false, "text": "cssSelector" }, { "answer_id": 74459560, "author": "kenneth", "author_id": 9877340, "author_profile": "https://Stackoverflow.com/users/9877340", "pm_score": 0, "selected": false, "text": "Document.readyState" }, { "answer_id": 74466192, "author": "Prophet", "author_id": 3485434, "author_profile": "https://Stackoverflow.com/users/3485434", "pm_score": 0, "selected": false, "text": "BeautifulSoup" }, { "answer_id": 74493617, "author": "César Rodriguez", "author_id": 9475947, "author_profile": "https://Stackoverflow.com/users/9475947", "pm_score": 0, "selected": false, "text": "driver.implicitly_wait(0.1) // depends on language\nList<org.openqa.WebElement> ret = driver.findElement(By.tagName(\"main\")) // driver = WebDriver\n .findElements(By.tagName(\"li\"))\n .stream()\n .filter(message -> message.getAttribute(\"id\") != null\n && message.getAttribute(\"id\").contains(\"chat-messages\"))\n .toList();\n\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74365565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/474323/" ]
74,365,569
<p>I have a dataset that looks like this in R:</p> <pre><code>name = c(&quot;john&quot;, &quot;john&quot;, &quot;john&quot;, &quot;alex&quot;, &quot;alex&quot;, &quot;peter&quot;, &quot;peter&quot;, &quot;peter&quot;, &quot;peter&quot;) year = c(2010, 2011, 2015, 2014, 2016, 2010, 2011, 2012, 2013) age = c(21, 21, 21, 55, 55, 61, 61, 61, 61) problem_data = data.frame(name, year, age) name year age 1 john 2010 21 2 john 2011 21 3 john 2015 21 4 alex 2014 55 5 alex 2016 55 6 peter 2010 61 7 peter 2011 61 8 peter 2012 61 9 peter 2013 61 </code></pre> <p>In this dataset, the age of each person at the last recorded year has been erroneously inserted at each row. For example - in reality:</p> <ul> <li>Peter was 61 in 2013</li> <li>Peter was 60 in 2012</li> <li>Peter was 59 in 2011</li> <li>Peter was 58 in 2010</li> </ul> <p>Sometimes years are missing - as a result:</p> <ul> <li>Alex was 55 in 2016</li> <li>Alex was 53 in 2014</li> </ul> <p>I am trying to research a way in R that can handle such a task. I have been trying to combine &quot;cumulative group differences&quot; and &quot;max row conditions&quot; - but I am not sure how these concepts can be combined together to achieve this:</p> <pre><code># https://stackoverflow.com/questions/39237345/subtract-value-in-previous-row-for-each-section-of-a-data-frame-that-corresponds library(dplyr) new_data = problem_data %&gt;% group_by(name) %&gt;% mutate(real_age= age - lag(age, default = age[1])) </code></pre> <p>Bur this approach has made everyone's age as 0!</p> <pre><code># A tibble: 9 x 4 # Groups: name [3] name year age real_age &lt;chr&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; 1 john 2010 21 0 2 john 2011 21 0 3 john 2015 21 0 4 alex 2014 55 0 5 alex 2016 55 0 6 peter 2010 61 0 7 peter 2011 61 0 8 peter 2012 61 0 9 peter 2013 61 0 </code></pre> <p>Can someone please show me how to fix this problem?</p> <p>Thank you!</p>
[ { "answer_id": 74371671, "author": "Easty77", "author_id": 2070127, "author_profile": "https://Stackoverflow.com/users/2070127", "pm_score": 2, "selected": true, "text": "List<WebElement> ret = driver.findElements(By.xpath(\"//main//li[contains(@id,'chat-messages')]\"));\n" }, { "answer_id": 74419558, "author": "Đorđe Zeljić", "author_id": 1291664, "author_profile": "https://Stackoverflow.com/users/1291664", "pm_score": 0, "selected": false, "text": "cssSelector" }, { "answer_id": 74459560, "author": "kenneth", "author_id": 9877340, "author_profile": "https://Stackoverflow.com/users/9877340", "pm_score": 0, "selected": false, "text": "Document.readyState" }, { "answer_id": 74466192, "author": "Prophet", "author_id": 3485434, "author_profile": "https://Stackoverflow.com/users/3485434", "pm_score": 0, "selected": false, "text": "BeautifulSoup" }, { "answer_id": 74493617, "author": "César Rodriguez", "author_id": 9475947, "author_profile": "https://Stackoverflow.com/users/9475947", "pm_score": 0, "selected": false, "text": "driver.implicitly_wait(0.1) // depends on language\nList<org.openqa.WebElement> ret = driver.findElement(By.tagName(\"main\")) // driver = WebDriver\n .findElements(By.tagName(\"li\"))\n .stream()\n .filter(message -> message.getAttribute(\"id\") != null\n && message.getAttribute(\"id\").contains(\"chat-messages\"))\n .toList();\n\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74365569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13203841/" ]
74,365,599
<p>I have a pandas dataframe, df defined as follows:</p> <pre><code>df = pd.DataFrame({'Year':[1,2,3,...],'A':[2000,4000,6000,...],'B':[200,400,600,...]}) </code></pre> <p>where 'Year' goes from 1-40 but it can be any integer n. I want to calculate a new column as follows</p> <pre><code>df['C'] = 0.06*(df.A + df.B] </code></pre> <p>However I wish to calculate column C only for years</p> <pre><code>years = [3,5,7,10] </code></pre> <p>i.e. I only want to perform the calculation when</p> <pre><code>Year in [3,5,7,10,13,15,17,20,...] </code></pre> <p>for the first 50 years (assuming the dataframe has that many rows; in my case, the last year is 40)</p>
[ { "answer_id": 74365636, "author": "Naveed", "author_id": 3494754, "author_profile": "https://Stackoverflow.com/users/3494754", "pm_score": 0, "selected": false, "text": "years = [3,5,7,10]\n# filter rows matching the year, and calculate C\n\ndf.loc[df['Year'].isin(years), 'C']=0.06*(df.A + df.B)\ndf\n" }, { "answer_id": 74365711, "author": "Nuri Taş", "author_id": 19255749, "author_profile": "https://Stackoverflow.com/users/19255749", "pm_score": 0, "selected": false, "text": "years = np.ravel([np.array([3,5,7,10]) + 10*i for i in range(4)])\ndf['C'] = np.where(df['Year'].isin(years), 0.06*(df.A + df.B), np.nan)\n" }, { "answer_id": 74365744, "author": "Ingwersen_erik", "author_id": 17587002, "author_profile": "https://Stackoverflow.com/users/17587002", "pm_score": 1, "selected": false, "text": "\n# Required imports\nimport pandas as pd\nimport numpy as np\n\n# Dummy data\ndf = pd.DataFrame(\n {\n 'Year':[1, 2, 3],\n 'A':[2000, 4000, 6000],\n 'B':[200, 400, 600]\n }\n)\n\n# List of yers you want to compute `0.06 * (df.A + df.B)`\nyears = [3, 5, 7, 10]\n\n\n# When Year value exists inside the `years` list defined above, perform the calculation\n# Otherwise, set it to None.\n# NOTE: chnage the third parameter (None) to some default value you want to\n# use when the year value is not contained inside your list.\ndf['C'] = np.where(df['Year'].isin(years), 0.06 * (df.A + df.B), None)\n# ^---------------------^ ^------------------^ ^---^\n# | | |\n# +--- Condition | +--- What to set when condition is not met.\n# +---- What to set when condition is met\ndf\n# Returns:\n# Year A B C\n# 0 1 2000 200 None\n# 1 2 4000 400 None\n# 2 3 6000 600 396.0\n\n\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74365599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14145480/" ]
74,365,629
<p>I have this perl command:</p> <pre class="lang-bash prettyprint-override"><code># Result: o # echo foo | perl -pe 's/f(o)o/$1/' </code></pre> <p>I'd like the replacement expression to be passed via env variable:</p> <pre class="lang-bash prettyprint-override"><code>echo foo | REPLACE='$1' perl -pe 's/f(o)o/$ENV{REPLACE}/' </code></pre> <p>however, in this case, Perl does not interpret the matching variable <code>$1</code>; instead, it just replaces it with the env variable value, so that the result is <code>$1</code>.</p> <p>I know I can work this around via Bash string interpolation:</p> <pre class="lang-bash prettyprint-override"><code>REPLACE='$1' echo foo | perl -pe 's/f(o)o/'&quot;$REPLACE&quot;'/' </code></pre> <p>however, this is hackish (and limited).</p> <p>Is the a more idiomatic Perl way to accomplish this task?</p>
[ { "answer_id": 74365753, "author": "mob", "author_id": 168657, "author_profile": "https://Stackoverflow.com/users/168657", "pm_score": 2, "selected": false, "text": "eval" }, { "answer_id": 74366059, "author": "ikegami", "author_id": 589924, "author_profile": "https://Stackoverflow.com/users/589924", "pm_score": 1, "selected": false, "text": "$ENV{REPLACE}" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74365629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/210029/" ]
74,365,638
<p>I have informations about companies presented in a table. One of the field of this table is the mean value of each note the company received ('note_moyenne' in models.FicheIdentification). By clicking on a button, people are able to submit a new note for the company ('note' in models.EvaluationGenerale). I want the mean value of the notes to update in the database each time someone submit a new note.</p> <p>Here is my models.py :</p> <pre><code>class FicheIdentification(models.Model): entreprise=models.ForeignKey(Entreprise, on_delete=models.CASCADE) note_moyenne=models.IntegerField() def __str__(self): return self.entreprise.nom_entreprise class EvaluationGenerale(models.Model): entreprise=models.ForeignKey(Entreprise, on_delete=models.CASCADE) note=models.IntegerField() commentaires=models.CharField(max_length=1000) date_evaluation=models.DateField(auto_now_add=True) def __str__(self): return self.commentaires </code></pre> <p>views.py :</p> <pre><code>class CreerEvaluationGenerale(CreateView): form_class = FormulaireEvaluationGenerale model = EvaluationGenerale def form_valid(self, form): form.instance.entreprise=Entreprise.objects.filter(siret=self.kwargs['siret']).first() return super(CreerEvaluationGenerale, self).form_valid(form) def get_success_url(self): return reverse('details-evaluations') </code></pre> <p>Currently I just display the mean value in my table using this</p> <pre><code>def render_evaluation(self, record): return (EvaluationGenerale.objects.filter(entreprise=record.entreprise.siret).aggregate(Avg('note'))['note__avg']) </code></pre> <p>but I really don't like this solution as I want the value to be stored in the database, in FicheIdentification.note_moyenne.</p> <p>I thought about creating a UpdateView class but couldn't manage to link it with my CreateView.</p> <p>Any help or documentation would be really appreciated, I'm a bit lost right know...</p>
[ { "answer_id": 74365753, "author": "mob", "author_id": 168657, "author_profile": "https://Stackoverflow.com/users/168657", "pm_score": 2, "selected": false, "text": "eval" }, { "answer_id": 74366059, "author": "ikegami", "author_id": 589924, "author_profile": "https://Stackoverflow.com/users/589924", "pm_score": 1, "selected": false, "text": "$ENV{REPLACE}" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74365638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20452537/" ]
74,365,641
<p>I have a button and a region. When the button is pressed, I want it to show the region if the region is hidden, and hide the region if the region is shown. I'm trying to do this with a JavaScript condition. Here are the button and the region in the rendering pane:</p> <p><a href="https://i.stack.imgur.com/Ft38k.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ft38k.png" alt="Rendering pane" /></a></p> <p>Under the button there's a Dynamic Action that's triggered when the button is pressed. If the result is True then it should show the region and if the result is false then it should hide the region.</p> <p>So all that is left is to add a JavaScript Expression under Client-side Condition to this Dynamic Action, something like</p> <pre><code>if (*region is visible*) return false;//hide the region else return true;//show the region </code></pre> <p>Problem is I don't know what the code is to find if a region is visible. I assigned a Static ID to the region called <code>TestRegionID</code>, and I guess it is referenced in JavaScript like this: <code>$(TestRegionID)</code></p> <p>So how do I write this JavaScript expression?</p> <p><strong>Update:</strong> Answer is just put <code>($(TestRegionID).is(&quot;:visible&quot;))</code> in the JavaScript expression box and flip the Hide and Show action positions (True -&gt; Hide, False -&gt; Show)</p>
[ { "answer_id": 74365753, "author": "mob", "author_id": 168657, "author_profile": "https://Stackoverflow.com/users/168657", "pm_score": 2, "selected": false, "text": "eval" }, { "answer_id": 74366059, "author": "ikegami", "author_id": 589924, "author_profile": "https://Stackoverflow.com/users/589924", "pm_score": 1, "selected": false, "text": "$ENV{REPLACE}" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74365641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14451198/" ]
74,365,665
<p>I am using a List with a selection Binding. My expectation is that clearing the selection should update the List to not have any selected rows but the row UI remains selected.</p> <p>Here is the example code:</p> <pre><code>struct ContentView: View { @State private var selection: String? let names = [ &quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot; ] var body: some View { NavigationView { VStack { List(names, id: \.self, selection: $selection) { name in Text(name) } Button(&quot;Deselect&quot;) { self.selection = nil } } } } } </code></pre> <p>I expect that when clearing the selection on button press, the list should update to not have any selection but it remains selected.</p> <p><a href="https://i.stack.imgur.com/l8lis.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/l8lis.png" alt="Deselection image" /></a></p>
[ { "answer_id": 74368833, "author": "Guillermo Jiménez", "author_id": 14096169, "author_profile": "https://Stackoverflow.com/users/14096169", "pm_score": 2, "selected": true, "text": "import SwiftUI\n\n struct listSelection: View {\n \n @State private var selection: String?\n \n let names = [\n \"a\",\n \"b\",\n \"c\",\n \"d\"\n ]\n \n var body: some View {\n NavigationView {\n VStack {\n List(names, id: \\.self, selection: $selection) { name in\n Text(name)\n }\n .id(UUID())\n \n Button(\"Deselect\") {\n selection = nil\n }\n }\n }\n }\n }\n" }, { "answer_id": 74380758, "author": "SPatel", "author_id": 6630644, "author_profile": "https://Stackoverflow.com/users/6630644", "pm_score": 0, "selected": false, "text": "listRowBackground" }, { "answer_id": 74382491, "author": "malhal", "author_id": 259521, "author_profile": "https://Stackoverflow.com/users/259521", "pm_score": 0, "selected": false, "text": "struct ListTestView2: View {\n @State var editMode:EditMode = EditMode.active\n @State private var selection: String?\n \n let names = [\n \"a\",\n \"b\",\n \"c\",\n \"d\"\n ]\n \n var body: some View {\n NavigationView {\n VStack {\n List(names, id: \\.self, selection: $selection) { name in\n Text(name)\n }\n .environment(\\.editMode, $editMode)\n Button(\"Deselect\") {\n self.selection = nil\n }\n }\n }\n }\n}\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74365665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1684508/" ]
74,365,708
<p>I currently am writing a Powershell script that remotely removes users from a local admin group on a list of servers. The CSV headers are Computer and Name. For each entry of user (name), matches the server (computer).</p> <p>Ex.</p> <pre class="lang-none prettyprint-override"><code>Computer,Name Server1,User1 Server1,User2 Server2,User1 </code></pre> <p>Script:</p> <pre><code>$List = Import-CSV C:\temp\LocalAdmin.CSV $user = $List.Name $objGroup = $List.Computer write-host &quot;Removing user&quot; $user &quot;from server&quot; $objGroup &quot;local admin group:&quot; -ForegroundColor Green Invoke-Command -ComputerName $objGroup -ScriptBlock {Remove-LocalGroupMember -Group &quot;Administrators&quot; -Member $using:user } write-host &quot;Completed.&quot; </code></pre> <p>When the script runs, it runs through perfectly fine the first time through, but then it runs through the script line by line for how many ever lines there are causing it to attempt to remove the users multiple times. Can someone help me fix this logic? It is almost like the CSV is being read as an array vs a list. I appreciate the help!</p>
[ { "answer_id": 74368833, "author": "Guillermo Jiménez", "author_id": 14096169, "author_profile": "https://Stackoverflow.com/users/14096169", "pm_score": 2, "selected": true, "text": "import SwiftUI\n\n struct listSelection: View {\n \n @State private var selection: String?\n \n let names = [\n \"a\",\n \"b\",\n \"c\",\n \"d\"\n ]\n \n var body: some View {\n NavigationView {\n VStack {\n List(names, id: \\.self, selection: $selection) { name in\n Text(name)\n }\n .id(UUID())\n \n Button(\"Deselect\") {\n selection = nil\n }\n }\n }\n }\n }\n" }, { "answer_id": 74380758, "author": "SPatel", "author_id": 6630644, "author_profile": "https://Stackoverflow.com/users/6630644", "pm_score": 0, "selected": false, "text": "listRowBackground" }, { "answer_id": 74382491, "author": "malhal", "author_id": 259521, "author_profile": "https://Stackoverflow.com/users/259521", "pm_score": 0, "selected": false, "text": "struct ListTestView2: View {\n @State var editMode:EditMode = EditMode.active\n @State private var selection: String?\n \n let names = [\n \"a\",\n \"b\",\n \"c\",\n \"d\"\n ]\n \n var body: some View {\n NavigationView {\n VStack {\n List(names, id: \\.self, selection: $selection) { name in\n Text(name)\n }\n .environment(\\.editMode, $editMode)\n Button(\"Deselect\") {\n self.selection = nil\n }\n }\n }\n }\n}\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74365708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13357839/" ]
74,365,734
<p>I'm trying to read some data from a text file I created into a list, but keep getting the &quot;TypeError: 'str' object is not callable&quot; error when i try to do this.</p> <p>Here is the code</p> <pre class="lang-py prettyprint-override"><code>class Weather(): &quot;&quot;&quot; Weather Class &quot;&quot;&quot; def __init__(self,weather = ''): self.weather= weather def rome_weather(self, weather =''): &quot;&quot;&quot; City temperature function &quot;&quot;&quot; #retrieving geocoding API to find longitude and latitude api = '66c622a1d43cb6e0010946bc5408b773' geo_url = f&quot;http://api.openweathermap.org/geo/1.0/direct?q=Rome,IT&amp;limit=2&amp;appid={api}&quot; request = urllib.request.urlopen(geo_url) result = json.loads(request.read()) #defining longitude and latititude for value in result: for key in value: lon = value[&quot;lon&quot;] lat = value[&quot;lat&quot;] #retrieving current weather API weather_url = f&quot;https://api.openweathermap.org/data/2.5/weather?lat={lat}&amp;lon={lon}&amp;appid={api}&quot; request2 = urllib.request.urlopen(weather_url) result2 = json.loads(request2.read()) #temperature variable weather = result2['main']['temp'] - 273.15 weather = round(weather,2) return f&quot;{weather}\n&quot; weather= Weather() for value in range(200): with open ('romeweather.txt','a') as f: f.write(str(weather.rome_weather(weather))) rome=[] with open ('romeweather.txt','r') as f: for line in f: if len(rome) &lt;= 200: rome.append(float(line())) </code></pre> <p>A class is made with a function that calls the temperature of Rome, from an API. This info is then stored in a text file &quot;romeweather.text&quot;. I need to store 200 lines of the data from that file into a list. The list part isnt working for me because the data is in the form of floats ex.15.67 on each line. I keep running into this error:</p> <pre><code>Traceback (most recent call last): File &quot;main.py&quot;, line 111, in &lt;module&gt; rome.append(float(line())) TypeError: 'str' object is not callable </code></pre> <p>Please let me know how I can make it work.</p>
[ { "answer_id": 74368833, "author": "Guillermo Jiménez", "author_id": 14096169, "author_profile": "https://Stackoverflow.com/users/14096169", "pm_score": 2, "selected": true, "text": "import SwiftUI\n\n struct listSelection: View {\n \n @State private var selection: String?\n \n let names = [\n \"a\",\n \"b\",\n \"c\",\n \"d\"\n ]\n \n var body: some View {\n NavigationView {\n VStack {\n List(names, id: \\.self, selection: $selection) { name in\n Text(name)\n }\n .id(UUID())\n \n Button(\"Deselect\") {\n selection = nil\n }\n }\n }\n }\n }\n" }, { "answer_id": 74380758, "author": "SPatel", "author_id": 6630644, "author_profile": "https://Stackoverflow.com/users/6630644", "pm_score": 0, "selected": false, "text": "listRowBackground" }, { "answer_id": 74382491, "author": "malhal", "author_id": 259521, "author_profile": "https://Stackoverflow.com/users/259521", "pm_score": 0, "selected": false, "text": "struct ListTestView2: View {\n @State var editMode:EditMode = EditMode.active\n @State private var selection: String?\n \n let names = [\n \"a\",\n \"b\",\n \"c\",\n \"d\"\n ]\n \n var body: some View {\n NavigationView {\n VStack {\n List(names, id: \\.self, selection: $selection) { name in\n Text(name)\n }\n .environment(\\.editMode, $editMode)\n Button(\"Deselect\") {\n self.selection = nil\n }\n }\n }\n }\n}\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74365734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20332337/" ]
74,365,736
<p>I'm trying to stop my program when the Warrior are Priest are both with 0 or &lt; 0 or the vampire goes to 0 our &lt; 0 if not they will not advance for the next round and just finish the battle that way, and set up a winner.</p> <pre><code>while (warrior[0] and priest[0]) &gt; 0 or vampire[0] &gt; 0: #Loop until all of the group die or the enemy dies first_turn() #Execute the first turn if (warrior[0] and priest[0]) &gt; 0 or vampire[0] &gt; 0: second_turn() #Execute the second turn if (warrior[0] and priest[0]) &gt; 0 or vampire[0] &gt; 0: third_turn() #Execute the third turn if (warrior[0] and priest[0]) &gt; 0 or vampire[0] &gt; 0: initiative_phase() else: break </code></pre> <p>I've tried the way it is above, but I'm not catching why is it not stopping.</p>
[ { "answer_id": 74365807, "author": "Kedar U Shet", "author_id": 13542152, "author_profile": "https://Stackoverflow.com/users/13542152", "pm_score": 2, "selected": true, "text": " while (warrior[0] > 0 or priest[0] > 0) and vampire[0] > 0:\n" }, { "answer_id": 74365843, "author": "callow", "author_id": 5468949, "author_profile": "https://Stackoverflow.com/users/5468949", "pm_score": -1, "selected": false, "text": "while ((warrior[0] > 0 or priest[0] > 0) and vampire[0] > 0): #Loop until all of the group die or the enemy dies\n execute_turn() #Execute the turn\nelse: #someone died\n break\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74365736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20442012/" ]
74,365,737
<p>Prior to <strong>Isolated</strong> Azure Functions, one could create an <strong>Output binding queue</strong> like so: <code>[Queue(...)] CloudQueue outputQueue</code></p> <p>Then, we could add a new message with the ability to add a Visibility Delay like so:</p> <pre><code>var cloudQueueMessage = new CloudQueueMessage(&quot;some message&quot;); var timespan = new TimeSpan(0, 10, 0); outputQueue.AddMessage(cloudQueueMessage, initialVisibilityDelay: timespan); </code></pre> <p>Now that we've migrated these Azure Function to the <strong>Isolated</strong> mode, how does one add a Visibility Delay to the message?</p> <p>Here's an example from Microsoft's website <a href="https://i.stack.imgur.com/9P0mJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9P0mJ.png" alt="enter image description here" /></a></p> <p>How can we add a Visibility Delay to the message using the <strong>Isolated</strong> mode</p> <p>Thank you</p>
[ { "answer_id": 74365807, "author": "Kedar U Shet", "author_id": 13542152, "author_profile": "https://Stackoverflow.com/users/13542152", "pm_score": 2, "selected": true, "text": " while (warrior[0] > 0 or priest[0] > 0) and vampire[0] > 0:\n" }, { "answer_id": 74365843, "author": "callow", "author_id": 5468949, "author_profile": "https://Stackoverflow.com/users/5468949", "pm_score": -1, "selected": false, "text": "while ((warrior[0] > 0 or priest[0] > 0) and vampire[0] > 0): #Loop until all of the group die or the enemy dies\n execute_turn() #Execute the turn\nelse: #someone died\n break\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74365737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/248925/" ]
74,365,745
<p>In <code>Android Studio</code> (version: Android Studio Dolphin 2021.3.1 Patch 1) before downloading virtual image with Android 12 (API 33, <code>Tiramisu</code>) I had to agree to the license agreement that start with the following worrying me statement:</p> <blockquote> <p>To get started with the Android SDK Preview, you must agree to the following terms and conditions. As described below, please note that this is a preview version of the Android SDK, subject to change, that you use at your own risk. <strong>The Android SDK Preview is not a stable</strong> <strong>release, and may contain errors and defects that can result in serious</strong> <strong>damage to your computer systems, devices and data</strong>.</p> </blockquote> <p>The same for 32 API (Android 11). For Android 7 there was no such warning. Is it safe now to install and use this emulators? What damage can happen to computer? How to prevent it? Does someone already install and use them?</p> <p>In the <a href="https://www.reddit.com/r/PCSX2/comments/g7s71f/can_running_the_emulator_damage_your_laptop/" rel="nofollow noreferrer">similar question</a> I found the following recommendations about potential overheating PC:</p> <blockquote> <p>It could potentially damage your laptop if it overheats. But that is why the fan is running. It is trying to cool down. If it gets too hot your computer will start throttling programs, apps and processes to try and cool down. And if it gets too hot it should shut itself down to prevent damage. Make sure to keep and vents and fans clear, clean and free for airflow.</p> </blockquote> <p>This is the only main problem with this emulators?</p>
[ { "answer_id": 74367381, "author": "Anton Samokat", "author_id": 1455694, "author_profile": "https://Stackoverflow.com/users/1455694", "pm_score": 0, "selected": false, "text": "Tiramisu" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74365745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1455694/" ]
74,365,747
<p>i have been working on the leetcode problems these days but i always get stuck with the problems where the solutions have the .next syntax. normally i used to run the solutions in my VScode console to see what it happens. but my Vscode console doesn't recognize the .next syntax so...</p> <p>can someone explain me by this &quot; 83. Remove Duplicates from Sorted List &quot; solution ? <a href="https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/" rel="nofollow noreferrer">https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/</a></p> <pre><code> var deleteDuplicates = function(head) { var current = head; while(current) { if(current.next !== null &amp;&amp; current.val == current.next.val) { current.next = current.next.next; } else { current = current.next; } } return head; }; deleteDuplicates([1,1,2,3,3]) </code></pre> <p>i tried put the solution on my Vscode console and use console.log() to see what is happening but for some reason my console doesn't recognize the .next syntax, despite it works perfectly on the leetcode console</p>
[ { "answer_id": 74367318, "author": "Scott Sauyet", "author_id": 1243641, "author_profile": "https://Stackoverflow.com/users/1243641", "pm_score": 1, "selected": true, "text": "/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74365747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20323181/" ]
74,365,763
<p>I'm working on a Django middleware to store all requests/responses in my main database (Postgres / SQLite). But it's not hard to guess that the overhead will be crazy, so I'm thinking to use Redis to queue the requests for an amount of time and then send them slowly to my database. e.g. receiving 100 requests, storing them in database, waiting to receive another 100 requests and doing the same, or something like this.</p> <p>The model is like this:</p> <pre class="lang-py prettyprint-override"><code>url method status user remote_ip referer user_agent user_ip metadata # any important piece of data related to request/response e.g. errors or ... created_at updated_at </code></pre> <p>My questions are &quot;is it a good approach? and how we can implement it? do you have any example that does such a thing?&quot; And the other question is that &quot;is there any better solution&quot;?</p>
[ { "answer_id": 74367318, "author": "Scott Sauyet", "author_id": 1243641, "author_profile": "https://Stackoverflow.com/users/1243641", "pm_score": 1, "selected": true, "text": "/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74365763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1930464/" ]
74,365,772
<p>I have app with 3 entity models</p> <pre><code>public class Project { public Guid ProjectId { get; set; } public string ProjectName { get; set; } public string ProjectInfo { get; set; } public Guid DepartMentId { get; set; } public ICollection&lt;Employee&gt; Employees { get; set; } = new List&lt;Employee&gt;(); public Department Department { get; set; } } public class Employee { public Guid EmployeeId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string PayrollNumber { get; set; } public int Seniority { get; set; } [Column(TypeName = &quot;decimal(10,2)&quot;)] public decimal Salary { get; set; } public int Rank { get; set; } public int Hours { get; set; } public ICollection&lt;Project&gt; Project { get; set; } } public class Department { public Guid DepartmentId { get; set; } public string DepartmentName { get; set; } public string DepartmentInfo { get; set; } public int Rank { get; set; } public List&lt;Project&gt; Projects { get; set; } = new List&lt;Project&gt;(); } </code></pre> <p>I am create a new employee after created department and project like this</p> <pre><code>public void AddEmployee(string fname, string lname, string payNum, int seniority, decimal salary, int hours, string projname) { var proj = _projectController.GetProjects().Where(x =&gt; x.ProjectName == projname).SingleOrDefault(); var projects = new List&lt;Project&gt;(); projects.Add(proj); var emp = new Employee { EmployeeId = Guid.NewGuid(), FirstName = fname, LastName = lname, PayrollNumber = payNum, Seniority = seniority, Salary = salary, Hours = hours, Project = projects }; _employeeController.AddEmployee(emp); } </code></pre> <p>AddEmployee method leads to SaveChanges(); method after all and I am getting this error SqlException: Violation of PRIMARY KEY constraint 'PK_Projects'. Cannot insert duplicate key in object 'dbo.Projects'. The duplicate key value is (10bc054b-b9a7-47da-eb14-08dac1b7a7fe). The statement has been terminated. How can I fix this?</p>
[ { "answer_id": 74367318, "author": "Scott Sauyet", "author_id": 1243641, "author_profile": "https://Stackoverflow.com/users/1243641", "pm_score": 1, "selected": true, "text": "/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74365772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19727965/" ]
74,365,788
<p>How would i check to see if the ID exists within the localStorage object key array</p> <p>i am currenty using this and it does not work</p> <pre><code>if (favorites.includes(theid)) { alert('You Allready Added this Listing'); } </code></pre> <p>Also how do i pull the indivdual object array apart into ID , image , title to make varibles</p> <p>Thank you</p> <p>Below is the Full Code</p> <pre><code>function checkfave (theid) { // get favorites from local storage or empty array var favorites = JSON.parse(localStorage.getItem('favorites')) || []; var theimage = $('#theimage'+theid).attr('src'); var thetitle = $('#thetitle'+theid).text(); if (localStorage.getItem('favorites') != null) { if (favorites.includes(theid)) { alert('You Allready Added this Listing'); } } favorites.push({ID:theid,IMAGE:theimage,TITLE:thetitle}); localStorage.setItem('favorites', JSON.stringify(favorites)); alert('You Just Added Listing '+theid+' To Your Favorites'); //Loop through the Favorites List and display in console (HIDDEN) console.clear(); for (let i = 0; i &lt; favorites.length; i++) { console.log('ID= '+favorites[i].ID+' IMAGE='+favorites[i].IMAGE+' TITLE='+favorites[i].TITLE); }//for loop } </code></pre>
[ { "answer_id": 74367318, "author": "Scott Sauyet", "author_id": 1243641, "author_profile": "https://Stackoverflow.com/users/1243641", "pm_score": 1, "selected": true, "text": "/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74365788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20082467/" ]
74,365,794
<p>I encountered this bash script and wanted to know what <code>sed -i</code> is doing and what's up with the <code>/s</code> and <code>/g</code>? I looked at the manpages and it says text <code>sed</code> is used to transform text and the <code>i</code> flag is used to do it in place. But in the context of this script what is being transformed and what is it being transformed to?</p> <pre><code>#!/bin/sh sed -i &quot;s/$SENTINEL_QUORUM/$SENTINEL_QUORUM/g&quot; /redis/sentinel.conf sed -i &quot;s/$SENTINEL_DOWN_AFTER/$SENTINEL_DOWN_AFTER/g&quot; /redis/sentinel.conf sed -i &quot;s/$SENTINEL_FAILOVER/$SENTINEL_FAILOVER/g&quot; /redis/sentinel.conf redis-server /redis/sentinel.conf --sentinel </code></pre> <p>Here is sentinel.conf if it helps:</p> <pre><code>port 26379 dir /tmp sentinel monitor redismaster redis-master 6379 $SENTINEL_QUORUM sentinel down-after-milliseconds redismaster $SENTINEL_DOWN_AFTER sentinel parallel-syncs redismaster 1 sentinel failover-timeout redismaster $SENTINEL_FAILOVER </code></pre>
[ { "answer_id": 74365896, "author": "markp-fuso", "author_id": 7366100, "author_profile": "https://Stackoverflow.com/users/7366100", "pm_score": 0, "selected": false, "text": "bash" }, { "answer_id": 74365915, "author": "Barmar", "author_id": 1491895, "author_profile": "https://Stackoverflow.com/users/1491895", "pm_score": 1, "selected": false, "text": "sed -i 's/\\$SENTINEL_QUORUM/'\"$SENTINEL_QUORUM/g\" /redis/sentinel.conf\n" }, { "answer_id": 74365955, "author": "enceladus2022", "author_id": 17972497, "author_profile": "https://Stackoverflow.com/users/17972497", "pm_score": 0, "selected": false, "text": ":s/searchfor/replacewith/g\n" }, { "answer_id": 74382228, "author": "Todd Sierra", "author_id": 20463345, "author_profile": "https://Stackoverflow.com/users/20463345", "pm_score": 0, "selected": false, "text": "[todd@overlord] ~$ cat sed_demo.txt \nHi! Hi again!\nHello!\nHi!\n\n[todd@overlord] ~$ sed \"s/Hi/Bye/\" sed_demo.txt\nBye! Hi again!\nHello!\nBye!\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74365794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14307345/" ]
74,365,810
<pre><code>UPDATE Team SET Team_name = CONCAT((SELECT Team_name FROM Team INNER JOIN Coach ON Team.Coach_id = Coach.Coach_id WHERE Coach_name = 'Sidny Jonson'), '_nure') ; </code></pre> <blockquote> <p>ORA-01427: single-row subquery returns more than one row ORA-06512:<br /> at &quot;SYS.DBMS_SQL&quot;, line 1721</p> </blockquote> <p>I need to do update with inner join in ORACLE</p>
[ { "answer_id": 74365896, "author": "markp-fuso", "author_id": 7366100, "author_profile": "https://Stackoverflow.com/users/7366100", "pm_score": 0, "selected": false, "text": "bash" }, { "answer_id": 74365915, "author": "Barmar", "author_id": 1491895, "author_profile": "https://Stackoverflow.com/users/1491895", "pm_score": 1, "selected": false, "text": "sed -i 's/\\$SENTINEL_QUORUM/'\"$SENTINEL_QUORUM/g\" /redis/sentinel.conf\n" }, { "answer_id": 74365955, "author": "enceladus2022", "author_id": 17972497, "author_profile": "https://Stackoverflow.com/users/17972497", "pm_score": 0, "selected": false, "text": ":s/searchfor/replacewith/g\n" }, { "answer_id": 74382228, "author": "Todd Sierra", "author_id": 20463345, "author_profile": "https://Stackoverflow.com/users/20463345", "pm_score": 0, "selected": false, "text": "[todd@overlord] ~$ cat sed_demo.txt \nHi! Hi again!\nHello!\nHi!\n\n[todd@overlord] ~$ sed \"s/Hi/Bye/\" sed_demo.txt\nBye! Hi again!\nHello!\nBye!\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74365810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20452808/" ]
74,365,816
<p>I have the following tibble</p> <pre><code>structure(list(blockLabel = structure(c(1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L), .Label = c(&quot;auditory_only&quot;, &quot;bimodal_focus_auditory&quot;, &quot;bimodal_focus_visual&quot;, &quot;divided&quot;, &quot;visual_only&quot;), class = &quot;factor&quot;), trial_resp.corr = structure(c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L), .Label = c(&quot;0&quot;, &quot;1&quot;), class = &quot;factor&quot;), participant = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c(&quot;pilot01&quot;, &quot;pilot02&quot;, &quot;pilot03&quot;), class = &quot;factor&quot;), Freq = c(0L, 1L, 3L, 74L, 0L, 12L, 71L, 69L, 70L, 12L, 0L, 1L, 2L, 77L, 11L, 12L, 71L, 70L, 67L, 1L, 1L, 1L, 3L, 75L, 0L, 11L, 71L, 69L, 69L, 12L ), tc = c(12, 72, 72, 144, 12, 12, 72, 72, 144, 12, 12, 72, 72, 144, 12, 12, 72, 72, 144, 12, 12, 72, 72, 144, 12, 12, 72, 72, 144, 12), freq = c(0, 1.38888888888889, 4.16666666666667, 51.3888888888889, 0, 100, 98.6111111111111, 95.8333333333333, 48.6111111111111, 100, 0, 1.38888888888889, 2.77777777777778, 53.4722222222222, 91.6666666666667, 100, 98.6111111111111, 97.2222222222222, 46.5277777777778, 8.33333333333333, 8.33333333333333, 1.38888888888889, 4.16666666666667, 52.0833333333333, 0, 91.6666666666667, 98.6111111111111, 95.8333333333333, 47.9166666666667, 100)), class = c(&quot;tbl_df&quot;, &quot;tbl&quot;, &quot;data.frame&quot; ), row.names = c(NA, -30L)) </code></pre> <p>I would like to create three different tables according to the levels of <strong>participant</strong> variable. More or less the final result should be like the following one:</p> <p><a href="https://i.stack.imgur.com/hoxnk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hoxnk.png" alt="enter image description here" /></a></p> <p>I have started scripting the following code (since I am looking for to do this via a dplyr, apply family, loops or map function)</p> <pre><code> list %&gt;% as_data_frame() %&gt;% select(blockLabel, trial_resp.corr, participant, Freq, freq) %&gt;% map(~ flextable(.x)) </code></pre> <p>But unfortunately, I get the following error code:</p> <pre><code>Error in flextable(.x) : is.data.frame(data) is not TRUE </code></pre> <p>I am not an expert in this method thus if you would have something to suggest about fixing the problem and sharing knowledge to achieve the final result, please just let me know (in passing I specify that Correctness corresponds to 1 and Incorrcetness to 0 of trial_resp.corr variable)</p> <p>Thanks</p>
[ { "answer_id": 74365870, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 3, "selected": true, "text": "select" }, { "answer_id": 74366040, "author": "asd-tm", "author_id": 5043424, "author_profile": "https://Stackoverflow.com/users/5043424", "pm_score": 1, "selected": false, "text": "library(dplyr)\ndfs <- list()\n\nfor (prt in levels(df$participant)){\n dfs[[prt]] <- df %>% filter(participant == prt) %>% select(-participant)\n}\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74365816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14712320/" ]
74,365,910
<p>How can I ensure an array is passed a certain number of parameter in a function apart from using a tuple</p> <p>I have a function in typescript which takes an array as a parameter and when the function is called i want a certain number of elements to be passed in the array how can I achieve this apart from using a tuple</p> <pre><code>type a =(arr: [number, number]) =&gt; boolean const b:a = (arr) =&gt; {} b([]) // should throw an error if the parameter passed in array is less than two </code></pre> <p>How can I achieve this without using tuples</p>
[ { "answer_id": 74366049, "author": "caTS", "author_id": 18244921, "author_profile": "https://Stackoverflow.com/users/18244921", "pm_score": 2, "selected": true, "text": "Array<number>" }, { "answer_id": 74366337, "author": "Darryl Noakes", "author_id": 15261914, "author_profile": "https://Stackoverflow.com/users/15261914", "pm_score": 0, "selected": false, "text": "length" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74365910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15156582/" ]
74,365,914
<p>I want my image to float to the right. But if I use the float: right; write a command, it also takes the section with it. See image. The picture is already so far to the right because it is so big. (the rest is transparent).</p> <p><a href="https://i.stack.imgur.com/5RV7j.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5RV7j.png" alt="Image before and after float" /></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>#second { background-color: black; } .orange { height: 10px; background-color: #F54703; } #secondBild { float: right; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div&gt; &lt;section id="first"&gt; &lt;img src="bilder/Oben_rechtsunten.png"&gt; &lt;/section&gt; &lt;section class="orange"&gt;&lt;/section&gt; &lt;/section&gt; &lt;section id="second"&gt; &lt;img src="bilder/Seite_unten.png" id="secondBild"&gt; &lt;/section&gt; &lt;section class="orange"&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74366107, "author": "Adam", "author_id": 12571484, "author_profile": "https://Stackoverflow.com/users/12571484", "pm_score": 0, "selected": false, "text": "div {\n display: flex;\n}\n\n#second {\n flex-grow: 1; /* added this */\n background-color: black;\n}\n\n.orange {\n height: 10px;\n background-color: #F54703;\n}\n\n#secondBild {\n /*float: right;*/\n margin-inline: auto 0; /* added this */\n display: block; /* added this */\n}" }, { "answer_id": 74366191, "author": "Louis", "author_id": 20452788, "author_profile": "https://Stackoverflow.com/users/20452788", "pm_score": 0, "selected": false, "text": "#first{\n background-color: white;\n background-image: url(bilder/Oben_rechtsunten.png);\n background-position: right;\n background-size: contain;\n background-repeat: no-repeat;\n height: 1000px;\n}\n" }, { "answer_id": 74366576, "author": "Emile Youssef FEGHALI EL", "author_id": 19603779, "author_profile": "https://Stackoverflow.com/users/19603779", "pm_score": -1, "selected": false, "text": "#img-container {\n display: flex;\n align-items: right;\n}\n\nUse `display: flex;` and `align-items: right;`" }, { "answer_id": 74366699, "author": "Gayatri", "author_id": 4377001, "author_profile": "https://Stackoverflow.com/users/4377001", "pm_score": 0, "selected": false, "text": "float" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74365914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20452788/" ]
74,365,918
<p>I am trying to solve this question for 2 days but unable to solve it, gets really frustrated. I hope anyone can help me to get rid out of this problem.</p> <p>Write a program for given an integer list where each number represents the number of hops you can make in hopscotch game, determine whether you can reach to the last index starting at index 0.</p> <p>For example, [2, 0, 1, 0] returns True while [1, 1, 0, 1] returns False.</p> <p>Input Format</p> <p>single line space separated integers</p> <p>Constraints</p> <p>len(list) &gt; 0</p> <p>Output Format</p> <p>Boolean True or False</p> <p>Sample Input 0</p> <pre><code>2 3 1 1 4 </code></pre> <p>Sample Output 0</p> <pre><code>True </code></pre> <p>Explanation 0</p> <p>Input: nums = [2,3,1,1,4] Output: True Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. Sample Input 1</p> <pre><code>3 2 1 0 4 </code></pre> <p>Sample Output 1</p> <pre><code>False </code></pre> <p>Explanation 1</p> <p>Input: nums = [3,2,1,0,4] Output: False Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.</p>
[ { "answer_id": 74366081, "author": "Domi", "author_id": 16217518, "author_profile": "https://Stackoverflow.com/users/16217518", "pm_score": 2, "selected": false, "text": "sample1 = [2,3,1,1,4]\nsample2 = [3,2,1,0,4]\n\ndef hopscotch(sample):\n last_index = len(sample) - 1\n current_index = 0\n while True:\n if current_index == last_index:\n return True\n elif current_index > last_index:\n return False #Or True depending on if you can hop off the end\n elif sample[current_index] == 0:\n return False\n else:\n current_index += sample[current_index] \n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74365918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16613519/" ]
74,365,933
<p>The .NET v7 framework introduced the concept of Route Groups to group mapped endpoints together based on a common prefix in the path:</p> <pre class="lang-cs prettyprint-override"><code>app.MapGroup(&quot;/public/todos&quot;).MapTodosApi(); </code></pre> <p>Now, in order to return an absolute path for the <code>Created</code> response (i.e. to a <code>POST</code> request), I need that route path prefix inside the service. This usecase is even discussed <a href="https://devblogs.microsoft.com/dotnet/asp-net-core-updates-in-dotnet-7-preview-4/#route-groups" rel="nofollow noreferrer">in the official documentation</a>:</p> <blockquote> <p>Instead of using relative addresses for the Location header in the 201 Created result, it’s also possible to use GroupRouteBuilder.GroupPrefix to construct a root-relative address</p> </blockquote> <p>However, the <code>GroupRouteBuilder</code> class does not exist. There is only a <a href="https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.routing.routegroupbuilder?view=aspnetcore-7.0" rel="nofollow noreferrer"><code>RouteGroupBuilder</code></a>, but an instance of it has no member <code>GroupPrefix</code>. Any suggestions how to actually get the prefix?</p>
[ { "answer_id": 74408319, "author": "pfx", "author_id": 9200675, "author_profile": "https://Stackoverflow.com/users/9200675", "pm_score": 3, "selected": true, "text": "GetPathByRouteValues" }, { "answer_id": 74415199, "author": "thewallrus", "author_id": 2528735, "author_profile": "https://Stackoverflow.com/users/2528735", "pm_score": 0, "selected": false, "text": "EndpointDataSource" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74365933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/777928/" ]
74,365,971
<p>I created a scatter plot using the <a href="https://en.wikipedia.org/wiki/Ggplot2" rel="nofollow noreferrer">ggplot2</a> package for my data. Since my data has a large number of points, I will explain my problem with already available small dataset. Consider this scatter plot:</p> <pre><code>ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() </code></pre> <p><a href="https://i.stack.imgur.com/atGWK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/atGWK.png" alt="Scatter plot between wt and mpg" /></a></p> <p>I want to use <a href="https://en.wikipedia.org/wiki/K-means_clustering" rel="nofollow noreferrer"><em>k</em>-means clustering</a> to cluster these data points, but then also show the clusters on the same scatter plot (the one shown above) and not a new dimensionality reduction plot? How can I do this?</p>
[ { "answer_id": 74366063, "author": "stefan", "author_id": 12993861, "author_profile": "https://Stackoverflow.com/users/12993861", "pm_score": 2, "selected": false, "text": "ggforce::geom_mark_ellipse" }, { "answer_id": 74366227, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 3, "selected": true, "text": "factoextra" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74365971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3138373/" ]
74,365,978
<p>I have three folders folder1, folder2, and folder3. They have data frames as follows:</p> <pre><code>folder1/ df1.csv df4.csv df5.csv folder2/ df1.csv df3.csv df4.csv folder3/ df4.csv </code></pre> <p>I am confused about how to contact the data frames using <code>pandas.concat()</code> with the same names in all three folders and save them in a new folder &quot;finalfolder&quot; such that the finalfolder contains concatinated files:</p> <pre><code>finalfolder/ df1.csv (concat from folder1 and folder2) df3.csv (From folder 2) df4.csv (concat from folder1, 2, and 3) df5.csv (From folder 1) </code></pre>
[ { "answer_id": 74366122, "author": "maxxel_", "author_id": 17575465, "author_profile": "https://Stackoverflow.com/users/17575465", "pm_score": 2, "selected": true, "text": "from os import listdir\nimport pandas as pd\n\nfolder_paths = ['put all the folder paths here']\ndf_dict = {'folder': [], 'file': []}\nfor folder_path in folder_paths:\n for file in listdir(folder_path):\n df_dict['folder'].append(folder_path)\n df_dict['file'].append(file)\n\ndf = pd.DataFrame(df_dict)\nfor file, group in df.groupby(df['file']):\n df_temp = pd.DataFrame()\n for folder in group['folder'].tolist():\n df_temp = pd.concat([df_temp, pd.read_csv(f'{folder}/{file}')])\n df_temp.to_csv(f'finalfolder/{file}')\n" }, { "answer_id": 74366573, "author": "Hari", "author_id": 20361389, "author_profile": "https://Stackoverflow.com/users/20361389", "pm_score": 0, "selected": false, "text": "import os\nimport csv as cs\nimport pandas as pd\n\nbase = os.path.abspath('/home/hari/Documents/python/pandas/') #base \ndirectory \nwhere the program saved\n\nprint(os.path.join(base, 'dir1/df1.csv'))\nq = os.path.join(base, 'dir1/df1.csv')\nw = os.path.join(base, 'dir1/df4.csv')\ne = os.path.join(base, 'dir1/df5.csv')\nr = os.path.join(base, 'dir2/df1.csv')\nt = os.path.join(base, 'dir2/df3.csv')\ny = os.path.join(base, 'dir2/df4.csv')\nu = os.path.join(base, 'dir3/df4.csv')\n\ncsv = [q, w, e, r, t, y, u]\n\nfi = pd.concat(map(pd.read_csv, csv), ignore_index=True) #used map \nfunction because of array\n\nprint(fi) #for testing\n\nfinal = open(os.path.join(base, 'final/final.csv'), 'w', encoding='UTF8')\n\nwrite = cs.writer(final) #passing the final file in csv writer\n\nwrite.writerow(fi) #passing the concatenated csv's in writer\n\n#make sure to change the url in base directory\n" }, { "answer_id": 74366849, "author": "Hira ", "author_id": 10440018, "author_profile": "https://Stackoverflow.com/users/10440018", "pm_score": 1, "selected": false, "text": "import os\nfolders_list = ['folder1','folder2','folder3']\nfiles1 = os.listdir(folders_list[0])\nfiles2 = os.listdir(folders_list[1])\nfiles3 = os.listdir(folders_list[2])\n\nmax_files_size =3\nfor i in range(max_files_size):\n f1=False\n f2=False\n f3=False\n try:\n folder1_df = pd.read_csv(os.path.abspath(\"folder1\")+\"/\"+files1[i])\n f1=True\n except:\n pass\n try:\n folder2_df = pd.read_csv(os.path.abspath(\"folder2\")+\"/\"+files2[i])\n f2=True\n except:\n pass\n try:\n folder3_df = pd.read_csv(os.path.abspath(\"folder3\")+\"/\"+files3[i])\n f3=True\n except:\n pass\n if f1 and f2 and f3:\n final_df = pd.concat([folder1_df,folder2_df,folder3_df])\n final_df.to_csv(os.path.abspath(\"final_folder\")+\"/\"+files1[i], index=None)\n print(final_df.shape)\n elif f1 and f3:\n final_df = pd.concat([folder1_df,folder3_df])\n final_df.to_csv(os.path.abspath(\"final_folder\")+\"/\"+files1[i], index=None)\n print(final_df.shape)\n elif f2 and f3:\n final_df = pd.concat([folder2_df,folder3_df])\n final_df.to_csv(os.path.abspath(\"final_folder\")+\"/\"+files2[i], index=None)\n print(final_df.shape)\n elif f1 and f2:\n final_df = pd.concat([folder1_df,folder2_df])\n final_df.to_csv(os.path.abspath(\"final_folder\")+\"/\"+files2[i], index=None)\n print(final_df.shape)\n elif f1:\n final_df = pd.concat([folder1_df])\n final_df.to_csv(os.path.abspath(\"final_folder\")+\"/\"+files1[i], index=None)\n print(final_df.shape)\n elif f2:\n final_df = pd.concat([folder2_df])\n final_df.to_csv(os.path.abspath(\"final_folder\")+\"/\"+files2[i], index=None)\n print(final_df.shape)\n elif f3:\n final_df = pd.concat([folder3_df])\n final_df.to_csv(os.path.abspath(\"final_folder\")+\"/\"+files3[i], index=None)\n print(final_df.shape)\n else:\n print(\"No\")\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74365978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13021743/" ]
74,365,987
<p>I would like to run a powershell script that can be supplied a directory name by the user and then it will check the directory, sub directories, and all file contents of those directories to compare if they are identical to each other. There are 8 servers that should all have identical files and contents. The below code does not appear to be doing what I intended. I have seen the use of Compare-Object, Get-ChildItem, and Get-FileHash but have not found the right combo that I am certain is actually accomplishing the task. Any and all help is appreciated!</p> <pre><code>$35 = &quot;\\server1\&quot; $36 = &quot;\\server2\&quot; $37 = &quot;\\server3\&quot; $38 = &quot;\\server4\&quot; $45 = &quot;\\server5\&quot; $46 = &quot;\\server6\&quot; $47 = &quot;\\server7\&quot; $48 = &quot;\\server8\&quot; do{ Write-Host &quot;|1 : New |&quot; Write-Host &quot;|2 : Repeat|&quot; Write-Host &quot;|3 : Exit |&quot; $choice = Read-Host -Prompt &quot;Please make a selection&quot; switch ($choice){ 1{ $App = Read-Host -Prompt &quot;Input Directory Application&quot; } 2{ #rerun } 3{ exit; } } $c35 = $35 + &quot;$App&quot; +&quot;\*&quot; $c36 = $36 + &quot;$App&quot; +&quot;\*&quot; $c37 = $37 + &quot;$App&quot; +&quot;\*&quot; $c38 = $38 + &quot;$App&quot; +&quot;\*&quot; $c45 = $45 + &quot;$App&quot; +&quot;\*&quot; $c46 = $46 + &quot;$App&quot; +&quot;\*&quot; $c47 = $47 + &quot;$App&quot; +&quot;\*&quot; $c48 = $48 + &quot;$App&quot; +&quot;\*&quot; Write-Host &quot;Comparing Server1 -&gt; Server2&quot; if((Get-ChildItem $c35 -Recurse | Get-FileHash | Select-Object Hash,Path).hash -eq (Get-ChildItem $c36 -Recurse | Get-FileHash | Select-Object Hash,Path).hash){&quot;Identical&quot;}else{&quot;NOT Identical&quot;} Write-Host &quot;Comparing Server1 -&gt; Server3&quot; if((Get-ChildItem $c35 -Recurse | Get-FileHash | Select-Object Hash,Path).hash -eq (Get-ChildItem $c37 -Recurse | Get-FileHash | Select-Object Hash,Path).hash){&quot;Identical&quot;}else{&quot;NOT Identical&quot;} Write-Host &quot;Comparing Server1 -&gt; Server4&quot; if((Get-ChildItem $c35 -Recurse | Get-FileHash | Select-Object Hash,Path).hash -eq (Get-ChildItem $c38 -Recurse | Get-FileHash | Select-Object Hash,Path).hash){&quot;Identical&quot;}else{&quot;NOT Identical&quot;} Write-Host &quot;Comparing Server1 -&gt; Server5&quot; if((Get-ChildItem $c35 -Recurse | Get-FileHash | Select-Object Hash,Path).hash -eq (Get-ChildItem $c45 -Recurse | Get-FileHash | Select-Object Hash,Path).hash){&quot;Identical&quot;}else{&quot;NOT Identical&quot;} Write-Host &quot;Comparing Server1 -&gt; Server6&quot; if((Get-ChildItem $c35 -Recurse | Get-FileHash | Select-Object Hash,Path).hash -eq (Get-ChildItem $c46 -Recurse | Get-FileHash | Select-Object Hash,Path).hash){&quot;Identical&quot;}else{&quot;NOT Identical&quot;} Write-Host &quot;Comparing Server1 -&gt; Server7&quot; if((Get-ChildItem $c35 -Recurse | Get-FileHash | Select-Object Hash,Path).hash -eq (Get-ChildItem $c47 -Recurse | Get-FileHash | Select-Object Hash,Path).hash){&quot;Identical&quot;}else{&quot;NOT Identical&quot;} Write-Host &quot;Comparing Server1 -&gt; Server8&quot; if((Get-ChildItem $c35 -Recurse | Get-FileHash | Select-Object Hash,Path).hash -eq (Get-ChildItem $c48 -Recurse | Get-FileHash | Select-Object Hash,Path).hash){&quot;Identical&quot;}else{&quot;NOT Identical&quot;} } until ($choice -eq 3) </code></pre>
[ { "answer_id": 74366122, "author": "maxxel_", "author_id": 17575465, "author_profile": "https://Stackoverflow.com/users/17575465", "pm_score": 2, "selected": true, "text": "from os import listdir\nimport pandas as pd\n\nfolder_paths = ['put all the folder paths here']\ndf_dict = {'folder': [], 'file': []}\nfor folder_path in folder_paths:\n for file in listdir(folder_path):\n df_dict['folder'].append(folder_path)\n df_dict['file'].append(file)\n\ndf = pd.DataFrame(df_dict)\nfor file, group in df.groupby(df['file']):\n df_temp = pd.DataFrame()\n for folder in group['folder'].tolist():\n df_temp = pd.concat([df_temp, pd.read_csv(f'{folder}/{file}')])\n df_temp.to_csv(f'finalfolder/{file}')\n" }, { "answer_id": 74366573, "author": "Hari", "author_id": 20361389, "author_profile": "https://Stackoverflow.com/users/20361389", "pm_score": 0, "selected": false, "text": "import os\nimport csv as cs\nimport pandas as pd\n\nbase = os.path.abspath('/home/hari/Documents/python/pandas/') #base \ndirectory \nwhere the program saved\n\nprint(os.path.join(base, 'dir1/df1.csv'))\nq = os.path.join(base, 'dir1/df1.csv')\nw = os.path.join(base, 'dir1/df4.csv')\ne = os.path.join(base, 'dir1/df5.csv')\nr = os.path.join(base, 'dir2/df1.csv')\nt = os.path.join(base, 'dir2/df3.csv')\ny = os.path.join(base, 'dir2/df4.csv')\nu = os.path.join(base, 'dir3/df4.csv')\n\ncsv = [q, w, e, r, t, y, u]\n\nfi = pd.concat(map(pd.read_csv, csv), ignore_index=True) #used map \nfunction because of array\n\nprint(fi) #for testing\n\nfinal = open(os.path.join(base, 'final/final.csv'), 'w', encoding='UTF8')\n\nwrite = cs.writer(final) #passing the final file in csv writer\n\nwrite.writerow(fi) #passing the concatenated csv's in writer\n\n#make sure to change the url in base directory\n" }, { "answer_id": 74366849, "author": "Hira ", "author_id": 10440018, "author_profile": "https://Stackoverflow.com/users/10440018", "pm_score": 1, "selected": false, "text": "import os\nfolders_list = ['folder1','folder2','folder3']\nfiles1 = os.listdir(folders_list[0])\nfiles2 = os.listdir(folders_list[1])\nfiles3 = os.listdir(folders_list[2])\n\nmax_files_size =3\nfor i in range(max_files_size):\n f1=False\n f2=False\n f3=False\n try:\n folder1_df = pd.read_csv(os.path.abspath(\"folder1\")+\"/\"+files1[i])\n f1=True\n except:\n pass\n try:\n folder2_df = pd.read_csv(os.path.abspath(\"folder2\")+\"/\"+files2[i])\n f2=True\n except:\n pass\n try:\n folder3_df = pd.read_csv(os.path.abspath(\"folder3\")+\"/\"+files3[i])\n f3=True\n except:\n pass\n if f1 and f2 and f3:\n final_df = pd.concat([folder1_df,folder2_df,folder3_df])\n final_df.to_csv(os.path.abspath(\"final_folder\")+\"/\"+files1[i], index=None)\n print(final_df.shape)\n elif f1 and f3:\n final_df = pd.concat([folder1_df,folder3_df])\n final_df.to_csv(os.path.abspath(\"final_folder\")+\"/\"+files1[i], index=None)\n print(final_df.shape)\n elif f2 and f3:\n final_df = pd.concat([folder2_df,folder3_df])\n final_df.to_csv(os.path.abspath(\"final_folder\")+\"/\"+files2[i], index=None)\n print(final_df.shape)\n elif f1 and f2:\n final_df = pd.concat([folder1_df,folder2_df])\n final_df.to_csv(os.path.abspath(\"final_folder\")+\"/\"+files2[i], index=None)\n print(final_df.shape)\n elif f1:\n final_df = pd.concat([folder1_df])\n final_df.to_csv(os.path.abspath(\"final_folder\")+\"/\"+files1[i], index=None)\n print(final_df.shape)\n elif f2:\n final_df = pd.concat([folder2_df])\n final_df.to_csv(os.path.abspath(\"final_folder\")+\"/\"+files2[i], index=None)\n print(final_df.shape)\n elif f3:\n final_df = pd.concat([folder3_df])\n final_df.to_csv(os.path.abspath(\"final_folder\")+\"/\"+files3[i], index=None)\n print(final_df.shape)\n else:\n print(\"No\")\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74365987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20452783/" ]
74,365,997
<p>I'm Getting some arrays from some wordpress custom fields:</p> <pre><code>$content = array(get_post_meta($postId, 'content')); $media = array(get_post_meta($postId, 'media')); $yt = array(get_post_meta($postId, 'youtube')); </code></pre> <p>I then need to have it printing in sequence, like:</p> <blockquote> <p>media</p> <p>content</p> <p>LInk</p> <p>Embed</p> </blockquote> <p>And repeat the sequence for each value</p> <pre><code>media content LInk Embed </code></pre> <p>For the sequence I'd use this:</p> <pre><code>echo '&lt;ul&gt;'; for ($i = 0; $i &lt; count($all_array['media']); $i++) { for ($j = 0; $j &lt; count($all_array['content']); $j++) { for ($k = 0; $k &lt; count($all_array['youtube']); $k++) { echo '&lt;li&gt;media-&gt;' . $all_array['media'][$i] . '&lt;/li&gt;'; echo '&lt;li&gt;content-&gt;' . $all_array['content'][$j] . '&lt;/li&gt;'; echo '&lt;li&gt;link-&gt;' . $all_array['link'][$k] . '&lt;/li&gt;'; } } } echo '&lt;/ul&gt;'; </code></pre> <p>But I'm doing something wrong with the merging of the 3 fields as if I do a <code>var_dump</code> before to run the <code>for</code> bit, like</p> <pre><code>echo '&lt;pre&gt;' . var_export($all_array, true) . '&lt;/pre&gt;'; </code></pre> <p>Then this is what I get and I cannot iterate as I wish:</p> <pre><code>array ( 0 =&gt; array ( 0 =&gt; array ( 0 =&gt; ' brother ', 1 =&gt; ' Lorem ', 2 =&gt; ' End it ', ), 1 =&gt; array ( 0 =&gt; '337', 1 =&gt; '339', ), 2 =&gt; array ( 0 =&gt; 'https://www.youtube.com/watch?v=94q6fzbJUfg', ), ), ) </code></pre> <p>Literally the layout in html that I'm looking for is:</p> <ol> <li>image</li> <li>content</li> <li>link</li> <li>image</li> <li>content</li> <li>link ...</li> </ol> <p><strong>UPDATE</strong></p> <p>This how I am merging the arrays:</p> <pre><code>foreach ( $content as $idx =&gt; $val ) { $all_array[] = [ $val, $media[$idx], $yt[$idx] ]; } </code></pre> <p>This is the associative array how it looks like:</p> <p>Content:</p> <pre><code> array ( 0 =&gt; array ( 0 =&gt; ' brother ', 1 =&gt; ' Lorem ', 2 =&gt; ' End it ', ), ) </code></pre> <p>Media</p> <pre><code> array ( 0 =&gt; array ( 0 =&gt; '337', 1 =&gt; '339', ), ) </code></pre> <p>Youtube</p> <pre><code> array ( 0 =&gt; array ( 0 =&gt; 'https://www.youtube.com/watch?v=94q6fzbJUfg', ), ) </code></pre>
[ { "answer_id": 74368282, "author": "leighboz", "author_id": 1807307, "author_profile": "https://Stackoverflow.com/users/1807307", "pm_score": -1, "selected": false, "text": "for" }, { "answer_id": 74408336, "author": "rob.m", "author_id": 1018804, "author_profile": "https://Stackoverflow.com/users/1018804", "pm_score": 0, "selected": false, "text": "//GET CUSTOM FIELDS\n $content = get_post_meta($post_to_edit->ID, 'content', false);\n $media = get_post_meta($post_to_edit->ID, 'media', false);\n $yt = get_post_meta($post_to_edit->ID, 'youtube', false);\n $max = max(count($content), count($media), count($yt));\n $combined = [];\n//\n// CREATE CUSTOM FIELDS UNIQUE ARRAY\nfor($i = 0; $i <= $max; $i++) {\n if(isset($media[$i])) {\n $combined[] = [\"type\" => \"media\", \"value\" => $media[$i]];\n }\n if(isset($content[$i])) {\n $combined[] = [\"type\" => \"content\", \"value\" => $content[$i]];\n }\n if(isset($yt[$i])) {\n $combined[] = [\"type\" => \"youtube\", \"value\" => $yt[$i]];\n } \n}\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74365997", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1018804/" ]
74,366,003
<p>Component:</p> <pre><code>const MyComponent = props =&gt; { const {price} = props; const result1 = useResult(price); return ( &lt;div&gt;...&lt;/div&gt; ) } </code></pre> <p>Custom Hook:</p> <pre><code>export const useResult = (price) =&gt; { const [result, setResult] = useState([]); useEffect(() =&gt; { const data = [{price: price}] setResult(data); }, [price]); return result; }; </code></pre> <p>Jest test:</p> <pre><code> it('should ...', async () =&gt; { render( &lt;MyComponent price={300}/&gt;) ) await waitFor(() =&gt; { expect(...).toBeInTheDocument(); }); }); </code></pre> <p>What it does happen with the above code is that <code>MyComponent</code>, <strong>when running the test</strong>, renders only once instead of two (when the application runs). After the initial render where <code>result1</code> is an empty array, <code>useEffect</code> of <code>useResult</code> is running and since there is a state change due to <code>setResult(data)</code>, I should expect <code>MyComponent</code> to be re-rendered. However, that's not the case and <code>result1</code> still equals to <code>[]</code> whereas it should equal to <code>[{price:300}]</code>.</p> <p>Hence, <em>it seems custom hooks under testing behave differently than the real app</em>. I thought it would be okay to test them indirectly through the component that calls them.</p> <p><em><strong>Any explanation/thoughts for the above</strong></em>?</p> <p><em><strong>UPDATE</strong></em></p> <p><em>The issue that invoked the above erroneous behaviour was <strong>state mutation</strong>!! It worked with the app but not with the test! My mistake was to attempt to use <code>push</code> in order to add an element to an array that was a state variable...</em></p>
[ { "answer_id": 74394417, "author": "Letincel", "author_id": 4735563, "author_profile": "https://Stackoverflow.com/users/4735563", "pm_score": -1, "selected": false, "text": "The test will have to be async: it('should ...', async() => { ....\n\nawait screen.findByText('whatever');\nThis is async so it will wait to find whatever and fail if it can't find it\n\nor you can do\nawait waitFor (() => {\n const whatever = screen.getByText('whatever');\n expect(whatever).toBeInTheDocument();\n})\n" }, { "answer_id": 74405121, "author": "Fer Toasted", "author_id": 13772033, "author_profile": "https://Stackoverflow.com/users/13772033", "pm_score": -1, "selected": false, "text": "import { waitFor, screen } from 'testing-library/react'\n\nit('should ...', async () => {\n render(\n <MyComponent price={300}/>)\n )\n \n await waitFor (() => {\n // check that props.price is shown\n screen.debug() // check what's renderered\n expect(screen.getByText(300)).toBeInTheDocument();\n });\n });\n" }, { "answer_id": 74405445, "author": "Ilê Caian", "author_id": 19330762, "author_profile": "https://Stackoverflow.com/users/19330762", "pm_score": 0, "selected": false, "text": "@testing-library" }, { "answer_id": 74415555, "author": "inwerpsel", "author_id": 4961158, "author_profile": "https://Stackoverflow.com/users/4961158", "pm_score": 0, "selected": false, "text": "useEffect" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1642344/" ]
74,366,009
<p><strong>React-native Android Platform building issue</strong></p> <blockquote> <p>The minCompileSdk (31) specified in a dependency's AAR metadata (<code>META-INF/com/android/build/gradle/aar-metadata.properties</code>) is greater than this module's compileSdkVersion (android-30). Dependency: androidx.appcompat:appcompat:1.4.1.</p> </blockquote> <p>I have tried many solutions with Gradle, SDK and many other solutions from GitHub and StackOverflow.</p>
[ { "answer_id": 74366062, "author": "Jemish Rajpara", "author_id": 14434481, "author_profile": "https://Stackoverflow.com/users/14434481", "pm_score": 1, "selected": false, "text": "allprojects {\n configurations.all {\n resolutionStrategy {\n force 'com.facebook.react:react-native:0.65.2' \n //select Version you used\n }\n }\n}\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14434481/" ]
74,366,053
<p>While debugging any iOS application, Xcode builds and run successfully, also launches a simulator but it is not able to attach debugger from Xcode 14 to Simulator iOS app.</p> <p>It throws an error in Xcode:</p> <p><a href="https://i.stack.imgur.com/MtNSd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MtNSd.png" alt="enter image description here" /></a></p> <p>Xcode console says:</p> <blockquote> <p>Could not attach to pid : “75997” Domain: IDEDebugSessionErrorDomain Code: 3 Failure Reason: attach failed (Not allowed to attach to process. Look in the console messages (Console.app), near the debugserver entries, when the attach failed. The subsystem that denied the attach permission will likely have logged an informative message about why it was denied.) User Info: { DVTRadarComponentKey = 855031; IDERunOperationFailingWorker = DBGLLDBLauncher; RawUnderlyingErrorMessage = &quot;attach failed (Not allowed to attach to process. Look in the console messages (Console.app), near the debugserver entries, when the attach failed. The subsystem that denied the attach permission will likely have logged an informative message about why it was denied.)&quot;; }</p> </blockquote> <p>Tried with re-installing Xcode and Command line tools, but issue persists.</p> <p>Steps:</p> <ul> <li>Build and run app with Debug executables true</li> <li>Simulator gets launched</li> <li>Error on Xcode and it gets disconnected from simulator</li> </ul> <p>Is there a possibility that it can be blocked by any other app, if so how to identify ?</p>
[ { "answer_id": 74384803, "author": "Wilson", "author_id": 6933737, "author_profile": "https://Stackoverflow.com/users/6933737", "pm_score": 1, "selected": false, "text": "sudo DevToolsSecurity -enable\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/775896/" ]
74,366,102
<p>I have the below rule for aws dms replication task. It copies rateattribute table from Test schema to target db sync-test schema. But it doesn't add a new column.</p> <pre><code>{ &quot;rules&quot;: [ { &quot;rule-type&quot;: &quot;transformation&quot;, &quot;rule-id&quot;: &quot;929406550&quot;, &quot;rule-name&quot;: &quot;929406550&quot;, &quot;rule-target&quot;: &quot;column&quot;, &quot;rule-action&quot;: &quot;add-column&quot;, &quot;object-locator&quot;: { &quot;schema-name&quot;: &quot;Test&quot;, &quot;table-name&quot;: &quot;rateattribute&quot; }, &quot;value&quot;: &quot;datacheck&quot;, &quot;expression&quot;: &quot;$LastModifiedTime&quot;, &quot;data-type&quot;: { &quot;type&quot;: &quot;string&quot;, &quot;length&quot;: 50 } }, { &quot;rule-type&quot;: &quot;selection&quot;, &quot;rule-id&quot;: &quot;812938400&quot;, &quot;rule-name&quot;: &quot;812938400&quot;, &quot;object-locator&quot;: { &quot;schema-name&quot;: &quot;Test&quot;, &quot;table-name&quot;: &quot;rateattribute&quot; }, &quot;rule-action&quot;: &quot;include&quot;, &quot;filters&quot;: [] }, { &quot;rule-type&quot;: &quot;transformation&quot;, &quot;rule-id&quot;: &quot;852878650&quot;, &quot;rule-name&quot;: &quot;852549480&quot;, &quot;rule-target&quot;: &quot;schema&quot;, &quot;object-locator&quot;: { &quot;schema-name&quot;: &quot;Test&quot; }, &quot;rule-action&quot;: &quot;rename&quot;, &quot;value&quot;: &quot;sync-test&quot;, &quot;old-value&quot;: null } ] } </code></pre> <p>Any help would be really appreciated!</p> <p>When copying data from source sql server to redsfhift, datetime2(7) column getting saved as varchar(37). Am trying to transform it to datetime. So am trying a tweak to add a column first with removing precision from datetime2 column values. Once it works, will add a new column to convert this to datetime</p>
[ { "answer_id": 74384803, "author": "Wilson", "author_id": 6933737, "author_profile": "https://Stackoverflow.com/users/6933737", "pm_score": 1, "selected": false, "text": "sudo DevToolsSecurity -enable\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17991267/" ]
74,366,132
<p>I need a type/interface to define a property that can be object or an array. The problem with typescript <code>|</code> operator is that if I use it I will have to explicitly check each time if the variable is array or not but I always know if its an object or an array. So instead I ended up using <code>as SomeType</code> or <code>as SomeType[]</code>. What I want is to not have to do it.</p> <p>So current idea is to create a mixture of object and array, so that instead of array checks or &quot;as&quot; assertions I will have to add <code>?.</code> everywhere.</p> <p>My current solution is</p> <pre><code>interface _Array&lt;T&gt; extends Array&lt;T | undefined&gt; {} type ArrayORObject&lt;T&gt; = Partial&lt;T&gt; &amp; Partial&lt;_Array&lt;T&gt;&gt;; </code></pre> <p>Which almost works but the only issue is that now I'm getting &quot;Index signature for type 'number' is missing in type SomeObject&quot;, seems that it requires objects to have Array index signature ([index: number]), but I can't figure out if its possible to have optional index signature.</p> <p>Edit: Thanks for suggesting &quot;satisfies&quot; but bumping TS to beta version not really an option rn. adding call to makeOrder() isn't much better then creating some function that will check if array.</p> <p>Better example <a href="https://www.typescriptlang.org/play?ts=4.4.4#code/JYOwLgpgTgZghgYwgAgEYFcoHNrIN4BQyxyAthHGAFzIDOYUoWA3ESQG4RZbAS0D8NeoxBYA2gF1WJOgHt0tCILoMmrAL4ECoSLEQpZUACa5CMwyagAVAJ4AHCDQDktJgBsIT5AB9kTo-KoHl6+TvBubqiIANYhfgCO6HBGjHbBPn6k6G5gwHEu7hAAtAEY6aGl2cUB6EGeGU6qadWB5QlJKcDNTtIkpHCgNACCUFBwNgDyAEoTqABWEAhgADwY2NAAfL3EtLJGcMojY5Mz84srwkxbBJoEMOggS8CyIMgBAMpg6DAwABSgdnQ1GQUwoARAbhsywsmwAlDQYVAMg8TDBQBAjPg2DsAO7AMAIAAWyH+IEBYAAdIjbA5YViZDIEHBFH5XKJglRsQyZFAIF8oK82VgPBNjNAABJwEBGDxQUnk2HbBlMllOLI5PKc7nc3n817q3KiyyS6Wy+VAxVcmSouDZahW7W6zAgJW3W4AendyAAkshoiBZDjkGBCZQyANXsBaMhZGclncHk8XnRCkaJVKZdBzcDQckXpDoWKoBt4TGi-SSE6BRXuRS6wCgQAaB3EfqDGva4h1ikNyltkDNzsyciUZzhOAwCBuJwt5CaGTqDRaT0+v0BoMhsP95BR5BwUbjBOPXLJg3ANNQE2ZuW9mi58EFxElhHlswkBAvejIcKRGIAIUwHAkQAXmQHAwAAMTgCIogQaJfktRlPzAb9gAiXQMWQUDewpfsKTRHJoH4ClflQLCNjQYiRxQgBCYDQKcVAIAgGAnDpfh+GQSQlSrV431resySbWd+xoAjCN5IwKQ8UQQ2QCiAAZkE48SMMxMToN-OCAPWKAuUXG4tHuY9nlecCoJgmIEJoNYgI7Xj8DIChgScIlgDgiAQC8Azbg-EAv0RABGF9LCwjtqXsRxWUKJxBz6CMaDwJzRz8JiWO8wyPi+H5fiCy0CD8gKiwAJhC3BQP4stLBpKK1TtPI4tbBKuKS6jnDS1i50bRy2tS5jOvUCRMtkT5vj+RFivylcAFkAE1kCsKZZu0cBoHgJBkAAfSOcZlisCiIAAD0gaVox2qErGRaUWPRIwKLwTQwEi5BzumWYFiWPaKNAgAFfdcmgr7kAAMmQP6oABtxlm2g8Lo2LYgA" rel="nofollow noreferrer">TS Playground</a></p>
[ { "answer_id": 74366793, "author": "Lesiak", "author_id": 1570854, "author_profile": "https://Stackoverflow.com/users/1570854", "pm_score": 2, "selected": false, "text": "satisfies" }, { "answer_id": 74366816, "author": "Dimava", "author_id": 5734961, "author_profile": "https://Stackoverflow.com/users/5734961", "pm_score": 0, "selected": false, "text": "if" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20452864/" ]
74,366,166
<p>I've been researching like mad and have used this property before, but it is just not working for me. It just displays as already rotated.</p> <p>I suspect it's an issue with my browser, but just wanted to check that my code was ok.</p> <p>Thanks!</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>.logosmall { width: 50%; border-radius: 50%; transform: rotate(420deg) scale(1.8); transition: all 0.3s ease-in-out 0s; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;table&gt; &lt;tr&gt; &lt;td&gt; &lt;img src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" class="logosmall" /&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74366238, "author": "Justinas", "author_id": 1346234, "author_profile": "https://Stackoverflow.com/users/1346234", "pm_score": 2, "selected": false, "text": "@keyframes" }, { "answer_id": 74367292, "author": "George Batty", "author_id": 5936256, "author_profile": "https://Stackoverflow.com/users/5936256", "pm_score": 0, "selected": false, "text": ".logosmall:hover{transform: rotate(420deg); scale(1.8); transition: all 0.3s ease-in-out 0s;}\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5936256/" ]
74,366,179
<p>I'm developing a custom shell. In this assignment, I need to implement uniq-like command. Given sorted lines, <em>uniq</em> should be able to print all unique values and (their number of occurences if the command is <strong>uniq -c</strong>). Example code is stated at the very end.</p> <p>I have no problem with the algorithm. I wrote a function which can do take exactly same operation with desired one. However, the problem is that, what are these types of outputs and inputs? I mean when I command <em>cat input.txt</em>, are these lines just one string or are they given in array? As I said, algorithm is ok but I do not know how to apply that correct algorithm in the shell? Any help or idea is appreciated.</p> <pre><code>$cat input.txt Cinnamon Egg Egg Flour Flour Flour Milk Milk </code></pre> <pre><code>$cat input.txt | uniq Cinnamon Egg Flour Milk </code></pre>
[ { "answer_id": 74366238, "author": "Justinas", "author_id": 1346234, "author_profile": "https://Stackoverflow.com/users/1346234", "pm_score": 2, "selected": false, "text": "@keyframes" }, { "answer_id": 74367292, "author": "George Batty", "author_id": 5936256, "author_profile": "https://Stackoverflow.com/users/5936256", "pm_score": 0, "selected": false, "text": ".logosmall:hover{transform: rotate(420deg); scale(1.8); transition: all 0.3s ease-in-out 0s;}\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18747531/" ]
74,366,194
<p>I'm using react and context: When I fetch items and there is no data, I send null. null becomes undefined (within res.send). In my reducer, I use spread operator when new items are being added. That results in an err as I'm trying to spread undefined (when there is no items yet and later added its first undefined).</p> <p>What is good practice and what should I do in this case to change undefined into an empty array or so? Thank you</p> <pre class="lang-js prettyprint-override"><code>const initialState = { isFetchingItems: null, items: [], fetchErrorMessage: null } const reducer = (state, action) =&gt; { switch (action.type) { case 'FETCH_ITEMS': return { ...state, isFetching: true } case 'FETCH_ITEMS_SUCCESS': return { ...state, items: action.payload.messages, isFetching: false } case 'FETCH_ITEMS_ERROR': return { ...state, fetchErrorMessage: action.payload, isFetching: false } case 'ADD_ITEMS_SUCCESS': return { ...state, items: [action.payload, ...state.items] // here the err comes from as its like [action.payload, ...undefined] } default: return state; } }; </code></pre> <p>My action:</p> <pre class="lang-js prettyprint-override"><code>const fetchItems = async() =&gt; { dispatch({ type: 'FETCH_ITEMS' }) try { let items = await API.fetchItems(); dispatch({ type: 'FETCH_Items_SUCCESS', payload: items }) } catch (error) { dispatch({ type: 'FETCH_ITEMS_ERROR', payload: error.message }) } }; const fetchItems = async() =&gt; { // ... dispatch({ type: 'ADD_ITEMS_SUCCESS', payload: items }) // ... } </code></pre>
[ { "answer_id": 74366212, "author": "caTS", "author_id": 18244921, "author_profile": "https://Stackoverflow.com/users/18244921", "pm_score": 4, "selected": true, "text": "[action.payload, ...(state.items ?? [])]\n" }, { "answer_id": 74371502, "author": "Drew Reese", "author_id": 8690857, "author_profile": "https://Stackoverflow.com/users/8690857", "pm_score": 2, "selected": false, "text": "items" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6377312/" ]
74,366,204
<p>I have a list of items containing unique and repeating IDs, I want to sum the prices and display the number of the repeating IDs</p> <pre><code>class Model{ int id,price,count; Model(this.id,this.price,this.count); } List&lt;Model&gt; list1 = [ Model(1,5000,10), Model(2,1000,20), Model(1,5000,5), Model(2,5000,10), ]; List&lt;Model&gt; list2 = []; </code></pre> <p>I need the second list to be like this</p> <pre><code> list2 = [ Model(1,10000,15), Model(2,6000,30), ]; </code></pre>
[ { "answer_id": 74366444, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 1, "selected": false, "text": "void main() {\n int sum = 0;\n\n List<Model> list1 = [\n Model(1, 5000, 10),\n Model(2, 1000, 20),\n Model(1, 5000, 5),\n Model(2, 5000, 10),\n ];\n\n List<Model> list2 = modelsWithoutRepeatingIdsButSumOfPricesAndAmount(\n list1); // [Model(1,10000,15), Model(2,6000,30),]\n}\n\nList<Model> modelsWithoutRepeatingIdsButSumOfPricesAndAmount(\n List<Model> modelList) {\n Map<int, Model> map = {};\n\n for (int index = 0; index < modelList.length; index += 1) {\n Model current = modelList[index];\n map[current.id] ??= Model(current.id, 0, 0);\n map[current.id]!.price += current.price;\n map[current.id]!.count += current.count;\n }\n\n return map.values.toList();\n}\n\nclass Model {\n int id, price, count;\n Model(this.id, this.price, this.count);\n}\n" }, { "answer_id": 74366447, "author": "Pawan", "author_id": 15514420, "author_profile": "https://Stackoverflow.com/users/15514420", "pm_score": 0, "selected": false, "text": "var total = [1, 2, 3].reduce((a, b) => a + b);\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12034196/" ]
74,366,207
<p>Objective: From a time-series df, make a plot of each occurrence of a particular state (or factor level) with x timepoints before, and y timepoints after, the onset (i.e. first row) of that state. The graph should be centered on zero (on the x-axis), such that the x timepoints before the event are negative values, and the y timepoints after the event are positive values. This is the same principal as a peristimulus time histogram.</p> <p>The data: I have time-series data where different states can occur for variable amounts of time. First I use run length encoding (rle) to determine the start and stop of each run of each state (not shown). Second, I use a function, <a href="https://stackoverflow.com/questions/13155609/returning-above-and-below-rows-of-specific-rows-in-r-dataframe/13155669#13155669">similar to the one described here</a>, to return, say one row above and two rows below the onset of a particular state (state &quot;A&quot; in the example below). Here’s what that data looks like.</p> <pre><code>df &lt;- data.frame( state = c(&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;B&quot;,&quot;A&quot;,&quot;A&quot;,&quot;X&quot;,&quot;Y&quot;,&quot;Z&quot;,&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;B&quot;,&quot;A&quot;,&quot;A&quot;), start = c(&quot;start&quot;,&quot;NA&quot;,&quot;NA&quot;,&quot;NA&quot;,&quot;NA&quot;,&quot;NA&quot;,&quot;start&quot;,&quot;NA&quot;,&quot;NA&quot;,&quot;NA&quot;,&quot;NA&quot;,&quot;start&quot;,&quot;NA&quot;,&quot;NA&quot;,&quot;NA&quot;,&quot;start&quot;,&quot;NA&quot;), rleGroup = c(&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;2&quot;,&quot;3&quot;,&quot;3&quot;,&quot;4&quot;,&quot;5&quot;,&quot;6&quot;,&quot;7&quot;,&quot;7&quot;,&quot;7&quot;,&quot;8&quot;,&quot;9&quot;,&quot;9&quot;), data = runif(17) ) df &lt;- df %&gt;% tidyr::unite(stateStart, c(state,start), sep = &quot;.&quot;, remove = FALSE) stateStart state start rleGroup data 1 A.start A start 1 0.85118187 2 A.NA A NA 1 0.23502147 3 A.NA A NA 1 0.97435662 4 A.NA A NA 1 0.45669042 5 A.NA A NA 1 0.48271803 6 B.NA B NA 2 0.80561653 7 A.start A start 3 0.27228361 8 A.NA A NA 3 0.07008506 9 X.NA X NA 4 0.44101076 10 Y.NA Y NA 5 0.95173954 11 Z.NA Z NA 6 0.65693316 12 A.start A start 7 0.45831802 13 A.NA A NA 7 0.83629347 14 A.NA A NA 7 0.62107270 15 B.NA B NA 8 0.53294588 16 A.start A start 9 0.08533221 17 A.NA A NA 9 0.28805362 extract.with.context &lt;- function(x, colname, rows, after = 0, before = 0) { match.idx &lt;- which(x[[colname]] %in% rows) span &lt;- seq(from = -before, to = after) extend.idx &lt;- c(outer(match.idx, span, `+`)) extend.idx &lt;- Filter(function(i) i &gt; 0 &amp; i &lt;= nrow(x), extend.idx) extend.idx &lt;- sort(unique(extend.idx)) return(x[extend.idx, , drop = FALSE]) } extracted = extract.with.context(x=df, colname=&quot;stateStart&quot;, rows=c(&quot;A.start&quot;), after = 2, before = 1) stateStart state start rleGroup data 1 A.start A start 1 0.85118187 2 A.NA A NA 1 0.23502147 3 A.NA A NA 1 0.97435662 6 B.NA B NA 2 0.80561653 7 A.start A start 3 0.27228361 8 A.NA A NA 3 0.07008506 9 X.NA X NA 4 0.44101076 11 Z.NA Z NA 6 0.65693316 12 A.start A start 7 0.45831802 13 A.NA A NA 7 0.83629347 14 A.NA A NA 7 0.62107270 15 B.NA B NA 8 0.53294588 16 A.start A start 9 0.08533221 17 A.NA A NA 9 0.28805362 </code></pre> <p>The problem: I want to plot each extracted run of state A (i.e., one timepoint before and two timepoints after A.start). One thought is to make a unique identifier for each run grouping of state &quot;A&quot; (Question 1), and then make a time sequence counter that reflects the desired rows before and after the onset of state A (Question 2).</p> <p>QUESTION NUMBER 1. Create a unique identifier for each &quot;plotGroup&quot;, defined as each run of state A (i.e., a row before A.start and two rows after A.start) I tried this, but it's not quite working</p> <p>extracted %&gt;% mutate(plotGroup = cumsum(lag(state) == &quot;A&quot; &amp; state != &quot;A&quot;))</p> <p>it should look like this</p> <pre><code>extracted$plotGroup &lt;- c(&quot;0&quot;,&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;2&quot;,&quot;2&quot;,&quot;2&quot;,&quot;2&quot;,&quot;3&quot;,&quot;3&quot;,&quot;3&quot;) stateStart state start rleGroup data plotGroup 1 A.start A start 1 0.85118187 0 2 A.NA A NA 1 0.23502147 0 3 A.NA A NA 1 0.97435662 0 6 B.NA B NA 2 0.80561653 1 7 A.start A start 3 0.27228361 1 8 A.NA A NA 3 0.07008506 1 9 X.NA X NA 4 0.44101076 1 11 Z.NA Z NA 6 0.65693316 2 12 A.start A start 7 0.45831802 2 13 A.NA A NA 7 0.83629347 2 14 A.NA A NA 7 0.62107270 2 15 B.NA B NA 8 0.53294588 3 16 A.start A start 9 0.08533221 3 17 A.NA A NA 9 0.28805362 3 </code></pre> <p>QUESTION NUMBER 2. Create a &quot;counter,&quot; centered on zero, of one row above and two rows after the A.start This I have no idea how to do! But presumably can make use of &quot;span&quot; in the function This is my desired output</p> <pre><code>extracted$span &lt;- c(&quot;0&quot;,&quot;1&quot;,&quot;2&quot;,&quot;-1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;2&quot;,&quot;-1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;2&quot;,&quot;-1&quot;,&quot;0&quot;,&quot;1&quot;) stateStart state start rleGroup data plotGroup span 1 A.start A start 1 0.85118187 0 0 2 A.NA A NA 1 0.23502147 0 1 3 A.NA A NA 1 0.97435662 0 2 6 B.NA B NA 2 0.80561653 1 -1 7 A.start A start 3 0.27228361 1 0 8 A.NA A NA 3 0.07008506 1 1 9 X.NA X NA 4 0.44101076 1 2 11 Z.NA Z NA 6 0.65693316 2 -1 12 A.start A start 7 0.45831802 2 0 13 A.NA A NA 7 0.83629347 2 1 14 A.NA A NA 7 0.62107270 2 2 15 B.NA B NA 8 0.53294588 3 -1 16 A.start A start 9 0.08533221 3 0 17 A.NA A NA 9 0.28805362 3 1 </code></pre> <p>Ultimate objective: plot data by span for each individual plotgroup</p> <pre><code>ggplot(data=extracted, aes(x=span, y = data, group = plotGroup)) + geom_line() </code></pre> <p><a href="https://i.stack.imgur.com/7tvYD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7tvYD.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74366444, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 1, "selected": false, "text": "void main() {\n int sum = 0;\n\n List<Model> list1 = [\n Model(1, 5000, 10),\n Model(2, 1000, 20),\n Model(1, 5000, 5),\n Model(2, 5000, 10),\n ];\n\n List<Model> list2 = modelsWithoutRepeatingIdsButSumOfPricesAndAmount(\n list1); // [Model(1,10000,15), Model(2,6000,30),]\n}\n\nList<Model> modelsWithoutRepeatingIdsButSumOfPricesAndAmount(\n List<Model> modelList) {\n Map<int, Model> map = {};\n\n for (int index = 0; index < modelList.length; index += 1) {\n Model current = modelList[index];\n map[current.id] ??= Model(current.id, 0, 0);\n map[current.id]!.price += current.price;\n map[current.id]!.count += current.count;\n }\n\n return map.values.toList();\n}\n\nclass Model {\n int id, price, count;\n Model(this.id, this.price, this.count);\n}\n" }, { "answer_id": 74366447, "author": "Pawan", "author_id": 15514420, "author_profile": "https://Stackoverflow.com/users/15514420", "pm_score": 0, "selected": false, "text": "var total = [1, 2, 3].reduce((a, b) => a + b);\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3448338/" ]
74,366,230
<p>I often get a list of names I need to update in a table from an Excel list, and I end up creating a SSIS program to reads the file into a staging table and doing it that way. But is there I way I could just copy and past the names into a table from Management Studio directly? Something like this:</p> <pre><code>create table #temp (personID int, userName varchar(15)) Insert Into #temp (userName) values ( 'kmcenti1', 'ladams5', 'madams3', 'haguir1', ) </code></pre> <p>Obviously this doesn't work but I've tried different variations and nothing seems to work.</p>
[ { "answer_id": 74366291, "author": "Stu", "author_id": 15332650, "author_profile": "https://Stackoverflow.com/users/15332650", "pm_score": 1, "selected": false, "text": "create table #temp (personID int identity(1,1), userName varchar(15))\ninsert into #temp (userName)\nselect n from (values \n('kmcenti1'),\n('ladams5'),\n('madams3'),\n('haguir1'))x(n);\n" }, { "answer_id": 74366299, "author": "KeithL", "author_id": 3325290, "author_profile": "https://Stackoverflow.com/users/3325290", "pm_score": 0, "selected": false, "text": "=\"('\"&A1&\"'),\"\n" }, { "answer_id": 74366445, "author": "John Cappelletti", "author_id": 1570000, "author_profile": "https://Stackoverflow.com/users/1570000", "pm_score": 3, "selected": true, "text": "Declare @List varchar(max) = '\nkmcenti1\nladams5\nmadams3\nhaguir1\n'\n\nInsert into #Temp (userName)\nSelect username=value\n From string_split(replace(@List,char(10),''),char(13))\n Where Value <>''\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2410605/" ]
74,366,239
<p>If you're using JS, the documentation works well. But in case of angular I would prefer to handle observables instead of promises. The problem is that this kind of promise has a handler. I tried many approaches listed below but nothing seems to work.</p> <pre><code>from(listen(&quot;click&quot;, v =&gt; v)) </code></pre> <pre><code>let x = async() =&gt; listen(&quot;click&quot;, v =&gt; v) </code></pre> <p>Does anyone know how to convert this kind of event to an <code>Observable</code>?</p> <p>The response is always this:</p> <pre><code>function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, &quot;next&quot;, value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, &quot;throw&quot;, err); } _next(undefined); }); } </code></pre>
[ { "answer_id": 74366345, "author": "Tobias S.", "author_id": 8613630, "author_profile": "https://Stackoverflow.com/users/8613630", "pm_score": 2, "selected": true, "text": "Observable" }, { "answer_id": 74366848, "author": "Jean-Paul Abi-Ghosn", "author_id": 13203815, "author_profile": "https://Stackoverflow.com/users/13203815", "pm_score": 0, "selected": false, "text": "import {from, map, Observable, ObservableInput, ObservedValueOf} from \"rxjs\";\nimport {emit, listen, Event} from \"@tauri-apps/api/event\";\n\nexport function tauriListen(listenerName: string): Observable<any> {\n return new Observable<any>((subscriber) => {\n // return from(listen(listenerName, v => subscriber.next(v))).subscribe()\n const unlisten = listen(listenerName, v => subscriber.next(v))\n return async () => {\n (await unlisten)()\n }\n }).pipe(\n map((response: Event<any>) => response.payload)\n );\n}\n\nexport function tauriEmit(emitterName: string, payload: any) {\n return from(emit(emitterName, payload));\n}\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13203815/" ]
74,366,252
<p>I am attempting to build a script that will request information (Hostname, MAC, IP, Caption (os version), and serial number using a list of computers pulled from AD.</p> <p>This works but it creates multiple lines/rows when instead I need all this information on one row. Yes I am a noob at this.. I can write a script for a single machine just fine but getting that same script to work with a list remotely eludes me, this script allows me to get the information but not on the same row.!!</p> <p>I am using PW version 5.1</p> <p>Here it is;</p> <pre><code>Function Get-CInfo { $ComputerName = Get-Content C:\Users\scott.hoffman.w.tsc\Desktop\scripts\get-cinfo-tools\comp-list.txt $ErrorActionPreference = 'Stop' foreach ($Computer in $ComputerName) { Try { gwmi -class &quot;Win32_NetworkAdapterConfiguration&quot; -cn $Computer | ? IpEnabled -EQ &quot;True&quot; | select DNSHostName, MACAddress, IPaddress | FT -AutoSize gwmi win32_operatingsystem -cn $computer | select Caption | FT -Autosize Get-WmiObject win32_bios -cn $computer | select Serialnumber | FT -Autosize } Catch { Write-Warning &quot;Can't Touch This : $Computer&quot; } }#End of Loop }#End of the Function Get-CInfo &gt; comp-details.txt </code></pre> <p>the comp-list.txt file is just;</p> <p>computername01 computername02</p> <p>I would love to use csv from input to output but I get lost.</p> <p>Thanks for your help/input/kick in the pants!</p>
[ { "answer_id": 74366345, "author": "Tobias S.", "author_id": 8613630, "author_profile": "https://Stackoverflow.com/users/8613630", "pm_score": 2, "selected": true, "text": "Observable" }, { "answer_id": 74366848, "author": "Jean-Paul Abi-Ghosn", "author_id": 13203815, "author_profile": "https://Stackoverflow.com/users/13203815", "pm_score": 0, "selected": false, "text": "import {from, map, Observable, ObservableInput, ObservedValueOf} from \"rxjs\";\nimport {emit, listen, Event} from \"@tauri-apps/api/event\";\n\nexport function tauriListen(listenerName: string): Observable<any> {\n return new Observable<any>((subscriber) => {\n // return from(listen(listenerName, v => subscriber.next(v))).subscribe()\n const unlisten = listen(listenerName, v => subscriber.next(v))\n return async () => {\n (await unlisten)()\n }\n }).pipe(\n map((response: Event<any>) => response.payload)\n );\n}\n\nexport function tauriEmit(emitterName: string, payload: any) {\n return from(emit(emitterName, payload));\n}\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20453039/" ]
74,366,263
<p>I have an array that stores the ID and Placeholder title of a new component every time the button &quot;Create a list&quot; is clicked. I am trying to make sure that there are no duplicated ID's. Essentially I just want check that the ID doesn't already exist, and if it does; to create a new one.</p> <p>My code is below:</p> <p><strong>ElementContext.js:</strong></p> <pre><code>import React, { createContext, useState } from 'react'; import Todobox from './components/Todobox'; export const ElementContext = createContext(); export const ElementContextProvider = ({children}) =&gt; { const [elements, setElements] = useState([]); const [elementId, setElementId] = useState(1); const newElementId = (elements) =&gt;{ const newId = Math.floor(Math.random()*100).toString(); setElementId(newId) } const newElement = () =&gt;{ newElementId(); setElements((prev) =&gt; [...prev, {title: 'Placeholder', id:elementId}]) console.log(elements) }; const value = { elements, setElements, newElement, newElementId, elementId }; return( &lt;ElementContext.Provider value={value}&gt; {children} &lt;/ElementContext.Provider&gt; ) }; </code></pre> <p><strong>HomePage.jsx:</strong></p> <pre><code>import react from 'react'; import { useContext } from 'react'; import '../App.css'; import Todobox from './Todobox'; import { ElementContext } from '../ElementContext'; export default function HomePage(){ const { elements, setElements, newElement, elementsId } = useContext(ElementContext); return( &lt;div className='page-container'&gt; &lt;div className='header'&gt; &lt;a className='header-title'&gt;Trello Clone!&lt;/a&gt; &lt;a className='header-button' onClick={newElement}&gt;Create a list&lt;/a&gt; &lt;/div&gt; &lt;div className='element-field'&gt; {elements.length !== 0 &amp;&amp; elements.map((elements, newElementId) =&gt; &lt;Todobox key={newElementId} /&gt;)} &lt;/div&gt; &lt;/div&gt; ) } </code></pre>
[ { "answer_id": 74366345, "author": "Tobias S.", "author_id": 8613630, "author_profile": "https://Stackoverflow.com/users/8613630", "pm_score": 2, "selected": true, "text": "Observable" }, { "answer_id": 74366848, "author": "Jean-Paul Abi-Ghosn", "author_id": 13203815, "author_profile": "https://Stackoverflow.com/users/13203815", "pm_score": 0, "selected": false, "text": "import {from, map, Observable, ObservableInput, ObservedValueOf} from \"rxjs\";\nimport {emit, listen, Event} from \"@tauri-apps/api/event\";\n\nexport function tauriListen(listenerName: string): Observable<any> {\n return new Observable<any>((subscriber) => {\n // return from(listen(listenerName, v => subscriber.next(v))).subscribe()\n const unlisten = listen(listenerName, v => subscriber.next(v))\n return async () => {\n (await unlisten)()\n }\n }).pipe(\n map((response: Event<any>) => response.payload)\n );\n}\n\nexport function tauriEmit(emitterName: string, payload: any) {\n return from(emit(emitterName, payload));\n}\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20422283/" ]
74,366,264
<p>I'm creating a Vue3 web app and I was wondering what is the best way to pass data from parent to nested components (more specific, from parent to child of children).</p> <p>Let's say I have this schema:</p> <pre><code> Card | | CardHeader CardBody | | BodyHeader BodyParams BodyResponse </code></pre> <p>And I want to know the best way to pass data from Card to BodyHeader, BodyParams and BodyResponse</p> <p>On <code>Card Component</code> I will be fetching some data from an API. Lets say that i fetch a json like this:</p> <pre><code>{ header: { title: 'hello header' }, body: { headers: ['authorization', 'anotherheader'] params: ['currency', 'hair'], response: ['200', '401'] } } </code></pre> <p>I know I just could do this:</p> <p><code>&lt;Card/&gt;</code> :</p> <pre><code>&lt;template&gt; &lt;CardHeader :header=&quot;hedaer&quot;&gt;&lt;/CardHeader&gt; &lt;CardBody :body=&quot;body&quot;&gt;&lt;/CardBody&gt; &lt;/template&gt; </code></pre> <p>Then, in <code>&lt;CardBody/&gt;</code> :</p> <pre><code>&lt;template&gt; &lt;CardBodyHeader :headers=&quot;body.headers&quot;&gt;&lt;/CardBodyHeader&gt; &lt;CardBodyParams :params=&quot;body.params&quot;&gt;&lt;/CardBodyParams&gt; &lt;CardBodyResponse :responses=&quot;body.responses&quot;&gt;&lt;/CardBodyResponse&gt; &lt;/template&gt; &lt;script&gt; import CardBodyHeader from &quot;./CardBodyHeader.vue&quot;; import CardBodyParams from &quot;./CardBodyParams.vue&quot;; import CardBodyResponse from &quot;./CardBodyResponse.vue&quot;; export default { components: { CardBodyHeader, CardBodyParams, CardBodyResponse }, props: { body: {type: Object} } }; &lt;/script&gt; </code></pre> <p>But I don't know if that would be the optimal solution.</p> <pre><code></code></pre>
[ { "answer_id": 74366333, "author": "Mina", "author_id": 11887902, "author_profile": "https://Stackoverflow.com/users/11887902", "pm_score": 0, "selected": false, "text": "Vuex" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20453029/" ]
74,366,274
<p>I'm trying to create a github action but I need to use an internal nuget package</p> <pre><code> - name: &quot;Setup Internal Packages&quot; run: | dotnet nuget add source ${{ secrets.artifactory_url }} \ -n myinternalpack \ -u ${{ secrets.artifactory_user }} \ -p ${{ secrets.artifactory_token }} \ --store-password-in-clear-text </code></pre> <p>When I run this step it says <code>Package source with Name: myinternalpack added successfully.</code></p> <p>I even make sure with the next step to list sources:</p> <pre><code>Run dotnet nuget list source Registered Sources: 1. nuget.org [Enabled] https://api.nuget.org/v3/index.json 2. myinternalpack [Enabled] *** </code></pre> <p>But when I try to do a restore</p> <pre><code>dotnet restore ./sample-app --source myinternalpack --source https://api.nuget.org/v3/index.json </code></pre> <p>It says it doesn't exist.</p>
[ { "answer_id": 74366333, "author": "Mina", "author_id": 11887902, "author_profile": "https://Stackoverflow.com/users/11887902", "pm_score": 0, "selected": false, "text": "Vuex" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15056431/" ]
74,366,280
<p>Here is a Rest Api method that sets the user rating. The database table contains the composite primary key: <code>user_id</code> + <code>rate_id</code>.</p> <p>When user tries to set the same rating the framework throws an exception. I catch it and return response.</p> <p>How to handle such these cases and make the method idempotent?</p>
[ { "answer_id": 74366333, "author": "Mina", "author_id": 11887902, "author_profile": "https://Stackoverflow.com/users/11887902", "pm_score": 0, "selected": false, "text": "Vuex" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20452649/" ]
74,366,293
<p>How to plot graph for 1:8 attributes using altair? Here is the <a href="http://archive.ics.uci.edu/ml/machine-learning-databases/00292/Wholesale%20customers%20data.csv" rel="nofollow noreferrer">link</a> to the dataset. I want to plot an interactive mark_point() graph for various attributes like fresh, frozen, etc, considering the region and channel as filters. The x-axis should have attributes, and the y-axis will have the count.</p> <p>The interaction is based on region and channel to show the values of user buying from distributor.</p> <p>I am not able to plot the 8 attributes on a single graph. I tried transforming the df into a dictionary and then using the same to plot the graph. but unsuccessful.</p>
[ { "answer_id": 74366333, "author": "Mina", "author_id": 11887902, "author_profile": "https://Stackoverflow.com/users/11887902", "pm_score": 0, "selected": false, "text": "Vuex" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20453099/" ]
74,366,298
<p>Sorry my English is not good) So I was repeating after tutorial and the tutor wrote a:link and gave a property color:red; but when i did so it didn't change it's color here is html:</p> <pre><code>&lt;nav class=&quot;clearfix&quot;&gt; &lt;ul class=&quot;navigation&quot;&gt; &lt;li&gt;&lt;a href=&quot;&quot; class=&quot;huy&quot;&gt;About us&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;&quot; class=&quot;huy&quot;&gt;Pricing&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;&quot; class=&quot;huy&quot;&gt;Contact&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;div class=&quot;button&quot;&gt; &lt;a href=&quot;&quot; class=&quot;btn-main&quot;&gt;Sign up&lt;/a&gt; &lt;a href=&quot;&quot; class=&quot;btn-hot&quot;&gt;Get a quote&lt;/a&gt; &lt;/div&gt; &lt;/nav&gt; </code></pre> <p>and SCSS:</p> <pre><code>.navigation{ list-style-type: none; float: left; li{ display: inline-block; margin-left: 30px; &amp;:first-child{ margin: 0; } a:link{ color: red; } } } </code></pre> <p>I wanted a to change it's color</p>
[ { "answer_id": 74366385, "author": "Emile Youssef FEGHALI EL", "author_id": 19603779, "author_profile": "https://Stackoverflow.com/users/19603779", "pm_score": -1, "selected": true, "text": "href" }, { "answer_id": 74366389, "author": "Tymon Jasiukiewicz", "author_id": 16631771, "author_profile": "https://Stackoverflow.com/users/16631771", "pm_score": 0, "selected": false, "text": "<nav class=\"clearfix\">\n <ul class=\"navigation\">\n <li><a href=\"...\" class=\"huy\">About us</a></li>\n <li><a href=\"...\" class=\"huy\">Pricing</a></li>\n <li><a href=\"...\" class=\"huy\">Contact</a></li>\n </ul>\n <div class=\"button\">\n <a href=\"...\" class=\"btn-main\">Sign up</a>\n <a href=\"...\" class=\"btn-hot\">Get a quote</a>\n </div>\n</nav>\n" }, { "answer_id": 74366562, "author": "MN_XD", "author_id": 18037338, "author_profile": "https://Stackoverflow.com/users/18037338", "pm_score": 0, "selected": false, "text": "a{\n color: red;\n}\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20381377/" ]
74,366,350
<p>I'm trying to get the version of the app from the jenkins log to send it to email.</p> <p>The log (part of it) is:</p> <pre><code>[INFO] Image 03127cdb479b: Layer already exists [INFO] Image 9c742cd6c7a5: Layer already exists [INFO] Image 1f8a8b50f407: Pushing [INFO] Image 1f8a8b50f407: Pushed [INFO] 4.2.3-202211071000: digest: sha256:[large_number] size: 2415 [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ </code></pre> <p>I want only the <strong>4.2.3-202211071000</strong> part, so I'm doing:</p> <pre><code>${BUILD_LOG_REGEX, regex=&quot;(?&lt;=\[INFO])(.*)(?=: digest)&quot;, maxMatches=1, showTruncatedLines=false, substText=&quot;$1&quot;} </code></pre> <p>but this is returning the entire line:</p> <pre><code>[INFO] 4.2.3-202211071000: digest: sha256:[large_number] size: 2415 </code></pre> <p>not only the text between &quot;[INFO] &quot; and &quot;: digest&quot;. How can I do that?</p>
[ { "answer_id": 74366385, "author": "Emile Youssef FEGHALI EL", "author_id": 19603779, "author_profile": "https://Stackoverflow.com/users/19603779", "pm_score": -1, "selected": true, "text": "href" }, { "answer_id": 74366389, "author": "Tymon Jasiukiewicz", "author_id": 16631771, "author_profile": "https://Stackoverflow.com/users/16631771", "pm_score": 0, "selected": false, "text": "<nav class=\"clearfix\">\n <ul class=\"navigation\">\n <li><a href=\"...\" class=\"huy\">About us</a></li>\n <li><a href=\"...\" class=\"huy\">Pricing</a></li>\n <li><a href=\"...\" class=\"huy\">Contact</a></li>\n </ul>\n <div class=\"button\">\n <a href=\"...\" class=\"btn-main\">Sign up</a>\n <a href=\"...\" class=\"btn-hot\">Get a quote</a>\n </div>\n</nav>\n" }, { "answer_id": 74366562, "author": "MN_XD", "author_id": 18037338, "author_profile": "https://Stackoverflow.com/users/18037338", "pm_score": 0, "selected": false, "text": "a{\n color: red;\n}\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1959257/" ]
74,366,357
<p>I just updated my Visual Studio instance from 17.3.6 to 17.4.0. Then I tried a clean build of my solution. Suddenly one of my projects gives me linker errors</p> <pre><code>8&gt;pch.obj : error LNK2001: unresolved external symbol __imp___tls_index_?init@?1??lazy_init_num_threads@internal@at@@YAXXZ@4_NA 8&gt;pch.obj : error LNK2001: unresolved external symbol __imp___tls_offset_?init@?1??lazy_init_num_threads@internal@at@@YAXXZ@4_NA 8&gt;C:\Users\jmole\Documents\Dev\Main\Solutions\..\Mobile\x64\Debug\net6.0-windows\mld_v143.dll : fatal error LNK1120: 2 unresolved externals </code></pre> <p>This completely confuses me. When I turn on verbose linking I see it finding all sorts of similar symbols in MSVCRTD.lib. For example.</p> <pre><code>2&gt; Found _tls_index 2&gt; Found __dyn_tls_init </code></pre> <p>Anyone else encountering this?</p>
[ { "answer_id": 74400482, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 2, "selected": true, "text": "at::internal::lazy_init_num_threads" }, { "answer_id": 74437172, "author": "Armen Poghosov", "author_id": 20504054, "author_profile": "https://Stackoverflow.com/users/20504054", "pm_score": 2, "selected": false, "text": "\\Lib\\site-packages\\torch\\include\\ATen\\Parallel.h" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5869304/" ]
74,366,371
<p>As I can tell it's not possible to just assign delete keycode to another key, so I tried to recreate its functionality, but I can't figure out how to do it properly.</p> <p>I tried to do it with slice, and it actually does what it should for the first time, but then any key I press triggers delete.</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> window.addEventListener("keydown", function(e) { let formuleInput = $(".mat-input-element"); if ($(formuleInput).is(':focus')) { formuleInput[0].addEventListener('keyup', function(f) { let caretPos = f.target.selectionStart; console.log(caretPos); let fInput = formuleInput[0].value; if (e.keyCode === 32 &amp;&amp; $(formuleInput).is(':focus')) { e.preventDefault(); fInput = fInput.slice(0, caretPos) + fInput.slice(caretPos + 1); formuleInput[0].value = fInput; } }) }})</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; &lt;input type="text" class="mat-input-element"&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74400482, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 2, "selected": true, "text": "at::internal::lazy_init_num_threads" }, { "answer_id": 74437172, "author": "Armen Poghosov", "author_id": 20504054, "author_profile": "https://Stackoverflow.com/users/20504054", "pm_score": 2, "selected": false, "text": "\\Lib\\site-packages\\torch\\include\\ATen\\Parallel.h" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10267441/" ]
74,366,373
<p>I've ready many stackoverflow answer, watched youtube videos and read many articles, and I still can't completely understand why we need two tokens. Here are my assumptions, please tell me where I am going wrong:</p> <p>Access Token:</p> <ol> <li><p>Result of some oauth flow, where an application requests for access to a resource on my behalf.</p> </li> <li><p>Contains information about what access has been granted</p> </li> <li><p>Can be any string format (Not necessarily a JWT), it's only important that the intended recipient can understand it.</p> </li> <li><p>Could potentially contain information about the ID of the person who granted the access (Me!)</p> </li> <li><p>Must be kept secret!</p> </li> </ol> <p>ID Token:</p> <ol> <li><p>Result of oidc flow(extension on top of oauth flow)</p> </li> <li><p>Contains information about the user (Me!) who authenticated, for example their username.</p> </li> <li><p>Is intended as nothing more than a standardized way to distribute information about the user. No actions are actually performed using the Id Token</p> </li> <li><p>Can be leaked without danger.</p> </li> </ol> <p>Access token &quot;flow&quot;:</p> <p>User X wants Service A to access Service B on its behalf</p> <p>User X is directed to Service B and authenticates</p> <p>Service B sends an access token to Service A</p> <p>Service A can now access Service B on behalf of User X according to the access rights contained within the token.</p> <p>Id token &quot;flow&quot;:</p> <p>User X signs up for Service A using Login to Service B.</p> <p>User X is directed to Service B and authenticates.</p> <p>Service B sends Id token to Service A.</p> <p>Service A can now display a personalized welcome message, &quot;Hello User X&quot;</p> <p>Is any of this wrong or am I missing something?</p> <p>Am I wrong in thinking that potentially User X could Authenticate against Service B, and grant access rights (access token) to some UserInformationAPI of Service B to Service A, which could then use that token to query Service B to read user information, and that this is in essence the same result as simply passing a standardized Id token to Service A directly?</p>
[ { "answer_id": 74485915, "author": "Takahiko Kawasaki", "author_id": 1174054, "author_profile": "https://Stackoverflow.com/users/1174054", "pm_score": 0, "selected": false, "text": "openid" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5384098/" ]
74,366,377
<p>How do I add color to the header (i.e the column names) of my data frame using the <code>gt()</code> function in R</p> <pre><code>gt_Head &lt;- gt_Head %&gt;% tab_header( title = md(&quot;**Table of First 10 Observations**&quot;) )%&gt;% tab_style( style = cell_text(weight = &quot;bold&quot;), locations = cells_body( rows = 0 ) ) </code></pre>
[ { "answer_id": 74366499, "author": "Julian", "author_id": 14137004, "author_profile": "https://Stackoverflow.com/users/14137004", "pm_score": 3, "selected": true, "text": "column_labels.background.color" }, { "answer_id": 74366527, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 1, "selected": false, "text": "exibble" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6686671/" ]
74,366,379
<pre><code>interface GetAmountProps { value: undefined | string } const getAmount = (value: GetAmountProps): string =&gt; { if (value === undefined) return '(0)'; return value; }; export default getAmount; </code></pre> <p>Why do I have an error on the line with <code>return value;</code>?</p> <blockquote> <p>Type 'GetAmountProps' is not assignable to type 'string'.</p> </blockquote> <p><a href="https://tsplay.dev/NdrQMW" rel="nofollow noreferrer">Playground</a></p>
[ { "answer_id": 74366418, "author": "Samathingamajig", "author_id": 12101554, "author_profile": "https://Stackoverflow.com/users/12101554", "pm_score": 2, "selected": true, "text": "value" }, { "answer_id": 74366422, "author": "David", "author_id": 328193, "author_profile": "https://Stackoverflow.com/users/328193", "pm_score": 0, "selected": false, "text": "string" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18942316/" ]
74,366,421
<p>Working with a Java client/server application and no access to source code.</p> <p>The client application uses the URLConnection object when making calls to the server. Most of the time it works but sporadically it fails with the following error.</p> <pre><code>java.net.BindException:Address already in use </code></pre> <p>When it fails it will do so for a number of attempts and then all of a sudden work fine again.</p> <p>In an attempt to capture the URL calls, the application was started via the command line and referenced the logging.properties file with the following entry.</p> <pre><code> sun.net.www.protocol.http.HttpURLConnection.level = ALL </code></pre> <p>This generated some good information but there was no reference as to the port it was attempting to open on the client side.</p> <ul> <li><strong>Question</strong> What entry needs to be added to the logging.properties file to capture the port the client is attempting to use?</li> </ul>
[ { "answer_id": 74366418, "author": "Samathingamajig", "author_id": 12101554, "author_profile": "https://Stackoverflow.com/users/12101554", "pm_score": 2, "selected": true, "text": "value" }, { "answer_id": 74366422, "author": "David", "author_id": 328193, "author_profile": "https://Stackoverflow.com/users/328193", "pm_score": 0, "selected": false, "text": "string" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3601445/" ]
74,366,426
<p>how can I exclude numbers from a range without creating a giant list?</p> <p>How would I get all the numbers from 1, 100, for example, but exclude every nth number?</p> <p>And what about with multiple n's? Exclude every 3rd and every 11th number, for example.</p> <p>What's the best way to do this?</p> <p>It's easy to do with if statements and appending to a list, but that becomes useless for any range of a large size, because I don't want a list with a million items.</p> <p>basically I have a very large range of numbers and i want to exclude those which are divisible by 3.</p> <p>using an if statement and checking %3 for every single number is also really inefficient</p> <p>everything seems so simple in python that it seems I should be able to just skip every 3rd number, but much googling has left me without an answer.</p> <p>is there no easy, efficient way to do this?</p>
[ { "answer_id": 74366456, "author": "Cory Kramer", "author_id": 2296458, "author_profile": "https://Stackoverflow.com/users/2296458", "pm_score": 1, "selected": false, "text": ">>> import numpy as np\n>>> values = np.arange(100)\n>>> values[values % 3 != 0]\narray([ 1, 2, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 20, 22, 23, 25,\n 26, 28, 29, 31, 32, 34, 35, 37, 38, 40, 41, 43, 44, 46, 47, 49, 50,\n 52, 53, 55, 56, 58, 59, 61, 62, 64, 65, 67, 68, 70, 71, 73, 74, 76,\n 77, 79, 80, 82, 83, 85, 86, 88, 89, 91, 92, 94, 95, 97, 98])\n" }, { "answer_id": 74366463, "author": "jsbueno", "author_id": 108205, "author_profile": "https://Stackoverflow.com/users/108205", "pm_score": 2, "selected": false, "text": "for number in (number in range(10) if number % 3):\n ...\n" }, { "answer_id": 74366609, "author": "Chris", "author_id": 15261315, "author_profile": "https://Stackoverflow.com/users/15261315", "pm_score": 1, "selected": false, "text": ">>> def skip(start, end, pred):\n... yield from (x for x in range(start, end) if not pred(x))\n... \n>>> list(skip(1, 100, lambda x: x % 3 == 0))\n[1, 2, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 20, 22, 23, 25, 26, 28, 29, 31, 32, 34, 35, 37, 38, 40, 41, 43, 44, 46, 47, 49, 50, 52, 53, 55, 56, 58, 59, 61, 62, 64, 65, 67, 68, 70, 71, 73, 74, 76, 77, 79, 80, 82, 83, 85, 86, 88, 89, 91, 92, 94, 95, 97, 98]\n>>> for x in skip(1, 100, lambda a: a % 3 == 0):\n... print(x, end=' ')\n... \n1 2 4 5 7 8 10 11 13 14 16 17 19 20 22 23 25 26 28 29 31 32 34 35 37 38 40 41 43 44 46 47 49 50 52 53 55 56 58 59 61 62 64 65 67 68 70 71 73 74 76 77 79 80 82 83 85 86 88 89 91 92 94 95 97 98\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366426", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20453054/" ]
74,366,429
<p>I have this query to fetch most recent conversations grouped by phone number, however the query time is too slow. How can it be faster?</p> <pre><code>SELECT * from messages WHERE id IN (SELECT max(id) from messages GROUP BY phone) AND chat = :ch AND status = :st AND seller_id = :seller ORDER BY created_at DESC </code></pre> <p>DB Version 10.2.44-MariaDB</p>
[ { "answer_id": 74366456, "author": "Cory Kramer", "author_id": 2296458, "author_profile": "https://Stackoverflow.com/users/2296458", "pm_score": 1, "selected": false, "text": ">>> import numpy as np\n>>> values = np.arange(100)\n>>> values[values % 3 != 0]\narray([ 1, 2, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 20, 22, 23, 25,\n 26, 28, 29, 31, 32, 34, 35, 37, 38, 40, 41, 43, 44, 46, 47, 49, 50,\n 52, 53, 55, 56, 58, 59, 61, 62, 64, 65, 67, 68, 70, 71, 73, 74, 76,\n 77, 79, 80, 82, 83, 85, 86, 88, 89, 91, 92, 94, 95, 97, 98])\n" }, { "answer_id": 74366463, "author": "jsbueno", "author_id": 108205, "author_profile": "https://Stackoverflow.com/users/108205", "pm_score": 2, "selected": false, "text": "for number in (number in range(10) if number % 3):\n ...\n" }, { "answer_id": 74366609, "author": "Chris", "author_id": 15261315, "author_profile": "https://Stackoverflow.com/users/15261315", "pm_score": 1, "selected": false, "text": ">>> def skip(start, end, pred):\n... yield from (x for x in range(start, end) if not pred(x))\n... \n>>> list(skip(1, 100, lambda x: x % 3 == 0))\n[1, 2, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 20, 22, 23, 25, 26, 28, 29, 31, 32, 34, 35, 37, 38, 40, 41, 43, 44, 46, 47, 49, 50, 52, 53, 55, 56, 58, 59, 61, 62, 64, 65, 67, 68, 70, 71, 73, 74, 76, 77, 79, 80, 82, 83, 85, 86, 88, 89, 91, 92, 94, 95, 97, 98]\n>>> for x in skip(1, 100, lambda a: a % 3 == 0):\n... print(x, end=' ')\n... \n1 2 4 5 7 8 10 11 13 14 16 17 19 20 22 23 25 26 28 29 31 32 34 35 37 38 40 41 43 44 46 47 49 50 52 53 55 56 58 59 61 62 64 65 67 68 70 71 73 74 76 77 79 80 82 83 85 86 88 89 91 92 94 95 97 98\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9137983/" ]
74,366,436
<p>I am training a multi-task transformer for a project and would like to switch my data structure over to TFRecords because my training is bottle-necked by on-the-fly data generation. I am currently structuring a single sample of data as a dictionary of tensors, like this:</p> <p><code>{'continuous_input': tf.Tensor(), 'categorical_input': tf.Tensor(), 'continuous_output': tf.Tensor(), 'categorical_output': tf.Tensor()}</code></p> <p>Within a sample, these 4 tensors have the same length, but between samples, these tensors vary in length. The two <code>continuous_</code> tensors are tf.float32, whereas the two <code>categorical_</code> tensors are tf.int32. More explicit details of these tensors are in the code below.</p> <p>I think that I've successfully written my data to TFRecords in the correct format (byte-strings).</p> <p><strong>Problem statement:</strong> I am unable to figure out how to read these TFRecords back into memory and parse the byte-strings into the dictionary of tensors structure above. I include a fully reproducible example of my issue below, which uses Numpy v1.23.4 and Tensorflow v2.10.0. It creates fake data with the aforementioned dictionary structure, saves TFRecords to your working directory, reloads these TFRecords and attempts to parse them with my function <code>parse_tfrecord_fn()</code>. I know that the issue lies in <code>parse_tfrecord_fn()</code> but I do not know the appropriate <code>tf.io</code> tool to resolve this.</p> <p><strong>Reproducible example:</strong></p> <pre><code>import os import os.path as op import numpy as np import tensorflow as tf # Helper functions for writing TFRecords def _tensor_feature(value): serialized_nonscalar = tf.io.serialize_tensor(value) return tf.train.Feature(bytes_list=tf.train.BytesList(value=[serialized_nonscalar.numpy()])) def create_example(sample): feature = { &quot;continuous_input&quot;: _tensor_feature(sample['continuous_input']), &quot;categorical_input&quot;: _tensor_feature(sample['categorical_input']), &quot;continuous_output&quot;: _tensor_feature(sample['continuous_output']), &quot;categorical_output&quot;: _tensor_feature(sample['categorical_output']), } return tf.train.Example(features=tf.train.Features(feature=feature)).SerializeToString() # Helper functions for reading/preparing TFRecord data def parse_tfrecord_fn(example): feature_description = { &quot;continuous_input&quot;: tf.io.VarLenFeature(tf.string), &quot;categorical_input&quot;: tf.io.VarLenFeature(tf.string), &quot;continuous_output&quot;: tf.io.VarLenFeature(tf.string), &quot;categorical_output&quot;: tf.io.VarLenFeature(tf.string) } example = tf.io.parse_single_example(example, feature_description) # TODO: WHAT GOES HERE? return example def get_dataset(filenames, batch_size): dataset = ( tf.data.TFRecordDataset(filenames, num_parallel_reads=tf.data.AUTOTUNE) .map(parse_tfrecord_fn, num_parallel_calls=tf.data.AUTOTUNE) .shuffle(batch_size * 10) .batch(batch_size) .prefetch(tf.data.AUTOTUNE) ) return dataset # Make fake data num_samples_per_tfrecord = 100 num_train_samples = 1600 num_tfrecords = num_train_samples // num_samples_per_tfrecord fake_sequence_lengths = np.random.randint(3, 35, num_train_samples) fake_data = [] for i in range(num_train_samples): seq_len = fake_sequence_lengths[i] fake_data.append({'continuous_input': tf.random.uniform([seq_len], minval=0, maxval=1, dtype=tf.float32), 'categorical_input': tf.random.uniform([seq_len], minval=0, maxval=530, dtype=tf.int32), 'continuous_output': tf.fill(seq_len, -1.0), 'categorical_output': tf.fill(seq_len, -1)}) tfrecords_dir = './tfrecords' if not op.exists(tfrecords_dir): os.makedirs(tfrecords_dir) # create TFRecords output folder # Write fake data to tfrecord files for tfrec_num in range(num_tfrecords): samples = fake_data[(tfrec_num * num_samples_per_tfrecord): ((tfrec_num + 1) * num_samples_per_tfrecord)] with tf.io.TFRecordWriter(tfrecords_dir + &quot;/file_%.2i.tfrec&quot; % tfrec_num) as writer: for sample in samples: example = create_example(sample) writer.write(example) # (Try to) Load all the TFRecord data into a (parsed) tf dataset train_filenames = tf.io.gfile.glob(f&quot;{tfrecords_dir}/*.tfrec&quot;) # Problem: the line below doesn't return the original tensors of fake_data, because my parse_tfrecord_fn is wrong # Question: What must I add to parse_tfrecord_fn to give this the desired behavior? dataset = get_dataset(train_filenames, batch_size=32) # For ease of debugging parse_tfrecord_fn(): dataset = tf.data.TFRecordDataset(train_filenames, num_parallel_reads=tf.data.AUTOTUNE) element = dataset.take(1).get_single_element() parse_tfrecord_fn(element) # set your breakpoint here, then can step through parse_tfrecord_fn() </code></pre> <p>The function <code>parse_tfrecord_fn()</code> accepts a byte-string as input, which looks like this:</p> <p>example = &quot;b'\n\xb4\x03\nj\n\x10continuous_input\x12V\nT\nR\x08\x01\x12\x04\x12\x02\x08\x12&quot;H...&quot;</p> <p>The command <code>example = tf.io.parse_single_example(example, feature_description)</code>, where the arguments are defined as in the my reproducible example, returns a dictionary of <code>SparseTensors</code> with the desired 4 keys ('continuous_input', 'categorical_input', etc.). However, the <em>values</em> of these SparseTensors are either absent or inaccessible to me, so I cannot extract them and parse them, such as with <code>tf.io.parse_tensor(example['continuous_input'].values.numpy().tolist()[0], out_type=tf.float32)</code>.</p>
[ { "answer_id": 74366456, "author": "Cory Kramer", "author_id": 2296458, "author_profile": "https://Stackoverflow.com/users/2296458", "pm_score": 1, "selected": false, "text": ">>> import numpy as np\n>>> values = np.arange(100)\n>>> values[values % 3 != 0]\narray([ 1, 2, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 20, 22, 23, 25,\n 26, 28, 29, 31, 32, 34, 35, 37, 38, 40, 41, 43, 44, 46, 47, 49, 50,\n 52, 53, 55, 56, 58, 59, 61, 62, 64, 65, 67, 68, 70, 71, 73, 74, 76,\n 77, 79, 80, 82, 83, 85, 86, 88, 89, 91, 92, 94, 95, 97, 98])\n" }, { "answer_id": 74366463, "author": "jsbueno", "author_id": 108205, "author_profile": "https://Stackoverflow.com/users/108205", "pm_score": 2, "selected": false, "text": "for number in (number in range(10) if number % 3):\n ...\n" }, { "answer_id": 74366609, "author": "Chris", "author_id": 15261315, "author_profile": "https://Stackoverflow.com/users/15261315", "pm_score": 1, "selected": false, "text": ">>> def skip(start, end, pred):\n... yield from (x for x in range(start, end) if not pred(x))\n... \n>>> list(skip(1, 100, lambda x: x % 3 == 0))\n[1, 2, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 20, 22, 23, 25, 26, 28, 29, 31, 32, 34, 35, 37, 38, 40, 41, 43, 44, 46, 47, 49, 50, 52, 53, 55, 56, 58, 59, 61, 62, 64, 65, 67, 68, 70, 71, 73, 74, 76, 77, 79, 80, 82, 83, 85, 86, 88, 89, 91, 92, 94, 95, 97, 98]\n>>> for x in skip(1, 100, lambda a: a % 3 == 0):\n... print(x, end=' ')\n... \n1 2 4 5 7 8 10 11 13 14 16 17 19 20 22 23 25 26 28 29 31 32 34 35 37 38 40 41 43 44 46 47 49 50 52 53 55 56 58 59 61 62 64 65 67 68 70 71 73 74 76 77 79 80 82 83 85 86 88 89 91 92 94 95 97 98\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14011525/" ]
74,366,438
<p>Is there a way in C++ to define a function so that I could do things like this:</p> <pre><code>foo( &quot;Error on line &quot; &lt;&lt; iLineNumber ); foo( &quot;name &quot; &lt;&lt; strName &lt;&lt; &quot; is Invalid&quot; ); </code></pre> <p>as it is now, I'm having to declare an ostringstream object before I call the foo function like this:</p> <pre><code>std::ostringstream strStream1; ostringstream1 &lt;&lt; &quot;Error on line &quot; &lt;&lt; iLineNumber; foo( ostringstream1 ); std::ostringstream strStream2; ostringstream2 &lt;&lt; &quot;name &quot; &lt;&lt; strName &lt;&lt; &quot; is Invalid&quot;; foo( ostringstream2 ); </code></pre>
[ { "answer_id": 74366598, "author": "François Andrieux", "author_id": 7359094, "author_profile": "https://Stackoverflow.com/users/7359094", "pm_score": 4, "selected": true, "text": "std::ostringstream" }, { "answer_id": 74366731, "author": "Useless", "author_id": 212858, "author_profile": "https://Stackoverflow.com/users/212858", "pm_score": 1, "selected": false, "text": "oss << \"String \" << number;\n" }, { "answer_id": 74367489, "author": "Jerry Coffin", "author_id": 179910, "author_profile": "https://Stackoverflow.com/users/179910", "pm_score": 0, "selected": false, "text": "std::ostringstream buffer;\nbuffer << \"whatever\";\nfoo(buffer);\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2179289/" ]
74,366,479
<p>We have a DNN site and I noticed on our home page that the dev tools show an error with an events.js file that is trying to call &quot;analytics.tiktok.com&quot;. It is being blocked. I don't know if this is purposeful and I've searched our DNN modules code but haven't found an such reference.</p> <p>The other devs can confirm they haven't added such code. I've searched the code folders for a file named events.js but haven't found one. I'm aware that DNN has large portions of it that are data driven but I don't know what tables to query to see if there's code that has that URL.</p> <p>Is anyone aware if DNN or kendo controls has an references to tiktok?</p>
[ { "answer_id": 74366598, "author": "François Andrieux", "author_id": 7359094, "author_profile": "https://Stackoverflow.com/users/7359094", "pm_score": 4, "selected": true, "text": "std::ostringstream" }, { "answer_id": 74366731, "author": "Useless", "author_id": 212858, "author_profile": "https://Stackoverflow.com/users/212858", "pm_score": 1, "selected": false, "text": "oss << \"String \" << number;\n" }, { "answer_id": 74367489, "author": "Jerry Coffin", "author_id": 179910, "author_profile": "https://Stackoverflow.com/users/179910", "pm_score": 0, "selected": false, "text": "std::ostringstream buffer;\nbuffer << \"whatever\";\nfoo(buffer);\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/323425/" ]
74,366,497
<p>After enabling the Middle East (Bahrain &amp; UAE) regions. when using the AWS CLI I received this error even though I've enabled STS in Regional endpoints.</p> <p><img src="https://i.stack.imgur.com/w98QA.png" alt="image1" /></p> <p><img src="https://i.stack.imgur.com/AWj7Q.png" alt="image4" /></p>
[ { "answer_id": 74366598, "author": "François Andrieux", "author_id": 7359094, "author_profile": "https://Stackoverflow.com/users/7359094", "pm_score": 4, "selected": true, "text": "std::ostringstream" }, { "answer_id": 74366731, "author": "Useless", "author_id": 212858, "author_profile": "https://Stackoverflow.com/users/212858", "pm_score": 1, "selected": false, "text": "oss << \"String \" << number;\n" }, { "answer_id": 74367489, "author": "Jerry Coffin", "author_id": 179910, "author_profile": "https://Stackoverflow.com/users/179910", "pm_score": 0, "selected": false, "text": "std::ostringstream buffer;\nbuffer << \"whatever\";\nfoo(buffer);\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366497", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12181518/" ]
74,366,541
<p>My tables:</p> <p>questions</p> <pre><code>id: serial content: text </code></pre> <p>tags</p> <pre><code>id: serial name: text </code></pre> <p>questions_tags</p> <pre><code>question_id integer tag_id integer </code></pre> <p>I need to select all questions with tag 'css', but don't remove all other tags from JSON from jsonb_agg(). I have this SQL query:</p> <pre class="lang-sql prettyprint-override"><code>SELECT q.id, jsonb_agg(to_jsonb(tags)) AS tags FROM questions q LEFT JOIN questions_tags qt ON qt.question_id = q.id LEFT JOIN tags ON tags.id = qt.tag_id WHERE tags.name = 'css' GROUP BY q.id ORDER BY id LIMIT 20 ; </code></pre> <p><code>WHERE tags.name = 'css'</code> clause removes all other tags from result!</p> <pre><code> id | tags -----+--------------------------- 3 | [{&quot;id&quot;: 3, &quot;name&quot;: &quot;css&quot;}] 5 | [{&quot;id&quot;: 3, &quot;name&quot;: &quot;css&quot;}] 13 | [{&quot;id&quot;: 3, &quot;name&quot;: &quot;css&quot;}] 57 | [{&quot;id&quot;: 3, &quot;name&quot;: &quot;css&quot;}] </code></pre> <p>This questions have other tags, but WHERE clause removes it. How to avoid it? I need something like this result:</p> <pre><code> id | tags -----+------------------------------------------------------ 3 | [{&quot;id&quot;: 3, &quot;name&quot;: &quot;css&quot;}, {&quot;id&quot;: 5, &quot;name&quot;: &quot;html&quot;}] 5 | [{&quot;id&quot;: 3, &quot;name&quot;: &quot;css&quot;}] 13 | [{&quot;id&quot;: 3, &quot;name&quot;: &quot;css&quot;}, {&quot;id&quot;: 7, &quot;name&quot;: &quot;js&quot;}] 57 | [{&quot;id&quot;: 3, &quot;name&quot;: &quot;css&quot;}] </code></pre>
[ { "answer_id": 74367412, "author": "GMB", "author_id": 10676716, "author_profile": "https://Stackoverflow.com/users/10676716", "pm_score": 2, "selected": true, "text": "where" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17685412/" ]
74,366,553
<p>I'm starting to work on a react components library and I want to reuse some SCSS code we share with other non-react projects.</p> <p>To accomplish that, I'm trying to use <a href="https://css-tricks.com/introducing-sass-modules/" rel="nofollow noreferrer">SASS modules</a> into react component.</p> <p>The simple use case works fine, but I'm creating a components library and I need to have several style combinations for some components like the button.</p> <p>Right now, I'm having an issue with the <code>Button</code> component. Component is pretty simple, but it has 3 different <code>variant</code> values.</p> <p>Here is the <code>Button.tsx</code> file:</p> <pre><code>import React from &quot;react&quot;; import styles from &quot;./Button.module.scss&quot;; type Variant = &quot;default&quot; | &quot;primary&quot; | &quot;tertiary&quot;; interface Props { children: String; variant: Variant; } export const Button: React.FC&lt;Props&gt; = ({ children, variant }) =&gt; { return &lt;button className={`${styles.button} ${variant}`}&gt;{children}&lt;/button&gt;; }; </code></pre> <p>and here is the <code>Button.module.scss</code> file:</p> <pre class="lang-scss prettyprint-override"><code>.button { border: none; padding: 0.5rem 1.5rem; border-radius: 0.25rem; background-color: grey; color: white; &amp;.default { background-color: green; } &amp;.primary { background-color: red; } } </code></pre> <p>What I expect, is to have a green button if I use the component like <code>&lt;Button variant=&quot;default&quot;&gt;I'm green&lt;/Button&gt;</code>, but instead I'm getting the grey button.</p> <p>Here is a live example on <a href="https://codesandbox.io/s/clever-varahamihira-topfyf?file=/src/components/Button.tsx" rel="nofollow noreferrer">codesandbox</a></p> <p>I'm stuck on this, could somebody help me to apply different styles based on prop values?</p>
[ { "answer_id": 74367877, "author": "Beatriz Infante", "author_id": 7773975, "author_profile": "https://Stackoverflow.com/users/7773975", "pm_score": 2, "selected": true, "text": "<button className={`${styles.button} ${styles[variant]}`}>\n" }, { "answer_id": 74368131, "author": "WebEXP0528", "author_id": 14749803, "author_profile": "https://Stackoverflow.com/users/14749803", "pm_score": 0, "selected": false, "text": "classnames" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1883581/" ]
74,366,559
<p>This is just a conceptual question to test if I understand how X works.</p> <p>Let's I have an X server running on machine A. If I make a new directory called <code>/tmp/.X11-unix</code> on on machine B, and use sshfs to mount <code>root@A:/tmp/.X11-unix</code> to <code>root@B:/tmp/.X11-unix</code>, would I be able to download statically compiled binaries on machine B that used X and see their display output on machine A?</p> <p>When I tried this experiment, exporting the same <code>DISPLAY</code> variable on B as the one on A, I got the <code>display unavailable</code> error when trying out <a href="https://portacle.github.io/" rel="nofollow noreferrer">Portacle</a>. I know that Portacle can display its output when working on a very minimal machine because when I run it on a busybox container, I can see the emacs window, so what is failing here? Does the problem lie in writing to a remote file or is something else missing on machine B?</p>
[ { "answer_id": 74368283, "author": "Philippe", "author_id": 2125671, "author_profile": "https://Stackoverflow.com/users/2125671", "pm_score": 1, "selected": false, "text": "socat TCP-LISTEN:6000,reuseaddr,fork UNIX-CONNECT:/tmp/.X11-unix/X0\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5693890/" ]
74,366,565
<p>I have a folder and inside has a list of subfolders/files Folders</p> <ul> <li>2022</li> <li>20221101</li> <li>20221103</li> <li>20221107</li> <li>20221108</li> <li>test123</li> <li>results</li> <li>test.txt</li> </ul> <p>Using Powershell</p> <ol> <li>How do get the list of folders that are dates.</li> <li>How do I get the second latest folder (20221107).</li> </ol> <p>This is what I was able to come with so far:</p> <pre><code>Get-ChildItem &quot;C:\code\Test&quot; -Filter &quot;2022*&quot; | Sort-Object Name -Descending </code></pre>
[ { "answer_id": 74366715, "author": "Santiago Squarzon", "author_id": 15339544, "author_profile": "https://Stackoverflow.com/users/15339544", "pm_score": 4, "selected": true, "text": "TryParseExact" }, { "answer_id": 74367082, "author": "mklement0", "author_id": 45375, "author_profile": "https://Stackoverflow.com/users/45375", "pm_score": 2, "selected": false, "text": "[datetime]" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19582384/" ]
74,366,585
<p>I am working on a project that has a GUI and tanks that move. While tanks move fine, I am not able to figure out how to move/rotate them individually. I also need to clean my code as I feel I have a lot of extra stuff going on.</p> <p>Here is some code, and here's what I tried.</p> <p>I have four classes. <em>Missiles</em>, <em>Tanks</em>, and <em>Board</em>. I am calling keylisteners in the <em>Tank</em> class. Should I do that in the doDrawing method? The doDrawing method is in the <em>Board</em> class.</p> <pre><code>private void doDrawing(Graphics g) { final double rads = Math.toRadians(120); final double sin = Math.abs(Math.sin(rads)); final double cos = Math.abs(Math.cos(rads)); final int w = (int) Math.floor(tank1.getX() * cos + tank1.getX() * sin); final int h = (int) Math.floor(tank1.getY() * cos + tank1.getY() * sin); Graphics2D g2d = (Graphics2D) g; g2d.translate(w, h); g2d.rotate(rot, tank1.getX(), tank1.getY()); AffineTransform backup = g2d.getTransform(); AffineTransform trans = new AffineTransform(); g2d.setTransform(backup); //g2d.drawImage(tank1.getImage(), tank1.getX(), tank1.getY(), this); trans.setToIdentity(); trans.rotate(rot, h, w); trans.translate(h, w); trans.setTransform(backup); g2d.drawImage(tank1.getImage(), tank1.getX(), tank1.getY(), this); //g2d.drawImage(tank1.getImage(), tank1.getX(), tank1.getY(), this); g2d.drawImage(tank2.getImage(), tank2.getX(), tank2.getY(), this); List&lt;Missile&gt; missiles = tank1.getMissiles(); for (Missile missile : missiles) { //trans.rotate(Math.toRadians(rads), w/2, h/2); g2d.drawImage(missile.getImage(), missile.getX(), missile.getY() - 7, this); //g2d.rotate(rot, missile.getX(), missile.getY() - 7); } } </code></pre>
[ { "answer_id": 74366745, "author": "Hovercraft Full Of Eels", "author_id": 522444, "author_profile": "https://Stackoverflow.com/users/522444", "pm_score": 2, "selected": false, "text": "java.util.List<Tank>" }, { "answer_id": 74366853, "author": "MadProgrammer", "author_id": 992484, "author_profile": "https://Stackoverflow.com/users/992484", "pm_score": 3, "selected": true, "text": "private void doDrawing(Graphics g)\n{\n //...\n Graphics2D g2d = (Graphics2D) g;\n g2d.translate(w, h);\n g2d.rotate(rot, tank1.getX(), tank1.getY());\n\n AffineTransform backup = g2d.getTransform();\n AffineTransform trans = new AffineTransform();\n \n g2d.setTransform(backup);\n //g2d.drawImage(tank1.getImage(), tank1.getX(), tank1.getY(), this);\n \n trans.setToIdentity();\n trans.rotate(rot, h, w); \n trans.translate(h,w);\n trans.setTransform(backup);\n \n g2d.drawImage(tank1.getImage(), tank1.getX(), tank1.getY(), this);\n g2d.drawImage(tank2.getImage(), tank2.getX(), tank2.getY(), this);\n //...\n}\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15831176/" ]
74,366,603
<p>I have written a piece of code that I am using to research the behavior of different libraries and functions. And doing so, I stumbled upon some strange behavior with sscanf.</p> <p>I have a piece of code that reads an input into a buffer, then tries to put that value into a numeric variable.</p> <p>When I call sscanf from main using the input buffer, and the format specifier %x yields a garbage value if the input string is shorter than the buffer. Let's say I enter 0xff, I get an arbitrarily large random number every time. But when I pass that buffer to a function, all calls to scanf result in 255 (0xff) like I expect, regardless of type and format specifier mismatch.</p> <p>My question is, why does this happen in the function main but not in the function test?</p> <p>This is the code:</p> <pre><code>#include &lt;stdio.h&gt; int test(char *buf){ unsigned short num; unsigned int num2; unsigned long long num3; sscanf(buf, &quot;%x&quot;, &amp;num); sscanf(buf, &quot;%x&quot;, &amp;num2); sscanf(buf, &quot;%x&quot;, &amp;num3); printf(&quot;%x&quot;, num); printf(&quot;%x&quot;, num2); printf(&quot;%x&quot;, num3); return 0; } void main(){ char buf[16]; unsigned long long num; printf(&quot;%s&quot;,&quot;Please enter the magic number:&quot;); fgets(buf, sizeof(buf),stdin); sscanf(buf, &quot;%x&quot;, &amp;num); printf(&quot;%x\n&quot;, num); test(&amp;buf); } </code></pre> <p>I expect the behavior to be cohesive; all calls should fail, or all calls should succeed, but this is not the case.</p> <p>I have tried to read the documentation and do experiments with different types, format specifiers, and so on. This behavior is present across all numeric types.</p> <p>I have tried compiling on different platforms; gcc and Linux behave the same, as do Windows and msvc.</p> <p>I also disassembled the binary to see if the call to sscanf differs between main() and test(), but that assembly is identical. It loads the pointer to the buffer into a register and pushes that register onto the stack, and calls sscanf.</p> <p>Now just to be clear: This happens consistently, and num in main is never equal to num, num2 or num3 in test, but num, num2 and num3 are always equal to each other. I would expect this to cause undefined behavior and not be consistent. Output when run - every time</p> <pre><code>./main Please enter the magic number: 0xff 0xaf23af23423 &lt;--- different every time 0xff &lt;--- never different 0xff &lt;--- never different 0xff &lt;--- never different </code></pre> <p>The current reasoning I have is in one instance sscanf is interpreting more bytes than in the other. It seems to keep evaluating the entire buffer, getting impacted by residual data in memory.</p> <p>I know I can make it behave correctly by either filling the buffer, with that last byte being a new line or using the correct format specifier to match the pointer type. &quot;%llx&quot; for main in this case. So that is not what I am wondering; I have made that error on purpose.</p> <p>I am wondering why using the wrong format specifier works in one case but not in the other consistently when the code runs.</p>
[ { "answer_id": 74366745, "author": "Hovercraft Full Of Eels", "author_id": 522444, "author_profile": "https://Stackoverflow.com/users/522444", "pm_score": 2, "selected": false, "text": "java.util.List<Tank>" }, { "answer_id": 74366853, "author": "MadProgrammer", "author_id": 992484, "author_profile": "https://Stackoverflow.com/users/992484", "pm_score": 3, "selected": true, "text": "private void doDrawing(Graphics g)\n{\n //...\n Graphics2D g2d = (Graphics2D) g;\n g2d.translate(w, h);\n g2d.rotate(rot, tank1.getX(), tank1.getY());\n\n AffineTransform backup = g2d.getTransform();\n AffineTransform trans = new AffineTransform();\n \n g2d.setTransform(backup);\n //g2d.drawImage(tank1.getImage(), tank1.getX(), tank1.getY(), this);\n \n trans.setToIdentity();\n trans.rotate(rot, h, w); \n trans.translate(h,w);\n trans.setTransform(backup);\n \n g2d.drawImage(tank1.getImage(), tank1.getX(), tank1.getY(), this);\n g2d.drawImage(tank2.getImage(), tank2.getX(), tank2.getY(), this);\n //...\n}\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4269730/" ]
74,366,613
<p>I have a button placed in the center using centerXAnchor of superview, but now I have to change the position of the button from centerX to align leading from code. However, it's not moving to the left. Instead, it gets full width button.</p> <pre class="lang-swift prettyprint-override"><code>buttonView!.translatesAutoresizingMaskIntoConstraints = false buttonView!.removeConstraints(buttonView!.constraints) NSLayoutConstraint.activate([ buttonView!.leadingAnchor.constraint(equalTo: mainView.leadingAnchor, constant: 12), buttonView!.bottomAnchor.constraint(equalTo: mainView.bottomAnchor, constant: 20), ]) </code></pre>
[ { "answer_id": 74366745, "author": "Hovercraft Full Of Eels", "author_id": 522444, "author_profile": "https://Stackoverflow.com/users/522444", "pm_score": 2, "selected": false, "text": "java.util.List<Tank>" }, { "answer_id": 74366853, "author": "MadProgrammer", "author_id": 992484, "author_profile": "https://Stackoverflow.com/users/992484", "pm_score": 3, "selected": true, "text": "private void doDrawing(Graphics g)\n{\n //...\n Graphics2D g2d = (Graphics2D) g;\n g2d.translate(w, h);\n g2d.rotate(rot, tank1.getX(), tank1.getY());\n\n AffineTransform backup = g2d.getTransform();\n AffineTransform trans = new AffineTransform();\n \n g2d.setTransform(backup);\n //g2d.drawImage(tank1.getImage(), tank1.getX(), tank1.getY(), this);\n \n trans.setToIdentity();\n trans.rotate(rot, h, w); \n trans.translate(h,w);\n trans.setTransform(backup);\n \n g2d.drawImage(tank1.getImage(), tank1.getX(), tank1.getY(), this);\n g2d.drawImage(tank2.getImage(), tank2.getX(), tank2.getY(), this);\n //...\n}\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11260762/" ]
74,366,624
<p>I have the next data in my Mongo DB</p> <pre><code>{ sucursal: 1 productos: [ { producto: 1, kilos: 50 } ] }, { sucursal: 2 productos: [ { producto: 1, kilos: 30 }, { producto: 2, kilos: 50 } ] }, { sucursal: 1 productos: [ { producto: 1, kilos: 50 }, { producto: 2, kilos: 40 } ] }, </code></pre> <p>and my goal is to obtain the data with the following format</p> <pre><code>{ sucursal: 1 productos: [ { producto: 1, kilos: 100 }, { producto: 2, kilos: 40 } ] }, { sucursal: 2 productos: [ { producto: 1, kilos: 30 }, { producto: 2, kilos: 50 } ] } </code></pre> <p>I am working with mongoose and nodeJS. I am using the aggregate function with $group but I'm not getting the expected results and I would like to know what I'm doing wrong. My goal is to group all 'sucursales' without repeating any elements, each 'sucursal' should have an array of all the 'productos' that are in each 'sucursal' with the same name but without repeating any 'producto', instead of repeating the element, the function should add the value to the element with the same name (see the data example above).</p> <p>The code that I'm using is this:</p> <pre><code>const ordenesTotal = await OrdCompCli.aggregate([ { $match: {fechaEntrega: new Date(fecha), estado: {$gt : 0, $lt : 5}} }, { $unwind: &quot;$productos&quot; }, { $group: { _id: &quot;$sucursal&quot;, productos: { $addToSet: { producto: &quot;$productos.producto&quot;, totalKilos: { $sum: &quot;$productos.kilos&quot; } } } } }, { $project: { _id: 0, sucursal: &quot;$_id&quot;, productos: 1 }, }, ]) </code></pre> <p>this code gave me this result:</p> <pre><code>{ sucursal: 1 productos: [ { producto: 1, kilos: 50 }, { producto: 2, kilos: 40 }, { producto: 1, kilos: 50 }, ] }, { sucursal: 2 productos: [ { producto: 1, kilos: 30 }, { producto: 2, kilos: 50 } ] } </code></pre> <p>and this result is not what I'm expecting because the 'producto' with the same name are not being grouped. Can someone tell me what I'm doing wrong?</p>
[ { "answer_id": 74366745, "author": "Hovercraft Full Of Eels", "author_id": 522444, "author_profile": "https://Stackoverflow.com/users/522444", "pm_score": 2, "selected": false, "text": "java.util.List<Tank>" }, { "answer_id": 74366853, "author": "MadProgrammer", "author_id": 992484, "author_profile": "https://Stackoverflow.com/users/992484", "pm_score": 3, "selected": true, "text": "private void doDrawing(Graphics g)\n{\n //...\n Graphics2D g2d = (Graphics2D) g;\n g2d.translate(w, h);\n g2d.rotate(rot, tank1.getX(), tank1.getY());\n\n AffineTransform backup = g2d.getTransform();\n AffineTransform trans = new AffineTransform();\n \n g2d.setTransform(backup);\n //g2d.drawImage(tank1.getImage(), tank1.getX(), tank1.getY(), this);\n \n trans.setToIdentity();\n trans.rotate(rot, h, w); \n trans.translate(h,w);\n trans.setTransform(backup);\n \n g2d.drawImage(tank1.getImage(), tank1.getX(), tank1.getY(), this);\n g2d.drawImage(tank2.getImage(), tank2.getX(), tank2.getY(), this);\n //...\n}\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13002388/" ]
74,366,649
<p>I've been using <code>graphql-codegen</code> for several month, it's a great tool.<br /> I've always used it with <code>@tanstack/react-query</code> <code>useQuery</code> &amp; <code>useMutation</code> hooks.</p> <p>Today, I would like to use it with <code>useQueries</code> (<a href="https://tanstack.com/query/v4/docs/guides/parallel-queries" rel="nofollow noreferrer">documentation</a>).<br /> To give you more inputs, I'm receiving a dynamic (then undeterministic) list of ids of same type, and I would like to populate them by querying my graphql api. Because of recursive issues, I can't do reconsiliation on server, so I have to do it on client. This is why I need to batch single queries. And this is why I wish I could use <code>useQueries</code>.</p> <p>It looks like there's no interoperability with <code>graphql-codegen</code> &amp; <code>useQueries</code>.<br /> Do you confirm ?<br /> If so, which pattern would you recommand in order to run multiple queries in parallel ?</p> <p>Thanks in advance.</p> <p>My use case here :</p> <pre class="lang-js prettyprint-override"><code>import { useQueries } from '@tanstack/react-query'; import { gql } from 'graphql-request'; import { graphQLClient } from '../../graphQLClient'; export const useGetSomeStuff = (ids: string[]) =&gt; useQueries({ queries: ids.map((id) =&gt; ({ queryKey: ['getSomeStuff', id], queryFn: async () =&gt; graphQLClient.request( gql` query GetSomeStuff($id: MongoObjectId!) { oneStuff(id: $id) { ...SomeFragment } } `, { id } ), })), }); </code></pre> <p>generates :</p> <pre class="lang-js prettyprint-override"><code>export type GetSomeStuffQueryVariables = Exact&lt;{ id: Scalars['MongoObjectId']; }&gt;; export type GetSomeStuffQuery = { __typename?: 'Query'; // ... generated query }; export const GetSomeStuffDocument = ` query GetSomeStuff($id: MongoObjectId!) { oneStuff(id: $id) { ...SomeFragment } }`; export const useGetSomeStuffQuery = &lt; TData = GetSomeStuffQuery, TError = unknown &gt;( client: GraphQLClient, variables: GetSomeStuffQueryVariables, options?: UseQueryOptions&lt;GetSomeStuffQuery, TError, TData&gt;, headers?: RequestInit['headers'] ) =&gt; useQuery&lt;GetSomeStuffQuery, TError, TData&gt;( ['GetSomeStuff', variables], fetcher&lt; GetSomeStuffQuery, GetSomeStuffQueryVariables &gt;(client, GetSomeStuffDocument, variables, headers), options ); </code></pre> <p>You can see that generated code still uses <code>useQuery</code></p>
[ { "answer_id": 74366745, "author": "Hovercraft Full Of Eels", "author_id": 522444, "author_profile": "https://Stackoverflow.com/users/522444", "pm_score": 2, "selected": false, "text": "java.util.List<Tank>" }, { "answer_id": 74366853, "author": "MadProgrammer", "author_id": 992484, "author_profile": "https://Stackoverflow.com/users/992484", "pm_score": 3, "selected": true, "text": "private void doDrawing(Graphics g)\n{\n //...\n Graphics2D g2d = (Graphics2D) g;\n g2d.translate(w, h);\n g2d.rotate(rot, tank1.getX(), tank1.getY());\n\n AffineTransform backup = g2d.getTransform();\n AffineTransform trans = new AffineTransform();\n \n g2d.setTransform(backup);\n //g2d.drawImage(tank1.getImage(), tank1.getX(), tank1.getY(), this);\n \n trans.setToIdentity();\n trans.rotate(rot, h, w); \n trans.translate(h,w);\n trans.setTransform(backup);\n \n g2d.drawImage(tank1.getImage(), tank1.getX(), tank1.getY(), this);\n g2d.drawImage(tank2.getImage(), tank2.getX(), tank2.getY(), this);\n //...\n}\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6939540/" ]
74,366,653
<p>How to group a pandas (or dask) dataframe and get the min, max and some operation, only when the diference between the grouped rows are 1 second?</p> <p><strong>MY DATA:</strong></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>DT</th> <th>VALOR</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>12:01:00</td> <td>7</td> </tr> <tr> <td>1</td> <td>12:01:01</td> <td>1</td> </tr> <tr> <td>1</td> <td>12:01:02</td> <td>4</td> </tr> <tr> <td>1</td> <td>12:01:03</td> <td>3</td> </tr> <tr> <td>1</td> <td>12:01:08</td> <td>1</td> </tr> <tr> <td>1</td> <td>12:01:09</td> <td>5</td> </tr> <tr> <td>2</td> <td>12:01:09</td> <td>6</td> </tr> <tr> <td>1</td> <td>12:01:10</td> <td>6</td> </tr> <tr> <td>1</td> <td>12:01:11</td> <td>4</td> </tr> </tbody> </table> </div> <p><strong>RETURN:</strong></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>MENOR_DT</th> <th>MAIOR_DT</th> <th>SOMA</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>12:01:00</td> <td>12:01:03</td> <td>15</td> </tr> <tr> <td>1</td> <td>12:01:08</td> <td>12:01:11</td> <td>16</td> </tr> <tr> <td>2</td> <td>12:01:09</td> <td>12:01:09</td> <td>6</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74366869, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 3, "selected": true, "text": "df[\"DT\"] = pd.to_timedelta(df[\"DT\"])\n\ntmp = df.groupby(\"ID\", group_keys=False)[\"DT\"].apply(\n lambda x: (x.diff().bfill() != \"1 second\").cumsum()\n)\n\ndf = (\n df.groupby([\"ID\", tmp])\n .agg(\n ID=(\"ID\", \"first\"),\n MENOR_DT=(\"DT\", \"min\"),\n MAIOR_DT=(\"DT\", \"max\"),\n SOME=(\"VALOR\", \"sum\"),\n )\n .reset_index(drop=True)\n)\ndf[\"MENOR_DT\"] = df[\"MENOR_DT\"].astype(str).str.split().str[-1]\ndf[\"MAIOR_DT\"] = df[\"MAIOR_DT\"].astype(str).str.split().str[-1]\nprint(df)\n" }, { "answer_id": 74366933, "author": "Naveed", "author_id": 3494754, "author_profile": "https://Stackoverflow.com/users/3494754", "pm_score": 1, "selected": false, "text": "df['seq'] = np.nan # create a temp column\n\n# sort the DF, find the seconds difference, and update the seq columns\n# ffill to group all rows that has a 1 second or less of difference\n\ndf['seq']=(df.sort_values(['ID','DT']) \n .assign(seq=df['seq']\n .mask(pd.to_timedelta(df['DT']).dt.total_seconds()\n .diff().ne(1), 1))['seq']\n .cumsum()\n .ffill()\n)\n\n# groupby ID, seq and take the aggregate\n# drop the seq columns\n\n(df.groupby(['ID','seq']).agg(MENOR_DT= ('DT','min'), \n MAIOR_DT= ('DT','max'), \n SOMA = ('VALOR','sum'))\n .reset_index()\n .drop(columns=['seq']))\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19505881/" ]
74,366,671
<p>I want to calculate the running difference of column ['Values'] based on a binary condition in another column ['Conditions']. If condition is 0 then it calculates the difference of the current row and preceding row. If condition is 1 then it calculates the difference of the current row and the previous row where the condition was also 1 like so:</p> <pre><code> Values Condition Desired_Output 0 5000 1 NaN 1 5500 0 500.0 2 6700 1 1700.0 3 7100 0 400.0 4 8500 0 1400.0 5 9000 0 500.0 6 10500 1 3800.0 7 15750 0 5250.0 8 18000 1 7500.0 9 22250 0 4250.0 10 26000 0 3750.0 11 29750 0 3750.0 12 33500 0 3750.0 13 37250 0 3750.0 14 41000 1 23000.0 15 44750 0 3750.0 16 48500 1 7500.0 17 52250 1 3750.0 18 56000 0 3750.0 19 59750 1 7500.0 20 63500 0 3750.0 21 67250 0 3750.0 22 71000 0 3750.0 23 74750 0 3750.0 24 78500 0 3750.0 25 82250 1 22500.0 26 86000 0 3750.0 27 89750 1 7500.0 </code></pre> <p>I tried using the groupby function with no such luck.</p> <pre><code>df.insert(2, 'Difference', (df.groupby('Condition')['Values'].diff())) </code></pre> <p>When I filter the dataframe based on the conditions and calculate the difference then I get close to the desired output however I have to work with two columns in that case. Is there a way to perform this function in a single column? I am fairly new to Python and would appreciate some help</p>
[ { "answer_id": 74366811, "author": "Ben.T", "author_id": 9274732, "author_profile": "https://Stackoverflow.com/users/9274732", "pm_score": 1, "selected": false, "text": "diff" }, { "answer_id": 74367044, "author": "Vincent Rupp", "author_id": 4024409, "author_profile": "https://Stackoverflow.com/users/4024409", "pm_score": 0, "selected": false, "text": "Values = [5000, 5500, 6700, 7100, 8500, 9000, 10500, 15750, 18000, 22250, 26000]\nCondition = [1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0]\ndf = pd.DataFrame(data={\"Values\":Values, \"Condition\":Condition})\ndf[\"Desired_Output\"] = df.Values.diff()\ndf.loc[df.Condition == 1, \"Desired_Output\"] = df[df.Condition==1].Values.diff()\nprint(df)\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19872294/" ]
74,366,672
<p>I need to get the latest row of each combinations of sender_id &amp; receiver_id</p> <p>my <code>messaging</code> table:</p> <pre><code>CREATE TABLE messaging ( msg_id SERIAL, sender_id BIGINT NOT NULL , receiver_id varchar(255) NOT NULL , msg text default NULL, media_link TEXT DEFAULT NULL, sent_time TIMESTAMP NOT NULL DEFAULT NOW(), received_time TIMESTAMP default NULL, msg_type ENUM('text','link','file') default 'text', is_seen BINARY DEFAULT 0 ) ENGINE=InnoDB; </code></pre> <p>Sample data:</p> <pre><code>+------+---------+-----------+---------------+----------+-------------------+-------------+--------+-------+ |msg_id|sender_id|receiver_id|msg |media_link|sent_time |received_time|msg_type|is_seen| +------+---------+-----------+---------------+----------+-------------------+-------------+--------+-------+ |1 |1 |10 |hi |NULL |2022-11-08 19:11:53|NULL |text |0 | |2 |1 |10 |r u there? |NULL |2022-11-08 19:12:46|NULL |text |0 | |3 |7 |10 |hi |NULL |2022-11-08 19:13:13|NULL |text |0 | |4 |7 |10 |where r u from?|NULL |2022-11-08 20:31:17|NULL |text |0 | +------+---------+-----------+---------------+----------+-------------------+-------------+--------+-------+ </code></pre> <p>ORDER BY latest with each sender_id receiver_id combination the result should look like this:</p> <pre><code>+------+---------+-----------+---------------+----------+-------------------+-------------+--------+-------+ |msg_id|sender_id|receiver_id|msg |media_link|sent_time |received_time|msg_type|is_seen| +------+---------+-----------+---------------+----------+-------------------+-------------+--------+-------+ |2 |1 |10 |r u there? |NULL |2022-11-08 19:12:46|NULL |text |0 | |4 |7 |10 |where r u from?|NULL |2022-11-08 20:31:17|NULL |text |0 | +------+---------+-----------+---------------+----------+-------------------+-------------+--------+-------+ </code></pre> <p>I have tried this statement:</p> <pre><code>SELECT msg_id, sender_id, receiver_id, msg, media_link, sent_time, received_time, msg_type, is_seen FROM messaging WHERE sender_id = 10 OR receiver_id = 10 GROUP BY sender_id,receiver_id ORDER BY msg_id DESC; </code></pre> <p>which gives there rows ascending order of each group:</p> <pre><code>+------+---------+-----------+---+----------+-------------------+-------------+--------+-------+ |msg_id|sender_id|receiver_id|msg|media_link|sent_time |received_time|msg_type|is_seen| +------+---------+-----------+---+----------+-------------------+-------------+--------+-------+ |3 |7 |10 |hi |NULL |2022-11-08 19:13:13|NULL |text |0 | |1 |1 |10 |hi |NULL |2022-11-08 19:11:53|NULL |text |0 | +------+---------+-----------+---+----------+-------------------+-------------+--------+-------+ </code></pre> <p>But it is only showing oldest row of each group by combination.</p> <p>I am still learning Mysql. Please help me</p>
[ { "answer_id": 74366811, "author": "Ben.T", "author_id": 9274732, "author_profile": "https://Stackoverflow.com/users/9274732", "pm_score": 1, "selected": false, "text": "diff" }, { "answer_id": 74367044, "author": "Vincent Rupp", "author_id": 4024409, "author_profile": "https://Stackoverflow.com/users/4024409", "pm_score": 0, "selected": false, "text": "Values = [5000, 5500, 6700, 7100, 8500, 9000, 10500, 15750, 18000, 22250, 26000]\nCondition = [1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0]\ndf = pd.DataFrame(data={\"Values\":Values, \"Condition\":Condition})\ndf[\"Desired_Output\"] = df.Values.diff()\ndf.loc[df.Condition == 1, \"Desired_Output\"] = df[df.Condition==1].Values.diff()\nprint(df)\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14677428/" ]
74,366,695
<p>I have a dataset like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">Date</th> <th style="text-align: center;">Account</th> <th style="text-align: center;">Spend</th> </tr> </thead> <tbody> <tr> <td style="text-align: center;">1/2/21</td> <td style="text-align: center;">A</td> <td style="text-align: center;">null</td> </tr> <tr> <td style="text-align: center;">1/3/21</td> <td style="text-align: center;">A</td> <td style="text-align: center;">null</td> </tr> <tr> <td style="text-align: center;">1/4/21</td> <td style="text-align: center;">A</td> <td style="text-align: center;">4</td> </tr> <tr> <td style="text-align: center;">1/5/21</td> <td style="text-align: center;">A</td> <td style="text-align: center;">6</td> </tr> <tr> <td style="text-align: center;">1/6/21</td> <td style="text-align: center;">A</td> <td style="text-align: center;">null</td> </tr> <tr> <td style="text-align: center;">1/7/21</td> <td style="text-align: center;">A</td> <td style="text-align: center;">7</td> </tr> <tr> <td style="text-align: center;">1/8/21</td> <td style="text-align: center;">A</td> <td style="text-align: center;">null</td> </tr> <tr> <td style="text-align: center;">1/2/21</td> <td style="text-align: center;">B</td> <td style="text-align: center;">null</td> </tr> <tr> <td style="text-align: center;">1/3/21</td> <td style="text-align: center;">B</td> <td style="text-align: center;">4</td> </tr> <tr> <td style="text-align: center;">1/4/21</td> <td style="text-align: center;">B</td> <td style="text-align: center;">null</td> </tr> <tr> <td style="text-align: center;">1/5/21</td> <td style="text-align: center;">B</td> <td style="text-align: center;">7</td> </tr> <tr> <td style="text-align: center;">1/6/21</td> <td style="text-align: center;">B</td> <td style="text-align: center;">null</td> </tr> </tbody> </table> </div> <p>I want to trim any leading and lagging nulls by group but keep the nulls where there is a value both before and after. The final dataset would look like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">Date</th> <th style="text-align: center;">Account</th> <th style="text-align: center;">Spend</th> </tr> </thead> <tbody> <tr> <td style="text-align: center;">1/4/21</td> <td style="text-align: center;">A</td> <td style="text-align: center;">4</td> </tr> <tr> <td style="text-align: center;">1/5/21</td> <td style="text-align: center;">A</td> <td style="text-align: center;">6</td> </tr> <tr> <td style="text-align: center;">1/6/21</td> <td style="text-align: center;">A</td> <td style="text-align: center;">null</td> </tr> <tr> <td style="text-align: center;">1/7/21</td> <td style="text-align: center;">A</td> <td style="text-align: center;">7</td> </tr> <tr> <td style="text-align: center;">1/3/21</td> <td style="text-align: center;">B</td> <td style="text-align: center;">4</td> </tr> <tr> <td style="text-align: center;">1/4/21</td> <td style="text-align: center;">B</td> <td style="text-align: center;">null</td> </tr> <tr> <td style="text-align: center;">1/5/21</td> <td style="text-align: center;">B</td> <td style="text-align: center;">7</td> </tr> </tbody> </table> </div> <p>How can I do this with SQL (specifically Snowflake SQL)?</p>
[ { "answer_id": 74366811, "author": "Ben.T", "author_id": 9274732, "author_profile": "https://Stackoverflow.com/users/9274732", "pm_score": 1, "selected": false, "text": "diff" }, { "answer_id": 74367044, "author": "Vincent Rupp", "author_id": 4024409, "author_profile": "https://Stackoverflow.com/users/4024409", "pm_score": 0, "selected": false, "text": "Values = [5000, 5500, 6700, 7100, 8500, 9000, 10500, 15750, 18000, 22250, 26000]\nCondition = [1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0]\ndf = pd.DataFrame(data={\"Values\":Values, \"Condition\":Condition})\ndf[\"Desired_Output\"] = df.Values.diff()\ndf.loc[df.Condition == 1, \"Desired_Output\"] = df[df.Condition==1].Values.diff()\nprint(df)\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8941248/" ]
74,366,698
<p>anyone has an idea what causes the ff issue and how do we address this one . property) closeEmail: (email: IEmail) =&gt; string</p> <p>Ideas would be much appreciated</p> <p>I was tracing the type EmailSelection but the issue indicates on that part ...</p> <p><a href="https://i.stack.imgur.com/QLMpq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QLMpq.png" alt="enter image description here" /></a></p> <p>#Code - EmailSelection.tsx</p> <pre><code>type EmailSelection = { isEmailOpen: boolean; closeEmail: (email: IEmail) =&gt; string; }; type IEmail = { emailAddress: string; firstName: string; id: number; lastName: string; }; const EmailSelection: FC&lt;EmailSelection&gt; = ({ isEmailOpen, closeEmail }) =&gt; { const { isPending, isError, isSuccess, data } = useAppSelector( (state) =&gt; state.yardUser ); const emailList = data ? data.data : []; return ( &lt;Dialog open={isEmailOpen} keepMounted onClose={closeEmail} aria-describedby=&quot;alert-dialog-slide-description&quot; &gt; &lt;DialogTitle&gt;Select Email&lt;/DialogTitle&gt; &lt;DialogContent&gt; &lt;List style={{ maxHeight: &quot;500px&quot;, overflow: &quot;auto&quot;, }} disablePadding &gt; {emailList.map((email: IEmail) =&gt; ( &lt;ListItem disablePadding&gt; &lt;ListItemButton onClick={() =&gt; closeEmail(email)}&gt; &lt;ListItemIcon&gt; &lt;EmailIcon /&gt; &lt;/ListItemIcon&gt; &lt;ListItemText primary={email.emailAddress} /&gt; &lt;/ListItemButton&gt; &lt;/ListItem&gt; ))} &lt;/List&gt; &lt;/DialogContent&gt; &lt;/Dialog&gt; ); }; </code></pre> <p>#main dialog that uses the EmailSelection</p> <p>#snippet</p> <pre><code> const closeEmail = (email: string) =&gt; { setOpenEmail(false); } </code></pre> <p>#snippet</p> <pre><code> return ( &lt;Dialog maxWidth={maxWidth} open={open} onClose={handleClose} aria-labelledby=&quot;alert-dialog-title&quot; aria-describedby=&quot;alert-dialog-description&quot; &gt; &lt;DialogTitle id=&quot;alert-dialog-title&quot;&gt;Edit Assignment&lt;/DialogTitle&gt; &lt;DialogContent&gt; &lt;Card sx={{ minWidth: 275 }} style={{ padding: 20 }}&gt; &lt;div&gt; &lt;EmailSelection closeEmail={closeEmail} isEmailOpen={isEmailOpen} /&gt; </code></pre> <p>#snippet ts</p> <pre><code> type EmailSelection = { isEmailOpen: boolean; closeEmail: (email: IEmail) =&gt; string; }; type IEmail = { emailAddress: string; firstName: string; id: number; lastName: string; }; </code></pre>
[ { "answer_id": 74366811, "author": "Ben.T", "author_id": 9274732, "author_profile": "https://Stackoverflow.com/users/9274732", "pm_score": 1, "selected": false, "text": "diff" }, { "answer_id": 74367044, "author": "Vincent Rupp", "author_id": 4024409, "author_profile": "https://Stackoverflow.com/users/4024409", "pm_score": 0, "selected": false, "text": "Values = [5000, 5500, 6700, 7100, 8500, 9000, 10500, 15750, 18000, 22250, 26000]\nCondition = [1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0]\ndf = pd.DataFrame(data={\"Values\":Values, \"Condition\":Condition})\ndf[\"Desired_Output\"] = df.Values.diff()\ndf.loc[df.Condition == 1, \"Desired_Output\"] = df[df.Condition==1].Values.diff()\nprint(df)\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19053255/" ]
74,366,707
<p>I'm working on the Library App as part of the Odin Project self-taught full stack course. Nearly done, just trying to get my data to show up as a table.</p> <p><strong>What I expect:</strong> When I hit &quot;submit book&quot;, I want the data to populate the table, even if no table currently exists. (see line 98-99 of the js)</p> <pre><code>clearTable(); document.getElementById('table-container').appendChild(buildTable(myLibrary)); </code></pre> <p><strong>What I get instead:</strong> Hitting &quot;submit book&quot; does nothing.</p> <p><strong>HOWEVER, and here's the weird part:</strong> If I start the page by creating a table initially with data from a placeholder array, the submit book and clearTable() functions will work as intended, and even add to the table even as you add more books, which is what I want it to do. It just looks like for some reason it is never able to make a table at all unless I start the page with <code>document.getElementById('table-container').appendChild(buildTable(BOOKS));</code> on line 170 of javascript.</p> <p>Code here: <a href="https://codepen.io/Krmanski/pen/BaVpNar" rel="nofollow noreferrer">https://codepen.io/Krmanski/pen/BaVpNar</a>. (You notice that a table shows up when you open this pen. That is my placeholder table with placeholder data. I ultimately want data objects constructed when the user hits the &quot;submit book&quot; button to populate this space instead. They currently do when this placeholder table is in place, but when you remove it, submit book no longer clears and adds data from the myLibrary Array.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>let myLibrary = []; function Book(title, author, pages, read) { this.title = title; this.author = author; this.pages = pages; this.read = read; this.info = function() { //allows for a different message to be given by the info method depending on the 'read' boolean if (read === true) { return `${title} by ${author}, ${pages} pages, has been read`; } else if (read === false) { return `${title} by ${author}, ${pages} pages, not read`; } else { return "ERROR"; } } } function addBookToLibrary(title, author, pages, read) { let newBook = new Book(title, author, pages, read); myLibrary.push(newBook); //adds the newly created Book object to the main array. } function displayBooksOnPage() { //successfully gets book objects from the main array to populate the dom by looping through them. //find the readout area in the web page and make a variable to contain it in memory let readout = document.querySelector("#readout"); //loop over library array myLibrary.forEach(myLibrary =&gt; { //for each item in the array, create a div container with a class "card" let card = document.createElement("div"); card.classList.add('card'); //add these cards to the readout area so we can see them on the page. readout.appendChild(card); //for each object in myLibrary, let that key represented by "key" as you loop through them. for (let key in myLibrary) { //create a p element inside your cards to get the info to appear let bookText = document.createElement('p'); //IMPORTANT //because we are iterating through each object key, 'key' represents the key/property we are actually currently on. //therefore when we put 'key' in [], it calls the VALUE of itself in that itterable. bookText.innerText = (`${key}: ${myLibrary[key]}`); card.appendChild(bookText); } }); } function clearForm() { //clears form document.getElementById('book-form').reset(); } //the submit-button calls a function that gets the form data when it is clicked. const submitButton = document.querySelector("#submit-button"); submitButton.addEventListener('click', getFormData); submitButton.addEventListener('click', function(event) { event.preventDefault(); }); //get form data from page so that js can use it: function getFormData() { //.value grabs whatever data is actually IN the form box that the user has typed. let fTitle = document.getElementById("title-input").value; let fAuthor = document.getElementById("author-input").value; let fPages = document.getElementById("pages-input").value; let numPages = parseInt(fPages); let fRead; if (document.getElementById("read-input").checked) { fRead = true; } else if (!document.getElementById("read-input").checked) { fRead = false; } else { fRead = "error"; } //then use this data to create an object and add it to the library array addBookToLibrary(fTitle, fAuthor, numPages, fRead); //clear the form upon submission document.getElementById('book-form').reset(); //update table clearTable(); document.getElementById('table-container').appendChild(buildTable(myLibrary)); //test logs console.log(myLibrary); } ///test stuff function buildTable(data) { var node = document.createElement("table"); node.setAttribute('id', 'book-table'); var tr = document.createElement("tr"); //fill the headers var with an array of the keys of the object in the 0 index (first place) of the array var headers = Object.keys(data[0]); //loop through each key in the array of key names for (var i = 0; i &lt; headers.length; ++i) { var header = headers[i]; //create table headers for the key names //create a new table header called th var th = document.createElement("th"); //use createTextNode to set its text to the current key via "header" th.appendChild(document.createTextNode(header)); //add that th to the table row (tr) you are looping through tr.appendChild(th); } //actually finally add this row to the table node.appendChild(tr); //now loop through each object in the array in "data" data.forEach(function(rowdata) { //for each object, make a new table row "tr" for it. tr = document.createElement("tr"); for (var i = 0; i &lt; headers.length; ++i) { //loops through each key and uses that key to get the value var header = headers[i]; var td = document.createElement("td"); //adds the value from the key:value pair to the td via createTextNode td.appendChild(document.createTextNode(rowdata[header])); //right-align the data if it is an int if (typeof rowdata[header] == "number") { td.style.textAlign = "right"; td.style.color = "#E50000"; } tr.appendChild(td); } node.appendChild(tr); }); return node; } function clearTable() { //select the table that had been added to the div container via the dom, so we remove the content and not the div itself. const toDel = document.querySelector("#book-table"); toDel.remove(); } //build from an array of objects var BOOKS = [{ name: "cat in the hat", author: "Dr. Suess", pages: 12, read: true, button: "click me" }, { name: "lorax", author: "Dr. Suess", pages: 28, read: false, button: "click me" }, { name: "sneeches on the beaches", author: "Dr. Suess", pages: 16, read: true, button: "click me" }, ]; //put the table right where we want it in the page. document.getElementById('table-container').appendChild(buildTable(BOOKS));</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>#main-content { min-height: 100vh; display: flex; } #form-flexbox { display: flex; flex-direction: column; width: 360px; padding: 40px; max-height: 100%; } #book-form { height: 50%; display: block; } #footer { position: fixed; bottom: 0; margin-bottom: 40px; } #library-container { display: flex; flex-direction: column; align-items: center; justify-content: start; padding: 40px; flex: 1; width: calc(100% - 350px); box-sizing: border-box; } .banner { width: 50%; height: 200px; background-image: url("https://live.staticflickr.com/2314/2854849909_4e5dcadff6_k.jpg"); background-position: 50% 50%; background-size: 300% 200%; z-index: -1; display: flex; justify-content: center; align-items: center; flex-direction: column; } .banner-text { color: white; } #title-banner { font-size: 42px; font-weight: 800; } #subtitle-banner { font-size: 30px; font-weight: 400; } /*Table Styles*/ table { border-collapse: collapse; border: 2px solid rgb(200, 200, 200); letter-spacing: 1px; font-size: 0.8rem; } td, th { border: 1px solid rgb(190, 190, 190); padding: 10px 20px; } th { background-color: rgb(235, 235, 235); } td { text-align: center; } tr:nth-child(even) td { background-color: rgb(250, 250, 250); } tr:nth-child(odd) td { background-color: rgb(245, 245, 245); } /* Layout construction temporary stuff */ .l0 { border: solid 3px black; } .l1 { border: solid 2px red; } .l2 { border: solid 1px orange; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;title&gt;Document&lt;/title&gt; &lt;link rel="stylesheet" href="style.css"&gt; &lt;/head&gt; &lt;body id="main-content" class="flexbox main-flexbox l0"&gt; &lt;div id="form-flexbox" class="flexbox form-container l1"&gt; &lt;header id="sidebar-header" class="l2"&gt;Form Box&lt;/header&gt; &lt;form id="book-form" onsubmit="testRec()" class="l2"&gt; &lt;label for="title-input"&gt;Book Title&lt;/label&gt; &lt;input type="text" id="title-input"&gt;&lt;br&gt; &lt;label for="author-input"&gt;Author&lt;/label&gt; &lt;input type="text" id="author-input"&gt;&lt;br&gt; &lt;label for="pages-input"&gt;Number of Pages&lt;/label&gt; &lt;input type="text" id="pages-input"&gt;&lt;br&gt; &lt;input type="checkbox" id="read-input"&gt; &lt;label for="read-input"&gt;Have you read this book?&lt;/label&gt;&lt;br&gt; &lt;input type="submit" id="submit-button" form="book-form" value="Submit Book"&gt; &lt;/form&gt; &lt;div id="footer" class="credit-flexbox flexbox l2"&gt; &lt;h3 class="footer-text l3"&gt;Fake web app project for learning purposes only&lt;/h3&gt; &lt;h3 class="footer-text l3"&gt;by &lt;a href="https://github.com/manski117"&gt;@manski117&lt;/a&gt;&lt;/h3&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="library-container" class="l1"&gt;library will go here &lt;div class="l2 banner"&gt; &lt;span id="title-banner" class="banner-text l3"&gt;Library&lt;/span&gt; &lt;span id="subtitle-banner" class="banner-text l3"&gt;Library&lt;/span&gt; &lt;/div&gt; &lt;div id="table-container" class="l2"&gt; &lt;/table&gt; &lt;/div&gt; &lt;div id="readout-container" class="l2"&gt; &lt;p id="readout"&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;script src="main.js"&gt;&lt;/script&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74366788, "author": "Chris", "author_id": 19681343, "author_profile": "https://Stackoverflow.com/users/19681343", "pm_score": 2, "selected": true, "text": "<div id=\"table-container\" class=\"l2\">\n </table>\n</div>\n" }, { "answer_id": 74366887, "author": "Barmar", "author_id": 1491895, "author_profile": "https://Stackoverflow.com/users/1491895", "pm_score": 0, "selected": false, "text": "toDel.remove();" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11309195/" ]
74,366,709
<p>So I am trying to test if I understand lifetimes, and wanted to create a scenario that would fail at compile time. The code I came up with is below:</p> <pre><code>#[test] fn lifetime() { struct Identity&lt;'a&gt; { first_name: &amp;'a str } let name: Identity; { let first: &amp;str = &quot;hello&quot;; name = Identity { first_name: first }; } println!(&quot;{}&quot;, name.first_name); } </code></pre> <p>the reasoning is that instance of <code>Identity</code> should live as long as what <code>first_name</code> refrences.</p> <p>Then in the code I create <code>let first: &amp;str = &quot;hello&quot;</code> with a smaller scope, set it to <code>let name: Identity;</code> and then after <code>first</code> should have gone out of scope, I then attempted to print <code>name.first_name</code>. I was expecting this not to compile,, but it compile fine.</p> <p>What am I missing in my understanding of how lifetimes work and why did this compile?</p> <p>#Edit</p> <p>updating the code to have this instead made the compilation fail:</p> <pre><code> let string = String::from(&quot;hello&quot;); let first: &amp;str = string.as_str(); </code></pre> <p>still curious to know why the original code worked.</p>
[ { "answer_id": 74366836, "author": "isaactfa", "author_id": 11423104, "author_profile": "https://Stackoverflow.com/users/11423104", "pm_score": 4, "selected": true, "text": "first" }, { "answer_id": 74366842, "author": "Özgür Murat Sağdıçoğlu", "author_id": 5106317, "author_profile": "https://Stackoverflow.com/users/5106317", "pm_score": 2, "selected": false, "text": "first" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12303851/" ]
74,366,726
<pre><code>struct ContentView: View { @State var error: Error? func ok() { error = nil } var body: some View { VStack {}.alert(&quot;Error&quot;, isPresented: error != nil) { Button(&quot;OK&quot;, action: ok) } message: { Text(error?.localizedDescription ?? &quot;&quot;) } } </code></pre> <p>How do you resolve <code>Cannot convert value of type 'Bool' to expected argument type 'Binding&lt;Bool&gt;'</code>? When you try to do this SwiftUI errors.</p>
[ { "answer_id": 74368647, "author": "whiteio", "author_id": 19222466, "author_profile": "https://Stackoverflow.com/users/19222466", "pm_score": 1, "selected": false, "text": "struct ContentView: View {\n @State var error: Error?\n @State var shouldShowModal = false\n\n func ok() {\n error = nil\n }\n\n var body: some View {\n VStack {}.alert(\"Error\", isPresented: $shouldShowModal) {\n Button(\"OK\", action: ok)\n } message: {\n Text(error?.localizedDescription ?? \"\")\n }\n .onChange(of: error) { newValue in \n shouldShowModal = newValue != nil\n }\n}\n" }, { "answer_id": 74369191, "author": "Jessy", "author_id": 652038, "author_profile": "https://Stackoverflow.com/users/652038", "pm_score": -1, "selected": false, "text": "Binding.constant" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/414415/" ]
74,366,747
<p>I've looked into Heap's algorithm for generating permutations, and all the numerous results on here for similar questions.</p> <p>But they all seem to want every permutation where the input can be shuffled around as much as it wants to be.</p> <p>I'd like a function that returns all possible substrings where the order remains the same so for input &quot;abc&quot; the result should not include &quot;cba&quot; for instance.</p> <p>Here's what I mean:</p> <p><code>getAllSubstrings(&quot;abcdefg&quot;)</code> should return:</p> <pre><code>[ &quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;,&quot;e&quot;,&quot;f&quot;,&quot;g&quot; &quot;ab&quot;,&quot;cd&quot;,&quot;ef&quot;, //&quot;g&quot; &quot;bc&quot;,&quot;de&quot;,&quot;fg&quot;, //&quot;a&quot; &quot;abc&quot;,&quot;def&quot;, //&quot;g&quot; &quot;bcd&quot;,&quot;efg&quot;, //&quot;a&quot; &quot;cde&quot;, //&quot;fg&quot;, &quot;ab&quot; &quot;abcd&quot;, //&quot;efg&quot; &quot;bcde&quot;, //&quot;a&quot;,&quot;fg&quot; &quot;cdef&quot;, //&quot;ab&quot;, &quot;g&quot; &quot;defg&quot;, //&quot;abc&quot; &quot;abcde&quot;, //&quot;fg&quot; &quot;bcdef&quot;, //&quot;a&quot;&quot;g&quot; &quot;cdefg&quot;, //&quot;ab&quot; &quot;abcdefg&quot; ] </code></pre> <p>Using <code>Set</code> to throw away the duplicate values is perfectly fine. I just can't wrap my head around how you would achieve the above. And it seems pretty simple...</p> <p>Anyone got any good ideas for how one can achieve this?</p>
[ { "answer_id": 74366805, "author": "trincot", "author_id": 5459839, "author_profile": "https://Stackoverflow.com/users/5459839", "pm_score": 3, "selected": true, "text": "function* getAllSubstrings(s) {\n for (let len = 1; len <= s.length; len++) {\n for (let i = 0; i + len <= s.length; i++) {\n yield s.slice(i, i + len);\n }\n }\n}\n\nconsole.log(Array.from(getAllSubstrings(\"abcedfg\")));" }, { "answer_id": 74366928, "author": "Nina Scholz", "author_id": 1447675, "author_profile": "https://Stackoverflow.com/users/1447675", "pm_score": 0, "selected": false, "text": "function* getAllSubstrings(s) {\n for (let i = 0; i < s.length; i++) yield s.slice(0, i + 1);\n if (s.length === 1) return;\n yield* getAllSubstrings(s.slice(1));\n}\n\nconsole.log(Array.from(getAllSubstrings(\"abcedfg\")));" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15067728/" ]
74,366,752
<p>I have a matrix that shows flight data and travellers names, with totals to show how many passengers are on each flight. I need to be able to filter this table down by the row totals so that only those with 2+ travellers are shown, but I cannot figure out how to do so since the count will always show as 1 for each line. <a href="https://i.stack.imgur.com/b7AeS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/b7AeS.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74366965, "author": "Strictly Funk", "author_id": 13366191, "author_profile": "https://Stackoverflow.com/users/13366191", "pm_score": 2, "selected": true, "text": "Summary Table = SUMMARIZE(Flights,Flights[Flight Number], \"Travelers\", Count(Flights[Traveler]))\n" }, { "answer_id": 74523806, "author": "courty340", "author_id": 13799997, "author_profile": "https://Stackoverflow.com/users/13799997", "pm_score": 0, "selected": false, "text": "Passenger Per Flight Filter = \nIF(\n [Passenger per Flight] <> BLANK(),\n CALCULATE( [Passenger per Flight], ALL( 'Dim Traveller' ) ),\n BLANK()\n)\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13799997/" ]
74,366,759
<p>I am trying to build a Spring Boot API using Spring Data JPA, Spring Web, and MySQL. I've done everything I am supposed to, it connects to the database, but Postman ALWAYS returns 404, &quot;Not Found&quot; error, no matter what I try. Spring Boot initializes succcesfully:</p> <pre><code> [0;39m [36mc.cg.TestProject.TestProjectApplication [0;39m [2m:[0;39m Starting TestProjectApplication using Java 17.0.3 on LNAR-5CG1514NF9 with PID 21336 (C:\Users\********\OneDrive - *********\Desktop\Orientation\TestProject\target\classes started by ******** in C:\Users\********\OneDrive - *********\Desktop\Orientation\TestProject) [0;39m [36mc.cg.TestProject.TestProjectApplication [0;39m [2m:[0;39m No active profile set, falling back to 1 default profile: &quot;default&quot; [0;39m [36m.s.d.r.c.RepositoryConfigurationDelegate[0;39m [2m:[0;39m Bootstrapping Spring Data JPA repositories in DEFAULT mode. [0;39m [36m.s.d.r.c.RepositoryConfigurationDelegate[0;39m [2m:[0;39m Finished Spring Data repository scanning in 80 ms. Found 1 JPA repository interfaces. [0;39m [36mo.s.b.w.embedded.tomcat.TomcatWebServer [0;39m [2m:[0;39m Tomcat initialized with port(s): 1111 (http) [0;39m [36mo.apache.catalina.core.StandardService [0;39m [2m:[0;39m Starting service [Tomcat] [0;39m [36morg.apache.catalina.core.StandardEngine [0;39m [2m:[0;39m Starting Servlet engine: [Apache Tomcat/9.0.68] [0;39m [36mo.a.c.c.C.[Tomcat].[localhost].[/] [0;39m [2m:[0;39m Initializing Spring embedded WebApplicationContext [0;39m [36mw.s.c.ServletWebServerApplicationContext[0;39m [2m:[0;39m Root WebApplicationContext: initialization completed in 974 ms [0;39m [36mo.hibernate.jpa.internal.util.LogHelper [0;39m [2m:[0;39m HHH000204: Processing PersistenceUnitInfo [name: default] [0;39m [36morg.hibernate.Version [0;39m [2m:[0;39m HHH000412: Hibernate ORM core version 5.6.12.Final [0;39m [36mo.hibernate.annotations.common.Version [0;39m [2m:[0;39m HCANN000001: Hibernate Commons Annotations {5.1.2.Final} [0;39m [36mcom.zaxxer.hikari.HikariDataSource [0;39m [2m:[0;39m HikariPool-1 - Starting... [0;39m [36mcom.zaxxer.hikari.HikariDataSource [0;39m [2m:[0;39m HikariPool-1 - Start completed. [0;39m [36morg.hibernate.dialect.Dialect [0;39m [2m:[0;39m HHH000400: Using dialect: org.hibernate.dialect.MySQL5InnoDBDialect [0;39m [36mo.h.e.t.j.p.i.JtaPlatformInitiator [0;39m [2m:[0;39m HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform] [0;39m [36mj.LocalContainerEntityManagerFactoryBean[0;39m [2m:[0;39m Initialized JPA EntityManagerFactory for persistence unit 'default' [0;39m [36mJpaBaseConfiguration$JpaWebConfiguration[0;39m [2m:[0;39m spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning [0;39m [36mo.s.b.w.embedded.tomcat.TomcatWebServer [0;39m [2m:[0;39m Tomcat started on port(s): 1111 (http) with context path '' [0;39m [36mc.cg.TestProject.TestProjectApplication [0;39m [2m:[0;39m Started TestProjectApplication in 2.839 seconds (JVM running for 3.873) [0;39m [36mo.a.c.c.C.[Tomcat].[localhost].[/] [0;39m [2m:[0;39m Initializing Spring DispatcherServlet 'dispatcherServlet' [0;39m [36mo.s.web.servlet.DispatcherServlet [0;39m [2m:[0;39m Initializing Servlet 'dispatcherServlet' [0;39m [36mo.s.web.servlet.DispatcherServlet [0;39m [2m:[0;39m Completed initialization in 1 ms </code></pre> <p>My project is divided into 5 packages: main class package(TestProject), POJOs, controllers, services, and repositories. I currently one have one, simple table I'm working with that stores a user's name, and &quot;password&quot; This is my main class called TestProjectApplication:</p> <pre><code>@EntityScan(&quot;com.cg.POJOs&quot;) @EnableJpaRepositories(&quot;com.cg.repositories&quot;) @SpringBootApplication public class TestProjectApplication { public static void main(String[] args) { SpringApplication.run(TestProjectApplication.class, args); } </code></pre> <p>My User POJO, and the UserRepo repository:</p> <pre><code>import javax.persistence.*; @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; private String name; private String password; public User() {} public User(int id, String name, String password) { super(); //OPTIONAL? this.id = id; this.name = name; this.password = password; } ...Getters, Setters, toString </code></pre> <pre><code>import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface UserRepo extends JpaRepository&lt;User,Integer&gt; { } </code></pre> <p>These have been largely unchanged, as they are pretty standard. Where it gets a little more confusing, and I have tried every type of and combination of Spring Boot annotations to no avail, is my UserServices interface, the UserServicesImpl implementation, and the UserController.</p> <p>UserServices and UserServicesImpl:</p> <pre><code>#UserServices: import java.util.List; public interface UserServices { // Save operation User saveUser(User user); // Read operation List&lt;User&gt; fetchUserList(); // Update operation User updateUser(User user, int userId); // Delete operation void deleteUserById(int userId); } #userServicesImpl: import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.ComponentScan; import org.springframework.stereotype.Service; @Service public class UserServicesImpl implements UserServices{ @Autowired private UserRepo userRepo; @Override public User saveUser(User user) { return userRepo.save(user); } @Override public List&lt;User&gt; fetchUserList() { return (List&lt;User&gt;)userRepo.findAll(); } ...updateUser(User user), deleteUserById(int id) are implemented. </code></pre> <p>And finally my controller class with a few test operations:</p> <pre><code>import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.ComponentScan; import org.springframework.web.bind.annotation.*; @RestController public class UserController { @Autowired private UserServices userServices; // Save operation @PostMapping(&quot;/users&quot;) public User saveUser(@RequestBody User department) { return userServices.saveUser(department); } // Read operation @GetMapping(&quot;/users&quot;) public List&lt;User&gt; fetchUserList() { return userServices.fetchUserList(); } // Read operation @GetMapping(&quot;/test&quot;) public List&lt;User&gt; fetchUsers() { return Arrays.asList( new User(12, &quot;Carlos&quot;,&quot;123123&quot;), new User(2, &quot;donald&quot;,&quot;123456&quot;) ); } </code></pre> <p>ALL requests I make, simply return a 404 &quot;Not Found&quot; error. An example request would be &quot;GET http://localhost:1111/test&quot;. The last bit of information I could possibly show that might show my mistake, is my application.properties file.</p> <pre><code>spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.jpa.show-sql: true spring.datasource.username=root spring.datasource.password=123456 spring.jpa.hibernate.ddl-auto=update server.port = 1111 spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect </code></pre> <p>Any ideas as to why it's not working would be greatly appreciated! Using Spring Boot 2.7.5 with Java 11 on the Spring Tool Suite IDE.</p>
[ { "answer_id": 74366965, "author": "Strictly Funk", "author_id": 13366191, "author_profile": "https://Stackoverflow.com/users/13366191", "pm_score": 2, "selected": true, "text": "Summary Table = SUMMARIZE(Flights,Flights[Flight Number], \"Travelers\", Count(Flights[Traveler]))\n" }, { "answer_id": 74523806, "author": "courty340", "author_id": 13799997, "author_profile": "https://Stackoverflow.com/users/13799997", "pm_score": 0, "selected": false, "text": "Passenger Per Flight Filter = \nIF(\n [Passenger per Flight] <> BLANK(),\n CALCULATE( [Passenger per Flight], ALL( 'Dim Traveller' ) ),\n BLANK()\n)\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20453187/" ]
74,366,770
<p>I am trying to use component MatSelect from Angular Material, on the iteration part i am using an array of objects that comes from a function</p> <p>Simple scenario that i got from Angular Material Website</p> <p>html file</p> <pre><code>&lt;h4&gt;Basic mat-select&lt;/h4&gt; &lt;mat-form-field appearance=&quot;fill&quot;&gt; &lt;mat-label&gt;Favorite food&lt;/mat-label&gt; &lt;mat-select&gt; &lt;mat-option *ngFor=&quot;let food of foods&quot; [value]=&quot;food.value&quot;&gt; {{food.viewValue}} &lt;/mat-option&gt; &lt;/mat-select&gt; &lt;/mat-form-field&gt; </code></pre> <p>ts file</p> <pre><code>import {Component} from '@angular/core'; interface Food { value: string; viewValue: string; } /** * @title Basic select */ @Component({ selector: 'select-overview-example', templateUrl: 'select-overview-example.html', }) export class SelectOverviewExample { foods: Food[] = [ {value: 'steak-0', viewValue: 'Steak'}, {value: 'pizza-1', viewValue: 'Pizza'}, {value: 'tacos-2', viewValue: 'Tacos'}, ]; } </code></pre> <p>Simple scenario of what i am trying to do and it doesn't just work but also it freezes the web app, no error displayed on console</p> <p>html file</p> <pre><code>&lt;h4&gt;Basic mat-select&lt;/h4&gt; &lt;mat-form-field appearance=&quot;fill&quot;&gt; &lt;mat-label&gt;Favorite food&lt;/mat-label&gt; &lt;mat-select&gt; &lt;mat-option *ngFor=&quot;let food of data()&quot; [value]=&quot;food.value&quot;&gt; {{food.viewValue}} &lt;/mat-option&gt; &lt;/mat-select&gt; &lt;/mat-form-field&gt; </code></pre> <p>ts file</p> <pre><code>import {Component} from '@angular/core'; interface Food { value: string; viewValue: string; } /** * @title Basic select */ @Component({ selector: 'select-overview-example', templateUrl: 'select-overview-example.html', }) export class SelectOverviewExample { foods: Food[] = [ {value: 'steak-0', viewValue: 'Steak'}, {value: 'pizza-1', viewValue: 'Pizza'}, {value: 'tacos-2', viewValue: 'Tacos'} ]; data(): Food[] { return [ {value: 'steak-0', viewValue: 'Steak'}, {value: 'pizza-1', viewValue: 'Pizza'}, {value: 'tacos-2', viewValue: 'Tacos'} ]; } } </code></pre> <p>Extra info, this works fine if the return value of the function is an array of strings</p> <p>html file</p> <pre><code>&lt;h4&gt;Basic mat-select&lt;/h4&gt; &lt;mat-form-field appearance=&quot;fill&quot;&gt; &lt;mat-label&gt;Favorite food&lt;/mat-label&gt; &lt;mat-select&gt; &lt;mat-option *ngFor=&quot;let food of data()&quot; [value]=&quot;food&quot;&gt; {{food}} &lt;/mat-option&gt; &lt;/mat-select&gt; &lt;/mat-form-field&gt; </code></pre> <p>ts file</p> <pre><code>import {Component} from '@angular/core'; interface Food { value: string; viewValue: string; } /** * @title Basic select */ @Component({ selector: 'select-overview-example', templateUrl: 'select-overview-example.html', }) export class SelectOverviewExample { foods: Food[] = [ {value: 'steak-0', viewValue: 'Steak'}, {value: 'pizza-1', viewValue: 'Pizza'}, {value: 'tacos-2', viewValue: 'Tacos'}, ]; foods2 = ['Steak', 'Pizza', 'Tacos']; data(): string[] { return ['Steak', 'Pizza', 'Tacos']; } } </code></pre>
[ { "answer_id": 74367246, "author": "Ignacio Ovidio Muñoz Nicolás", "author_id": 20123929, "author_profile": "https://Stackoverflow.com/users/20123929", "pm_score": 0, "selected": false, "text": "[value]=\"food.value\"" }, { "answer_id": 74369374, "author": "paranaaan", "author_id": 11634381, "author_profile": "https://Stackoverflow.com/users/11634381", "pm_score": 2, "selected": true, "text": "mat-option" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9028115/" ]
74,366,772
<p>I have a column <strong>number</strong> containing number and NaN. I want to add a column <strong>label</strong> identifying by 1 and 0 the &quot;zones&quot; where we have a number: the zone includes adjacents (above and below) rows.</p> <p>The result should look like below:</p> <pre><code>Number Label Nan 0 Nan 1 4 1 Nan 1 Nan 0 Nan 0 Nan 1 8.9 1 Nan 1 Nan 0 Nan 0 Nan 1 47 1 </code></pre> <p>I came up with the following solution. But it's ugly and it wound not scale if I wanted to Label more adjacent cells ( above + 2 below).</p> <pre><code>import numpy as np import pandas as pd pd.set_option('display.max_rows', 100) #Generating our DataFrame and ensuring there are some NaN df = pd.DataFrame(np.random.randn(100), columns=['number']) df.loc[df.number&lt;1] = np.nan #diffusing the values on adjacent cells and summing df['label'] = df.number.fillna(0) + df.number.shift(1).fillna(0) + df.number.shift(-1).fillna(0) #Replace values by 1 df.loc[df.label&gt;0, 'label'] = 1 print(df) </code></pre> <p>Could anyone help me find a more elegant solution? Maybe with a nice df.apply that I have so much difficulties using?</p>
[ { "answer_id": 74367146, "author": "Steinn Hauser Magnusson", "author_id": 13819183, "author_profile": "https://Stackoverflow.com/users/13819183", "pm_score": 0, "selected": false, "text": "label == 1" }, { "answer_id": 74368049, "author": "chrslg", "author_id": 20037042, "author_profile": "https://Stackoverflow.com/users/20037042", "pm_score": 1, "selected": false, "text": "shift" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5248243/" ]
74,366,808
<p>The title is mostly self-explanatory. I'm trying to create a program that opens a text file based on the title a user inputs in python. However, the program doesn't print anything - it's not taking time to compute and print out the text, but instead doesn't do anything.</p> <p>I've tried re-wording the program to not include the first function and simply ask the user for an input, but then I'm prompted with an error about the file not being in the proper directory. All I'm expecting is for it to print the contents of a file that the user specifies. Here is my code:</p> <pre><code>filename = 0 def get_filename(): filename = str(input(&quot;Give a file name: &quot;)) return filename def process_file(): reading = open(filename, &quot;r&quot;, encoding=&quot;utf-8&quot;) lines = reading.readlines() for line in lines: print(line) def main(): get_filename() process_file() main() filename.close() </code></pre>
[ { "answer_id": 74366872, "author": "quamrana", "author_id": 4834, "author_profile": "https://Stackoverflow.com/users/4834", "pm_score": 0, "selected": false, "text": "0" }, { "answer_id": 74366873, "author": "jsbueno", "author_id": 108205, "author_profile": "https://Stackoverflow.com/users/108205", "pm_score": 0, "selected": false, "text": "filename" }, { "answer_id": 74366907, "author": "BokiX", "author_id": 16843389, "author_profile": "https://Stackoverflow.com/users/16843389", "pm_score": 2, "selected": false, "text": "with open(input(\"Filename: \"), \"r\") as file:\n print(file.read())\n" }, { "answer_id": 74366925, "author": "0x0fba", "author_id": 20339407, "author_profile": "https://Stackoverflow.com/users/20339407", "pm_score": 0, "selected": false, "text": "get_filename()" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17468209/" ]
74,366,812
<p>I know this will cause memory leak because there is no unsubscription</p> <pre><code>interval(100).subscribe(console.log); </code></pre> <p>question is: If I do not pass any observer into subscribe method, is it still causing memory leak? thanks</p> <pre><code>interval(100).subscribe(); </code></pre>
[ { "answer_id": 74366872, "author": "quamrana", "author_id": 4834, "author_profile": "https://Stackoverflow.com/users/4834", "pm_score": 0, "selected": false, "text": "0" }, { "answer_id": 74366873, "author": "jsbueno", "author_id": 108205, "author_profile": "https://Stackoverflow.com/users/108205", "pm_score": 0, "selected": false, "text": "filename" }, { "answer_id": 74366907, "author": "BokiX", "author_id": 16843389, "author_profile": "https://Stackoverflow.com/users/16843389", "pm_score": 2, "selected": false, "text": "with open(input(\"Filename: \"), \"r\") as file:\n print(file.read())\n" }, { "answer_id": 74366925, "author": "0x0fba", "author_id": 20339407, "author_profile": "https://Stackoverflow.com/users/20339407", "pm_score": 0, "selected": false, "text": "get_filename()" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19776366/" ]
74,366,827
<p>I have a dataset like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">Date</th> <th style="text-align: center;">Account</th> <th style="text-align: center;">Spend</th> </tr> </thead> <tbody> <tr> <td style="text-align: center;">2/1/21</td> <td style="text-align: center;">A</td> <td style="text-align: center;">4</td> </tr> <tr> <td style="text-align: center;">3/1/21</td> <td style="text-align: center;">A</td> <td style="text-align: center;">6</td> </tr> <tr> <td style="text-align: center;">5/1/21</td> <td style="text-align: center;">A</td> <td style="text-align: center;">7</td> </tr> <tr> <td style="text-align: center;">6/1/21</td> <td style="text-align: center;">A</td> <td style="text-align: center;">2</td> </tr> <tr> <td style="text-align: center;">4/1/21</td> <td style="text-align: center;">B</td> <td style="text-align: center;">8</td> </tr> <tr> <td style="text-align: center;">5/1/21</td> <td style="text-align: center;">B</td> <td style="text-align: center;">2</td> </tr> <tr> <td style="text-align: center;">6/1/21</td> <td style="text-align: center;">B</td> <td style="text-align: center;">1</td> </tr> <tr> <td style="text-align: center;">9/1/21</td> <td style="text-align: center;">B</td> <td style="text-align: center;">7</td> </tr> </tbody> </table> </div> <p>Note that the dates the accounts span are NOT the same. I want to fill in zeroes for the missing months that are in between the minimum and maximum date for each account. The final table would look like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">Date</th> <th style="text-align: center;">Account</th> <th style="text-align: center;">Spend</th> </tr> </thead> <tbody> <tr> <td style="text-align: center;">2/1/21</td> <td style="text-align: center;">A</td> <td style="text-align: center;">4</td> </tr> <tr> <td style="text-align: center;">3/1/21</td> <td style="text-align: center;">A</td> <td style="text-align: center;">6</td> </tr> <tr> <td style="text-align: center;">4/1/21</td> <td style="text-align: center;">A</td> <td style="text-align: center;">0</td> </tr> <tr> <td style="text-align: center;">5/1/21</td> <td style="text-align: center;">A</td> <td style="text-align: center;">7</td> </tr> <tr> <td style="text-align: center;">6/1/21</td> <td style="text-align: center;">A</td> <td style="text-align: center;">2</td> </tr> <tr> <td style="text-align: center;">4/1/21</td> <td style="text-align: center;">B</td> <td style="text-align: center;">8</td> </tr> <tr> <td style="text-align: center;">5/1/21</td> <td style="text-align: center;">B</td> <td style="text-align: center;">2</td> </tr> <tr> <td style="text-align: center;">6/1/21</td> <td style="text-align: center;">B</td> <td style="text-align: center;">1</td> </tr> <tr> <td style="text-align: center;">7/1/21</td> <td style="text-align: center;">B</td> <td style="text-align: center;">0</td> </tr> <tr> <td style="text-align: center;">8/1/21</td> <td style="text-align: center;">B</td> <td style="text-align: center;">0</td> </tr> <tr> <td style="text-align: center;">9/1/21</td> <td style="text-align: center;">B</td> <td style="text-align: center;">7</td> </tr> </tbody> </table> </div> <p>What's the best way to go about this in Snowflake SQL?</p> <p>I thought I could cross join the accounts with another table that contains all months. Then I could join back to the original table and fill in any missing values within the Spend column with zeroes. But I'm unsure how to deal with the &quot;lagging&quot; and &quot;leading&quot; nulls that result from this. For example, there would be a null value for the combination of 2/1/21 and B after the cross join but that date occurs before the first occurrence of B in the original table (4/1/21) so I wouldn't want that row in my final dataset.</p>
[ { "answer_id": 74367231, "author": "GMB", "author_id": 10676716, "author_profile": "https://Stackoverflow.com/users/10676716", "pm_score": 2, "selected": true, "text": "calendar(date)" }, { "answer_id": 74367574, "author": "trillion", "author_id": 12513693, "author_profile": "https://Stackoverflow.com/users/12513693", "pm_score": 0, "selected": false, "text": "first_value" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8941248/" ]
74,366,841
<p>I want to implement a function which takes a key k :: Either a b, and a list of pairs. I want the keys to have two shapes. One of the shape Left l, which will perform a lookup on the left half of the pairs, and one for the right half. Both shall return the other half of the first matching pair in the list. If no match is found, the function should return Nothing.</p> <p>An instance of the Output with example list:</p> <pre><code>namesAges = [(&quot;Felix&quot;, 45), (&quot;Grace&quot;, 25), (&quot;Hans&quot;, 57), (&quot;Ivy&quot;, 25)] </code></pre> <pre><code>bidirectionalLookup (Left &quot;Grace&quot;) namesAges == Just (Right 25) bidirectionalLookup (Right 57) namesAges == Just (Left &quot;Hans&quot;) </code></pre> <p>I've successfully defined the functions for lookupRhs as well as lookupLhs but I am not able to combine them in my &quot;bidirectionalLookup&quot; function. What function form do I use? ITE, case-of, pattern-matching?</p> <p>This is one version of my attempts. I have many modifications but none gave me any results. I have a feeling that I am on the wrong track.</p> <pre><code>namesAges = [(&quot;Felix&quot;, 45), (&quot;Grace&quot;, 25), (&quot;Hans&quot;, 57), (&quot;Ivy&quot;, 25)] lookupLhs :: Eq a =&gt; a -&gt; [(a, b)] -&gt; Maybe b lookupLhs x ((l, r) : namesAges) = if x == l then Just r else lookupLhs x namesAges lookupRhs :: Eq b =&gt; b -&gt; [(a, b)] -&gt; Maybe a lookupRhs x ((l, r) : namesAges) = if x == r then Just l else lookupRhs x namesAges bidirectionalLookup :: (Eq b, Eq a) =&gt; Either a b -&gt; [(a, b)] -&gt; Maybe (Either a b) bidirectionalLookup (Left x) namesAges = lookupLhs x bidirectionalLookup (Right x) namesAges = lookupRhs x bidirectionalLookup _ _ = Nothing </code></pre> <p>I am aware that this is beginner level and that I may be completely off track (or have the answer right in front of my nose for that matter), still any kind of help will be greatly appreciated.</p>
[ { "answer_id": 74366984, "author": "Chris", "author_id": 15261315, "author_profile": "https://Stackoverflow.com/users/15261315", "pm_score": 3, "selected": true, "text": "bidirectionalLookup" }, { "answer_id": 74366988, "author": "Fyodor Soikin", "author_id": 180286, "author_profile": "https://Stackoverflow.com/users/180286", "pm_score": 2, "selected": false, "text": "lookupLhs" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20272631/" ]
74,366,843
<p>I'm trying to add a json file's name as a key to the file structure itself. For example:</p> <p>Input:</p> <pre><code>test.json {} </code></pre> <p>Output:</p> <pre><code>test.json { &quot;test&quot;: {} } </code></pre> <p>These are the commands I'm trying:</p> <pre><code>output=`cat $file` | jq --arg fn &quot;$file_name&quot; '. += {&quot;$fn&quot; : {}}' or # file_name already contains file name without extension output=`cat $file | jq --argjson k '{&quot;$file_name&quot;: {}}' '. += $k'` echo &quot;$output&quot; &gt; $file </code></pre> <p>However, the outputs are:</p> <pre><code>test.json { &quot;$fn&quot;: {} } test.json { &quot;$file_name&quot;: {} } </code></pre> <p>How do I make sure <code>jq</code> can recognize args as a variable and not a string literal ?</p>
[ { "answer_id": 74366918, "author": "pmf", "author_id": 2158479, "author_profile": "https://Stackoverflow.com/users/2158479", "pm_score": 3, "selected": true, "text": "input_filename" }, { "answer_id": 74366927, "author": "knittl", "author_id": 112968, "author_profile": "https://Stackoverflow.com/users/112968", "pm_score": 1, "selected": false, "text": "output=\"$(jq --arg fn \"$file_name\" '. += {$fn: {}}' $file)\"\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9030977/" ]
74,366,870
<p>This is what I'm doing:</p> <pre><code>$content = array(get_post_meta($postId, 'content')); $media = array(get_post_meta($postId, 'media')); $yt = array(get_post_meta($postId, 'youtube')); $max = max(count($content), count($media), count($yt)); $combined = []; for($i = 0; $i &lt;= $max; $i++) { if(isset($content[$i])) { $combined[] = [&quot;type&quot; =&gt; &quot;content&quot;, &quot;value&quot; =&gt; $content[$i]]; } if(isset($media[$i])) { $combined[] = [&quot;type&quot; =&gt; &quot;media&quot;, &quot;value&quot; =&gt; $media[$i]]; } if(isset($yt[$i])) { $combined[] = [&quot;type&quot; =&gt; &quot;youtube&quot;, &quot;value&quot; =&gt; $yt[$i]]; } } foreach ($combined as $key =&gt; $val) { echo '&lt;li&gt;'.$val['value'].'&lt;/li&gt;'; } </code></pre> <p>The result is:</p> <pre><code>Array Array Array </code></pre> <p>I'd expect:</p> <pre><code>media value content value youtube value </code></pre>
[ { "answer_id": 74367059, "author": "IT goldman", "author_id": 3807365, "author_profile": "https://Stackoverflow.com/users/3807365", "pm_score": 3, "selected": true, "text": "$single" }, { "answer_id": 74367096, "author": "Rob Eyre", "author_id": 20418616, "author_profile": "https://Stackoverflow.com/users/20418616", "pm_score": -1, "selected": false, "text": "$content = array(get_post_meta($postId, 'content'));\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1018804/" ]
74,366,889
<p>new bee in Kotlin and I am trying to compile a very simple thing. I'd like to initialize an array of lists with one line of code. But I get stuck in always have to uses mutable objects and inserts unto the list.</p> <p>Here what I have which <em>I don't like</em>. It is too complicated and many lines of code, the array does not need to be mutable in reality. It will be always the same size and same number of elements.</p> <pre><code>val r0 = arrayListOf&lt;Int&gt;(1, 3, 5, 7) val r1 = arrayListOf&lt;Int&gt;(10, 11, 16, 20) val r2 = arrayListOf&lt;Int&gt;(23, 30, 34, 60) val list: MutableList&lt;ArrayList&lt;Int&gt;&gt; = ArrayList() list.add(r0) list.add(r1) list.add(r2) </code></pre> <p>That works, but I want something like</p> <pre><code>val list2: List&lt;ArrayList&lt;Int&gt;&gt; = ArrayList( arrayListOf&lt;Int&gt;(1, 3, 5, 7), arrayListOf&lt;Int&gt;(10, 11, 16, 20), arrayListOf&lt;Int&gt;(23, 30, 34, 60) ) </code></pre> <p>But this does not compile, not sure why.</p> <p>thank you.</p>
[ { "answer_id": 74367059, "author": "IT goldman", "author_id": 3807365, "author_profile": "https://Stackoverflow.com/users/3807365", "pm_score": 3, "selected": true, "text": "$single" }, { "answer_id": 74367096, "author": "Rob Eyre", "author_id": 20418616, "author_profile": "https://Stackoverflow.com/users/20418616", "pm_score": -1, "selected": false, "text": "$content = array(get_post_meta($postId, 'content'));\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3657747/" ]
74,366,926
<p>I'd like to create a dropdown in an html form that will dynamically list the next four upcoming Saturdays. The idea is that when someone is signing up they can choose which of the four upcoming Saturdays they'd like to come in to visit our space, so we can keep track and send automated email responses. The time is the same every week so that's not an issue.</p> <p>Been trying to do this through Wordpress plugins but that's proving complicated to integrate with email software... I think it must be easier and cleaner to do it in html/javascript/php.</p>
[ { "answer_id": 74367059, "author": "IT goldman", "author_id": 3807365, "author_profile": "https://Stackoverflow.com/users/3807365", "pm_score": 3, "selected": true, "text": "$single" }, { "answer_id": 74367096, "author": "Rob Eyre", "author_id": 20418616, "author_profile": "https://Stackoverflow.com/users/20418616", "pm_score": -1, "selected": false, "text": "$content = array(get_post_meta($postId, 'content'));\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20453475/" ]
74,366,934
<p>I have data with several infrequent levels in each column. Find the <code>dput()</code> of a small portion of data at the bottom of the question. Here's how the data is structured;</p> <pre><code> AppointmentMonth DayofWeek AppointmentHour EncounterType 1 Sep Mon 16 Office Visit 2 Jun Tue 13 Office Visit 3 Sep Mon 14 Procedure Visit 4 Dec Thu 14 Office Visit 5 Mar Tue 11 Office Visit 6 May Fri 14 Office Visit 7 May Tue 11 Office Visit 8 May Tue 9 Office Visit ....... </code></pre> <p>When you check the frequency table of each column you will realize some levels have 0, 1, or 2 occurrences. Here is an example.</p> <pre><code>table(data$AppointmentHour) 8 9 10 11 12 13 14 15 16 17 4 4 2 4 1 2 8 1 3 1 </code></pre> <p>I would like to identify and remove the infrequent levels whose frequencies, let's say less than 3 (can be changed depending on the problem/data), in each column.</p> <p>I tried @akrun's answer in <a href="https://stackoverflow.com/questions/46282359/removing-infrequent-rows-in-a-data-frame/46282408?noredirect=1#comment131205274_46282408">this question</a>. Here is the code chunk:</p> <pre><code>library(data.table) setDT(data)[data[, .I[.N &gt;= 3], by = .(AppointmentMonth, DayofWeek, AppointmentHour, EncounterType)]$V1] </code></pre> <p>However, this code removes the infrequent levels based on the combination of columns, not based on each individual column.</p> <h4>Data:</h4> <pre><code>data &lt;- structure(list(AppointmentMonth = structure(c(9L, 6L, 9L, 12L, 3L, 5L, 5L, 5L, 7L, 10L, 9L, 12L, 7L, 3L, 11L, 9L, 11L, 12L, 12L, 7L, 1L, 6L, 7L, 12L, 1L, 3L, 11L, 4L, 9L, 4L), levels = c(&quot;Jan&quot;, &quot;Feb&quot;, &quot;Mar&quot;, &quot;Apr&quot;, &quot;May&quot;, &quot;Jun&quot;, &quot;Jul&quot;, &quot;Aug&quot;, &quot;Sep&quot;, &quot;Oct&quot;, &quot;Nov&quot;, &quot;Dec&quot;), class = c(&quot;ordered&quot;, &quot;factor&quot;)), DayofWeek = structure(c(2L, 3L, 2L, 5L, 3L, 6L, 3L, 3L, 3L, 5L, 4L, 2L, 2L, 4L, 2L, 5L, 3L, 2L, 4L, 3L, 4L, 6L, 6L, 5L, 2L, 2L, 3L, 2L, 3L, 5L), levels = c(&quot;Sun&quot;, &quot;Mon&quot;, &quot;Tue&quot;, &quot;Wed&quot;, &quot;Thu&quot;, &quot;Fri&quot;, &quot;Sat&quot;), class = c(&quot;ordered&quot;, &quot;factor&quot;)), AppointmentHour = c(16L, 13L, 14L, 14L, 11L, 14L, 11L, 9L, 9L, 11L, 12L, 10L, 16L, 15L, 8L, 8L, 11L, 8L, 14L, 8L, 16L, 9L, 14L, 14L, 13L, 9L, 10L, 14L, 17L, 14L), EncounterType = structure(c(`Office Visit` = 1L, `Office Visit` = 1L, `Procedure Visit` = 2L, `Office Visit` = 1L, `Office Visit` = 1L, `Office Visit` = 1L, `Office Visit` = 1L, `Office Visit` = 1L, `Office Visit` = 1L, Appointment = 3L, `Office Visit` = 1L, `Office Visit` = 1L, `Office Visit` = 1L, `Office Visit` = 1L, `Office Visit` = 1L, `Office Visit` = 1L, `Office Visit` = 1L, `Procedure Visit` = 2L, `Office Visit` = 1L, `Office Visit` = 1L, `Office Visit` = 1L, `Office Visit` = 1L, `Office Visit` = 1L, `Procedure Visit` = 2L, `Office Visit` = 1L, `Office Visit` = 1L, `Office Visit` = 1L, `Office Visit` = 1L, `Office Visit` = 1L, `Office Visit` = 1L), levels = c(&quot;Office Visit&quot;, &quot;Procedure Visit&quot;, &quot;Appointment&quot;, &quot;Treatment&quot;, &quot;Telemedicine&quot;), class = &quot;factor&quot;)), row.names = c(NA, 30L), class = &quot;data.frame&quot;) </code></pre>
[ { "answer_id": 74367005, "author": "MarcusCodrescu", "author_id": 20331897, "author_profile": "https://Stackoverflow.com/users/20331897", "pm_score": 0, "selected": false, "text": "data |>\n dplyr::add_count(\n AppointmentHour\n ) |>\n dplyr::filter(\n n < 3\n )\n#> AppointmentMonth DayofWeek AppointmentHour EncounterType n\n#> 1 Jun Tue 13 Office Visit 2\n#> 2 Sep Wed 12 Office Visit 1\n#> 3 Dec Mon 10 Office Visit 2\n#> 4 Mar Wed 15 Office Visit 1\n#> 5 Jan Mon 13 Office Visit 2\n#> 6 Nov Tue 10 Office Visit 2\n#> 7 Sep Tue 17 Office Visit 1\n" }, { "answer_id": 74367539, "author": "M--", "author_id": 6461462, "author_profile": "https://Stackoverflow.com/users/6461462", "pm_score": 2, "selected": true, "text": "inner_join" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74366934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9264869/" ]
74,367,007
<p>I was using RN V0.63.3 until <a href="https://github.com/facebook/react-native/issues/35210" rel="nofollow noreferrer">this </a>build failures happenings. I change my version to 0.63.5 and build done successfully. <strong>Now my application is being crashed instantly after build in development mode.</strong></p> <p>ERROR log :</p> <p>java.lang.UnsatisfiedLinkError: couldn't find DSO to load: libturbomodulejsijni.so SoSource 0: com.facebook.soloader.ApkSoSource[root = /data/user/0/com.zcarpet/lib-main flags = 1] SoSource 1: com.facebook.soloader.DirectorySoSource[root = ...</p> <p>I upgraded my gradle version from 3.5.2 to 3.5.3 and tried these fixes :</p> <ol> <li>I used this code in \Android\build.gradle :</li> </ol> <pre><code> configurations.all { resolutionStrategy { force &quot;com.facebook.react:react-native:0.63.5&quot; } } </code></pre> <ol start="2"> <li>Add below code in \Android\build.gridle :</li> </ol> <pre><code> project.ext.react = [ enableHermes: false, // clean and rebuild if changing deleteDebugFilesForVariant: { false } ] </code></pre> <ol start="3"> <li>many other fixes that could not help...</li> </ol> <p>my project configurations :</p> <pre><code> buildscript { ext { buildToolsVersion = &quot;29.0.2&quot; minSdkVersion = 21 compileSdkVersion = 29 targetSdkVersion = 29 } repositories { google() mavenCentral() jcenter() maven { url 'https://maven.fabric.io/public' } } dependencies { classpath(&quot;com.android.tools.build:gradle:3.5.3&quot;) // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files if (useIntlJsc) { implementation 'org.webkit:android-jsc-intl:+' } else { implementation 'org.webkit:android-jsc:+' } } } allprojects { configurations.all { resolutionStrategy { force &quot;com.facebook.react:react-native:0.63.5&quot; } } repositories { google() jcenter() mavenLocal() maven { // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm url(&quot;$rootDir/../node_modules/react-native/android&quot;) } maven { // Android JSC is installed from npm url(&quot;$rootDir/../node_modules/jsc-android/dist&quot;) } maven { url 'https://s3.amazonaws.com/repo.commonsware.com' } maven { url 'https://oss.sonatype.org/content/repositories/snapshots' } maven { url 'https://www.jitpack.io' } maven { url &quot;https://maven.google.com&quot; } google() maven { url 'https://www.jitpack.io' } } // Workaround for https://issuetracker.google.com/117900475 // Remove when upgrading to AGP 3.4 or higher. configurations.matching { it.name == '_internal_aapt2_binary' }.all { config -&gt; config.resolutionStrategy.eachDependency { details -&gt; details.useVersion(&quot;3.5.0-alpha03-5252756&quot;) } } } </code></pre>
[ { "answer_id": 74367005, "author": "MarcusCodrescu", "author_id": 20331897, "author_profile": "https://Stackoverflow.com/users/20331897", "pm_score": 0, "selected": false, "text": "data |>\n dplyr::add_count(\n AppointmentHour\n ) |>\n dplyr::filter(\n n < 3\n )\n#> AppointmentMonth DayofWeek AppointmentHour EncounterType n\n#> 1 Jun Tue 13 Office Visit 2\n#> 2 Sep Wed 12 Office Visit 1\n#> 3 Dec Mon 10 Office Visit 2\n#> 4 Mar Wed 15 Office Visit 1\n#> 5 Jan Mon 13 Office Visit 2\n#> 6 Nov Tue 10 Office Visit 2\n#> 7 Sep Tue 17 Office Visit 1\n" }, { "answer_id": 74367539, "author": "M--", "author_id": 6461462, "author_profile": "https://Stackoverflow.com/users/6461462", "pm_score": 2, "selected": true, "text": "inner_join" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74367007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3080525/" ]
74,367,019
<p>I'm trying to extract a certain character from a buffer that isn't ASCII. I'm reading in a file that contains movie names that have some non ASCII character sprinkled in it like so.</p> <pre class="lang-none prettyprint-override"><code>1|Tóy Story (1995) 2|GoldenEye (1995) 3|Four Rooms (1995) 4|Gét Shorty (1995) </code></pre> <p>I was able to pick off the lines that contained the non ASCII characters, but I'm trying to figure out how to get that particular character from the lines that have said non ASCII character and replace it with an ACSII character from the map I've made.</p> <pre><code>import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class Main { public static void main(String[] args) { HashMap&lt;Character, Character&gt;Char_Map = new HashMap&lt;&gt;(); Char_Map.put('o','ó'); Char_Map.put('e','é'); Char_Map.put('i','ï'); for(Map.Entry&lt;Character,Character&gt; entry: Char_Map.entrySet()) { System.out.println(entry.getKey() + &quot; -&gt; &quot;+ entry.getValue()); } try { BufferedReader br = new BufferedReader(new FileReader(&quot;movie-names.txt&quot;)); String contentLine= br.readLine(); while(contentLine != null) { String[] contents = contentLine.split(&quot;\\|&quot;); boolean result = contents[1].matches(&quot;\\A\\p{ASCII}*\\z&quot;); if(!result) { System.out.println(contentLine); //System.out.println(); } contentLine= br.readLine(); } } catch (IOException ioe) { System.out.println(&quot;Cannot open file as it doesn't exist&quot;); } } } </code></pre> <p>I tried using something along the lines of:</p> <pre><code>if((contentLine.charAt(i) == something </code></pre> <p>But I'm not sure.</p>
[ { "answer_id": 74367099, "author": "knittl", "author_id": 112968, "author_profile": "https://Stackoverflow.com/users/112968", "pm_score": 0, "selected": false, "text": "Map<Character, Character> charMap = new HashMap<>();\ncharMap.put('ó','o');\ncharMap.put('é','e');\ncharMap.put('ï','i');\n" }, { "answer_id": 74367272, "author": "Robert", "author_id": 1431720, "author_profile": "https://Stackoverflow.com/users/1431720", "pm_score": 2, "selected": true, "text": "replaceAll" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74367019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20453486/" ]
74,367,021
<p>Is there any way to search only the first line of a Multiline Textbox without knowing exactly at what position the text is you're looking for?</p> <p>If I knew the position of the text I was looking for I could do something like:</p> <pre><code>Dim myNotes As String = &quot;The book has a lot of text&quot; Dim myText As String = &quot;text&quot; If Not myNotes.Substring(0,4) = myText Then ' Do Something End If </code></pre> <p>Or if I wanted to search the entire textbox I could do something like:</p> <pre><code>Dim myNotes As String = &quot;The book has a lot of text&quot; Dim myText As String = &quot;text&quot; If Not myNotes.Contains(myText) Then ' Do Something End If </code></pre> <p>But I want to search only the first line of the textbox and I'm not sure at what position the text may be. Is there anyway to do a search like that?</p>
[ { "answer_id": 74367176, "author": "Jonathan Wood", "author_id": 522663, "author_profile": "https://Stackoverflow.com/users/522663", "pm_score": 2, "selected": true, "text": "int pos = text.IndexOfAny('\\r', '\\n');\nif (pos >= 0)\n text = text.SubString(0, pos);\n\n// text now contains only the first line\n" }, { "answer_id": 74368489, "author": "jmcilhinney", "author_id": 584183, "author_profile": "https://Stackoverflow.com/users/584183", "pm_score": 2, "selected": false, "text": "TextBox" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74367021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7201774/" ]
74,367,046
<pre><code>students = ['Ally',100, 'Emo',88, 'Stefan',70, 'George',60, 'Alex',45, 'Vasil',32, 'Daniel',0] passed_students = list(filter(lambda x: x &gt;= 60, students)) print(passed_students) </code></pre> <p>What did I do wrong,I also added 'str' before student,it didn't work so i added int but that also didn't work.</p>
[ { "answer_id": 74367100, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 1, "selected": false, "text": "students" }, { "answer_id": 74367193, "author": "Barmar", "author_id": 1491895, "author_profile": "https://Stackoverflow.com/users/1491895", "pm_score": 0, "selected": false, "text": "passed_students = [students[i] for i in range(0, len(students), 2) if students[i+1] >= 60]\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74367046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20453509/" ]
74,367,070
<p>I have written a super small logger in a typescript class and placed it in a file call <code>Log.ts</code>. The file also contains a type definition. I would like to reference it as a library so that I can create an instance of that class in the script lab script. How do I do that?</p> <p>I have placed the <code>Log.ts</code> file on a public website and referenced it in the Libraries tab in script lab but it is not getting picked up.</p> <p>What do I need to do to be able to create a new logger as <code>const log = new Log()</code>?</p> <h2>Update</h2> <p>I have tried to create a minimal example. This is now the <code>log.ts</code> file:</p> <pre><code>export type PongType = &quot;pong&quot;; export class Log { ping(): PongType { return &quot;pong&quot;; } } </code></pre> <p>I have compiled this to a <code>log.js</code> as:</p> <pre><code>var Log = /** @class */ (function () { function Log() { } Log.prototype.ping = function () { return &quot;pong&quot;; }; return Log; }()); export { Log }; </code></pre> <p>I have then placed <code>log.js</code> on a public server and then tried to import it in the HTML section in script lab as suggested in the comments. This is done as:</p> <p><code>&lt;script src=&quot;https://somedomain.com/log.js&quot;&gt;&lt;/script&gt;</code></p> <p>But I still don't understand how I could create an instance of <code>Log()</code> in the Script lab script.</p>
[ { "answer_id": 74367100, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 1, "selected": false, "text": "students" }, { "answer_id": 74367193, "author": "Barmar", "author_id": 1491895, "author_profile": "https://Stackoverflow.com/users/1491895", "pm_score": 0, "selected": false, "text": "passed_students = [students[i] for i in range(0, len(students), 2) if students[i+1] >= 60]\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74367070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18944680/" ]
74,367,084
<p>I have a list that looks like this:</p> <pre><code>lst = [(1,'X1', 256),(1,'X2', 356),(2,'X3', 223)] </code></pre> <p>The first item of each tuple is an ID and I want to marge the items of each tuple where the ID is the same. For example I want the list to look like this:</p> <pre><code>lst = [(1,('X1','X2'),(256,356)),(2,'X3',223) </code></pre> <p>How do I do this the easiest way?</p> <p>I have tried some solutions based on own logic but it did not work out.</p>
[ { "answer_id": 74367100, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 1, "selected": false, "text": "students" }, { "answer_id": 74367193, "author": "Barmar", "author_id": 1491895, "author_profile": "https://Stackoverflow.com/users/1491895", "pm_score": 0, "selected": false, "text": "passed_students = [students[i] for i in range(0, len(students), 2) if students[i+1] >= 60]\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74367084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20453405/" ]
74,367,090
<p>I want to implement an algorithm that basically moves every value(besides the last one) one place to the left, as in the first element becomes the second element, and so on.</p> <p>I have already implemented it like this:</p> <pre><code>for(int i = 0; i &lt; vct.size() - 1; i++){ vct[i] = vct[i + 1]; } </code></pre> <p>which works, but I was just wondering if there is a faster, optionally shorter way to achieve the same result?</p> <p><strong>EDIT</strong>: I have made a mistake where I said that I wanted it to move to the right, where in reality I wanted it to go left, so sorry for the confusion and thanks to everyone for pointing that out. I also checked if the vector isn't empty beforehand, just didn't include it in the snippet.</p>
[ { "answer_id": 74367243, "author": "Ahmed AEK", "author_id": 15649230, "author_profile": "https://Stackoverflow.com/users/15649230", "pm_score": 1, "selected": false, "text": "std::move_backwards" }, { "answer_id": 74368006, "author": "Jerry Coffin", "author_id": 179910, "author_profile": "https://Stackoverflow.com/users/179910", "pm_score": 3, "selected": true, "text": "std::deque" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74367090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16400339/" ]
74,367,143
<p>Please, help. I'm use scrapingant for bypass cloudflare. The task to develop a real-time data parser, stuck at the request stage... :(</p> <p>`</p> <pre><code>headers = { &quot;accept&quot;: &quot;*/*&quot;, &quot;accept-encoding&quot;: &quot;gzip, deflate, br&quot;, &quot;accept-language&quot;: &quot;ru-RU,ru;q=0.9,en-GB;q=0.8,en;q=0.7,en-US;q=0.6&quot;, &quot;cf-device-type&quot;: &quot;&quot;, &quot;content-length&quot;: &quot;3315&quot;, &quot;content-type&quot;: &quot;application/json&quot;, &quot;cookie&quot;: &quot;session_info=undefined; currency_currency=btc; currency_hideZeroBalances=false; currency_currencyView=crypto; currency_bankingCurrencies=[]; casinoSearch=['Monopoly','Crazy Time','Sweet Bonanza','Money Train','Reactoonz']; sportsSearch=['Liverpool FC','Kansas City Chiefs','Los Angeles Lakers','FC Barcelona','FC Bayern Munich']; oddsFormat=decimal; sportMarketGroupMap={}; locale=ru; intercom-id-cx1ywgf2=86f79ef7-ca71-4205-8f41-b73b0b559b2e; intercom-session-cx1ywgf2=; cookie_consent=true; leftSidebarView_v2=minimized; sidebarView=hidden; cf_clearance=6420a111bb498d49b56800690b298b7bba53e91d-1667643880-0-150; __cf_bm=cj_pRlIaag.zmXOLQPWJ0GEip_W3NuRcjBa.OlOvIzU-1667643883-0-Ad3+LGxBsAD+n4k5G6mVTfRhfqAthNtU9O9VY4MicOoFQ82/DvoS6h44JXKfexV2niXlGcEBTEMB9VUOYiNbr/2tr1EidvV2unVIk7hyX8cYAcc0btV2eZv1yvPZEcGumjKYXvKuFJOx/vPpi53NXizPc8apm56HvNxb9SkKULIy&quot;, &quot;dnt&quot;: &quot;1&quot;, &quot;origin&quot;: &quot;https://stake.com&quot;, &quot;referer&quot;: &quot;https://stake.com/sports/home&quot;, &quot;sec-ch-ua&quot;: &quot;'Google Chrome';v='107', 'Chromium';v='107', 'Not=A?Brand';v='24'&quot;, &quot;sec-ch-ua-mobile&quot;: &quot;?0&quot;, &quot;sec-ch-ua-platform&quot;: &quot;Windows&quot;, &quot;sec-fetch-dest&quot;: &quot;empty&quot;, &quot;sec-fetch-mode&quot;: &quot;cors&quot;, &quot;sec-fetch-site&quot;: &quot;same-origin&quot;, &quot;user-agent&quot;: &quot;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36&quot;, &quot;x-forwarded-for&quot;: &quot;88.99.58.45, 162.158.38.53, 172.20.242.28&quot;, &quot;x-geoip-country&quot;: &quot;DE&quot;, &quot;x-geoip-state&quot;: &quot;&quot;, &quot;x-language&quot;: &quot;ru&quot; } body = &quot;&quot;&quot; query highrollerSportBets($limit: Int!) { highrollerSportBets(limit: $limit) { ...RealtimeSportBet __typename } } fragment RealtimeSportBet on Bet { id iid bet { __typename ... on PlayerPropBet { ...PlayerPropBetFragment __typename } ... on SportBet { outcomes { fixture { data { __typename ... on SportFixtureDataMatch { competitors { name abbreviation __typename } __typename } } tournament { category { sport { slug __typename } __typename } __typename } __typename } __typename } createdAt potentialMultiplier amount currency user { id name __typename } __typename } } } fragment PlayerPropBetFragment on PlayerPropBet { __typename active amount cashoutMultiplier createdAt currency customBet id odds payout payoutMultiplier updatedAt status user { id name __typename } playerProps { id odds lineType playerProp { ...PlayerPropLineFragment __typename } __typename } } fragment PlayerPropLineFragment on PlayerPropLine { id line over under suspended balanced name player { id name __typename } market { id stat { name value __typename } game { id fixture { id name status eventStatus { ...FixtureEventStatus __typename } data { ... on SportFixtureDataMatch { __typename startTime competitors { ...CompetitorFragment __typename } } __typename } tournament { id category { id sport { id name slug __typename } __typename } __typename } __typename } __typename } __typename } } fragment FixtureEventStatus on SportFixtureEventStatus { homeScore awayScore matchStatus clock { matchTime remainingTime __typename } periodScores { homeScore awayScore matchStatus __typename } currentServer { extId __typename } homeGameScore awayGameScore statistic { yellowCards { away home __typename } redCards { away home __typename } corners { home away __typename } __typename } } fragment CompetitorFragment on SportFixtureCompetitor { name extId countryCode abbreviation } &quot;&quot;&quot; operationName = &quot;highrollerSportBets&quot; variables = {&quot;limit&quot;:10} url = 'https://stake.com/_api/graphql' sa_key = '280a2b7336344a8ea15106dd3220cc5a' sa_api = 'https://api.scrapingant.com/v2/general' qParams = {'url': url, 'x-api-key': sa_key} reqUrl = f'{sa_api}?{urllib.parse.urlencode(qParams)}' r = requests.post(url=reqUrl, json={&quot;query&quot;: body, &quot;operationName&quot;: operationName, &quot;variables&quot;: variables}, headers=headers) print(r.text) </code></pre> <p>`</p> <p>Output</p> <blockquote> <p>POST body missing, invalid Content-Type, or JSON object has no keys.</p> </blockquote> <p>Tell me, please, where did I make a mistake? Perhaps there is some library for similar tasks?</p> <p>I'm running with a VPN. Passing cookies is mandatory</p>
[ { "answer_id": 74367243, "author": "Ahmed AEK", "author_id": 15649230, "author_profile": "https://Stackoverflow.com/users/15649230", "pm_score": 1, "selected": false, "text": "std::move_backwards" }, { "answer_id": 74368006, "author": "Jerry Coffin", "author_id": 179910, "author_profile": "https://Stackoverflow.com/users/179910", "pm_score": 3, "selected": true, "text": "std::deque" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74367143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20453548/" ]
74,367,163
<p>I'm trying to make this design:</p> <p><a href="https://i.stack.imgur.com/yrOzK.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yrOzK.jpg" alt="enter image description here" /></a></p> <p>What I do is this:</p> <p><a href="https://i.stack.imgur.com/OnU0l.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OnU0l.jpg" alt="enter image description here" /></a></p> <p>I couldn't do the round icon in the right corner of <code>Latest</code> and the color change from <code>Premium</code> to <code>Free</code>. Can you help me?</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-bottom&gt;.filter-menu&gt;ul li { display: inline; } .body-bottom&gt;.filter-menu&gt;ul li a { padding: 15px; text-decoration: none; color: #222429; } .body-bottom&gt;.filter-menu&gt;ul li a:nth-child(2) { /* try */ color: red; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="body-bottom"&gt; &lt;div class="filter-menu"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href=""&gt;Latest&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=""&gt;Popular&lt;/a&gt;&lt;/li&gt; &lt;li&gt;|&lt;/li&gt; &lt;li&gt;&lt;a href=""&gt;Premium&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=""&gt;Free&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74367243, "author": "Ahmed AEK", "author_id": 15649230, "author_profile": "https://Stackoverflow.com/users/15649230", "pm_score": 1, "selected": false, "text": "std::move_backwards" }, { "answer_id": 74368006, "author": "Jerry Coffin", "author_id": 179910, "author_profile": "https://Stackoverflow.com/users/179910", "pm_score": 3, "selected": true, "text": "std::deque" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74367163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18003111/" ]