qid
int64
4
22.2M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,247,896
<p>I am validating form from server side. once I get error message, I wants to show error message on respective textbox field's error message</p> <p><strong>client side Object</strong></p> <pre><code>const formFields = { firstName: { helperText: '', error: false }, lastName: { helperText: '', error: false }, emailID: { helperText: '', error: false }, phoneNo: { helperText: '', error: false }, password: { helperText: '', error: false }, confirmPassword: { helperText: '', error: false } } </code></pre> <p><strong>Server side response object after validation</strong></p> <pre><code>const responseError = errorData.response.data.errors //below object is the response //{ //&quot;LastName&quot;: [&quot;Enter LastName&quot;], //&quot;FirstName&quot;: [&quot;Enter FirstName&quot;], //&quot;ConfirmPassword&quot;: [&quot;Enter Confirm Password&quot;,&quot;confirm password do not match&quot;] //} </code></pre> <p><strong>useState</strong></p> <pre><code>const [inpValues, setInpValues] = useState(formFields) </code></pre> <p><strong>Conditions to update</strong></p> <p>if ClientSideObj.key === responseObj.key then setInpValues of error and helperText field</p> <pre><code>const responseError = errorData.response.data.errors console.log(responseError) var FormFieldName = &quot;&quot; for (keys in formFields) { console.log('FormField keys = ' + keys) for (var errorKeys in responseError) { if (keys.toLowerCase() === errorKeys.toLowerCase()) { console.log('* MATCHED FIELDS = ' + errorKeys) //Matched 3 fields(LastName,FirstName,ConfirmPassword) successfully FormFieldName = keys setInpValues(prevInpValues =&gt; ({ ...prevInpValues, [FormFieldName]: { ...prevInpValues[FormFieldName], error: true, helperText: responseError[errorKeys] } }) ) console.table(inpValues) } } } </code></pre> <p><strong>Note</strong></p> <blockquote> <p>I go through this <a href="https://stackoverflow.com/questions/63377715/react-usestate-only-affecting-last-property-value">stack overflow</a> already, then I passed previousState values also. still result same.</p> </blockquote> <blockquote> <p>It's updating only the last for loop condition value</p> </blockquote> <blockquote> <p>If the response.error object has return only one field, then it's updating that one</p> </blockquote>
[ { "answer_id": 74248148, "author": "a_horse_with_no_name", "author_id": 330315, "author_profile": "https://Stackoverflow.com/users/330315", "pm_score": 2, "selected": false, "text": "select *\nfrom the_table\nwhere num_nonnulls(a,b,c,d) >= 2;\n" }, { "answer_id": 74249922, "a...
2022/10/29
[ "https://Stackoverflow.com/questions/74247896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7734785/" ]
74,247,921
<p>starting to get familiar with R. can't get why this simple chunk doesn't work</p> <p>want to do it particularly using 'break'</p> <pre><code>prime.check &lt;- function(num) { for (del in 2:(num-1)) { if (num %% del == 0) { break } print(paste(num, 'is not prime')) } } </code></pre>
[ { "answer_id": 74247982, "author": "danlooo", "author_id": 16853114, "author_profile": "https://Stackoverflow.com/users/16853114", "pm_score": 3, "selected": false, "text": "for" }, { "answer_id": 74248007, "author": "r2evans - GO NAVY BEAT ARMY", "author_id": 3358272, ...
2022/10/29
[ "https://Stackoverflow.com/questions/74247921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20367590/" ]
74,247,945
<p>I'm new to Python for the last 3 months but have quite a bit of development experience. I'm trying to figure out a good way to manage a collection of functions and classes that are shared across several projects. I'm working on a Windows 10 machine that I don't have admin access to, so the PATH variable is not an option. I'm using VS Code with Python 3.10</p> <p>I have several active projects and my current working directory structure is:</p> <p>python</p> <ul> <li>Project A</li> <li>Project B</li> <li>Project C</li> <li>Common</li> </ul> <ul> <li> <pre><code> __init__.py (empty) </code></pre> </li> <li> <pre><code> ClassA.py </code></pre> </li> <li> <pre><code> ClassB.py </code></pre> </li> <li> <pre><code> functions.py </code></pre> </li> </ul> <p>I've added a .pth file in AppData/Local/Programs/Python/Python310/Lib/site-packages which contains the path to the python root folder.</p> <p>Right now I'm able to use this configuration by importing each file as a separate module:</p> <pre><code>from Common.ClassA import ClassA from Common.ClassB import ClassB from Common import functions as fn </code></pre> <p>I would like to do something like:</p> <pre><code>from Common import ClassA, ClassB, functions as fn </code></pre> <p>Just looking for some experienced advice on how to manage this situation. Thanks to any and all who have time to respond.</p>
[ { "answer_id": 74247982, "author": "danlooo", "author_id": 16853114, "author_profile": "https://Stackoverflow.com/users/16853114", "pm_score": 3, "selected": false, "text": "for" }, { "answer_id": 74248007, "author": "r2evans - GO NAVY BEAT ARMY", "author_id": 3358272, ...
2022/10/29
[ "https://Stackoverflow.com/questions/74247945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1564070/" ]
74,247,954
<p>I study streams and solve various tasks with them. And I can’t cope with one, I have a map with cities and the amount of violence. I need to display only the name of the cities in descending order of the number of population.In fact, it should display the cities in this order Brest, Vitebsk,Minsk, Mogilev. No matter how I write, I can't, here's my code.</p> <pre><code> Map&lt;String,Integer&gt; cities = new HashMap&lt;&gt;(); cities.put(&quot;Minsk&quot;,1999234); cities.put(&quot;Mogilev&quot;,1599234); cities.put(&quot;Vitebsk&quot;,3999231); cities.put(&quot;Brest&quot;,4999234); List&lt;Integer&gt; collect =cities.entrySet().stream() .map(o-&gt;o.getValue()) .sorted(Comparator.reverseOrder()) .collect(Collectors.toList()); </code></pre> <p>So far, I was able to sort by population, but I don’t understand how to display the name of the cities sorted further</p>
[ { "answer_id": 74247982, "author": "danlooo", "author_id": 16853114, "author_profile": "https://Stackoverflow.com/users/16853114", "pm_score": 3, "selected": false, "text": "for" }, { "answer_id": 74248007, "author": "r2evans - GO NAVY BEAT ARMY", "author_id": 3358272, ...
2022/10/29
[ "https://Stackoverflow.com/questions/74247954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17047574/" ]
74,247,961
<p>As you can see in the these two photos below, this problem happened only when the address contains many words, if the address contains fewer words I don't see any issues, I got stuck here and can't think anymore :) what shall I do in this case, please?</p> <p>Code:</p> <pre><code> child: Column( mainAxisSize: MainAxisSize.min, children: [ Row( children: [ UserAvatarView( urlPrefix: serverUrl, url: null, cornerRadius: 60, size: 20), const SizedBox(width: 8), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( order.service.name, style: Theme.of(context).textTheme.titleMedium, ), Text( &quot;${(driverDistance / 1000).round()} KM away&quot;, style: Theme.of(context).textTheme.labelMedium, ) ], ), const Spacer(), Container( padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), decoration: BoxDecoration( color: CustomTheme.primaryColors.shade200, borderRadius: BorderRadius.circular(12)), child: Text( NumberFormat.simpleCurrency(name: order.currency) .format(order.costBest), style: Theme.of(context).textTheme.headlineMedium, ), ) ], ), const Divider(), ...order.addresses.mapIndexed((e, index) { if (order.addresses.length &gt; 2 &amp;&amp; index &gt; 0 &amp;&amp; index != order.addresses.length - 1) { return const SizedBox( width: 1, height: 1, ); } return Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ Padding( padding: const EdgeInsets.all(0), child: Icon( getIconByIndex(index, order.addresses.length), color: CustomTheme.neutralColors.shade500, ), ), Expanded( child: Text(e, overflow: TextOverflow.visible, style: Theme.of(context).textTheme.bodySmall), ), if (index == order.addresses.length - 1) Text( order.durationBest == 0 ? &quot;&quot; : durationToString( Duration(seconds: order.durationBest)), style: Theme.of(context).textTheme.bodySmall) ], ).pOnly(right: 0), if (index &lt; order.addresses.length - 1) DottedLine( direction: Axis.vertical, lineLength: 25, lineThickness: 3, dashLength: 3, dashColor: CustomTheme.neutralColors.shade500) .pOnly(left: 10) ], ); }).toList(), const Spacer(), Row( children: order.options .map((e) =&gt; OrderPreferenceTagView( icon: e.icon, name: e.name, )) .toList()), ElevatedButton( onPressed: !isActionActive ? null : () =&gt; onAcceptCallback(order.id), child: Row( children: [ const Spacer(), Text(S.of(context).available_order_action_accept), const Spacer() ], ).p4()) .p4() ], ), </code></pre> <p>Photo of a few address words: <a href="https://i.stack.imgur.com/Wz3gD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Wz3gD.png" alt="enter image description here" /></a></p> <p>Photo of many address words: <a href="https://i.stack.imgur.com/84yb0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/84yb0.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74247982, "author": "danlooo", "author_id": 16853114, "author_profile": "https://Stackoverflow.com/users/16853114", "pm_score": 3, "selected": false, "text": "for" }, { "answer_id": 74248007, "author": "r2evans - GO NAVY BEAT ARMY", "author_id": 3358272, ...
2022/10/29
[ "https://Stackoverflow.com/questions/74247961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5992559/" ]
74,247,969
<p>I'm learning javascript through MDN documentation. They have an example on the <a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Functions" rel="nofollow noreferrer">function topic</a> which apparently I'm unable to understand.</p> <pre><code>const textBox = document.querySelector(&quot;#textBox&quot;); const output = document.querySelector(&quot;#output&quot;); textBox.addEventListener('keydown', (event) =&gt; output.textContent = `You pressed &quot;${event.key}&quot;.`); </code></pre> <p>I've read a few documentation on<strong>key down</strong> function and I assume it is supposed to return some value for every character entered (correct me if I'm wrong); but in the example on MDN, it only returns <strong>enter</strong> when I press enter key and <strong>backspace</strong> when I press backspace (while input box has no other characters). I'm reading this example on a mobile device btw.</p>
[ { "answer_id": 74248041, "author": "IT goldman", "author_id": 3807365, "author_profile": "https://Stackoverflow.com/users/3807365", "pm_score": 0, "selected": false, "text": "const textBox = document.querySelector(\"#textBox\");\n\nconst output = document.querySelector(\"#output\");\n\nt...
2022/10/29
[ "https://Stackoverflow.com/questions/74247969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20114922/" ]
74,248,004
<p>I'm working on document clustering where I first build a distance matrix from the tf-idf results. I use the below code to get my tf-idf matrix:</p> <pre><code>from sklearn.feature_extraction.text import TfidfVectorizer vectorizer = TfidfVectorizer(stop_words={'english'}) X = vectorizer.fit_transform(models) </code></pre> <p>This results in a matrix of (9069, 22210). Now I want to build a distance matrix from this (9069*9069). I'm using the following code for that:</p> <pre><code>import numpy as np import pandas as pd from scipy.spatial import distance_matrix from scipy.spatial import distance arrX = X.toarray() rowSize = X.shape[0] distMatrix = np.zeros(shape=(rowSize, rowSize)) #build distance matrix for i, x in enumerate(arrX): for j, y in enumerate(arrX): distMatrix[i][j] = distance.braycurtis(x, y) np.savetxt(&quot;dist.csv&quot;, distMatrix, delimiter=&quot;,&quot;) </code></pre> <p>The problem with this code is that it's extremely slow for this matrix size. Is there a faster way of doing this?</p>
[ { "answer_id": 74253179, "author": "Jérôme Richard", "author_id": 12939557, "author_profile": "https://Stackoverflow.com/users/12939557", "pm_score": 1, "selected": false, "text": "O(n^3)" } ]
2022/10/29
[ "https://Stackoverflow.com/questions/74248004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1789591/" ]
74,248,034
<h1>I don't know how to make the bottom navigation bar blur with the background in Flutter as shown below<a href="https://i.stack.imgur.com/yUPF6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yUPF6.png" alt="enter image description here" /></a></h1> <p>I want the bottom navigation bar to blur the background near the bottom of the screen, but I can only do it below with a white background with two very thick top and bottom borders that obscure the content</p> <p><a href="https://i.stack.imgur.com/1Puio.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1Puio.png" alt="enter image description here" /></a></p> <p>here is my code,</p> <pre><code>class _MainPageState extends State&lt;MainPage&gt; { var currentIndex = 0; //int currentIndex = 0; void onTabTapped(int index) { setState(() { currentIndex = index; HapticFeedback.lightImpact(); }); } final screens = [ const HomePage(), NotificationPage(), MessagePage(), BookmarkPage(), ]; List&lt;IconData&gt; listOfIcons = [ Icons.home_rounded, Icons.notifications, Icons.message_rounded, Icons.library_books, ]; List&lt;String&gt; listOfStrings = [ 'Home', 'T.báo', 'T.Nhắn', 'B.Đăng', ]; @override Widget build(BuildContext context) { double displayWidth = MediaQuery.of(context).size.width; return Scaffold( backgroundColor: Colors.white, body: SafeArea(child: screens[currentIndex]), bottomNavigationBar: Container( margin: EdgeInsets.all(displayWidth * .03), height: displayWidth * .155, decoration: BoxDecoration( color: Colors.white, boxShadow: [ BoxShadow( color: Colors.black.withOpacity(.1), blurRadius: 30, offset: Offset(0, 10), ), ], borderRadius: BorderRadius.circular(50), ), child: ListView.builder( itemCount: 4, scrollDirection: Axis.horizontal, padding: EdgeInsets.symmetric(horizontal: displayWidth * .02), itemBuilder: (context, index) =&gt; InkWell( onTap: () { setState(() { currentIndex = index; HapticFeedback.lightImpact(); }); }, splashColor: Colors.transparent, highlightColor: Colors.transparent, child: Stack( children: [ AnimatedContainer( duration: Duration(seconds: 1), curve: Curves.fastLinearToSlowEaseIn, width: index == currentIndex ? displayWidth * .32 : displayWidth * .18, alignment: Alignment.center, child: AnimatedContainer( duration: Duration(seconds: 1), curve: Curves.fastLinearToSlowEaseIn, height: index == currentIndex ? displayWidth * .12 : 0, width: index == currentIndex ? displayWidth * .32 : 0, decoration: BoxDecoration( color: index == currentIndex ? Color(0xffEC1C24).withOpacity(.2) : Colors.transparent, borderRadius: BorderRadius.circular(50), ), ), ), AnimatedContainer( duration: Duration(seconds: 1), curve: Curves.fastLinearToSlowEaseIn, width: index == currentIndex ? displayWidth * .31 : displayWidth * .18, alignment: Alignment.center, child: Stack( children: [ Row( children: [ AnimatedContainer( duration: Duration(seconds: 1), curve: Curves.fastLinearToSlowEaseIn, width: index == currentIndex ? displayWidth * .13 : 0, ), AnimatedOpacity( opacity: index == currentIndex ? 1 : 0, duration: Duration(seconds: 1), curve: Curves.fastLinearToSlowEaseIn, child: Text( index == currentIndex ? '${listOfStrings[index]}' : '', style: TextStyle( color: Color(0xffEC1C24), fontWeight: FontWeight.w600, fontSize: 15, ), ), ), ], ), Row( children: [ AnimatedContainer( duration: Duration(seconds: 1), curve: Curves.fastLinearToSlowEaseIn, width: index == currentIndex ? displayWidth * .03 : 20, ), Icon( listOfIcons[index], size: displayWidth * .076, color: index == currentIndex ? Color(0xffEC1C24) : Colors.black26, ), ], ), ], ), ), ], ), ), ), ), ); } } </code></pre> <p>Thank you very much for your comments and contributions.</p>
[ { "answer_id": 74253179, "author": "Jérôme Richard", "author_id": 12939557, "author_profile": "https://Stackoverflow.com/users/12939557", "pm_score": 1, "selected": false, "text": "O(n^3)" } ]
2022/10/29
[ "https://Stackoverflow.com/questions/74248034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20249248/" ]
74,248,066
<pre><code>window.setFramerateLimit(60); while(window.isOpen()) { //manage events } </code></pre> <p>this above while loop runs 60 times in 1 second after we set the frame rate limit, I want to know how does SFML internally manage to run the while loop in a controlled manner(i.e maintaining frame rate) by just using the &quot;window.isOpen()&quot; function in while loop condition. Or is there anything else working under the hood.</p> <p>I am unable to understand how does setFramerateLimit works in SFML.</p>
[ { "answer_id": 74248416, "author": "alter_igel", "author_id": 5023438, "author_profile": "https://Stackoverflow.com/users/5023438", "pm_score": 1, "selected": false, "text": "window.display()" } ]
2022/10/29
[ "https://Stackoverflow.com/questions/74248066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20208110/" ]
74,248,105
<p>im using fakeapi store to fetch products and loop on them to show in a component im using a service to do that and it goes as follows</p> <pre><code>import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { environment } from 'src/environments/environment'; @Injectable({ providedIn: 'root', }) export class ProductsService { eleProducts: any[]; spinnerElec: boolean; constructor(private http: HttpClient) { this.spinnerElec = true; this.eleProducts = []; } getElectronics() { this.spinnerElec = true; this.http .get(environment.baseUrl + '/category/electronics') .subscribe((res: any) =&gt; { this.eleProducts = res; this.spinnerElec = false; }); } </code></pre> <p>then in the electronics-component.ts</p> <pre><code>export class ElectronicsComponent implements OnInit { Products: any[]; spinner: boolean; constructor(public service: ProductsService) { this.Products = []; this.spinner = true; } ngOnInit(): void { this.getProducts(); } getProducts() { this.spinner = this.service.spinnerElec; this.service.getElectronics(); this.Products = this.service.eleProducts; } </code></pre> <p>and to display data in electronics-component.html</p> <pre><code>&lt;div class=&quot;row gap-3 justify-content-center&quot; *ngIf=&quot;!spinner&quot;&gt; &lt;div class=&quot;card col-lg-4 col-md-6 col-sm-12 bg-warning&quot; style=&quot;width: 18rem&quot; *ngFor=&quot;let product of Products&quot; &gt; &lt;app-product [elecCart]=&quot;service.elecCart&quot; [Product]=&quot;product&quot; (target)=&quot;addToCart($event)&quot; &gt;&lt;/app-product&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;spin d-flex justify-content-center align-items-center w-100&quot; *ngIf=&quot;spinner&quot; &gt; &lt;app-spinner&gt;&lt;/app-spinner&gt; &lt;/div&gt; </code></pre> <p>im using ngif on the spinner to clear it from the dom and show data once it fetched sucessfuly the problem is that i must open the componet then go to another component then come back to it again to show the data otherwise the data wont show... thanks in advance</p>
[ { "answer_id": 74248263, "author": "Andres2142", "author_id": 2841091, "author_profile": "https://Stackoverflow.com/users/2841091", "pm_score": 2, "selected": false, "text": "getProducts" }, { "answer_id": 74254614, "author": "jesus marmol", "author_id": 20102799, "au...
2022/10/29
[ "https://Stackoverflow.com/questions/74248105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19587061/" ]
74,248,108
<p>my function wont carry out for the button assigned. Im using visual studio code. For the def myClick(): myLabel =Label(window, text ..., command...</p> <p>it wont occur. on visual studio code, the 'myLabel' greys out and has the error 'is not accessedPylance'</p> <pre><code># add response to input def myClick(): myLabel = Label(window, text=&quot;Hello&quot; + e.get() + &quot;... &quot;) myLabel.pack # create button myButton = Button(window, text=&quot;next&quot;, command=myClick, fg=&quot;black&quot;) myButton.pack() </code></pre>
[ { "answer_id": 74248167, "author": "quamrana", "author_id": 4834, "author_profile": "https://Stackoverflow.com/users/4834", "pm_score": 2, "selected": true, "text": "pack()" }, { "answer_id": 74248173, "author": "Jan Niedospial", "author_id": 17995694, "author_profile...
2022/10/29
[ "https://Stackoverflow.com/questions/74248108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20366624/" ]
74,248,109
<p>I am practicing JavaScript Proxies and want to access a method from another object but with an empty Proxy object:</p> <pre class="lang-js prettyprint-override"><code>const data = { hello: { log() { return 'hello log' }, }, hi: { log() { return 'hi log' }, }, } const blankObject = {} // I can just pass the data object but I want an empty one const proxy = new Proxy(blankObject, { get(target, key) { const v = target[key] if (typeof v === 'function') { // if data.hello.log() or data.hi.log() return function() { return data[key]['WHAT_TO_DO']// access data.hello.log or data.hi.log() here? } } return v } }) proxy.hello.log() // hello log; </code></pre> <p>Basically I'm trying to check if that method property exist in another object. I just want to tell the proxy to get the value from another object without passing it into the constructor.</p>
[ { "answer_id": 74248172, "author": "dqhendricks", "author_id": 512922, "author_profile": "https://Stackoverflow.com/users/512922", "pm_score": 1, "selected": false, "text": "const blankObject = { hello: data.hello };\n" }, { "answer_id": 74248304, "author": "trincot", "au...
2022/10/29
[ "https://Stackoverflow.com/questions/74248109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19591579/" ]
74,248,156
<p>I have a fairly straightforward database schema. I have a list of Cemeteries, each Cemetery may have a CountryId for where it's located. The majority are currently null. I am attempting to return a paged result.</p> <p>If I do the below, it works perfectly fine, fast and paged. If I use the <code>.Include</code>, I can see the <code>List&lt;T&gt;</code> returned to the controller, and the controllers return sit to the API. The API however shows error 500.</p> <pre><code>public Shared.Models.Paging.PagedResult&lt;Cemetery&gt; List(int page, string filter) { const int pageSize = 10; var data = _ctx.Cemeteries // .Include(p =&gt; p.Country) .AsNoTracking() .AsQueryable(); if (!string.IsNullOrEmpty(filter) &amp;&amp; filter != &quot;null&quot;) { data = data.Where(filter); } return data.GetPaged(page, pageSize); } public partial class Cemetery { public int Id { get; set; } public string Name { get; set; } = null!; public int? CountryId { get; set; } public DateTime? CreatedAt { get; set; } public DateTime? UpdatedAt { get; set; } public virtual Country? Country { get; set; } } public partial class Country { public Country() { Cemeteries = new HashSet&lt;Cemetery&gt;(); } public int Id { get; set; } public string Name { get; set; } = null!; public DateTime? CreatedAt { get; set; } public DateTime? UpdatedAt { get; set; } public virtual ICollection&lt;Cemetery&gt; Cemeteries { get; set; } } </code></pre> <p>If I place a <code>try/catch</code> in the code, all I get is an error 500, the server did not indicate success.</p> <pre><code>public async Task&lt;PagedResult&lt;CemeteryModel&gt;&gt; List(int page, string filter) { var searchParams = $&quot;/{page}?filter=&quot;; searchParams += string.IsNullOrEmpty(filter) ? &quot;null&quot; : filter; return await _httpClient.GetFromJsonAsync&lt;PagedResult&lt;CemeteryModel&gt;&gt;($&quot;api/Cemetery/List{searchParams}&quot;); } </code></pre>
[ { "answer_id": 74248172, "author": "dqhendricks", "author_id": 512922, "author_profile": "https://Stackoverflow.com/users/512922", "pm_score": 1, "selected": false, "text": "const blankObject = { hello: data.hello };\n" }, { "answer_id": 74248304, "author": "trincot", "au...
2022/10/29
[ "https://Stackoverflow.com/questions/74248156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1555453/" ]
74,248,195
<p>I want divide a 8-digit number into parts with a 4 digit. pls help</p> <pre><code> def div4(a, n = 4): return [a [i*4: (i + 1) * 4] for i in range (len(a) // n)] </code></pre> <p>i tried this but it wont work</p>
[ { "answer_id": 74248217, "author": "wim", "author_id": 674039, "author_profile": "https://Stackoverflow.com/users/674039", "pm_score": 1, "selected": false, "text": "divmod" }, { "answer_id": 74248478, "author": "Chris", "author_id": 15261315, "author_profile": "https...
2022/10/29
[ "https://Stackoverflow.com/questions/74248195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18528605/" ]
74,248,207
<p>I am trying to read several TXT files, I make some modifications to them and then I convert them into a DataFrame with Pandas and there I also run some modification processes, so far everything is fine, everything works perfect, I do it through a for loop but at the moment of save the xlsx file and create the first sheet and it doesn't create new sheets, it just creates the first one.</p> <p>the code is the following:</p> <pre><code>from netmiko import ConnectHandler from datetime import datetime import re from pathlib import Path import os import pandas as pd ruta = Path(&quot;E:\Python\Visual Studio Code Proyects\M2M Real\Archivos&quot;) def is_free(valor): color = 'green' if valor == &quot;free&quot; else 'white' return 'background-color: %s' % color list_txt = [ruta/&quot;Router_a.txt&quot;, ruta/&quot;Router_b.txt&quot;] for txt in list_txt: host = txt.stem sheet_name=f'{host}-Gi0-3-4-2' ruta_host = f'{ruta}\\interfaces.xlsx' df = pd.read_fwf(txt) df[&quot;Description&quot;] = (df.iloc[:, 3:].fillna(&quot;&quot;).astype(str).apply(&quot; &quot;.join, axis=1).str.strip()) df = df.iloc[:, :4] df = df.drop(columns = [&quot;Status&quot;, &quot;Protocol&quot;]) df.Interface = df.Interface.str.extract('Gi0/3/4/2\.(\d+)') df = df[df.Interface.notnull()].reset_index() df = df.drop(columns = [&quot;index&quot;]) df['Interface'] = df['Interface'].astype(int) df = df.set_index('Interface').reindex(range(1,50)).fillna('free').reset_index() df = df.style.applymap(is_free) with pd.ExcelWriter(ruta_host, mode='a') as writer: df.to_excel(writer, sheet_name, index=False) </code></pre> <p>the format of the txt is as follows, it is worth clarifying that basically both txt from both routers are almost identical:</p> <pre><code>Interface Status Protocol Description Gi0/3/4/2 up up ENLACE A Router_X Gi0/3/4/2.5 up up Frontera Cliente A Gi0/3/4/2.6 up up Frontera Cliente B Gi0/3/4/2.7 up up Frontera Cliente C Gi0/3/4/2.8 up up Frontera Cliente D Gi0/3/4/2.9 up up Frontera Cliente E </code></pre> <p>Any idea what I'm doing wrong?</p>
[ { "answer_id": 74251857, "author": "Pranay", "author_id": 4182362, "author_profile": "https://Stackoverflow.com/users/4182362", "pm_score": 0, "selected": false, "text": "with pd.ExcelWriter(ruta_host, mode='a') as writer\n" }, { "answer_id": 74256900, "author": "Martin Barbi...
2022/10/29
[ "https://Stackoverflow.com/questions/74248207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20178424/" ]
74,248,224
<p>Django Version: 4.1.2</p> <p>Exception Type: FieldError</p> <p>Exception Value: Cannot resolve keyword ‘data’ into the field. Choices are: id, nome</p> <p>Here are my codes</p> <pre class="lang-py prettyprint-override"><code>#model from django.db import models class Teste(models.Model): nome = models.CharField(max_length = 100) #serializer from rest_framework import serializers from .models import Teste class TesteSerializer(serializers.ModelSerializer): class Meta: model = Teste fields = '__all__' #view from .models import Teste from .serializer import TesteSerializer from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.parsers import JSONParser @api_view(['POST']) def create_teste(request): #data = JSONParser().parse(request) teste = Teste.objects.get(data = request.data) serializer = TesteSerializer(teste) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.errors) </code></pre> <p>Hi, I'm trying to make an essay for <code>django_rest_framework</code> but I'm facing this error.</p>
[ { "answer_id": 74249430, "author": "Utkucan Bıyıklı", "author_id": 7437136, "author_profile": "https://Stackoverflow.com/users/7437136", "pm_score": 2, "selected": true, "text": "data" }, { "answer_id": 74289973, "author": "Mohsin Maqsood", "author_id": 11561910, "aut...
2022/10/29
[ "https://Stackoverflow.com/questions/74248224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12064384/" ]
74,248,240
<p>I'm trying to run <strong>2 async functions <code>test1()</code> and <code>test2()</code></strong> with <a href="https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.run_until_complete" rel="nofollow noreferrer"><strong>loop.run_until_complete()</strong></a> alternately in Python as shown below:</p> <pre class="lang-py prettyprint-override"><code>import asyncio async def test1(): for _ in range(3): print(&quot;Test1&quot;) await asyncio.sleep(1) async def test2(): for _ in range(3): print(&quot;Test2&quot;) await asyncio.sleep(1) loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(test1()) # Here loop.run_until_complete(test2()) # Here </code></pre> <p>But as shown below, they don't run with <a href="https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.run_until_complete" rel="nofollow noreferrer"><strong>loop.run_until_complete()</strong></a> alternately:</p> <pre class="lang-none prettyprint-override"><code>Test1 Test1 Test1 Test2 Test2 Test2 </code></pre> <p>I know that if I use <a href="https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.run_forever" rel="nofollow noreferrer"><strong>loop.run_forever()</strong></a> with <a href="https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.create_task" rel="nofollow noreferrer"><strong>loop.create_task()</strong></a> as shown below:</p> <pre class="lang-py prettyprint-override"><code>import asyncio async def test1(loop): for _ in range(3): print(&quot;Test1&quot;) await asyncio.sleep(1) loop.stop() # Extra code to stop &quot;loop.run_forever()&quot; async def test2(loop): for _ in range(3): print(&quot;Test2&quot;) await asyncio.sleep(1) loop.stop() # Extra code to stop &quot;loop.run_forever()&quot; loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.create_task(test1(loop)) # Here loop.create_task(test2(loop)) # Here loop.run_forever() # Here </code></pre> <p>I can run them alternately as shown below but <a href="https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.run_forever" rel="nofollow noreferrer"><strong>loop.run_forever()</strong></a> runs forever so to stop <a href="https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.run_forever" rel="nofollow noreferrer"><strong>loop.run_forever()</strong></a>, <strong>the extra code <a href="https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.stop" rel="nofollow noreferrer">loop.stop()</a></strong> is needed which is troublesome. In addition, I know that <a href="https://docs.python.org/3/library/asyncio-task.html#asyncio.gather" rel="nofollow noreferrer"><strong>asyncio.gather()</strong></a> can also run them alternately but it needs <strong><code>await</code></strong> which I don't want:</p> <pre class="lang-none prettyprint-override"><code>Test1 Test2 Test1 Test2 Test1 Test2 </code></pre> <p>So, how can I run them with <a href="https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.run_until_complete" rel="nofollow noreferrer"><strong>loop.run_until_complete()</strong></a> alternately?</p>
[ { "answer_id": 74249430, "author": "Utkucan Bıyıklı", "author_id": 7437136, "author_profile": "https://Stackoverflow.com/users/7437136", "pm_score": 2, "selected": true, "text": "data" }, { "answer_id": 74289973, "author": "Mohsin Maqsood", "author_id": 11561910, "aut...
2022/10/29
[ "https://Stackoverflow.com/questions/74248240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8172439/" ]
74,248,245
<pre class="lang-py prettyprint-override"><code>number = 50 while number &gt;= 0: if number % 5 == 0: print(number) number = number - 1 elif number % 5 == 1: continue number = number = number - 1 </code></pre> <p>the answer it's giving me is 50 then the loop stops executing</p> <p>Here is the program I am trying to make:</p> <p>While Loops Practice #2 Create a While Loop that subtracts one by one the numbers from 50 to 0 (both numbers included) with the following additional conditions:</p> <p>If the number is divisible by 5, show that number on the screen (remember that here you can use the modulus operation dividing by 5 and checking the remainder!)</p> <p>If the number is not divisible by 5, continue executing the loop without showing the value on the screen (don't forget to continue subtracting so that the program doesn't run infinitely).</p>
[ { "answer_id": 74248289, "author": "Samwise", "author_id": 3799759, "author_profile": "https://Stackoverflow.com/users/3799759", "pm_score": 0, "selected": false, "text": "number" }, { "answer_id": 74248308, "author": "Anton Chernyshov", "author_id": 20127679, "author...
2022/10/29
[ "https://Stackoverflow.com/questions/74248245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15573682/" ]
74,248,270
<p>I have a code with an html span that has a content of 0.00 and I want to update this span with an item from localStorage so I don't lose the data when reloading the page, I can rescue the item, but it disappears when I f5 on the page Does anybody know how to solve this?</p> <p>my html code:</p> <p>I have a button that when clicked should update the span with the item saved in localStorage</p> <pre class="lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt; &lt;title&gt;Products&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div&gt;Products&lt;/div&gt; &lt;button&gt;&lt;a href=&quot;/index.html&quot;&gt;Products&lt;/a&gt;&lt;/button&gt; &lt;div data-js=&quot;value-cart-products&quot;&gt;0,00&lt;/div&gt; &lt;button data-js=&quot;add-product&quot;&gt;Add to Cart&lt;/button&gt; &lt;script src=&quot;./app.js&quot;&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I can rescue the item from localStorage, but when I reload the page the item is lost.</p> <p>my javascript code:</p> <pre class="lang-js prettyprint-override"><code>const addProducts = document.querySelector('[data-js=&quot;add-product&quot;]') const cartValue = document.querySelector('[data-js=&quot;value-cart-products&quot;]') let valueCartNumber = 1 let getNumber = JSON.parse(localStorage.getItem('number')) let updateLocalStorage = ()=&gt;{ localStorage.setItem('number', JSON.stringify(valueCartNumber)) } addProducts.addEventListener('click', ()=&gt;{ cartValue.innerHTML = getNumber; }) updateLocalStorage() </code></pre>
[ { "answer_id": 74248289, "author": "Samwise", "author_id": 3799759, "author_profile": "https://Stackoverflow.com/users/3799759", "pm_score": 0, "selected": false, "text": "number" }, { "answer_id": 74248308, "author": "Anton Chernyshov", "author_id": 20127679, "author...
2022/10/29
[ "https://Stackoverflow.com/questions/74248270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20367778/" ]
74,248,286
<p>I have a something that is sending an SNMP set command to my server. I can see the packet in wireshark, and I know that I'm getting the packet. Once I get this packet I need to decode it and do an operation (using a script). I can't believe I am the first person that needs to do this, but have googled for hours and found no one else in this use case. I've seen utilities that allow me to use a get snmp, but as the set doesn't actually set anything on my server, there is no way to get it. It doesn't seem traps are helpful as that seems to find the message, as its not labeled a trap. Is there a way to convert the set to a trap once my server gets it, or is there a better method. My server is windows, but if I have to create a linux VM to make this easier I'm all ears. As of now I'm thinking powershell, but if there is an easy way in go, c#, etc I would totally do it.</p> <p>I am attempting to get a SNMP SET to and use that as a trigger for running a script.</p>
[ { "answer_id": 74248289, "author": "Samwise", "author_id": 3799759, "author_profile": "https://Stackoverflow.com/users/3799759", "pm_score": 0, "selected": false, "text": "number" }, { "answer_id": 74248308, "author": "Anton Chernyshov", "author_id": 20127679, "author...
2022/10/29
[ "https://Stackoverflow.com/questions/74248286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20367745/" ]
74,248,296
<p>I am unable to get the url redirected to one of the patterns defined in the url routing file.</p> <p><em>web.py</em></p> <pre><code>from django.urls import path from django.contrib import admin from heyurl import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('store', views.store, name='store'), path('/metrics/', views.get_month_metrics, name= 'metrics'), ] </code></pre> <p><em>views.py</em> (Includes the function that is getting called along with the libraries included)</p> <pre><code>from django.shortcuts import render, redirect from django.http import HttpResponse from .models import Url, Click from django.core.validators import URLValidator, ValidationError from heyurl.utils import db_services, helper from django_user_agents.utils import get_user_agent from django.template.defaulttags import register from datetime import datetime def get_month_metrics(request, url): today = datetime.now() ident = Url.objects.filter(short_url= url) ident = ident[0].id # GETTING THE CLICKS THIS MONTH clicks_this_month = Click.objects.filter(url=ident, created_at__year=today.year, created_at__month=today.month) # TOTAL CLICKS PER BROWSER safari = Click.objects.filter(url=ident, browser__contains='safari') chrome = Click.objects.filter(url=ident, browser__contains='chrome') firefox = Click.objects.filter(url=ident, browser__contains='firefox') # TOTAL CLICKS PER PLATFORM mobile = Click.objects.filter(url=ident, platform='Mobile') pc = Click.objects.filter(url=ident, platform='PC') #CONTEXT TO DISPLAY ON DATA PANEL context = { 'url': url, 'clicks': len(clicks_this_month), 'safari': len(safari), 'chrome': len(chrome), 'firefox': len(firefox), 'mobile': len(mobile), 'pc': len(pc), } return render(request, 'heyurl/metrics.html', context) </code></pre> <p>Now I tried hardcoding and supplied the exact pattern that it says is missing by changing the <em>web.py</em> as follows</p> <pre><code>urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('store', views.store, name='store'), path('RQvw4/metrics/', views.get_month_metrics, name= 'metrics'), ] </code></pre> <p>and it gives me the following error <a href="https://i.stack.imgur.com/NbgoL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NbgoL.png" alt="error after hardcoding url" /></a></p>
[ { "answer_id": 74248379, "author": "strykb", "author_id": 17406509, "author_profile": "https://Stackoverflow.com/users/17406509", "pm_score": 0, "selected": false, "text": "url" }, { "answer_id": 74248754, "author": "furas", "author_id": 1832058, "author_profile": "ht...
2022/10/29
[ "https://Stackoverflow.com/questions/74248296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7841468/" ]
74,248,305
<p>i have some image elements that when hovered on, scale up, however, this causes some other elements to move, which i dont want happening.</p> <p>I have tried things like <code>float: right</code> which work, but dont fit for my website, since it's margined and centered.</p> <p>here is a simpled version of my site:</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 { background-color:#1a1a1a; } img{ max-width: 15%; transition-duration: 0.5s; transform-origin: top; border-radius: 25px; overflow: hidden; margin: 50px; } img:hover{ max-width: 17%; cursor: pointer; transform: scale(110%); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;img src="https://www.tazzadesign.com/wp-content/uploads/sites/65/2013/11/dummy-image-square.jpg"&gt; &lt;img src="https://www.tazzadesign.com/wp-content/uploads/sites/65/2013/11/dummy-image-square.jpg"&gt; &lt;img src="https://www.tazzadesign.com/wp-content/uploads/sites/65/2013/11/dummy-image-square.jpg"&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74248332, "author": "Robo Robok", "author_id": 4403732, "author_profile": "https://Stackoverflow.com/users/4403732", "pm_score": 2, "selected": true, "text": "transform: scale(110%)" }, { "answer_id": 74248371, "author": "David Francisco", "author_id": 1478...
2022/10/29
[ "https://Stackoverflow.com/questions/74248305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10885581/" ]
74,248,340
<p>I am developing an application for android devices, using the jetpack compose library.</p> <p>Example I created inside a compose function</p> <p>var taskVeriable = remember {mutableStateOf(&quot;Hello World&quot;)}</p> <p>I need to update the value of variable from another compose function. Is there any way to achieve this?</p> <pre><code>@Composable fun TestComposeA(){ var taskVeriable = remember {mutableStateOf(&quot;Hello World&quot;)} TestComposeB(taskVeriable) } @Composable fun TestComposeB(taskVeriable : String){ taskVeriable = &quot;New Value&quot; } </code></pre> <p>I want to know if there is a way to do this.</p>
[ { "answer_id": 74248332, "author": "Robo Robok", "author_id": 4403732, "author_profile": "https://Stackoverflow.com/users/4403732", "pm_score": 2, "selected": true, "text": "transform: scale(110%)" }, { "answer_id": 74248371, "author": "David Francisco", "author_id": 1478...
2022/10/29
[ "https://Stackoverflow.com/questions/74248340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14329913/" ]
74,248,352
<p>I am currently taking a class on C and I am baffled by gcc options a lot of the time, because the videos/documentation on the options are sparse and those that eixst are hard to understand(for idiots/non-technical majors like myself). Please consider the following scenario:</p> <p>Lets say I have a header file, myHeader.h and main.c which would like to include myHeader.h. Assume they are in the same directory.</p> <p>In main.c, I could write #include &quot;myHeader.h&quot;. However, according to my professor the &quot;&quot; is permitted because gcc will check in the current directory for anything in the &quot;&quot;. However, where I am lost is when it comes to how I could add myHeader.h to the gcc header file search path such that #include &lt;myHeader.h&gt; would work. I am wondering what gcc commands would work, and why they work in specific. I would love any references(that aren't super nerdy) to better understand this.</p> <p>So far, I researched on stackoverflow and on google, and it said something about -Idir gcc command, where dir is the directory you would like to add to the header file search path, but I am confused as to why this works or how to actually implement it. Since the &quot;path&quot; to myHeader.h is CStuff/workspace/myHeader.h I attempted to do gcc -I/CStuff/workspace/myHeader.h but this didn't really work out. I really thought it would take that directory and add it to the header file search path, but it just gave me an error.</p> <p>I am a very confused business major so please take it easy on me! I really would love a dumbed-down explanation or a reference to a source that is more &quot;basic&quot; and has more than 1-2 sentences of explanation(if possible).</p>
[ { "answer_id": 74248332, "author": "Robo Robok", "author_id": 4403732, "author_profile": "https://Stackoverflow.com/users/4403732", "pm_score": 2, "selected": true, "text": "transform: scale(110%)" }, { "answer_id": 74248371, "author": "David Francisco", "author_id": 1478...
2022/10/29
[ "https://Stackoverflow.com/questions/74248352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19464057/" ]
74,248,409
<p>New to VBA. I have a large PPT with over 150 slides, and I have run a VBA macro to tag them (SlidesA ... SlidesF) into tag &quot;groupings&quot;. I have a userform with a bunch of check boxes to select slide groupings the user wants keep. After selecting the groupings the user wants to keep they click an OK button. I have some code (below) to find slides that are not checked and delete them based on Tags.Value, and keep the rest. But for some reason it's not deleting all the slides, it's just deleting like 4 of them in SlidesA group.</p> <pre><code>Private Sub btnOK_Click() ' Slide.Tag has .Name and .Value parameters If chkSlidesA = False Then For Each s In Application.ActivePresentation.Slides With s.Tags For i = 1 To .Count If .Value(i) = &quot;SlidesA&quot; Then s.Delete End If Next i End With Next Else If chkSlidesB = False Then For Each s In Application.ActivePresentation.Slides With s.Tags For i = 1 To .Count If .Value(i) = &quot;SlidesB&quot; Then s.Delete End If Next i End With Next Else If chkSlidesC = False Then For Each s In Application.ActivePresentation.Slides With s.Tags For i = 1 To .Count If .Value(i) = &quot;SlidesC&quot; Then s.Delete End If Next i End With Next Else If chkSlidesD = False Then For Each s In Application.ActivePresentation.Slides With s.Tags For i = 1 To .Count If .Value(i) = &quot;SlidesD&quot; Then s.Delete End If Next i End With Next Else If chkSlidesE = False Then For Each s In Application.ActivePresentation.Slides With s.Tags For i = 1 To .Count If .Value(i) = &quot;SlidesE&quot; Then s.Delete End If Next i End With Next Else If chkSlidesF = False Then For Each s In Application.ActivePresentation.Slides With s.Tags For i = 1 To .Count If .Value(i) = &quot;SlidesF&quot; Then s.Delete End If Next i End With Next Else End If End If End If End If End If End If Unload Me End Sub </code></pre> <p>I have verified the slides are tagged with the right values by running some VBA to read the tags and display a MsgBox to display the tag value.</p> <p>I'm trying to understand why it isn't deleting all the slides.</p>
[ { "answer_id": 74248967, "author": "milo5m", "author_id": 20076134, "author_profile": "https://Stackoverflow.com/users/20076134", "pm_score": 1, "selected": false, "text": "Private Sub btnOK_Click()\n Dim concatSlidesAF As String\n concatSlidesAF = IIf(chkSlidesA, \"A\", \"\") & II...
2022/10/29
[ "https://Stackoverflow.com/questions/74248409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3709475/" ]
74,248,427
<p>I got following problem which I can't solved :(</p> <p>Scenario: I have a list with Ingredients and I want to compare it with a recipes list which holds a list of ingredients depending on the recipes.</p> <pre><code>List&lt;RecipeList&gt; recipesList = [ RecipeList(recipeName: &quot;Cake&quot;, itemNames: [&quot;banana&quot;, &quot;appel&quot;]), RecipeList(recipeName: &quot;Soup&quot;, itemNames: [&quot;potatato&quot;, &quot;egg&quot;]), RecipeList(recipeName: &quot;Sandwich&quot;, itemNames: [&quot;Toast&quot;, &quot;Sausage&quot;, &quot;Ketchup&quot;]), RecipeList(recipeName: &quot;Pizza&quot;, itemNames: [&quot;Tomato&quot;, &quot;Mushroom&quot;]), ]; List inventory = [&quot;coke&quot;, &quot;egg&quot;, &quot;banana&quot;, &quot;apple&quot;]; class RecipeList { String? recipeName; List&lt;String&gt;? itemNames; RecipeList({this.recipeName, this.itemNames}); } </code></pre> <p>I am thankful for any help or idea :D!</p> <p>Thank you very much for your help, ReeN</p>
[ { "answer_id": 74248967, "author": "milo5m", "author_id": 20076134, "author_profile": "https://Stackoverflow.com/users/20076134", "pm_score": 1, "selected": false, "text": "Private Sub btnOK_Click()\n Dim concatSlidesAF As String\n concatSlidesAF = IIf(chkSlidesA, \"A\", \"\") & II...
2022/10/29
[ "https://Stackoverflow.com/questions/74248427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20367893/" ]
74,248,440
<p>Probably this is a very stupid mistake but I can't find a solution. I have the lists below:</p> <pre><code>node_pair = [('a', 'b'), ('b', 'a')] edge_list = [ (1, 'unuseful thing', {'orig-id': 'a'}), (11, 'unuseful thing', {'orig-id': 'b'}), ] </code></pre> <p>I need to find the numeric couple in <code>edge_list</code> that is related to <code>node_pair</code>. For <code>('a', 'b')</code> I will see <code>(1, 11)</code> and for <code>('b', 'a')</code> I will see <code>(11, 1)</code>. Below my code:</p> <pre><code>for pair in node_pair: start_node = pair[0][0] end_node = pair[1][0] print(f'from {start_node} --&gt; to {end_node}') graph_start_end_node = [] for edge in edge_list: edge_orig_id = edge[2]['orig-id'] if start_node == edge_orig_id: edge_start_node = edge[0] graph_start_end_node.append(edge_start_node) if end_node == edge_orig_id: edge_start_node = edge[0] graph_start_end_node.append(edge_start_node) print(graph_start_end_node) </code></pre> <p>The result is:</p> <pre><code>from a --&gt; to b [1, 11] from b --&gt; to a [1, 11] </code></pre>
[ { "answer_id": 74248967, "author": "milo5m", "author_id": 20076134, "author_profile": "https://Stackoverflow.com/users/20076134", "pm_score": 1, "selected": false, "text": "Private Sub btnOK_Click()\n Dim concatSlidesAF As String\n concatSlidesAF = IIf(chkSlidesA, \"A\", \"\") & II...
2022/10/29
[ "https://Stackoverflow.com/questions/74248440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10012856/" ]
74,248,477
<p><a href="https://i.stack.imgur.com/gZcOL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gZcOL.png" alt="enter image description here" /></a></p> <p>Does anyone know how to create a grid like this using GridView.builder. Any other alternative will be much appreciated too.</p> <p>The text in the container should be dynamic as well based on the size of the text.</p> <p>Thank you</p> <p>Tried using gridView but the container was always of fixed width and height. The row items was not dynamic as well</p>
[ { "answer_id": 74248967, "author": "milo5m", "author_id": 20076134, "author_profile": "https://Stackoverflow.com/users/20076134", "pm_score": 1, "selected": false, "text": "Private Sub btnOK_Click()\n Dim concatSlidesAF As String\n concatSlidesAF = IIf(chkSlidesA, \"A\", \"\") & II...
2022/10/29
[ "https://Stackoverflow.com/questions/74248477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10159679/" ]
74,248,480
<p>Imagine we have a table like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>name</th> <th>type</th> <th>created_at</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>James</td> <td>male</td> <td>2022-03-02</td> </tr> <tr> <td>2</td> <td>Jane</td> <td>female</td> <td>2022-04-02</td> </tr> <tr> <td>3</td> <td>Kirk</td> <td>male</td> <td>2022-03-04</td> </tr> <tr> <td>4</td> <td>Sarah</td> <td>female</td> <td>2022-04-04</td> </tr> <tr> <td>5</td> <td>Jason</td> <td>male</td> <td>2022-03-05</td> </tr> </tbody> </table> </div> <p>And i want to <em>group by</em> type and just get latest records based on <code>created_at</code>.<br /> So i tried this code and not bad:</p> <pre><code>result = User.objects.values('type').annotate( latest_date=Max('created_at'), ) </code></pre> <p>When print the <strong>result</strong> i face to this:</p> <pre><code>&lt;QuerySet [ {'type': 'male', 'latest_date': '2022-03-05'}, {'type': 'female', 'latest_date': '2022-04-04'} ]&gt; </code></pre> <p>My question is: Where is other fields <code>id</code> and <code>name</code>? I expect to get:</p> <pre><code>&lt;QuerySet [ {id: 5, name: 'Jason', 'type': 'male', 'latest_date': '2022-03-05'}, {id: 4, name: 'Sarah', 'type': 'female', 'latest_date': '2022-04-04'} ]&gt; </code></pre>
[ { "answer_id": 74248599, "author": "Seyed Mehrshad Hosseini", "author_id": 11733513, "author_profile": "https://Stackoverflow.com/users/11733513", "pm_score": 3, "selected": true, "text": "order_by" }, { "answer_id": 74250214, "author": "lord stock", "author_id": 14689289...
2022/10/29
[ "https://Stackoverflow.com/questions/74248480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3319132/" ]
74,248,482
<p>I need to remove &quot;km&quot; from <code>distance</code> column:</p> <pre><code>[Distance] 0 114 km 1 114 km 2 9.1 km 3 33.1 km 4 182 km 5 93.2 km 6 40.4 km 7 0.0 8 0.0 9 43.4 km Name: distance, dtype: object </code></pre> <p>Has to look like this:</p> <pre><code>[Distance] 0 114 1 114 2 9.1 3 33.1 4 182 5 93.2 6 40.4 7 8 9 43.4 </code></pre>
[ { "answer_id": 74248532, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": false, "text": "km" }, { "answer_id": 74249355, "author": "salman", "author_id": 19060245, "author_profile": "h...
2022/10/29
[ "https://Stackoverflow.com/questions/74248482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20367961/" ]
74,248,540
<p>I am trying to make an array store each number I type in.</p> <p>Some like: <strong>Enter number:687544</strong></p> <p>And return as an array like: <strong>6 8 7 5 4 4</strong></p> <p>I only figure out how to store the nums in order in the &quot;store (num) &quot; function below:</p> <pre><code>#include&lt;stdio.h&gt; int store(int num); int main() {     int num;     printf(&quot;Enter number: &quot;);     scanf(&quot;%d&quot;,&amp;num);         return store(num); } int store(int num) {   if(num!= 0)     { int mod = num % 10;  //split last digit from number      store(num/10);  //recuring it back to the right order      printf(&quot;%i\n&quot;,mod); //divide num by 10. num /= 10 also a valid one  } } </code></pre> <p>Following is I tried but not working code</p> <pre><code>#include&lt;stdio.h&gt; int store(int num); int main() { int num,d; printf(&quot;Enter number: &quot;); scanf(&quot;%d&quot;,&amp;num); for(d=0; num&lt;0;d++); { num /= 10; } int a[d]; int i; for(i=0;i&lt;d;i++){ a[d]=store(num); } printf(&quot;%d \n&quot;,a[d]); } int store(int num) { if(num!= 0) { int mod = num % 10; store(num/10); return mod; } } </code></pre> <p>Unexpected Result.......</p> <pre><code>Enter number: 123 115183680 </code></pre> <p>Feel like I almost there but I have no idea which part goes wrong. May I ask how to fix this?</p> <p>I only figure out how to store the nums in order in the &quot;store (num) &quot; function, however I tried the to expand my code that the result is not I expected.</p>
[ { "answer_id": 74248935, "author": "stark", "author_id": 1216776, "author_profile": "https://Stackoverflow.com/users/1216776", "pm_score": 1, "selected": true, "text": "int store(int num, int digit);\n\nint a[20]; // Don't bother with dynamic allocation\n\nint main()\n{\n int num,d;\...
2022/10/29
[ "https://Stackoverflow.com/questions/74248540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20367940/" ]
74,248,547
<p>I am taking the Operating Systems course and trying to understand how exactly <code>fork()</code> works. I know the basic definition: &quot;fork() creates a new process by duplicating the calling process.&quot;.</p> <p>I was told the child process will only execute the codes below the <code>fork()</code> statement. What I don't understand is, let's say we have a 10-lined code. If line 6 is <code>fork()</code>, Will the whole code from lines 1 to 10 run in the child process or only 6 to 10 ?</p> <p>How will this code will work:</p> <pre><code>int main(){ pid_t smith; int a=2; int b=3; smith = fork(); if(smith == 0){ fork(); a++; fork(); } else if(smith &gt; 0){ b++; fork(); } printf(&quot;%d %d&quot;,a,b); } </code></pre> <p>The <code>fork()</code>s in if blocks are confusing. How will they act? When a child process is created from the fork() in the else if, what code will it run?</p>
[ { "answer_id": 74248825, "author": "Steve Summit", "author_id": 3923896, "author_profile": "https://Stackoverflow.com/users/3923896", "pm_score": 3, "selected": true, "text": "1. Apple\n2. Banana\n3. Cranberry\n4. Daffodil\n5. Eggplant\n6. Fuchsia\n7. Germanium\n8. Hollyhock\n9. Indigo\n...
2022/10/29
[ "https://Stackoverflow.com/questions/74248547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20468293/" ]
74,248,577
<p>I'm a beginner in android app making and I'm trying to do an app for a project. I found this tutorial and I'm currently trying to put to apps together in android studio. Both are reminders apps, however the second one (the food one), the FAB is not working it register the touch but when it does it says APP keeps stopping. If anybody can help me I'll appreciated.</p> <p>First Reminder .java</p> <pre><code>public class MedicineActivity extends AppCompatActivity { @BindView(R.id.compactcalendar_view) CompactCalendarView mCompactCalendarView; @BindView(R.id.date_picker_text_view) TextView datePickerTextView; @BindView(R.id.date_picker_button) RelativeLayout datePickerButton; @BindView(R.id.toolbar) Toolbar toolbar; @BindView(R.id.collapsingToolbarLayout) CollapsingToolbarLayout collapsingToolbarLayout; @BindView(R.id.app_bar_layout) AppBarLayout appBarLayout; @BindView(R.id.contentFrame) FrameLayout contentFrame; @BindView(R.id.fab_add_task) FloatingActionButton fabAddTask; @BindView(R.id.coordinatorLayout) CoordinatorLayout coordinatorLayout; @BindView(R.id.date_picker_arrow) ImageView arrow; private MedicinePresenter presenter; private SimpleDateFormat dateFormat = new SimpleDateFormat(&quot;MMM dd&quot;, /*Locale.getDefault()*/Locale.ENGLISH); private boolean isExpanded = false; public ImageButton imageButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_medicine); ButterKnife.bind(this); setSupportActionBar(toolbar); imageButton = (ImageButton) findViewById(R.id.image2button); imageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent= new Intent(MedicineActivity.this,dashboard_screen.class); startActivity(intent); } }); mCompactCalendarView.setLocale(TimeZone.getDefault(), /*Locale.getDefault()*/Locale.ENGLISH); mCompactCalendarView.setShouldDrawDaysHeader(true); mCompactCalendarView.setListener(new CompactCalendarView.CompactCalendarViewListener() { @Override public void onDayClick(Date dateClicked) { setSubtitle(dateFormat.format(dateClicked)); Calendar calendar = Calendar.getInstance(); calendar.setTime(dateClicked); int day = calendar.get(Calendar.DAY_OF_WEEK); if (isExpanded) { ViewCompat.animate(arrow).rotation(0).start(); } else { ViewCompat.animate(arrow).rotation(180).start(); } isExpanded = !isExpanded; appBarLayout.setExpanded(isExpanded, true); presenter.reload(day); } @Override public void onMonthScroll(Date firstDayOfNewMonth) { setSubtitle(dateFormat.format(firstDayOfNewMonth)); } }); setCurrentDate(new Date()); MedicineFragment medicineFragment = (MedicineFragment) getSupportFragmentManager().findFragmentById(R.id.contentFrame); if (medicineFragment == null) { medicineFragment = MedicineFragment.newInstance(); ActivityUtils.addFragmentToActivity(getSupportFragmentManager(), medicineFragment, R.id.contentFrame); } //Create MedicinePresenter presenter = new MedicinePresenter(Injection.provideMedicineRepository(MedicineActivity.this), medicineFragment); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.medicine_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.menu_stats) { Intent intent = new Intent(this, MonthlyReportActivity.class); startActivity(intent); } return super.onOptionsItemSelected(item); } public void setCurrentDate(Date date) { setSubtitle(dateFormat.format(date)); mCompactCalendarView.setCurrentDate(date); } public void setSubtitle(String subtitle) { datePickerTextView.setText(subtitle); } @OnClick(R.id.date_picker_button) void onDatePickerButtonClicked() { if (isExpanded) { ViewCompat.animate(arrow).rotation(0).start(); } else { ViewCompat.animate(arrow).rotation(180).start(); } isExpanded = !isExpanded; appBarLayout.setExpanded(isExpanded, true); } } </code></pre> <p>First Reminder XML File</p> <pre><code> &lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot; xmlns:tools=&quot;http://schemas.android.com/tools&quot; android:id=&quot;@+id/coordinatorLayout&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot;&gt; &lt;com.google.android.material.appbar.AppBarLayout android:id=&quot;@+id/app_bar_layout&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;wrap_content&quot; android:fitsSystemWindows=&quot;true&quot; android:theme=&quot;@style/AppTheme.AppBarOverlay&quot; app:expanded=&quot;false&quot; app:layout_behavior=&quot;com.gautam.medicinetime.utils.ScrollingCalendarBehavior&quot;&gt; &lt;com.google.android.material.appbar.CollapsingToolbarLayout android:id=&quot;@+id/collapsingToolbarLayout&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot; android:fitsSystemWindows=&quot;true&quot; android:minHeight=&quot;?attr/actionBarSize&quot; app:contentScrim=&quot;?attr/colorPrimary&quot; app:titleEnabled=&quot;false&quot; app:layout_scrollFlags=&quot;scroll|exitUntilCollapsed&quot; app:statusBarScrim=&quot;?attr/colorPrimaryDark&quot;&gt; &lt;LinearLayout android:id=&quot;@+id/compactcalendar_view_container&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;250dp&quot; android:paddingTop=&quot;?attr/actionBarSize&quot; app:layout_collapseMode=&quot;parallax&quot; app:layout_collapseParallaxMultiplier=&quot;1.0&quot;&gt; &lt;com.github.sundeepk.compactcalendarview.CompactCalendarView android:id=&quot;@+id/compactcalendar_view&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;wrap_content&quot; android:paddingLeft=&quot;10dp&quot; android:paddingRight=&quot;10dp&quot; app:compactCalendarBackgroundColor=&quot;?attr/colorPrimary&quot; app:compactCalendarCurrentDayBackgroundColor=&quot;#FFC107&quot; app:compactCalendarCurrentSelectedDayBackgroundColor=&quot;#BBDEFB&quot; app:compactCalendarTextColor=&quot;#fff&quot; app:compactCalendarTextSize=&quot;12sp&quot; /&gt; &lt;/LinearLayout&gt; &lt;androidx.appcompat.widget.Toolbar android:id=&quot;@+id/toolbar&quot; style=&quot;@style/ToolbarStyle&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;?attr/actionBarSize&quot; app:layout_collapseMode=&quot;pin&quot; app:popupTheme=&quot;@style/AppTheme.PopupOverlay&quot;&gt; &lt;RelativeLayout android:id=&quot;@+id/date_picker_button&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;?attr/actionBarSize&quot; android:background=&quot;?android:selectableItemBackground&quot; android:gravity=&quot;center_vertical&quot; android:clickable=&quot;true&quot; android:focusable=&quot;true&quot; android:orientation=&quot;vertical&quot;&gt; &lt;TextView android:id=&quot;@+id/date_picker_text_view&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:ellipsize=&quot;end&quot; android:maxLines=&quot;1&quot; android:textStyle=&quot;bold&quot; android:textSize=&quot;18sp&quot; android:textColor=&quot;@android:color/white&quot; /&gt; &lt;ImageView android:id=&quot;@+id/date_picker_arrow&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:layout_alignBottom=&quot;@id/date_picker_text_view&quot; android:layout_toRightOf=&quot;@id/date_picker_text_view&quot; app:srcCompat=&quot;@drawable/ic_arrow_drop_down&quot; tools:ignore=&quot;ContentDescription,RtlHardcoded&quot; /&gt; &lt;/RelativeLayout&gt; &lt;/androidx.appcompat.widget.Toolbar&gt; &lt;/com.google.android.material.appbar.CollapsingToolbarLayout&gt; &lt;/com.google.android.material.appbar.AppBarLayout&gt; &lt;RelativeLayout android:id=&quot;@+id/relativeLayout2&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;wrap_content&quot; android:backgroundTint=&quot;@color/design_default_color_background&quot;&gt; &lt;androidx.constraintlayout.widget.ConstraintLayout android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot;&gt; &lt;ImageButton android:id=&quot;@+id/image2button&quot; android:layout_width=&quot;48dp&quot; android:layout_height=&quot;50dp&quot; android:background=&quot;@drawable/roundbutton&quot; android:src=&quot;@drawable/menu_icon&quot; android:text=&quot;Button&quot; app:layout_constraintBottom_toBottomOf=&quot;parent&quot; app:layout_constraintEnd_toEndOf=&quot;parent&quot; app:layout_constraintHorizontal_bias=&quot;0.046&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; app:layout_constraintTop_toTopOf=&quot;parent&quot; app:layout_constraintVertical_bias=&quot;0.976&quot; /&gt; &lt;/androidx.constraintlayout.widget.ConstraintLayout&gt; &lt;/RelativeLayout&gt; &lt;com.google.android.material.floatingactionbutton.FloatingActionButton android:id=&quot;@+id/fab_add_task&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:layout_margin=&quot;@dimen/sixteen_dp&quot; app:fabSize=&quot;normal&quot; app:layout_anchor=&quot;@+id/relativeLayout2&quot; app:layout_anchorGravity=&quot;end|bottom&quot; app:srcCompat=&quot;@drawable/ic_add&quot; /&gt; &lt;FrameLayout android:id=&quot;@+id/contentFrame&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;674dp&quot; app:layout_behavior=&quot;@string/appbar_scrolling_view_behavior&quot; /&gt; &lt;/androidx.coordinatorlayout.widget.CoordinatorLayout&gt; </code></pre> <p>Second Remider .java</p> <pre><code>public class FoodActivity extends AppCompatActivity { FloatingActionButton mCreateRem; RecyclerView mRecyclerview; ArrayList&lt;Model&gt; dataholder = new ArrayList&lt;Model&gt;(); //Array list to add reminders and display in recyclerview myAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_food); mRecyclerview = (RecyclerView) findViewById(R.id.recyclerView_food); mRecyclerview.setLayoutManager(new LinearLayoutManager(getApplicationContext())); mCreateRem = (FloatingActionButton) findViewById(R.id.create_reminder); //Floating action button to change activity mCreateRem.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getApplicationContext(), FoodAddReminder.class); startActivity(intent); //Starts the new activity to add Reminders } }); Cursor cursor = new dbManager(getApplicationContext()).readallreminders(); //Cursor To Load data From the database while (cursor.moveToNext()) { Model model = new Model (cursor.getString(1), cursor.getString(2), cursor.getString(3)); dataholder.add(model); } adapter = new myAdapter(dataholder); mRecyclerview.setAdapter(adapter); //Binds the adapter with recyclerview } @Override public void onBackPressed() { finish(); //Makes the user to exit from the app super.onBackPressed(); } } </code></pre> <p>Second Reminder XML file</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot; xmlns:tools=&quot;http://schemas.android.com/tools&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot; tools:context=&quot;.FoodActivity&quot; android:id=&quot;@+id/Food_Container&quot;&gt; &lt;androidx.appcompat.widget.Toolbar android:id=&quot;@+id/FoodToolbar&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;wrap_content&quot; android:background=&quot;@color/yellow_light&quot; app:layout_constraintEnd_toEndOf=&quot;parent&quot; app:layout_constraintHorizontal_bias=&quot;0.0&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; app:layout_constraintTop_toTopOf=&quot;parent&quot; app:title=&quot;What's on you firdge?&quot; /&gt; &lt;androidx.recyclerview.widget.RecyclerView android:id=&quot;@+id/recyclerView_food&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;0dp&quot; android:layout_marginTop=&quot;8dp&quot; android:visibility=&quot;invisible&quot; app:layout_constraintBaseline_toBottomOf=&quot;parent&quot; app:layout_constraintTop_toBottomOf=&quot;@id/FoodToolbar&quot; tools:layout_editor_absoluteX=&quot;-4dp&quot; /&gt; &lt;TextView android:id=&quot;@+id/textView4&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:gravity=&quot;center&quot; android:text=&quot;No food reminder added\n + Add now&quot; android:textAlignment=&quot;center&quot; android:textSize=&quot;18dp&quot; app:layout_constraintBottom_toBottomOf=&quot;parent&quot; app:layout_constraintEnd_toEndOf=&quot;@+id/recyclerView_food&quot; app:layout_constraintStart_toStartOf=&quot;@+id/recyclerView_food&quot; app:layout_constraintTop_toBottomOf=&quot;@+id/FoodToolbar&quot; app:layout_constraintVertical_bias=&quot;0.523&quot; android:visibility=&quot;gone&quot; /&gt; &lt;ImageView android:layout_width=&quot;379dp&quot; android:layout_height=&quot;46dp&quot; android:src=&quot;@drawable/food_icon&quot; app:layout_constraintBottom_toTopOf=&quot;@+id/textView4&quot; app:layout_constraintEnd_toEndOf=&quot;parent&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; app:layout_constraintTop_toTopOf=&quot;@+id/FoodToolbar&quot; app:layout_constraintVertical_bias=&quot;0.966&quot; android:visibility=&quot;gone&quot; /&gt; &lt;com.google.android.material.floatingactionbutton.FloatingActionButton android:id=&quot;@+id/create_reminder&quot; android:layout_width=&quot;65dp&quot; android:layout_height=&quot;56dp&quot; android:src=&quot;@drawable/ic_baseline_add_24&quot; app:backgroundTint=&quot;@color/yellow_light&quot; app:layout_anchorGravity=&quot;right|bottom&quot; app:layout_constraintBottom_toBottomOf=&quot;parent&quot; app:layout_constraintEnd_toEndOf=&quot;parent&quot; app:layout_constraintHorizontal_bias=&quot;0.928&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; app:layout_constraintTop_toTopOf=&quot;parent&quot; app:layout_constraintVertical_bias=&quot;0.961&quot; /&gt; &lt;/androidx.constraintlayout.widget.ConstraintLayout&gt; </code></pre>
[ { "answer_id": 74248825, "author": "Steve Summit", "author_id": 3923896, "author_profile": "https://Stackoverflow.com/users/3923896", "pm_score": 3, "selected": true, "text": "1. Apple\n2. Banana\n3. Cranberry\n4. Daffodil\n5. Eggplant\n6. Fuchsia\n7. Germanium\n8. Hollyhock\n9. Indigo\n...
2022/10/29
[ "https://Stackoverflow.com/questions/74248577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20367958/" ]
74,248,585
<p>Given a Mongo collection of data of the form:</p> <pre><code>// 'Entities' { tags: [{ a: '1', b: '1' }, { a: '2', b: '3' }] } { tags: [{ a: '1', b: '2' }, { a: '2', b: '3' }] } { tags: [{ a: '4', b: '4' }, { a: '4', b: '5' }, { a: '6', b: '7' }] } </code></pre> <p>I'd like to find all documents whose 'tag' entry has any of the following objects:</p> <pre><code>[{ a: '1', b: '1' }, { a: '4', b: '4' }] </code></pre> <p>With the example data, this would match the first and third elements:</p> <pre><code>{ tags: [{ a: '1', b: '1' }, { a: '2', b: '3' }] } { tags: [{ a: '4', b: '4' }, { a: '4', b: '5' }, { a: '6', b: '7' }] } </code></pre> <p>At the moment I'm doing it with a generated query (JS):</p> <pre><code>entities.find({ $or: tags.map(tag =&gt; ({ tags: { $elemMatch: tag }, }) }) </code></pre> <p>But this seems very inefficient, as if the number of tags I'm searching for is large I'll be essentially running hundreds of separate queries. Is there a better way?</p>
[ { "answer_id": 74248825, "author": "Steve Summit", "author_id": 3923896, "author_profile": "https://Stackoverflow.com/users/3923896", "pm_score": 3, "selected": true, "text": "1. Apple\n2. Banana\n3. Cranberry\n4. Daffodil\n5. Eggplant\n6. Fuchsia\n7. Germanium\n8. Hollyhock\n9. Indigo\n...
2022/10/29
[ "https://Stackoverflow.com/questions/74248585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20368038/" ]
74,248,598
<p>I'm trying to create a plug-in system using Symfony and its bundle system. I know bundle must be independent but for my system, I know my bundle will never be used in another context.</p> <p>I have a doctrine entity called &quot;Mark&quot; and I want to associate an entity from the main application called &quot;Student&quot; so a student can have a mark from my mark plugin.</p> <p>For the moment, I only have an entity Mark that is really simple and I don't know how to associate a new field to my Student entity</p> <pre class="lang-php prettyprint-override"><code>namespace Zenith\QuinzeBundle\Model; [...] #[ORM\Entity(repositoryClass: MarkRepository::class)] class Mark { #[ORM\Id] #[ORM\GeneratedValue] #[ORM\Column] private ?int $id = null; #[ORM\Column(length: 255)] private ?string $comment = null; public function getId(): ?int { return $this-&gt;id; } public function getComment(): ?string { return $this-&gt;comment; } public function setComment(string $comment): self { $this-&gt;comment = $comment; return $this; } } </code></pre> <p>And this is my Student entity (simplified) :</p> <pre class="lang-php prettyprint-override"><code>namespace Zenith\Entity; [...] #[ORM\Entity(repositoryClass: StudentRepository::class)] class Student { #[ORM\Id] #[ORM\GeneratedValue] #[ORM\Column] private ?int $id = null; #[ORM\Column(length: 255)] private ?string $firstname = null; #[ORM\Column(length: 255)] private ?string $name = null; public function __construct() { $this-&gt;userfieldValues = new ArrayCollection(); } public function getId(): ?int { return $this-&gt;id; } public function getFirstname(): ?string { return $this-&gt;firstname; } public function setFirstname(string $firstname): self { $this-&gt;firstname = $firstname; return $this; } public function getName(): ?string { return $this-&gt;name; } public function setName(string $name): self { $this-&gt;name = $name; return $this; } </code></pre> <p>How can I associate this two entities that one is in an app and the other in a bundle ?</p>
[ { "answer_id": 74248825, "author": "Steve Summit", "author_id": 3923896, "author_profile": "https://Stackoverflow.com/users/3923896", "pm_score": 3, "selected": true, "text": "1. Apple\n2. Banana\n3. Cranberry\n4. Daffodil\n5. Eggplant\n6. Fuchsia\n7. Germanium\n8. Hollyhock\n9. Indigo\n...
2022/10/29
[ "https://Stackoverflow.com/questions/74248598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7200302/" ]
74,248,609
<p>I have two div connected to each other through svg line(implementation from d3js chart). On certain action, I want to fade/greyout some of the divs. I am able to achieve it by setting opacity 0.5. But it makes the div transparent so background svg line gets visible. I have created a jsfiddle to demo the issue.</p> <pre><code>&lt;div id=&quot;div1&quot; style=&quot;width: 100px; height: 100px; top:0; left:0; background:#777; position:absolute;&quot;&gt; &lt;div class=&quot;child1&quot;&gt; text &lt;/div&gt; &lt;div class=&quot;child2&quot;&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id=&quot;div2&quot; style=&quot;width: 100px; height: 100px; top:200px; left:200px; background:#333; position:absolute;&quot;&gt; &lt;div class=&quot;child1&quot;&gt; text &lt;/div&gt; &lt;div class=&quot;child2&quot;&gt; &lt;/div&gt; &lt;/div&gt; &lt;svg width=&quot;300&quot; height=&quot;250&quot;&gt;&lt;line x1=&quot;50&quot; y1=&quot;50&quot; x2=&quot;350&quot; y2=&quot;350&quot; stroke=&quot;black&quot;/&gt;&lt;/svg&gt; &lt;button onclick=&quot;fade()&quot;&gt; fade &lt;/button&gt; &lt;button onclick=&quot;reset()&quot;&gt; reset &lt;/button&gt; function fade () { document.getElementById('div1').className = 'greyout'; } .greyout { opacity: 0.5; } </code></pre> <p><a href="https://jsfiddle.net/srxoL1zj/2/" rel="nofollow noreferrer">jsfiddle link</a></p> <p>Is there any way to hide line inside div when opacity is set to 0.5?</p> <p>mock screen(requirement):</p> <p><a href="https://i.stack.imgur.com/pmPAD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pmPAD.png" alt="enter image description here" /></a></p> <p>Thanks!</p>
[ { "answer_id": 74248749, "author": "lucutzu33", "author_id": 8770336, "author_profile": "https://Stackoverflow.com/users/8770336", "pm_score": 0, "selected": false, "text": ".greyout {\n filter: grayscale(70%);\n}\n" }, { "answer_id": 74256318, "author": "Bqardi", "autho...
2022/10/29
[ "https://Stackoverflow.com/questions/74248609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6841106/" ]
74,248,610
<p>I updated macos to version 13 Ventura. I'm developing apps using Xamarin/MAUI on Visual Studio on Windows. Access to macOS over the network is no longer possible. Error message: Unable to connect to SSH using the SSH keys. I have enabled remote access to macOS.</p>
[ { "answer_id": 74260572, "author": "Alexandar May - MSFT", "author_id": 9644964, "author_profile": "https://Stackoverflow.com/users/9644964", "pm_score": 1, "selected": false, "text": "macOS 13 (Ventura)" } ]
2022/10/29
[ "https://Stackoverflow.com/questions/74248610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13825768/" ]
74,248,626
<p>I'm new to HTML/CSS and attempting to replicate <a href="https://www.w3schools.com/css/tryit.asp?filename=trycss_buttons_animate3" rel="nofollow noreferrer">this button effect</a> in a project of mine where the buttons are children of a div. However, whenever I do the <code>translateY</code>, my buttons move to the side instead. Here is the HTML and CSS; button-2 is the problematic one:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.container { position: relative width: 600px; height: 600px; } #button-1 { position: absolute; padding: 15px 25px; font-size: 24px; cursor: pointer; text-align: center; text-decoration: none; outline: none; color: #fff; background-color: #4CAF50; border: ridge; border-radius: 15px; box-shadow: 0 9px #999; top: 50%; left: 25%; } #button-1:hover { background-color: #3e8e41 } #button-1:active { background-color: #3e8e41; box-shadow: 0 5px #666; transform: translateY(10px); } #button-2 { position: absolute; width: 100px; padding: 5px 5px; border-style: solid; border-width: 2px; border-radius: 10px; border-color: darkslategray; background-color: antiquewhite; box-shadow: 0px 9px gray; cursor: pointer; top: 62%; left: 50%; /* if i remove this line, translation works as expected but then the button is no longer centered horizontally consequently, keeping the line breaks the affect but the button can be centered horizontally */ transform: translate(-50%, 0); } #button-2:hover { background-color: cornsilk; } #button-2:active { background-color: cornsilk; box-shadow: 0px 3px gray; transform: translateY(5px); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;h2&gt;Animated Button - "Pressed Effect"&lt;/h2&gt; &lt;div class=container&gt; &lt;button id="button-1"&gt;Btn1&lt;/button&gt; &lt;button id="button-2"&gt;Btn2&lt;/button&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>The problem seems to stem from <code>transform: translate(-50%, 0);</code>, which is what I have to do to center button-2 horizontally in the <code>container</code> div. I can remove that line and the effect works, but then button-2 is no longer centered horizontally. Why is it that <code>transform: translate(-50%, 0);</code> seemingly causes the subsequent <code>transform: translateY(5px);</code> not to work for button-2? Is there anyway I can horizontally (but not vertically) center button-2 while also being able to achieve the desired effect?</p>
[ { "answer_id": 74249865, "author": "Z2r", "author_id": 10885581, "author_profile": "https://Stackoverflow.com/users/10885581", "pm_score": 0, "selected": false, "text": "translate(-50%, 0)" }, { "answer_id": 74251544, "author": "A Haworth", "author_id": 10867454, "aut...
2022/10/29
[ "https://Stackoverflow.com/questions/74248626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17717171/" ]
74,248,698
<p>I am developing an 8 ball pool/billiards game in which I want to find out when all the balls on the table stop.</p> <p>I tried using this piece of code however the number of balls that have stopped keeps on incrementing to massive numbers when the value should be 16 or less.</p> <pre><code> IEnumerator CheckObjectsHaveStopped() { bool allSleeping = false; Rigidbody[] GOS = FindObjectsOfType(typeof(Rigidbody)) as Rigidbody[]; while (!allSleeping) { allSleeping = true; foreach (Rigidbody GO in GOS) { if (GO.velocity.magnitude &lt;= 0.1) { Balls_Stopped += 1; Debug.Log(&quot;Balls Stopped = &quot; + Balls_Stopped); yield return null; } } } if (Balls_Stopped == Balls_Left) { print(&quot;All objects sleeping&quot;); //Do something here } } </code></pre>
[ { "answer_id": 74249865, "author": "Z2r", "author_id": 10885581, "author_profile": "https://Stackoverflow.com/users/10885581", "pm_score": 0, "selected": false, "text": "translate(-50%, 0)" }, { "answer_id": 74251544, "author": "A Haworth", "author_id": 10867454, "aut...
2022/10/29
[ "https://Stackoverflow.com/questions/74248698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20352181/" ]
74,248,742
<p>I am generating a plot to show the estimates and CI graphically. Right now my estimates and y axis labels are out of synch on the plot.</p> <p>If this is my dataset.</p> <pre><code> Group Est conf.low conf.high pvalue Bi 1.12 0.65 1.603 0.000 Di -0.24 -0.44 -0.038 0.02 Dn -0.47 -0.80 -0.140 0.005 HMD -0.006 -0.32 0.311 0.968 HMS 0.72 -1.00 -0.436 0.000 LM -0.055 -0.32 0.214 0.6886 PaS -1.31 -1.79 -0.850 0.000 Ph A 0.065 -0.250 0.381 0.6885 TRB 1.023 0.63 1.41 0.000 TRC -0.599 -0.94 -0.249 0.0008 </code></pre> <p>What I am seeing is a plot like this below where the y axis labels and estimates are completely out of order. <a href="https://i.stack.imgur.com/TUEUC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TUEUC.png" alt="enter image description here" /></a></p> <p>This is my code</p> <pre><code> ggplot(df, aes(y = row.names(df), x= Est))+ geom_point(shape = 16, size =5)+ scale_y_discrete(label = df$Group) + geom_errobarh(aes(xmin = conf.low, xmax = conf.high), width =0, size = 1)+ geom_vline(xintercept=1, color=&quot;black&quot;, linetype = &quot;dashed&quot;, cex=1, alpha=0.5) </code></pre> <p>Any help on how to sync my y-axis labels with the estimates is much appreciated. Thanks.</p>
[ { "answer_id": 74248932, "author": "Wasim Aftab", "author_id": 6524326, "author_profile": "https://Stackoverflow.com/users/6524326", "pm_score": 2, "selected": false, "text": "geom_errorbarh" }, { "answer_id": 74248972, "author": "Allan Cameron", "author_id": 12500315, ...
2022/10/29
[ "https://Stackoverflow.com/questions/74248742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18795729/" ]
74,248,772
<p>I have a picture of the virtual address space of a process (for x86-64):</p> <p><a href="https://i.stack.imgur.com/hV5Vr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hV5Vr.png" alt="enter image description here" /></a></p> <p>However, I am confused about a few things.</p> <ol> <li>What is the &quot;Physical memory map&quot; region for?</li> <li>I know the 4-page tables are found in the high canonical region but where exactly are they? (data, code, stack, heap or physical memory map?)</li> </ol>
[ { "answer_id": 74249296, "author": "Peter Cordes", "author_id": 224132, "author_profile": "https://Stackoverflow.com/users/224132", "pm_score": 2, "selected": true, "text": "kmalloc" } ]
2022/10/29
[ "https://Stackoverflow.com/questions/74248772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14042260/" ]
74,248,796
<p>I'm trying to make a program that adds text to a web-page, like so:</p> <pre><code>Hello Morning Morning Morning Morning Evening </code></pre> <p>There should be:</p> <ol> <li>5 second delay between &quot;Hello&quot; and the first &quot;Morning&quot;.</li> <li>5 second delay between each &quot;Morning&quot;.</li> <li>6 second delay between the last &quot;Morning&quot; and &quot;Evening&quot;.</li> </ol> <p>Here's the whole HTML and JavaScript I've got so far.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function notify(msg, loops, taskTime) { var ul = document.getElementById("notifications"); for (let i = 0; i &lt; loops; i++) { (function(i) { window.setTimeout(function() { var li = document.createElement("li") li.appendChild(document.createTextNode(`${msg}`)); ul.appendChild(li) }, taskTime * i) }(i)) } } notify('Hello', 1, 5000) notify('Morning', 4, 5000) notify('Evening', 1, 6000)</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div&gt; &lt;ul id="notifications" style="list-style-type:none;margin-left:10%;"&gt;&lt;/ul&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>My problem is that on loading the web-page, the output is:</p> <pre><code>Hello Morning Evening Morning Morning Morning </code></pre> <p>How can I make sure that the function is ran in the order I want it to and not this mixed output? The first 3 outputs also appear instantly instead of a delay. How do I avoid that?</p>
[ { "answer_id": 74249296, "author": "Peter Cordes", "author_id": 224132, "author_profile": "https://Stackoverflow.com/users/224132", "pm_score": 2, "selected": true, "text": "kmalloc" } ]
2022/10/29
[ "https://Stackoverflow.com/questions/74248796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17988251/" ]
74,248,847
<p>I cannot understand this about C. Since every variable and function has to be unique (since they are global) then how can this be possible with a huge library like the standard C library and 3rd party libraries? Yes you could make every variable &quot;static&quot; but that does not seem to be the case.</p> <p>For example I was looking and I found this <code>random_data</code> struct <code>stdlib.h</code> and I am wondering - what are the chances that another library also has a struct called <code>random_data</code>? Won't that be a clash?</p> <p><strong>stdlib.h</strong></p> <pre><code>struct random_data { int32_t *fptr; int32_t *rptr; ... }; </code></pre> <p>I mean what if both <code>stdlib</code> and <code>stdio</code> have a struct called <code>random_data</code> and I was to include both libraries in my program? The standard library has thousands of functions and variables and it seems impossible that they all would be unique. Also what about 3rd party libraries? What if a 3rd party library also has a struct called <code>random_data</code>?</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; int main() { } </code></pre>
[ { "answer_id": 74249067, "author": "Sebastian Gudiño", "author_id": 12641617, "author_profile": "https://Stackoverflow.com/users/12641617", "pm_score": 4, "selected": true, "text": "SDL_" }, { "answer_id": 74249160, "author": "Suman Chapai", "author_id": 11436303, "au...
2022/10/29
[ "https://Stackoverflow.com/questions/74248847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9008233/" ]
74,248,861
<p><a href="https://i.stack.imgur.com/z62nb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/z62nb.png" alt="enter image description here" /></a></p> <p>I'm trying to start my game with none of the systems in place and the only thing on the screen is some background objects and the BUTTON.</p> <p>when I press the button, I want to instantiate all the objects that I need in the game.(which i know how to do, and isnt my problem.)</p> <p>MY PROBLEM is that i want the button to either</p> <ol> <li>destroy itself or 2) Move off screen or 3) scale down so it cant be seen.</li> </ol> <p>the script i have in place should be doing the scale down solution as thats attached to the onpress function but nothing seems to happen to the button on press but it does seem to manipulate the prefab of the button that isnt even on screen?</p> <p>CAN A BUTTON NOT MANIPULATE ITSELF?</p>
[ { "answer_id": 74249067, "author": "Sebastian Gudiño", "author_id": 12641617, "author_profile": "https://Stackoverflow.com/users/12641617", "pm_score": 4, "selected": true, "text": "SDL_" }, { "answer_id": 74249160, "author": "Suman Chapai", "author_id": 11436303, "au...
2022/10/29
[ "https://Stackoverflow.com/questions/74248861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20368164/" ]
74,248,865
<p>I have this formula:</p> <pre><code>=LET(a;FRUITS!A2:INDEX(FRUITS!B:B;LOOKUP(2;1/(FRUITS!A:A&lt;&gt;&quot;&quot;);ROW(FRUITS!B:B))); aa;INDEX(a;;1); ab;INDEX(a;;2); u;UNIQUE(INDEX(a;;2)); c;COUNTIF(ab;u); d;COUNTIFS(ab;u; aa;&quot;&gt;=&quot;&amp;TODAY() -VLOOKUP(SUBSTITUTE(D2;&quot; &quot;;&quot;&quot;); {&quot;24HOURS&quot;\0;&quot;2DAYS&quot;\1;&quot;3DAYS&quot;\4;&quot;7DAYS&quot;\7;&quot;2WEEKS&quot;\14;&quot;1MONTH&quot;\30;&quot;3MONTHS&quot;\90;&quot;6MONTHS&quot;\180;&quot;1YEAR&quot;\365;&quot;2YEARS&quot;\730;&quot;3YEARS&quot;\1095;&quot;TOTAL&quot;\999999}; 2;0)); SORT(CHOOSE({1\2\3};u;c;d);{2\1\1};{-1\1\1})) </code></pre> <p>This is in one sheet where the formula is:<br/> <a href="https://i.stack.imgur.com/lpPcs.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lpPcs.jpg" alt="enter image description here" /></a></p> <p>This is the other sheet containing the table with the raw data:<br/> <a href="https://i.stack.imgur.com/lOmzJ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lOmzJ.jpg" alt="enter image description here" /></a></p> <p>It is not counting by period in my real work file. I don't know why. Probably something to do with date formats? Now when I made this dummy file, I just changed names, and now it is working. The names in the real file are of people instead of fruits, like: &quot;Doe, John&quot;, &quot;Jane, Mary&quot; etc. Could this be the problem and not the date format?</p> <p>Also, I would like to have only 2 columns: one with the names of the unique items, and the 2nd with count &quot;By Period&quot;. If I want the total count, I will just choose from the validation menu. The name's column on the left should be sorted by descending order according to the count by period.</p> <p>Here is a file:<br/> <a href="https://1drv.ms/x/s!AhJ6NsWJczYBhSjKQVMab8WlYINT?e=akPt6d" rel="nofollow noreferrer">https://1drv.ms/x/s!AhJ6NsWJczYBhSjKQVMab8WlYINT?e=akPt6d</a></p> <p><strong>EDIT:<BR/></strong> The expected result is below. The count would change according to the period chosen above. In this case by month:<br/></p> <p><a href="https://i.stack.imgur.com/iL6Hm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iL6Hm.jpg" alt="enter image description here" /></a></p>
[ { "answer_id": 74249202, "author": "David Leal", "author_id": 6237093, "author_profile": "https://Stackoverflow.com/users/6237093", "pm_score": 1, "selected": false, "text": "G2" }, { "answer_id": 74256323, "author": "P.b", "author_id": 12634230, "author_profile": "ht...
2022/10/29
[ "https://Stackoverflow.com/questions/74248865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16498578/" ]
74,248,882
<p>I'm writing a program to play Chess. My <code>Game</code> class has the async function <code>play</code>. This function returns when the game ends, returning a Winner enum, which is either a stalemate or a win for some colour.</p> <p>In my <code>main</code> fn, I want to run <code>game.play</code>, then run <code>game.render()</code> repeatedly, until <code>game.play</code> returns a Winner, at which point the loop should stop.</p> <p>Having attempted to read the docs, I don't really understand why Pinning or Boxing is neccesary in order to poll the future, and I haven't been able to get it working.</p> <p>The desired code for <code>main</code> should look something like this:</p> <pre><code> let textures = piece::Piece::load_all_textures().await; let mut game = game::Game::new(player::Player::User, player::Player::User); let future = game.play(); while None = future.poll() { game.render(textures).await; next_frame().await; } // Do something now that the game has ended </code></pre> <p>I also understand that I will run into issues with borrow checking with this code, but that's a problem for me to deal with once I figure this one out.</p> <p>What is the easiest way of attempting what I am trying to do?</p>
[ { "answer_id": 74249202, "author": "David Leal", "author_id": 6237093, "author_profile": "https://Stackoverflow.com/users/6237093", "pm_score": 1, "selected": false, "text": "G2" }, { "answer_id": 74256323, "author": "P.b", "author_id": 12634230, "author_profile": "ht...
2022/10/29
[ "https://Stackoverflow.com/questions/74248882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13706799/" ]
74,248,895
<p>I have next big JSON...</p> <pre><code>{ &quot;field1&quot;: &quot;value1&quot;, &quot;field2&quot;: &quot;value2&quot;, ... &quot;field100&quot;: &quot;value100&quot;, } </code></pre> <p>...and appropriate POJO</p> <pre><code>@Builder @Data public class BigJsonDto{ private String field1; private String field2; private String field100; } </code></pre> <p>Let's say all fields are required and nullable except <code>field1</code> that can't have a <code>null</code> value.</p> <p>So I want to tell Jackson (or another way) stop serialization if one or more required fields have <code>null</code> value, rather than just ignore it (with <code>@JsonInclude</code>). How can I reach it?</p> <p>It would be nice if it's possible to use built-in <code>ObjectMapper</code>.</p> <p>I tried to use <code>@JsonProperty(required = true)</code> annotation but as I can see this annotation is used in deserialization. So in this case, I got required fields with null values.</p>
[ { "answer_id": 74249202, "author": "David Leal", "author_id": 6237093, "author_profile": "https://Stackoverflow.com/users/6237093", "pm_score": 1, "selected": false, "text": "G2" }, { "answer_id": 74256323, "author": "P.b", "author_id": 12634230, "author_profile": "ht...
2022/10/29
[ "https://Stackoverflow.com/questions/74248895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10941865/" ]
74,248,898
<p>I am trying to create a regular expression that will capture JavaScript object properties, but I only want top level properties.<br /> So for example I want to capture <code>this.nodeName</code> but I do not want to capture <code>this.nodeName.length</code></p> <p>I am trying the following expression: <code>(this\.\w+)(?!\.)</code><br /> But the lookahead seems to be only working on the <code>\w+</code> and not on the whole capture group and I don't understand why this is.<br /> For example if I apply <code>this(?!\.)</code> to <code>this.</code> then it doesn't match <code>thi</code>, so I don't understand why capture groups seem to act differently.</p> <p><a href="https://regexr.com/717lh" rel="nofollow noreferrer">Here is a demo of my expression</a></p> <p>Perhaps someone more experienced in regular expression could help me out.</p> <p>Thanks</p>
[ { "answer_id": 74249202, "author": "David Leal", "author_id": 6237093, "author_profile": "https://Stackoverflow.com/users/6237093", "pm_score": 1, "selected": false, "text": "G2" }, { "answer_id": 74256323, "author": "P.b", "author_id": 12634230, "author_profile": "ht...
2022/10/29
[ "https://Stackoverflow.com/questions/74248898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2137483/" ]
74,248,917
<p>I've made a dummy project just to show what is trying to be made. I'm going for a transition on color for text without CSS (as I just can't wrap my head around CSS). In the dummy project, the text starts from red</p> <p><a href="https://i.stack.imgur.com/qKma0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qKma0.png" alt="enter image description here" /></a></p> <p>then goes to blue</p> <p><a href="https://i.stack.imgur.com/Ib6Vg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ib6Vg.png" alt="enter image description here" /></a></p> <p>Found out about <code>FillTransition</code> though that only works with shapes, so this would be a similar function. My other attempt was trying to get the RGB values of both colors then stick them in a <code>do while</code> with a new <code>Color</code> just to test it out though the transition is almost instant as the application starts so it changes the color but without transitioning effect. I'm thinking of making an <code>Timeline</code> for this similar to the <code>do while</code> but I haven't tried that yet.</p> <p>Before going into this what are some ways to make this effect?</p> <p>Here's the dummy code:</p> <pre><code>package application; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.layout.BorderPane; import javafx.scene.layout.StackPane; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.stage.Stage; public class Main extends Application { @Override public void start(Stage primaryStage) { try { BorderPane root = new BorderPane(); Scene scene = new Scene(root,400,400); StackPane stack = new StackPane(); Text text = new Text(&quot;Hello there StackOverflow, how are you? (:&quot;); Color color1 = Color.RED; Color color2 = Color.BLUE; double r1 = color1.getRed(); double g1 = color1.getGreen(); double b1 = color1.getBlue(); double r2 = color2.getRed(); double g2 = color2.getGreen(); double b2 = color2.getBlue(); Color colorEffect = new Color(r1, g1, b1, 1.0); stack.setLayoutX(200); stack.setLayoutY(200); text.setFont(Font.font(16)); text.setFill(colorEffect); stack.getChildren().add(text); root.getChildren().add(stack); scene.getStylesheets().add(getClass().getResource(&quot;application.css&quot;).toExternalForm()); primaryStage.setScene(scene); primaryStage.show(); } catch(Exception e) { e.printStackTrace(); } } public static void main(String[] args) { launch(args); } } </code></pre>
[ { "answer_id": 74249258, "author": "trashgod", "author_id": 230513, "author_profile": "https://Stackoverflow.com/users/230513", "pm_score": 3, "selected": true, "text": "Color" }, { "answer_id": 74283063, "author": "jewelsea", "author_id": 1155209, "author_profile": "...
2022/10/29
[ "https://Stackoverflow.com/questions/74248917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18969521/" ]
74,248,951
<p>I'm trying to copy text using clipboard.js but it's not copying. here's my code</p> <pre><code>$(document).ready(async function () { var html = '' var script = '&lt;script&gt;' let response = await ajax('/admin/all_files', 'POST', '') for (let i = 0; i &lt; response.length; i++) { var url = window.location.origin + '/get_file/' + response[i][0] html += `&lt;div&gt; &lt;img src=&quot;`+ url +`&quot; alt=&quot;&quot;&gt; &lt;div&gt; &lt;button id=&quot;ttc_`+ i +`_url&quot; data-clipboard-text=`+ url +`&gt;URL&lt;/button&gt; &lt;/div&gt; &lt;/div&gt;` script += `var ttc_`+ i +`_url = new Clipboard('#ttc_`+ i +`_url');` } $('#insert_image_modal_body').html(html) script += '&lt;/script&gt;' $('body').append(script) }) </code></pre> <p>my ajax function is:</p> <pre><code>async function ajax(url, method, data) { return $.ajax({ url: window.location.origin + url, method: method, data: data }).done((response) =&gt; { return response }); } </code></pre> <p>it shows nothing, no error but the text is not copying too.</p>
[ { "answer_id": 74249668, "author": "MackProgramsAlot", "author_id": 3625915, "author_profile": "https://Stackoverflow.com/users/3625915", "pm_score": -1, "selected": true, "text": "var" }, { "answer_id": 74255446, "author": "Usama Javed", "author_id": 16414320, "autho...
2022/10/29
[ "https://Stackoverflow.com/questions/74248951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16414320/" ]
74,248,962
<p>Im using opencv for detecting a hand gesture (in this case, when i lift my index finger), when that happens it prints &quot;hi&quot;, then i use time.sleep to pause the print for 1 second because it will print it until I put my index down, but time.sleep pauses the entire footage, so if i sleep 5 seconds, the footage wont run untile those 5 seconds have passed</p> <p>What can I do to use the time.sleep without pausing the footage</p> <pre><code>while True: #all the opencv initial stuff #mediapipe functions for the hand detection if INDEX_UP: print(&quot;hi&quot;) time.sleep(2) cv2.imshow(&quot;Frame&quot;, frame) if cv2.waitKey(1) &amp; 0xFF == 27: break </code></pre> <p>Im trying to use time.sleep inside the while loop im using for opencv, but the time.sleep pauses the footage until the time.sleep finish</p>
[ { "answer_id": 74249668, "author": "MackProgramsAlot", "author_id": 3625915, "author_profile": "https://Stackoverflow.com/users/3625915", "pm_score": -1, "selected": true, "text": "var" }, { "answer_id": 74255446, "author": "Usama Javed", "author_id": 16414320, "autho...
2022/10/29
[ "https://Stackoverflow.com/questions/74248962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19884479/" ]
74,248,986
<p>I am running the following query: (see <a href="https://learn.microsoft.com/en-us/sql/relational-databases/search/query-with-full-text-search?view=sql-server-ver16" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/sql/relational-databases/search/query-with-full-text-search?view=sql-server-ver16</a>)</p> <pre><code>SELECT KEY_TBL.RANK, FT_TBL.* FROM dbo.Forums AS FT_TBL INNER JOIN FREETEXTTABLE(dbo.Forums, Title,'{searchTerm}') AS KEY_TBL ON FT_TBL.Id = KEY_TBL.[KEY] ORDER BY KEY_TBL.RANK DESC </code></pre> <p>This works great when I run it in SQL Server Management Studio, but when I run it in my API, I do not get the rank. It is always 0.</p> <p>Here is my model:</p> <pre><code>public class Forum : BaseModel { public ApplicationUser? ForumAuthor { get; set; } public string ForumAuthorId { get; set; } = &quot;&quot;; [Required (AllowEmptyStrings = false,ErrorMessage = &quot;A Title is required&quot;)] public string? Title { get; set; } public List&lt;Post&gt;? Posts { get; set; } [NotMapped] public int RANK { get; set; } } </code></pre> <p>Notice that RANK has a <code>[NotMapped]</code> attribute. I did that because I don't have a RANK field on the Forums table.</p> <p>So I decided to create a <code>ForumViewModel</code> that has a RANK field without the <code>[NotMapped]</code> attribute.</p> <p>Here is my query:</p> <pre><code>List&lt;ForumViewModel&gt; forums = await _context.Forums.FromSqlRaw(forumSql).Select(x =&gt; new ForumViewModel() { ForumAuthor = x.ForumAuthor, ForumAuthorId = x.ForumAuthorId, Posts = x.Posts, RANK = x.RANK, Title = x.Title, }).ToListAsync(); </code></pre> <p>The result is the same. RANK = 0.</p> <p>If I remove the <code>[NotMapped]</code> attribute, I get the rank with a valid number greater than 0. So I believe the <code>[NotMapped]</code> attribute is the problem.</p> <p>The rank is returned by the FREETEXTTABLE. So, I am using DbContext to query my Forums table, joined to FREETEXTTABLE. This table returns the rank of the search term against all text in the title field of the Forums table. Please see the link I put in the beginning of this post.</p> <p>How can I get the Rank without having to needlessly add the <code>Rank</code> field to my <code>Forum</code> table.</p> <p>Edit: Solved I figured it out. There is a data annotation for this situation:</p> <pre><code>[DatabaseGenerated(DatabaseGeneratedOption.Computed)] public int RANK { get; set; } </code></pre>
[ { "answer_id": 74249108, "author": "jdweng", "author_id": 5015238, "author_profile": "https://Stackoverflow.com/users/5015238", "pm_score": -1, "selected": false, "text": " int[] quantities = { 49, 49, 41, 30, 17, 35, 25, 24, 14, 12 };\n\n Dictionary<int, int> rankDic...
2022/10/29
[ "https://Stackoverflow.com/questions/74248986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1561777/" ]
74,248,987
<p>I want to repeat over the first 50 items in a list with 150 items/objects. Is there some shortcut or smart way achieve this in AppleScript. I know of</p> <pre><code>repeat with theObject in theObjectList </code></pre> <p>as well ass</p> <pre><code>repeat 50 times </code></pre> <p>Can they be combined somehow?</p>
[ { "answer_id": 74249108, "author": "jdweng", "author_id": 5015238, "author_profile": "https://Stackoverflow.com/users/5015238", "pm_score": -1, "selected": false, "text": " int[] quantities = { 49, 49, 41, 30, 17, 35, 25, 24, 14, 12 };\n\n Dictionary<int, int> rankDic...
2022/10/29
[ "https://Stackoverflow.com/questions/74248987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1802826/" ]
74,248,994
<pre><code> ElevatedButton.icon( onPressed: null, label: Text(&quot;Close&quot;), icon: Icon(Icons.close), ) </code></pre> <p><a href="https://i.stack.imgur.com/K1uu8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/K1uu8.png" alt="enter image description here" /></a></p> <p>As seen in the picture, the icon is on the left, the text is on the right. How can I do the opposite?</p>
[ { "answer_id": 74249115, "author": "zabaykal", "author_id": 12247578, "author_profile": "https://Stackoverflow.com/users/12247578", "pm_score": 0, "selected": false, "text": "label" }, { "answer_id": 74249116, "author": "hamza aboshhiwa", "author_id": 15965038, "autho...
2022/10/29
[ "https://Stackoverflow.com/questions/74248994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17906689/" ]
74,249,004
<p>Can't find the answer to this question.</p> <p>What would you set delim to if you had a line of text data as follows in R?</p> <pre><code>Casey.Brook-Smith.”1200 Clover Lane, Hamden, CT”.8605555812.10-24-2001 </code></pre> <p>Test your answer with <code>read_&lt;fill in here&gt;</code>.</p> <p>I tried:</p> <pre><code>#create data frame df &lt;- data.frame(Casey.Brook-Smith.”1200 Clover Lane, Hamden, CT”.8605555812.10-24-2001) </code></pre> <p>but it said it was an error.</p>
[ { "answer_id": 74249115, "author": "zabaykal", "author_id": 12247578, "author_profile": "https://Stackoverflow.com/users/12247578", "pm_score": 0, "selected": false, "text": "label" }, { "answer_id": 74249116, "author": "hamza aboshhiwa", "author_id": 15965038, "autho...
2022/10/29
[ "https://Stackoverflow.com/questions/74249004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20249990/" ]
74,249,014
<p>The user is supposed to enter a number from 1 to 10 and the code is supposed to check for 3 conditions if the input is not a number ask for entering again, if the input is out of 1-10 ask for entering again, and if the number is in range of 1-10 break the loop and store the value in the variable. the first two checks are running correctly, but the last is not working, the loop does not break, and it says invalid input like other conditions. What is the problem?</p> <pre><code> while True: num_guess = input(&quot;How many times you want to guess [1-10]: &quot;) # Asking for number of guess if num_guess != int: # Checking for non number input print(&quot;Invalid input&quot;) elif int(num_guess) &lt; 1 or int(num_guess) &gt; 10: # Checking for out of range input print(&quot;Invalid input&quot;) elif 1 &lt;= int(num_guess) &lt;= 10: # if input is in the range just break the loop and store the answer break </code></pre>
[ { "answer_id": 74249060, "author": "user17301834", "author_id": 17301834, "author_profile": "https://Stackoverflow.com/users/17301834", "pm_score": -1, "selected": false, "text": "if num_guess != int" }, { "answer_id": 74249072, "author": "keidakida", "author_id": 9492513...
2022/10/29
[ "https://Stackoverflow.com/questions/74249014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
74,249,021
<p>I can't seem to figure out where in my loop I don't come back to referencing the same indexed values to validate the palindrome.</p> <p>I tried the code and should expect to see &quot;This is a palindrome&quot; but it returns the opposite</p>
[ { "answer_id": 74249086, "author": "Ric Villalba", "author_id": 6912817, "author_profile": "https://Stackoverflow.com/users/6912817", "pm_score": 2, "selected": false, "text": "seq_along" }, { "answer_id": 74249332, "author": "Allan Cameron", "author_id": 12500315, "a...
2022/10/29
[ "https://Stackoverflow.com/questions/74249021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11915247/" ]
74,249,038
<p>Currently, both the image and play button are both clickable. How would I adjust it so that only the play button is clickable?</p> <p>I am trying to figure out how to adjust it so that only the play button is clickable. How am I able to do that? Is this able to be done?</p> <p>code <a href="https://jsitor.com/3RCuY3s_O" rel="nofollow noreferrer">https://jsitor.com/3RCuY3s_O</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-js lang-js prettyprint-override"><code>(function(){ let YouTubeContainers = document.querySelectorAll(".embed-youtube"); // Iterate over every YouTube container you may have for (let i = 0; i &lt; YouTubeContainers.length; i++) { let container = YouTubeContainers[i]; let imageSource = "https://img.youtube.com/vi/"+ container.dataset.videoId +"/sddefault.jpg"; // Load the Thumbnail Image asynchronously let image = new Image(); image.src = imageSource; image.addEventListener("load", function() { container.appendChild(image); }); // When the user clicks on the container, load the embedded YouTube video container.addEventListener("click", function() { let iframe = document.createElement( "iframe" ); iframe.setAttribute("frameborder", "0"); iframe.setAttribute("allowfullscreen", ""); iframe.setAttribute("allow", "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"); // Important: add the autoplay GET parameter, otherwise the user would need to click over the YouTube video again to play it iframe.setAttribute("src", "https://www.youtube.com/embed/"+ this.dataset.videoId +"?rel=0&amp;showinfo=0&amp;autoplay=1"); // Clear Thumbnail and load the YouTube iframe this.innerHTML = ""; this.appendChild( iframe ); }); } })();</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.container { position: absolute; left: 0; right: 0; min-height: 100%; display: flex; padding: 8px 8px; } .curtain { flex: 1 0 0; margin: auto; max-width: 640px; min-width: 155px; position: relative; } .embed-youtube { background-color: #000; margin-bottom: 10px; position: relative; height: 0; padding-top: 56.25%; overflow: hidden; } .embed-youtube img { width: 100%; top: -16.84%; left: 0; opacity: 0.7; } /*.embed-youtube img, .embed-youtube .embed-youtube-play { cursor: default; }*/ .embed-youtube img, .embed-youtube iframe, .embed-youtube .embed-youtube-play, .embed-youtube .embed-youtube-play:before { position: absolute; } .embed-youtube iframe { height: 100%; width: 100%; top: 0; left: 0; } .embed-youtube .embed-youtube-play { -webkit-appearance: none; appearance: none; position: absolute; top: 0; left: 0; bottom: 0; right: 0; margin: auto; display: flex; justify-content: center; align-items: center; width: 90px; height: 90px; border-radius: 50%; cursor: pointer; border: 9px solid blue; background: transparent; filter: drop-shadow(3px 3px 3px #000000b3); z-index: 1; } .embed-youtube-play::before { content: ""; width: 0; height: 0; border-top: 20px solid transparent; border-bottom: 20px solid transparent; border-left: 27px solid blue; transform: translateX(4px); } .embed-youtube-play:hover { box-shadow: 0 0 0 5px rgba(43, 179, 20, 0.5); } .embed-youtube-play:focus { outline: 0; box-shadow: 0 0 0 5px rgba(0, 255, 255, 0.5); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="container"&gt; &lt;div class="curtain"&gt; &lt;!-- 1. Video Wrapper Container --&gt; &lt;div class="embed-youtube" data-video-id="djV11Xbc914"&gt; &lt;!-- 2. The preview button that will contain the Play icon --&gt; &lt;button class="embed-youtube-play" type="button" aria-label="Open"&gt;&lt;/button&gt; &lt;/div&gt; &lt;!-- 1. Video Wrapper Container --&gt; &lt;div class="embed-youtube" data-video-id="djV11Xbc914"&gt; &lt;!-- 2. The preview button that will contain the Play icon --&gt; &lt;button class="embed-youtube-play" type="button" aria-label="Open"&gt;&lt;/button&gt; &lt;/div&gt; &lt;!-- 1. Video Wrapper Container --&gt; &lt;div class="embed-youtube" data-video-id="djV11Xbc914"&gt; &lt;!-- 2. The preview button that will contain the Play icon --&gt; &lt;button class="embed-youtube-play" type="button" aria-label="Open"&gt;&lt;/button&gt; &lt;/div&gt; &lt;!-- 1. Video Wrapper Container --&gt; &lt;div class="embed-youtube" data-video-id="djV11Xbc914"&gt; &lt;!-- 2. The preview button that will contain the Play icon --&gt; &lt;button class="embed-youtube-play" type="button" aria-label="Open"&gt;&lt;/button&gt; &lt;/div&gt; &lt;!-- 1. Video Wrapper Container --&gt; &lt;div class="embed-youtube" data-video-id="djV11Xbc914"&gt; &lt;!-- 2. The preview button that will contain the Play icon --&gt; &lt;button class="embed-youtube-play" type="button" aria-label="Open"&gt;&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74249071, "author": "Marco1314", "author_id": 16371374, "author_profile": "https://Stackoverflow.com/users/16371374", "pm_score": 0, "selected": false, "text": " for(let button of embed-youtube-play) {\n button.addEventListener(\"click\", function() {\n //yourCode\...
2022/10/29
[ "https://Stackoverflow.com/questions/74249038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17631451/" ]
74,249,054
<p>I just upgraded to cordova-android@11.0.0 targeting API 31. This required replacing the splash screen plugin from my previous builds. I use <code>AutoHideSplashScreen = false</code> so that I can hide the splash screen after the UI is rendered. This works fine on iOS but the splash screen persists forever on Android despite calls to <code>navigator.splashscreen.hide()</code> (even with the debugger). This happened both on API 31 and older devices. I resorted to auto-hide with a long fade for now, to get something working. I tried several different config.xml variants so I'm not sure whether putting one here will be useful, but for all of them <code>AutoHideSplashScreen = false</code> on Android did not work.</p>
[ { "answer_id": 74249071, "author": "Marco1314", "author_id": 16371374, "author_profile": "https://Stackoverflow.com/users/16371374", "pm_score": 0, "selected": false, "text": " for(let button of embed-youtube-play) {\n button.addEventListener(\"click\", function() {\n //yourCode\...
2022/10/29
[ "https://Stackoverflow.com/questions/74249054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3003010/" ]
74,249,075
<p>I have a single dynamodb table. One of the type records is called &quot;Result&quot; and one of its PK stores a composite key (class, student and exercise). This is the example design:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>PK</th> <th>SK</th> <th>SCORE</th> <th>...</th> <th>GSI PK 1</th> <th>GSI SK 1</th> </tr> </thead> <tbody> <tr> <td>RESULT#001</td> <td>RESULT#001</td> <td>90</td> <td>...</td> <td>CLASS#MATH#STUDENT#TOM#EXERCISE#1</td> <td>RESULT#001</td> </tr> </tbody> </table> </div> <p>Use cases:</p> <ol> <li>Find result by student (<code>gsi pk 1 = &quot;CLASS#MATH#STUDENT#TOM#EXERCISE#1&quot;, gsi sk 1 = begins_with(&quot;RESULT&quot;)</code>)</li> </ol> <p>Now, there's a new use case: 2. Find all results by student</p> <p>To meet this requirement, I could either:</p> <ul> <li>Add a new GSI which does not store the exercise ID. The query will look: (<code>gsi pk 2 = &quot;CLASS#MATH#STUDENT#TOM&quot;, gsi sk 2 = begins_with(&quot;RESULT&quot;)</code>)</li> <li>In the backend service, iterate over all exercises and execute multiple dynamo db queries re-using GSI 1</li> </ul> <p>First option may be performant. However, it requires to update the dynamo db table whereas second option uses same design. What's a recommended design criteria to follow?</p>
[ { "answer_id": 74249071, "author": "Marco1314", "author_id": 16371374, "author_profile": "https://Stackoverflow.com/users/16371374", "pm_score": 0, "selected": false, "text": " for(let button of embed-youtube-play) {\n button.addEventListener(\"click\", function() {\n //yourCode\...
2022/10/29
[ "https://Stackoverflow.com/questions/74249075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/858820/" ]
74,249,187
<p>Suppose I have an enum class</p> <pre><code>enum class ENUM{ A, B, C}; </code></pre> <p>And I want to have a switch statement. So I get</p> <pre><code>char c = 'B'; ENUM e = ENUM::A; switch(e) { case A: break; case B: break; case C: break; } </code></pre> <p>The case could never be B. But how to convert value <code>c</code> to be enum value?</p>
[ { "answer_id": 74249229, "author": "πάντα ῥεῖ", "author_id": 1413395, "author_profile": "https://Stackoverflow.com/users/1413395", "pm_score": 0, "selected": false, "text": "enum class ENUM{ A = 'A', B = 'B', C = 'C' };\n" }, { "answer_id": 74249260, "author": "Luminous", ...
2022/10/29
[ "https://Stackoverflow.com/questions/74249187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19106825/" ]
74,249,192
<p>I want to split a string of 1s and 0s into a list of repeated groups of these characters.</p> <p>Example:</p> <p><code>m = '00001100011111000'</code></p> <p>Goes to:</p> <p><code>m = ['0000', '11', '000', '11111', '000']</code></p> <p>How would I do this in efficient concise code? Would regex work for this?</p>
[ { "answer_id": 74249208, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 2, "selected": false, "text": "re" }, { "answer_id": 74249214, "author": "Community", "author_id": -1, "author_profile"...
2022/10/29
[ "https://Stackoverflow.com/questions/74249192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14333466/" ]
74,249,226
<p>I am trying to write a program that will convert a Stream&lt;String&gt; into a String&lt;Record&gt; where everytime there is a comma in the string, it puts that data into one section of the data. My first thought on doing this was to use split() like so:</p> <pre><code>return fileToStream(&quot;data.csv&quot;).forEach(s -&gt; s.split(&quot;,&quot;)); </code></pre> <p>The fileToStream function is simply taking the data.csv and converting it into a Stream I don't quite understand why this is returning void, any help would be greatly appreciated.</p> <p>I expected it to take something like 123,hello,hello,hello,123,123 and instead of it all being one string, turning it into a record of int, string, string, string, double, double, etc.</p>
[ { "answer_id": 74249288, "author": "knittl", "author_id": 112968, "author_profile": "https://Stackoverflow.com/users/112968", "pm_score": 1, "selected": false, "text": "forEach" }, { "answer_id": 74259340, "author": "Teddy Tsai", "author_id": 16959486, "author_profile...
2022/10/29
[ "https://Stackoverflow.com/questions/74249226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13335868/" ]
74,249,262
<p>I am trying to write a code that will work like this:</p> <p>First function of the code is registration: here the user will input their username and password, then the code will create a text file named after the username and it will include 2 lines:</p> <pre class="lang-none prettyprint-override"><code>1.username 2.password </code></pre> <pre><code>import time def registracia(): print (&quot;To register you'll need to type your username and your password.&quot;) time.sleep (1.5) userName = input(&quot;username: &quot;) time.sleep (1.5) passWord = input(&quot;password: &quot;) filename = userName + &quot;.txt&quot; file = open(filename, &quot;+w&quot;) file.write (userName+&quot;\n&quot;) file.write (passWord) file.close if __name__ == &quot;__main__&quot;: registracia() </code></pre> <p>Then there's the 2nd function of the code and that will be login. My thought for the login is that it will ask for input of the username, then it will open the file named after the username and read the 2nd line, after reading the line it will ask for input of password and then use if to check if the input is equal to the 2nd line.</p> <p>My problem is that the readline only reads 1 letter from the username, at least that's what I think it's doing.</p> <pre><code>import time print (&quot;To login you'll need to type your username first&quot;) def login(): #time.sleep (1.5) userName = input (&quot;username: &quot;) filename = userName +&quot;.txt&quot; file = open(filename, &quot;r&quot;) #time.sleep (1.5) realPassWord = file.readline(2) print (realPassWord) passWord = input (&quot;password: &quot;) if passWord == realPassWord: print (&quot;successfuly logged in &quot;) elif passWord != realPassWord: print (&quot;incorrect password&quot;) login() login() </code></pre> <p>I'm also adding an example of input and outputs to see what's happening:</p> <p>Registration:</p> <p>Input:</p> <pre class="lang-none prettyprint-override"><code>username: abc321 password: cba123 </code></pre> <p>Output:</p> <p>abc321.txt (a text file):</p> <pre class="lang-none prettyprint-override"><code>abc321 cba123 </code></pre> <p>Login:</p> <p>Input:</p> <pre class="lang-none prettyprint-override"><code>abc321 </code></pre> <p>Output (the output shouldn't be really visible, output is what the code will expect for the password input, but I added the print of <code>realPassWord</code> so I can see what the code expects):</p> <pre class="lang-none prettyprint-override"><code>ab </code></pre> <p>Desired output:</p> <pre class="lang-none prettyprint-override"><code>cba123 </code></pre>
[ { "answer_id": 74249389, "author": "lambdaxpy", "author_id": 14001706, "author_profile": "https://Stackoverflow.com/users/14001706", "pm_score": 2, "selected": true, "text": "file.close()" }, { "answer_id": 74252022, "author": "ukBaz", "author_id": 7721752, "author_pr...
2022/10/29
[ "https://Stackoverflow.com/questions/74249262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20056212/" ]
74,249,276
<p>I'm trying to make this kind of transformations :</p> <p><a href="https://i.stack.imgur.com/PQmJ4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PQmJ4.png" alt="enter image description here" /></a></p> <p>I tried so many reshape functions but still not getting the expected output.</p> <p>Do you have any ideas, please ? If needed, here is an example :</p> <pre><code>import pandas as pd df = pd.DataFrame({'A': ['ID_X', 'A01', 'Green', 'A02', 'Cerise', 'ID_Y', 'A01', 'Azure', 'A02', 'Black'], 'B': ['ID_X', 'B01', 'Red', 'B02', 'Celeste', 'ID_Y', 'B01', 'Beige', 'B02', 'Rose'], 'C': ['ID_X', 'C01', 'Brown', 'C02', 'Orange', 'ID_Y', 'C01', 'Canary', 'C02', 'White'], 'TYPE': ['ID', 'POSITION', 'COLOR', 'POSITION', 'COLOR', 'ID', 'POSITION', 'COLOR', 'POSITION', 'COLOR']}) </code></pre>
[ { "answer_id": 74249370, "author": "BeRT2me", "author_id": 11865956, "author_profile": "https://Stackoverflow.com/users/11865956", "pm_score": 3, "selected": true, "text": "# Cumcount to mark your different groups\ndf['column'] = df[df.TYPE.eq('ID')].groupby('TYPE').cumcount()\ndf.column...
2022/10/29
[ "https://Stackoverflow.com/questions/74249276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16120011/" ]
74,249,406
<p>I'd like to create dynamic types excluding duplicates. This is what I have right now:</p> <pre class="lang-js prettyprint-override"><code>type Currency = 'CAD' | 'USD' | 'EUR'; type CurrencyQuote = `${Currency}x${Currency}`; // returns: &quot;CADxUSD&quot; | &quot;USDxCAD&quot; | &quot;CADxCAD&quot; | &quot;CADxEUR&quot; | &quot;USDxUSD&quot; | &quot;USDxEUR&quot; | &quot;EURxCAD&quot; | &quot;EURxUSD&quot; | &quot;EURxEUR&quot; </code></pre> <p>How could I exclude the ones that are duplicated, like <code>USD|USD</code>, <code>CAD|CAD</code> and <code>EUR|EUR</code>?</p> <p>Thanks</p>
[ { "answer_id": 74249435, "author": "Tobias S.", "author_id": 8613630, "author_profile": "https://Stackoverflow.com/users/8613630", "pm_score": 2, "selected": false, "text": "Currency" }, { "answer_id": 74249444, "author": "jcalz", "author_id": 2887218, "author_profile...
2022/10/29
[ "https://Stackoverflow.com/questions/74249406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5203020/" ]
74,249,471
<p>I’m trying to figure out what are some loop optimizations (in compilers) that can be applied to (linear algebra) vector summation?</p> <p>Vector sum is defined</p> <pre class="lang-py prettyprint-override"><code>for i in range(len(vector1)): vector_result[i] = vector1[i] + vector2[i] </code></pre> <p>How can I optimize this?</p> <p>Some loop optimizations I’m aware of:</p> <ol> <li>Loop fission</li> <li>Loop fusion</li> <li>Vectorization</li> <li>Tiling But I don’t know how any of these can be applied to the summation of vectors.</li> </ol> <p>If anybody out there know a thing or two about compilers and loop optimizations i will appreciate if you give me an example of the code after a loop optimization is applied. Thanks</p>
[ { "answer_id": 74250317, "author": "chez93", "author_id": 15403542, "author_profile": "https://Stackoverflow.com/users/15403542", "pm_score": 0, "selected": false, "text": "for i in range(0, len(v), 2):\n vector_result[i] = v[i] + v[i]\n vector_result[i+1] = v[i+1] + v[i+1]\n" },...
2022/10/29
[ "https://Stackoverflow.com/questions/74249471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15403542/" ]
74,249,478
<p>I am creating a flutter Web application, but have issues when resizing the window with a SingleChildScrollView + ScrollController.</p> <p>When I resize the browser window, the page &quot;snaps&quot; back up to the very top. Being a web app, most of the page &quot;sections&quot; are made from Columns with responsively coded widgets as children, with such widgets as Flexible or Expanded. From what I have read, the SingleChildScrollView widget doesn't work well with Flexible or Expanded widgets, so I thought that may be my issue.</p> <p>For testing purposes, I created a new page with a single SizedBox that had a height of 3000, which would allow me to scroll. After scrolling to the bottom and resizing the window, I was still snapped up to the top of the page. Thus, with or without using Expanded or Flexible widgets, I have the same result.</p> <p><strong>Test with a SizedBox only</strong></p> <pre><code> @override Widget build(BuildContext context) { return Scaffold( color: Colors.white, body: SingleChildScrollView( controller: controller.scrollController, primary: false, child: Column( children: [ SizedBox( width: 150, height: 3000, ), ], ), ), ); } </code></pre> <p>I am using Getx with this project to try getting a demo app up and running a bit quicker while I am still learning the core concepts. Below is my controller.</p> <p><strong>Controller</strong></p> <pre><code>class HomePageScrollControllerX extends GetxController { late ScrollController scrollController; @override void onInit() { super.onInit(); scrollController = ScrollController( initialScrollOffset: 0.0, keepScrollOffset: true, ); } } </code></pre> <p>Thank you in advance for any insight on this subject!</p> <p><strong>EDIT</strong></p> <p>I have added a listener on my ScrollController, which is able to print to the console that I am scrolling. However, the listener does not get called when I resize the window (tested in both Chrome and Edge).</p> <p>Currently, I believe my only option is to use the listener to update an &quot;offset&quot; variable in the controller, and pass the window's width over to the controller when the widget rebuilds. If done properly, I should be able to use the controller to scroll to the saved offset. Something like this:</p> <pre><code>if (scrollController.hasClients) { if (offset &gt; scrollController.position.maxScrollExtent) { scrollController.jumpTo(scrollController.position.maxScrollExtent); } else if (offset &lt; scrollController.position.minScrollExtent) { scrollController.jumpTo(scrollController.position.minScrollExtent); } else { scrollController.jumpTo(offset); } } </code></pre> <p>However, I feel like this shouldn't be necessary - and I bet this solution would be visually evident to the user.</p> <p><strong>Edit 2</strong></p> <p>While I did get this to work with adding the below code just before the return statement, it appears that my initial thoughts were correct. When I grab the edge of the window and move it, it pops up to the top of the window, then will jump to the correct scroll position. It looks absolutely terrible!</p> <pre><code> @override Widget build(BuildContext context) { Future.delayed(Duration.zero, () { controller.setWindowWithAndScroll(MediaQuery.of(context).size.width); }); return PreferredScaffold( color: Colors.white, body: SingleChildScrollView( controller: controller.scrollController, ...... </code></pre>
[ { "answer_id": 74250317, "author": "chez93", "author_id": 15403542, "author_profile": "https://Stackoverflow.com/users/15403542", "pm_score": 0, "selected": false, "text": "for i in range(0, len(v), 2):\n vector_result[i] = v[i] + v[i]\n vector_result[i+1] = v[i+1] + v[i+1]\n" },...
2022/10/29
[ "https://Stackoverflow.com/questions/74249478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11229377/" ]
74,249,488
<p>I am fetching data from jsonplaceholder. It works correctly. But I want to add new position to the list using RTK query. Request is being submitted successfully, but the new item is not being added to my list. What I am doing wrong?</p> <p>That's my slice:</p> <pre><code>import { createApi, fetchBaseQuery } from &quot;@reduxjs/toolkit/query/react&quot;; export const apiUsersSlice = createApi({ reducerPath: &quot;apiUsersSlice&quot;, baseQuery: fetchBaseQuery({ baseUrl: &quot;https://my-json-server.typicode.com&quot;, }), tagTypes: ['Users'], endpoints: (builder) =&gt; ({ getUsers: builder.query({ query: () =&gt; &quot;/karolkproexe/jsonplaceholderdb/data&quot;, providesTags: ['Users'], transformResponse: (response) =&gt; { const data = response.map((obj) =&gt; ({ id: obj.id, name: obj.name, username: obj.username, city: obj.address.city, email: obj.email, })); return data; }, }), addUser: builder.mutation({ query: (body) =&gt; ({ url: '/karolkproexe/jsonplaceholderdb/data', method: 'POST', body, invalidatesTags: ['Users'], }), transformResponse: (response) =&gt; response.data, }), }), }); export const { useGetUsersQuery, useAddUserMutation } = apiUsersSlice; </code></pre> <p>That's my store file:</p> <pre><code>import { configureStore } from &quot;@reduxjs/toolkit&quot; import { apiUsersSlice } from &quot;./api/apiUsersSlice&quot;; export const store = configureStore({ reducer : { [apiUsersSlice.reducerPath] : apiUsersSlice.reducer, }, middleware : (getDefaultMiddlewares) =&gt; getDefaultMiddlewares().concat(apiUsersSlice.middleware), }) </code></pre> <p>And of course the index file:</p> <pre><code>import React from &quot;react&quot;; import ReactDOM from &quot;react-dom/client&quot;; import App from &quot;./App&quot;; import { Provider } from 'react-redux'; import { ApiProvider } from &quot;@reduxjs/toolkit/dist/query/react&quot;; import { apiUsersSlice } from &quot;./api/apiUsersSlice&quot;; import {store} from './store'; const root = ReactDOM.createRoot(document.getElementById(&quot;root&quot;)); root.render( &lt;React.StrictMode&gt; &lt;Provider store={store}&gt; &lt;App /&gt; &lt;/Provider&gt; &lt;/React.StrictMode&gt; ); </code></pre> <p>If it's not possible to add new item to the list because of fake json server, what can I do to solve my problem? I thought about saving data from rtk query to local storage and then to operate on it, but I found some answers that's not possible.</p>
[ { "answer_id": 74249578, "author": "markerikson", "author_id": 62937, "author_profile": "https://Stackoverflow.com/users/62937", "pm_score": 2, "selected": true, "text": "jsonplaceholder" }, { "answer_id": 74253406, "author": "phry", "author_id": 2075944, "author_prof...
2022/10/29
[ "https://Stackoverflow.com/questions/74249488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7334225/" ]
74,249,542
<p><strong>I have two components &quot;search&quot; and &quot;Maindata&quot;. I am passing the input value from the search component to maindata component where I want to replace the city attribute with the input value(location) in API. but the browser display went blank and the console give an undefined 'city' error, etc. I got stuck in this problem if anyone has a solution?</strong></p> <p><strong>Here &quot;search&quot; component;</strong></p> <pre><code>import React , {useState} from &quot;react&quot;; import Maindata from &quot;./Maindata&quot;; import &quot;../Componentstyle/search.css&quot;; export default function Search() { const [location, setLocation] = useState(); &lt;Maindata city={location}/&gt; return ( &lt;div className=&quot;main&quot;&gt; &lt;nav className=&quot;istclass&quot;&gt; &lt;form className=&quot;form&quot;&gt; &lt;div className=&quot;search&quot;&gt; &lt;input value={location} placeholder=&quot;search city&quot; className=&quot;searchbox&quot; onChange={(e)=&gt;setLocation(e.target.value)} /&gt; &lt;button className=&quot;nd&quot; onClick={(e)=&gt;setLocation(e.target.value)}&gt; Submit &lt;/button&gt; &lt;/div&gt; &lt;/form&gt; &lt;/nav&gt; &lt;/div&gt; ); } </code></pre> <p><strong>Here &quot;Maindata&quot; component;</strong></p> <pre><code>import React, { useState, useEffect } from &quot;react&quot;; import &quot;../Componentstyle/Main.css&quot;; export default function Maindata(props) { const [data, setData] = useState(null); let city = console.log(props.city); let weather = async () =&gt; { const key = &quot;1ab6ef20384db1d7d9d205d609f7eef0&quot;; await fetch( `https://api.openweathermap.org/data/2.5/weather?q=${city}&amp;appid=${key}&amp;units=metric&amp;formatted=0` ) .then((response) =&gt; response.json()) .then((actualData) =&gt; setData(actualData)); }; useEffect(() =&gt; { weather(); }, []); if (!data) { return &lt;div&gt;Loading...&lt;/div&gt;; } const link = `http://openweathermap.org/img/w/${data.weather[0].icon}.png`; return ( &lt;div className=&quot;maindata&quot;&gt; &lt;div className=&quot;city&quot;&gt;{data.name}&lt;/div&gt; &lt;div className=&quot;temp&quot;&gt;{data.main.temp} C&lt;/div&gt; &lt;div className=&quot;icon&quot;&gt; &lt;img src={link} alt=&quot;not found&quot; /&gt;{&quot; &quot;} &lt;/div&gt; &lt;div className=&quot;feel&quot;&gt;feels Like {data.main.feels_like} C&lt;/div&gt; &lt;div className=&quot;wind&quot;&gt;Wind {data.wind.speed} Km/hr&lt;/div&gt; &lt;div className=&quot;cloudy&quot;&gt;{data.weather[0].main}&lt;/div&gt; &lt;div className=&quot;humidity&quot;&gt;humidity {data.main.humidity}%&lt;/div&gt; &lt;div className=&quot;sunrise&quot;&gt; sunrise :- {new Date(data.sys.sunrise * 1000).toUTCString()}{&quot; &quot;} &lt;/div&gt; &lt;div className=&quot;sunset&quot;&gt; sunset :- {new Date(data.sys.sunset * 1000).toUTCString()} &lt;/div&gt; &lt;/div&gt; ); } </code></pre>
[ { "answer_id": 74249578, "author": "markerikson", "author_id": 62937, "author_profile": "https://Stackoverflow.com/users/62937", "pm_score": 2, "selected": true, "text": "jsonplaceholder" }, { "answer_id": 74253406, "author": "phry", "author_id": 2075944, "author_prof...
2022/10/29
[ "https://Stackoverflow.com/questions/74249542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16762504/" ]
74,249,547
<p>I'm creating a booking reference for the user to download after successfully making a booking. It looks like this in the browser: <a href="https://i.stack.imgur.com/yFbhU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yFbhU.png" alt="enter image description here" /></a></p> <p>However, after using html2canvas to get a screenshot of the component in React, I get this: <a href="https://i.stack.imgur.com/uadhy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uadhy.png" alt="enter image description here" /></a></p> <p>I suspect the issue has to do with the fact that the static map's use is protected by an API key, causing issues to render the image in an external view.</p> <p>This is the callback that fires on hitting the share button, which for now just downloads the png (which is then converted to pdf using jsPDF):</p> <pre><code> const share = () =&gt; { const input = document.getElementById(&quot;trip-summary&quot;); if (input === null) return; html2canvas(input!).then((canvas) =&gt; { var image = canvas .toDataURL(&quot;image/png&quot;) .replace(&quot;image/png&quot;, &quot;image/octet-stream&quot;); const pdf = new jsPDF(); // @ts-ignore pdf.addImage(image, &quot;PNG&quot;, 0, 0); pdf.save(&quot;download.pdf&quot;); }); }; </code></pre>
[ { "answer_id": 74249608, "author": "kind user", "author_id": 6695924, "author_profile": "https://Stackoverflow.com/users/6695924", "pm_score": 2, "selected": true, "text": "allowTaint" }, { "answer_id": 74249674, "author": "AlePouroullis", "author_id": 14050808, "auth...
2022/10/29
[ "https://Stackoverflow.com/questions/74249547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14050808/" ]
74,249,550
<p>I have lambda function that is screwing up the pickling of an object. What makes it hard to debug is that it doesn't tell me the name of field causing this issue. I created a recursive function that tries to find such fields but it fails on the code I need it to work on (but succeeds in toy self contained cases).</p> <p>It works in this toy example:</p> <pre><code># %% &quot;&quot;&quot; trying to detect which field is the anonymous function giving me isse since: AttributeError: Can't pickle local object 'FullOmniglot.__init__.&lt;locals&gt;.&lt;lambda&gt;' doesn't tell me which one for some reason. &quot;&quot;&quot; import re from typing import Any, Callable, Union, Optional def _is_anonymous_function(f) -&gt; bool: &quot;&quot;&quot; Returns true if it's an anonynouys function. ref: https://stackoverflow.com/questions/3655842/how-can-i-test-whether-a-variable-holds-a-lambda &quot;&quot;&quot; return callable(f) and f.__name__ == &quot;&lt;lambda&gt;&quot; def _get_anonymous_function_attributes(anything, halt: bool = False, verbose: bool = False) -&gt; dict: &quot;&quot;&quot; Returns the dictionary of name of fields to anonymous functions in the past anything thing. :param anything: :param halt: :param verbose: :return: &quot;&quot;&quot; anons: dict = {} for field_name in dir(anything): field = getattr(anything, field_name) if _is_anonymous_function(field): if verbose: print(f'{field_name=}') print(f'{field=}') if halt: from pdb import set_trace as st st() anons[str(field_name)] = field return anons def _get_anonymous_function_attributes_recursive(anything: Any, path: str = '') -&gt; dict[str, Callable]: &quot;&quot;&quot;&quot;&quot;&quot; anons: dict = {} def __get_anonymous_function_attributes_recursive(anything: Any, path: Optional[str] = '', ) -&gt; None: if _is_anonymous_function(anything): # assert field is anything, f'Err not save thing/obj: \n{field=}\n{anything=}' # key: str = str(dict(obj=anything, field_name=field_name)) key: str = str(path) anons[key] = anything else: for field_name in dir(anything): # if field_name != '__abstractmethods__': if not bool(re.search(r'__(.+)__', field_name)): field = getattr(anything, field_name) # only recurse if new field is not itself if field is not anything: # avoids infinite recursions path_for_this_field = f'{path}.{field_name}' __get_anonymous_function_attributes_recursive(field, path_for_this_field) return __get_anonymous_function_attributes_recursive(anything, path) return anons class MyObj: def __init__(self): self.data = 'hi' self.anon = lambda x: x local_variable_me = 'my a local variable!' def non_anon(self, x): return x class MyObj2: def __init__(self): self.data = 'hi' self.anon = lambda x: x local_variable_me = 'my a local variable!' self.obj = MyObj() def non_anon(self, x): return x &quot;&quot;&quot; Trying to fix: AttributeError: Can't pickle local object 'FullOmniglot.__init__.&lt;locals&gt;.&lt;lambda&gt;' Trying to approximate with my obj and get: obj.__init__.&lt;locals&gt; to to get the obj.__ini__.&lt;locals&gt;.&lt;lambda&gt; &quot;&quot;&quot; top_obj = MyObj2() # print(f'anons recursive: {_get_anonymous_function_attributes_recursive(obj)=}') print('getting all anonymous functions recursively: ') anons: dict = _get_anonymous_function_attributes_recursive(top_obj, 'top_obj') print(f'{len(anons.keys())=}') for k, v in anons.items(): print() print(f'{k=}') print(f'{v=}') # print(k, v) print() </code></pre> <p>but fails in the wild pytorch code:</p> <pre><code># %% &quot;&quot;&quot; pip install torch pip install learn2learn &quot;&quot;&quot; print() import learn2learn from torch.utils.data import DataLoader omni = learn2learn.vision.benchmarks.get_tasksets('omniglot', root='~/data/l2l_data') loader = DataLoader(omni, num_workers=1) next(iter(loader)) print() </code></pre> <p>with error:</p> <pre><code>Traceback (most recent call last): File &quot;/Users/brandomiranda/opt/anaconda3/envs/meta_learning/lib/python3.9/multiprocessing/popen_spawn_posix.py&quot;, line 47, in _launch reduction.dump(process_obj, fp) File &quot;/Users/brandomiranda/opt/anaconda3/envs/meta_learning/lib/python3.9/multiprocessing/reduction.py&quot;, line 60, in dump ForkingPickler(file, protocol).dump(obj) AttributeError: Can't pickle local object 'FullOmniglot.__init__.&lt;locals&gt;.&lt;lambda&gt;' </code></pre> <p>Why does it fail there?</p> <hr /> <p>Full self contained reproducible code in one place:</p> <pre><code># %% &quot;&quot;&quot; trying to detect which field is the anonymous function giving me isse since: AttributeError: Can't pickle local object 'FullOmniglot.__init__.&lt;locals&gt;.&lt;lambda&gt;' doesn't tell me which one for some reason. &quot;&quot;&quot; import re from typing import Any, Callable, Union, Optional def _is_anonymous_function(f) -&gt; bool: &quot;&quot;&quot; Returns true if it's an anonynouys function. ref: https://stackoverflow.com/questions/3655842/how-can-i-test-whether-a-variable-holds-a-lambda &quot;&quot;&quot; return callable(f) and f.__name__ == &quot;&lt;lambda&gt;&quot; def _get_anonymous_function_attributes(anything, halt: bool = False, verbose: bool = False) -&gt; dict: &quot;&quot;&quot; Returns the dictionary of name of fields to anonymous functions in the past anything thing. :param anything: :param halt: :param verbose: :return: &quot;&quot;&quot; anons: dict = {} for field_name in dir(anything): field = getattr(anything, field_name) if _is_anonymous_function(field): if verbose: print(f'{field_name=}') print(f'{field=}') if halt: from pdb import set_trace as st st() anons[str(field_name)] = field return anons def _get_anonymous_function_attributes_recursive(anything: Any, path: str = '') -&gt; dict[str, Callable]: &quot;&quot;&quot;&quot;&quot;&quot; anons: dict = {} def __get_anonymous_function_attributes_recursive(anything: Any, path: Optional[str] = '', ) -&gt; None: if _is_anonymous_function(anything): # assert field is anything, f'Err not save thing/obj: \n{field=}\n{anything=}' # key: str = str(dict(obj=anything, field_name=field_name)) key: str = str(path) anons[key] = anything else: for field_name in dir(anything): # if field_name != '__abstractmethods__': if not bool(re.search(r'__(.+)__', field_name)): field = getattr(anything, field_name) # only recurse if new field is not itself if field is not anything: # avoids infinite recursions path_for_this_field = f'{path}.{field_name}' __get_anonymous_function_attributes_recursive(field, path_for_this_field) return __get_anonymous_function_attributes_recursive(anything, path) return anons class MyObj: def __init__(self): self.data = 'hi' self.anon = lambda x: x local_variable_me = 'my a local variable!' def non_anon(self, x): return x class MyObj2: def __init__(self): self.data = 'hi' self.anon = lambda x: x local_variable_me = 'my a local variable!' self.obj = MyObj() def non_anon(self, x): return x &quot;&quot;&quot; Trying to fix: AttributeError: Can't pickle local object 'FullOmniglot.__init__.&lt;locals&gt;.&lt;lambda&gt;' Trying to approximate with my obj and get: obj.__init__.&lt;locals&gt; to to get the obj.__ini__.&lt;locals&gt;.&lt;lambda&gt; &quot;&quot;&quot; top_obj = MyObj2() # print(f'anons recursive: {_get_anonymous_function_attributes_recursive(obj)=}') print('getting all anonymous functions recursively: ') anons: dict = _get_anonymous_function_attributes_recursive(top_obj, 'top_obj') print(f'{len(anons.keys())=}') for k, v in anons.items(): print() print(f'{k=}') print(f'{v=}') # print(k, v) print() # from uutils import get_anonymous_function_attributes_recursive # get_anonymous_function_attributes_recursive(top_obj, 'top_obj', print_output=True) # print() # %% &quot;&quot;&quot; pip install torch pip install learn2learn &quot;&quot;&quot; print() import learn2learn from torch.utils.data import DataLoader omni = learn2learn.vision.benchmarks.get_tasksets('omniglot', root='~/data/l2l_data') loader = DataLoader(omni, num_workers=1) next(iter(loader)) print() </code></pre> <hr /> <p>related:</p> <ul> <li><a href="https://stackoverflow.com/questions/58172877/error-involving-lambda-giving-code-function-main-locals-lambda-at-0x0000023">Error involving lambda giving code &lt;function main.&lt;locals&gt;.&lt;lambda&gt; at 0x00000234D43C68B8&gt;</a></li> <li><a href="https://stackoverflow.com/questions/58172877/error-involving-lambda-giving-code-function-main-locals-lambda-at-0x0000023/58173889?noredirect=1#comment131063992_58173889">Error involving lambda giving code &lt;function main.&lt;locals&gt;.&lt;lambda&gt; at 0x00000234D43C68B8&gt;</a></li> <li><a href="https://stackoverflow.com/questions/72339545/attributeerror-cant-pickle-local-object-locals-lambda">AttributeError: Can&#39;t pickle local object &#39;&lt;locals&gt;.&lt;lambda&gt;&#39;</a></li> <li><a href="https://stackoverflow.com/questions/4214936/how-can-i-get-the-values-of-the-locals-of-a-function-after-it-has-been-executed">How can I get the values of the locals of a function after it has been executed?</a></li> <li>l2l gitissue: <a href="https://github.com/learnables/learn2learn/issues/369" rel="nofollow noreferrer">https://github.com/learnables/learn2learn/issues/369</a></li> </ul>
[ { "answer_id": 74249608, "author": "kind user", "author_id": 6695924, "author_profile": "https://Stackoverflow.com/users/6695924", "pm_score": 2, "selected": true, "text": "allowTaint" }, { "answer_id": 74249674, "author": "AlePouroullis", "author_id": 14050808, "auth...
2022/10/29
[ "https://Stackoverflow.com/questions/74249550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1601580/" ]
74,249,563
<p>I have this JSON string that should be posted from JavaScript to the API:</p> <pre><code> &quot;model&quot;: &quot;kpi.availability&quot;, &quot;typeId&quot;: &quot;kpi.availability&quot;, &quot;name&quot;: &quot;Availability&quot;, &quot;description&quot;: &quot;&quot;, &quot;version&quot;: &quot;1.0.0&quot;, &quot;properties&quot;: { &quot;X&quot;: { &quot;dataType&quot;: &quot;string&quot;, &quot;value&quot;: &quot;&quot; }, &quot;Y&quot;: { &quot;dataType&quot;: &quot;number&quot;, &quot;value&quot;: 0, &quot;isMandatory&quot;: true }, &quot;Z&quot;: { &quot;dataType&quot;: &quot;number&quot;, &quot;value&quot;: 0, &quot;isMandatory&quot;: true } } </code></pre> <p>here we have 3 properties, just for instance, but it can be more than 3 with different names.</p> <p>And have this C# model which doesn't work</p> <pre><code>public class KPIType{ public string model { get; set; } public string typeId { get; set; } public string name { get; set; } public string description { get; set; } public int version { get; set; } public IDictionary&lt;string, PropertyItem&gt;[] properties { get; set; } //public List&lt;IDictionary&lt;string, PropertyItem&gt;&gt; properties { get; set; } //Didn't work } public class PropertyItem { public string dataType { get; set; } public string value { get; set; } public bool isMandatory { get; set; } } </code></pre> <p>But when trying to send it to the backend, it fails at the client side and I'm getting this error:</p> <blockquote> <p>&quot;The JSON value could not be converted to System.Collections.Generic.IDictionary`2[System.String,ABB.Advanced.Services.Management.Controllers.PropertyItem][]. Path: $.kpiType.properties | LineNumber: 0 | BytePositionInLine: 294.&quot;</p> </blockquote> <p><a href="https://i.stack.imgur.com/7IP0V.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7IP0V.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74249607, "author": "Paul de Champignon", "author_id": 11797381, "author_profile": "https://Stackoverflow.com/users/11797381", "pm_score": 1, "selected": false, "text": "{\n \"model\": \"kpi.availability\",\n \"typeId\": \"kpi.availability\",\n \"name\": \"Availability\...
2022/10/29
[ "https://Stackoverflow.com/questions/74249563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5345219/" ]
74,249,574
<p>We are given the main function and structures, asked to create two different linked lists. One being in ascending order and another in descending order and then joined together without changing their order. To give an example,if we have L1: 1-&gt;3-&gt;4-&gt;6 and L2: 9-&gt;8-&gt;5-&gt;2, The final list would be 1-&gt;9-&gt;3-&gt;8-&gt;4-&gt;5-&gt;6-&gt;2. This below is my work. I'm having some problems.</p> <p>This is the main function:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;malloc.h&gt; #include &quot;function.h&quot; struct nodeFB *startFB = NULL; struct nodeGS *startGS = NULL; struct newNodeFB *startNewFB = NULL; int main() { int id, age; scanf(&quot;%d&quot;, &amp;id); while(id!=-1) { scanf(&quot;%d&quot;, &amp;age); insertFB(&amp;startFB, id, age); scanf(&quot;%d&quot;, &amp;id); } scanf(&quot;%d&quot;, &amp;id); while(id!=-1) { insertGS(&amp;startGS, id); scanf(&quot;%d&quot;, &amp;id); } printFB(startFB); printGS(startGS); createFinalList(&amp;startNewFB,startFB,startGS); printAll(startNewFB); return 0; } </code></pre> <p>These are the given structures and the functions I've written:</p> <pre><code>#include &lt;string.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdbool.h&gt; #include &lt;stdio.h&gt; struct nodeFB { int id; int age; struct nodeFB *next; }; struct nodeGS { int id; struct nodeGS *next; }; struct newNodeFB { int id; int age; struct newNodeGS *next; }; struct newNodeGS { int id; struct newNodeFB *next; }; struct nodeFB *startFB; struct nodeGS *startGS; //functions struct nodeFB *insertFB( struct nodeFB **startFB, int id, int age) {//address of the first node in the linked list of FB struct nodeFB *newnode, *ptr; newnode = (struct nodeFB*)malloc(sizeof(struct nodeFB)); newnode-&gt;id = id; newnode-&gt;age = age; if (startFB == NULL) { newnode-&gt;next = NULL; *startFB = newnode; } else { ptr = *startFB; while(ptr-&gt;next!=NULL) { ptr=ptr-&gt;next; ptr-&gt;next= newnode; newnode-&gt;next = NULL; } } return *startFB; } void swap(struct nodeFB *a, struct nodeFB *b) {//function to swap two nodes int temp = a-&gt;id; a-&gt;id = b-&gt;id; b-&gt;id = temp; } void sortFB(struct nodeFB *startFB) { //function to bubble sort the given linked list int i; int swapped; struct nodeFB *ptr1; struct nodeFB *ptr2= NULL; if (startFB==NULL) { //checking for empty list return; } do { swapped = 0; ptr1=startFB; while (ptr1-&gt;next !=ptr2) { if (ptr1-&gt;id &gt; ptr1-&gt;next-&gt;id) { swap (ptr1, ptr1-&gt;next); swapped = 1; } ptr1= ptr2-&gt;next; } ptr2=ptr1; } while (swapped); } void printFB(struct nodeFB *startFB) { //function to display the sorted list struct nodeFB *ptr; ptr = startFB; sortFB(ptr); while(ptr != NULL) { printf(&quot;%d %d/n&quot;, ptr-&gt;id, ptr-&gt;age); ptr=ptr-&gt;next; } } struct nodeGS *insertGS(struct nodeGS **startGS, int id ) { struct nodeGS *newnode, *ptr; newnode = (struct nodeGS*)malloc(sizeof(struct nodeGS)); newnode-&gt;id = id; if (startGS == NULL) { newnode-&gt;next = NULL; *startGS = newnode; } else { ptr = *startGS; while(ptr-&gt;next!=NULL) { ptr=ptr-&gt;next; ptr-&gt;next= newnode; newnode-&gt;next = NULL; } } return *startGS; } void swapGS(struct nodeGS *c, struct nodeGS *d) {//function to swap two nodes int temp = c-&gt;id; c-&gt;id = d-&gt;id; d-&gt;id = temp; } void sortGS(struct nodeGS *startGS) { //function to bubble sort the given linked list int i; int swapped; struct nodeGS *ptr1; struct nodeGS *ptr2= NULL; if (startGS==NULL) { //checking for empty list return; } do { swapped = 0; ptr1=startGS; while (ptr1-&gt;next !=ptr2) { if (ptr1-&gt;id &lt; ptr1-&gt;next-&gt;id) { swapGS (ptr1, ptr1-&gt;next); swapped = 1; } ptr1= ptr2-&gt;next; } ptr2=ptr1; } while (swapped); } void printGS(struct nodeGS *startGS) { struct nodeGS *ptr; ptr = startGS; sortGS(startGS); while(ptr != NULL) { printf(&quot;%d/n&quot;, ptr-&gt;id); ptr = ptr-&gt;next; } } **struct newNodeFB *createFinalList(struct newNodeFB **startNewFB, struct nodeFB *startFB, struct nodeGS *startGS ) { struct newNodeFB *temp1, *ptr1; temp1=(struct newNodeFB*) malloc(sizeof(struct newNodeFB)); temp1-&gt;id= startFB-&gt;id; temp1-&gt;age=startFB-&gt;age; struct newNodeGS *temp2; temp2-&gt;id= startGS-&gt;id; struct newNodeFB *temp3 = NULL; struct newNodeGS *temp4 = NULL; while (temp1 != NULL &amp;&amp; temp2 != NULL) { ptr1=temp1; while (ptr1-&gt;next!=NULL) { ptr1=ptr1-&gt;next; ptr1-&gt;next= temp2; temp2-&gt;next=NULL; } temp3=temp1-&gt;next; temp4= temp2-&gt;next; temp1-&gt;next=temp2; temp2-&gt;next=temp3; temp1=temp3; temp2=temp4; } startGS = temp2; return startNewFB; }** void printALL(struct newNodeFB *startNewFB){ struct newNodeFB *ptr; ptr= startNewFB; while(ptr != NULL) { printf(&quot;%d %d/n%d&quot;, startNewFB-&gt;id, startNewFB-&gt;age, startNewFB-&gt;id); ptr=ptr-&gt;next; } } </code></pre>
[ { "answer_id": 74249741, "author": "Some programmer dude", "author_id": 440558, "author_profile": "https://Stackoverflow.com/users/440558", "pm_score": 1, "selected": false, "text": "Node *node1 = list1->head; // Node from first list\nNode *node2 = list2->head; // Node from second list...
2022/10/29
[ "https://Stackoverflow.com/questions/74249574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17006528/" ]
74,249,585
<p>First I think this is a complicated question to follow. Please see the Steps of my M code which I think will make it clearer.</p> <p>So I am trying to achieve the following:</p> <p><a href="https://i.stack.imgur.com/cgZpd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cgZpd.png" alt="enter image description here" /></a></p> <p>The idea is any text in the input box can be limited to relevant sections using the parameters table If the Text in the parameters box is Contained in the Text being searched. For me, at least the question is more complicated than it first appears. If required /interested Please see my explanation below:</p> <p><strong>Desired Output</strong> Fundamentally I want a way of filtering the Input text, using the parameters box such that each line returned is <strong>contained</strong> only within the relevant sections of start1-End1, Start2-End2.</p> <p>Ideally, you can use any part of the text to set the limits. So I could say Everything between SECTION1-2, and between lines 2 and 5. will returns lines 2-5.</p> <p>Or you could say Everything between SECTION 1-3, lines 4-8. Will return lines 4-8. Note you could even say SECTION1-3, Lines 4 -SECTION 4 which would return lines 4 up to 14.</p> <p>Finally you could even overlap sections and These should still be captured separately and the lines where overlap occurs should repeat in the output.</p> <p>M Code:</p> <p><strong>Parameters:</strong></p> <pre><code>let Source = Excel.CurrentWorkbook(){[Name=&quot;Parameters&quot;]}[Content], #&quot;Changed Type&quot; = Table.TransformColumnTypes(Source,{{&quot;Start1&quot;, type text}, {&quot;End1&quot;, type text}, {&quot;Start2&quot;, type text}, {&quot;End2&quot;, type text}}), #&quot;Filled Down&quot; = Table.FillDown(#&quot;Changed Type&quot;,{&quot;Start1&quot;, &quot;End1&quot;}), #&quot;Duplicated Column1&quot; = Table.DuplicateColumn(#&quot;Filled Down&quot;, &quot;Start1&quot;, &quot;Start1 - Copy&quot;), #&quot;Duplicated Column2&quot; = Table.DuplicateColumn(#&quot;Duplicated Column1&quot;, &quot;End1&quot;, &quot;End1 - Copy&quot;), #&quot;Duplicated Column3&quot; = Table.DuplicateColumn(#&quot;Duplicated Column2&quot;, &quot;Start2&quot;, &quot;Start2 - Copy&quot;), #&quot;Duplicated Column4&quot; = Table.DuplicateColumn(#&quot;Duplicated Column3&quot;, &quot;End2&quot;, &quot;End2 - Copy&quot;), #&quot;Added Custom&quot; = Table.AddColumn(#&quot;Duplicated Column4&quot;, &quot;Custom&quot;, each &quot;X&quot;), #&quot;Merged Columns&quot; = Table.CombineColumns(#&quot;Added Custom&quot;,{&quot;Start1&quot;, &quot;Custom&quot;},Combiner.CombineTextByDelimiter(&quot;+++&quot;, QuoteStyle.None),&quot;Start1&quot;), #&quot;Duplicated Column&quot; = Table.DuplicateColumn(#&quot;Merged Columns&quot;, &quot;End1&quot;, &quot;End1 - Copy.1&quot;), #&quot;Merged Columns3&quot; = Table.CombineColumns(#&quot;Duplicated Column&quot;,{&quot;Start1&quot;, &quot;End1&quot;},Combiner.CombineTextByDelimiter(&quot;,&quot;, QuoteStyle.None),&quot;Search1&quot;), #&quot;Added Custom1&quot; = Table.AddColumn(#&quot;Merged Columns3&quot;, &quot;Custom&quot;, each &quot;X&quot;), #&quot;Added Custom3&quot; = Table.AddColumn(#&quot;Added Custom1&quot;, &quot;Custom.1&quot;, each &quot;X&quot;), #&quot;Merged Columns1&quot; = Table.CombineColumns(#&quot;Added Custom3&quot;,{&quot;Start2&quot;, &quot;Custom&quot;},Combiner.CombineTextByDelimiter(&quot;+++&quot;, QuoteStyle.None),&quot;Start2&quot;), #&quot;Merged Columns4&quot; = Table.CombineColumns(#&quot;Merged Columns1&quot;,{&quot;End2&quot;, &quot;Custom.1&quot;},Combiner.CombineTextByDelimiter(&quot;+++&quot;, QuoteStyle.None),&quot;End2&quot;), #&quot;Merged Columns2&quot; = Table.CombineColumns(#&quot;Merged Columns4&quot;,{&quot;Start2&quot;, &quot;End2&quot;, &quot;End1 - Copy.1&quot;},Combiner.CombineTextByDelimiter(&quot;,&quot;, QuoteStyle.None),&quot;Search2&quot;), #&quot;Added Custom2&quot; = Table.AddColumn(#&quot;Merged Columns2&quot;, &quot;Custom&quot;, each Table.FromColumns({Text.Split([Search1], &quot;,&quot;), Text.Split([Search2], &quot;,&quot;)})), #&quot;Removed Other Columns&quot; = Table.SelectColumns(#&quot;Added Custom2&quot;,{&quot;Start1 - Copy&quot;, &quot;End1 - Copy&quot;,&quot;Start2 - Copy&quot;,&quot;End2 - Copy&quot;,&quot;Custom&quot;}), #&quot;Expanded Custom&quot; = Table.ExpandTableColumn(#&quot;Removed Other Columns&quot;, &quot;Custom&quot;, {&quot;Column1&quot;, &quot;Column2&quot;}, {&quot;Search1&quot;, &quot;Search2&quot;}), #&quot;Split Column by Delimiter&quot; = Table.SplitColumn(#&quot;Expanded Custom&quot;, &quot;Search1&quot;, Splitter.SplitTextByEachDelimiter({&quot;+++&quot;}, QuoteStyle.None, true), {&quot;Search1&quot;, &quot;Filter1&quot;}), #&quot;Split Column by Delimiter1&quot; = Table.SplitColumn(#&quot;Split Column by Delimiter&quot;, &quot;Search2&quot;, Splitter.SplitTextByEachDelimiter({&quot;+++&quot;}, QuoteStyle.None, true), {&quot;Search2&quot;, &quot;Filter2&quot;}), #&quot;Changed Type1&quot; = Table.TransformColumnTypes(#&quot;Split Column by Delimiter1&quot;,{{&quot;Search1&quot;, type text}, {&quot;Filter1&quot;, type text}, {&quot;Search2&quot;, type text}, {&quot;Filter2&quot;, type text}}), #&quot;Filled Down1&quot; = Table.FillDown(#&quot;Changed Type1&quot;,{&quot;Search1&quot;}), #&quot;Sorted Rows&quot; = Table.Sort(#&quot;Filled Down1&quot;,{{&quot;Filter1&quot;, Order.Ascending}}), #&quot;Replaced Value&quot; = Table.ReplaceValue(#&quot;Sorted Rows&quot;,null,&quot;&quot;,Replacer.ReplaceValue,{&quot;Filter1&quot;, &quot;Search2&quot;, &quot;Filter2&quot;}) in #&quot;Replaced Value&quot; </code></pre> <p><strong>Text:</strong></p> <pre><code>let Source = Excel.CurrentWorkbook(){[Name=&quot;TextToSearch&quot;]}[Content], #&quot;Changed Type&quot; = Table.TransformColumnTypes(Source,{{&quot;Text&quot;, type text}}), Search1 = Table.AddColumn(#&quot;Changed Type&quot;, &quot;Search1&quot;, (x) =&gt; Table.SelectRows(Parameters, each Text.Contains(x[Text],[Search1], Comparer.OrdinalIgnoreCase))), #&quot;Expanded Search1&quot; = Table.ExpandTableColumn(Search1, &quot;Search1&quot;, {&quot;Search1&quot;, &quot;Filter1&quot;}, {&quot;Search1&quot;, &quot;Filter1&quot;}), #&quot;Filled Down&quot; = Table.FillDown(#&quot;Expanded Search1&quot;,{&quot;Search1&quot;, &quot;Filter1&quot;}), #&quot;Filtered Rows&quot; = Table.SelectRows(#&quot;Filled Down&quot;, each ([Filter1] = &quot;X&quot;)), #&quot;Removed Other Columns&quot; = Table.SelectColumns(#&quot;Filtered Rows&quot;,{&quot;Text&quot;, &quot;Search1&quot;}), Search2 = Table.AddColumn(#&quot;Removed Other Columns&quot;, &quot;Search2&quot;, (x) =&gt; Table.SelectRows(Parameters, each Text.Contains(x[Search1],[Search1], Comparer.OrdinalIgnoreCase) and Text.Contains(x[Text],[Search2], Comparer.OrdinalIgnoreCase))), #&quot;Removed Other Columns1&quot; = Table.SelectColumns(Search2,{&quot;Text&quot;, &quot;Search2&quot;}), #&quot;Expanded Search2&quot; = Table.ExpandTableColumn(#&quot;Removed Other Columns1&quot;, &quot;Search2&quot;, {&quot;Start1 - Copy&quot;, &quot;End1 - Copy&quot;, &quot;Start2 - Copy&quot;, &quot;End2 - Copy&quot;, &quot;Search2&quot;, &quot;Filter2&quot;}, {&quot;Start1 - Copy&quot;, &quot;End1 - Copy&quot;, &quot;Start2 - Copy&quot;, &quot;End2 - Copy&quot;, &quot;Search2.1&quot;, &quot;Filter2&quot;}), #&quot;Filled Down1&quot; = Table.FillDown(#&quot;Expanded Search2&quot;,{&quot;Search2.1&quot;, &quot;Filter2&quot;}), #&quot;Filtered Rows1&quot; = Table.SelectRows(#&quot;Filled Down1&quot;, each ([Filter2] = &quot;X&quot;)), #&quot;Removed Other Columns2&quot; = Table.SelectColumns(#&quot;Filtered Rows1&quot;,{&quot;Start1 - Copy&quot;, &quot;End1 - Copy&quot;, &quot;Start2 - Copy&quot;, &quot;End2 - Copy&quot;, &quot;Text&quot;}), #&quot;Filled Down2&quot; = Table.FillDown(#&quot;Removed Other Columns2&quot;,{&quot;Start1 - Copy&quot;, &quot;End1 - Copy&quot;, &quot;Start2 - Copy&quot;, &quot;End2 - Copy&quot;, &quot;Text&quot;}), #&quot;Renamed Columns&quot; = Table.RenameColumns(#&quot;Filled Down2&quot;,{{&quot;Start1 - Copy&quot;, &quot;Start1&quot;}, {&quot;End1 - Copy&quot;, &quot;End1&quot;}, {&quot;Start2 - Copy&quot;, &quot;Start2&quot;}, {&quot;End2 - Copy&quot;, &quot;End2&quot;}}) in #&quot;Renamed Columns&quot; </code></pre> <p>Real Example:</p> <p><a href="https://1drv.ms/x/s!AsrLaUgt0KCLvUgQQctfMtFe057l?e=AkbeP3" rel="nofollow noreferrer">https://1drv.ms/x/s!AsrLaUgt0KCLvUgQQctfMtFe057l?e=AkbeP3</a></p>
[ { "answer_id": 74251655, "author": "David Bacci", "author_id": 18345037, "author_profile": "https://Stackoverflow.com/users/18345037", "pm_score": 2, "selected": false, "text": "let\n Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText(\"i45WCnZ1DvH091MwVNKBs42A7Jz...
2022/10/29
[ "https://Stackoverflow.com/questions/74249585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13562186/" ]
74,249,605
<p>I thought this would be something simple to do, but I don't think it's possible, why is that?</p> <p>This is what I'm trying to do.</p> <pre><code>console.log(&quot;hello&quot;) ? bool : &quot;&quot;; </code></pre> <p>This gives me an error: Expected an assignment or function call and instead saw an expression. Not sure exactly what that means.</p>
[ { "answer_id": 74249654, "author": "Patrick Kelly", "author_id": 20368669, "author_profile": "https://Stackoverflow.com/users/20368669", "pm_score": -1, "selected": false, "text": "const someBool = true;\nconsole.log(someBool?'hello':'goodbye');\n" }, { "answer_id": 74249676, ...
2022/10/29
[ "https://Stackoverflow.com/questions/74249605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
74,249,613
<p>I'm trying to have a function use the autokey cipher to encrypt a message. The function has an <code>if</code> statement telling it whether to use the uppercase ASCII letters or lower case. I do not understand why that <code>if</code> statement is not working. If the letter getting ciphered is lowercase, it should use the lowercase list, but that is not the case and it keeps using the upper case list to try to cipher it, which gives me an error since the letter is not an element in the list.</p> <pre><code>import string # This is the variable that will hold the list of the alphabet alphau = list(string.ascii_uppercase) alphal = list(string.ascii_lowercase) punctuation=list(string.punctuation) # This is the encryption function def encrypt(plaintext,key): enc = '' i = 0 for letter in plaintext: if letter == ' ': enc += ' ' elif letter =='\n': enc += '\n' else: if letter in alphal: x = (alphal.index(letter)+alphal.index(key[i]))%26 i += 1 enc += alphal[x] x = '' if letter in alphau: x = (alphau.index(letter)+alphau.index(key[i]))%26 i += 1 enc += alphau[x] x = '' if letter not in alphal or alphau: enc += letter return enc msg=encrypt(&quot;MyNameIsMhegazy&quot;,&quot;jMiXMyNameIsMahm&quot;) print(msg) </code></pre> <pre class="lang-py prettyprint-override"><code>Traceback (most recent call last): File &quot;c:\Users\User\Documents\GitHub\Coursework-1\encrypt.py&quot;, line 41, in &lt;module&gt; msg=encrypt(&quot;MyNameIsMahmoud&quot;,key1) File &quot;c:\Users\User\Documents\GitHub\Coursework-1\encrypt.py&quot;, line 25, in encrypt x = (alphau.index(letter)+alphau.index(key[i]))%26 ValueError: 'j' is not in list </code></pre> <p>I have tried using the lists in other <code>if</code> statements and they are working fine. Also tried putting strings and having a <code>for</code> loop separate upper from lower case letters using the lists and that has also worked fine. I am not sure what the problem is with the code posted above. Thanks For Your Help!</p>
[ { "answer_id": 74249681, "author": "Syed Hammad Ahmed", "author_id": 8724524, "author_profile": "https://Stackoverflow.com/users/8724524", "pm_score": 1, "selected": false, "text": "(alphau.index(letter)+alphau.index(key[i]))%26\n" }, { "answer_id": 74249691, "author": "Tim R...
2022/10/29
[ "https://Stackoverflow.com/questions/74249613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20368589/" ]
74,249,617
<p>So I'm a trying to create a function which first flips an unbiased coin but if the result is heads it flips a biased coin with 0.75 probability of heads. If it shows tails then the next flip is unbiased. I've tried the following code but I can only run this flow once i.e., if it's a head, then only the next one flip is biased and then the flow is returning to the top of the 'for' loop. Is there any recursion that I can do which can keep it inside the loop?</p> <pre><code>def prob1(): choices = [] for _ in range (1,501): x = random.choice(Toss_list) if x == 0: y = random.choices(Toss_list, weights=(0.75,0.25)) else: y = random.choices(Toss_list, weights=(1,1)) choices.append(x) choices.append(y) heads = choices.count([0])+choices.count(0) tails = choices.count([1])+choices.count(1) return print(f'Count of heads = {heads} and count of tails = {tails}' ) </code></pre>
[ { "answer_id": 74249641, "author": "Topepe", "author_id": 18223044, "author_profile": "https://Stackoverflow.com/users/18223044", "pm_score": 0, "selected": false, "text": "While True:\n#Do code here\n" }, { "answer_id": 74249702, "author": "Swifty", "author_id": 20267366...
2022/10/29
[ "https://Stackoverflow.com/questions/74249617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20368660/" ]
74,249,686
<p>I have this data frame.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>IQ</th> <th>sleep</th> <th>GRE</th> <th>happiness</th> </tr> </thead> <tbody> <tr> <td>105</td> <td>70</td> <td>200</td> <td>15</td> </tr> <tr> <td>40</td> <td>50</td> <td>150</td> <td>15</td> </tr> <tr> <td>70</td> <td>20</td> <td>70</td> <td>10</td> </tr> <tr> <td>150</td> <td>150</td> <td>80</td> <td>6</td> </tr> <tr> <td>148</td> <td>60</td> <td>900</td> <td>7</td> </tr> <tr> <td>115</td> <td>10</td> <td>1200</td> <td>40</td> </tr> <tr> <td>110</td> <td>90</td> <td>15</td> <td>5</td> </tr> <tr> <td>120</td> <td>40</td> <td>60</td> <td>12</td> </tr> <tr> <td>99</td> <td>30</td> <td>70</td> <td>15</td> </tr> <tr> <td>1000</td> <td>15</td> <td>30</td> <td>68</td> </tr> <tr> <td>70</td> <td>60</td> <td>12</td> <td>70</td> </tr> </tbody> </table> </div> <p>I would like to remove the outliers for each variable. I do not want to delete a whole row if one value is identified an outlier. For example, let's say the outlier for IQ is 40, I just want to delete 40, I don't want a whole row deleted.</p> <p>If I define any values that are &gt; mean * 3sd and &lt; mean - 3sd as outliers, what are the codes I can use to run it? <strong>If I can achieve this using Dplyr and subset, that would be great</strong></p> <p>I would expect something like this</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>IQ</th> <th>sleep</th> <th>GRE</th> <th>happiness</th> </tr> </thead> <tbody> <tr> <td>105</td> <td>70</td> <td>200</td> <td>15</td> </tr> <tr> <td></td> <td>50</td> <td>150</td> <td>15</td> </tr> <tr> <td>70</td> <td>20</td> <td>70</td> <td>10</td> </tr> <tr> <td>150</td> <td></td> <td>80</td> <td>6</td> </tr> <tr> <td>148</td> <td>60</td> <td>900</td> <td>7</td> </tr> <tr> <td>115</td> <td></td> <td>40</td> <td></td> </tr> <tr> <td>110</td> <td>90</td> <td></td> <td>5</td> </tr> <tr> <td>120</td> <td>40</td> <td>60</td> <td>12</td> </tr> <tr> <td>99</td> <td>30</td> <td>70</td> <td>15</td> </tr> <tr> <td></td> <td>15</td> <td>30</td> <td>68</td> </tr> <tr> <td>70</td> <td>60</td> <td>12</td> <td>70</td> </tr> </tbody> </table> </div> <p>I have tried the remove_sd_outlier code (from dataPreperation package) and it deleted an entire row of data. I do not want this.</p>
[ { "answer_id": 74249781, "author": "Seth", "author_id": 19316600, "author_profile": "https://Stackoverflow.com/users/19316600", "pm_score": 0, "selected": false, "text": "df %>%\n mutate(across(everything(),\n ~ ifelse(. > (mean(.) + 3*sd(.)),\n \"...
2022/10/30
[ "https://Stackoverflow.com/questions/74249686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20242571/" ]
74,249,703
<p>I am trying to trim (take difference of) a polygon by another polygon.</p> <p>I've created <code>SpatialPolygons</code> with the package <code>sp</code>, and I can use <code>rgeos::gDifference</code> (from <a href="https://gis.stackexchange.com/a/54146/171788">https://gis.stackexchange.com/a/54146/171788</a>) for a duplicated (but shifted) polygon, but it doesn't work for the polygon of the states from <code>ggplot2</code> (see below).</p> <pre><code>## Load data library(&quot;ggplot2&quot;) states &lt;- map_data(&quot;state&quot;) ## load state data states&lt;-states[states$region==&quot;washington&quot;|states$region==&quot;oregon&quot;|states$region==&quot;california&quot;,] ## trim to continental west coast ## load data for primary polygon WCG&lt;-structure(list(X = c(665004L, 665232L, 661983L, 663266L, 660980L, 666562L, 660979L, 659316L, 661115L, 665803L, 663685L, 666535L, 667728L, 660758L, 661000L, 665903L, 664469L, 659077L, 665725L ), Survey = c(&quot;WCGBTS&quot;, &quot;WCGBTS&quot;, &quot;WCGBTS&quot;, &quot;WCGBTS&quot;, &quot;WCGBTS&quot;, &quot;WCGBTS&quot;, &quot;WCGBTS&quot;, &quot;WCGBTS&quot;, &quot;WCGBTS&quot;, &quot;WCGBTS&quot;, &quot;WCGBTS&quot;, &quot;WCGBTS&quot;, &quot;WCGBTS&quot;, &quot;WCGBTS&quot;, &quot;WCGBTS&quot;, &quot;WCGBTS&quot;, &quot;WCGBTS&quot;, &quot;WCGBTS&quot;, &quot;WCGBTS&quot; ), Lat = c(33.07667, 32.91278, 32.70306, 32.57472, 32.0075, 31.99861, 32.01028, 32.28583, 32.38222, 32.81528, 40.13528, 40.25611, 48.07222, 48.175, 48.42278, 48.44444, 48.45083, 48.41556, 48.37028), Lon = c(-117.3383, -117.2867, -117.2897, -117.3006, -118.3397, -118.6144, -118.8803, -119.6567, -119.885, -120.2967, -125.07, -125.1383, -125.9614, -125.9075, -125.1892, -124.9861, -124.8464, -124.7778, -124.755 ), Date = c(&quot;7/15/2011&quot;, &quot;7/17/2012&quot;, &quot;7/17/2012&quot;, &quot;7/17/2015&quot;, &quot;7/14/2010&quot;, &quot;10/12/2016&quot;, &quot;7/14/2010&quot;, &quot;7/15/2007&quot;, &quot;10/13/2010&quot;, &quot;10/9/2017&quot;, &quot;6/22/2015&quot;, &quot;9/18/2016&quot;, &quot;5/29/2019&quot;, &quot;5/26/2010&quot;, &quot;8/24/2010&quot;, &quot;5/23/2017&quot;, &quot;5/29/2009&quot;, &quot;8/22/2007&quot;, &quot;8/25/2017&quot; )), row.names = c(478258L, 478486L, 475237L, 476520L, 474234L, 479816L, 474233L, 472570L, 474369L, 479057L, 476939L, 479789L, 480982L, 474012L, 474254L, 479157L, 477723L, 472331L, 478979L ), class = &quot;data.frame&quot;) </code></pre> <p>There is probably a simpler way to make polygons that can be subtracted from one another, but <code>sp::Polygon</code> doesn't work with <code>rgeos::gDifference</code>, so I convert to <code>SpatialPolygons</code></p> <pre><code>library(sp) WCGPoly&lt;-Polygon(as.matrix(cbind(WCG$Lon,WCG$Lat))) statesPoly&lt;-Polygon(as.matrix(cbind(states$long,states$lat))) crdref &lt;- CRS('+proj=longlat +datum=WGS84') p1 &lt;- SpatialPolygons(list(Polygons(list(WCGPoly), &quot;p1&quot;)),proj4string=crdref) p2 &lt;- SpatialPolygons(list(Polygons(list(statesPoly), &quot;p2&quot;)),proj4string=crdref) </code></pre> <p>To visualize the difference we are trying to keep:</p> <pre><code>plot(p1,col=&quot;red&quot;) plot(p2,add=T) </code></pre> <p><a href="https://i.stack.imgur.com/xvQSx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xvQSx.png" alt="enter image description here" /></a></p> <p>We want to keep the red that is off the west coast (not overlapped by the states).</p> <pre><code>library(&quot;rgeos&quot;) Real &lt;- gDifference(p1,p2) </code></pre> <p>Here I get a huge output, with errors:</p> <pre><code>p2 is invalid Input geom 1 is INVALID: Self-intersection at or near point -122.33795166 48.281641190312918 (-122.33795166000000165 48.2816411903129179) &lt;A&gt; ... Error in RGEOSBinTopoFunc(spgeom1, spgeom2, byid, id, drop_lower_td, unaryUnion_if_byid_false, : TopologyException: Input geom 1 is invalid: Self-intersection at -122.33795166 48.281641190312918 In addition: Warning messages: 1: In RGEOSUnaryPredFunc(spgeom, byid, &quot;rgeos_isvalid&quot;) : Self-intersection at or near point -122.33795166 48.281641190312918 2: In gDifference(p1, p2) : Invalid objects found; consider using set_RGEOS_CheckValidity(2L) </code></pre> <p>I am assuming this is because the state polygon isn't one cohesive polygon (state borders are intact somehow and lines intersect one another, even though I only fed Lat/Lon to <code>Polygon</code>.</p> <p>If I create a test polygon just by shifting the initial polygon it works:</p> <pre><code> testPoly&lt;-Polygon(as.matrix(cbind(WCG$Lon+1,WCG$Lat))) p3 &lt;- SpatialPolygons(list(Polygons(list(testPoly), &quot;p3&quot;)),proj4string=crdref) plot(p1,col=&quot;red&quot;) plot(p3,add=T) </code></pre> <p><a href="https://i.stack.imgur.com/If2nn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/If2nn.png" alt="enter image description here" /></a></p> <pre><code>Test &lt;- gDifference(p1,p3) plot(Test,col=&quot;red&quot;) </code></pre> <p><a href="https://i.stack.imgur.com/w84FL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/w84FL.png" alt="enter image description here" /></a></p> <p>I've tried combining the &quot;states&quot; polygon with various forms of &quot;union&quot; functions (<a href="https://gis.stackexchange.com/a/63696/171788">https://gis.stackexchange.com/a/63696/171788</a>, <a href="https://gis.stackexchange.com/a/385360/171788">https://gis.stackexchange.com/a/385360/171788</a>), but this doesn't really make sense to me because most examples are using two distinct polygons, not a polygon with multiple &quot;separated&quot; areas like these states.</p> <p>Trying this different answer (<a href="https://gis.stackexchange.com/a/169597/171788">https://gis.stackexchange.com/a/169597/171788</a>):</p> <pre><code>x&lt;- p1-p2 x&lt;- erase(p1,p2) </code></pre> <p>I get the following error:</p> <pre><code>x is invalid Attempting to make x valid by zero-width buffering Warning message: In RGEOSUnaryPredFunc(spgeom, byid, &quot;rgeos_isvalid&quot;) : Self-intersection at or near point -122.33795166 48.281641190312918 </code></pre> <p>Which again is telling me that my states polygon has a self-intersection. Is there a better way to trim my original polygon by the North American continent?</p> <p>I've posted another (related) question here (<a href="https://stackoverflow.com/q/74249819/9096420">How to use `polyclip::polysimplify` on a polygon</a>) to understand how I might get rid of this self-intersection and create a solid polygon.</p> <p>Any pointers would be greatly appreciated.</p>
[ { "answer_id": 74250064, "author": "Dylan_Gomes", "author_id": 9096420, "author_profile": "https://Stackoverflow.com/users/9096420", "pm_score": 0, "selected": false, "text": "ggplot2" }, { "answer_id": 74252529, "author": "dmflk", "author_id": 11709296, "author_profi...
2022/10/30
[ "https://Stackoverflow.com/questions/74249703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9096420/" ]
74,249,749
<p>I can't figure out how to use the tk calender ui to print if the year selected is a leap year or no.</p> <pre><code> from tkinter import* from tkcalendar import* root=Tk() root.title(&quot;Code project&quot;) selectedDate = Label(root, text=&quot;&quot;) def selectDate(): myDate =my_Cal.get_date() selectedDate.config(text=myDate) selectedDate.pack() my_Cal= Calendar(root, setmode = 'day', date_pattern = 'd/m/yy') my_Cal.pack() openCal = Button(root, text=&quot;Select Date&quot;, command=selectDate) openCal.pack() root.mainloop() </code></pre> <p>this is the code i have now and it outputs this:</p> <p><a href="https://i.stack.imgur.com/VcIoZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VcIoZ.png" alt="enter image description here" /></a> i want to know how to print if it is a leap year or not when the button is clicked</p>
[ { "answer_id": 74250064, "author": "Dylan_Gomes", "author_id": 9096420, "author_profile": "https://Stackoverflow.com/users/9096420", "pm_score": 0, "selected": false, "text": "ggplot2" }, { "answer_id": 74252529, "author": "dmflk", "author_id": 11709296, "author_profi...
2022/10/30
[ "https://Stackoverflow.com/questions/74249749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19283128/" ]
74,249,761
<p>I'm working on a C project, the goal is to reach a web server, read the data inside a file (example.com/shellcode.bin for example) and store it inside an array.</p> <p>Currently, I managed to make the necessary GET requests, i can find my shellcode, insert it into an array (mycode) but when I return it, it sends me the wrong size.</p> <p><strong>For example, if sizeof(mycode) return 270, sizeof(PE) return 8.</strong></p> <p><strong>Is it possible to find the total size of the PE variable ?</strong></p> <pre class="lang-c prettyprint-override"><code> size_t size = sizeof(mycode); char* PE = (char*)malloc(size); for (int i = 0; i &lt; sizeof(mycode); i++) { PE[i] = mycode[i]; } printf(&quot;Shellcode size before return : %ld\n&quot;, sizeof(PE)); return PE; </code></pre> <p>I tried different format string outputs (%s with strlen, %d, %ld, %zu ....) all of them returned 8.</p>
[ { "answer_id": 74250064, "author": "Dylan_Gomes", "author_id": 9096420, "author_profile": "https://Stackoverflow.com/users/9096420", "pm_score": 0, "selected": false, "text": "ggplot2" }, { "answer_id": 74252529, "author": "dmflk", "author_id": 11709296, "author_profi...
2022/10/30
[ "https://Stackoverflow.com/questions/74249761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18728275/" ]
74,249,764
<p>I want to script behavior when people insert event in my calendar. (e.g. when they add something into my &quot;focus time&quot;). I was able to connect an appscript &quot;trigger&quot; to call <code>onEventUpdate</code>. Sadly AppScript does not give you the event id for the event that was modified... (can you confirm the API does not offer this?).</p> <p>So I tried to fetch the &quot;last updated&quot; events instead:</p> <pre><code>function getOptions() { var now = new Date(); var yesterday = new Date(); yesterday.setDate(now.getDate() - 1); console.log(yesterday.toISOString()) return { updateMin: yesterday.toISOString(), maxResults: 2, orderBy: 'updated', singleEvents: true, showDeleted: false } } function onEventUpdate() { var options = getOptions(); var calendarId = Session.getActiveUser().getEmail(); // var calendar = CalendarApp.getCalendarById(calendarId); // console.log(calendar.getName()); var events = Calendar.Events.list(calendarId, options); if(!events.items) return for (var i = 0; i &lt; events.items.length; i++) { var event = events.items[i]; console.log(event.summary + &quot; @ &quot; + event.start['dateTime']); } } </code></pre> <p>Yet, I have just modified an event, but instead I am getting events from the past (i.e. August, 2mo ago...):</p> <pre><code>5:11:21 PM Notice Execution started 5:11:21 PM Info 2022-10-29T00:11:21.826Z 5:11:22 PM Info Old Meeting @ 2022-08-08T17:00:00-07:00 5:11:22 PM Info Old Meeting @ 2022-08-03T14:00:00-07:00 5:11:22 PM Notice Execution completed </code></pre> <p>Thoughts?</p>
[ { "answer_id": 74249901, "author": "Tanaike", "author_id": 7108653, "author_profile": "https://Stackoverflow.com/users/7108653", "pm_score": 1, "selected": false, "text": "orderBy" }, { "answer_id": 74266545, "author": "andrea", "author_id": 2202787, "author_profile":...
2022/10/30
[ "https://Stackoverflow.com/questions/74249764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2202787/" ]
74,249,793
<p>I want to sum the value of keys that are the same but in diffrent case.</p> <p>Let's say we have this array</p> <pre><code>&lt;?php $array = ['KEY'=&gt; 5, ,'TEST' =&gt; 3,'Test' =&gt; 10,'Key'=&gt; 2]; //--- a function to sum //--- print_r($array); /* ['KEY'] =&gt; 7, ['TEST'] =&gt; 13 */ ?&gt; </code></pre>
[ { "answer_id": 74249935, "author": "Jamie Sayers", "author_id": 7286012, "author_profile": "https://Stackoverflow.com/users/7286012", "pm_score": 1, "selected": false, "text": "foreach" }, { "answer_id": 74249936, "author": "kmoser", "author_id": 378779, "author_profi...
2022/10/30
[ "https://Stackoverflow.com/questions/74249793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16777309/" ]
74,249,808
<p>See for the invoice page I have BlocBuilder wrapped in a scaffold of statful page, inside that body under several widgets is a call to future void in seperate file call to create a dialog widget. And inside the dialog method is a call to create an invoice form which is in a seprate file and is stateful class displayed to be displayed on the dialog screen. In this form the user will be able to add and delete UI elements from a list view what I need to do is rebuild the widget either dialog screen/form or the list view/ to reflect the changes made by the user</p> <pre class="lang-dart prettyprint-override"><code>import 'package:flutter/material.dart'; import 'dart:developer' as dev; import 'package:track/src/features/invoices/application/bloc.dart'; import 'package:track/src/features/invoices/application/events.dart'; import 'package:track/src/features/invoices/application/pdf_invoice_api.dart'; class InvoiceForm extends StatefulWidget { final InvoiceBlocController blocController; const InvoiceForm(this.blocController, {Key? key}) : super(key: key); @override State&lt;InvoiceForm&gt; createState() =&gt; _InvoiceFormState(); } class _InvoiceFormState extends State&lt;InvoiceForm&gt; { final _formKey = GlobalKey&lt;FormState&gt;(); @override Widget build(BuildContext context) { return Form( key: _formKey, child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ TextFormField( controller: TextEditingController() ..text = widget.blocController.invoice.client, validator: (value) { value!.isEmpty ? 'Enter a value for client' : null; }, style: Theme.of(context).textTheme.labelMedium, decoration: InputDecoration( focusedBorder: const UnderlineInputBorder( borderSide: BorderSide( color: Colors.white, ), ), enabledBorder: const UnderlineInputBorder( borderSide: BorderSide( color: Colors.white, ), ), labelText: 'Client:', labelStyle: Theme.of(context).textTheme.labelMedium), ), TextFormField( controller: TextEditingController() ..text = '${widget.blocController.invoice.projectNumber}-${widget.blocController.invoice.invoiceNumber}', validator: (value) { value!.isEmpty ? 'Enter a valid project number' : null; }, style: Theme.of(context).textTheme.labelMedium, decoration: InputDecoration( focusedBorder: const UnderlineInputBorder( borderSide: BorderSide( color: Colors.white, ), ), enabledBorder: const UnderlineInputBorder( borderSide: BorderSide( color: Colors.white, ), ), labelText: 'Client:', labelStyle: Theme.of(context).textTheme.labelMedium), ), ListView.builder( shrinkWrap: true, itemCount: widget.blocController.invoice.items.length, itemBuilder: (context, index) { final item = widget.blocController.invoice.items[index]; return ListTile( contentPadding: EdgeInsets.zero, trailing: IconButton( onPressed: () { widget.blocController.add(DeleteItemFromInvoice(index)); }, icon: Icon(Icons.delete)), title: Column( children: [ Row( children: [ itemTextFormField( initialValue: item.name ?? '', labelText: 'name', index: index), SizedBox(width: 20), itemTextFormField( initialValue: item.description ?? '', labelText: 'description', index: index), ], ), Row( children: [ itemTextFormField( initialValue: item.quantity.toString(), labelText: 'quantity', index: index), SizedBox(width: 20), itemTextFormField( initialValue: item.costBeforeVAT.toString(), labelText: 'Cost Before VAT', index: index), ], ), SizedBox(height: 30), Divider( thickness: 2, color: Colors.black, ) ], ), ); }, ), Row( mainAxisAlignment: MainAxisAlignment.end, children: [ IconButton( onPressed: () { dev.log('button clicked to add new item'); widget.blocController.add(AddNewItemToInvoice()); }, icon: Icon(Icons.add)), IconButton( onPressed: () async { _formKey.currentState!.save(); Navigator.pop(context); await PdfInvoiceApi.generate(widget.blocController.invoice); }, icon: Icon(Icons.send)) ], ) ], ), ); } Expanded itemTextFormField({ required String initialValue, required String labelText, required int index, }) { return Expanded( child: TextFormField( controller: TextEditingController()..text = initialValue, onSaved: (newValue) { widget.blocController.add(UpdateInvoiceDetails(index)); }, style: Theme.of(context).textTheme.labelMedium, decoration: InputDecoration( focusedBorder: const UnderlineInputBorder( borderSide: BorderSide( color: Colors.white, ), ), enabledBorder: const UnderlineInputBorder( borderSide: BorderSide( color: Colors.white, ), ), labelText: labelText, labelStyle: Theme.of(context).textTheme.labelMedium, ), ), ); } } </code></pre> <p>InvoiceDialog Source code: <a href="https://pastebin.com/PCjmCWsk" rel="nofollow noreferrer">https://pastebin.com/PCjmCWsk</a> InvoiceDialog Source code: <a href="https://pastebin.com/VS5CG22D" rel="nofollow noreferrer">https://pastebin.com/VS5CG22D</a> <a href="https://i.stack.imgur.com/ciqDJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ciqDJ.png" alt="InvoiceDialog" /></a></p> <p>Edit 2: Made the follwoing changes to bloc per Mostafa answer as best I could, getting pressed against a deadline here so really need some help: These changes were to main page calling the show dialog passing bloc.</p> <pre class="lang-dart prettyprint-override"><code>showDialog( context: context, builder: (context) =&gt; BlocProvider.value( value: blocController, child: InvoiceDetailsDialog( screenWidth: screenWidth, screenHeight: screenHeight), ), ); </code></pre> <p>This file was the original place where showdialog was called and was custom Future return showDialog. Results: showDialog takes enitre screen. Rendering Invoice form reulsts in error being displayed in place of the form:</p> <pre class="lang-dart prettyprint-override"><code>No Material widget found. </code></pre> <p>Edit 3: fixed previous error but back where i started bloc is still being called succesfully but no changes to the ui:</p> <pre class="lang-dart prettyprint-override"><code>Widget build(BuildContext context) { final blocController = BlocProvider.of&lt;InvoiceBlocController&gt;(context); return Center( child: Material(color: Colors.red, borderRadius: BorderRadius.circular(50), child: SizedBox( width: screenWidth / 2, height: screenHeight / 2, child: Padding(padding: const EdgeInsets.all(20), child: Column(children: [ Expanded(child: ListView(children: [ Text('Invoices', style: Theme.of(context) .textTheme.bodyLarge?.copyWith(color: Colors.white)), InvoiceForm() ]))]))))); } </code></pre> <p>As form nothing changed except instead of passing the blocController through a method I am now calling it like:</p> <pre class="lang-dart prettyprint-override"><code>class _InvoiceFormState extends State&lt;InvoiceForm&gt; { final _formKey = GlobalKey&lt;FormState&gt;(); late final InvoiceBlocController blocController; @override void initState() { blocController = BlocProvider.of&lt;InvoiceBlocController&gt;(context); super.initState(); } </code></pre> <p>Still nothing changes.</p> <p>Edit 4: Set state does work and leaving in bloc code was excuting and if I clicked add two items would be added or delete would remove two items. But with setstate commented out it went back to not rebuilding. Using setstate for now but not preffered.</p> <p>Edit 5: Don't if thiss is still being paid attention to hopfully is. Can I keep add add events like: add(NewItem), add(deleteItem),add(GeneratePDF). Without changing state. currently I have done that once so far. Is this bad practice</p>
[ { "answer_id": 74249935, "author": "Jamie Sayers", "author_id": 7286012, "author_profile": "https://Stackoverflow.com/users/7286012", "pm_score": 1, "selected": false, "text": "foreach" }, { "answer_id": 74249936, "author": "kmoser", "author_id": 378779, "author_profi...
2022/10/30
[ "https://Stackoverflow.com/questions/74249808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11642462/" ]
74,249,811
<p>The clang-tidy static analyzer detects uses of variables after being moved.</p> <pre><code>class a_class { std::unique_ptr&lt;int&gt; p_; public: auto p() -&gt; auto&amp; {return p_;} void f() const {} }; int main() { auto aa = a_class{}; [[maybe_unused]] auto bb = std::move(aa); aa.f(); } </code></pre> <pre><code> error: Method called on moved-from object 'aa' [clang-analyzer-cplusplus.Move,-warnings-as-errors] </code></pre> <p><strong>This great!</strong> ©.</p> <p><strong>How can I make the <em>compiler</em>, clang or GCC detect the same issue too? Either by activating some warning option or by some (non-standard?) attribute?</strong></p> <p>I tried using <code>-Wmove</code> in clang and the <code>[[consumed]]</code> attribute but they didn't help. Perhaps I used them incorrectly.</p> <p>The code is here: <a href="https://godbolt.org/z/18hr4vn7x" rel="nofollow noreferrer">https://godbolt.org/z/18hr4vn7x</a> (the lower panel is clang-tidy and the mid panel on the right is the [empty] compiler output)</p> <p>Is there a chance a compiler will warn about this or it is just too costly for the compiler to check for this pattern?</p>
[ { "answer_id": 74250567, "author": "alfC", "author_id": 225186, "author_profile": "https://Stackoverflow.com/users/225186", "pm_score": 2, "selected": false, "text": "class [[clang::consumable(unconsumed)]] a_class {\n std::unique_ptr<int> p_;\n\npublic:\n [[clang::callable_when(un...
2022/10/30
[ "https://Stackoverflow.com/questions/74249811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225186/" ]
74,249,830
<p>I got a query &quot;top 3 employees in terms of total invoice value&quot; based on the following related tables:</p> <p><a href="https://i.stack.imgur.com/et9R9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/et9R9.png" alt="enter image description here" /></a></p> <pre><code> [{ &quot;customerid__supportrepid__id&quot;: 3, &quot;sells&quot;: 833.0400000000013 }, ...] </code></pre> <p>I would like the first filed to be: &quot;employee_id&quot; and a sells field value</p> <pre><code> class CustomerViewSet(viewsets.ReadOnlyModelViewSet): queryset = Customer.objects.all() serializer_class = CustomerSerializer @action(detail=False, methods=['get']) def top_three_employees(self, request): total_sells_by_employees = Invoice.objects \ .select_related('customerid') \ .select_related('customerid__supportrepid') \ .values('customerid__supportrepid__id') \ .annotate(sells=Sum('total')) \ .order_by('-sells') return Response(total_sells_by_employees) </code></pre>
[ { "answer_id": 74289811, "author": "Mohsin Maqsood", "author_id": 11561910, "author_profile": "https://Stackoverflow.com/users/11561910", "pm_score": 0, "selected": false, "text": "You can use .annotate() to create an aliased, transformed field, and then serialize that field:\nfrom djang...
2022/10/30
[ "https://Stackoverflow.com/questions/74249830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10245686/" ]
74,249,887
<p>Say I have these two lists (could be of different sizes):</p> <pre><code>const a = [0,1,3]; const b = [7,2,6,4]; </code></pre> <p>say I want to <em>swap</em> element <code>1</code> of <code>a</code>, with element <code>3</code> of <code>b</code>? what's the easiest way to do this?</p> <p>AKA, I am looking to do this:</p> <pre><code>swap(1, a, 3, b) =&gt; { a: [0,4,3], b: [7,2,6,1] } </code></pre>
[ { "answer_id": 74249906, "author": "Eric Fortis", "author_id": 529725, "author_profile": "https://Stackoverflow.com/users/529725", "pm_score": 3, "selected": true, "text": "function swap(i, a, j, b) {\n const t = a[i]\n a[i] = b[j]\n b[j] = t\n}\n" }, { "answer_id": 74249913, ...
2022/10/30
[ "https://Stackoverflow.com/questions/74249887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1223975/" ]
74,249,949
<p>This is my code to request data from API</p> <p>`</p> <pre><code>@app.route('/quote/{symbol}') def quote(symbol): response = c.get_quote(symbol) return response.json() </code></pre> <p>`</p> <p>This is my json response:</p> <blockquote> </blockquote> <pre><code>{&quot;SPY&quot;:{&quot;assetType&quot;:&quot;ETF&quot;,&quot;assetMainType&quot;:&quot;EQUITY&quot;,&quot;cusip&quot;:&quot;78462F103&quot;,&quot;assetSubType&quot;:&quot;ETF&quot;,&quot;symbol&quot;:&quot;SPY&quot;,&quot;description&quot;:&quot;SPDR S&amp;P 500&quot;,&quot;bidPrice&quot;:390.2,&quot;bidSize&quot;:300,&quot;bidId&quot;:&quot;P&quot;,&quot;askPrice&quot;:390.21,&quot;askSize&quot;:100,&quot;askId&quot;:&quot;P&quot;,&quot;lastPrice&quot;:389.02,&quot;lastSize&quot;:2528800,&quot;lastId&quot;:&quot;P&quot;,&quot;openPrice&quot;:379.87,&quot;highPrice&quot;:389.52,&quot;lowPrice&quot;:379.68,&quot;bidTick&quot;:&quot; &quot;,&quot;closePrice&quot;:389.02,&quot;netChange&quot;:0.0,&quot;totalVolume&quot;:100301958,&quot;quoteTimeInLong&quot;:1667001600168,&quot;tradeTimeInLong&quot;:1667001600004,&quot;mark&quot;:389.02,&quot;exchange&quot;:&quot;p&quot;,&quot;exchangeName&quot;:&quot;PACIFIC&quot;,&quot;marginable&quot;:true,&quot;shortable&quot;:true,&quot;volatility&quot;:0.0109,&quot;digits&quot;:2,&quot;52WkHigh&quot;:479.98,&quot;52WkLow&quot;:348.11,&quot;nAV&quot;:0.0,&quot;peRatio&quot;:0.0,&quot;divAmount&quot;:6.1757,&quot;divYield&quot;:1.59,&quot;divDate&quot;:&quot;2022-09-16 00:00:00.000&quot;,&quot;securityStatus&quot;:&quot;Normal&quot;,&quot;regularMarketLastPrice&quot;:389.02,&quot;regularMarketLastSize&quot;:30,&quot;regularMarketNetChange&quot;:0.0,&quot;regularMarketTradeTimeInLong&quot;:1667001600004,&quot;netPercentChangeInDouble&quot;:0.0,&quot;markChangeInDouble&quot;:0.0,&quot;markPercentChangeInDouble&quot;:0.0,&quot;regularMarketPercentChangeInDouble&quot;:0.0,&quot;delayed&quot;:false,&quot;realtimeEntitled&quot;:true}} </code></pre> <blockquote> </blockquote> <p>How do I get the response to only be a specific part of the body like &quot;lastPrice&quot;?</p> <p>I'm a mewbie so I have searched for a solution but cant find anything that works yet.</p>
[ { "answer_id": 74250038, "author": "Brad", "author_id": 362536, "author_profile": "https://Stackoverflow.com/users/362536", "pm_score": 1, "selected": false, "text": "data" }, { "answer_id": 74250053, "author": "Rafael de Souza Costa", "author_id": 18456797, "author_p...
2022/10/30
[ "https://Stackoverflow.com/questions/74249949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20368921/" ]
74,249,969
<p>I have a bunch of targets that are built with the same type of make rule:</p> <pre><code> env GOARCH=amd64 GOOS=linux go build -ldflags=&quot;-s -w&quot; -o bin/foo foo/*.go env GOARCH=amd64 GOOS=linux go build -ldflags=&quot;-s -w&quot; -o bin/bar bar/*.go env GOARCH=amd64 GOOS=linux go build -ldflags=&quot;-s -w&quot; -o bin/hello hello/*.go env GOARCH=amd64 GOOS=linux go build -ldflags=&quot;-s -w&quot; -o bin/world world/*.go </code></pre> <p>and I was trying to write one generic rule, based on</p> <ul> <li><a href="https://stackoverflow.com/questions/15718653/makefile-pattern-rule-for-no-extension">Makefile pattern rule for no extension?</a></li> <li><a href="https://stackoverflow.com/questions/1932904/make-wildcard-subdirectory-targets">make wildcard subdirectory targets</a></li> </ul> <p>Here is what I come up so far (but not working):</p> <pre><code>DIRS =$(filter %/, $(wildcard */)) build: $(DIRS) export GO111MODULE=on bin/%: %/$(wildcard *.go) env GOARCH=amd64 GOOS=linux go build -ldflags=&quot;-s -w&quot; -o bin/$@ $@/*.go </code></pre>
[ { "answer_id": 74250038, "author": "Brad", "author_id": 362536, "author_profile": "https://Stackoverflow.com/users/362536", "pm_score": 1, "selected": false, "text": "data" }, { "answer_id": 74250053, "author": "Rafael de Souza Costa", "author_id": 18456797, "author_p...
2022/10/30
[ "https://Stackoverflow.com/questions/74249969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2125837/" ]
74,249,995
<p>Very new to coding. I have 2 tables, zips_usa which includes all properly formatted zips (zipcode, lat / lon / city / state etc) in the US, and table ageus which includes columns such as first name, last name, category, comments. It took 3 weeks to write the zipcode radius search but I got there, mainly due to answers I found on this site. Thanks. I now need help dealing with the output. I think I need a join statement between the tables and cannot get my head around the logic. Any help would be appreciated.</p> <p>sql statement for zip radius search runs error free. Input is performed by a html form.</p> <pre><code> $sql = &quot;SELECT latitude, longitude FROM zips_usa WHERE zipcode = '$zipcode'&quot;; </code></pre> <p>Table ageus column details (where users post to)</p> <p>id first_name last_name dog_type comments city state entered gender category zipcode</p> <p>How do I join the two tables so I can select output that includes all info from table ageus that includes zip codes found within the X mile radius?</p>
[ { "answer_id": 74250545, "author": "Misunderstood", "author_id": 3813605, "author_profile": "https://Stackoverflow.com/users/3813605", "pm_score": 0, "selected": false, "text": "$sql = \"SELECT `lat`,`lng` FROM `zipLocation` WHERE `zip` = $zip \";\n$results = mysqli_query($link,$sql);\nl...
2022/10/30
[ "https://Stackoverflow.com/questions/74249995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19605491/" ]
74,250,028
<p>I have this .txt file that I wanted to split, strip then save the content to a dictionary</p> <pre class="lang-none prettyprint-override"><code>Jon, ID1, 30.0, ID2, 35.4, ID3, 478.5 Paige, ID1, 15.8, ID3, 723.5, ID4, 250, ID6, 66.2 Jil, ID1, 46.2, ID2, 37.7, ID3, 68.4, ID4, 40, ID5, 22 Jig5, ID1, 90.5, ID2, 69.4, ID6, 35.8 Kit4, ID3, 700.2, ID4, 260, ID5, 96 </code></pre> <p>I wanted to achieve an output that is similar to this</p> <pre><code>Jon {ID1: 30.0, ID2: 35.4, ID3: 478.5} Paige {ID1: 15.8, ID3: 723.5, ID4: 250, ID6: 66.2} Jil {ID1: 46.2, ID2: 37.7, ID3: 68.4, ID4: 40, ID5: 22} Jig5 {ID1: 90.5, ID2: 69.4, ID6: 35.8 Kit4 {ID3: 700.2, ID4: 260, ID5: 96} </code></pre> <p>I have tried:</p> <pre><code>output = {} with open(&quot;records.txt&quot;, &quot;r&quot;) as f_in: for line in f_in: names = line[0].strip() usage = usage[1::2].strip() if usage == &quot;&quot;: continue ID, SCORE = usage.split(&quot;,&quot;) output[state] = capital print(output) </code></pre>
[ { "answer_id": 74250545, "author": "Misunderstood", "author_id": 3813605, "author_profile": "https://Stackoverflow.com/users/3813605", "pm_score": 0, "selected": false, "text": "$sql = \"SELECT `lat`,`lng` FROM `zipLocation` WHERE `zip` = $zip \";\n$results = mysqli_query($link,$sql);\nl...
2022/10/30
[ "https://Stackoverflow.com/questions/74250028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20368957/" ]
74,250,054
<pre class="lang-py prettyprint-override"><code>keep_playing = &quot;yes&quot; print(&quot;I can write and help you to study. What am I?&quot;) print(&quot; &quot;) guesses = 1 guess = input(&quot;What is your guess? &quot;) while keep_playing == &quot;yes&quot;: secret_word = &quot;pen&quot; while guess.lower() != secret_word: print(&quot;Sorry, that's the wrong answer.&quot;) guess = input(&quot;What is your guess?: &quot;) guesses = guesses + 1 if guess.lower()== secret_word : print(&quot;Congratulations! , You guessed it&quot;) print(f&quot;It took you {guesses} guesses&quot;) keep_playing = input(&quot;Would you like to play again (yes/no)? &quot;) print(&quot;See you next time! Thanks for playing.&quot;) </code></pre> <p>At the end of the game, when I responded with <code>YES</code>, It doesn't loop back to the beginning of the game. Still pretty new to this. May I know what the problem is?</p> <p>I expect the game to loop to the beginning when the player type <code>YES</code>.</p>
[ { "answer_id": 74250545, "author": "Misunderstood", "author_id": 3813605, "author_profile": "https://Stackoverflow.com/users/3813605", "pm_score": 0, "selected": false, "text": "$sql = \"SELECT `lat`,`lng` FROM `zipLocation` WHERE `zip` = $zip \";\n$results = mysqli_query($link,$sql);\nl...
2022/10/30
[ "https://Stackoverflow.com/questions/74250054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20369030/" ]
74,250,078
<p>I am trying to program a short story line as part of my scripting class, but I have been getting a weird result.</p> <p>Work so far:</p> <p>Values</p> <pre class="lang-py prettyprint-override"><code>first_name = input ('Nick') generic_location = input ('Costco') whole_number = input ('12') plural_noun = input ('donuts') print(first_name, 'went to', generic_location, 'to buy', whole_number, 'different types of', plural_noun) </code></pre> <p>What end result SHOULD be: Nick went to Costco to buy 12 different types ofdonuts.</p> <p>Actual result: NickCostco12donutsNick went to Costco to buy 12 different types of donuts.</p> <p>Where did I go wrong?</p>
[ { "answer_id": 74250545, "author": "Misunderstood", "author_id": 3813605, "author_profile": "https://Stackoverflow.com/users/3813605", "pm_score": 0, "selected": false, "text": "$sql = \"SELECT `lat`,`lng` FROM `zipLocation` WHERE `zip` = $zip \";\n$results = mysqli_query($link,$sql);\nl...
2022/10/30
[ "https://Stackoverflow.com/questions/74250078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20368403/" ]
74,250,107
<p>My code obtains certain paragraphs from a textbook. I would like the code to spit out several versions of this paragraph using some sort of paraphrasing tool, automatically. The code is written mostly in Python, but also uses Js (and Ts) for certain aspects.</p> <p>I tried implementing several completed models, including; (python) Pytorch, parrot, scpn, and others, but it quickly became too complicated for me. Can someone help me write a better way, or help me use an already made model? Thank you &lt;3</p>
[ { "answer_id": 74250545, "author": "Misunderstood", "author_id": 3813605, "author_profile": "https://Stackoverflow.com/users/3813605", "pm_score": 0, "selected": false, "text": "$sql = \"SELECT `lat`,`lng` FROM `zipLocation` WHERE `zip` = $zip \";\n$results = mysqli_query($link,$sql);\nl...
2022/10/30
[ "https://Stackoverflow.com/questions/74250107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20369057/" ]
74,250,115
<p>When I add or edit a customer in Customer table, it does not appear in customer filed of Sales table, so I have to destroy the window and open it again manually or with refresh button. The refresh button also work 1 time, means when I add or edit another customer in Customer table, then click the refresh button just the window destroy. How to solve this problem without a refresh button means when I add or edit a customer in Customer table Immediately appear in customer filed of Sales table?</p> <p>I add a customer name in Entry widget but it does not appear in Combobox</p> <pre><code>widget of tkinter. from tkinter import * from tkinter import ttk from tkinter import messagebox import mysql.connector root = Tk() root.title('Car Store') root.geometry('1600x860') # Customer Functions def update(rows): trv.delete(*trv.get_children()) for dt in rows: trv.insert('', 'end', values=dt) def get_row(event): item = trv.item(trv.focus()) id_var.set(item['values'][0]) name_var.set(item['values'][1]) f_name_var.set(item['values'][2]) last_name_var.set(item['values'][3]) tazkera_no_var.set(item['values'][4]) address_var.set(item['values'][5]) mobile_no_var.set(item['values'][6]) def clean_data_list(): ent_id.delete(0, END) ent_name.delete(0, END) ent_f_name.delete(0, END) ent_last_name.delete(0, END) ent_tazkera_no.delete(0, END) ent_address.delete(0, END) ent_mobile_no.delete(0, END) def add_customer(): if ent_name.get() == '': messagebox.showerror('Error!', 'Customer Name Field is required') else: con = mysql.connector.connect(user='nesarahmad', password='1114WE', host='127.0.0.1', database='carstore') my_cursor = con.cursor() query = 'USE carstore' my_cursor.execute(query) query = 'SELECT * FROM customer WHERE tazkera_num = %s' my_cursor.execute(query, (tazkera_no_var.get(),)) row = my_cursor.fetchone() if row != None: messagebox.showerror( 'Error!', 'Tazkera Number is Already exists, Try Another Tazkera Number') else: query = &quot;INSERT INTO customer VALUES(%s, %s, %s, %s, %s, %s, %s)&quot; values = ('null', name_var.get(), f_name_var.get(), last_name_var.get( ), tazkera_no_var.get(), address_var.get(), mobile_no_var.get()) my_cursor.execute(query, values) con.commit() clear() con.close() clean_data_list() def edit_customer(): if messagebox.askyesno('Confirm Edit?', 'Are you shure you want to Edit this Customer'): con = mysql.connector.connect(user='nesarahmad', password='1114WE', host='127.0.0.1', database='carstore') my_cursor = con.cursor() customer_id = id_var.get() query = &quot;UPDATE customer SET name=%s, f_name=%s, last_name=%s, tazkera_num=%s, address=%s, mobile_num=%s WHERE id=&quot; + customer_id values = (name_var.get(), f_name_var.get(), last_name_var.get( ), tazkera_no_var.get(), address_var.get(), mobile_no_var.get()) my_cursor.execute(query, values) con.commit() clear() con.close() clean_data_list() else: return True # Sales Functions def update_sales_list(rows): trv_sales.delete(*trv_sales.get_children()) for dt in rows: trv_sales.insert('', 'end', values=dt) def sales_get_row(event): item = trv_sales.item(trv_sales.focus()) id_var_sales.set(item['values'][0]) cb_car_id.set(str(item['values'][1]) + '-' + item['values'][3]) cb_customer_id.set(str(item['values'][2]) + '-' + item['values'][4]) qty_var_sales.set(item['values'][5]) sales_price_var_sales.set(item['values'][6]) def sales_clean_data_list(): ent_id_sales.delete(0, END) cb_car_id_sales.set('') cb_customer_id_sales.set('') ent_qty_sales.delete(0, END) ent_sales_price_sales.delete(0, END) def add_sales(): if cb_car_id_sales.get() == '' or cb_customer_id_sales.get() == '' or ent_qty_sales.get() == '' or ent_sales_price_sales.get() == '': messagebox.showerror('Error!', 'All Fields are required') elif int(ent_qty_sales.get()) &lt; 1 or int(ent_qty_sales.get()) &gt; 1: messagebox.showerror('Error!', 'QTY must be 1') else: con = mysql.connector.connect(user='nesarahmad', password='1114WE', host='127.0.0.1', database='carstore') my_cursor = con.cursor() query = 'USE carstore' my_cursor.execute(query) query = &quot;SELECT * FROM sales WHERE car_id = %s&quot; my_cursor.execute(query, (cb_car_id.get().split('-')[0],)) car_id = my_cursor.fetchone() if car_id != None: messagebox.showerror( 'Error!', 'This car already solde, try another car') else: query = &quot;SELECT COUNT(QTY) FROM car_inventory WHERE car_id = %s&quot; my_cursor.execute(query, (cb_car_id.get().split('-')[0],)) qty_car_inventory_check = my_cursor.fetchone() # print(qty_car_inventory_check) if qty_car_inventory_check[0] == 1: query = &quot;INSERT INTO sales VALUES(%s, %s, %s, %s, %s)&quot; values = ( 'null', cb_car_id.get().split('-')[0], cb_customer_id.get().split('-')[0], qty_var_sales.get(), sales_price_var_sales.get() ) my_cursor.execute(query, values) # Update the QTY in Car Inventory query = &quot;UPDATE car_inventory SET QTY = QTY - 1 WHERE car_id = %s&quot; my_cursor.execute(query, (cb_car_id.get().split('-')[0],)) con.commit() clear_sales() clear_car_inventory() con.close() sales_clean_data_list() else: messagebox.showerror( '!Errot', 'There is no This Car in Car Inventory, Chose the Other Car') def edit_sales(): if messagebox.askyesno('Confirm Edit?', 'Are you shure you want to Edit this Sales'): if ent_qty_sales.get() == '' or ent_sales_price_sales.get() == '': messagebox.showerror('Error!', 'All Fields are required') elif int(ent_qty_sales.get()) &lt; 1 or int(ent_qty_sales.get()) &gt; 1: messagebox.showerror('Error!', 'QTY must be 1') else: con = mysql.connector.connect(user='nesarahmad', password='1114WE', host='127.0.0.1', database='carstore') my_cursor = con.cursor() id_sales = id_var_sales.get() query = &quot;UPDATE sales SET car_id=%s, customer_id=%s, QTY=%s, sales_price=%s WHERE id=&quot; + id_sales values = ( cb_car_id.get(), cb_customer_id.get(), qty_var_sales.get(), sales_price_var_sales.get(), ) my_cursor.execute(query, values) con.commit() clear_sales() con.close() sales_clean_data_list() else: return True def refresh(): root.destroy() import CARSTORE nb = ttk.Notebook(root) frm_customer = Frame(nb, bg='firebrick1') frm_wrapper1 = LabelFrame(frm_customer, text='Cusotmer List', pady=30) frm_wrapper1.pack(fill='both', expand='yes', padx=40, pady=10) frm_wrapper3 = LabelFrame(frm_customer, text='Customer Data', pady=30) frm_wrapper3.pack(fill='both', expand='yes', padx=40, pady=(10, 50)) trv = ttk.Treeview(frm_wrapper1, selectmode='browse', columns=( 1, 2, 3, 4, 5, 6, 7), show='headings') trv.pack() trv.heading(1, text='Customer ID') trv.heading(2, text='Name') trv.heading(3, text=&quot;Fateher's Name&quot;) trv.heading(4, text='Last Name') trv.heading(5, text='Tazkera no') trv.heading(6, text='Address') trv.heading(7, text='Mobile no') # Hide Customer ID column trv.column(1, stretch=NO, minwidth=0, width=0) trv.bind('&lt;Double 1&gt;', get_row) con = mysql.connector.connect(user='nesarahmad', password='1114WE', host='127.0.0.1', database='carstore') my_cursor = con.cursor() query = 'USE carstore' my_cursor.execute(query) try: query = 'create table customer(id int auto_increment primary key, name varchar(50) not null, f_name varchar(50), last_name varchar(50), tazkera_num varchar(50) unique, address varchar(200), mobile_num varchar(13))' my_cursor.execute(query) except: print('Same Tabel(s) exist.') query = 'SELECT * FROM customer' my_cursor.execute(query) rows = my_cursor.fetchall() update(rows) con.close() # Customer Data section id_var = StringVar() name_var = StringVar() f_name_var = StringVar() last_name_var = StringVar() tazkera_no_var = StringVar() address_var = StringVar() mobile_no_var = StringVar() lbl_id = Label(frm_wrapper3, text='Cutomer ID') lbl_id.grid(row=0, column=0, sticky='w') ent_id = Entry(frm_wrapper3, textvariable=id_var) ent_id.grid(row=0, column=1) # Hide the following 2 Label and Entry lbl_id.grid_forget() ent_id.grid_forget() lbl_name = Label(frm_wrapper3, text='Name') lbl_name.grid(row=1, column=0, sticky='w') ent_name = Entry(frm_wrapper3, textvariable=name_var) ent_name.grid(row=1, column=1) lbl_f_name = Label(frm_wrapper3, text=&quot;Father's Name&quot;) lbl_f_name.grid(row=2, column=0, sticky='w') ent_f_name = Entry(frm_wrapper3, textvariable=f_name_var) ent_f_name.grid(row=2, column=1) lbl_last_name = Label(frm_wrapper3, text=&quot;Last Name&quot;) lbl_last_name.grid(row=3, column=0, sticky='w') ent_last_name = Entry(frm_wrapper3, textvariable=last_name_var) ent_last_name.grid(row=3, column=1) lbl_tazkera_no = Label(frm_wrapper3, text=&quot;Tazkera no&quot;) lbl_tazkera_no.grid(row=4, column=0, sticky='w') ent_tazkera_no = Entry(frm_wrapper3, textvariable=tazkera_no_var) ent_tazkera_no.grid(row=4, column=1) lbl_address = Label(frm_wrapper3, text=&quot;Address&quot;) lbl_address.grid(row=5, column=0, sticky='w') ent_address = Entry(frm_wrapper3, textvariable=address_var) ent_address.grid(row=5, column=1) lbl_mobile_no = Label(frm_wrapper3, text=&quot;Mobile no&quot;) lbl_mobile_no.grid(row=6, column=0, sticky='w') ent_mobile_no = Entry(frm_wrapper3, textvariable=mobile_no_var) ent_mobile_no.grid(row=6, column=1) btn_add_customer = Button( frm_wrapper3, text='Add Customer', width=15, bg='green', fg='white', activebackground='green', activeforeground='white', command=add_customer) btn_add_customer.grid(row=7, column=0, pady=30) btn_edit_customer = Button( frm_wrapper3, text='Edit Customer', width=15, bg='blue', fg='white', activebackground='blue', activeforeground='white', command=edit_customer) btn_edit_customer.grid(row=7, column=1, pady=30) frm_customer.pack(fill='both', expand='yes') # End of Customer section # Sales Section frm_sales = Frame(nb, bg='firebrick1') frm_sales_list = LabelFrame( frm_sales, text='Sales List', pady=30) frm_sales_list.pack(fill='both', expand='yes', padx=40, pady=10) frm_sales_data = LabelFrame( frm_sales, text='Sales Data', pady=30) frm_sales_data.pack(fill='both', expand='yes', padx=40, pady=(10, 50)) trv_sales = ttk.Treeview(frm_sales_list, selectmode='browse', columns=( 1, 2, 3, 4, 5, 6, 7), show='headings') trv_sales.pack() trv_sales.heading(1, text='Sales ID') trv_sales.heading(2, text='Car ID') trv_sales.heading(3, text=&quot;Customer ID&quot;) trv_sales.heading(4, text=&quot;Car&quot;) trv_sales.heading(5, text=&quot;Customer&quot;) trv_sales.heading(6, text='QTY') trv_sales.heading(7, text='Sales Price') # Hide Sales ID, Car ID and Customer ID columns trv_sales.column(1, stretch=NO, minwidth=0, width=0) trv_sales.column(2, stretch=NO, minwidth=0, width=0) trv_sales.column(3, stretch=NO, minwidth=0, width=0) trv_sales.column(4, stretch=NO, minwidth=0, width=0) trv_sales.bind('&lt;Double 1&gt;', sales_get_row) con = mysql.connector.connect(user='nesarahmad', password='1114WE', host='127.0.0.1', database='carstore') my_cursor = con.cursor() query = 'USE carstore' my_cursor.execute(query) try: query = 'CREATE TABLE sales(id int auto_increment primary key, car_id int NOT NULL UNIQUE, customer_id int, QTY int NOT NULL, sales_price decimal NOT NULL, FOREIGN KEY (car_id) REFERENCES car_inventory(car_id) ON DELETE CASCADE ON UPDATE CASCADE, FOREIGN KEY (customer_id) REFERENCES customer(id) ON DELETE CASCADE ON UPDATE CASCADE)' my_cursor.execute(query) except: print('Same Tabel(s) exist.') query = 'SELECT sales.id, car_inventory.car_id, customer.id, car_inventory.car_name, customer.name, sales.QTY, sales.sales_price FROM sales JOIN car_inventory ON car_inventory.car_id = sales.car_id JOIN customer ON customer.id = sales.customer_id' my_cursor.execute(query) rows = my_cursor.fetchall() update_sales_list(rows) con.close() # Sales Data section id_var_sales = StringVar() cb_car_id = StringVar() cb_customer_id = StringVar() qty_var_sales = StringVar() sales_price_var_sales = StringVar() con = mysql.connector.connect(user='nesarahmad', password='1114WE', host='127.0.0.1', database='carstore') my_cursor = con.cursor() customer_options_sales = [] query = 'SELECT id, name FROM customer' my_cursor.execute(query) customer_ids_names = my_cursor.fetchall() for id_name in customer_ids_names: customer_options_sales.append(str(id_name[0]) + '-' + id_name[1]) lbl_id_sales = Label(frm_sales_data, text='Sales ID') lbl_id_sales.grid(row=0, column=0, sticky='w') ent_id_sales = Entry( frm_sales_data, textvariable=id_var_sales) ent_id_sales.grid(row=0, column=1) # Hide the following 2 Label and Entry lbl_id_sales.grid_forget() ent_id_sales.grid_forget() lbl_customer_id_sales = Label(frm_sales_data, text='Customer') lbl_customer_id_sales.grid(row=2, column=0, sticky='w') cb_customer_id_sales = ttk.Combobox( frm_sales_data, textvariable=cb_customer_id, state='readonly', width=17) cb_customer_id_sales.grid(row=2, column=1) cb_customer_id_sales['values'] = customer_options_sales lbl_qty_sales = Label(frm_sales_data, text='QTY') lbl_qty_sales.grid(row=3, column=0, sticky='w') ent_qty_sales = Entry( frm_sales_data, textvariable=qty_var_sales) ent_qty_sales.grid(row=3, column=1) lbl_sales_price_sales = Label(frm_sales_data, text='Sales Price') lbl_sales_price_sales.grid(row=4, column=0, sticky='w') ent_sales_price_sales = Entry( frm_sales_data, textvariable=sales_price_var_sales) ent_sales_price_sales.grid(row=4, column=1) btn_add_sales = Button( frm_sales_data, text='Add ', width=15, bg='green', fg='white', activebackground='green', activeforeground='white', command=add_sales) btn_add_sales.grid(row=5, column=0, pady=30) btn_edit_sales = Button( frm_sales_data, text='Edit', width=15, bg='blue', fg='white', activebackground='blue', activeforeground='white', command=edit_sales) btn_edit_sales.grid(row=5, column=1, pady=30) btn_refresh_sales = Button( frm_sales_data, text='Refresh', width=15, bg='orange', fg='white', activebackground='orange', activeforeground='white', command=refresh) btn_refresh_sales.grid(row=5, column=3, pady=30) frm_sales.pack(fill='both', expand='yes') # End of Sales Section nb.pack(fill=BOTH, expand=True) nb.add(frm_customer, text='Customer') nb.add(frm_sales, text='Sales') root.mainloop() </code></pre>
[ { "answer_id": 74251907, "author": "mnikley", "author_id": 12892026, "author_profile": "https://Stackoverflow.com/users/12892026", "pm_score": 1, "selected": false, "text": "from tkinter import Tk\nfrom tkinter.ttk import Entry, Combobox\n\nroot = Tk()\n\n\ndef add_to_combobox(event):\n\...
2022/10/30
[ "https://Stackoverflow.com/questions/74250115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20207835/" ]
74,250,127
<p>As soon as I try to access a folder/file containing an emoji in its name from my Lua 5.2 script, for example like this:</p> <pre><code>os.execute('start &quot;&quot; &quot;' .. path .. &quot;\\scripts\\menu\\ My Scripts&quot; .. '&quot;') </code></pre> <p>The Windows' Command Prompt simply refuses to open it with the following error message:</p> <p><a href="https://i.stack.imgur.com/KnHpT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KnHpT.png" alt="CMD and emoji in path issue" /></a></p> <p>I'm aware Windows' Command Prompt doesn't support emojis and therefore is not possible to make it work just like that, but my doubt is if won't exist some workaround or whatever I can do to ensure any Windows/Unix user is going to able to get the folder open by my Lua script without any problem.</p> <p>I have tried i.e. things like use the codes instead (1246 and U+1F4F0 in this <em>page facing up</em> case) without success. Couldn't I for example simply use some kind of &quot;wildcard&quot; instead? I mean, knowing it's always going to be the very first character in the name. Or, well, any other ideas will be welcomed, cause nothing I'm trying really seems to work...</p> <p>Of course if it's going to represent any problem I'll simply refuse to use them, but it came in handy for some &quot;first sight&quot; folder distinction and, if possible, I'd like to can count this little visual resource </p>
[ { "answer_id": 74251907, "author": "mnikley", "author_id": 12892026, "author_profile": "https://Stackoverflow.com/users/12892026", "pm_score": 1, "selected": false, "text": "from tkinter import Tk\nfrom tkinter.ttk import Entry, Combobox\n\nroot = Tk()\n\n\ndef add_to_combobox(event):\n\...
2022/10/30
[ "https://Stackoverflow.com/questions/74250127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2805176/" ]
74,250,142
<p>How do you rename any response/value to 1 and any NA to 0?</p> <p>Sample Dataframe:</p> <pre><code>Dataframeexample &lt;- data.frame(Q5 = c(&quot;potato&quot;, &quot;chips&quot;, &quot;chips&quot;, &quot;chips,potato&quot;,&quot;icecream,chips,potato&quot;, &quot;icecream,potato&quot;, &quot;chips&quot;, &quot;NA&quot;, &quot;NA&quot;)) </code></pre> <p>My actual dataframe has hundreds of potential combinations, so renaming each potential value individually isn't feasible.</p>
[ { "answer_id": 74250589, "author": "Shawn Hemelstrand", "author_id": 16631565, "author_profile": "https://Stackoverflow.com/users/16631565", "pm_score": 1, "selected": false, "text": "#### Data Fix ####\nlibrary(tidyverse) # for mutate later\n\nDataframeexample <- data.frame(Q5 = c(\"pot...
2022/10/30
[ "https://Stackoverflow.com/questions/74250142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19552453/" ]
74,250,158
<pre><code>def print_prime_1_n(n): for i in range(1, n+1): prime = True for j in range(2, i): if i % j == 0: prime = False break if prime: print(i) print_prime_1_n(10) </code></pre> <p>I spent 2 days to figure out this code but i coudn't find a way to figout it out. please explain to me?</p>
[ { "answer_id": 74250189, "author": "Michael Sohnen", "author_id": 5166365, "author_profile": "https://Stackoverflow.com/users/5166365", "pm_score": 0, "selected": false, "text": "def is_prime(i):\n \n # if I is divisible by any number smaller than it, it is not prime\n\n prime =...
2022/10/30
[ "https://Stackoverflow.com/questions/74250158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20369136/" ]
74,250,159
<p>I have a payload like below:</p> <pre><code>{ &quot;data&quot;: [ { &quot;id&quot;: &quot;f251f05f-038c-4c26-bf7c-3b2fc47210e6&quot;, &quot;specialtyIds&quot;: [ &quot;20c5f3f0-54c9-4779-b1a3-19baeee91b4a&quot; ] }, { &quot;id&quot;: &quot;61d34a84-940d-4556-9c4b-ef7bede9caca&quot;, &quot;specialtyIds&quot;: [ &quot;20c5f3f0-54c9-4779-b1a3-19baeee91b4a&quot;, &quot;9834e1cf-94c4-4188-83e6-867ac1d60017&quot;, &quot;30d6g4d3-54c9-4779-b1a3-19baeee92cdc&quot; ] } ] } </code></pre> <p>and want to return an array like:</p> <pre><code>[ { id: &quot;20c5f3f0-54c9-4779-b1a3-19baeee91b4a&quot; }, { id: &quot;9834e1cf-94c4-4188-83e6-867ac1d60017&quot; }, { id: &quot;30d6g4d3-54c9-4779-b1a3-19baeee92cdc&quot; } ] </code></pre> <p>I've used the following dataweave which works fine when <code>specialtyIds</code> is only one element. But the second there's more than one element it breaks:</p> <pre><code>payload.data map { id: $.specialtyIds joinBy(&quot;,&quot;) } distinctBy $ </code></pre> <p>if the array has more than two elements the script returns:</p> <pre><code>[ { id: &quot;20c5f3f0-54c9-4779-b1a3-19baeee91b4a&quot; }, { id: &quot;20c5f3f0-54c9-4779-b1a3-19baeee91b4a,9834e1cf-94c4-4188-83e6-867ac1d60017&quot; } ] </code></pre> <p>I am relatively new to dataweave, but have explored pluck and reduce to iterate over the arrays but haven't had much luck. I feel like there is probably a simpler way to tackle this structure.</p>
[ { "answer_id": 74250189, "author": "Michael Sohnen", "author_id": 5166365, "author_profile": "https://Stackoverflow.com/users/5166365", "pm_score": 0, "selected": false, "text": "def is_prime(i):\n \n # if I is divisible by any number smaller than it, it is not prime\n\n prime =...
2022/10/30
[ "https://Stackoverflow.com/questions/74250159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1698350/" ]