qid
int64
4
22.2M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,479,001
<p>Writing an admin action so an administrator can select a template they can use to send a message to subscribers by inputting only the subject and text message. Using a filtered list from the admin panel an action called <code>broadcast</code> is triggered on this queryset (the default filter list). The admin action 'broadcast' is a function of a sub-classed UserAdmin class. The intermediate page is displayed that shows a dropdown selector for the <code>emailtype</code>, the queryset items (which will be email addresses, input fields for the subject and message text (message is required field) a button for optional file attachment followed by send or cancel buttons. Problem 1) after hitting the send button the app reverts to the admin change list page. In the broadcast function, the conditional <code>if 'send' in request.POST:</code> is never called.</p> <p><strong><code>forms.py</code></strong></p> <pre class="lang-py prettyprint-override"><code>mail_types=(('1','Newsletter Link'),('2','Update Alert')) class SendEmailForm(forms.Form): _selected_action = forms.CharField(widget=forms.MultipleHiddenInput) #Initialized 'accounts' from Account:admin.py Actions: 'send_email' using&gt;&gt; form = SendEmailForm(initial={'accounts': queryset}) my_mail_type=forms.ChoiceField(label='Mail Type',choices=mail_types,required=False) subject = forms.CharField(widget=forms.TextInput(attrs={'placeholder': ('Subject')}),required=False) message = forms.CharField(widget=forms.Textarea(attrs={'placeholder': ('Teaser')}),required=True,min_length=5,max_length=1000) attachment = forms.FileField(widget=forms.ClearableFileInput(),required=False) accounts = forms.ModelChoiceField(label=&quot;To:&quot;, queryset=Account.objects.all(), widget=forms.SelectMultiple(attrs={'placeholder': ('user_email@somewhere.com')}), empty_label='user_email@somewhere.com', required=False, </code></pre> <p><strong><code>admin.py</code></strong></p> <pre class="lang-py prettyprint-override"><code>from .forms import SendEmailForm from django.http import HttpResponseRedirect,HttpResponse from django.shortcuts import render, redirect from django.template.response import TemplateResponse def broadcast(self, request, queryset): form=None if 'send' in request.POST: print('DEBUGGING: send found in post request') form = SendEmailForm(request.POST, request.FILES,initial={'accounts': queryset,}) if form.is_valid(): #do email sending stuff here print('DEBUGGING form.valid ====&gt;&gt;&gt; BROADCASTING TO:',queryset) #num_sent=send_mail('test subject2', 'test message2','From Team',['dummy@hotmail.com'],fail_silently=False, html_message='email_simple_nb_template.html',) self.message_user(request, &quot;Broadcasting of %s messages has been started&quot; % len(queryset)) print('DEBUGGING: returning to success page') return HttpResponseRedirect(request, 'success.html', {}) if not form: # intermediate page right here print('DEBUGGING: broadcast ELSE called') form = SendEmailForm(request.POST, request.FILES, initial={'accounts': queryset,}) return TemplateResponse(request, &quot;send_email.html&quot;,context={'accounts': queryset, 'form': form},) </code></pre> <p><strong><code>send_email.html</code></strong></p> <pre class="lang-html prettyprint-override"><code>{% extends &quot;admin/base_site.html&quot; %} {% load i18n admin_urls static %} {% load crispy_forms_tags %} {% block content %} &lt;form method=&quot;POST&quot; enctype=&quot;multipart/form-data&quot; action=&quot;&quot; &gt; {% csrf_token %} &lt;div&gt; &lt;div&gt; &lt;p&gt;{{ form.my_mail_type.label_tag }}&lt;/p&gt; &lt;p&gt;{{ form.my_mail_type }}&lt;/p&gt; &lt;/div&gt; &lt;div&gt; &lt;p&gt;{{ form.accounts.label_tag }}&lt;/p&gt; &lt;p&gt; {% for account in form.accounts.queryset %} {{ account.email }}{% if not forloop.last %},&amp;nbsp;{% endif %} {% endfor %} &lt;/p&gt; &lt;p&gt;&lt;select name=&quot;accounts&quot; multiple style=&quot;display: form.accounts.email&quot;&gt; {% for account in form.accounts.initial %} &lt;option value=&quot;{{ account.email }}&quot; selected&gt;{{ account }}&lt;/option&gt; {% endfor %} &lt;/p&gt;&lt;/select&gt; &lt;/div&gt; &lt;div&gt; &lt;p&gt;{{ form.subject.label_tag }}&lt;/p&gt; &lt;p&gt;{{ form.subject }}&lt;/p&gt; &lt;/div&gt; &lt;div&gt; &lt;p&gt;{{ form.message.label_tag }}&lt;/p&gt; &lt;p&gt;{{ form.message }}&lt;/p&gt; &lt;/div&gt; &lt;div&gt; &lt;p&gt;{{ form.attachment.label_tag }}&lt;/p&gt; &lt;p&gt;{{ form.attachment.errors }}&lt;/p&gt; &lt;p&gt;{{ form.attachment }}&lt;/p&gt; &lt;/div&gt; &lt;input type=&quot;hidden&quot; name=&quot;action&quot; value=&quot;send_email&quot; /&gt; &lt;input type=&quot;submit&quot; name=&quot;send&quot; id=&quot;send&quot; value=&quot;{% trans 'Send messages' %}&quot;/&gt; &lt;a href=&quot;{% url 'admin:account_account_changelist' %}&quot; name=&quot;cancel&quot; class=&quot;button cancel-link&quot;&gt;{% trans &quot;Cancel this Message&quot; %}&lt;/a&gt; &lt;/div&gt; &lt;/form&gt; {% endblock %} </code></pre> <p>Inspecting the browser at the <em>POST</em> call seems to show all the data was bound. Another poster <a href="https://stackoverflow.com/questions/31591215/django-admin-form-action-dont-send-post-params">here</a> suggested the admin action buttons divert requests to an internal 'view' and you should redirect to a new view to handle the <em>POST</em> request. I can't get that to work because I can't get a redirect to 'forward' the queryset. The form used in the suggested fix was simpler and did not use the queryset the same way. I have tried writing some FBVs in Forms.py and Views.py and also tried CBVs in views.py but had issues having a required field (message) causing non-field errors and resulting in an invalid form. I tried overriding these by writing <code>def \_clean_form(self):</code> that would ignore this error, which did what it was told to do but resulted in the form essentially being bound and validated without any inputs so the intermediate page didn't appear. Which means the rabbit hole returned to the same place. The <code>send</code> button gets <code>ignored</code> in either case of FBVs or CBVs, which comes back to the admin action buttons Post requests revert to the admin channels! Any ideas on how to work around this? Key requirements: From the admin changelist action buttons:</p> <ol> <li><p>the Form on an intermediate page must appear with the queryset passed from the admin changelist filter.</p> </li> <li><p>The <code>message</code> input field on the form is a required field.</p> </li> <li><p>the send button on the HTML form view needs to trigger further action.</p> </li> </ol> <p>NOTES: My custom Admin User is a subclass of <code>AbstractBaseUser</code> called Account, where I chose not to have a username and am using <code>USERNAME_FIELD='email'</code>. Also, I do not need a <code>Model.py</code> for the <code>SendEmailForm</code> as I don't need to save the data or update the user models, just send the input message using the chosen template and queryset. Help is much appreciated!</p>
[ { "answer_id": 74535017, "author": "Maxim Danilov", "author_id": 18728010, "author_profile": "https://Stackoverflow.com/users/18728010", "pm_score": 3, "selected": true, "text": "POST" }, { "answer_id": 74585396, "author": "matevz.ap", "author_id": 19750230, "author_profile": "https://Stackoverflow.com/users/19750230", "pm_score": 0, "selected": false, "text": "def broadcast(self, request, queryset):\n request.session[\"emails\"] = list(queryset.values_list(\"emails\", flat=True))\n return HttpResponseRedirect(\"url_to_new_view\")\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15146780/" ]
74,479,025
<p>I have no basic clue about html and and right now am kinda stuck, I need two images side by side around the bottom half part of a email template, thing is no matter what I do I can't get the image to be side by side. there is already a hero image on the email template I am not sure if that's what causing the error. Can you please help me with this or give me some learning metrials so that I can figure this out.</p> <p>Can you please help me with this or give me some learning metrials so that I can figure this out.</p> <p>PS: Please don't mind the rickroll video, I added it to replace the link</p> <p>The below code is how the banner hero image is setup</p> <pre><code>&lt;tr&gt; &lt;td class=&quot;hero&quot; style=&quot;border-collapse: collapse; border-spacing: 0px; margin: 0px; padding: 0px;&quot; align=&quot;center&quot; valign=&quot;top&quot;&gt; &lt;a title=&quot;placeholdertext&quot; href=&quot;https://www.youtube.com/watch?v=dQw4w9WgXcQ&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt; &lt;img class=&quot;fr-dib&quot; style=&quot;width: 620px; max-width: 560px; color: #000000; font-size: 13px; padding: 0px; outline: currentcolor none medium; text-decoration: none;&quot; title=&quot;rick roll&quot; src=&quot;test_mail_f.jpg&quot; alt=&quot;rick roll&quot; width=&quot;560&quot; height=&quot;349&quot; border=&quot;0&quot; /&gt; &lt;/a&gt; &lt;/td&gt; &lt;/tr&gt; </code></pre>
[ { "answer_id": 74535017, "author": "Maxim Danilov", "author_id": 18728010, "author_profile": "https://Stackoverflow.com/users/18728010", "pm_score": 3, "selected": true, "text": "POST" }, { "answer_id": 74585396, "author": "matevz.ap", "author_id": 19750230, "author_profile": "https://Stackoverflow.com/users/19750230", "pm_score": 0, "selected": false, "text": "def broadcast(self, request, queryset):\n request.session[\"emails\"] = list(queryset.values_list(\"emails\", flat=True))\n return HttpResponseRedirect(\"url_to_new_view\")\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20532020/" ]
74,479,043
<p>This is an example of the dataset</p> <pre><code>n | rbc ------- 1 | 2500 2 | 2.7 3 | 4500 </code></pre> <p>I want to find rows that has decimal points and then multiply them by 1000</p>
[ { "answer_id": 74535017, "author": "Maxim Danilov", "author_id": 18728010, "author_profile": "https://Stackoverflow.com/users/18728010", "pm_score": 3, "selected": true, "text": "POST" }, { "answer_id": 74585396, "author": "matevz.ap", "author_id": 19750230, "author_profile": "https://Stackoverflow.com/users/19750230", "pm_score": 0, "selected": false, "text": "def broadcast(self, request, queryset):\n request.session[\"emails\"] = list(queryset.values_list(\"emails\", flat=True))\n return HttpResponseRedirect(\"url_to_new_view\")\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20532118/" ]
74,479,054
<p>I have a tableView with cells that contain UiCollectionView. My didSelect tableView's delegate isn't called when I touch the cell on the collectionView. I think it's my collectionView that get the touch instead. Do you have any elegant solution to keep the scroll enabled on my collectionView but disable the selection and pass it to the tableview ?</p> <p>Here is my tableView declaration :</p> <pre><code>private lazy var tableView:UITableView = { [weak self] in $0.register(TestTableViewCell.self, forCellReuseIdentifier: &quot;identifier&quot;) $0.delegate = self $0.dataSource = self return $0 }(UITableView()) </code></pre> <p>Here are my delegate and dataSource methods:</p> <pre><code>public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int { return 20 } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: &quot;identifier&quot;, for: indexPath) as! TestTableViewCell return cell } public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) print(indexPath) } </code></pre> <p>And here is my cell :</p> <pre><code>public class TestTableViewCell : UITableViewCell { private lazy var collectionViewFlowLayout:UICollectionViewFlowLayout = { $0.scrollDirection = .horizontal $0.minimumLineSpacing = 0 $0.minimumInteritemSpacing = 0 return $0 }(UICollectionViewFlowLayout()) private lazy var collectionView:UICollectionView = { $0.register(UICollectionViewCell.self, forCellWithReuseIdentifier: &quot;identifier&quot;) $0.delegate = self $0.dataSource = self return $0 }(UICollectionView(frame: .zero, collectionViewLayout: collectionViewFlowLayout)) public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(collectionView) collectionView.snp.makeConstraints { make in make.edges.equalToSuperview() } } required init?(coder aDecoder: NSCoder) { fatalError(&quot;init(coder:) has not been implemented&quot;) } public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -&gt; Int { return 5 } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -&gt; UICollectionViewCell { let cell:UICollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: cell:&quot;identifier&quot;, for: indexPath) as! cell:UICollectionViewCell return cell } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -&gt; CGSize { return collectionView.frame.size } } </code></pre> <p>If you spot any compilation error, excuse me, this is an anonymized copy/past. My app is running without error.</p> <p>If you want an example of what I'm trying to do you can check AirBnb's app. TableView with some houses with cells and inside, pictures collectionView. Il you touch the collectionView, the tableView select the cell...</p> <p>Thanks</p>
[ { "answer_id": 74481687, "author": "Ankur Lahiry", "author_id": 8475638, "author_profile": "https://Stackoverflow.com/users/8475638", "pm_score": 1, "selected": false, "text": "didSelectItem" }, { "answer_id": 74483054, "author": "DonMag", "author_id": 6257435, "author_profile": "https://Stackoverflow.com/users/6257435", "pm_score": 2, "selected": true, "text": "UICollectionView" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/631927/" ]
74,479,060
<p>I have the json file, which is define the fields for form in react, so in this file I defined soome properties regarding this field, so I have for example this json object:</p> <pre class="lang-json prettyprint-override"><code> &quot;type&quot;: &quot;input&quot;, &quot;config&quot;: { &quot;mask&quot;: &quot;00°00'00''X&quot;, &quot;maskRules&quot;: { &quot;X&quot;: &quot;/N|S/&quot;}, &quot;value&quot;: &quot; N&quot; } } </code></pre> <p>As a result I have this <a href="https://i.stack.imgur.com/Qy44E.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Qy44E.png" alt="enter image description here" /></a></p> <p>My character 'X' should be as an object which is replacing with regexp, regarding this <a href="https://js.devexpress.com/Documentation/Guide/UI_Components/TextBox/Specify_a_Mask_for_the_Input/" rel="nofollow noreferrer">documentation</a></p> <p>But it find this regExp as just string, what should I do in this case?</p>
[ { "answer_id": 74481687, "author": "Ankur Lahiry", "author_id": 8475638, "author_profile": "https://Stackoverflow.com/users/8475638", "pm_score": 1, "selected": false, "text": "didSelectItem" }, { "answer_id": 74483054, "author": "DonMag", "author_id": 6257435, "author_profile": "https://Stackoverflow.com/users/6257435", "pm_score": 2, "selected": true, "text": "UICollectionView" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15790479/" ]
74,479,074
<p>I have app that work with decks (decks of one trading card game).</p> <p>My security config:</p> <pre class="lang-java prettyprint-override"><code> @Bean //httpSecurity прототип public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception { httpSecurity .authorizeRequests() .antMatchers(&quot;/&quot;, &quot;/registration&quot;, &quot;/css/**&quot;, &quot;/images/**&quot;, &quot;/static/**&quot;).permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage(&quot;/login&quot;) .permitAll() .and() .logout() .logoutSuccessUrl(&quot;/&quot;) .permitAll(); return httpSecurity.build(); } </code></pre> <p>and now I want to unsecure intermediate endpoint:</p> <pre><code>GET /decks &lt;-- secured. return view with all decks of specified user GET /decks/{id} &lt;-- must be not secured. return single deck view by its id GET /decks/{id}/edit &lt;-- must be secured. return view for editing deck. </code></pre> <p>Is there are way to allow via Spring Security anonymous calls for <code>GET /decks/{id}</code>?</p>
[ { "answer_id": 74480244, "author": "Артём Власов", "author_id": 13411640, "author_profile": "https://Stackoverflow.com/users/13411640", "pm_score": 0, "selected": false, "text": "/decks/{\\\\d+}" }, { "answer_id": 74482277, "author": "jzheaux", "author_id": 2243324, "author_profile": "https://Stackoverflow.com/users/2243324", "pm_score": 1, "selected": false, "text": "mvcMatchers" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13411640/" ]
74,479,083
<p>In the Next.js application, I am getting the error</p> <pre><code>TestingLibraryElementError: Unable to find an accessible element with the role &quot;link&quot; </code></pre> <p>while performing below assertion -</p> <pre><code>expect(screen.getAllByRole(&quot;link&quot;).length).toEqual(1); </code></pre> <p>for the anchor tag that is wrapped in Link Component of next.js</p> <pre><code> &lt;Link href={`/article/${Id}`} &gt; &lt;a title={Title} onClick={() =&gt; { /// }} &gt; {Title} &lt;/a&gt; &lt;/Link&gt; </code></pre>
[ { "answer_id": 74480244, "author": "Артём Власов", "author_id": 13411640, "author_profile": "https://Stackoverflow.com/users/13411640", "pm_score": 0, "selected": false, "text": "/decks/{\\\\d+}" }, { "answer_id": 74482277, "author": "jzheaux", "author_id": 2243324, "author_profile": "https://Stackoverflow.com/users/2243324", "pm_score": 1, "selected": false, "text": "mvcMatchers" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1506462/" ]
74,479,087
<p>I'm working on an angular project, where I want to convert a list to a specific data structure, to be able to use it with the TreeSelect component of primeng.</p> <p>from:</p> <pre><code> initialDataStructure = [ { &quot;country&quot;: &quot;GERMANY&quot;, &quot;productType&quot;: &quot;BASE&quot;, &quot;deliveryPeriod&quot;: &quot;MONTH&quot;}, { &quot;country&quot;: &quot;GERMANY&quot;, &quot;productType&quot;: &quot;BASE&quot;, &quot;deliveryPeriod&quot;: &quot;YEAR&quot;}, { &quot;country&quot;: &quot;GERMANY&quot;, &quot;productType&quot;: &quot;PEAK&quot;, &quot;deliveryPeriod&quot;: &quot;MONTH&quot;}, { &quot;country&quot;: &quot;GERMANY&quot;, &quot;productType&quot;: &quot;PEAK&quot;, &quot;deliveryPeriod&quot;: &quot;YEAR&quot;}, { &quot;country&quot;: &quot;AUSTRIA&quot;, &quot;productType&quot;: &quot;BASE&quot;, &quot;deliveryPeriod&quot;: &quot;MONTH&quot;}, { &quot;country&quot;: &quot;AUSTRIA&quot;, &quot;productType&quot;: &quot;BASE&quot;, &quot;deliveryPeriod&quot;: &quot;YEAR&quot;}, { &quot;country&quot;: &quot;AUSTRIA&quot;, &quot;productType&quot;: &quot;PEAK&quot;, &quot;deliveryPeriod&quot;: &quot;MONTH&quot;}, { &quot;country&quot;: &quot;AUSTRIA&quot;, &quot;productType&quot;: &quot;PEAK&quot;, &quot;deliveryPeriod&quot;: &quot;YEAR&quot;}, ] </code></pre> <p>I tried this, but it didn't work as expected. is there any other way to get this mapped? I tried this, but it didn't work as expected. is there any other way to get this mapped?</p> <pre><code> for (var i = 0, len = this.listContracts.length, p; i &lt; len; i++) { // faster than .forEach p = this.listContracts[i]; if (this.grouped[p.country] === undefined) // twice faster then hasOwnProperty this.grouped[p.country] ={} if (this.grouped[p.country][p.productType] === undefined) this.grouped[p.country][p.productType] ={} if (this.grouped[p.country][p.productType][p.deliveryPeriod] === undefined) this.grouped[p.country][p.productType][p.deliveryPeriod]=[] this.grouped[p.country][p.productType][p.deliveryPeriod].push(p); // groupby is HERE xD } </code></pre> <pre><code>expectedDataStructure = [ { label: &quot;GERMANY&quot;, children: [ { label: &quot;BASE&quot;, children: [ { label: &quot;MONTH&quot;, children: [{ &quot;country&quot;: &quot;GERMANY&quot;, &quot;productType&quot;: &quot;BASE&quot;, &quot;deliveryPeriod&quot;: &quot;MONTH&quot;}] }, { label: &quot;YEAR&quot;, children: [{ &quot;country&quot;: &quot;GERMANY&quot;, &quot;productType&quot;: &quot;BASE&quot;, &quot;deliveryPeriod&quot;: &quot;YEAR&quot;}] } ] }, { label: &quot;PEAK&quot;, children: [ { label: &quot;MONTH&quot;, children: [{ &quot;country&quot;: &quot;GERMANY&quot;, &quot;productType&quot;: &quot;PEAK&quot;, &quot;deliveryPeriod&quot;: &quot;MONTH&quot;}] }, { label: &quot;YEAR&quot;, children: [{ &quot;country&quot;: &quot;GERMANY&quot;, &quot;productType&quot;: &quot;PEAK&quot;, &quot;deliveryPeriod&quot;: &quot;YEAR&quot;}] } ] }, ] }, { label: &quot;AUSTRIA&quot;, children: [ { label: &quot;BASE&quot;, children: [ { label: &quot;MONTH&quot;, children: [{ &quot;country&quot;: &quot;AUSTRIA&quot;, &quot;productType&quot;: &quot;BASE&quot;, &quot;deliveryPeriod&quot;: &quot;MONTH&quot;}] }, { label: &quot;YEAR&quot;, children: [{ &quot;country&quot;: &quot;AUSTRIA&quot;, &quot;productType&quot;: &quot;BASE&quot;, &quot;deliveryPeriod&quot;: &quot;YEAR&quot;}] } ] }, { label: &quot;PEAK&quot;, children: [ { label: &quot;MONTH&quot;, children: [{ &quot;country&quot;: &quot;AUSTRIA&quot;, &quot;productType&quot;: &quot;PEAK&quot;, &quot;deliveryPeriod&quot;: &quot;MONTH&quot;}] }, { label: &quot;YEAR&quot;, children: [{ &quot;country&quot;: &quot;AUSTRIA&quot;, &quot;productType&quot;: &quot;PEAK&quot;, &quot;deliveryPeriod&quot;: &quot;YEAR&quot;}] } ] }, ] }, ] </code></pre>
[ { "answer_id": 74479326, "author": "Dreamy Player", "author_id": 15319747, "author_profile": "https://Stackoverflow.com/users/15319747", "pm_score": -1, "selected": false, "text": "const initialDs = [\n { country: 'GERMANY', productType: 'BASE', deliveryPeriod: 'MONTH' },\n { country: 'GERMANY', productType: 'BASE', deliveryPeriod: 'YEAR' },\n { country: 'GERMANY', productType: 'PEAK', deliveryPeriod: 'MONTH' },\n { country: 'GERMANY', productType: 'PEAK', deliveryPeriod: 'YEAR' },\n\n { country: 'AUSTRIA', productType: 'BASE', deliveryPeriod: 'MONTH' },\n { country: 'AUSTRIA', productType: 'BASE', deliveryPeriod: 'YEAR' },\n { country: 'AUSTRIA', productType: 'PEAK', deliveryPeriod: 'MONTH' },\n { country: 'AUSTRIA', productType: 'PEAK', deliveryPeriod: 'YEAR' },\n];\n\nconst DataStucture = (array, Type) => {\n const res = array\n .filter(x => x.productType === Type)\n .map(x => {\n const obj = {\n label: x.country,\n chilren: [\n {\n label: x.deliveryPeriod,\n children: [x],\n },\n ],\n };\n return obj;\n });\n return res;\n};\n\nconsole.log(DataStucture(initialDs, 'PEAK'));" }, { "answer_id": 74497880, "author": "Eddy Lin", "author_id": 19768317, "author_profile": "https://Stackoverflow.com/users/19768317", "pm_score": 0, "selected": false, "text": "const { map, from, pipe, identity, groupBy, mergeMap, toArray } = rxjs;\n\nconst initialDataStructure = [\n { country: 'GERMANY', productType: 'BASE', deliveryPeriod: 'MONTH' },\n { country: 'GERMANY', productType: 'BASE', deliveryPeriod: 'YEAR' },\n { country: 'GERMANY', productType: 'PEAK', deliveryPeriod: 'MONTH' },\n { country: 'GERMANY', productType: 'PEAK', deliveryPeriod: 'YEAR' },\n { country: 'AUSTRIA', productType: 'BASE', deliveryPeriod: 'MONTH' },\n { country: 'AUSTRIA', productType: 'BASE', deliveryPeriod: 'YEAR' },\n { country: 'AUSTRIA', productType: 'PEAK', deliveryPeriod: 'MONTH' },\n { country: 'AUSTRIA', productType: 'PEAK', deliveryPeriod: 'YEAR' },\n];\n\nconst treeSelect = (...keys) => {\n const key = keys.shift();\n return !key ? identity : pipe(\n groupBy((data) => data[key]),\n mergeMap((c$) => c$.pipe(\n treeSelect(...keys),\n map((arr) => ({label: c$.key, children: arr}))),\n ),\n toArray());\n};\n\nfrom(initialDataStructure).pipe(\n treeSelect('country', 'productType', 'deliveryPeriod')\n).subscribe(console.log);" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10203015/" ]
74,479,105
<p>I need to write a <code>golang</code> application with the help of <a href="https://github.com/kubernetes/client-go" rel="nofollow noreferrer">client-go</a> which will listen/watch a particular namespace for any of these events:</p> <ul> <li>A new pod has been created</li> <li>A pod has been deleted</li> <li>A new container has been added to existing pods</li> <li>Image for container for any pod has changed</li> </ul> <p>And I want to communicate this information to another application application running in other namespace.</p> <p>I am really new to the <code>client-go</code> library and I searched their documentation but couldn't find something similar to <a href="https://kopf.readthedocs.io/en/latest/events/" rel="nofollow noreferrer">Events in Kopf</a></p> <p><strong>I am new to this library and I couldn't find a method/function of doing this. I don't need to have the full code of doing this, but I appreciate where I can look into, so I can find my way out</strong></p> <p>Can someone help me on this?</p>
[ { "answer_id": 74501528, "author": "Raihan Khan", "author_id": 7360615, "author_profile": "https://Stackoverflow.com/users/7360615", "pm_score": 2, "selected": false, "text": "OnUpdate" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7084115/" ]
74,479,111
<p>Let's say I have a list <code>[1,2,3,4,5,6]</code>, and I want to iterate over all the subgroups of len 2 <code>[1,2] [3,4] [5,6]</code>.</p> <p>The naive way of doing it</p> <pre><code> L = [1,2,3,4,5,6] N = len(L)//2 for k in range(N): slice = L[k*2:(k+1)*2] for val in slice: #Do things with the slice </code></pre> <p>However I was wondering if there is a more pythonic method to iterate over a &quot;partitioned&quot; list already. I also accept solutions with <code>numpy arrays</code>. Something like:</p> <pre><code> L = [1,2,3,4,5,6] slices = f(L,2) # A nice &quot;f&quot; here? for slice in slices: for val in slice: #Do things with the slice </code></pre> <p>Thanks a lot!</p>
[ { "answer_id": 74479409, "author": "Woodford", "author_id": 8451814, "author_profile": "https://Stackoverflow.com/users/8451814", "pm_score": 3, "selected": true, "text": "grouper" }, { "answer_id": 74479564, "author": "chrslg", "author_id": 20037042, "author_profile": "https://Stackoverflow.com/users/20037042", "pm_score": 1, "selected": false, "text": "f" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4952549/" ]
74,479,115
<p>I am trying to extract date from a DF column containing strings and store in another column.</p> <pre><code>from dateutil.parser import parse extract = parse(&quot;January 24, 1976&quot;, fuzzy_with_tokens=True) print(str(extract[0])) </code></pre> <p>The above code extracts: 1976-01-24 00:00:00</p> <p>I would like this to be done to all strings in a column in a DF.</p> <p>The below is what I am trying but is not working:</p> <pre><code>df['Dates'] = df.apply(lambda x: parse(x['Column to extract'], fuzzy_with_tokens=True), axis=1) </code></pre> <p>Things to note:</p> <ol> <li>If there are multiple dates, need to join them with some delimiter</li> <li>There can be strings without date. In that case parser returns an error &quot;ParserError: String does not contain a date&quot;. This needs to be handled.</li> </ol>
[ { "answer_id": 74479125, "author": "Ian Thompson", "author_id": 6509519, "author_profile": "https://Stackoverflow.com/users/6509519", "pm_score": 1, "selected": false, "text": "pd.to_datetime" }, { "answer_id": 74479283, "author": "Nuri Taş", "author_id": 19255749, "author_profile": "https://Stackoverflow.com/users/19255749", "pm_score": 0, "selected": false, "text": "parse" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15130945/" ]
74,479,143
<p>I am just starting to play with Excel macros and am already stuck.</p> <p>I have a main sheet where data is structured like this:</p> <pre><code>France 10 Germany 14 US 20 </code></pre> <p>and then I have three other sheets called: France, Germany, US.</p> <p>My goal is to copy the number into each corresponding sheet. Always copying into the same cell (just on different sheets) defined on the main sheet in cell O1 I have = B5 and in cell P1 I have = 3 (because I want it 3 times).</p> <p>My idea was to go through the sheet row by row and have two variables:</p> <pre><code>country value </code></pre> <p>I managed to put, for example, France into country and 10 into value, but when I try to do it in the loop I get this error (where the stars are): <code>error 1004: method &quot;range&quot; of object &quot;global&quot; failed</code></p> <pre><code>Sub trial() Dim destination As String Dim inputer As Long Dim country As String Dim counter As Boolean Dim maxcounter As Boolean maxcounter = Range(&quot;P1&quot;).Value counter = &quot;1&quot; While maxcounter &gt; counter: destination = Range(&quot;O1&quot;).Value **country = Range(&quot;A&quot; &amp; counter).Value** inputer = Range(&quot;B&quot; &amp; counter).Value Sheets(country).Range(destination).Value = inputer counter = counter + 1 Wend End Sub </code></pre>
[ { "answer_id": 74479125, "author": "Ian Thompson", "author_id": 6509519, "author_profile": "https://Stackoverflow.com/users/6509519", "pm_score": 1, "selected": false, "text": "pd.to_datetime" }, { "answer_id": 74479283, "author": "Nuri Taş", "author_id": 19255749, "author_profile": "https://Stackoverflow.com/users/19255749", "pm_score": 0, "selected": false, "text": "parse" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20531763/" ]
74,479,164
<p>I thought my goal was simple enough. I have a client that makes calls to a Web API (registered in an Azure B2C tenant) to receive an access token. So far so good. When I use this access token to call a Web API method that is secured with the [Authorize] tag, I only get back an 401 Unauthorized error.</p> <p>I'm using ASP.NET Core 3.1.</p> <p><strong>1. Web Api</strong> - My method to acquire the token:</p> <pre><code>IPublicClientApplication app = PublicClientApplicationBuilder.Create(_clientId) .WithB2CAuthority(_authority) .Build(); result = await app.AcquireTokenByUsernamePassword(_scopes, _username, _password) .ExecuteAsync(); return Ok(result.AccessToken); </code></pre> <p>This returns a token and when I enter it in jwt.io it looks okay, with the right username and scopes, but at the bottom it says &quot;Invalid Signature&quot;. This could be the problem, but someone also had a similar issue and claimed that it worked for him anyway. It makes me uncomfortable and maybe someone can tell me reasons why the signature could be invalid or what this means exactly.</p> <p><strong>2. Local Client</strong> - sending my requests:</p> <pre><code>HttpRequestMessage request = new HttpRequestMessage() { Method = method, RequestUri = new Uri(_httpClient.BaseAddress + requestUri), }; request.Headers.Authorization = new AuthenticationHeaderValue(&quot;Bearer&quot;, _token); return await _httpClient.SendAsync(request); </code></pre> <p><strong>3. Web Api</strong> - <code>Startup.cs</code> service configuration:</p> <p>Here I tried so many things that I couldn't say which one worked best, because none of them seemed to work. I thought this version looked promising:</p> <pre><code>services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApi(Configuration, &quot;AzureB2C&quot;) .EnableTokenAcquisitionToCallDownstreamApi() .AddMicrosoftGraph(Configuration.GetSection(&quot;MicrosoftGraph&quot;)) .AddInMemoryTokenCaches(); </code></pre> <p><strong>4. appsettings.json</strong></p> <p>I also tried different settings here and I didn't know what to use for my ROPC policy, so I entered it into &quot;SignUpSignInPolicyId&quot; which probably is a problem too:</p> <pre><code>&quot;AzureB2C&quot;: { &quot;Instance&quot;: &quot;https://[tenant].b2clogin.com/&quot;, &quot;Domain&quot;: &quot;[domain name]&quot;, &quot;TenantId&quot;: &quot;[tenantId]&quot;, &quot;ClientId&quot;: &quot;[clientId]&quot;, &quot;SignUpSignInPolicyId&quot;: &quot;[ropc policy name]&quot;, &quot;B2cExtensionAppClientId&quot;: &quot;[client id of b2cextensionapp]&quot;, &quot;Scopes&quot;: &quot;[scopeurl]&quot; } </code></pre> <p>Any help with this would be extremely appreciated since I'm going a little crazy with this. I'm pretty new to Azure, authorization and Web APIs in general, but I researched a lot over the last weeks and I still don't understand why this is not working, especially since I'm getting back an access token for the right user.</p> <p>Thank you!</p>
[ { "answer_id": 74479125, "author": "Ian Thompson", "author_id": 6509519, "author_profile": "https://Stackoverflow.com/users/6509519", "pm_score": 1, "selected": false, "text": "pd.to_datetime" }, { "answer_id": 74479283, "author": "Nuri Taş", "author_id": 19255749, "author_profile": "https://Stackoverflow.com/users/19255749", "pm_score": 0, "selected": false, "text": "parse" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20439892/" ]
74,479,177
<p>Im a complete noob to computer vision.</p> <p>I have went through the Roboflow tutorial how to train YOLOv7 with my custom dataset using colab, Tutorial: <a href="https://www.youtube.com/watch?v=5nsmXLyDaU4" rel="nofollow noreferrer">https://www.youtube.com/watch?v=5nsmXLyDaU4</a> colab notebook: <a href="https://colab.research.google.com/drive/1X9A8odmK4k6l26NDviiT6dd6TgR-piOa" rel="nofollow noreferrer">https://colab.research.google.com/drive/1X9A8odmK4k6l26NDviiT6dd6TgR-piOa</a></p> <p>In my custom dataset the labels look like this:</p> <pre><code>1 0.453125 0.6647727265625 0.434375 0.7244318187500001 0.40625 0.7613636359375 0.4109375 0.8153409093749999 0.3828125 0.8835227265625001 0.3828125 0.90056818125 0.409375 0.9176136359375 0.4171875 0.9772727265625001 0.4578125 0.96875 0.5265625 0.90056818125 0.5671875 0.84375 0.578125 0.7642045453125 0.578125 0.6335227265625 0.5625 0.6051136359375 0.54375 0.6022727265625 0.5125 0.6335227265625 0.4671875 0.6448863640625 0.453125 0.6647727265625 </code></pre> <p>this is a lable for a picture with a single class, it has a lot of coordinates because I used Roboflow's editor to draw a precise contour around my image, so it has many &quot;dots&quot; since the contour is made up of many individual lines.</p> <p>The YOLOv7 net trained with out any problems with ~98% accuracy and was able to id my object very well.</p> <p>When I tried using the same data set to train YOLOv4-tiny per this tutorial: <a href="https://www.youtube.com/watch?v=H3SJcwttTi4" rel="nofollow noreferrer">https://www.youtube.com/watch?v=H3SJcwttTi4</a> colab notebook: <a href="https://colab.research.google.com/drive/1hQO4nOoD6RDxdbz3C1YSiifTsyZjZpYm?usp=sharing" rel="nofollow noreferrer">https://colab.research.google.com/drive/1hQO4nOoD6RDxdbz3C1YSiifTsyZjZpYm?usp=sharing</a></p> <p>The training failed, it gave only about ~40% accuracy and the training log complained about not having the correct coordinates (I know I should have kept the log to show, my bad)</p> <p>I realize that the notebooks and the repos are different, but I cant shake the feeling that it might be that YOLOv4-tiny does not like complex geometry labeling, that it wants the box.</p> <p>I expected that training youlov4-tiny would be as straight forward as training yolov7 with the same dataset. In the end I trained yolov4-tiny with a dataset where the labels were given as a set of 4 coordinates - making a box around the object (unlike the dataset for yolov7 where the labels were given as a set of multiple coordinates because I drew a complex contour around the object)</p> <p>If anyone had this experience before, I would be grateful to hear your thoughts.</p> <p>Thank you.</p>
[ { "answer_id": 74479125, "author": "Ian Thompson", "author_id": 6509519, "author_profile": "https://Stackoverflow.com/users/6509519", "pm_score": 1, "selected": false, "text": "pd.to_datetime" }, { "answer_id": 74479283, "author": "Nuri Taş", "author_id": 19255749, "author_profile": "https://Stackoverflow.com/users/19255749", "pm_score": 0, "selected": false, "text": "parse" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11019692/" ]
74,479,183
<pre><code>enter code here i = 0 sums = [] while i &lt;= 1000: if i%3==0 or i%5==0: sums.append(i) i=i+1 for i in sums: total = sums[i] + sums[i+1] print(total) </code></pre> <p>The problem was: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.</p> <p>Find the sum of all the multiples of 3 or 5 below 1000. After i run the above code it brings out this error</p> <pre><code>Traceback (most recent call last): File &quot;c:\Users\user\Desktop\Python projects\Multiples of 3 or 5.py&quot;, line 8, in &lt;module&gt; total = sums[i] + sums[i+1] IndexError: list index out of range </code></pre>
[ { "answer_id": 74479125, "author": "Ian Thompson", "author_id": 6509519, "author_profile": "https://Stackoverflow.com/users/6509519", "pm_score": 1, "selected": false, "text": "pd.to_datetime" }, { "answer_id": 74479283, "author": "Nuri Taş", "author_id": 19255749, "author_profile": "https://Stackoverflow.com/users/19255749", "pm_score": 0, "selected": false, "text": "parse" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17957425/" ]
74,479,192
<p>I have a pandas dataframe:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Reference</th> <th>timestamp</th> <th>sub_reference</th> <th>datatype_indicator</th> <th>figure</th> </tr> </thead> <tbody> <tr> <td>REF1</td> <td>2022-09-01</td> <td>10</td> <td>A</td> <td>23.6</td> </tr> <tr> <td>REF1</td> <td>2022-09-01</td> <td>48</td> <td>B</td> <td>25.8</td> </tr> <tr> <td>REF1</td> <td>2022-09-02</td> <td>10</td> <td>A</td> <td>17.4</td> </tr> <tr> <td>REF1</td> <td>2022-10-01</td> <td>10</td> <td>A</td> <td>23.6</td> </tr> <tr> <td>REF1</td> <td>2022-10-01</td> <td>48</td> <td>B</td> <td>25.8</td> </tr> <tr> <td>REF1</td> <td>2022-10-02</td> <td>10</td> <td>A</td> <td>17.4</td> </tr> <tr> <td>REF2</td> <td>2022-09-01</td> <td>10</td> <td>A</td> <td>23.6</td> </tr> <tr> <td>REF2</td> <td>2022-09-01</td> <td>48</td> <td>B</td> <td>25.8</td> </tr> <tr> <td>REF2</td> <td>2022-09-02</td> <td>10</td> <td>A</td> <td>17.4</td> </tr> <tr> <td>REF2</td> <td>2022-10-01</td> <td>11</td> <td>A</td> <td>23.6</td> </tr> <tr> <td>REF2</td> <td>2022-10-01</td> <td>47</td> <td>B</td> <td>25.8</td> </tr> <tr> <td>REF2</td> <td>2022-10-02</td> <td>10</td> <td>A</td> <td>17.4</td> </tr> <tr> <td>REF3</td> <td>2022-09-01</td> <td>10</td> <td>A</td> <td>23.6</td> </tr> <tr> <td>REF3</td> <td>2022-09-01</td> <td>48</td> <td>B</td> <td>25.8</td> </tr> <tr> <td>REF3</td> <td>2022-09-02</td> <td>10</td> <td>A</td> <td>17.4</td> </tr> <tr> <td>REF3</td> <td>2022-10-01</td> <td>11</td> <td>A</td> <td>23.6</td> </tr> <tr> <td>REF3</td> <td>2022-10-01</td> <td>47</td> <td>B</td> <td>25.8</td> </tr> <tr> <td>REF3</td> <td>2022-10-02</td> <td>10</td> <td>A</td> <td>17.4</td> </tr> </tbody> </table> </div> <p>I need to group the data by 'Reference' and the month in 'timestamp' to produce an aggregated value of 'figure' for the reference/month..</p> <p>I am trying the below code, but receive <em>TypeError: unhashable type: 'Series'</em></p> <pre><code>dg = df1.groupby([ pd.Grouper('reference'), pd.Grouper(df1['timestamp'].dt.month) ]).sum() dg.index = dg.index.strftime('%B') print(dg) </code></pre>
[ { "answer_id": 74479347, "author": "Naveed", "author_id": 3494754, "author_profile": "https://Stackoverflow.com/users/3494754", "pm_score": 0, "selected": false, "text": "# create a year-month from teh date\n# groupby and sum figure\ndf['month'] = pd.to_datetime(df['timestamp']).dt.strftime('%Y-%b')\nout= df.groupby(['Reference','month' ], as_index=False)['figure'].sum()\n\nout\n" }, { "answer_id": 74479393, "author": "JohnFrum", "author_id": 13927459, "author_profile": "https://Stackoverflow.com/users/13927459", "pm_score": 2, "selected": true, "text": "pd.Grouper" }, { "answer_id": 74479422, "author": "Panda Kim", "author_id": 20430449, "author_profile": "https://Stackoverflow.com/users/20430449", "pm_score": 0, "selected": false, "text": "grouper = pd.PeriodIndex(df['timestamp'], freq='M')\ndf.groupby(['Reference', grouper])['figure'].sum().reset_index()\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20410122/" ]
74,479,220
<p>Wondering if there would be a neat way to use <code>List Comprehension</code> to accomplish removing an element from a list based on a bool.</p> <h1>example</h1> <pre><code>test_list = [ &quot;apple&quot;, &quot;orange&quot;, &quot;grape&quot;, &quot;lemon&quot; ] apple = True if apple: test_list.remove(&quot;apple&quot;) print(test_list) </code></pre> <h1>expected output</h1> <pre><code>['orange', 'grape', 'lemon'] </code></pre> <p>I know I could so something like:</p> <pre><code>test_list = [x for x in test_list if &quot;apple&quot; not in x] </code></pre> <p>But wondering if I could use a bool flag to do this instead of a string as I only want to to run if the bool is <code>True</code>.</p>
[ { "answer_id": 74479279, "author": "9769953", "author_id": 9769953, "author_profile": "https://Stackoverflow.com/users/9769953", "pm_score": 2, "selected": true, "text": "test_list = [x for x in test_list if not (apple and x == \"apple\")]\n" }, { "answer_id": 74479625, "author": "Khaled DELLAL", "author_id": 15852600, "author_profile": "https://Stackoverflow.com/users/15852600", "pm_score": 0, "selected": false, "text": "test_list" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15126763/" ]
74,479,233
<p>Parse int is messing up my file scanning I'm basically trying to read the first number in this txt document and use that as the number to implement within a for loop. My code runs well without including it but I want to use this to continue with this small project.</p> <pre><code> { int i=0; while(inFile.hasNextLine()){ String line = inFile.nextLine(); //int num = Integer.parseInt(line); if(line.toLowerCase().equals(&quot;basketball&quot;)){ AllSports.add(new Basketball(i)); } if(line.toLowerCase().equals(&quot;football&quot;)){ AllSports.add(new Football(i)); } for(Sports obj:AllSports){ obj.Score_Med(); obj.Score_Med(); } i++; } } </code></pre> <p>I commented the parseInt line, I've also tried .nextInt and it still gives me an error. My txt file currently looks like this:</p> <p>3 Basketball Basketball Football</p> <p>and the error I'm getting is</p> <pre><code>File name?: input.txt Exception in thread &quot;main&quot; java.lang.NumberFormatException: For input string: &quot;Basketball&quot; at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67) at java.base/java.lang.Integer.parseInt(Integer.java:665) at java.base/java.lang.Integer.parseInt(Integer.java:781) at Sport_Runner.main(Sport_Runner.java:24) </code></pre> <p>My txt file:</p> <pre><code>3 Basketball Basketball Football </code></pre> <p>Line 24 is where the parseInt line is.</p>
[ { "answer_id": 74479279, "author": "9769953", "author_id": 9769953, "author_profile": "https://Stackoverflow.com/users/9769953", "pm_score": 2, "selected": true, "text": "test_list = [x for x in test_list if not (apple and x == \"apple\")]\n" }, { "answer_id": 74479625, "author": "Khaled DELLAL", "author_id": 15852600, "author_profile": "https://Stackoverflow.com/users/15852600", "pm_score": 0, "selected": false, "text": "test_list" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18336823/" ]
74,479,254
<p>I have a .txt file with lines such as &quot;G1 X174.774 Y46.362 E1.48236&quot;, &quot;M73 Q1 S245&quot;, all with one letter then a number and then a space. I'm trying to create a dataframe such that each row is a line from my file and each column is a letter. If my file were just the two lines above, my resulting dataframe would be</p> <pre><code>G X Y E M Q S 1 174.774 46.362 1.48236 0 0 0 0 0 0 0 73 1 245 </code></pre> <p>So far I have a dataframe with the columns of all possible letters in the .txt file, and the .txt file is now represented as a list of strings representing each line of the file. As of now I can only figure out how to add each line individually to the df with the following for loop:</p> <pre><code>for j in tqdm(range(len(lines))): line = lines[j] points = line.split() k = [x[0] for x in points] v = [x[1:] for x in points] line_dict = dict(zip(k, v)) df.loc[j] = pd.Series(line_dict) </code></pre> <p>This gives me my desired result (the unspecified values are NaN, but I can change these to zero later), but as my files have 200k+ lines, it's taking about an hour per file. Is there a faster way I could do this? I've been trying to think of a way to use list comprehension, but using the dict is confusing me a bit, and I'm not sure how much faster that would make things anyway. I haven't been able to find much on stackoverflow about this subject, but if I missed something please feel free to share the link with me! Thanks!</p>
[ { "answer_id": 74479423, "author": "juanpa.arrivillaga", "author_id": 5014455, "author_profile": "https://Stackoverflow.com/users/5014455", "pm_score": 2, "selected": true, "text": "df.loc[j] = pd.Series(line_dict)\n" }, { "answer_id": 74479451, "author": "LEGION GREEN", "author_id": 17495765, "author_profile": "https://Stackoverflow.com/users/17495765", "pm_score": 0, "selected": false, "text": "sep" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17135502/" ]
74,479,263
<p>I am trying to set to &quot;Other&quot; the names which are not in the top 3 values by group (and the top 3 will be &quot;TOP&quot;). I tried this, and i really don't know why it's not working...</p> <pre><code>x &lt;- data.frame( Groupe=c(rep(&quot;a&quot;, 10), rep(&quot;b&quot;, 10)), Value=c(runif(20)*20), Name=c(&quot;aa&quot;,&quot;bb&quot;,&quot;cc&quot;,&quot;dd&quot;,&quot;ee&quot;, &quot;ff&quot;,&quot;zz&quot;,&quot;yy&quot;,&quot;oo&quot;,&quot;uu&quot;) ) f &lt;- x %&gt;% group_by(Groupe) %&gt;% mutate(test = ifelse(Name %in% slice_max(., order_by=Value, n=3)$Name, &quot;TOP&quot;, &quot;Other&quot;)) %&gt;% ungroup() </code></pre>
[ { "answer_id": 74479540, "author": "Gregor Thomas", "author_id": 903061, "author_profile": "https://Stackoverflow.com/users/903061", "pm_score": 3, "selected": true, "text": "slice_max(., order_by=Value, n=3)$Name" }, { "answer_id": 74479543, "author": "Jamie", "author_id": 11564586, "author_profile": "https://Stackoverflow.com/users/11564586", "pm_score": 1, "selected": false, "text": "x %>%\n group_by(Groupe) %>%\n arrange(desc(Value), .by_group = T) %>%\n # mutate(test = ifelse(Value %in% head(Value,3), \"TOP\", \"Other\")) %>% \n mutate(test = ifelse(row_number() <= 3, \"TOP\", \"Other\")) %>% \n ungroup()\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13433781/" ]
74,479,273
<p>I need a regex to change this:</p> <pre class="lang-css prettyprint-override"><code>.my-class { @apply .p-4 .bg-red-500; } </code></pre> <p>into this:</p> <pre class="lang-css prettyprint-override"><code>.my-class { @apply p-4 bg-red-500; } </code></pre> <p>I found this regex but it is not working:</p> <pre><code>(?&lt;=@apply.*)\. </code></pre> <p>any ideas?</p>
[ { "answer_id": 74480286, "author": "Wiktor Stribiżew", "author_id": 3832970, "author_profile": "https://Stackoverflow.com/users/3832970", "pm_score": 2, "selected": true, "text": "regex" }, { "answer_id": 74487098, "author": "Stefan Mielke", "author_id": 738345, "author_profile": "https://Stackoverflow.com/users/738345", "pm_score": 0, "selected": false, "text": "<?php\nforeach(glob('./site/assets/stylesheets/' . sprintf(\"**/*.%s\", 'sass')) as $file) {\n $contents = file_get_contents($file);\n $regex = '/((?:\\G(?!^)|@apply)[^.\\r\\n]*)\\./m';\n $subst = '$1';\n\n $result = preg_replace($regex, $subst, $contents);\n\n file_put_contents($file, $result);\n echo \"written $file\";\n}\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/738345/" ]
74,479,293
<p>I want to hide a link if the records are less than 6. The code that I'm using -</p> <pre><code>var link = document.getElementById('id-name'); if (index&lt;=4){ link.style.visibility = 'hidden'; } else{ link.style.visibility = 'visible'; } </code></pre> <p>Its working fine if I have 1 record present. But, if I have 0 records its showing the link.</p> <p>How to hide link if the record is 0.</p> <p>UPDATE -</p> <p>Sharing full code for more clarity.</p> <pre><code>function getfunction(token) { httpRequest = new XMLHttpRequest(); httpRequest.open(&quot;GET&quot;, &quot;/path&quot;); httpRequest.onreadystatechange = function () { if (httpRequest.readyState === 4) { if (httpRequest.status === 401) { SignOut(); } else { var data = JSON.parse(httpRequest.response); var d = $(data).get().reverse(); $.each(d, function(index, itemData) { var link = document.getElementById('id-name'); if (index&lt;=4){ link.style.visibility = 'hidden'; } else{ link.style.visibility = 'visible'; } }); } } }; } </code></pre>
[ { "answer_id": 74480286, "author": "Wiktor Stribiżew", "author_id": 3832970, "author_profile": "https://Stackoverflow.com/users/3832970", "pm_score": 2, "selected": true, "text": "regex" }, { "answer_id": 74487098, "author": "Stefan Mielke", "author_id": 738345, "author_profile": "https://Stackoverflow.com/users/738345", "pm_score": 0, "selected": false, "text": "<?php\nforeach(glob('./site/assets/stylesheets/' . sprintf(\"**/*.%s\", 'sass')) as $file) {\n $contents = file_get_contents($file);\n $regex = '/((?:\\G(?!^)|@apply)[^.\\r\\n]*)\\./m';\n $subst = '$1';\n\n $result = preg_replace($regex, $subst, $contents);\n\n file_put_contents($file, $result);\n echo \"written $file\";\n}\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15439038/" ]
74,479,313
<p>This is a select &amp; option in HTML. I use jquery here. I need to fetch the value of both select and pass the values to ajax.php where I need to use both values to check in my database and proceed with another dependent dropdown.</p> <pre><code>&lt;label&gt;Select Number: &lt;/label&gt; &lt;select id= &quot;number&quot; onchange=&quot;FetchState(this.value)&quot; required&gt; &lt;option value=&quot;0&quot;&gt;-- 0 --&lt;/option&gt; &lt;option value=&quot;1&quot;&gt;-- 1 --&lt;/option&gt; &lt;option value=&quot;2&quot;&gt;-- 2 --&lt;/option&gt; &lt;option value=&quot;3&quot;&gt;-- 3 --&lt;/option&gt; &lt;/select&gt; &lt;label&gt;Select letter: &lt;/label&gt; &lt;select id=&quot;alphabet&quot; required&gt; &lt;option value=&quot;a&quot;&gt;-- a --&lt;/option&gt; &lt;option value=&quot;b&quot;&gt;-- b --&lt;/option&gt; &lt;option value=&quot;c&quot;&gt;-- c --&lt;/option&gt; &lt;option value=&quot;d&quot;&gt;-- d --&lt;/option&gt; &lt;/select&gt; &lt;select id=&quot;dependent&quot;&gt; &lt;/select&gt; </code></pre> <p>This is my script code written below.</p> <pre><code>function FetchState(id) { $(&quot;#dependent&quot;).html(''); $.ajax({ type: &quot;POST&quot;, url: &quot;ajax.php&quot;, data: { number: id, }, success: function(data) { $(&quot;#dependent&quot;).html(data); } }); } &lt;/script&gt; </code></pre> <p>I need to pass two values to PHP via jquery(ajax) to continue further. Here both letter and alphabet value should be get and pass as data in jquery to ajax.php</p>
[ { "answer_id": 74480286, "author": "Wiktor Stribiżew", "author_id": 3832970, "author_profile": "https://Stackoverflow.com/users/3832970", "pm_score": 2, "selected": true, "text": "regex" }, { "answer_id": 74487098, "author": "Stefan Mielke", "author_id": 738345, "author_profile": "https://Stackoverflow.com/users/738345", "pm_score": 0, "selected": false, "text": "<?php\nforeach(glob('./site/assets/stylesheets/' . sprintf(\"**/*.%s\", 'sass')) as $file) {\n $contents = file_get_contents($file);\n $regex = '/((?:\\G(?!^)|@apply)[^.\\r\\n]*)\\./m';\n $subst = '$1';\n\n $result = preg_replace($regex, $subst, $contents);\n\n file_put_contents($file, $result);\n echo \"written $file\";\n}\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19869127/" ]
74,479,316
<p>I have a dictionary where the key is a list</p> <pre><code>cfn = {('A', 'B'): 1, ('A','C'): 2 , ('A', 'D'): 3} genes = ['A', 'C', 'D', 'E'] </code></pre> <p>I am trying to get a value from the dictionary if the gene pairs in the key exist in a list together. My attempt is as follows, however I get <code>TypeError: unhashable type: 'list'</code></p> <pre><code>def create_networks(genes, cfn): network = list() for i in range(0, len(genes)): for j in range(1, len(genes)): edge = cfn.get([genes[i], genes[j]],0) if edge &gt; 0: network.append([genes[i], genes[j], edge]) </code></pre> <p>desired output:</p> <pre><code>network = [['A','C', 2], ['A', 'D', 3]] </code></pre> <p>solution based on comments and answer below: <code>edge = cfn.get((genes[i], genes[j]),0)</code></p>
[ { "answer_id": 74479344, "author": "Wolric", "author_id": 20163209, "author_profile": "https://Stackoverflow.com/users/20163209", "pm_score": 2, "selected": true, "text": "cfn" }, { "answer_id": 74479489, "author": "Tirth", "author_id": 11717445, "author_profile": "https://Stackoverflow.com/users/11717445", "pm_score": 0, "selected": false, "text": "cfn = {'AB': 1, 'AC': 2 , 'AD': 3}\ngenes = ['A', 'C', 'D', 'E']\n\ndef create_networks(genes, cfn):\n network = []\n for i in range(0, len(genes)):\n for j in range(1, len(genes)):\n keyy = genes[i]+''+genes[j]\n if keyy in cfn.keys():\n edge2 = cfn[genes[i]+''+genes[j]]\n if edge2 > 0:\n network.append([genes[i], genes[j], edge2])\n return network\n\nprint(create_networks(genes,cfn))\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12369606/" ]
74,479,334
<p>I have a dataframe 'df1' with a string column 'Field_notes' of various information that looks like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Alt_ID</th> <th>Field_notes</th> </tr> </thead> <tbody> <tr> <td></td> <td>JMs # 04J0342</td> </tr> <tr> <td></td> <td>JMs # 04J0343</td> </tr> <tr> <td></td> <td>JMs # 04J0344</td> </tr> <tr> <td></td> <td># broken leg</td> </tr> <tr> <td></td> <td>54.2</td> </tr> <tr> <td></td> <td>JMs # 04J0345</td> </tr> </tbody> </table> </div> <p>I would like to extract parts of the strings from the &quot;Field_notes&quot; column for specific rows only to the &quot;Alt_ID&quot; column. In this case, I'd like to subset rows 1,2,3,6 so that the alphanumeric combination after &quot;JMs # &quot; is moved to the &quot;Alt_ID&quot; column, so the result looks like:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Alt_ID</th> <th>Field_notes</th> </tr> </thead> <tbody> <tr> <td>04J0342</td> <td>JMs # 04J0342</td> </tr> <tr> <td>04J0343</td> <td>JMs # 04J0343</td> </tr> <tr> <td>04J0344</td> <td>JMs # 04J0344</td> </tr> <tr> <td></td> <td># broken leg</td> </tr> <tr> <td></td> <td>54.2</td> </tr> <tr> <td>04J0345</td> <td>JMs # 04J0345</td> </tr> </tbody> </table> </div> <p>The tricky part is that there are so many combinations of information in Field_notes that I probably can't rely on character patterns and instead have to rely on specifying row names/numbers. In this case, I don't want to extract anything from '# broken leg'.</p>
[ { "answer_id": 74479412, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 2, "selected": false, "text": "#" }, { "answer_id": 74479562, "author": "Santiago", "author_id": 13507658, "author_profile": "https://Stackoverflow.com/users/13507658", "pm_score": 2, "selected": false, "text": "library(dplyr)\nlibrary(stringr)\n\ndf <- data.frame(\n Alt_ID = NA_character_,\n Field_notes = c(\"JMs # 04J0342\", \"JMs # 04J0343\", \"JMs # 04J0344\",\n \"# broken leg\", \"54.2\", \"JMs # 04J0345\")\n)\n\nid_pattern <- \"(?<=JMs # )\\\\w+\"\n\ndf %>%\n mutate(\n Alt_ID = str_extract(Field_notes, id_pattern)\n )\n# Alt_ID Field_notes\n# 1 04J0342 JMs # 04J0342\n# 2 04J0343 JMs # 04J0343\n# 3 04J0344 JMs # 04J0344\n# 4 <NA> # broken leg\n# 5 <NA> 54.2\n# 6 04J0345 JMs # 04J0345\n\n# Or equivalently:\ndf$Alt_ID <- str_extract(df$Field_notes, id_pattern)\ndf\n# Alt_ID Field_notes\n# 1 04J0342 JMs # 04J0342\n# 2 04J0343 JMs # 04J0343\n# 3 04J0344 JMs # 04J0344\n# 4 <NA> # broken leg\n# 5 <NA> 54.2\n# 6 04J0345 JMs # 04J0345\n" }, { "answer_id": 74479585, "author": "henryn", "author_id": 14348996, "author_profile": "https://Stackoverflow.com/users/14348996", "pm_score": 1, "selected": false, "text": "JMs\\\\s#\\\\s(\\\\w+)$" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7238688/" ]
74,479,339
<p>I'm looking for a solution to fix the max-height of a div related to another div in CSS, if it exceeds it should let use the scrollbar.</p> <p>I was planned to use flexbox or grid, but I do not success to the result wanted...</p> <p>The objective is to not specify any height in px but keep something flexible without JS.</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>// Not looking for JS solution</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.parent { display: flex; } .child1 { background: #eeeeee; height: 100% } .child2 { overflow: auto; max-height: 100%; background: #cccccc }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="parent"&gt; &lt;div class="child1"&gt; &lt;h2&gt;Child1&lt;/h2&gt; &lt;p&gt;Some content&lt;/p&gt; &lt;p&gt;Some content&lt;/p&gt; &lt;p&gt;Some content&lt;/p&gt; &lt;p&gt;Some content&lt;/p&gt; &lt;p&gt;Some content&lt;/p&gt; &lt;/div&gt; &lt;div class="child2"&gt; &lt;h2&gt;Child2&lt;/h2&gt; &lt;p&gt;this content height must not exceed the height of "child1"&lt;/p&gt; &lt;p&gt;this content height must not exceed the height of "child1"&lt;/p&gt; &lt;p&gt;this content height must not exceed the height of "child1"&lt;/p&gt; &lt;p&gt;this content height must not exceed the height of "child1"&lt;/p&gt; &lt;p&gt;this content height must not exceed the height of "child1"&lt;/p&gt; &lt;p&gt;this content height must not exceed the height of "child1"&lt;/p&gt; &lt;p&gt;this content height must not exceed the height of "child1"&lt;/p&gt; &lt;p&gt;this content height must not exceed the height of "child1"&lt;/p&gt; &lt;p&gt;this content height must not exceed the height of "child1"&lt;/p&gt; &lt;p&gt;this content height must not exceed the height of "child1"&lt;/p&gt; &lt;p&gt;this content height must not exceed the height of "child1"&lt;/p&gt; &lt;p&gt;this content height must not exceed the height of "child1"&lt;/p&gt; &lt;p&gt;this content height must not exceed the height of "child1"&lt;/p&gt; &lt;p&gt;this content height must not exceed the height of "child1"&lt;/p&gt; &lt;p&gt;this content height must not exceed the height of "child1"&lt;/p&gt; &lt;p&gt;this content height must not exceed the height of "child1"&lt;/p&gt; &lt;p&gt;this content height must not exceed the height of "child1"&lt;/p&gt; &lt;p&gt;this content height must not exceed the height of "child1"&lt;/p&gt; &lt;p&gt;this content height must not exceed the height of "child1"&lt;/p&gt; &lt;p&gt;this content height must not exceed the height of "child1"&lt;/p&gt; &lt;p&gt;this content height must not exceed the height of "child1"&lt;/p&gt; &lt;p&gt;this content height must not exceed the height of "child1"&lt;/p&gt; &lt;p&gt;this content height must not exceed the height of "child1"&lt;/p&gt; &lt;p&gt;this content height must not exceed the height of "child1"&lt;/p&gt; &lt;p&gt;this content height must not exceed the height of "child1"&lt;/p&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74479412, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 2, "selected": false, "text": "#" }, { "answer_id": 74479562, "author": "Santiago", "author_id": 13507658, "author_profile": "https://Stackoverflow.com/users/13507658", "pm_score": 2, "selected": false, "text": "library(dplyr)\nlibrary(stringr)\n\ndf <- data.frame(\n Alt_ID = NA_character_,\n Field_notes = c(\"JMs # 04J0342\", \"JMs # 04J0343\", \"JMs # 04J0344\",\n \"# broken leg\", \"54.2\", \"JMs # 04J0345\")\n)\n\nid_pattern <- \"(?<=JMs # )\\\\w+\"\n\ndf %>%\n mutate(\n Alt_ID = str_extract(Field_notes, id_pattern)\n )\n# Alt_ID Field_notes\n# 1 04J0342 JMs # 04J0342\n# 2 04J0343 JMs # 04J0343\n# 3 04J0344 JMs # 04J0344\n# 4 <NA> # broken leg\n# 5 <NA> 54.2\n# 6 04J0345 JMs # 04J0345\n\n# Or equivalently:\ndf$Alt_ID <- str_extract(df$Field_notes, id_pattern)\ndf\n# Alt_ID Field_notes\n# 1 04J0342 JMs # 04J0342\n# 2 04J0343 JMs # 04J0343\n# 3 04J0344 JMs # 04J0344\n# 4 <NA> # broken leg\n# 5 <NA> 54.2\n# 6 04J0345 JMs # 04J0345\n" }, { "answer_id": 74479585, "author": "henryn", "author_id": 14348996, "author_profile": "https://Stackoverflow.com/users/14348996", "pm_score": 1, "selected": false, "text": "JMs\\\\s#\\\\s(\\\\w+)$" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3472601/" ]
74,479,351
<p>We have an application that validate user credentials with our internal ActiveDirectory domain. To do so, it uses the PrincipalContext::ValidateCredentials method from the .NET Framework.</p> <p>While investigating another issue, we discovered that this method return true even when the password is expired. This result in users being able to access one of our internet systems despite having an expired password for months, even years in some cases. This seems strange, and a severe security flaw that we need to fix now that we're aware of it.</p> <p>I tried looking up online about this behavior, but so far I found nothing. As far as I could tell, this method is really supposed to reject credentials if there is anything wrong with the account. For example, it does return false when the account is locked.</p> <p>I doubt that this a bug in the ValidateCredential method itself. Its been around too long for that. It's fairly simple to use, so I don't think we screwed up here. Here's our code :</p> <pre><code>using (PrincipalContext context = new PrincipalContext(ContextType.Domain, domainName)) { bool valide = context.ValidateCredentials(userName, passWord); // Remaining code omitted } </code></pre> <p>So, what could be happening here? What could cause ValidateCredentials to accept expired password?</p>
[ { "answer_id": 74479412, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 2, "selected": false, "text": "#" }, { "answer_id": 74479562, "author": "Santiago", "author_id": 13507658, "author_profile": "https://Stackoverflow.com/users/13507658", "pm_score": 2, "selected": false, "text": "library(dplyr)\nlibrary(stringr)\n\ndf <- data.frame(\n Alt_ID = NA_character_,\n Field_notes = c(\"JMs # 04J0342\", \"JMs # 04J0343\", \"JMs # 04J0344\",\n \"# broken leg\", \"54.2\", \"JMs # 04J0345\")\n)\n\nid_pattern <- \"(?<=JMs # )\\\\w+\"\n\ndf %>%\n mutate(\n Alt_ID = str_extract(Field_notes, id_pattern)\n )\n# Alt_ID Field_notes\n# 1 04J0342 JMs # 04J0342\n# 2 04J0343 JMs # 04J0343\n# 3 04J0344 JMs # 04J0344\n# 4 <NA> # broken leg\n# 5 <NA> 54.2\n# 6 04J0345 JMs # 04J0345\n\n# Or equivalently:\ndf$Alt_ID <- str_extract(df$Field_notes, id_pattern)\ndf\n# Alt_ID Field_notes\n# 1 04J0342 JMs # 04J0342\n# 2 04J0343 JMs # 04J0343\n# 3 04J0344 JMs # 04J0344\n# 4 <NA> # broken leg\n# 5 <NA> 54.2\n# 6 04J0345 JMs # 04J0345\n" }, { "answer_id": 74479585, "author": "henryn", "author_id": 14348996, "author_profile": "https://Stackoverflow.com/users/14348996", "pm_score": 1, "selected": false, "text": "JMs\\\\s#\\\\s(\\\\w+)$" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19617189/" ]
74,479,362
<p>Between the dates 11/28/2023 and 10/01/2022 I know how many days there are. DATE(2023, 11, 28) - DATE(2022, 12, 02), how can I calculate that between these two dates are the months of November 2022, December 2022 to November 2023?</p>
[ { "answer_id": 74479412, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 2, "selected": false, "text": "#" }, { "answer_id": 74479562, "author": "Santiago", "author_id": 13507658, "author_profile": "https://Stackoverflow.com/users/13507658", "pm_score": 2, "selected": false, "text": "library(dplyr)\nlibrary(stringr)\n\ndf <- data.frame(\n Alt_ID = NA_character_,\n Field_notes = c(\"JMs # 04J0342\", \"JMs # 04J0343\", \"JMs # 04J0344\",\n \"# broken leg\", \"54.2\", \"JMs # 04J0345\")\n)\n\nid_pattern <- \"(?<=JMs # )\\\\w+\"\n\ndf %>%\n mutate(\n Alt_ID = str_extract(Field_notes, id_pattern)\n )\n# Alt_ID Field_notes\n# 1 04J0342 JMs # 04J0342\n# 2 04J0343 JMs # 04J0343\n# 3 04J0344 JMs # 04J0344\n# 4 <NA> # broken leg\n# 5 <NA> 54.2\n# 6 04J0345 JMs # 04J0345\n\n# Or equivalently:\ndf$Alt_ID <- str_extract(df$Field_notes, id_pattern)\ndf\n# Alt_ID Field_notes\n# 1 04J0342 JMs # 04J0342\n# 2 04J0343 JMs # 04J0343\n# 3 04J0344 JMs # 04J0344\n# 4 <NA> # broken leg\n# 5 <NA> 54.2\n# 6 04J0345 JMs # 04J0345\n" }, { "answer_id": 74479585, "author": "henryn", "author_id": 14348996, "author_profile": "https://Stackoverflow.com/users/14348996", "pm_score": 1, "selected": false, "text": "JMs\\\\s#\\\\s(\\\\w+)$" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9847636/" ]
74,479,418
<p>i have document_title variable value with lowercase letters and same value is in the dic keys with upercase letter</p> <pre><code> TITLE_MAP = { 'AUS Marketing Consent': &quot;DOCUMENT_TYPE_MARKETING_CONSENT&quot;, 'Consent &amp; History': &quot;DOCUMENT_TYPE_CONSENT&quot;, } document_title = 'aus marketing consent' </code></pre> <p>if i do this won't work with me</p> <pre><code>if document_title in TITLE_MAP.keys(): return True </code></pre> <p>I want to fulfill the condition even with the difference</p>
[ { "answer_id": 74479673, "author": "Luke B", "author_id": 8228122, "author_profile": "https://Stackoverflow.com/users/8228122", "pm_score": 1, "selected": false, "text": "casefold" }, { "answer_id": 74479677, "author": "Zeglarz", "author_id": 20532554, "author_profile": "https://Stackoverflow.com/users/20532554", "pm_score": 0, "selected": false, "text": "if document_title.upper() in TITLE_MAP.key():\n return True\n" }, { "answer_id": 74479683, "author": "Antoine Piron", "author_id": 13485655, "author_profile": "https://Stackoverflow.com/users/13485655", "pm_score": 0, "selected": false, "text": "if document_title.lower() in {k.lower() for k in TITLE_MAP.keys()}:\n print(True)\n" }, { "answer_id": 74479747, "author": "Douglas Damler", "author_id": 15173207, "author_profile": "https://Stackoverflow.com/users/15173207", "pm_score": 0, "selected": false, "text": "TITLE_MAP = {\n 'AUS Marketing Consent': \"DOCUMENT_TYPE_MARKETING_CONSENT\",\n 'Consent & History': \"DOCUMENT_TYPE_CONSENT\",\n}\n\nTITLE_MAP = {k.lower(): v for k, v in TITLE_MAP.items()}\n\ndocument_title = 'aus marketing consent'\n\nif document_title.lower() in TITLE_MAP:\n print(True)\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19416392/" ]
74,479,429
<p>Ok this topic had been discussed a lot of times, but since Haskell evolves lets consider it again to see what we can do in contemporary Haskell (by contemporary I mean GHC 9.0 - 9.2).</p> <p>Fist let me state the problem by an example. Suppose we have a function which determines a number of bytes required to store a value of a given type. We can have two instances of this function: one for fixed sized data types and other for variable sized. For example <code>Int32</code> is fixed sized and always takes 4 bytes to store regardless it's value. But <code>data C = A Int32 | B Int32 Int32</code> can be considered variable sized since it may take 4 bytes to store in case of <code>A</code> constructor or 8 bytes in case of <code>B</code> constructor. It's natural to have two classes for this:</p> <ol> <li>A class for fixed sized values. Note that value itself not required, we can use <code>Proxy</code> as a parameter to determine the size.</li> </ol> <pre class="lang-hs prettyprint-override"><code>class FixedSize a where fixedSize :: p a -&gt; Int </code></pre> <ol start="2"> <li>A class for variable sized values. The function takes a value to determine the size.</li> </ol> <pre class="lang-hs prettyprint-override"><code>class VariableSize a where variableSize :: a -&gt; Int </code></pre> <p>Now lets say we want to define a function which determines the size of a list of values. The values in the list can be either fixed or variable sized. So it's natural to have two functions:</p> <ol> <li>One for a list of fixed sized values.</li> </ol> <pre class="lang-hs prettyprint-override"><code>listSize :: (FixedSize a) =&gt; [a] -&gt; Int listSize _ = (* fixedSize (Proxy @a) ) . length </code></pre> <ol start="2"> <li>Other for a list of variable sized values.</li> </ol> <pre class="lang-hs prettyprint-override"><code>listSize :: (VariableSize a) =&gt; [a] -&gt; Int listSize = sum . map variableSize </code></pre> <p>However it is not possible to use a naive approach, the following basically won't compile:</p> <pre class="lang-hs prettyprint-override"><code>class Size a where size :: a -&gt; Int instance (FixedSize a) =&gt; Size [a] where size = _ = (* fixedSize (Proxy @a) ) . length instance (VariableSize a) =&gt; Size [a] where size = sum . map variableSize </code></pre> <p>This happens because Haskell relies on type when selecting an instance, but not on the context. There are trick to overcome this limitation described here: <a href="https://wiki.haskell.org/GHC/AdvancedOverlap" rel="nofollow noreferrer">https://wiki.haskell.org/GHC/AdvancedOverlap</a>. The basic idea is to define type-level predicate which reflects the context and use it to select an instance using multi-parameter type classes an overlapping instances. In this case Haskell will be able to select more specific instance based on the type parameters. By &quot;more specific&quot; I mean matching type-level predicates.</p> <p>The proposed approaches can be divided into three groups conditionally.</p> <ol> <li><p>Use closed type families to define a type-level predicate (&quot;Solution 3&quot; according to the wiki-page). This is not usable approach because it will disallow user to define instances for custom data types. I won't discuss it further.</p> </li> <li><p>Define the predicate as a separate type class, define default (fallback) overlappable instance for the predicate (&quot;Solution 1&quot; according to the wiki-page). This is working approach, but it requres from user to maintain additional instances for the predicate.</p> </li> <li><p>Use open type families (&quot;Solution 2&quot;). I'd like to discuss slightly modified version of this approach.</p> </li> </ol> <pre class="lang-hs prettyprint-override"><code>class Size a where size :: a -&gt; Int class FixedSize a where type FixedSized a :: Bool type FixedSized a = 'True fixedSize :: p a -&gt; Int #include &quot;MachDeps.h&quot; instance FixedSize Int where fixedSize _ = SIZEOF_HSINT class ListSize (isElemFixed :: Bool) a where listSize :: p isElemFixed -&gt; a -&gt; Int instance (ListSize (FixedSized a) [a]) =&gt; Size [a] where size = listSize $ Proxy @(FixedSized a) instance (FixedSize a) =&gt; ListSize 'True [a] where listSize _ = trace &quot;elem size is fiхed&quot; . (* fixedSize (Proxy @a) ) . length instance {-# INCOHERENT #-} (Size a) =&gt; ListSize any [a] where listSize _ = trace &quot;elem size is variable&quot; . sum . map size test1 = size [1::Int,2,3] test2 = size [[1::Int], [2,3,4]] </code></pre> <p>This approach seems the most convenient user-wise to me. The separate type-level predicate facility is still required and user can still mess up by defining something like this explicitly:</p> <pre class="lang-hs prettyprint-override"><code>class FixedSize UserType where type FixedSized UserType = 'False </code></pre> <p>but it just works as expected when using defaults.</p> <p>However, it reqires incoherent instances. And I'm scare of incoherent instances. Because the Hasllkel documentation leterelly says that in case of incoherent instances the compiler is free to choose any instance it wants which looks unpredictable. Now I'll probably doing a bad thing by asking 4 questions in one post but they all related:</p> <ol> <li><p>Why incoherent instances are needed here exactly? Does not <code>ListSize 'True [a]</code> just overlap with <code>ListSize any [a]</code> and could be picked when first paramenter evaluates to <code>True</code>?</p> </li> <li><p>Is there a way to break this code? I mean, to make a complier to choose <code>ListSize any [a]</code> (variable sized elem code) when <code>FixedSize a</code> is in scope?</p> </li> <li><p>Are these instances really incoherent? Probably compiler just can't prove coherence, so how it can be proven manually?</p> </li> <li><p>Is there a completely different approach to solve this problem in modern Haskell? By the problem I mean a partial exapmle above, selecting an appropriate function to determine the size of a list of values based on the type of the values in compile time.</p> </li> </ol>
[ { "answer_id": 74480002, "author": "Iceland_jack", "author_id": 165806, "author_profile": "https://Stackoverflow.com/users/165806", "pm_score": 2, "selected": false, "text": "{-# OPTIONS_GHC -fplugin=IfSat.Plugin #-}\n\nimport Data.Constraint.If ( type (||) (dispatch) )\n\ninstance FixedSize a || VariableSize a => Size [a] where\n size :: [a] -> Int\n size as = dispatch fixed variable where\n\n fixed :: FixedSize a => Int\n fixed = fixedSize (Proxy @a) * length as\n\n variable :: VariableSize a => Int\n variable = sum (map variableSize as)\n" }, { "answer_id": 74480294, "author": "chi", "author_id": 3234959, "author_profile": "https://Stackoverflow.com/users/3234959", "pm_score": 2, "selected": false, "text": "data Scale a = Fixed Int | Variable (a -> Int)\n\nclass Size a where\n scale :: Scale a\n\ninstance Size Int where\n scale = Fixed 4\n\ninstance Size a => Size [a] where\n scale = case scale @a of\n Fixed n -> Variable (\\xs -> n * length xs)\n Variable s -> Variable (\\xs -> sum $ map s xs)\n\nsize :: forall a. Size a => a -> Int\nsize x = case scale @a of\n Fixed n -> n\n Variable s -> s x\n" }, { "answer_id": 74480858, "author": "Daniel Wagner", "author_id": 791604, "author_profile": "https://Stackoverflow.com/users/791604", "pm_score": 0, "selected": false, "text": "deriving" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2236092/" ]
74,479,431
<p>I have 96 bam files, How do I output the txt file with the unique sample IDs? I am looping through the bam files, but need to assign unique output files. For example: SC845414.txt</p> <pre><code>#Typical Bam Files: SC845414-CTGATCGT-GCGCATAT_Aligned.sortedByCoord.out.bam SC845425-TGTGACTG-AGCCTATC_Aligned.sortedByCoord.out.bam #!/bin/bash #SBATCH --mem=110g #SBATCH --cpus-per-task=12 #SBATCH --time=10-00:00:00 module load python DIR=/PATH/* for d in $DIR; do python -m HTSeq.scripts.count -s yes -f bam &quot;$d&quot; /PATH1/gencode.v35.annotation.gtf &gt; /PATH3/HTseq/SC845414.txt done </code></pre>
[ { "answer_id": 74479545, "author": "Nick S", "author_id": 726773, "author_profile": "https://Stackoverflow.com/users/726773", "pm_score": 2, "selected": true, "text": "for d in $DIR; do\n id=$(basename \"$d\" | cut -f 1 -d -)\n python -m HTSeq.scripts.count -s yes -f bam \"$d\" /PATH1/gencode.v35.annotation.gtf > \"/PATH3/HTseq/$id.txt\"\ndone\n" }, { "answer_id": 74481466, "author": "tomc", "author_id": 5714068, "author_profile": "https://Stackoverflow.com/users/5714068", "pm_score": 0, "selected": false, "text": "for d in $DIR; do\n fname=${d##*/}\n python -m HTSeq.scripts.count -s yes -f bam \"$d\" /PATH1/gencode.v35.annotation.gtf > \"/PATH3/HTseq/${fname%%-*}.txt\"\ndone\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5640213/" ]
74,479,435
<p>I was wondering what's the &quot;best&quot; or most common way to use semantic elements in HTML. I know what they are and what they do, but should I use them like that :</p> <pre><code>&lt;section&gt; &lt;div class=&quot;info&quot;&gt; ... </code></pre> <p>or like that :</p> <pre><code>&lt;section class=&quot;info&quot;&gt; ... </code></pre> <p>Is it wrong to use one or another ? Are both actually &quot;valid&quot; ?</p> <p>Another example would be the header element :</p> <pre><code>&lt;body&gt; &lt;header&gt; &lt;div class=&quot;logo&quot;&gt; ... </code></pre> <p>or should I directly start with</p> <pre><code>&lt;body&gt; &lt;header class=&quot;logo&quot;&gt; ... </code></pre> <p>Maybe this question might sound strange for advanced developers but for a beginner it might not be obvious and I didn't really find a clear answer.</p> <p>I'm personally using the &quot;long&quot; version and started questioning myself when I started looking at other people's codes.</p>
[ { "answer_id": 74480427, "author": "Danyal Chatha", "author_id": 20401157, "author_profile": "https://Stackoverflow.com/users/20401157", "pm_score": 1, "selected": false, "text": "<section>\n <div class=\"info\">\n <h1>Information</h1>\n </div>\n</section>\n" }, { "answer_id": 74480850, "author": "offkee", "author_id": 16357891, "author_profile": "https://Stackoverflow.com/users/16357891", "pm_score": 1, "selected": false, "text": "<section class=blogPost>\n<!-- section acts as a container for content -->\n<h1>Introduction to HTML</h1>\n<p> blah blah blah blah </p>\n<!-- h1 and p are the actual content -->\n</section>" }, { "answer_id": 74484026, "author": "budi.sann", "author_id": 20339580, "author_profile": "https://Stackoverflow.com/users/20339580", "pm_score": 2, "selected": false, "text": "<body>\n<header class=\"logo\">\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19111213/" ]
74,479,445
<p>Say I have a dataframe 'df':</p> <p><a href="https://i.stack.imgur.com/CvQbt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CvQbt.png" alt="enter image description here" /></a></p> <p>I would like to add an additional column named 'Day No' which adds a count to each day. Desired output below:</p> <p><a href="https://i.stack.imgur.com/uiiqn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uiiqn.png" alt="enter image description here" /></a></p> <p>This wont reset at the end of each month, the count will just continue. For example at the end of the year it will read 365 for all the 1 hour entries in the last day of the year. The dtype of column 'Datetime' is datetime64[ns].</p> <p>Any help greatly appreciated, Thanks.</p>
[ { "answer_id": 74479550, "author": "Nuri Taş", "author_id": 19255749, "author_profile": "https://Stackoverflow.com/users/19255749", "pm_score": 0, "selected": false, "text": "map" }, { "answer_id": 74479754, "author": "Naveed", "author_id": 3494754, "author_profile": "https://Stackoverflow.com/users/3494754", "pm_score": 3, "selected": true, "text": "# convert to datetime and extract dayofyear\n\ndf['Day No']= pd.to_datetime(df['DateTime'], dayfirst=True).dt.dayofyear\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7605946/" ]
74,479,505
<p>I am using a task template in Azure Devops which is like the snippet below</p> <pre><code> - task: sampletask@0 inputs: flag1: true flag2: true </code></pre> <p>The flag1&amp;2 are expected to be boolean values there. But instead of making it hardcoded as 'true', there is an option to pass a string as an external variable to set the value.</p> <p>But when I try to declare externalVar1&amp;2 externally as 'true', and try:</p> <pre><code> - task: sampletask@0 inputs: flag1: $[$(externalVar1), 'true')] --- Incorrect type. Expected &quot;boolean&quot;. flag2: $[$(externalVar2), 'true')] --- Incorrect type. Expected &quot;boolean&quot;. </code></pre> <p>So is there a feasible way to evaluate an external string expression, say <code>$(expr)</code>, into a boolean variable/object and pass into the target flag parameters that expect boolean type?</p>
[ { "answer_id": 74479550, "author": "Nuri Taş", "author_id": 19255749, "author_profile": "https://Stackoverflow.com/users/19255749", "pm_score": 0, "selected": false, "text": "map" }, { "answer_id": 74479754, "author": "Naveed", "author_id": 3494754, "author_profile": "https://Stackoverflow.com/users/3494754", "pm_score": 3, "selected": true, "text": "# convert to datetime and extract dayofyear\n\ndf['Day No']= pd.to_datetime(df['DateTime'], dayfirst=True).dt.dayofyear\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14398751/" ]
74,479,513
<p>I have an array of objects below. This is the raw data</p> <pre><code>const data = [ {id:1, sItem:&quot;This is javascript&quot;, status:&quot;trending&quot;}, {id:2, sItem:&quot;javascript is fun&quot;, status:&quot;trending&quot;}, {id:3, sItem:&quot;learning javascript&quot;, status:&quot;trending&quot;}, {id:4, sItem:&quot;how to code in javascript&quot;, status:&quot;trending&quot;}, {id:5, sItem:&quot;javascript will rule&quot;, status:&quot;trending&quot;}, {id:6, sItem:&quot;javascript can do anything&quot;, status:&quot;trending&quot;} ] </code></pre> <p>And I want to search the <strong>sItem</strong> properties with the keyword <strong>javascript</strong> and reorder them so that where ever <em>javascript</em> comes at the start of <strong>sItem</strong> that element should come first with index 0. Other objects starting with <em>javascript</em> should come next followed by the rest of the array objects.</p> <p><strong>expected o/p</strong></p> <pre><code>const data = [ {id:2, sItem:&quot;javascript is fun&quot;, status:&quot;trending&quot;}, {id:5, sItem:&quot;javascript will rule&quot;, status:&quot;trending&quot;}, {id:6, sItem:&quot;javascript can do anything&quot;, status:&quot;trending&quot;}, {id:1, sItem:&quot;This is javascript&quot;, status:&quot;trending&quot;}, {id:3, sItem:&quot;learning javascript&quot;, status:&quot;trending&quot;}, {id:4, sItem:&quot;how to code in javascript&quot;, status:&quot;trending&quot;} ] </code></pre> <p>I have tried to filter array objects <code>const search = &quot;javascript&quot; data.filter(obj =&gt; Object.values(obj).some(val =&gt; val.includes(search)))</code></p> <p>any suggestion will be useful.</p>
[ { "answer_id": 74479697, "author": "Kinglish", "author_id": 1772933, "author_profile": "https://Stackoverflow.com/users/1772933", "pm_score": 1, "selected": false, "text": "[...data.reduce((b,a) => {\nif (a.sItem.split(\" \")[0].toLowerCase() == \"javascript\") b[0].push(a);\nelse b[1].push(a);\nreturn b\n}, [[],[]]).map(m => m.sort((a,b) => a.sItem.localeCompare(b.sItem)))]\n" }, { "answer_id": 74480113, "author": "Angel Figuera", "author_id": 20382647, "author_profile": "https://Stackoverflow.com/users/20382647", "pm_score": 0, "selected": false, "text": "const filterByKeyword = (arr, keyword) => {\n const [a, b] = [[], []];\n\n for (let i = 0; i < arr.length; i++) {\n const el = arr[i];\n\n if (el.sItem.includes(keyword)) {\n if (el.sItem.startsWith(keyword)) a.push(arr[i]);\n else b.push(arr[i]);\n }\n }\n\n return [...a, ...b];\n};\n\nconsole.log(filterByKeyword(data, search));\n" }, { "answer_id": 74480275, "author": "Omkar Pattanaik", "author_id": 13779639, "author_profile": "https://Stackoverflow.com/users/13779639", "pm_score": 0, "selected": false, "text": "var ssSearch = require(\"ss-search\")\nconst data = [{id:2, sItem:\"javascript is fun\", status:\"trending\"},{id:5, sItem:\"javascript will rule\", status:\"trending\"},{id:6, sItem:\"javascript can do anything\", status:\"trending\"},{id:1, sItem:\"This is javascript\", status:\"trending\"},{id:3, sItem:\"learning javascript\", status:\"trending\"},{id:4, sItem:\"how to code in javascript\", status:\"trending\"}]\nconst searchKeys = [\"sItem\"] \nconst searchText = \"javascript\"\n\nconst results = ssSearch.search(data, searchKeys, searchText)\nconsole.log(results)\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16479883/" ]
74,479,514
<p>I was able to align the numbers by decimal points but I don't know how to add the comma. I know how to add commas using the format() but don't know how to align and add commas together. I need to align by the decimal points and have commas also.</p> <pre><code>print(f&quot;{i + 1}\t\t\t{salary :11.2f}&quot;) </code></pre> <p>This is a line inside the for loop.</p>
[ { "answer_id": 74479697, "author": "Kinglish", "author_id": 1772933, "author_profile": "https://Stackoverflow.com/users/1772933", "pm_score": 1, "selected": false, "text": "[...data.reduce((b,a) => {\nif (a.sItem.split(\" \")[0].toLowerCase() == \"javascript\") b[0].push(a);\nelse b[1].push(a);\nreturn b\n}, [[],[]]).map(m => m.sort((a,b) => a.sItem.localeCompare(b.sItem)))]\n" }, { "answer_id": 74480113, "author": "Angel Figuera", "author_id": 20382647, "author_profile": "https://Stackoverflow.com/users/20382647", "pm_score": 0, "selected": false, "text": "const filterByKeyword = (arr, keyword) => {\n const [a, b] = [[], []];\n\n for (let i = 0; i < arr.length; i++) {\n const el = arr[i];\n\n if (el.sItem.includes(keyword)) {\n if (el.sItem.startsWith(keyword)) a.push(arr[i]);\n else b.push(arr[i]);\n }\n }\n\n return [...a, ...b];\n};\n\nconsole.log(filterByKeyword(data, search));\n" }, { "answer_id": 74480275, "author": "Omkar Pattanaik", "author_id": 13779639, "author_profile": "https://Stackoverflow.com/users/13779639", "pm_score": 0, "selected": false, "text": "var ssSearch = require(\"ss-search\")\nconst data = [{id:2, sItem:\"javascript is fun\", status:\"trending\"},{id:5, sItem:\"javascript will rule\", status:\"trending\"},{id:6, sItem:\"javascript can do anything\", status:\"trending\"},{id:1, sItem:\"This is javascript\", status:\"trending\"},{id:3, sItem:\"learning javascript\", status:\"trending\"},{id:4, sItem:\"how to code in javascript\", status:\"trending\"}]\nconst searchKeys = [\"sItem\"] \nconst searchText = \"javascript\"\n\nconst results = ssSearch.search(data, searchKeys, searchText)\nconsole.log(results)\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14749171/" ]
74,479,628
<p>I have a perfect code that compares the data from one table with another (see below) which works totally fine and runs fine as well in BigQuery:</p> <pre><code>with source1 as ( select b.id, b.qty, a.price from &lt;table&gt; as a ,unnest &lt;details&gt; as b where b.status != 'canceled' ), source2 as ( select id_, qty_, price_ from &lt;table2&gt; where city != 'delhi' ) select * from source1 s1 full outer join source2 s2 on id = id_ where format('%t', s1) != format('%t', s2) </code></pre> <p>However, the code above runs into an error in <strong>sqlfluff</strong> i.e a certain SQL formatting rules checker that I can't bypass or turn off, see the error from sqlfluff below:</p> <p><strong>ERROR FROM SQLFLUFF:</strong></p> <p>*<em>'s1' found in select with more than one referenced table/view' and 's2' found in select with more than one referenced table/view</em></p> <p>Does anybody know how I can fix it ?</p>
[ { "answer_id": 74479697, "author": "Kinglish", "author_id": 1772933, "author_profile": "https://Stackoverflow.com/users/1772933", "pm_score": 1, "selected": false, "text": "[...data.reduce((b,a) => {\nif (a.sItem.split(\" \")[0].toLowerCase() == \"javascript\") b[0].push(a);\nelse b[1].push(a);\nreturn b\n}, [[],[]]).map(m => m.sort((a,b) => a.sItem.localeCompare(b.sItem)))]\n" }, { "answer_id": 74480113, "author": "Angel Figuera", "author_id": 20382647, "author_profile": "https://Stackoverflow.com/users/20382647", "pm_score": 0, "selected": false, "text": "const filterByKeyword = (arr, keyword) => {\n const [a, b] = [[], []];\n\n for (let i = 0; i < arr.length; i++) {\n const el = arr[i];\n\n if (el.sItem.includes(keyword)) {\n if (el.sItem.startsWith(keyword)) a.push(arr[i]);\n else b.push(arr[i]);\n }\n }\n\n return [...a, ...b];\n};\n\nconsole.log(filterByKeyword(data, search));\n" }, { "answer_id": 74480275, "author": "Omkar Pattanaik", "author_id": 13779639, "author_profile": "https://Stackoverflow.com/users/13779639", "pm_score": 0, "selected": false, "text": "var ssSearch = require(\"ss-search\")\nconst data = [{id:2, sItem:\"javascript is fun\", status:\"trending\"},{id:5, sItem:\"javascript will rule\", status:\"trending\"},{id:6, sItem:\"javascript can do anything\", status:\"trending\"},{id:1, sItem:\"This is javascript\", status:\"trending\"},{id:3, sItem:\"learning javascript\", status:\"trending\"},{id:4, sItem:\"how to code in javascript\", status:\"trending\"}]\nconst searchKeys = [\"sItem\"] \nconst searchText = \"javascript\"\n\nconst results = ssSearch.search(data, searchKeys, searchText)\nconsole.log(results)\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12513693/" ]
74,479,635
<p>How to show only HTML elements that match the element selected by the drop-down list ?</p> <p>I want to show in my page only the element that matchup with the value that I choose in drop-down list</p> <p>When I changed the value of select element to 3 i get the text Nodelist in the body of html</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const divs_exept_3 = document.querySelectorAll("body &gt; div:not(.element3)") const listOperations = document.querySelector('#elements'); listOperations.addEventListener('change', () =&gt; { if (listOperations.value === "3") { document.body.innerHTML = divs_exept_3; } });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="element1"&gt; &lt;p&gt; this is element 1 &lt;/p&gt; &lt;/div&gt; &lt;div class="element2"&gt; &lt;p&gt; this is element 2 &lt;/p&gt; &lt;/div&gt; &lt;div class="element3"&gt; &lt;p&gt; this is element 3 &lt;/p&gt; &lt;/div&gt; &lt;div class="element1"&gt; &lt;p&gt; this is element 1 &lt;/p&gt; &lt;/div&gt; &lt;div class="element2"&gt; &lt;p&gt; this is element 2 &lt;/p&gt; &lt;/div&gt; &lt;div class="element3"&gt; &lt;p&gt; this is element 3 &lt;/p&gt; &lt;/div&gt; &lt;select id="elements"&gt; &lt;option value="1"&gt;1&lt;/option&gt; &lt;option value="2"&gt;2&lt;/option&gt; &lt;option value="3"&gt;3&lt;/option&gt; &lt;/select&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74479697, "author": "Kinglish", "author_id": 1772933, "author_profile": "https://Stackoverflow.com/users/1772933", "pm_score": 1, "selected": false, "text": "[...data.reduce((b,a) => {\nif (a.sItem.split(\" \")[0].toLowerCase() == \"javascript\") b[0].push(a);\nelse b[1].push(a);\nreturn b\n}, [[],[]]).map(m => m.sort((a,b) => a.sItem.localeCompare(b.sItem)))]\n" }, { "answer_id": 74480113, "author": "Angel Figuera", "author_id": 20382647, "author_profile": "https://Stackoverflow.com/users/20382647", "pm_score": 0, "selected": false, "text": "const filterByKeyword = (arr, keyword) => {\n const [a, b] = [[], []];\n\n for (let i = 0; i < arr.length; i++) {\n const el = arr[i];\n\n if (el.sItem.includes(keyword)) {\n if (el.sItem.startsWith(keyword)) a.push(arr[i]);\n else b.push(arr[i]);\n }\n }\n\n return [...a, ...b];\n};\n\nconsole.log(filterByKeyword(data, search));\n" }, { "answer_id": 74480275, "author": "Omkar Pattanaik", "author_id": 13779639, "author_profile": "https://Stackoverflow.com/users/13779639", "pm_score": 0, "selected": false, "text": "var ssSearch = require(\"ss-search\")\nconst data = [{id:2, sItem:\"javascript is fun\", status:\"trending\"},{id:5, sItem:\"javascript will rule\", status:\"trending\"},{id:6, sItem:\"javascript can do anything\", status:\"trending\"},{id:1, sItem:\"This is javascript\", status:\"trending\"},{id:3, sItem:\"learning javascript\", status:\"trending\"},{id:4, sItem:\"how to code in javascript\", status:\"trending\"}]\nconst searchKeys = [\"sItem\"] \nconst searchText = \"javascript\"\n\nconst results = ssSearch.search(data, searchKeys, searchText)\nconsole.log(results)\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15789479/" ]
74,479,651
<p>I have a list object like the following:</p> <p><code>list_data &lt;- list(&quot;Red&quot;, &quot;Green&quot;, c(&quot;Purple&quot;, &quot;Yellow&quot;), &quot;Orange&quot;, c(&quot;Black&quot;,&quot;White&quot;)) </code></p> <p>I would like to drop the second observations in every character vector to get an output like this `</p> <pre><code>print(list_data)` &quot;Red, Green, Purple, Orange, Black&quot; </code></pre> <p>So I am trying to drop the second observations that are Yellow and White. How do I do it? Please note that it is a large list so I can not do it manually.</p>
[ { "answer_id": 74479697, "author": "Kinglish", "author_id": 1772933, "author_profile": "https://Stackoverflow.com/users/1772933", "pm_score": 1, "selected": false, "text": "[...data.reduce((b,a) => {\nif (a.sItem.split(\" \")[0].toLowerCase() == \"javascript\") b[0].push(a);\nelse b[1].push(a);\nreturn b\n}, [[],[]]).map(m => m.sort((a,b) => a.sItem.localeCompare(b.sItem)))]\n" }, { "answer_id": 74480113, "author": "Angel Figuera", "author_id": 20382647, "author_profile": "https://Stackoverflow.com/users/20382647", "pm_score": 0, "selected": false, "text": "const filterByKeyword = (arr, keyword) => {\n const [a, b] = [[], []];\n\n for (let i = 0; i < arr.length; i++) {\n const el = arr[i];\n\n if (el.sItem.includes(keyword)) {\n if (el.sItem.startsWith(keyword)) a.push(arr[i]);\n else b.push(arr[i]);\n }\n }\n\n return [...a, ...b];\n};\n\nconsole.log(filterByKeyword(data, search));\n" }, { "answer_id": 74480275, "author": "Omkar Pattanaik", "author_id": 13779639, "author_profile": "https://Stackoverflow.com/users/13779639", "pm_score": 0, "selected": false, "text": "var ssSearch = require(\"ss-search\")\nconst data = [{id:2, sItem:\"javascript is fun\", status:\"trending\"},{id:5, sItem:\"javascript will rule\", status:\"trending\"},{id:6, sItem:\"javascript can do anything\", status:\"trending\"},{id:1, sItem:\"This is javascript\", status:\"trending\"},{id:3, sItem:\"learning javascript\", status:\"trending\"},{id:4, sItem:\"how to code in javascript\", status:\"trending\"}]\nconst searchKeys = [\"sItem\"] \nconst searchText = \"javascript\"\n\nconst results = ssSearch.search(data, searchKeys, searchText)\nconsole.log(results)\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19473322/" ]
74,479,654
<p><strong>my Code doesent understand letters in the list i would like somone to help me fix this</strong></p> <pre><code>usernames = (BTP, btp, Btp, BTp) def username(usernames2): if usernames == input('whats your username? : ') </code></pre> <p>Its a simple username system, i plan to use for a interface im making.</p>
[ { "answer_id": 74479723, "author": "Random Davis", "author_id": 6273251, "author_profile": "https://Stackoverflow.com/users/6273251", "pm_score": 1, "selected": false, "text": "usernames" }, { "answer_id": 74479734, "author": "Wolric", "author_id": 20163209, "author_profile": "https://Stackoverflow.com/users/20163209", "pm_score": 1, "selected": true, "text": "BTP" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20427591/" ]
74,479,658
<p>Below is a small QML application. What I intended was for the application to start full screen, and on the Escape key, change it to maximized:</p> <pre class="lang-js prettyprint-override"><code>import QtQuick 2.15 import QtQuick.Window 2.15 Window { id: topLevelWindow width: 640 height: 480 visible: true title: qsTr(&quot;Hello World&quot;) visibility: Window.FullScreen Rectangle { id: rect anchors.fill: parent color: &quot;lightBlue&quot; focus: true Keys.onPressed: { if (event.key === Qt.Key_Escape) { rect.color = &quot;lightGreen&quot; topLevelWindow.visibility = Window.Maximized } } } } </code></pre> <p>What actually happens, though, is that it starts full screen as intended, but pressing Escape makes it windowed but <em><strong>not</strong></em> maximized. Pressing Escape a second time actually maximizes it.</p> <p>Is there a way to do this without making the user hit Escape twice?</p>
[ { "answer_id": 74479723, "author": "Random Davis", "author_id": 6273251, "author_profile": "https://Stackoverflow.com/users/6273251", "pm_score": 1, "selected": false, "text": "usernames" }, { "answer_id": 74479734, "author": "Wolric", "author_id": 20163209, "author_profile": "https://Stackoverflow.com/users/20163209", "pm_score": 1, "selected": true, "text": "BTP" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3684433/" ]
74,479,668
<p>Regex to validate image url which may contains extension like jpeg, jpg, gif, png</p> <p>I'm using</p> <pre><code>/\.(jpg|jpeg|png|gif|webp)(\?.*)*$/i </code></pre> <p>but it gives false for <code>https://store.storeimages.cdn-apple.com/4668/as-images.apple.com/is/macbook-air-gallery3-20201110?wid=4000&amp;hei=3072&amp;fmt=jpeg&amp;qlt=80&amp;.v=1603399121000</code></p> <p>I'm expecting a regex which can give true if this extensions like jpg, jpeg, png, gif, webp are present in url.</p>
[ { "answer_id": 74479723, "author": "Random Davis", "author_id": 6273251, "author_profile": "https://Stackoverflow.com/users/6273251", "pm_score": 1, "selected": false, "text": "usernames" }, { "answer_id": 74479734, "author": "Wolric", "author_id": 20163209, "author_profile": "https://Stackoverflow.com/users/20163209", "pm_score": 1, "selected": true, "text": "BTP" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19439659/" ]
74,479,688
<p>I have a script for creating accounts that outputs the following:</p> <pre><code>creating user in XYZ: username: testing firstName: Bob lastName:Test email:auto999@nowhere.com password:gWY6*Pja&amp;4 </code></pre> <p>So, I need to create a python script that will store the username and password in a csv file.</p> <p>I tried splitting this string by spaces and colons then indexing it, but this isn't working quite properly and could fail if the message is different. Does anyone have any idea how to do this?</p>
[ { "answer_id": 74479723, "author": "Random Davis", "author_id": 6273251, "author_profile": "https://Stackoverflow.com/users/6273251", "pm_score": 1, "selected": false, "text": "usernames" }, { "answer_id": 74479734, "author": "Wolric", "author_id": 20163209, "author_profile": "https://Stackoverflow.com/users/20163209", "pm_score": 1, "selected": true, "text": "BTP" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20532510/" ]
74,479,749
<p>First timer posting here and new to Python, so apologies in advance if I am missing any key information below.</p> <p>Essentially, I have a large CSV file that I was able to clean up a bit on scripts that contains various numerical values over ~150 miles of data with each data line being one foot. After I clean the file up a bit, tables would typically look like something below:</p> <pre><code>ABC Mile Ft Param1 A 1 1000 0.1234 A 1 1001 0.1111 A 1 1002 0.1221 A 1 1003 0.1511 B 1 1004 0.1999 B 1 1005 0.2011 B 1 1006 0.1878 B 1 1007 0.1999 C 1 1008 0.5321 C 1 1009 0.5333 C 1 1010 0.5445 C 1 1011 0.5655 C 1 1012 0.5852 A 1 1013 0.2788 A 1 1014 0.2899 A 1 1015 0.2901 A 1 1016 0.2921 A 1 1017 0.2877 A 1 1018 0.2896 </code></pre> <p>For this file, the 'ABC' column will always only equal A, B, or C.</p> <p>What I am trying to do is average the Param1 numbers for each set of A, B, and C. Thus in the example above, I would be looking to get the average of Param1 when it equals A from Ft 1000 to 1003, when it equals B from Ft 1004 to 1007, when it equals C from Ft 1008 to 1012, when it equals A from 1013 to 1018 and so on for the rest of the file.</p> <p><em>Edit</em> I should also mention that in these files, ABC will equal the same value typically for several hundred rows until it equals another value that will again repeat for several hundred rows, and so on. So the 'ABC' column could values could be something like this:</p> <p>AAA...AAA BBB...BBB CCC...CCC BBB...BBB AAA...AAA</p> <p>I have been looking at use of a for loop as below, but the problem is that I get all the averages of Param1 when equals A over a full mile, not each grouping. This is what I have thus far:</p> <pre><code>for i in range(1,df['Mile'].max()): avg_p1 = df.loc[(df['Mile'] == i) &amp; (df['ABC'] =='A'), 'Param1'].mean() print(avg_p1) </code></pre> <p>But in this case, I get the average of Param1 when ABC = A over the full mile. In the table example above, I want the average of Param1 when ABC = A from Ft 1000 to 1003 and 1013 to 1018, as separate averages repeated through the whole document.</p> <p>Would there need to be a second for loop or some kind of if/else condition added to the existing loop above? Any help for this novice programmer would be much appreciated :)</p>
[ { "answer_id": 74480003, "author": "amirhm", "author_id": 4529589, "author_profile": "https://Stackoverflow.com/users/4529589", "pm_score": 0, "selected": false, "text": "df.groupby('ABC')['Ft'].mean()\n" }, { "answer_id": 74480154, "author": "Fidel Lopez", "author_id": 10397975, "author_profile": "https://Stackoverflow.com/users/10397975", "pm_score": 0, "selected": false, "text": "results = {}\nfor cat in df['ABC'].unique():\n results[cat] = []\n category_index = df[df['ABC'] == cat].index.to_series()\n\n # Get list of continuous indexes\n bins = category_index.groupby(\n category_index.diff().ne(1).cumsum()\n ).agg(['first','last']).apply(tuple,1).tolist()\n\n # Average by category and bin\n for bin in bins:\n bin_low, bin_high = bin\n df_cut = df.iloc[bin_low:bin_high]\n low_ft, high_ft = df.iloc[bin_low]['Ft'], df.iloc[bin_high]['Ft']\n average_value = df_cut.groupby('ABC').mean()['Param1'][cat]\n results[cat].append(((low_ft, high_ft), average_value))\n\nresults\n" }, { "answer_id": 74480295, "author": "PTQuoc", "author_id": 11850322, "author_profile": "https://Stackoverflow.com/users/11850322", "pm_score": 2, "selected": true, "text": "df['change'] = np.where(df['ABC']!=df['ABC'].shift(1),1.0,0.0)\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20531737/" ]
74,479,753
<p>This problem occurs when using the kbl() function to create tables in R if the table's caption is too long. If the caption is too long, the text begins to wrap to the next line, but then it becomes left-justified.</p> <p>Sometimes the caption is short enough can be solved by adding the landscape argument to the style options, but I'd like a solution that is more flexible. The styling options for kbl offer lots of tools to manipulate the table cells, but I'm having difficulty doing that to the table captions. Here is example code that would result in the problem I'm having.</p> <pre><code>kbl(mtcars, caption = &quot;This is a really long title that will go past the borders when knitting to PDF in portrait mode. I'd love to figure out how to keep it centered even if the text is really long.&quot;, booktabs = TRUE, linesep = &quot;&quot;, align = &quot;c&quot;) %&gt;% kable_styling(latex_options = c(&quot;striped&quot;, &quot;hold_position&quot;)) </code></pre> <p>Adding the &quot;hold_position&quot; argument works for keeping the table in centered and in place, but the caption doesn't behave the same. Also, adding around the caption works if knitting to HTML, but I'd like a solution that works when knitting to PDF.</p> <p>Additionally, using \n to do linebreaks doesn't seem to work like it does for other packages like ggplot().</p>
[ { "answer_id": 74545257, "author": "Carlos Luis Rivera", "author_id": 10215301, "author_profile": "https://Stackoverflow.com/users/10215301", "pm_score": 1, "selected": false, "text": "caption" }, { "answer_id": 74595153, "author": "Abdur Rohman", "author_id": 14812170, "author_profile": "https://Stackoverflow.com/users/14812170", "pm_score": 0, "selected": false, "text": "kable" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20532475/" ]
74,479,776
<p>What is the best way to find out if a address/postalcode is within 60 miles of an address in Snowflake? In Google BigQuery there is the <code>bigquery-public-data.geo_us_boundaries.zip_codes</code> that allows you to this.</p>
[ { "answer_id": 74545257, "author": "Carlos Luis Rivera", "author_id": 10215301, "author_profile": "https://Stackoverflow.com/users/10215301", "pm_score": 1, "selected": false, "text": "caption" }, { "answer_id": 74595153, "author": "Abdur Rohman", "author_id": 14812170, "author_profile": "https://Stackoverflow.com/users/14812170", "pm_score": 0, "selected": false, "text": "kable" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/420558/" ]
74,479,814
<p>I know there are similar questions asked but I have read them and couldn't solved my problem I'm trying to <code>import pyrebase</code>; however it gives me these error messages:</p> <pre><code>Traceback (most recent call last): File &quot;c:\Users\yaman\OneDrive\Masaüstü\BİYOLOJİK ŞİFRELEME\JustSth.py&quot;, line 1, in &lt;module&gt; import pyrebase File &quot;C:\Users\yaman\AppData\Local\Programs\Python\Python39\lib\site-packages\pyrebase\__init__.py&quot;, line 1, in &lt;module&gt; from .pyrebase import initialize_app File &quot;C:\Users\yaman\AppData\Local\Programs\Python\Python39\lib\site-packages\pyrebase\pyrebase.py&quot;, line 23, in &lt;module&gt; from Crypto.PublicKey import RSA ModuleNotFoundError: No module named 'Crypto' </code></pre> <p>I downloaded the pycryptodome and it says <code>Requirement Satisfied</code> when I try to install it again? How can I solve this problem?</p> <p>Thanks from now!</p>
[ { "answer_id": 74545257, "author": "Carlos Luis Rivera", "author_id": 10215301, "author_profile": "https://Stackoverflow.com/users/10215301", "pm_score": 1, "selected": false, "text": "caption" }, { "answer_id": 74595153, "author": "Abdur Rohman", "author_id": 14812170, "author_profile": "https://Stackoverflow.com/users/14812170", "pm_score": 0, "selected": false, "text": "kable" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16723643/" ]
74,479,848
<p>I've multiple users which I want to configure into spring-boot's <code>UserDetailsService</code> for basic authentication.</p> <p><code>User</code> has a additional field <code>id</code> tagged with it.</p> <pre><code>import org.springframework.security.core.userdetails.UserDetails; public class User implements UserDetails { private final String username; private final String password; private final String id; private static final String ROLE_USER = &quot;ROLE_USER&quot;; @Override public Collection&lt;? extends GrantedAuthority&gt; getAuthorities() { SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(ROLE_USER); return Stream.of(simpleGrantedAuthority).collect(Collectors.toList()); } // Getter &amp; setter } </code></pre> <p>Properties yml looks like:</p> <pre><code>basic-auth: oliver: password: twist id: 1 ruskin: password: bond id: 2 mark: password: twain id: 3 </code></pre> <p>In <code>UserDetailsService</code>, I'm not sure how to configure users using application properties dynamically.</p> <pre><code>public class UserService implements UserDetailsService { @Override public UserDetails loadUserByUsername(String username) { String encodedPassword = passwordEncoder.encode( // How to fetch password ); String id = // How to fetch id return new User(username, encodedPassword, id); } } </code></pre>
[ { "answer_id": 74504414, "author": "jccampanero", "author_id": 13942448, "author_profile": "https://Stackoverflow.com/users/13942448", "pm_score": 2, "selected": false, "text": "basic-auth:\n users:\n oliver:\n password: twist\n id: 1\n ruskin:\n password: bond\n id: 2\n mark:\n password: twain\n id: 3\n" }, { "answer_id": 74582738, "author": "Ferenc Hrutka", "author_id": 20581896, "author_profile": "https://Stackoverflow.com/users/20581896", "pm_score": 1, "selected": false, "text": "constants:\nappUserList:\n- userId: 1\n userName: oliver\n password: twist\n role: USER\n\n- userId: 2\n userName: ruskin\n password: bond\n role: USER\n\n- userId: 3\n userName: mark\n password: twain\n role: ADMIN\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/926572/" ]
74,479,854
<p>I have a 10-input form. I added button cancel which is activating =&gt; confirmation modal which pop up when all input are filled. But I must do this is such way that modal will pop-up from 2 inputs are filled up ? Any suggestion? help articles? Angular</p> <pre><code> &lt;app-task-form #form [draftInput]=&quot;data&quot;&gt;&lt;/app-task-form&gt; &lt;button mat-flat-button (click)=&quot;clickTwo(!form.valid)&quot; i18n=&quot;@@CancelButton&quot;&gt; Cancel &lt;/button&gt; clickTwo(result: boolean): void { if (result == false) { this.closeModal() } else { this.dialogRef.close(); } } </code></pre> <p>If user will input two fields and will press button modal shoud pop-up. If inputs are empty after pressing button form should close.</p>
[ { "answer_id": 74504414, "author": "jccampanero", "author_id": 13942448, "author_profile": "https://Stackoverflow.com/users/13942448", "pm_score": 2, "selected": false, "text": "basic-auth:\n users:\n oliver:\n password: twist\n id: 1\n ruskin:\n password: bond\n id: 2\n mark:\n password: twain\n id: 3\n" }, { "answer_id": 74582738, "author": "Ferenc Hrutka", "author_id": 20581896, "author_profile": "https://Stackoverflow.com/users/20581896", "pm_score": 1, "selected": false, "text": "constants:\nappUserList:\n- userId: 1\n userName: oliver\n password: twist\n role: USER\n\n- userId: 2\n userName: ruskin\n password: bond\n role: USER\n\n- userId: 3\n userName: mark\n password: twain\n role: ADMIN\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15515293/" ]
74,479,863
<p>I'm trying to get a list of my top-level dirs in a subdir, so I can post process them, e.g., delete certain ones. I have</p> <pre class="lang-bash prettyprint-override"><code># List the top-level dirs and create an array with the resul DIRS=`ls -1` IFS=$'\n' read -ra TOP_DIRS &lt;&lt;&lt; &quot;$DIRS&quot; # Iterate the array for D in &quot;${TOP_DIRS[@]}&quot;; do # For now, just echo the dirs echo $D done </code></pre> <p>The <code>ls -1</code> command gives me this for example</p> <pre class="lang-bash prettyprint-override"><code>00 PRM - AUTO GA 00 PRM - AUTO GA Prod 00 PRM - AUTO GA Prod@script 00 PRM - AUTO GA Prod@script@tmp 00 PRM - AUTO GA STG 00 PRM - AUTO GA STG@script 00 PRM - AUTO GA STG@script@tmp </code></pre> <p>However, the <code>for</code> loop only echoes the first value, that is</p> <pre class="lang-bash prettyprint-override"><code>$ ./clean_workspace.sh 00 PRM - AUTO GA </code></pre> <p>So obviously my <code>IFS</code> statement is wrong. What am I missing? TIA!</p>
[ { "answer_id": 74479914, "author": "Barmar", "author_id": 1491895, "author_profile": "https://Stackoverflow.com/users/1491895", "pm_score": 3, "selected": true, "text": "ls" }, { "answer_id": 74480035, "author": "markp-fuso", "author_id": 7366100, "author_profile": "https://Stackoverflow.com/users/7366100", "pm_score": 1, "selected": false, "text": "read" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1401560/" ]
74,479,880
<p>I am trying to aggregate strings that belong to the same product code in one row. Which Qlik sense aggregation function should I use?</p> <p><a href="https://i.stack.imgur.com/i1rmy.png" rel="nofollow noreferrer">image</a></p> <p>I am able to aggregate integers in such example, but failed for string aggregation.</p>
[ { "answer_id": 74522780, "author": "SmoothBrane", "author_id": 11486874, "author_profile": "https://Stackoverflow.com/users/11486874", "pm_score": 0, "selected": false, "text": "MaxString()" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20532584/" ]
74,479,890
<p>I have an issue where I need to track the progression of patients insurance claim statuses based on the dates of those statuses. I also need to create a count of status based on certain conditions.</p> <p>DF:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ClaimID</th> <th>New</th> <th>Accepted</th> <th>Denied</th> <th>Pending</th> <th>Expired</th> <th>Group</th> </tr> </thead> <tbody> <tr> <td>001</td> <td>2021-01-01T09:58:35:335Z</td> <td>2021-01-01T10:05:43:000Z</td> <td></td> <td></td> <td></td> <td>A</td> </tr> <tr> <td>002</td> <td>2021-01-01T06:30:30:000Z</td> <td>2021-03-01T04:11:45:000Z</td> <td>2021-03-01T04:11:53:000Z</td> <td></td> <td></td> <td>A</td> </tr> <tr> <td>003</td> <td>2021-02-14T14:23:54:154Z</td> <td>2021-02-15T11:11:56:000Z</td> <td></td> <td></td> <td>2021-02-15T11:15:00:000Z</td> <td>A</td> </tr> <tr> <td>004</td> <td>2021-02-14T15:36:05:335Z</td> <td>2021-02-14T17:15:30:000Z</td> <td></td> <td></td> <td></td> <td>A</td> </tr> <tr> <td>005</td> <td>2021-02-14T15:56:59:009Z</td> <td>2021-03-01T10:05:43:000Z</td> <td></td> <td></td> <td></td> <td>A</td> </tr> </tbody> </table> </div> <p>In the above dataset, we have 6 columns. ClaimID is simple and just indicates the ID of the claim. New, Accepted, Denied, Pending, and Expired indicate the status of the claim and the day/time those statuses were set.</p> <p>What I need to do is get a count of how many claims are New on each day and how many move out of new into a new status. For example, There are 2 new claims on 2021-01-01. On that same day 1 moved to Accepted about 7 minutes later. Thus on 2021-01-01 the table of counts would read:</p> <p>DF_Count:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Date</th> <th>New</th> <th>Accepted</th> <th>Denied</th> <th>Pending</th> <th>Expired</th> </tr> </thead> <tbody> <tr> <td>2021-01-01</td> <td>2</td> <td>1</td> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <td>2021-01-02</td> <td>1</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <td>2021-01-03</td> <td>1</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <td>2021-01-04</td> <td>1</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <td>2021-01-05</td> <td>1</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <td>....</td> <td>....</td> <td>....</td> <td>....</td> <td>....</td> <td>....</td> </tr> <tr> <td>2021-02-14</td> <td>4</td> <td>2</td> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <td>2021-02-15</td> <td>2</td> <td>3</td> <td>0</td> <td>0</td> <td>1</td> </tr> <tr> <td>2021-02-16</td> <td>2</td> <td>2</td> <td>0</td> <td>0</td> <td>0</td> </tr> </tbody> </table> </div> <p>Few Conditions:</p> <ol> <li>If a claim moves from one status to the other on the same day (even if they are a minutes/hours apart) it would not be subtracted from the original status until the next day. This can be seen on 2021-01-01 where claim 001 moves from new to accepted on the same day but the claim is not subtracted from new until 2021-01-02.</li> <li>Until something happens to a claim, it should remain in its original status. Claim 002 will remain in new until 2021-03-01 when it is approved.</li> <li>If a claim changes status on a later date than its original status, it will be subtracted on that later date. For this, see status 003. It is new on 2/14 but accepted on 2/15. This is why New goes down by 2 on 2/15 (the other claim is the is 004 which is new and accepted on the same day)</li> <li>For certain statuses, I do not need to look at all columns. For example, For new I only look at the dates inside Accepted and Denied. Not Pending and Expired. When I do these same steps for approved, I no longer need to look at new, just the other columns. How would I do that?</li> <li>In the final DF_count table, the dates should start from the earliest date in 'New' and end on todays date.</li> <li>The code needs to be grouped by the Group Column as well. For example, patients in group B (not pictured) will have to have the same start and end date but for their own claims.</li> <li>I need to do this separately for all of the statuses. Not just new.</li> </ol> <p>Current Solution:</p> <p>My current solution has been to create an dataset with just dates from the min New Date to todays date. Then for each column, what I do is use the .loc method to find dates that are greater than New in each of the other columns. For example, in the code below I look for all cases where new is equal to approved.</p> <pre><code>df1 = df.loc[(df['New'] == df['Approved']) &amp; ((df['Expired'].isnull()) | (df['Expired'] &gt;= df['Accepted'])) &amp; ((df['Pending'].isnull()) | (df['Pending'] &gt;= df['Accepted'])) &amp; ((df['Denied'].isnull()) | (df['Denied'] &gt;= df['Accepted']))] newtoaccsday = df1.loc[:, ('Group', 'Accepted')] newtoappsday['Date'] = newtoappsday['Accepted'] newtoappsday = newtoappsday.reset_index(drop = True) newtoappsday= newtoappsday.groupby(['Date', 'Group'], as_index = False)['Approved'].value_counts() newtoappsday.drop(columns = {'Accepted'}, inplace = True) newtoappsday.rename(columns = {'count': 'NewAppSDay'}, inplace = True) newtoappsday['Date'] = newtoappsday['Date'] + timedelta(1) df_count= df_count.merge(newtoappsday, how = 'left', on = ['Date', 'Group']).fillna(0) --After doing the above steps for all conditions (where new goes to accepted on a later date etc.) I will do the final calculation for new: df_count['New'] = df_count.eval('New = New - (NewAccSDay + NewAccLater + NewDenSDay + NewDenLater + NewExpLater + NewPendSDay + NewPendLater)').groupby(['Tier2_ID', 'ClaimType'])['New'].cumsum() </code></pre> <p>Any and all help would be greatly appreciated. My method above is extremely inefficient and leading to some errors. Do I need to write a for loop for this? What is the best way to go about this.</p>
[ { "answer_id": 74527080, "author": "wrbp", "author_id": 16662333, "author_profile": "https://Stackoverflow.com/users/16662333", "pm_score": 1, "selected": false, "text": "import pandas as pd\nimport numpy as np\nfrom datetime import timedelta\nfrom datetime import date\n\ndef dateRange(d1,d2):\n return [d1 + timedelta(days=x) for x in range((d2-d1).days)]\n \ndef addCount(dic,group,dat,cat):\n if group not in dic:\n dic[group]={}\n if dat not in dic[group]:\n dic[group][dat]={}\n if cat not in dic[group][dat]:\n dic[group][dat][cat]=0\n dic[group][dat][cat]+=1\n \ndf =pd.read_csv(\"testdf.csv\",\n parse_dates=[\"New\",\"Accepted\",\"Denied\",\"Pending\", \"Expired\"])#,\n\ncdic={}\nfor i,row in df.iterrows():\n cid=row[\"ClaimID\"]\n dnew=row[\"New\"].date()\n dacc=row[\"Accepted\"].date()\n dden=row[\"Denied\"].date()\n dpen=row[\"Pending\"].date()\n dexp=row[\"Expired\"].date()\n group=row[\"Group\"]\n \n if not pd.isna(dacc): #Claim has been accepted\n if(dnew == dacc):\n dacc+=timedelta(days=1)\n nend=dacc\n addCount(cdic,group,dacc,\"acc\")\n if not pd.isna(dden): # Claim has been denied\n if(dnew == dden):\n dden+=timedelta(days=1)\n if pd.isna(dacc):\n nend=dden\n addCount(cdic,group,dden,\"den\")\n if not pd.isna(dpen):\n addCount(cdic,group,dpen,\"pen\") # Claim is pending\n if not pd.isna(dexp):\n addCount(cdic,group,dexp,\"exp\") # Claim is expired\n if pd.isna(dacc) and pd.isna(dden):\n nend=date.today()+timedelta(days+1)\n for d in dateRange(dnew,nend): # Fill new status until first change\n addCount(cdic,group,d,\"new\")\nndfl=[] \nfor group in cdic:\n for dat in sorted(cdic[group].keys()):\n r=cdic[group][dat]\n ndfl.append([group,dat,r.get(\"new\",0),r.get(\"acc\",0),\n r.get(\"den\",0),r.get(\"pen\",0),r.get(\"exp\",0)])\nndf=pd.DataFrame(ndfl,columns=[\"Group\", \"Date\",\"New\",\"Accepted\",\"Denied\",\"Pending\",\"Expired\"])\n\n" }, { "answer_id": 74527349, "author": "gputrain", "author_id": 20472812, "author_profile": "https://Stackoverflow.com/users/20472812", "pm_score": 3, "selected": true, "text": "for i in ['New', 'Accepted', 'Denied', 'Pending', 'Expired']:\n df[i] = pd.to_datetime(df[i], format=\"%Y-%m-%dT%H:%M:%S:%f%z\")\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19852587/" ]
74,479,898
<p>Let me explain the structure of the problem that I'm trying to solve. Let's suppose that we have two dataframes</p> <p>DF1:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>Value</th> </tr> </thead> <tbody> <tr> <td>AA</td> <td>2</td> </tr> <tr> <td>AB</td> <td>1</td> </tr> <tr> <td>AC</td> <td>2</td> </tr> <tr> <td>AD</td> <td>1</td> </tr> <tr> <td>AE</td> <td>2</td> </tr> </tbody> </table> </div> <p>DF2:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>New Value</th> </tr> </thead> <tbody> <tr> <td>AA</td> <td>1</td> </tr> <tr> <td>AC</td> <td>1</td> </tr> </tbody> </table> </div> <p>If the ID column row in DF1 is in DF2, then I would like to change the value in the same row in DF1 to the one that it has in DF2, so the end result would be something like this:</p> <p>DF1:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>Value</th> </tr> </thead> <tbody> <tr> <td>AA</td> <td>1</td> </tr> <tr> <td>AB</td> <td>1</td> </tr> <tr> <td>AC</td> <td>1</td> </tr> <tr> <td>AD</td> <td>1</td> </tr> <tr> <td>AE</td> <td>2</td> </tr> </tbody> </table> </div> <p>So far, I have tried attempts with .loc and np.where but none of them where successful, my closest attempt is the following line of code:</p> <pre><code>DF1['Value'][row] = [DF2['New Value'][row] if ((DF1['ID'][row]).isin(DF2['ID'])) else DF1['Value'][row] for row in DF['ID']] </code></pre>
[ { "answer_id": 74527080, "author": "wrbp", "author_id": 16662333, "author_profile": "https://Stackoverflow.com/users/16662333", "pm_score": 1, "selected": false, "text": "import pandas as pd\nimport numpy as np\nfrom datetime import timedelta\nfrom datetime import date\n\ndef dateRange(d1,d2):\n return [d1 + timedelta(days=x) for x in range((d2-d1).days)]\n \ndef addCount(dic,group,dat,cat):\n if group not in dic:\n dic[group]={}\n if dat not in dic[group]:\n dic[group][dat]={}\n if cat not in dic[group][dat]:\n dic[group][dat][cat]=0\n dic[group][dat][cat]+=1\n \ndf =pd.read_csv(\"testdf.csv\",\n parse_dates=[\"New\",\"Accepted\",\"Denied\",\"Pending\", \"Expired\"])#,\n\ncdic={}\nfor i,row in df.iterrows():\n cid=row[\"ClaimID\"]\n dnew=row[\"New\"].date()\n dacc=row[\"Accepted\"].date()\n dden=row[\"Denied\"].date()\n dpen=row[\"Pending\"].date()\n dexp=row[\"Expired\"].date()\n group=row[\"Group\"]\n \n if not pd.isna(dacc): #Claim has been accepted\n if(dnew == dacc):\n dacc+=timedelta(days=1)\n nend=dacc\n addCount(cdic,group,dacc,\"acc\")\n if not pd.isna(dden): # Claim has been denied\n if(dnew == dden):\n dden+=timedelta(days=1)\n if pd.isna(dacc):\n nend=dden\n addCount(cdic,group,dden,\"den\")\n if not pd.isna(dpen):\n addCount(cdic,group,dpen,\"pen\") # Claim is pending\n if not pd.isna(dexp):\n addCount(cdic,group,dexp,\"exp\") # Claim is expired\n if pd.isna(dacc) and pd.isna(dden):\n nend=date.today()+timedelta(days+1)\n for d in dateRange(dnew,nend): # Fill new status until first change\n addCount(cdic,group,d,\"new\")\nndfl=[] \nfor group in cdic:\n for dat in sorted(cdic[group].keys()):\n r=cdic[group][dat]\n ndfl.append([group,dat,r.get(\"new\",0),r.get(\"acc\",0),\n r.get(\"den\",0),r.get(\"pen\",0),r.get(\"exp\",0)])\nndf=pd.DataFrame(ndfl,columns=[\"Group\", \"Date\",\"New\",\"Accepted\",\"Denied\",\"Pending\",\"Expired\"])\n\n" }, { "answer_id": 74527349, "author": "gputrain", "author_id": 20472812, "author_profile": "https://Stackoverflow.com/users/20472812", "pm_score": 3, "selected": true, "text": "for i in ['New', 'Accepted', 'Denied', 'Pending', 'Expired']:\n df[i] = pd.to_datetime(df[i], format=\"%Y-%m-%dT%H:%M:%S:%f%z\")\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12252396/" ]
74,479,899
<p>I am very badly stuck on this error for days, and I am unable to understand what it is trying to tell me as it is only 2 words.</p> <p>The error is coming when I am trying to insert data into the DB table using python manage.py shell</p> <pre><code>&gt; from app_name.models import Usermanagement &gt; from app_name.models import Inquery i = Inquery( inqueryid=6, inquerynumber=&quot;INQ765758499&quot;, sourceairportid=Airport(airportid=1), destinationairportid=Airport(airportid=21), stageid=Stage(stageid=1), commoditytypeid=6, customerid=Customer(customerid=1), branchid=1, transactiontype=&quot;AGENT&quot;, businesstype=&quot;Self&quot;, hodate=&quot;2020-11-18&quot;, totalshipmentunits=56, unitid=100, grossweight=100, volumemetricweight=100, remark=&quot;test&quot;, dateofcreation=&quot;2018-11-20 00:00:00&quot;, dateofmodification=&quot;2018-11-20 00:00:00&quot;, createdby = Usermanagement(userid=0), modifiedby = Usermanagement(userid=0)) </code></pre> <p>#error</p> <pre><code>KeyError: 'createdby' </code></pre> <p>#traceback</p> <pre><code>File C:\Python310\lib\site-packages\django\db\models\base.py:768, in Model.save(self, force_insert, force_update, using, update_fields) 757 def save( 758 self, force_insert=False, force_update=False, using=None, update_fields=None 759 ): 760 &quot;&quot;&quot; 761 Save the current instance. Override this in a subclass if you want to 762 control the saving process. (...) 766 non-SQL backends), respectively. Normally, they should not be set. 767 &quot;&quot;&quot; --&gt; 768 self._prepare_related_fields_for_save(operation_name=&quot;save&quot;) 770 using = using or router.db_for_write(self.__class__, instance=self) 771 if force_insert and (force_update or update_fields): File C:\Python310\lib\site-packages\django\db\models\base.py:1092, in Model._prepare_related_fields_for_save(self, operation_name, fields) 1087 # If the relationship's pk/to_field was changed, clear the 1088 # cached relationship. 1089 if getattr(obj, field.target_field.attname) != getattr( 1090 self, field.attname 1091 ): -&gt; 1092 field.delete_cached_value(self) 1093 # GenericForeignKeys are private. 1094 for field in self._meta.private_fields: File C:\Python310\lib\site-packages\django\db\models\fields\mixins.py:28, in FieldCacheMixin.delete_cached_value(self, instance) 27 def delete_cached_value(self, instance): ---&gt; 28 del instance._state.fields_cache[self.get_cache_name()] KeyError: 'createdby' </code></pre> <p>#models.py (only some part of it, for sort Question)</p> <pre><code># this model is in freight app class Inquery(models.Model): inqueryid = models.BigAutoField(db_column='InqueryID', primary_key=True) inquerynumber = models.CharField(db_column='InqueryNumber', max_length=45) sourceairportid = models.ForeignKey(Airport, on_delete=models.CASCADE, db_column='SourceAirportID',related_name=&quot;Flight_inquery_source&quot;) destinationairportid = models.ForeignKey(Airport, on_delete=models.CASCADE, db_column='DestinationAirportID',related_name=&quot;Flight_inquery_destination&quot;) stageid = models.ForeignKey('Stage', on_delete=models.CASCADE, db_column='StageID') commoditytypeid = models.IntegerField(db_column='CommodityTypeID') customerid = models.ForeignKey(Customer, on_delete=models.CASCADE, db_column='CustomerID') branchid = models.IntegerField(db_column='BranchID') transactiontype = models.CharField(db_column='TransactionType', max_length=10) businesstype = models.CharField(db_column='BusinessType', max_length=15) hodate = models.DateTimeField(db_column='HODate') totalshipmentunits = models.CharField(db_column='TotalShipmentUnits', max_length=20) unitid = models.CharField(db_column='UnitID', max_length=3) grossweight = models.FloatField(db_column='GrossWeight') volumemetricweight = models.FloatField(db_column='VolumemetricWeight') remark = models.CharField(db_column='Remark', max_length=8000) dateofcreation = models.DateTimeField(db_column='DateOfCreation') dateofmodification = models.DateTimeField(db_column='DateOfModification') createdby = models.ForeignKey('accounts.Usermanagement', on_delete=models.CASCADE, db_column='CreatedBy', to_field='createdby',related_name=&quot;Usermanagement_Inquery_createdby&quot;) modifiedby = models.ForeignKey('accounts.Usermanagement', on_delete=models.CASCADE, db_column='ModifiedBy', to_field='modifiedby',related_name=&quot;Usermanagement_Inquery_modifiedby&quot;) isactive = models.IntegerField(db_column='IsActive') def __str__(self): return self.inquerynumber class Meta: managed = False db_table = 'Inquery' </code></pre> <p>#another app model</p> <pre><code>class Usermanagement(AbstractBaseUser): userid = models.BigAutoField(db_column='UserID', primary_key=True) emailid = models.CharField(db_column='EmailID', unique=True, max_length=45) roleid = models.ForeignKey(Role, on_delete=models.CASCADE, db_column='RoleID') organizationid = models.ForeignKey(Organization, on_delete=models.CASCADE, db_column='OrganizationID') firstname = models.CharField(db_column='FirstName', max_length=45) middlename = models.CharField(db_column='MiddleName', max_length=45, blank=True, null=True) lastname = models.CharField(db_column='LastName', max_length=45, blank=True, null=True) numberofretry = models.IntegerField(db_column='NumberOfRetry',default=0) timeoffset = models.CharField(db_column='TimeOffSet', max_length=6,default=&quot;+5:30&quot;) password = models.CharField(db_column='Password', max_length=45) passwordexpirydate = models.DateTimeField(db_column='PasswordExpiryDate',default='2022-12-30 12:30:59') dateofcreation = models.DateTimeField(db_column='DateOfCreation',auto_now_add = True) dateofmodification = models.DateTimeField(db_column='DateOfModification',auto_now = True) createdby = models.BigIntegerField(db_column='CreatedBy',unique=True) #this field is FK in many other models modifiedby = models.BigIntegerField(db_column='ModifiedBy',unique=True) #this field is FK in many other models isactive = models.BooleanField(db_column='IsActive',default=1) last_login = False objects = UsermanagementCustomUserManager() USERNAME_FIELD = &quot;emailid&quot; EMAIL_FIELD = &quot;emailid&quot; REQUIRED_FIELDS = [&quot;roleid&quot;,&quot;organizationid&quot;,&quot;firstname&quot;,&quot;passwordexpirydate&quot;,&quot;createdby&quot;,&quot;modifiedby&quot;] def __str__(self): return self.emailid --------------------- some more code ------------------ </code></pre>
[ { "answer_id": 74527080, "author": "wrbp", "author_id": 16662333, "author_profile": "https://Stackoverflow.com/users/16662333", "pm_score": 1, "selected": false, "text": "import pandas as pd\nimport numpy as np\nfrom datetime import timedelta\nfrom datetime import date\n\ndef dateRange(d1,d2):\n return [d1 + timedelta(days=x) for x in range((d2-d1).days)]\n \ndef addCount(dic,group,dat,cat):\n if group not in dic:\n dic[group]={}\n if dat not in dic[group]:\n dic[group][dat]={}\n if cat not in dic[group][dat]:\n dic[group][dat][cat]=0\n dic[group][dat][cat]+=1\n \ndf =pd.read_csv(\"testdf.csv\",\n parse_dates=[\"New\",\"Accepted\",\"Denied\",\"Pending\", \"Expired\"])#,\n\ncdic={}\nfor i,row in df.iterrows():\n cid=row[\"ClaimID\"]\n dnew=row[\"New\"].date()\n dacc=row[\"Accepted\"].date()\n dden=row[\"Denied\"].date()\n dpen=row[\"Pending\"].date()\n dexp=row[\"Expired\"].date()\n group=row[\"Group\"]\n \n if not pd.isna(dacc): #Claim has been accepted\n if(dnew == dacc):\n dacc+=timedelta(days=1)\n nend=dacc\n addCount(cdic,group,dacc,\"acc\")\n if not pd.isna(dden): # Claim has been denied\n if(dnew == dden):\n dden+=timedelta(days=1)\n if pd.isna(dacc):\n nend=dden\n addCount(cdic,group,dden,\"den\")\n if not pd.isna(dpen):\n addCount(cdic,group,dpen,\"pen\") # Claim is pending\n if not pd.isna(dexp):\n addCount(cdic,group,dexp,\"exp\") # Claim is expired\n if pd.isna(dacc) and pd.isna(dden):\n nend=date.today()+timedelta(days+1)\n for d in dateRange(dnew,nend): # Fill new status until first change\n addCount(cdic,group,d,\"new\")\nndfl=[] \nfor group in cdic:\n for dat in sorted(cdic[group].keys()):\n r=cdic[group][dat]\n ndfl.append([group,dat,r.get(\"new\",0),r.get(\"acc\",0),\n r.get(\"den\",0),r.get(\"pen\",0),r.get(\"exp\",0)])\nndf=pd.DataFrame(ndfl,columns=[\"Group\", \"Date\",\"New\",\"Accepted\",\"Denied\",\"Pending\",\"Expired\"])\n\n" }, { "answer_id": 74527349, "author": "gputrain", "author_id": 20472812, "author_profile": "https://Stackoverflow.com/users/20472812", "pm_score": 3, "selected": true, "text": "for i in ['New', 'Accepted', 'Denied', 'Pending', 'Expired']:\n df[i] = pd.to_datetime(df[i], format=\"%Y-%m-%dT%H:%M:%S:%f%z\")\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19818111/" ]
74,479,931
<p>I'm using Github pages to host my website currently and my function works perfectly fine on desktop but not on my phone(Ios) and other peoples phone(also Ios).</p> <p>My function is supposed to calculate how many calories and grams of protein someone needs to maintain/gain/lose weight.</p> <p>my code</p> <pre><code>function lbsToProtein(lbs, weightGoal, cm, age, excercise) { var kgs = lbs / 2.205; var calorieIntake; var proteinGrams; switch (weightGoal) { case 1: //maintain weight calorieIntake = (kgs * 13.397) + (cm * 4.799) - (age * 5.677) + 88.362 + excercise; proteinGrams = kgs * 0.8; break; case 2: //gain weight calorieIntake = ((kgs * 13.397) + (cm * 4.799) - (age * 5.677) + 88.362) + 700 + excercise; proteinGrams = kgs * 1.35; break; case 3: //lose weight calorieIntake = (((kgs * 13.397) + (cm * 4.799) - (age * 5.677) + 88.362) - 700) + excercise; proteinGrams = kgs * 0.8; break; } var calorieIntake = Math.round(calorieIntake); var proteinGrams = Math.round(proteinGrams); //changed this to 2.55 for now until you add maintaining too console.log(&quot;Protein: &quot;+proteinGrams+&quot;g&quot;); console.log('Calorie Intake: '+calorieIntake+'cal', (typeof calorieIntake)); var info = [proteinGrams, calorieIntake]; console.log(info) return info; } function ftTocm(height) { console.log(height) var ft = height.split(&quot;'&quot;); //console.log(ft[0], ft[1]); var cm = ((parseInt(ft[0]) * 12) + parseInt(ft[1])) * 2.54; console.log(&quot;cm&quot;, cm); return cm; } function submit() { var lbs = parseFloat(document.getElementById('lbs-input').value); var age = document.getElementById('age-input').value; var height = document.getElementById('height-input').value; var fat = document.getElementById('fat-input').value; var goal_input = document.getElementById('select'); var excercise_input = document.getElementById('excercise'); // value given 1 through 3 to switch function var excercise = excercise_input.value; var weightGoal = goal_input.value; var info = lbsToProtein(lbs, parseInt(weightGoal), ftTocm(height), parseInt(age), parseInt(excercise)); document.getElementById('calories').innerHTML = info[1] + ' calories'; document.getElementById('protein').innerHTML = info[0] + ' grams'; document.getElementById('form').style.cssText = 'display: none;'; document.getElementById('results').style.cssText = 'display: block !important;'; } </code></pre> <p>I've tried switching things from let to var since people have said es6 didn't work on IOS, but that issue was 12 years ago so probably not the problem. Clearing cache also isn't working. Besides that, any tips are helpful. I do have a node module in my website but it's just for animations. I haven't tried it on Android yet either. I've looked at other posts about IOS not working but none seem to fix my issue.</p>
[ { "answer_id": 74480456, "author": "Ali Iqbal", "author_id": 20321054, "author_profile": "https://Stackoverflow.com/users/20321054", "pm_score": 1, "selected": false, "text": "submit()" }, { "answer_id": 74540164, "author": "RaidLucky", "author_id": 11499016, "author_profile": "https://Stackoverflow.com/users/11499016", "pm_score": 1, "selected": true, "text": "var ft = height.split(\"'\");" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11499016/" ]
74,479,939
<p>I want to sort a list with an <em>arbitrary</em> number of lists inside to sort by <em>each</em> of said lists. Furthermore I do <em>not</em> want to use any libraries (neither python-native nor 3rd party).</p> <pre class="lang-py prettyprint-override"><code>data = [['a', 'b', 'a', 'b', 'a'], [9, 8, 7, 6, 5]] </code></pre> <p>I know I can achieve this by doing</p> <pre class="lang-py prettyprint-override"><code>list(zip(*sorted(zip(*data)))) # [('a', 'a', 'a', 'b', 'b'), (5, 7, 9, 6, 8)] </code></pre> <p>but I would like to have the sorting-index of that very process. In this case:</p> <pre class="lang-py prettyprint-override"><code>index = [4, 2, 0, 3, 1] </code></pre> <p>I found several answers for a <em>fixed</em> number of inside lists, or such that only want to sort by a specific list. Neither case is what I am looking for.</p>
[ { "answer_id": 74480120, "author": "Temba", "author_id": 3593621, "author_profile": "https://Stackoverflow.com/users/3593621", "pm_score": 1, "selected": false, "text": "data = [[\"a\", \"b\", \"a\", \"b\", \"a\"], [9, 8, 7, 6, 5]]\n\n\ndef sortList(inputList):\n masterList = [[value, index] for index, value in enumerate(inputList)]\n masterList.sort()\n\n values = []\n indices = []\n for item in masterList:\n values.append(item[0]) # get the item\n indices.append(item[1]) # get the index\n return values, indices\n\n\nsortedData = []\nsortedIndices = []\nfor subList in data:\n sortedList, indices = sortList(subList)\n sortedData.append(sortedList)\n sortedIndices.append(indices)\n\n\nprint(sortedData)\nprint(sortedIndices)\n" }, { "answer_id": 74480191, "author": "Woodford", "author_id": 8451814, "author_profile": "https://Stackoverflow.com/users/8451814", "pm_score": 3, "selected": true, "text": "data = [['a', 'b', 'a', 'b', 'a'], [9, 8, 7, 6, 5]]\nassert all(len(sublist) == len(data[0]) for sublist in data)\ndata.append(range(len(data[0])))\n*sorted_data, indices = list(zip(*sorted(zip(*data))))\n\nprint(sorted_data)\n# [('a', 'a', 'a', 'b', 'b'), (5, 7, 9, 6, 8)]\n\nprint(indices)\n# (4, 2, 0, 3, 1)\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8537572/" ]
74,479,970
<p>Filter seems slower than the vectorised version in the following example:</p> <pre class="lang-r prettyprint-override"><code>u = rnorm(1000000) system.time(u[u &gt; 0]) # utilisateur système écoulé # 0.02 0.00 0.01 system.time(Filter(\(x) x &gt; 0, u)) # utilisateur système écoulé # 0.71 0.00 0.72 </code></pre> <p>Is there a faster function than <code>Filter</code> in this case (<code>purrr::keep</code> is even slower)?</p>
[ { "answer_id": 74480183, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 2, "selected": false, "text": "subset" }, { "answer_id": 74480287, "author": "SteveM", "author_id": 3574156, "author_profile": "https://Stackoverflow.com/users/3574156", "pm_score": -1, "selected": false, "text": "> 0" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8806649/" ]
74,479,971
<p>I have a scenario where I have different events like the following:</p> <pre><code>type EventType = 'foo' | 'bar' type Event = { type: 'foo', timestamp: number, payload: { a: number } } | { type: 'bar', timestamp: number, payload: { b: string } } </code></pre> <p>Then I have a listener like this:</p> <pre><code>on('foo', event =&gt; { // Here we should know that the type must be 'foo', // and therefore the payload has the shape {a: number} // but I don't know how to tell that to TS }) </code></pre> <p>I've tried a few different things, but so far all I've managed is for the compiler to stop compiling </p> <p>I thought <a href="https://stackoverflow.com/questions/55167093/associating-a-message-type-with-a-payload-type">this question</a> could help, but I didn't manage to get it working. I think the problem is that I'm using a literal union instead of an enum.</p> <p>I imagine this is a situation happening in many places, so I was hoping to find a solution more easily.</p>
[ { "answer_id": 74480015, "author": "Dimava", "author_id": 5734961, "author_profile": "https://Stackoverflow.com/users/5734961", "pm_score": -1, "selected": false, "text": "if (event.type == 'foo') {\n // event is Extract<event, {type: 'foo'}>\n event.payload.a\n} else {\n // event is Exclude<event, {type: 'foo'}>\n event.payload.b\n}\n" }, { "answer_id": 74480277, "author": "jcalz", "author_id": 2887218, "author_profile": "https://Stackoverflow.com/users/2887218", "pm_score": 3, "selected": true, "text": "on()" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74479971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5452969/" ]
74,480,005
<p>I have a data.table made of data.tables as per the dput at the end of this question. I manipulate this data.table of data.tables using the following nested for-loops:</p> <pre><code>test_E2 &lt;- list() for (i in unique(lst_512_32_E2$ID)){ test_E2[[i]] &lt;- list() for (j in 1:length(lst_512_32_E2$V1[[i]])){ test_E2[[i]][[j]] &lt;- sapply(lst_512_32_E2[ID==i]$V1, '[[', j) } } t_test_E2 &lt;- list() for (i in 1:length(test_E2)){ t_test_E2[[i]] &lt;- list() for (j in 1:length(test_E2[[i]])){ t_test_E2[[i]][[j]] &lt;- t(test_E2[[i]][[j]]) } } </code></pre> <p>Any chance these for-loops could be re-generated/optimized while staying in the data.table world? What about an apply/mapply function as a second alternative? Minding that I want the final output as matrix.</p> <p>Edit 1 (revised code):</p> <pre><code>#This function will be used to delete null list elements delete.NULLs &lt;- function(x.list){ x.list[unlist(lapply(x.list, length) != 0)] } #I revised the nested loop to accommodate more than one variable, i.e., V1, V2, V3, etc. test_E2 &lt;- list() for (i in unique(lst_512_32_E2$ID)){ test_E2[[i]] &lt;- list() for (j in 2:length(lst_512_32_E2)){ test_E2[[i]][[j]] &lt;- (sapply(lst_512_32_E2[ID==i,..j][[1]], '[[',1)) } } #This is where the NULL list elements are deleted. test_E2 &lt;- lapply(test_E2, delete.NULLs) #This is the same. Could be eliminated using Karl's answer though t_test_E2 &lt;- list() for (i in 1:length(test_E2)){ t_test_E2[[i]] &lt;- list() for (j in 1:length(test_E2[[i]])){ t_test_E2[[i]][[j]] &lt;- t(test_E2[[i]][[j]]) } } </code></pre> <p>I refer you to this question which was of help before. Maybe it brings up some ideas: <a href="https://stackoverflow.com/questions/66830782/optimizing-a-foreach-with-an-embeded-lapply-loop-is-it-possible-to-optimize-co">Optimizing a foreach with an embeded lapply loop - Is it possible to optimize code?</a></p> <p>Edit 2: Trying to play with data.table syntax</p> <pre><code>#Test_E22 and Test_E222 could be chained but they're kept separate for readability. test_E22 &lt;- lst_512_32_E2[,.(.(lapply(.SD, function(x) .(sapply(x, '[[',1))))),by = ID] test_E222 &lt;- test_E22[,.(lapply(.SD, function(x) matrix(unlist(x),nrow = window_size))), by=ID] #Turning the data.table into a list of data.tables abc &lt;- lapply(unique(test_E222$ID), function(x) test_E222[ID==x][,c(.SD), by=ID]) #Combine Values into a Vector or List. Can the V1 inside the c() be replaced with a function and still return a vector or list? What if if I want to return more than one vector or list in the case I have V1, V2, etc.? abc2 &lt;- lapply(abc, function(x) x[,c(V1)]) #This is a first attempt at it to keep the community engaged with the question. Hopefully, someone is able to optimize it further and can help resolve the c() issue. </code></pre> <p>Edit 3: What is the code supposed to achieve? I have been asked couple of times what is the code supposed to achieve. Will try to answer by going through the loops of the first nested loop bottom up:</p> <pre><code>sapply(lst_512_32_E2[ID==i,..j][[1]], '[[',1)) </code></pre> <p>For each sliding window within ID==i of variable j (only V1 of interest here), 625 windows in this sapply, return the sliding window time series (512 readings) of that sliding window.</p> <pre><code>for (j in 2:length(lst_512_32_E2)) </code></pre> <p>Apply the sapply for the variables of interest (only V1 of interest here) skipping the ID column.</p> <pre><code>for (i in unique(lst_512_32_E2$ID)) </code></pre> <p>Repeat this for each decomposed time signal.</p> <p>The second nested loop is basically transposing the output to have each time increment (t1, t2,... and tn) from each sliding window of in one vector. To generate the results, please run the 2 nested loops on the dput below.</p> <p>dput:</p> <pre><code>print(dput(lst_512_32_E2[1:2])) structure(list(ID = c(1L, 1L), gl = structure(1:2, levels = c(&quot;1&quot;, &quot;2&quot;, &quot;3&quot;, &quot;4&quot;, &quot;5&quot;, &quot;6&quot;, &quot;7&quot;, &quot;8&quot;, &quot;9&quot;, &quot;10&quot;, &quot;11&quot;, &quot;12&quot;, &quot;13&quot;, &quot;14&quot;, &quot;15&quot;, &quot;16&quot;, &quot;17&quot;, &quot;18&quot;, &quot;19&quot;, &quot;20&quot;, &quot;21&quot;, &quot;22&quot;, &quot;23&quot;, &quot;24&quot;, &quot;25&quot;, &quot;26&quot;, &quot;27&quot;, &quot;28&quot;, &quot;29&quot;, &quot;30&quot;, &quot;31&quot;, &quot;32&quot;, &quot;33&quot;, &quot;34&quot;, &quot;35&quot;, &quot;36&quot;, &quot;37&quot;, &quot;38&quot;, &quot;39&quot;, &quot;40&quot;, &quot;41&quot;, &quot;42&quot;, &quot;43&quot;, &quot;44&quot;, &quot;45&quot;, &quot;46&quot;, &quot;47&quot;, &quot;48&quot;, &quot;49&quot;, &quot;50&quot;, &quot;51&quot;, &quot;52&quot;, &quot;53&quot;, &quot;54&quot;, &quot;55&quot;, &quot;56&quot;, &quot;57&quot;, &quot;58&quot;, &quot;59&quot;, &quot;60&quot;, &quot;61&quot;, &quot;62&quot;, &quot;63&quot;, &quot;64&quot;, &quot;65&quot;, &quot;66&quot;, &quot;67&quot;, &quot;68&quot;, &quot;69&quot;, &quot;70&quot;, &quot;71&quot;, &quot;72&quot;, &quot;73&quot;, &quot;74&quot;, &quot;75&quot;, &quot;76&quot;, &quot;77&quot;, &quot;78&quot;, &quot;79&quot;, &quot;80&quot;, &quot;81&quot;, &quot;82&quot;, &quot;83&quot;, &quot;84&quot;, &quot;85&quot;, &quot;86&quot;, &quot;87&quot;, &quot;88&quot;, &quot;89&quot;, &quot;90&quot;, &quot;91&quot;, &quot;92&quot;, &quot;93&quot;, &quot;94&quot;, &quot;95&quot;, &quot;96&quot;, &quot;97&quot;, &quot;98&quot;, &quot;99&quot;, &quot;100&quot;, &quot;101&quot;, &quot;102&quot;, &quot;103&quot;, &quot;104&quot;, &quot;105&quot;, &quot;106&quot;, &quot;107&quot;, &quot;108&quot;, &quot;109&quot;, &quot;110&quot;, &quot;111&quot;, &quot;112&quot;, &quot;113&quot;, &quot;114&quot;, &quot;115&quot;, &quot;116&quot;, &quot;117&quot;, &quot;118&quot;, &quot;119&quot;, &quot;120&quot;, &quot;121&quot;, &quot;122&quot;, &quot;123&quot;, &quot;124&quot;, &quot;125&quot;, &quot;126&quot;, &quot;127&quot;, &quot;128&quot;, &quot;129&quot;, &quot;130&quot;, &quot;131&quot;, &quot;132&quot;, &quot;133&quot;, &quot;134&quot;, &quot;135&quot;, &quot;136&quot;, &quot;137&quot;, &quot;138&quot;, &quot;139&quot;, &quot;140&quot;, &quot;141&quot;, &quot;142&quot;, &quot;143&quot;, &quot;144&quot;, &quot;145&quot;, &quot;146&quot;, &quot;147&quot;, &quot;148&quot;, &quot;149&quot;, &quot;150&quot;, &quot;151&quot;, &quot;152&quot;, &quot;153&quot;, &quot;154&quot;, &quot;155&quot;, &quot;156&quot;, &quot;157&quot;, &quot;158&quot;, &quot;159&quot;, &quot;160&quot;, &quot;161&quot;, &quot;162&quot;, &quot;163&quot;, &quot;164&quot;, &quot;165&quot;, &quot;166&quot;, &quot;167&quot;, &quot;168&quot;, &quot;169&quot;, &quot;170&quot;, &quot;171&quot;, &quot;172&quot;, &quot;173&quot;, &quot;174&quot;, &quot;175&quot;, &quot;176&quot;, &quot;177&quot;, &quot;178&quot;, &quot;179&quot;, &quot;180&quot;, &quot;181&quot;, &quot;182&quot;, &quot;183&quot;, &quot;184&quot;, &quot;185&quot;, &quot;186&quot;, &quot;187&quot;, &quot;188&quot;, &quot;189&quot;, &quot;190&quot;, &quot;191&quot;, &quot;192&quot;, &quot;193&quot;, &quot;194&quot;, &quot;195&quot;, &quot;196&quot;, &quot;197&quot;, &quot;198&quot;, &quot;199&quot;, &quot;200&quot;, &quot;201&quot;, &quot;202&quot;, &quot;203&quot;, &quot;204&quot;, &quot;205&quot;, &quot;206&quot;, &quot;207&quot;, &quot;208&quot;, &quot;209&quot;, &quot;210&quot;, &quot;211&quot;, &quot;212&quot;, &quot;213&quot;, &quot;214&quot;, &quot;215&quot;, &quot;216&quot;, &quot;217&quot;, &quot;218&quot;, &quot;219&quot;, &quot;220&quot;, &quot;221&quot;, &quot;222&quot;, &quot;223&quot;, &quot;224&quot;, &quot;225&quot;, &quot;226&quot;, &quot;227&quot;, &quot;228&quot;, &quot;229&quot;, &quot;230&quot;, &quot;231&quot;, &quot;232&quot;, &quot;233&quot;, &quot;234&quot;, &quot;235&quot;, &quot;236&quot;, &quot;237&quot;, &quot;238&quot;, &quot;239&quot;, &quot;240&quot;, &quot;241&quot;, &quot;242&quot;, &quot;243&quot;, &quot;244&quot;, &quot;245&quot;, &quot;246&quot;, &quot;247&quot;, &quot;248&quot;, &quot;249&quot;, &quot;250&quot;, &quot;251&quot;, &quot;252&quot;, &quot;253&quot;, &quot;254&quot;, &quot;255&quot;, &quot;256&quot;, &quot;257&quot;, &quot;258&quot;, &quot;259&quot;, &quot;260&quot;, &quot;261&quot;, &quot;262&quot;, &quot;263&quot;, &quot;264&quot;, &quot;265&quot;, &quot;266&quot;, &quot;267&quot;, &quot;268&quot;, &quot;269&quot;, &quot;270&quot;, &quot;271&quot;, &quot;272&quot;, &quot;273&quot;, &quot;274&quot;, &quot;275&quot;, &quot;276&quot;, &quot;277&quot;, &quot;278&quot;, &quot;279&quot;, &quot;280&quot;, &quot;281&quot;, &quot;282&quot;, &quot;283&quot;, &quot;284&quot;, &quot;285&quot;, &quot;286&quot;, &quot;287&quot;, &quot;288&quot;, &quot;289&quot;, &quot;290&quot;, &quot;291&quot;, &quot;292&quot;, &quot;293&quot;, &quot;294&quot;, &quot;295&quot;, &quot;296&quot;, &quot;297&quot;, &quot;298&quot;, &quot;299&quot;, &quot;300&quot;, &quot;301&quot;, &quot;302&quot;, &quot;303&quot;, &quot;304&quot;, &quot;305&quot;, &quot;306&quot;, &quot;307&quot;, &quot;308&quot;, &quot;309&quot;, &quot;310&quot;, &quot;311&quot;, &quot;312&quot;, &quot;313&quot;, &quot;314&quot;, &quot;315&quot;, &quot;316&quot;, &quot;317&quot;, &quot;318&quot;, &quot;319&quot;, &quot;320&quot;, &quot;321&quot;, &quot;322&quot;, &quot;323&quot;, &quot;324&quot;, &quot;325&quot;, &quot;326&quot;, &quot;327&quot;, &quot;328&quot;, &quot;329&quot;, &quot;330&quot;, &quot;331&quot;, &quot;332&quot;, &quot;333&quot;, &quot;334&quot;, &quot;335&quot;, &quot;336&quot;, &quot;337&quot;, &quot;338&quot;, &quot;339&quot;, &quot;340&quot;, &quot;341&quot;, &quot;342&quot;, &quot;343&quot;, &quot;344&quot;, &quot;345&quot;, &quot;346&quot;, &quot;347&quot;, &quot;348&quot;, &quot;349&quot;, &quot;350&quot;, &quot;351&quot;, &quot;352&quot;, &quot;353&quot;, &quot;354&quot;, &quot;355&quot;, &quot;356&quot;, &quot;357&quot;, &quot;358&quot;, &quot;359&quot;, &quot;360&quot;, &quot;361&quot;, &quot;362&quot;, &quot;363&quot;, &quot;364&quot;, &quot;365&quot;, &quot;366&quot;, &quot;367&quot;, &quot;368&quot;, &quot;369&quot;, &quot;370&quot;, &quot;371&quot;, &quot;372&quot;, &quot;373&quot;, &quot;374&quot;, &quot;375&quot;, &quot;376&quot;, &quot;377&quot;, &quot;378&quot;, &quot;379&quot;, &quot;380&quot;, &quot;381&quot;, &quot;382&quot;, &quot;383&quot;, &quot;384&quot;, &quot;385&quot;, &quot;386&quot;, &quot;387&quot;, &quot;388&quot;, &quot;389&quot;, &quot;390&quot;, &quot;391&quot;, &quot;392&quot;, &quot;393&quot;, &quot;394&quot;, &quot;395&quot;, &quot;396&quot;, &quot;397&quot;, &quot;398&quot;, &quot;399&quot;, &quot;400&quot;, &quot;401&quot;, &quot;402&quot;, &quot;403&quot;, &quot;404&quot;, &quot;405&quot;, &quot;406&quot;, &quot;407&quot;, &quot;408&quot;, &quot;409&quot;, &quot;410&quot;, &quot;411&quot;, &quot;412&quot;, &quot;413&quot;, &quot;414&quot;, &quot;415&quot;, &quot;416&quot;, &quot;417&quot;, &quot;418&quot;, &quot;419&quot;, &quot;420&quot;, &quot;421&quot;, &quot;422&quot;, &quot;423&quot;, &quot;424&quot;, &quot;425&quot;, &quot;426&quot;, &quot;427&quot;, &quot;428&quot;, &quot;429&quot;, &quot;430&quot;, &quot;431&quot;, &quot;432&quot;, &quot;433&quot;, &quot;434&quot;, &quot;435&quot;, &quot;436&quot;, &quot;437&quot;, &quot;438&quot;, &quot;439&quot;, &quot;440&quot;, &quot;441&quot;, &quot;442&quot;, &quot;443&quot;, &quot;444&quot;, &quot;445&quot;, &quot;446&quot;, &quot;447&quot;, &quot;448&quot;, &quot;449&quot;, &quot;450&quot;, &quot;451&quot;, &quot;452&quot;, &quot;453&quot;, &quot;454&quot;, &quot;455&quot;, &quot;456&quot;, &quot;457&quot;, &quot;458&quot;, &quot;459&quot;, &quot;460&quot;, &quot;461&quot;, &quot;462&quot;, &quot;463&quot;, &quot;464&quot;, &quot;465&quot;, &quot;466&quot;, &quot;467&quot;, &quot;468&quot;, &quot;469&quot;, &quot;470&quot;, &quot;471&quot;, &quot;472&quot;, &quot;473&quot;, &quot;474&quot;, &quot;475&quot;, &quot;476&quot;, &quot;477&quot;, &quot;478&quot;, &quot;479&quot;, &quot;480&quot;, &quot;481&quot;, &quot;482&quot;, &quot;483&quot;, &quot;484&quot;, &quot;485&quot;, &quot;486&quot;, &quot;487&quot;, &quot;488&quot;, &quot;489&quot;, &quot;490&quot;, &quot;491&quot;, &quot;492&quot;, &quot;493&quot;, &quot;494&quot;, &quot;495&quot;, &quot;496&quot;, &quot;497&quot;, &quot;498&quot;, &quot;499&quot;, &quot;500&quot;, &quot;501&quot;, &quot;502&quot;, &quot;503&quot;, &quot;504&quot;, &quot;505&quot;, &quot;506&quot;, &quot;507&quot;, &quot;508&quot;, &quot;509&quot;, &quot;510&quot;, &quot;511&quot;, &quot;512&quot;, &quot;513&quot;, &quot;514&quot;, &quot;515&quot;, &quot;516&quot;, &quot;517&quot;, &quot;518&quot;, &quot;519&quot;, &quot;520&quot;, &quot;521&quot;, &quot;522&quot;, &quot;523&quot;, &quot;524&quot;, &quot;525&quot;, &quot;526&quot;, &quot;527&quot;, &quot;528&quot;, &quot;529&quot;, &quot;530&quot;, &quot;531&quot;, &quot;532&quot;, &quot;533&quot;, &quot;534&quot;, &quot;535&quot;, &quot;536&quot;, &quot;537&quot;, &quot;538&quot;, &quot;539&quot;, &quot;540&quot;, &quot;541&quot;, &quot;542&quot;, &quot;543&quot;, &quot;544&quot;, &quot;545&quot;, &quot;546&quot;, &quot;547&quot;, &quot;548&quot;, &quot;549&quot;, &quot;550&quot;, &quot;551&quot;, &quot;552&quot;, &quot;553&quot;, &quot;554&quot;, &quot;555&quot;, &quot;556&quot;, &quot;557&quot;, &quot;558&quot;, &quot;559&quot;, &quot;560&quot;, &quot;561&quot;, &quot;562&quot;, &quot;563&quot;, &quot;564&quot;, &quot;565&quot;, &quot;566&quot;, &quot;567&quot;, &quot;568&quot;, &quot;569&quot;, &quot;570&quot;, &quot;571&quot;, &quot;572&quot;, &quot;573&quot;, &quot;574&quot;, &quot;575&quot;, &quot;576&quot;, &quot;577&quot;, &quot;578&quot;, &quot;579&quot;, &quot;580&quot;, &quot;581&quot;, &quot;582&quot;, &quot;583&quot;, &quot;584&quot;, &quot;585&quot;, &quot;586&quot;, &quot;587&quot;, &quot;588&quot;, &quot;589&quot;, &quot;590&quot;, &quot;591&quot;, &quot;592&quot;, &quot;593&quot;, &quot;594&quot;, &quot;595&quot;, &quot;596&quot;, &quot;597&quot;, &quot;598&quot;, &quot;599&quot;, &quot;600&quot;, &quot;601&quot;, &quot;602&quot;, &quot;603&quot;, &quot;604&quot;, &quot;605&quot;, &quot;606&quot;, &quot;607&quot;, &quot;608&quot;, &quot;609&quot;, &quot;610&quot;, &quot;611&quot;, &quot;612&quot;, &quot;613&quot;, &quot;614&quot;, &quot;615&quot;, &quot;616&quot;, &quot;617&quot;, &quot;618&quot;, &quot;619&quot;, &quot;620&quot;, &quot;621&quot;, &quot;622&quot;, &quot;623&quot;, &quot;624&quot;, &quot;625&quot;, &quot;626&quot;, &quot;627&quot;, &quot;628&quot;, &quot;629&quot;, &quot;630&quot;, &quot;631&quot;, &quot;632&quot;, &quot;633&quot;, &quot;634&quot;, &quot;635&quot;, &quot;636&quot;, &quot;637&quot;, &quot;638&quot;, &quot;639&quot;, &quot;640&quot; ), class = &quot;factor&quot;), V1 = list(structure(list(V1 = c(-0.049, -0.042, 0.015, -0.051, -0.107, -0.078, -0.02, -0.046, -0.063, 0.068, 0.095, -0.007, -0.046, 0.044, 0.137, 0.098, 0.081, -0.073, -0.037, 0.012, -0.037, -0.044, 0.015, 0.044, -0.029, -0.09, -0.061, -0.042, -0.002, 0.007, 0.024, -0.005, -0.11, -0.076, 0.032, 0.088, -0.005, -0.105, -0.117, -0.071, -0.002, -0.017, -0.034, -0.098, -0.071, -0.056, -0.083, -0.093, -0.012, 0.002, 0.042, -0.056, -0.017, 0.007, -0.015, 0.02, 0.015, 0.007, 0.029, 0.054, 0.01, -0.007, -0.056, -0.049, -0.034, 0.002, 0.017, -0.071, -0.103, -0.093, -0.051, -0.01, -0.107, -0.063, 0.054, 0.007, 0.037, 0.071, 0.107, -0.02, -0.056, -0.078, 0.027, 0.063, -0.051, -0.115, -0.068, -0.059, -0.024, -0.044, 0.027, -0.012, -0.054, -0.02, 0.022, -0.066, -0.037, 0.117, 0.071, 0.029, 0.015, -0.032, 0.027, -0.044, -0.22, -0.2, -0.024, 0.007, -0.129, -0.068, 0.044, 0.059, 0.012, 0.002, -0.068, 0.029, 0.117, 0.039, 0.005, 0.088, 0.032, -0.095, -0.076, -0.032, -0.059, -0.142, -0.164, -0.071, -0.02, -0.032, -0.088, -0.022, 0.032, 0.032, 0.007, -0.022, -0.042, 0.024, 0.042, -0.017, -0.034, 0.01, 0.002, -0.076, -0.078, -0.054, -0.095, -0.073, -0.034, -0.103, -0.081, -0.088, -0.017, -0.049, 0.012, -0.09, -0.122, 0.01, 0.022, 0.122, 0.107, 0.012, -0.017, -0.107, -0.107, 0.034, -0.034, -0.044, -0.061, -0.115, -0.132, -0.193, -0.029, 0.078, 0.093, 0.1, 0.049, -0.037, 0.029, -0.027, 0.002, 0.081, -0.024, -0.083, -0.046, -0.002, -0.037, -0.149, -0.02, 0.01, -0.049, -0.105, -0.051, 0.078, 0.071, 0.007, -0.081, 0.054, 0.164, 0.042, 0.073, -0.02, -0.032, 0.015, 0.002, -0.081, 0.042, 0.024, -0.132, -0.063, 0.051, 0.02, 0, 0.02, -0.01, -0.005, 0.071, 0.01, -0.005, 0.088, 0.037, -0.015, -0.042, -0.024, -0.012, 0.071, -0.022, -0.1, -0.115, -0.029, -0.01, -0.002, -0.051, -0.081, 0.027, 0.11, 0.022, -0.061, 0.061, 0.01, -0.012, -0.02, -0.049, 0.029, 0.01, -0.029, -0.032, 0.01, 0.042, -0.01, 0.042, 0.034, -0.088, -0.083, -0.09, 0.037, -0.002, 0.056, 0.024, 0.044, 0.154, 0.088, 0.027, 0.034, 0.105, 0.081, -0.02, -0.083, -0.068, -0.017, 0.034, 0.042, -0.073, -0.112, -0.015, 0.088, 0.071, -0.066, -0.085, 0.083, 0.156, 0.105, -0.073, -0.071, 0.09, 0.078, -0.051, -0.142, -0.076, 0.005, -0.01, -0.093, -0.076, -0.049, 0.056, 0.01, -0.046, 0.042, 0.132, 0.049, -0.029, 0.044, 0.107, 0.122, 0.068, -0.002, -0.078, -0.012, -0.037, -0.105, -0.115, 0.017, 0.042, 0.015, 0.032, 0.054, 0.024, -0.002, 0.083, 0.061, -0.007, 0.056, 0.046, -0.01, 0.049, 0.022, -0.024, -0.024, -0.022, -0.127, -0.176, -0.081, -0.068, 0, 0.015, -0.029, -0.017, -0.027, -0.002, 0.054, 0.005, -0.022, -0.027, -0.007, 0.095, 0.029, -0.085, -0.059, -0.063, 0.024, 0.029, -0.063, -0.078, -0.127, -0.068, -0.022, -0.029, 0.046, 0.029, 0.01, 0.039, 0.132, 0.068, 0.044, 0.012, -0.029, -0.015, 0.093, -0.01, -0.134, -0.115, -0.066, -0.032, 0.002, -0.039, -0.134, -0.051, 0.034, 0.061, 0.066, 0.061, 0.066, 0.01, 0.024, 0.093, 0.044, 0.037, 0.012, 0.002, -0.027, -0.11, -0.11, -0.073, -0.029, 0.032, 0.005, -0.066, -0.005, -0.02, -0.029, -0.068, -0.01, 0.071, 0.081, 0.034, -0.037, -0.032, -0.007, -0.012, -0.073, -0.088, -0.071, -0.049, -0.083, -0.044, -0.112, 0.015, -0.1, -0.154, 0.029, 0.073, 0.073, 0, -0.01, 0.005, -0.012, -0.103, -0.12, -0.093, -0.042, -0.024, -0.154, -0.073, -0.054, -0.1, -0.125, -0.117, -0.066, 0.034, 0.085, 0.012, 0.039, 0.085, 0.005, -0.022, -0.017, 0.02, 0.039, -0.046, -0.007, 0.012, -0.012, -0.063, -0.054, 0.007, -0.056, -0.107, 0.037, 0.093, 0.046, -0.061, -0.015, 0.039, 0.024, 0.068, 0.007, -0.027, 0.051, -0.134, -0.11, 0.007, -0.093, -0.105, -0.056, -0.076, 0.012, -0.071, -0.056, -0.117, -0.073, 0.002, 0.054, 0.078, 0.09, 0.11, 0.09, -0.022, -0.044, 0.042, 0.073, -0.005, 0.015, 0.017, -0.085, -0.1, -0.085, -0.059, -0.103, -0.071, -0.056, -0.034, 0.032, 0.039, -0.007, -0.007, 0.068, 0.027, -0.054, -0.078, -0.061, -0.059, -0.024)), row.names = c(NA, -512L), class = c(&quot;data.table&quot;, &quot;data.frame&quot;)), structure(list( V1 = c(-0.11, -0.076, 0.032, 0.088, -0.005, -0.105, -0.117, -0.071, -0.002, -0.017, -0.034, -0.098, -0.071, -0.056, -0.083, -0.093, -0.012, 0.002, 0.042, -0.056, -0.017, 0.007, -0.015, 0.02, 0.015, 0.007, 0.029, 0.054, 0.01, -0.007, -0.056, -0.049, -0.034, 0.002, 0.017, -0.071, -0.103, -0.093, -0.051, -0.01, -0.107, -0.063, 0.054, 0.007, 0.037, 0.071, 0.107, -0.02, -0.056, -0.078, 0.027, 0.063, -0.051, -0.115, -0.068, -0.059, -0.024, -0.044, 0.027, -0.012, -0.054, -0.02, 0.022, -0.066, -0.037, 0.117, 0.071, 0.029, 0.015, -0.032, 0.027, -0.044, -0.22, -0.2, -0.024, 0.007, -0.129, -0.068, 0.044, 0.059, 0.012, 0.002, -0.068, 0.029, 0.117, 0.039, 0.005, 0.088, 0.032, -0.095, -0.076, -0.032, -0.059, -0.142, -0.164, -0.071, -0.02, -0.032, -0.088, -0.022, 0.032, 0.032, 0.007, -0.022, -0.042, 0.024, 0.042, -0.017, -0.034, 0.01, 0.002, -0.076, -0.078, -0.054, -0.095, -0.073, -0.034, -0.103, -0.081, -0.088, -0.017, -0.049, 0.012, -0.09, -0.122, 0.01, 0.022, 0.122, 0.107, 0.012, -0.017, -0.107, -0.107, 0.034, -0.034, -0.044, -0.061, -0.115, -0.132, -0.193, -0.029, 0.078, 0.093, 0.1, 0.049, -0.037, 0.029, -0.027, 0.002, 0.081, -0.024, -0.083, -0.046, -0.002, -0.037, -0.149, -0.02, 0.01, -0.049, -0.105, -0.051, 0.078, 0.071, 0.007, -0.081, 0.054, 0.164, 0.042, 0.073, -0.02, -0.032, 0.015, 0.002, -0.081, 0.042, 0.024, -0.132, -0.063, 0.051, 0.02, 0, 0.02, -0.01, -0.005, 0.071, 0.01, -0.005, 0.088, 0.037, -0.015, -0.042, -0.024, -0.012, 0.071, -0.022, -0.1, -0.115, -0.029, -0.01, -0.002, -0.051, -0.081, 0.027, 0.11, 0.022, -0.061, 0.061, 0.01, -0.012, -0.02, -0.049, 0.029, 0.01, -0.029, -0.032, 0.01, 0.042, -0.01, 0.042, 0.034, -0.088, -0.083, -0.09, 0.037, -0.002, 0.056, 0.024, 0.044, 0.154, 0.088, 0.027, 0.034, 0.105, 0.081, -0.02, -0.083, -0.068, -0.017, 0.034, 0.042, -0.073, -0.112, -0.015, 0.088, 0.071, -0.066, -0.085, 0.083, 0.156, 0.105, -0.073, -0.071, 0.09, 0.078, -0.051, -0.142, -0.076, 0.005, -0.01, -0.093, -0.076, -0.049, 0.056, 0.01, -0.046, 0.042, 0.132, 0.049, -0.029, 0.044, 0.107, 0.122, 0.068, -0.002, -0.078, -0.012, -0.037, -0.105, -0.115, 0.017, 0.042, 0.015, 0.032, 0.054, 0.024, -0.002, 0.083, 0.061, -0.007, 0.056, 0.046, -0.01, 0.049, 0.022, -0.024, -0.024, -0.022, -0.127, -0.176, -0.081, -0.068, 0, 0.015, -0.029, -0.017, -0.027, -0.002, 0.054, 0.005, -0.022, -0.027, -0.007, 0.095, 0.029, -0.085, -0.059, -0.063, 0.024, 0.029, -0.063, -0.078, -0.127, -0.068, -0.022, -0.029, 0.046, 0.029, 0.01, 0.039, 0.132, 0.068, 0.044, 0.012, -0.029, -0.015, 0.093, -0.01, -0.134, -0.115, -0.066, -0.032, 0.002, -0.039, -0.134, -0.051, 0.034, 0.061, 0.066, 0.061, 0.066, 0.01, 0.024, 0.093, 0.044, 0.037, 0.012, 0.002, -0.027, -0.11, -0.11, -0.073, -0.029, 0.032, 0.005, -0.066, -0.005, -0.02, -0.029, -0.068, -0.01, 0.071, 0.081, 0.034, -0.037, -0.032, -0.007, -0.012, -0.073, -0.088, -0.071, -0.049, -0.083, -0.044, -0.112, 0.015, -0.1, -0.154, 0.029, 0.073, 0.073, 0, -0.01, 0.005, -0.012, -0.103, -0.12, -0.093, -0.042, -0.024, -0.154, -0.073, -0.054, -0.1, -0.125, -0.117, -0.066, 0.034, 0.085, 0.012, 0.039, 0.085, 0.005, -0.022, -0.017, 0.02, 0.039, -0.046, -0.007, 0.012, -0.012, -0.063, -0.054, 0.007, -0.056, -0.107, 0.037, 0.093, 0.046, -0.061, -0.015, 0.039, 0.024, 0.068, 0.007, -0.027, 0.051, -0.134, -0.11, 0.007, -0.093, -0.105, -0.056, -0.076, 0.012, -0.071, -0.056, -0.117, -0.073, 0.002, 0.054, 0.078, 0.09, 0.11, 0.09, -0.022, -0.044, 0.042, 0.073, -0.005, 0.015, 0.017, -0.085, -0.1, -0.085, -0.059, -0.103, -0.071, -0.056, -0.034, 0.032, 0.039, -0.007, -0.007, 0.068, 0.027, -0.054, -0.078, -0.061, -0.059, -0.024, 0.037, -0.007, -0.083, -0.032, -0.061, -0.081, -0.093, -0.117, 0.034, 0.044, 0.037, 0.054, 0.083, 0.002, -0.103, 0.083, 0.115, -0.139, -0.046, 0.142, 0.032, -0.139, -0.151, 0.081, 0.107, -0.061, -0.076, 0.005, 0.176, 0.078, -0.061, 0.01)), row.names = c(NA, -512L), class = c(&quot;data.table&quot;, &quot;data.frame&quot;)))), row.names = c(NA, -2L), class = c(&quot;data.table&quot;, &quot;data.frame&quot;), .internal.selfref = &lt;pointer: 0x000002289534be80&gt;) ID gl V1 1: 1 1 &lt;data.table[512x1]&gt; 2: 1 2 &lt;data.table[512x1]&gt; </code></pre>
[ { "answer_id": 74480015, "author": "Dimava", "author_id": 5734961, "author_profile": "https://Stackoverflow.com/users/5734961", "pm_score": -1, "selected": false, "text": "if (event.type == 'foo') {\n // event is Extract<event, {type: 'foo'}>\n event.payload.a\n} else {\n // event is Exclude<event, {type: 'foo'}>\n event.payload.b\n}\n" }, { "answer_id": 74480277, "author": "jcalz", "author_id": 2887218, "author_profile": "https://Stackoverflow.com/users/2887218", "pm_score": 3, "selected": true, "text": "on()" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7221040/" ]
74,480,056
<p>I have user-defined type:</p> <pre><code>class String::CharProxy { public: const char* operator&amp;() const; char* operator&amp;(); operator char() const; operator char&amp;(); }; </code></pre> <p>The problem is when I'm trying to perform some explicit casts, the wrong operator is called:</p> <pre><code>CharProxy p(...); static_cast&lt;char&gt;(p); // operator char&amp;() call instead of operator char() const </code></pre> <p>I want <code>operator char() const</code> to be called when casting to <code>char</code> and <code>operator char&amp;()</code> - when casting to <code>char&amp;</code> only.</p> <p>Could anyone explain how this mechanism works? Am I mistaken anywhere?</p>
[ { "answer_id": 74480237, "author": "Nicol Bolas", "author_id": 734069, "author_profile": "https://Stackoverflow.com/users/734069", "pm_score": 2, "selected": false, "text": "char&" }, { "answer_id": 74480302, "author": "Wintermute", "author_id": 4301306, "author_profile": "https://Stackoverflow.com/users/4301306", "pm_score": 4, "selected": true, "text": "static_cast" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20492391/" ]
74,480,093
<p>I'm currently porting a C library to python using pybind11, and it has lots of <em>C-style function pointers</em> (i.e. <em>not</em> std::function, as described in <a href="https://pybind11.readthedocs.io/en/stable/advanced/cast/functional.html" rel="nofollow noreferrer">https://pybind11.readthedocs.io/en/stable/advanced/cast/functional.html</a>)</p> <p>So my question is: is there an easy way to handle C style function pointers, when they are passed a function parameters?</p> <hr /> <p>For example I need to bind this function type (as an illustration, I took function pointers from the C library glfw)</p> <pre class="lang-cpp prettyprint-override"><code>typedef void (* GLFWmonitorfun)(GLFWmonitor* monitor, int event); </code></pre> <p>which is used like this:</p> <pre class="lang-cpp prettyprint-override"><code>void glfwSetMonitorCallback(GLFWmonitorfun cbfun) </code></pre> <p>I know I could wrap the function pointers in <code>std::function</code>, but it is quite cumbersome, since there are about 30 different function pointer types in the library, and I would need to patch manually all their usages.</p> <p>Is there an easier way ?</p> <p>PS: Below is how I could wrap them with std::function. Beware, this is borderline atrocious, since it requires global variable and global callbacks. This is exactly what I would like to avoid.</p> <pre class="lang-cpp prettyprint-override"><code> // C function pointer type typedef void (* GLFWmonitorfun)(GLFWmonitor* monitor, int event); // Wrapper std::function type using GLFWmonitorfun_std = std::function&lt;void(GLFWmonitor*, int)&gt;; // We need to store a global std::function pointer GLFWmonitorfun_std globalGLFWmonitorfun_std; // As well as a global C callback void myGlobalCallback(GLFWmonitor* monitor, int event) { if (globalGLFWmonitorfun_std) globalGLFWmonitorfun_std(monitor, event); } void py_init_module_glfw(py::module&amp; m) { m.def(&quot;glfwSetMonitorCallback&quot;, [](const GLFWmonitorfun_std&amp; f) { // And we set the global std::function pointer in the binding globalGLFWmonitorfun_std = f; // Before setting the C callback glfwSetMonitorCallback(myGlobalCallback); }); // .... </code></pre>
[ { "answer_id": 74480877, "author": "ecatmur", "author_id": 567292, "author_profile": "https://Stackoverflow.com/users/567292", "pm_score": 3, "selected": true, "text": "static" }, { "answer_id": 74481325, "author": "Pascal T.", "author_id": 19816, "author_profile": "https://Stackoverflow.com/users/19816", "pm_score": 0, "selected": false, "text": "#define ADD_FN_POINTER_CALLBACK_ONE_PARAM(functionName, CallbackType, Type1) \\\n m.def(#functionName, [](std::function<std::remove_pointer_t<CallbackType>> f) { \\\n static std::function<std::remove_pointer_t<CallbackType>> callback; \\\n callback = std::move(f); \\\n functionName([](Type1 v1) { \\\n callback(v1); \\\n });\\\n });\n\n#define ADD_FN_POINTER_CALLBACK_TWO_PARAMS(functionName, CallbackType, Type1, Type2) \\\n m.def(#functionName, [](std::function<std::remove_pointer_t<CallbackType>> f) { \\\n static std::function<std::remove_pointer_t<CallbackType>> callback; \\\n callback = std::move(f); \\\n functionName([](Type1 v1, Type2 v2) { \\\n callback(v1, v2); \\\n });\\\n });\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19816/" ]
74,480,148
<p>I created a class method that is called when a new object is created and copied from an old existing object. However, I only want to copy <strong>some</strong> of the values. Is there some sort of Ruby shorthand I can use to clean this up? It's not entirely necessary, just curious to know if something like this exists?</p> <p>Here is the method I want to DRY up:</p> <pre><code>def set_message_settings_from_existing existing self.can_message = existing.can_message self.current_format = existing.current_format self.send_initial_message = existing.send_initial_message self.send_alert = existing.send_alert self.location = existing.location end </code></pre> <p>Obviously this works perfectly fine, but to me looks a little ugly. Is there any way to clean this up? If I wanted to copy over every value that would be easy enough, but because I only want to copy these 5 (out of 20 something) values, I decided to do it this way.</p>
[ { "answer_id": 74480609, "author": "AbM", "author_id": 2697183, "author_profile": "https://Stackoverflow.com/users/2697183", "pm_score": 3, "selected": true, "text": "def set_message_settings_from_existing(existing)\n [:can_message, :current_format, :send_initial_message, :send_alert, :location].each do |attribute|\n self.send(\"#{attribute}=\", existing.send(attribute))\n end\nend\n" }, { "answer_id": 74480666, "author": "Haumer", "author_id": 11042897, "author_profile": "https://Stackoverflow.com/users/11042897", "pm_score": 0, "selected": false, "text": "def set_message_settings_from_existing existing\n fields = {\n can_message: existing.can_message,\n current_format: existing.current_format,\n send_initial_message: existing.send_initial_message,\n send_alert: existing.send_alert,\n location: existing.location\n }\n self.attributes = fields\nend\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15587214/" ]
74,480,186
<p>I would like to filter my query with only closed months, so today (17/11/2022) would return only 31/10/2022 and before. I have tried the following:</p> <pre><code>WHERE EXTRACT(MONTH FROM dc.data) &lt;= (EXTRACT(MONTH FROM CURDATE()) - 1) </code></pre> <p>So I get the current date, extract the month and subtract 1, then filter &lt;= that month right? Also, dc.data is on the right date format, and it's working properly</p> <p>But here is the problem, it's filtering past Years with months 1-10 too, that filter should be applied only to current year, and <strong>still show past years with all months</strong>, how could I do this?</p> <p>This query is being written on Apache Superset SQL editor, so I have some limitations on functions I think... the database is MySQL (edited)</p> <p>PS: I was also wondering if there is a way to optimize this query, not sure if this is a good way of handling dates</p>
[ { "answer_id": 74480609, "author": "AbM", "author_id": 2697183, "author_profile": "https://Stackoverflow.com/users/2697183", "pm_score": 3, "selected": true, "text": "def set_message_settings_from_existing(existing)\n [:can_message, :current_format, :send_initial_message, :send_alert, :location].each do |attribute|\n self.send(\"#{attribute}=\", existing.send(attribute))\n end\nend\n" }, { "answer_id": 74480666, "author": "Haumer", "author_id": 11042897, "author_profile": "https://Stackoverflow.com/users/11042897", "pm_score": 0, "selected": false, "text": "def set_message_settings_from_existing existing\n fields = {\n can_message: existing.can_message,\n current_format: existing.current_format,\n send_initial_message: existing.send_initial_message,\n send_alert: existing.send_alert,\n location: existing.location\n }\n self.attributes = fields\nend\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17604480/" ]
74,480,192
<p>I follow this installation guide : <a href="https://docs.janusgraph.org/getting-started/installation/" rel="nofollow noreferrer">https://docs.janusgraph.org/getting-started/installation/</a></p> <p>I run :</p> <pre><code>docker run -it -p 8182:8182 janusgraph/janusgraph </code></pre> <p>but when i try to connect with the gremlin console I have this exception :</p> <pre><code>gremlin-driver-initializer] INFO org.apache.tinkerpop.gremlin.driver.ConnectionPool - Signalled closing of connection pool on Host{address=localhost/127.0.0.1:8182, hostUri=ws://localhost:8182/gremlin} with core size of 2 18:32:42.556 [gremlin-driver-initializer] ERROR org.apache.tinkerpop.gremlin.driver.Client - Could not initialize client for Host{address=localhost/127.0.0.1:8182, hostUri=ws://localhost:8182/gremlin} 18:32:42.560 [main] ERROR org.apache.tinkerpop.gremlin.driver.Client - java.net.ConnectException: Connection refused: no further information* </code></pre> <p>I try with docker desktop and realize than my container automatically stop after 26 seconds. I have read than docker container automatically stop when nothing run on it. When I inspect it there is the message :</p> <pre><code>/etc/opt/janusgraph/janusgraph-server.yaml will be used to start JanusGraph Server in foreground. </code></pre> <p>Could you help me to configure it ?</p>
[ { "answer_id": 74480609, "author": "AbM", "author_id": 2697183, "author_profile": "https://Stackoverflow.com/users/2697183", "pm_score": 3, "selected": true, "text": "def set_message_settings_from_existing(existing)\n [:can_message, :current_format, :send_initial_message, :send_alert, :location].each do |attribute|\n self.send(\"#{attribute}=\", existing.send(attribute))\n end\nend\n" }, { "answer_id": 74480666, "author": "Haumer", "author_id": 11042897, "author_profile": "https://Stackoverflow.com/users/11042897", "pm_score": 0, "selected": false, "text": "def set_message_settings_from_existing existing\n fields = {\n can_message: existing.can_message,\n current_format: existing.current_format,\n send_initial_message: existing.send_initial_message,\n send_alert: existing.send_alert,\n location: existing.location\n }\n self.attributes = fields\nend\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13870287/" ]
74,480,232
<p><a href="https://stackoverflow.com/questions/15389091/how-to-exclude-records-with-certain-values-in-sql-select">How to exclude records with certain values in sql select</a></p> <p>I need to exclude the entire month where Video or Face-to-Face exist but keep the months where either one of those options is not found. I'm using the NOT EXISTS which works but when I filter based on a date range, it excludes everything because it found a single instance somewhere in the date range</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>C1</th> <th>c2</th> <th>c3</th> </tr> </thead> <tbody> <tr> <td>149000</td> <td>2022-06-21 00:00:00.000</td> <td>Telephone</td> </tr> <tr> <td>149000</td> <td>2022-06-21 00:00:00.000</td> <td>Video</td> </tr> <tr> <td>149000</td> <td>2022-06-24 00:00:00.000</td> <td>Telephone</td> </tr> <tr> <td>149000</td> <td>2022-07-08 00:00:00.000</td> <td>Telephone</td> </tr> <tr> <td>149000</td> <td>2022-07-15 00:00:00.000</td> <td>Telephone</td> </tr> <tr> <td>149000</td> <td>2022-07-22 00:00:00.000</td> <td>Telephone</td> </tr> <tr> <td>149000</td> <td>2022-07-29 00:00:00.000</td> <td>Telephone</td> </tr> <tr> <td>149000</td> <td>2022-08-12 00:00:00.000</td> <td>Telephone</td> </tr> <tr> <td>149000</td> <td>2022-08-26 00:00:00.000</td> <td>Telephone</td> </tr> <tr> <td>149000</td> <td>2022-09-01 00:00:00.000</td> <td>Face-to-Face</td> </tr> <tr> <td>149000</td> <td>2022-09-01 00:00:00.000</td> <td>Face-to-Face</td> </tr> <tr> <td>149000</td> <td>2022-09-12 00:00:00.000</td> <td>Telephone</td> </tr> <tr> <td>149000</td> <td>2022-09-12 00:00:00.000</td> <td>Video</td> </tr> </tbody> </table> </div> <p>The two commented lines are tests lines to see what it would do to my results.</p> <pre><code>SELECT c1 ,c2 ,C3 FROM a1 WHERE not exists (SELECT * FROM a1 as B WHERE b.c1 = a1.c1 and (b.c3= 'Face-to-Face' or b.c3 = 'Video') ) --and a1.c2 between '2022-06-01' and '2022-06-30') --and a1.c2 = b.c2) and c2 between '2022-01-01' and '2022-12-30' </code></pre>
[ { "answer_id": 74480359, "author": "Abe", "author_id": 18092664, "author_profile": "https://Stackoverflow.com/users/18092664", "pm_score": -1, "selected": false, "text": "select main.* \nfrom a1 main\nwhere extract(month from main.c2) not in(\n select extract(month from sub.c2)\n from a1 sub\n where sub.c3 in ('Video', 'Face-to-Face')\n)\n" }, { "answer_id": 74481244, "author": "b_loy", "author_id": 20382717, "author_profile": "https://Stackoverflow.com/users/20382717", "pm_score": 0, "selected": false, "text": "SELECT c1, c2, c3\nFROM a1\nWHERE DATEPART(MONTH, c2) NOT IN (\n SELECT DATEPART(MONTH, c2) FROM a1 WHERE c3 IN ('Video', 'Face-to-Face')\n)\n" }, { "answer_id": 74482909, "author": "Tony Pham", "author_id": 20505025, "author_profile": "https://Stackoverflow.com/users/20505025", "pm_score": 0, "selected": false, "text": "SELECT \n c1\n ,c2\n ,C3\n\nFROM a1\n\nWHERE\nDATEADD(month, DATEDIFF(MONTH, 0, c2), 0) not in (\nSelect DATEADD(month, DATEDIFF(MONTH, 0, c2), 0) \nfrom a1 \nwhere c1= a1.c1 and c3 IN ('Video', 'Face-to-Face'))\n\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20505025/" ]
74,480,257
<p>I need to select the count of unique value combinations of column B in an XRef table which is grouped by column A.</p> <p>Consider the following schema and data, which represents a simple family structure. Each child has a father and mother:</p> <p><strong>TABLE Father</strong></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>FatherID</th> <th>Name</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Alex</td> </tr> <tr> <td>2</td> <td>Bob</td> </tr> </tbody> </table> </div> <p><strong>TABLE Mother</strong></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>MotherID</th> <th>Name</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Alice</td> </tr> <tr> <td>2</td> <td>Barbara</td> </tr> </tbody> </table> </div> <p><strong>TABLE Child</strong></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ChildID</th> <th>FatherID</th> <th>MotherID</th> <th>Name</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>1 (Alex)</td> <td>1 (Alice)</td> <td>Adam</td> </tr> <tr> <td>2</td> <td>1 (Alex)</td> <td>1 (Alice)</td> <td>Billy</td> </tr> <tr> <td>3</td> <td>1 (Alex)</td> <td>2 (Barbara)</td> <td>Celine</td> </tr> <tr> <td>4</td> <td>2 (Bob)</td> <td>2 (Barbara)</td> <td>Derek</td> </tr> </tbody> </table> </div> <p>The distinct combinations of mothers for each father are:</p> <ul> <li>Alex (Alice, Barbara)</li> <li>Bob (Barbara)</li> </ul> <p>In all there are <strong>two distinct combinations of mothers</strong>:</p> <ol> <li>Alice, Barbara</li> <li>Barbara</li> </ol> <p>The query I want to write would return the count of those distinct combinations of mother, <em>regardless of which father they are associated with</em>:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>UniqueMotherGroups</th> </tr> </thead> <tbody> <tr> <td>2</td> </tr> </tbody> </table> </div> <p>I was able to do this successfully using the STRING_AGG function, but it feels clunky. It also needs to operate over millions of rows and is quite slow at the moment. Is there a more idiomatic way to do this with set operations instead?</p> <p>Here is my working example:</p> <pre><code>-- Drop pre-existing tables DROP TABLE IF EXISTS dbo.Child; DROP TABLE IF EXISTS dbo.Father; DROP TABLE IF EXISTS dbo.Mother; -- Create family tables. CREATE TABLE dbo.Father ( FatherID INT NOT NULL , Name VARCHAR(50) NOT NULL ); ALTER TABLE dbo.Father ADD CONSTRAINT PK_Father PRIMARY KEY CLUSTERED (FatherID); ALTER TABLE dbo.Father SET (LOCK_ESCALATION = TABLE); CREATE TABLE dbo.Mother ( MotherID INT NOT NULL , Name VARCHAR(50) NOT NULL ); ALTER TABLE dbo.Mother ADD CONSTRAINT PK_Mother PRIMARY KEY CLUSTERED (MotherID); ALTER TABLE dbo.Mother SET (LOCK_ESCALATION = TABLE); CREATE TABLE dbo.Child ( ChildID INT NOT NULL , FatherID INT NOT NULL , MotherID INT NOT NULL , Name VARCHAR(50) NOT NULL ); ALTER TABLE dbo.Child ADD CONSTRAINT PK_Child PRIMARY KEY CLUSTERED (ChildID); CREATE NONCLUSTERED INDEX IX_Parents ON dbo.Child (FatherID, MotherID); ALTER TABLE dbo.Child ADD CONSTRAINT FK_Child_Father FOREIGN KEY (FatherID) REFERENCES dbo.Father (FatherID); ALTER TABLE dbo.Child ADD CONSTRAINT FK_Child_Mother FOREIGN KEY (MotherID) REFERENCES dbo.Mother (MotherID); -- Insert two children with the same parents INSERT INTO dbo.Father ( FatherID , Name ) VALUES (1, 'Alex') , (2, 'Bob') , (3, 'Charlie') INSERT INTO dbo.Mother ( MotherID , Name ) VALUES (1, 'Alice') , (2, 'Barbara'); INSERT INTO dbo.Child ( ChildID , FatherID , MotherID , Name ) VALUES (1, 1, 1, 'Adam') , (2, 1, 1, 'Billy') , (3, 1, 2, 'Celine') , (4, 2, 2, 'Derek') , (5, 3, 1, 'Eric'); -- CTE Gets distinct combinations of parents WITH distinctParentCombinations (FatherID, MotherID) AS (SELECT children.FatherID , children.MotherID FROM dbo.Child as children GROUP BY children.FatherID , children.MotherID ) -- CTE Gets uses STRING_AGG to get unique combinations of mothers. , motherGroups (Mothers) AS (SELECT STRING_AGG(CONVERT(VARCHAR(MAX), distinctParentCombinations.MotherID), '-') WITHIN GROUP (ORDER BY distinctParentCombinations.MotherID) AS Mothers FROM distinctParentCombinations GROUP BY distinctParentCombinations.FatherID ) -- Remove the COUNT function to see the actual combinations SELECT COUNT(motherGroups.Mothers) AS UniqueMotherGroups FROM motherGroups -- Clean up the example DROP TABLE IF EXISTS dbo.Child; DROP TABLE IF EXISTS dbo.Father; DROP TABLE IF EXISTS dbo.Mother; </code></pre>
[ { "answer_id": 74482243, "author": "Tim Jarosz", "author_id": 2452207, "author_profile": "https://Stackoverflow.com/users/2452207", "pm_score": 1, "selected": false, "text": "CREATE" }, { "answer_id": 74646659, "author": "p3consulting", "author_id": 4956336, "author_profile": "https://Stackoverflow.com/users/4956336", "pm_score": 0, "selected": false, "text": "select count(*) as UniqueMotherGroups from (\nselect distinct m1, m2, m3, m4, m5, m6, m7 from (\n select FatherID, row_number() over(partition by FatherID order by motherid) as rn, motherid\n from (\n select distinct FatherID, MotherID\n from t_Child \n )\n)\npivot (\n max(motherid) for rn in (1 as m1,2 as m2,3 as m3,4 as m4,5 as m5,6 as m6,7 as m7)\n)\n)\n;\n\n\nUNIQUEMOTHERGROUPS\n------------------\n 3\n" }, { "answer_id": 74674690, "author": "Vladimir Baranov", "author_id": 4116017, "author_profile": "https://Stackoverflow.com/users/4116017", "pm_score": 0, "selected": false, "text": "STRING_AGG" }, { "answer_id": 74675968, "author": "Johnny", "author_id": 15232829, "author_profile": "https://Stackoverflow.com/users/15232829", "pm_score": 0, "selected": false, "text": "-- Column 1: Hashed value of the aggregated mother group for each Father row.\nalter table Father add MotherHash varbinary(1600)\ncreate index IX_MotherHash on Father(MotherHash) \n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/406732/" ]
74,480,291
<p>I have a data frame that looks like:</p> <pre><code>Amount person1 person2 person3 pocketmoney 0.5 1.3 1.7 chores 3 5 2 </code></pre> <p>How do I turn it into something like this:</p> <pre><code> Person Pocketmoney chores person1 0.5 3 person2 1.3 5 person3 1.7 2 </code></pre> <p>Thanks!</p>
[ { "answer_id": 74482243, "author": "Tim Jarosz", "author_id": 2452207, "author_profile": "https://Stackoverflow.com/users/2452207", "pm_score": 1, "selected": false, "text": "CREATE" }, { "answer_id": 74646659, "author": "p3consulting", "author_id": 4956336, "author_profile": "https://Stackoverflow.com/users/4956336", "pm_score": 0, "selected": false, "text": "select count(*) as UniqueMotherGroups from (\nselect distinct m1, m2, m3, m4, m5, m6, m7 from (\n select FatherID, row_number() over(partition by FatherID order by motherid) as rn, motherid\n from (\n select distinct FatherID, MotherID\n from t_Child \n )\n)\npivot (\n max(motherid) for rn in (1 as m1,2 as m2,3 as m3,4 as m4,5 as m5,6 as m6,7 as m7)\n)\n)\n;\n\n\nUNIQUEMOTHERGROUPS\n------------------\n 3\n" }, { "answer_id": 74674690, "author": "Vladimir Baranov", "author_id": 4116017, "author_profile": "https://Stackoverflow.com/users/4116017", "pm_score": 0, "selected": false, "text": "STRING_AGG" }, { "answer_id": 74675968, "author": "Johnny", "author_id": 15232829, "author_profile": "https://Stackoverflow.com/users/15232829", "pm_score": 0, "selected": false, "text": "-- Column 1: Hashed value of the aggregated mother group for each Father row.\nalter table Father add MotherHash varbinary(1600)\ncreate index IX_MotherHash on Father(MotherHash) \n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20322342/" ]
74,480,336
<p>As stated, I would like to use a Mock where all of the void methods are inhibited.</p> <p>I am mocking a CLASS and not an interface. The default behaviour is to run the class methods.</p> <pre><code>MyClass = new Mock&lt;MyClass&gt;().Object; </code></pre> <p>Obviously, I can setup all of the methods to do nothing:</p> <pre><code>mock.Setup(p =&gt; p.MyMethod1(It.IsAny&lt;string&gt;())); mock.Setup(p =&gt; p.MyMethod2(It.IsAny&lt;string&gt;())); </code></pre> <p>etc...</p> <p>But maybe there is a special behaviour that does it without I need to do anything?</p> <p>EDIT: nothing particular about the class / methods themselves AFAIK.</p> <pre><code>public class MyClass { ... public void MyMT(int p1, int? p2...) { ... } } </code></pre> <p>The method calls I would like to &quot;short-circuit&quot; are as follows:</p> <pre><code>myClassInstance.Mymt(p1, p2...); </code></pre> <p>If what I want is impossible to achieve, my other plan will be to create a class inheriting from MyClass and override the concerned methods so they won't do nothing in the child class. I just had the feeling that Moq could do this without a line of code in some of its modes.</p>
[ { "answer_id": 74482243, "author": "Tim Jarosz", "author_id": 2452207, "author_profile": "https://Stackoverflow.com/users/2452207", "pm_score": 1, "selected": false, "text": "CREATE" }, { "answer_id": 74646659, "author": "p3consulting", "author_id": 4956336, "author_profile": "https://Stackoverflow.com/users/4956336", "pm_score": 0, "selected": false, "text": "select count(*) as UniqueMotherGroups from (\nselect distinct m1, m2, m3, m4, m5, m6, m7 from (\n select FatherID, row_number() over(partition by FatherID order by motherid) as rn, motherid\n from (\n select distinct FatherID, MotherID\n from t_Child \n )\n)\npivot (\n max(motherid) for rn in (1 as m1,2 as m2,3 as m3,4 as m4,5 as m5,6 as m6,7 as m7)\n)\n)\n;\n\n\nUNIQUEMOTHERGROUPS\n------------------\n 3\n" }, { "answer_id": 74674690, "author": "Vladimir Baranov", "author_id": 4116017, "author_profile": "https://Stackoverflow.com/users/4116017", "pm_score": 0, "selected": false, "text": "STRING_AGG" }, { "answer_id": 74675968, "author": "Johnny", "author_id": 15232829, "author_profile": "https://Stackoverflow.com/users/15232829", "pm_score": 0, "selected": false, "text": "-- Column 1: Hashed value of the aggregated mother group for each Father row.\nalter table Father add MotherHash varbinary(1600)\ncreate index IX_MotherHash on Father(MotherHash) \n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5317085/" ]
74,480,365
<p>I have below drawing image which is an arc of a circumference and now I would like to apply rotations from 0 to 360 in a loop indefinitely to simulate a spinner animated. Something like you can see <a href="https://www.lowgif.com/dc86e54ceca03be4.html" rel="nofollow noreferrer">here</a>, an arc of circumference rotating forever.</p> <p><a href="https://i.stack.imgur.com/Dbpaq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Dbpaq.png" alt="enter image description here" /></a></p> <pre><code>&lt;DrawingImage x:Key=&quot;ico_spinnerDrawingImage&quot;&gt; &lt;DrawingImage.Drawing&gt; &lt;DrawingGroup ClipGeometry=&quot;M0,0 V12 H12 V0 H0 Z&quot;&gt; &lt;DrawingGroup.Transform&gt; &lt;TranslateTransform X=&quot;9.5367397534573684E-07&quot; Y=&quot;1.1465158453161615E-14&quot; /&gt; &lt;/DrawingGroup.Transform&gt; &lt;GeometryDrawing Brush=&quot;#FF00AA2B&quot; Geometry=&quot;F1 M12,12z M0,0z M12,12C12,10.4241 11.6896,8.86371 11.0866,7.4078 10.4835,5.95189 9.59958,4.62902 8.48528,3.51472 7.37098,2.40042 6.04811,1.5165 4.5922,0.913445 3.13629,0.310389 1.57586,-6.88831E-08 -9.53674E-07,0L0,3C1.1819,3 2.35222,3.23279 3.44415,3.68508 4.53608,4.13738 5.52823,4.80031 6.36396,5.63604 7.19969,6.47177 7.86262,7.46392 8.31492,8.55585 8.76721,9.64778 9,10.8181 9,12L12,12z&quot; /&gt; &lt;/DrawingGroup&gt; &lt;/DrawingImage.Drawing&gt; &lt;/DrawingImage&gt; </code></pre> <p>Above drawingimage is inclosed within a dictionary that I import to my WPF view and I associate it to the source property of an WPF image by doing this (i removed the not relevant properties):</p> <pre><code> &lt;Image Source=&quot;{Binding Path=MySpinnerIcon}&quot;/&gt; </code></pre> <p>Now, how can apply that animation to the drawingimage to simulate an animated spinner circling continuously forever?</p>
[ { "answer_id": 74480873, "author": "Clemens", "author_id": 1136211, "author_profile": "https://Stackoverflow.com/users/1136211", "pm_score": 2, "selected": true, "text": "Angle" }, { "answer_id": 74481397, "author": "EldHasp", "author_id": 13349759, "author_profile": "https://Stackoverflow.com/users/13349759", "pm_score": 1, "selected": false, "text": "<StackPanel>\n <FrameworkElement.Resources>\n <Pen x:Key=\"сircle\" Brush=\"LightGray\" Thickness=\"5\"/>\n <Pen x:Key=\"arc\" Brush=\"LightGreen\" Thickness=\"5\" EndLineCap=\"Round\" StartLineCap=\"Round\"/>\n <DrawingImage x:Key=\"ico_spinnerDrawingImage\">\n <DrawingImage.Drawing>\n <DrawingGroup>\n <DrawingGroup.Transform>\n <RotateTransform Angle=\"0\"/>\n </DrawingGroup.Transform>\n <GeometryDrawing Pen=\"{StaticResource сircle}\">\n <GeometryDrawing.Geometry>\n <EllipseGeometry Center=\"0,0\" RadiusX=\"10\" RadiusY=\"10\"/>\n </GeometryDrawing.Geometry>\n </GeometryDrawing>\n <GeometryDrawing Geometry=\"M10,0 A10,10 90 0 1 0,10\"\n Pen=\"{StaticResource arc}\"/>\n </DrawingGroup>\n </DrawingImage.Drawing>\n </DrawingImage>\n </FrameworkElement.Resources>\n\n <Image Source=\"{DynamicResource ico_spinnerDrawingImage}\" Width=\"100\">\n <Image.Triggers>\n <EventTrigger RoutedEvent=\"Loaded\">\n <BeginStoryboard>\n <Storyboard>\n <DoubleAnimation From=\"0\" To=\"360\" Duration=\"0:0:1\"\n Storyboard.TargetProperty=\"Source.Drawing.Transform.Angle\"\n RepeatBehavior=\"Forever\"/>\n </Storyboard>\n </BeginStoryboard>\n </EventTrigger>\n </Image.Triggers>\n </Image>\n</StackPanel>\n" }, { "answer_id": 74485201, "author": "New Guy", "author_id": 19433977, "author_profile": "https://Stackoverflow.com/users/19433977", "pm_score": -1, "selected": false, "text": "<Grid>\n <Grid.ColumnDefinitions>\n <ColumnDefinition Width=\"*\"/>\n </Grid.ColumnDefinitions>\n <ed:Arc Grid.Column=\"0\" x:Name=\"Arc1\" ArcThickness=\"5\" Height=\"32\" Width=\"32\" StartAngle=\"0\" EndAngle=\"360\" Stretch=\"None\" Fill=\"Gray\"/>\n <ed:Arc Grid.Column=\"0\" x:Name=\"Arc2\" ArcThickness=\"5\" Height=\"32\" Width=\"32\" StartAngle=\"0\" EndAngle=\"45\" Stretch=\"None\" Fill=\"DeepSkyBlue\"/>\n</Grid>\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1624552/" ]
74,480,379
<p>Im trying to add coördinates to a set of addresses that are saved in an excel file using the google geocoder API. See code below:</p> <pre><code>for i, row in df.iterrows(): #below combines the address columns together in one variable, to push to the geocoder API. apiAddress = str(df.at[i, 'adresse1']) + ',' + str(df.at[i, 'postnr']) + ',' + str(df.at[i, 'By']) #below creates a dictionary with the API key and the address info, to push to the Geocoder API on each iteration parameters = { 'key' : API_KEY, 'address' : apiAddress } #response from the API, based on the input url + the dictionary above. response = requests.get(base_url, params = parameters).json() #when you look at the response, it is given as a dictionary. with this command I access the geometry part of the dictionary. geometry = response['results'][0]['geometry'] #within the geometry party of the dictionary given by the API, I access the lat and lng respectively. lat = geometry['location']['lat'] lng = geometry['location']['lng'] #here I append the lat / lng to a new column in the dataframe for each iteration. df.at[i, 'Geo_Lat_New'] = lat df.at[i, 'Geo_Lng_New'] = lng #printing the first 10 rows. print(df.head(10)) </code></pre> <p>the above code works perfectly fine for 20 addresses. But when I try to run it on the entire dataset of 90000 addresses; using iterrows() I get a IndexError:</p> <pre><code> File &quot;C:\Users\...&quot;, line 29, in &lt;module&gt; geometry = response['results'][0]['geometry'] IndexError: list index out of range </code></pre> <p>Using itertuples() instead, with:</p> <pre><code>for i, row in df.itertuples(): </code></pre> <p>I get a ValueError:</p> <pre><code> File &quot;C:\Users\...&quot;, line 22, in &lt;module&gt; for i, row in df.itertuples(): ValueError: too many values to unpack (expected 2) </code></pre> <p>when I use:</p> <pre><code>for i in df.itertuples(): </code></pre> <p>I get a complicated KeyError. That is to long to put here.</p> <p>Any suggestions on how to properly add coördinates for each address in the entire dataframe?</p>
[ { "answer_id": 74480873, "author": "Clemens", "author_id": 1136211, "author_profile": "https://Stackoverflow.com/users/1136211", "pm_score": 2, "selected": true, "text": "Angle" }, { "answer_id": 74481397, "author": "EldHasp", "author_id": 13349759, "author_profile": "https://Stackoverflow.com/users/13349759", "pm_score": 1, "selected": false, "text": "<StackPanel>\n <FrameworkElement.Resources>\n <Pen x:Key=\"сircle\" Brush=\"LightGray\" Thickness=\"5\"/>\n <Pen x:Key=\"arc\" Brush=\"LightGreen\" Thickness=\"5\" EndLineCap=\"Round\" StartLineCap=\"Round\"/>\n <DrawingImage x:Key=\"ico_spinnerDrawingImage\">\n <DrawingImage.Drawing>\n <DrawingGroup>\n <DrawingGroup.Transform>\n <RotateTransform Angle=\"0\"/>\n </DrawingGroup.Transform>\n <GeometryDrawing Pen=\"{StaticResource сircle}\">\n <GeometryDrawing.Geometry>\n <EllipseGeometry Center=\"0,0\" RadiusX=\"10\" RadiusY=\"10\"/>\n </GeometryDrawing.Geometry>\n </GeometryDrawing>\n <GeometryDrawing Geometry=\"M10,0 A10,10 90 0 1 0,10\"\n Pen=\"{StaticResource arc}\"/>\n </DrawingGroup>\n </DrawingImage.Drawing>\n </DrawingImage>\n </FrameworkElement.Resources>\n\n <Image Source=\"{DynamicResource ico_spinnerDrawingImage}\" Width=\"100\">\n <Image.Triggers>\n <EventTrigger RoutedEvent=\"Loaded\">\n <BeginStoryboard>\n <Storyboard>\n <DoubleAnimation From=\"0\" To=\"360\" Duration=\"0:0:1\"\n Storyboard.TargetProperty=\"Source.Drawing.Transform.Angle\"\n RepeatBehavior=\"Forever\"/>\n </Storyboard>\n </BeginStoryboard>\n </EventTrigger>\n </Image.Triggers>\n </Image>\n</StackPanel>\n" }, { "answer_id": 74485201, "author": "New Guy", "author_id": 19433977, "author_profile": "https://Stackoverflow.com/users/19433977", "pm_score": -1, "selected": false, "text": "<Grid>\n <Grid.ColumnDefinitions>\n <ColumnDefinition Width=\"*\"/>\n </Grid.ColumnDefinitions>\n <ed:Arc Grid.Column=\"0\" x:Name=\"Arc1\" ArcThickness=\"5\" Height=\"32\" Width=\"32\" StartAngle=\"0\" EndAngle=\"360\" Stretch=\"None\" Fill=\"Gray\"/>\n <ed:Arc Grid.Column=\"0\" x:Name=\"Arc2\" ArcThickness=\"5\" Height=\"32\" Width=\"32\" StartAngle=\"0\" EndAngle=\"45\" Stretch=\"None\" Fill=\"DeepSkyBlue\"/>\n</Grid>\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18861667/" ]
74,480,381
<p>I have a query that return values ​​based on a boolean column: if the id_crsp includes a boolean true AND false, then it is selected. Values ​​of id_crsp that have only a true or false value are not selected.</p> <p>From this result, I would like to sort the id_crsp which have duplicates, and select only the one with the oldest date</p> <p>Database values :</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">id</th> <th style="text-align: center;">idcrsp</th> <th style="text-align: right;">date</th> <th>boolean</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">1</td> <td style="text-align: center;">100</td> <td style="text-align: right;">11-2022</td> <td>true</td> </tr> <tr> <td style="text-align: left;">2</td> <td style="text-align: center;">100</td> <td style="text-align: right;">07-2022</td> <td>false</td> </tr> <tr> <td style="text-align: left;">3</td> <td style="text-align: center;">200</td> <td style="text-align: right;">06-2022</td> <td>false</td> </tr> <tr> <td style="text-align: left;">4</td> <td style="text-align: center;">300</td> <td style="text-align: right;">09-2022</td> <td>true</td> </tr> <tr> <td style="text-align: left;">5</td> <td style="text-align: center;">300</td> <td style="text-align: right;">08-2022</td> <td>false</td> </tr> <tr> <td style="text-align: left;">6</td> <td style="text-align: center;">400</td> <td style="text-align: right;">10-2022</td> <td>false</td> </tr> <tr> <td style="text-align: left;">7</td> <td style="text-align: center;">100</td> <td style="text-align: right;">01-2022</td> <td>false</td> </tr> <tr> <td style="text-align: left;">8</td> <td style="text-align: center;">100</td> <td style="text-align: right;">02-2022</td> <td>false</td> </tr> </tbody> </table> </div> <p>My actual request :</p> <pre><code>SELECT true_table.* FROM mydb as true_table INNER JOIN (SELECT * FROM mydb WHERE requalif=TRUE) as false_table ON true_table.idcrsp = false_table.idcrsp AND true_table.requalif = FALSE; </code></pre> <p>This return :</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">id</th> <th style="text-align: center;">idcrsp</th> <th style="text-align: right;">date</th> <th>boolean</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">8</td> <td style="text-align: center;">100</td> <td style="text-align: right;">02-2022</td> <td>false</td> </tr> <tr> <td style="text-align: left;">7</td> <td style="text-align: center;">100</td> <td style="text-align: right;">01-2022</td> <td>false</td> </tr> <tr> <td style="text-align: left;">2</td> <td style="text-align: center;">100</td> <td style="text-align: right;">07-2022</td> <td>false</td> </tr> <tr> <td style="text-align: left;">5</td> <td style="text-align: center;">300</td> <td style="text-align: right;">08-2022</td> <td>false</td> </tr> </tbody> </table> </div> <p>I would like to enrich my request in order to have only two lines:</p> <ul> <li>id 5</li> <li>id 7 (which has duplicates of id_crsp and which has the oldest date).</li> </ul> <p>Thanks for your help !</p>
[ { "answer_id": 74480873, "author": "Clemens", "author_id": 1136211, "author_profile": "https://Stackoverflow.com/users/1136211", "pm_score": 2, "selected": true, "text": "Angle" }, { "answer_id": 74481397, "author": "EldHasp", "author_id": 13349759, "author_profile": "https://Stackoverflow.com/users/13349759", "pm_score": 1, "selected": false, "text": "<StackPanel>\n <FrameworkElement.Resources>\n <Pen x:Key=\"сircle\" Brush=\"LightGray\" Thickness=\"5\"/>\n <Pen x:Key=\"arc\" Brush=\"LightGreen\" Thickness=\"5\" EndLineCap=\"Round\" StartLineCap=\"Round\"/>\n <DrawingImage x:Key=\"ico_spinnerDrawingImage\">\n <DrawingImage.Drawing>\n <DrawingGroup>\n <DrawingGroup.Transform>\n <RotateTransform Angle=\"0\"/>\n </DrawingGroup.Transform>\n <GeometryDrawing Pen=\"{StaticResource сircle}\">\n <GeometryDrawing.Geometry>\n <EllipseGeometry Center=\"0,0\" RadiusX=\"10\" RadiusY=\"10\"/>\n </GeometryDrawing.Geometry>\n </GeometryDrawing>\n <GeometryDrawing Geometry=\"M10,0 A10,10 90 0 1 0,10\"\n Pen=\"{StaticResource arc}\"/>\n </DrawingGroup>\n </DrawingImage.Drawing>\n </DrawingImage>\n </FrameworkElement.Resources>\n\n <Image Source=\"{DynamicResource ico_spinnerDrawingImage}\" Width=\"100\">\n <Image.Triggers>\n <EventTrigger RoutedEvent=\"Loaded\">\n <BeginStoryboard>\n <Storyboard>\n <DoubleAnimation From=\"0\" To=\"360\" Duration=\"0:0:1\"\n Storyboard.TargetProperty=\"Source.Drawing.Transform.Angle\"\n RepeatBehavior=\"Forever\"/>\n </Storyboard>\n </BeginStoryboard>\n </EventTrigger>\n </Image.Triggers>\n </Image>\n</StackPanel>\n" }, { "answer_id": 74485201, "author": "New Guy", "author_id": 19433977, "author_profile": "https://Stackoverflow.com/users/19433977", "pm_score": -1, "selected": false, "text": "<Grid>\n <Grid.ColumnDefinitions>\n <ColumnDefinition Width=\"*\"/>\n </Grid.ColumnDefinitions>\n <ed:Arc Grid.Column=\"0\" x:Name=\"Arc1\" ArcThickness=\"5\" Height=\"32\" Width=\"32\" StartAngle=\"0\" EndAngle=\"360\" Stretch=\"None\" Fill=\"Gray\"/>\n <ed:Arc Grid.Column=\"0\" x:Name=\"Arc2\" ArcThickness=\"5\" Height=\"32\" Width=\"32\" StartAngle=\"0\" EndAngle=\"45\" Stretch=\"None\" Fill=\"DeepSkyBlue\"/>\n</Grid>\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14131200/" ]
74,480,474
<p>Given the following two tables</p> <p>users</p> <pre><code>user_id name join_date 1 Jon 2020-02-14 2 Jane 2020-02-14 3 Jill 2020-02-15 4 Josh 2020-02-15 5 Jean 2020-02-16 6 Justin 2020-02-17 7 Jeremy 2020-02-18 </code></pre> <p>events</p> <pre><code>user_id type access_date 1 F1 2020-03-01 2 F2 2020-03-02 2 P 2020-03-12 3 F2 2020-03-15 4 F2 2020-03-15 1 P 2020-03-16 3 P 2020-03-22 </code></pre> <p>return the fraction of users, rounded to two decimal places, who accessed feature two (type: F2 in events table) and upgraded to premium within the first 30 days of signing up. It should give upgrade_rate 0.33.</p> <p>Here is my attempt</p> <pre><code>;WITH users AS ( SELECT * FROM ( VALUES (1, 'Jon', CAST('14-02-20' AS date)), (2, 'Jane', CAST('14-02-20' AS date)), (3, 'Jill', CAST('15-02-20' AS date)), (4, 'Josh', CAST('15-02-20' AS date)), (5, 'Jean', CAST('16-02-20' AS date)), (6, 'Justin', CAST('17-02-20' AS date)), (7, 'Jeremy', CAST('18-02-20' AS date)) ) AS _ (user_id, name, join_date) ), events AS ( SELECT * FROM ( VALUES (1, 'F1', CAST('01-03-20' AS date)), (2, 'F2', CAST('02-03-20' AS date)), (2, 'P', CAST('12-03-20' AS date)), (3, 'F2', CAST('15-03-20' AS date)), (4, 'F2', CAST('15-03-20' AS date)), (1, 'P', CAST('16-03-20' AS date)), (3, 'P', CAST('22-03-20' AS date)) ) AS _ (user_id, type, access_date) ), feature_two_upg AS ( SELECT * FROM events WHERE type = 'F2' ), premium_upg AS ( SELECT * FROM events WHERE type = 'P' ), differ_date AS ( SELECT feature.user_id, premium.access_date FROM feature_two_upg AS feature INNER JOIN premium_upg AS premium ON feature.user_id = premium.user_id WHERE DATEDIFF(DAY, feature.access_date, premium.access_date) &lt; 30 ) SELECT ROUND(AVG(CAST(CASE WHEN differ_date.user_id IS NOT NULL THEN 1.0 ELSE 0.0 END AS float)), 2) AS upgrade_rate FROM users LEFT JOIN differ_date ON users.user_id = differ_date.user_id </code></pre> <p>Right now it's giving me 0.29 upgrade_rate and I'm wondering why</p>
[ { "answer_id": 74481076, "author": "Diego", "author_id": 20478349, "author_profile": "https://Stackoverflow.com/users/20478349", "pm_score": 1, "selected": false, "text": "SELECT users.user_id, differ_date.user_id\nFROM users\nLEFT JOIN differ_date\nON users.user_id = differ_date.user_id\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17775991/" ]
74,480,475
<p>I wrote a code in C# that get the user input and saves it in a JSON file, but like I need a database, that means that I'll need write several lines, but that's the problem, the code do not put it inside the []. Here is the output:</p> <pre class="lang-json prettyprint-override"><code>[ {&quot;modelo&quot;:&quot;gtr&quot;,&quot;ano&quot;:2004,&quot;cor&quot;:&quot;branco&quot;,&quot;marca&quot;:&quot;nissan&quot;,&quot;placa&quot;:&quot;123abc&quot;,&quot;completo&quot;:&quot;sim&quot;,&quot;potencia&quot;:500}, {&quot;modelo&quot;:&quot;gol&quot;,&quot;ano&quot;:2023,&quot;cor&quot;:&quot;preto&quot;,&quot;marca&quot;:&quot;volkswagen&quot;,&quot;placa&quot;:&quot;23b4ab&quot;,&quot;completo&quot;:&quot;sim&quot;,&quot;potencia&quot;:130}, {&quot;modelo&quot;:&quot;enzo&quot;,&quot;ano&quot;:2015,&quot;cor&quot;:&quot;vermelho&quot;,&quot;marca&quot;:&quot;ferrari&quot;,&quot;placa&quot;:&quot;123456a&quot;,&quot;completo&quot;:&quot;sim&quot;,&quot;potencia&quot;:700} ] </code></pre> <p>As you can see, the lines inside the [], I put manually, that one below is automatic by the code, I have to put that line inside the [].</p> <pre class="lang-json prettyprint-override"><code>{&quot;modelo&quot;:&quot;292&quot;,&quot;ano&quot;:11,&quot;cor&quot;:&quot;11&quot;,&quot;marca&quot;:&quot;292&quot;,&quot;placa&quot;:&quot;1&quot;,&quot;completo&quot;:&quot;11&quot;,&quot;potencia&quot;:1} </code></pre> <p>and here is the code:</p> <pre><code>string jsonString = JsonSerializer.Serialize(estoque); Console.WriteLine(jsonString); string filePath = @&quot;C:\Users\willi\Desktop\programas\CarDataBase\data.json&quot;; List&lt;string&gt; lines = new List&lt;string&gt;(); lines = File.ReadAllLines(filePath).ToList(); foreach (string line in lines) { Console.WriteLine(line); } lines.Add(jsonString); // lines.Add(); lines.Add(&quot;&quot;); File.WriteAllLines(filePath, lines); </code></pre> <p>I have to put the lines(output) inside the [], as I explained above</p>
[ { "answer_id": 74480612, "author": "SNBS", "author_id": 20426120, "author_profile": "https://Stackoverflow.com/users/20426120", "pm_score": 2, "selected": false, "text": "JsonSerializer" }, { "answer_id": 74480947, "author": "Serge", "author_id": 11392290, "author_profile": "https://Stackoverflow.com/users/11392290", "pm_score": 2, "selected": false, "text": " using Newtonsoft.Json;\n\n string json = File.ReadAllText(filePath);\n\n var arr = JArray.Parse(json);\n \n var newObj = JObject.FromObject(estoque);\n\n arr.Add(newObj);\n\n json = arr.ToString();\n\n File.WriteAllText(filePath, json);\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15391900/" ]
74,480,500
<p>I'm trying to check what letters repeat in a string by creating a new array of only the repeated letters using the <code>.filter()</code> method but I only want the letter to appear one time, no matter how many times it repeats.</p> <p>This is what I tried:</p> <pre><code>const fullName = &quot;Muhammad Ali&quot;; const fullNameLowercase = fullName.toLowerCase(); const splitName = fullNameLowercase.split(&quot;&quot;); let repeats = splitName.filter((letter, index) =&gt; {return splitName.indexOf(letter) !== index}); console.log(repeats); // prints [ 'm', 'm', 'a', 'a' ] </code></pre> <p>I want it to only add the letter once to the array <code>repeats</code>, how do I do it? Is there any other more efficient way to do what I want that doesn't use <code>.filter()</code>?</p>
[ { "answer_id": 74480553, "author": "El Mehdi", "author_id": 14529779, "author_profile": "https://Stackoverflow.com/users/14529779", "pm_score": 1, "selected": false, "text": "repeats" }, { "answer_id": 74480616, "author": "Lucasbk38", "author_id": 20480528, "author_profile": "https://Stackoverflow.com/users/20480528", "pm_score": 0, "selected": false, "text": "const fullName = 'Muhammad Ali';\nconst fullNameLowercase = fullName.toLowerCase();\nconst splitName = fullNameLowercase.split('');\n\nlet repeats = splitName\n .filter((e, i) => splitName.indexOf(e) !== i)\n /* we create an empty array and for every letter :\n - if the letter is already in the array: don't do anything\n - if the letter isn't already in the array: add it to the array\n it returns us the array without duplicates\n */\n .reduce((g, c) => g.includes(c) ? g : g.concat([c]), []);\n \nconsole.log(repeats);" }, { "answer_id": 74480675, "author": "symlink", "author_id": 818326, "author_profile": "https://Stackoverflow.com/users/818326", "pm_score": 0, "selected": false, "text": "Array.filter()" }, { "answer_id": 74480711, "author": "Mister Jojo", "author_id": 10669010, "author_profile": "https://Stackoverflow.com/users/10669010", "pm_score": 0, "selected": false, "text": "const repeatLetters=s=>Object.keys([...s.toLowerCase()].reduce((r,c,i,a)=>((a.indexOf(c)<i)?r[c]='':'',r),{})) \n\nconsole.log( repeatLetters('Muhammad Ali') )" }, { "answer_id": 74481337, "author": "gog", "author_id": 3494774, "author_profile": "https://Stackoverflow.com/users/3494774", "pm_score": 1, "selected": false, "text": "let str = \"Muhammad Ali\"\nlet counter = new Map\n\nfor (let char of str.toLowerCase())\n counter.set(char, 1 + (counter.get(char) ?? 0))\n\nlet repeats = []\n\nfor (let [char, count] of counter)\n if (count > 1)\n repeats.push(char)\n \nconsole.log(repeats)" }, { "answer_id": 74481364, "author": "zer00ne", "author_id": 2813224, "author_profile": "https://Stackoverflow.com/users/2813224", "pm_score": 0, "selected": false, "text": "filter()" }, { "answer_id": 74483437, "author": "PeterKA", "author_id": 3558931, "author_profile": "https://Stackoverflow.com/users/3558931", "pm_score": 0, "selected": false, "text": "[...new Set(repeats)]" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17250969/" ]
74,480,543
<p>I'm new to html/css and javascript. I want Buttons to be on the same line and they can be scrolled through horizontally... The problem is two</p> <ol> <li>I can't get them all in one line rather some are going to second line..</li> <li>I can't understand how can I have them all in one so I can scroll them horizontally...</li> </ol> <p>As attached images I want these circles to be on same line... What I have done is given below. But the problem is some of these circles are shown in next line... My code is Below Html:</p> <pre><code>&lt;html&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;Areeba Textile&lt;/title&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css&quot;&gt;&lt;/link&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;style.css&quot;&gt;&lt;/link&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Unstitch Cloth&lt;/h1&gt; &lt;p&gt;Category of Unstitch Cloth available&lt;/p&gt; &lt;div class=&quot;topnav circontain&quot;&gt; &lt;a href=&quot;&quot; &gt;Silk&lt;/a&gt; &lt;a href=&quot;&quot;&gt;Cotton&lt;/a&gt; &lt;a href=&quot;&quot;&gt;Lawn&lt;/a&gt; &lt;a href=&quot;&quot;&gt;Khadder&lt;/a&gt; &lt;a href=&quot;&quot;&gt;Linen&lt;/a&gt; &lt;a href=&quot;&quot;&gt;Shafoon&lt;/a&gt; &lt;a href=&quot;&quot;&gt;Chiffon&lt;/a&gt; &lt;a href=&quot;&quot;&gt;1 piece&lt;/a&gt; &lt;a href=&quot;&quot;&gt;2 piece&lt;/a&gt; &lt;a href=&quot;&quot;&gt;3 piece&lt;/a&gt; &lt;a href=&quot;&quot;&gt;Winter&lt;/a&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>CSS:</p> <pre><code>@import url(&quot;https://fonts.googleapis.com/css2?family=Sriracha&amp;display=swap&quot;); body { background-size: cover; background-repeat: no-repeat; color: #585858; margin: 0; padding: 0; font-family: 'Yaldevi', sans-serif; margin-top: 30px; box-sizing: border-box; } h1, p, h3 { text-align: center; color: black; } a { text-decoration: none; } .circontain a{ color: black; display: inline; height: 100px; width: 100px; line-height: 200px; background-color: pink; border-radius: 50%; margin-left: 50px; text-align: center; margin-top: 100px; padding: 18px; border: none; cursor: pointer; } .topnav { overflow-x: scroll; height: 150px; } .topnav a{ float: left; text-decoration: none; font-size: 17px; } /* Change the color of links on hover */ .topnav a:hover { background: rgba(255,0,0,0.5) ; color: black } /* Add a color to the active/current link */ .topnav a.active { background-color: #04AA6D; color: rgb(15, 13, 13,0.5); } </code></pre> <p>I want something like <a href="https://i.stack.imgur.com/jz01a.png" rel="nofollow noreferrer">this</a> or <a href="https://i.stack.imgur.com/4455o.png" rel="nofollow noreferrer">these </a> so that I can scroll horizontally...</p> <p>Lastly, Advanced Thankyou for help!</p>
[ { "answer_id": 74482197, "author": "Giorgi Shalamberidze", "author_id": 20248276, "author_profile": "https://Stackoverflow.com/users/20248276", "pm_score": 0, "selected": false, "text": "body {\n background-size: cover;\n background-repeat: no-repeat;\n color: #585858;\n margin: 0;\n padding: 0;\n font-family: 'Yaldevi', sans-serif;\n margin-top: 30px;\n box-sizing: border-box;\n}\n\n\n h1, p, h3 {\n text-align: center;\n color: black;\n }\n a {\n text-decoration: none;\n}\n\n.circontain a{\n color: black;\n /* display: inline; */\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100px;\n width: 100px;\n /* line-height: 200px; */ \n background-color: pink;\n border-radius: 50%;\n margin-left: 50px;\n text-align: center;\n margin-top: 100px;\n padding: 18px;\n border: none;\n cursor: pointer; \n} \n.topnav {\n height: auto;\n display: -webkit-box;\n overflow: auto;\n\n } \n .topnav a{\n float: left;\n text-decoration: none;\n font-size: 17px;\n }\n\n /* Change the color of links on hover */\n.topnav a:hover {\n background: rgba(255,0,0,0.5) ;\n color: black\n }\n\n /* Add a color to the active/current link */\n.topnav a.active {\n background-color: #04AA6D;\n color: rgb(15, 13, 13,0.5);\n }\n" }, { "answer_id": 74485064, "author": "unleashed gamer", "author_id": 13794470, "author_profile": "https://Stackoverflow.com/users/13794470", "pm_score": 0, "selected": false, "text": "<!DOCTYPE html> \n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<style>\ndiv.scrollmenu {\n background-color: #333;\n overflow: auto;\n white-space: nowrap;\n}\n\ndiv.scrollmenu a {\n display: inline-block;\n color: white;\n text-align: center;\n padding: 14px;\n text-decoration: none;\n}\n\ndiv.scrollmenu a:hover {\n background-color: #777;\n}\n</style>\n</head>\n<body>\n\n<div class=\"scrollmenu\">\n <a href=\"#home\">Home</a>\n <a href=\"#news\">News</a>\n <a href=\"#contact\">Contact</a>\n <a href=\"#about\">About</a>\n <a href=\"#support\">Support</a>\n <a href=\"#blog\">Blog</a>\n <a href=\"#tools\">Tools</a> \n <a href=\"#base\">Base</a>\n <a href=\"#custom\">Custom</a>\n <a href=\"#more\">More</a>\n <a href=\"#logo\">Logo</a>\n <a href=\"#friends\">Friends</a>\n <a href=\"#partners\">Partners</a>\n <a href=\"#people\">People</a>\n <a href=\"#work\">Work</a>\n</div>\n\n<h2>Horizontal Scrollable Menu</h2>\n<p>Resize the browser window to see the effect.</p>\n\n</body>\n</html>\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20520316/" ]
74,480,548
<p>I am following Microsoft documentation in obtaining credentials for Azure Graph API. <a href="https://learn.microsoft.com/en-us/graph/sdks/choose-authentication-providers?tabs=Java#authorization-code-provider" rel="nofollow noreferrer">This document</a> states that an unattended application should use <code>client credentials provider</code> when making web api calls.</p> <p>The <a href="https://learn.microsoft.com/en-us/graph/sdks/choose-authentication-providers?tabs=Java#client-credentials-provider" rel="nofollow noreferrer">example</a> in the documents for this is:</p> <pre><code>final ClientSecretCredential clientSecretCredential = new ClientSecretCredentialBuilder() .clientId(clientId) .clientSecret(clientSecret) .tenantId(tenant) .build(); List&lt;String&gt; scopes = Arrays.asList(&quot;https://graph.microsoft.com/.default&quot;); final TokenCredentialAuthProvider tokenCredentialAuthProvider = new TokenCredentialAuthProvider(scopes, clientSecretCredential); final GraphServiceClient graphClient = GraphServiceClient .builder() .authenticationProvider(tokenCredentialAuthProvider) .buildClient(); final User me = graphClient.me().buildRequest().get(); </code></pre> <p>But I encounter an exception on the last line:</p> <pre><code>Error message: /me request is only valid with delegated authentication flow. </code></pre> <p>In researching this error, I came across <a href="https://learn.microsoft.com/en-us/answers/questions/852080/how-to-fix-34me-request-is-only-valid-with-delegat.html" rel="nofollow noreferrer">this post</a> that explains the error further - which confuses me as to why the documentation would use what <em>appears to be</em> inappropriate example of how to consume this API. It appears to be <code>delegated permissions authorization code flow</code>.</p> <p><a href="https://stackoverflow.com/questions/70515836/code-badrequest-message-me-request-is-only-valid-with-delegated-authenticatio">This post</a> does not add any clarity.</p> <blockquote> <p>What is the correct way to make this call? Or is this the result of incorrect configuration settings in <a href="https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow#application-permissions" rel="nofollow noreferrer">Azure management console</a> for the app to use Application permissions instead of Delegated permissions?</p> </blockquote> <ul> <li>Azure identity = v1.3.1</li> </ul>
[ { "answer_id": 74483883, "author": "Derek Gusoff", "author_id": 1452528, "author_profile": "https://Stackoverflow.com/users/1452528", "pm_score": -1, "selected": false, "text": "/me" }, { "answer_id": 74495565, "author": "Roy Hinkley", "author_id": 371077, "author_profile": "https://Stackoverflow.com/users/371077", "pm_score": 1, "selected": true, "text": "graphClient.users(\"user-id\")" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/371077/" ]
74,480,557
<p>I'm a bit confused about what to do with this problem. I have to take a Stack and flip it, once flipped the elements in the stack have to also 'flip'. for example every string that reads 'blue' must now read 'red', every string that reads 'White' should be 'black' etc.</p> <p>I've written a method to flip the stack, but writing a method to replace all instances of the given variables with new variables isn't working. This is what i have so far. I've tried two approaches and i'm still not getting the result i want. Here is what I have:</p> <pre><code>//here color is the name of my stack. I tried to convert the stack to an array Object[] arr = color.toArray(); for (int i =0;i&lt;arr.length;i++){ /* * replace instances of &quot;blue&quot; in the string [] with red */ arr [i] = ((String) arr[i]).replaceAll(&quot;Blue&quot;, &quot;Red&quot;); arr [i] = ((String) arr[i]).replaceAll(&quot;Red&quot;, &quot;Blue&quot;); arr [i] = ((String) arr[i]).replaceAll(&quot;Green&quot;, &quot;Yellow&quot;); arr [i] = ((String) arr[i]).replaceAll(&quot;Yellow&quot;, &quot;Green&quot;); System.out.print(arr[i]); } </code></pre> <p>another method i tried:</p> <pre><code>import java.util.*; public class colors{ /* * method to swap the colors * color black gets changed to white, blue changes to red etc... * method would have to be implemented on a stack to change all the elm of the stack to the opposite * then the stack gets printed out and can be changed in the flip part of the main method */ private static Stack&lt;String&gt; opposite(Stack&lt;String&gt;color){ // method takes stack of strings. if 'red' then change to 'blue' /* * the stack gets put into this method * if the stack (strings) has these values then they are replaced with my values * * can't return String values if the input is Stack&lt;String&gt; */ String b = &quot;blue&quot;; String r = &quot;red&quot;; String g = &quot;green&quot;; String y = &quot;yellow&quot;; b.replace(&quot;blue&quot;, &quot;red&quot;); r.replace(&quot;red&quot;, &quot;blue&quot;); g.replace(&quot;green&quot;,&quot;yellow&quot;); y.replace(&quot;yellow&quot;,&quot;green&quot;); return color; // return type hase to be same as input type so change return type to match Stack&lt;String&gt; /* * if return type is same it can't return color.... try using switch statement to */ } public static void main(String[]args){ Stack&lt;String&gt; way = new Stack&lt;&gt;(); color.push(&quot;red&quot;); color.push(&quot;blue&quot;); System.out.println(way); System.out.println(opposite(way)); } } </code></pre> <p>I wanted the method to intake a stack and output a stack that has the elements changed</p>
[ { "answer_id": 74483883, "author": "Derek Gusoff", "author_id": 1452528, "author_profile": "https://Stackoverflow.com/users/1452528", "pm_score": -1, "selected": false, "text": "/me" }, { "answer_id": 74495565, "author": "Roy Hinkley", "author_id": 371077, "author_profile": "https://Stackoverflow.com/users/371077", "pm_score": 1, "selected": true, "text": "graphClient.users(\"user-id\")" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20532996/" ]
74,480,562
<p>I have a fixture that looks something like this:</p> <pre><code>{ &quot;field&quot;: [ { &quot;1&quot;: { &quot;admin&quot;: { &quot;place&quot;: &quot;For Admins&quot;, &quot;email&quot;: &quot;admin@gmail.com&quot;, &quot;password&quot;: &quot;admin123&quot; }, &quot;normal&quot;: { &quot;place&quot;: &quot;Normal&quot;, &quot;email&quot;: &quot;normal@gmail.com&quot;, &quot;password&quot;: &quot;normal123&quot; }, &quot;superAdmin&quot;: { &quot;email&quot;: &quot;superAdmin@gmail.com&quot;, &quot;password&quot;: &quot;superAdmin123&quot; } }, &quot;2&quot;: { &quot;admin&quot;: { &quot;place&quot;: &quot;For Admins&quot;, &quot;email&quot;: &quot;admin@gmail.com&quot;, &quot;password&quot;: &quot;admin123&quot; }, &quot;normal&quot;: { &quot;place&quot;: &quot;Normal&quot;, &quot;email&quot;: &quot;normal@gmail.com&quot;, &quot;password&quot;: &quot;normal123&quot; }, &quot;superAdmin&quot;: { &quot;email&quot;: &quot;superAdmin@gmail.com&quot;, &quot;password&quot;: &quot;superAdmin123&quot; } }, &quot;3&quot;: { &quot;admin&quot;: { &quot;place&quot;: &quot;For Admins&quot;, &quot;email&quot;: &quot;admin@gmail.com&quot;, &quot;password&quot;: &quot;admin123&quot; }, &quot;normal&quot;: { &quot;place&quot;: &quot;Normal&quot;, &quot;email&quot;: &quot;normal@gmail.com&quot;, &quot;password&quot;: &quot;normal123&quot; }, &quot;superAdmin&quot;: { &quot;email&quot;: &quot;superAdmin@gmail.com&quot;, &quot;password&quot;: &quot;superAdmin123&quot; } }, &quot;common&quot;: { &quot;wrong_email&quot;: &quot;wrong-email@gmail.com&quot;, &quot;wrong_password&quot;: &quot;wrong&quot; } } ] } </code></pre> <p>How can I go trough each of those <code>email</code> and <code>password</code> to have a Login validation for all ?</p> <p>Like:</p> <pre><code> it(&quot;Successful Login&quot;, function () { login(email, password) { cy.visit(&quot;/&quot;); cy.get('input[name=&quot;email&quot;]').type(email); cy.get('input[name=&quot;password&quot;]').type(password); }); </code></pre> <p>Not sure if I need a clear fixture</p>
[ { "answer_id": 74480605, "author": "Brandon", "author_id": 7763383, "author_profile": "https://Stackoverflow.com/users/7763383", "pm_score": 1, "selected": false, "text": "/fixture/field/1" }, { "answer_id": 74481888, "author": "TesterDick", "author_id": 18366749, "author_profile": "https://Stackoverflow.com/users/18366749", "pm_score": 0, "selected": false, "text": "it()" }, { "answer_id": 74498510, "author": "Harshith Raj", "author_id": 14768312, "author_profile": "https://Stackoverflow.com/users/14768312", "pm_score": 0, "selected": false, "text": "loginCreds.json\n{\n \"admin@gmail.com\": \"admin123\",\n \"normal@gmail.com\": \"normal123\",\n \"superAdmin@gmail.com\": \"superAdmin123\",\n \"wrong-email@gmail.com\": \"wrong\"\n }\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4322208/" ]
74,480,581
<p>Let's assume I have the following proto definition:</p> <pre><code>message Course { int32 id = 1; string course_name = 2; } </code></pre> <p>And the following legacy Controller (Spring Boot) that needs to be backwards compatible:</p> <pre><code>@RestController public class CourseController { @Autowired CourseRepository courseRepo; @RequestMapping(&quot;/courses/{id}&quot;) Course customer(@PathVariable Integer id) { return courseRepo.getCourse(id); } @PostMapping(&quot;/courses&quot;) Course post(@RequestBody Course course) { courseRepo.add(course); return course; } @PostMapping(&quot;/courses-bulk&quot;) Collection&lt;Course&gt; bulk(@RequestBody List&lt;Course&gt; courses) { for (Course c : courses) { courseRepo.add(c); } return courseRepo.getAll(); } } </code></pre> <p>In my <code>Application</code> class, I am using</p> <pre><code>@Bean ProtobufHttpMessageConverter protobufHttpMessageConverter() { return new ProtobufHttpMessageConverter(); } </code></pre> <p>Instead of using <code>ProtobufHttpMessageConverter</code>, it appears that Spring MVC is falling back to Jackson, which trying to interpret the type as a POJO:</p> <pre><code>Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot find a (Map) Key deserializer for type [simple type, class com.google.protobuf.Descriptors$FieldDescriptor] </code></pre> <p><strong>Questions:</strong></p> <ol> <li>Is it at all possible to deserialize JSON arrays with <code>ProtobufHttpMessageConverter</code>?</li> <li>If not, how can I make Jackson work with Protobuf POJOs, so that I can use Jackson as a fallback if <code>ProtobufHttpMessageConverter</code> can't deserialize a JSON array payload?</li> </ol>
[ { "answer_id": 74480605, "author": "Brandon", "author_id": 7763383, "author_profile": "https://Stackoverflow.com/users/7763383", "pm_score": 1, "selected": false, "text": "/fixture/field/1" }, { "answer_id": 74481888, "author": "TesterDick", "author_id": 18366749, "author_profile": "https://Stackoverflow.com/users/18366749", "pm_score": 0, "selected": false, "text": "it()" }, { "answer_id": 74498510, "author": "Harshith Raj", "author_id": 14768312, "author_profile": "https://Stackoverflow.com/users/14768312", "pm_score": 0, "selected": false, "text": "loginCreds.json\n{\n \"admin@gmail.com\": \"admin123\",\n \"normal@gmail.com\": \"normal123\",\n \"superAdmin@gmail.com\": \"superAdmin123\",\n \"wrong-email@gmail.com\": \"wrong\"\n }\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1867854/" ]
74,480,613
<p>I am trying to get the name of several webpages and this is an example of the dataset that I have:</p> <pre class="lang-r prettyprint-override"><code>c(&quot;https://arealdata-api.miljoeportal.dk/download/dai/BES_NATURTYPER_SHAPE.zip&quot;, &quot;https://download.kortforsyningen.dk/content/matrikelkortet&quot;, &quot;https://b0902-prod-dist-app.azurewebsites.net/geoserver/wfs&quot;, &quot;https://sit-ftp.statens-it.dk/main.html&quot;, &quot;https://arealdata.miljoeportal.dk/datasets/saerligtudpejede&quot;, &quot;https://miljoegis3.mim.dk/spatialmap?profile=privatskovtilskud&quot;, &quot;https://envs.au.dk/fileadmin/envs/Hjemmeside_2018/Zip_filer/Basemap03_public_geotiff.zip&quot;, &quot;https://arealdata-api.miljoeportal.dk/download/dai/BES_VANDLOEB_SHAPE.zip&quot;, &quot;https://wfs2-miljoegis.mim.dk/vp3basis2019/ows?service=WFS&amp;version=1.0.0&amp;request=GetCapabilities&quot;, &quot;httphttps://datasets.catalogue.data.gov.dk/dataset/ramsaromrader&quot;, &quot;https://ens.dk/service/statistik-data-noegletal-og-kort/download-gis-filer&quot;, &quot;https://miljoegis.mim.dk/cbkort?profile=miljoegis-raastofferhavet&quot;, &quot;https://www.marineregions.org/&quot;, &quot;https://CRAN.R-project.org/package=geodata&gt;.&quot;, &quot;https://miljoegis3.mim.dk/spatialmap?profile=vandprojekter&quot;, &quot;https://landbrugsgeodata.fvm.dk/&quot;) </code></pre> <p>As an example for the first entry, I want to get the webpage <em>&quot;https://arealdata-api.miljoeportal.dk/&quot;</em> without the rest of the address, so erase <em>&quot;download/dai/BES_NATURTYPER_SHAPE.zip&quot;</em>.</p> <p>I was thinking something like keep everything between <code>https://</code> and the first <code>/</code> after that.</p> <p>These are the variations I have tried so far:</p> <pre class="lang-r prettyprint-override"><code># 1 URLS &lt;- gsub(&quot;.*?//&quot;, &quot;&quot;, URLS) # 2 URLS &lt;- gsub(&quot;http://&quot;, &quot;&quot;, URLS) # 3 URLS &lt;- gsub(&quot;.*?//&quot;, &quot;&quot;, URLS) # 4 URLS &lt;- gsub(&quot;/.*&quot;, &quot;&quot;, URLS) </code></pre> <p>None of which works.</p>
[ { "answer_id": 74480644, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 2, "selected": false, "text": "(...)" }, { "answer_id": 74481139, "author": "M--", "author_id": 6461462, "author_profile": "https://Stackoverflow.com/users/6461462", "pm_score": 2, "selected": false, "text": "my_ptrn <- paste(paste0(\"https://(.*)\", \n c(\".dk\", \".net\", \".com\", \".org\")),\n collapse = \"|\")\n\nstringr::str_extract(URLS, my_ptrn)\n" }, { "answer_id": 74481299, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 3, "selected": true, "text": "sapply(strsplit(URLS, \"(?<=\\\\w/).\", perl = TRUE), `[`, 1)\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3808018/" ]
74,480,656
<p>We have a Spring-Boot REST application running with Infinispan 13.0.12 caches and we see periodic seemingly random cases where the application becomes un-responsive. A thread dump indicates over 200 threads in this state:</p> <pre><code>&quot;http-nio-8080-exec-379&quot; #11999 daemon prio=5 os_prio=0 tid=0x00007f28900f9800 nid=0x2c68 waiting on condition [0x00007f28485c2000] java.lang.Thread.State: TIMED_WAITING (parking) at sun.misc.Unsafe.park(Native Method) - parking to wait for &lt;0x00000006c09af3e8&gt; (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject) at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215) at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2163) at org.jgroups.util.Credit.decrementIfEnoughCredits(Credit.java:65) at org.jgroups.protocols.UFC.handleDownMessage(UFC.java:119) at org.jgroups.protocols.FlowControl.down(FlowControl.java:323) at org.jgroups.protocols.FlowControl.down(FlowControl.java:317) at org.jgroups.protocols.FRAG3.down(FRAG3.java:139) at org.jgroups.stack.ProtocolStack.down(ProtocolStack.java:927) at org.jgroups.JChannel.down(JChannel.java:645) at org.jgroups.JChannel.send(JChannel.java:484) at org.infinispan.remoting.transport.jgroups.JGroupsTransport.send(JGroupsTransport.java:1161) </code></pre> <p>Our Java configuration looks like this:</p> <pre><code>@Autowired @Bean public SpringEmbeddedCacheManagerFactoryBean springEmbeddedCacheManagerFactoryBean(GlobalConfigurationBuilder gcb, ConfigurationBuilder configurationBuilder) { SpringEmbeddedCacheManagerFactoryBean springEmbeddedCacheManagerFactoryBean = new SpringEmbeddedCacheManagerFactoryBean(); springEmbeddedCacheManagerFactoryBean.addCustomGlobalConfiguration(gcb); springEmbeddedCacheManagerFactoryBean.addCustomCacheConfiguration(configurationBuilder); return springEmbeddedCacheManagerFactoryBean; } @Autowired @Bean public EmbeddedCacheManager defaultCacheManager(SpringEmbeddedCacheManager springEmbeddedCacheManager) throws Exception { return springEmbeddedCacheManager.getNativeCacheManager(); } @Bean public GlobalConfigurationBuilder globalConfigurationBuilder() { GlobalConfigurationBuilder result = GlobalConfigurationBuilder.defaultClusteredBuilder(); result.transport().addProperty(&quot;configurationFile&quot;, jgroupsConfigFile); result.cacheManagerName(IDENTITY_CACHE); result.defaultCacheName(IDENTITY_CACHE + &quot;-default&quot;); result.serialization() .marshaller(new JavaSerializationMarshaller()) .allowList() .addClasses( LinkedMultiValueMap.class, String.class ); result.globalState().enable().persistentLocation(DATA_DIR); return result; } @Bean public ConfigurationBuilder configurationBuilder() { ConfigurationBuilder result = new ConfigurationBuilder(); result.clustering().cacheMode(CacheMode.REPL_SYNC); return result; } @Bean public org.infinispan.configuration.cache.Configuration cacheConfiguration() { ConfigurationBuilder builder = new ConfigurationBuilder(); return builder .clustering() .cacheMode(CacheMode.REPL_SYNC) .remoteTimeout(replicationTimeoutSeconds, TimeUnit.SECONDS) .stateTransfer().timeout(stateTransferTimeoutMinutes, TimeUnit.MINUTES) .persistence() .addSoftIndexFileStore() .shared(false) .fetchPersistentState(true) .expiration().lifespan(expirationHours, TimeUnit.HOURS) .build(); } @Autowired @Bean public Cache&lt;String, MultiValueMap&lt;String, String&gt;&gt; identityCache(EmbeddedCacheManager manager, org.infinispan.configuration.cache.Configuration cacheConfiguration) throws IOException { Cache&lt;String, MultiValueMap&lt;String, String&gt;&gt; result = manager .administration().withFlags(CacheContainerAdmin.AdminFlag.VOLATILE) .getOrCreateCache(IDENTITY_CACHE, cacheConfiguration); result.getAdvancedCache().getStats().setStatisticsEnabled(true); return result; } </code></pre> <p>and we run a three node cluster with the default-jgroups-udp.xml config. Can anyone suggest a likely cause? Perhaps the config is sub-optimal?</p> <p>TIA</p> <pre><code> &lt;config xmlns=&quot;urn:org:jgroups&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot;urn:org:jgroups http://www.jgroups.org/schema/jgroups-4.0.xsd&quot;&gt; &lt;UDP mcast_addr=&quot;${jgroups.udp.mcast_addr:228.6.7.9}&quot; mcast_port=&quot;${jgroups.udp.mcast_port:46655}&quot; ucast_send_buf_size=&quot;1m&quot; mcast_send_buf_size=&quot;1m&quot; ucast_recv_buf_size=&quot;20m&quot; mcast_recv_buf_size=&quot;25m&quot; ip_ttl=&quot;${jgroups.ip_ttl:2}&quot; thread_naming_pattern=&quot;pl&quot; enable_diagnostics=&quot;false&quot; bundler_type=&quot;no-bundler&quot; max_bundle_size=&quot;8500&quot; thread_pool.min_threads=&quot;${jgroups.thread_pool.min_threads:0}&quot; thread_pool.max_threads=&quot;${jgroups.thread_pool.max_threads:200}&quot; thread_pool.keep_alive_time=&quot;60000&quot; /&gt; &lt;PING /&gt; &lt;MERGE3 min_interval=&quot;10000&quot; max_interval=&quot;30000&quot; /&gt; &lt;FD_SOCK /&gt; &lt;FD_ALL timeout=&quot;60000&quot; interval=&quot;15000&quot; timeout_check_interval=&quot;5000&quot; /&gt; &lt;VERIFY_SUSPECT timeout=&quot;5000&quot; /&gt; &lt;pbcast.NAKACK2 xmit_interval=&quot;100&quot; xmit_table_num_rows=&quot;50&quot; xmit_table_msgs_per_row=&quot;1024&quot; xmit_table_max_compaction_time=&quot;30000&quot; resend_last_seqno=&quot;true&quot; /&gt; &lt;UNICAST3 xmit_interval=&quot;100&quot; xmit_table_num_rows=&quot;50&quot; xmit_table_msgs_per_row=&quot;1024&quot; xmit_table_max_compaction_time=&quot;30000&quot; conn_expiry_timeout=&quot;0&quot; /&gt; &lt;pbcast.STABLE stability_delay=&quot;500&quot; desired_avg_gossip=&quot;5000&quot; max_bytes=&quot;1M&quot; /&gt; &lt;pbcast.GMS print_local_addr=&quot;false&quot; install_view_locally_first=&quot;true&quot; join_timeout=&quot;${jgroups.join_timeout:5000}&quot; /&gt; &lt;UFC max_credits=&quot;2m&quot; min_threshold=&quot;0.40&quot; /&gt; &lt;MFC max_credits=&quot;2m&quot; min_threshold=&quot;0.40&quot; /&gt; &lt;FRAG3 frag_size=&quot;8000&quot;/&gt; &lt;/config&gt; </code></pre>
[ { "answer_id": 74480644, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 2, "selected": false, "text": "(...)" }, { "answer_id": 74481139, "author": "M--", "author_id": 6461462, "author_profile": "https://Stackoverflow.com/users/6461462", "pm_score": 2, "selected": false, "text": "my_ptrn <- paste(paste0(\"https://(.*)\", \n c(\".dk\", \".net\", \".com\", \".org\")),\n collapse = \"|\")\n\nstringr::str_extract(URLS, my_ptrn)\n" }, { "answer_id": 74481299, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 3, "selected": true, "text": "sapply(strsplit(URLS, \"(?<=\\\\w/).\", perl = TRUE), `[`, 1)\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4541199/" ]
74,480,694
<p>I have created a sample data frame below using a relatively raw and somehow &quot;dumb&quot; way and I would like to know if there are shorter/neater ways doing so? Million thanks.</p> <pre><code>library(pedquant) PECCPC&lt;-md_stock(c(&quot;600028&quot;,&quot;601857&quot;,&quot;00386.HK&quot;,&quot;00857.HK&quot;),type='real') a&lt;-as.data.frame(PECCPC$symbol[1:2]) b&lt;-as.data.frame(PECCPC$close[1:2]) c&lt;-as.data.frame(PECCPC$symbol[3:4]) d&lt;-as.data.frame(PECCPC$close[3:4]) e&lt;-cbind(a,b) f&lt;-cbind(c,d) g&lt;-cbind(e,f) g$spread&lt;-g[,2]-g[,4] colnames(g)&lt;-c(&quot;A-shares&quot;,&quot;Price&quot;,&quot;H-shares&quot;,&quot;Price&quot;,&quot;AH_spread&quot;) g A-shares Price H-shares Price AH_spread 1 600028.SS 4.31 00386.HK 3.42 0.89 2 601857.SS 5.04 00857.HK 3.38 1.66 </code></pre>
[ { "answer_id": 74480644, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 2, "selected": false, "text": "(...)" }, { "answer_id": 74481139, "author": "M--", "author_id": 6461462, "author_profile": "https://Stackoverflow.com/users/6461462", "pm_score": 2, "selected": false, "text": "my_ptrn <- paste(paste0(\"https://(.*)\", \n c(\".dk\", \".net\", \".com\", \".org\")),\n collapse = \"|\")\n\nstringr::str_extract(URLS, my_ptrn)\n" }, { "answer_id": 74481299, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 3, "selected": true, "text": "sapply(strsplit(URLS, \"(?<=\\\\w/).\", perl = TRUE), `[`, 1)\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16601198/" ]
74,480,734
<p>I found the code of logical gate xor written in Haskell, but I don't know what does this &quot;<code>(/=)</code>&quot; mean!</p> <pre><code>xor :: Bool -&gt; Bool -&gt; Bool xor = (/=) </code></pre>
[ { "answer_id": 74481075, "author": "Willem Van Onsem", "author_id": 67579, "author_profile": "https://Stackoverflow.com/users/67579", "pm_score": 4, "selected": true, "text": "(/=) :: Eq a => a -> a -> Bool" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15203917/" ]
74,480,738
<p>I have a component that need to dynamically load another component in its template, so I followed this tutorial <a href="https://angular.io/guide/dynamic-component-loader" rel="nofollow noreferrer">dynamic-component-loader</a>, so basically my component looks like</p> <pre><code>@Component( selector: 'appPopout', template: ` &lt;div&gt; ...some stuff here... &lt;/div&gt; &lt;ng-template appTableHost&gt;&lt;/ng-template&gt; ` ) export class PopoutComponent&lt;T extends PopoutTable&gt; implements OnInit { @ViewChild(TableHostDirective, {static: true}) tableHost!: TableHostDirective; constructor(){} ngOnInit(){ const viewContainerRef = this.tableHost.viewContainerRef; viewVontainerRef.clear(); const componentRef = viewContainerRef.createComponent&lt;T&gt;(); } } </code></pre> <p>I'm stuck here and don't know how to proceed, the <code>createComponent</code> method requires a <code>Type&lt;T&gt;</code> as a parameter, how can I pass one?</p> <p>Any help will be much appreciated</p>
[ { "answer_id": 74481075, "author": "Willem Van Onsem", "author_id": 67579, "author_profile": "https://Stackoverflow.com/users/67579", "pm_score": 4, "selected": true, "text": "(/=) :: Eq a => a -> a -> Bool" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19199956/" ]
74,480,741
<p>I understand the concept of non-nullable types, and try to use them whenever possible, but have hit a situation where I don't understand what to do.</p> <p>If I create a Blazor component (content irrelevant and therefore not shown), and want to refer to it in code, I can add a private variable for it. Since I know that Blazor will assign it a value, I can tell the compiler not to worry that it is non-nullable, but I haven't set an initial value...</p> <pre class="lang-cs prettyprint-override"><code>private MyComponent _myComponent = null!; </code></pre> <p>I can then use <code>@ref</code> in the markup, which will populate the variable with a reference to the component...</p> <pre class="lang-xml prettyprint-override"><code>&lt;MyComponent @ref=&quot;_myComponent&quot; /&gt; </code></pre> <p>However, Visual Studio gives me a wavy green line under the last part of this line, and a warning &quot;<em>Cannot convert null literal to non-nullable reference type</em>&quot;.</p> <p>I'm not sure how to get around this. I'm not even sure what the warning means, as I told the compiler that the variable won't be null.</p> <p>Can anyone explain a) what I'm doing wrong here, and b) how I should be doing this? Thanks</p>
[ { "answer_id": 74481075, "author": "Willem Van Onsem", "author_id": 67579, "author_profile": "https://Stackoverflow.com/users/67579", "pm_score": 4, "selected": true, "text": "(/=) :: Eq a => a -> a -> Bool" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6826677/" ]
74,480,742
<p>I want function maxmintuple(m), that takes m, a 2D list returns a tuple with the min value and max value in the corresponding brackets. eg:</p> <pre><code>maxmintuple ([[3,5],[6,8]]) (3,8) </code></pre> <p>This is how I call it:</p> <p>maxmintuple([1,5],[2,8])</p> <p>and it returns this :</p> <pre><code>Traceback (most recent call last): File &quot;&lt;pyshell#17&gt;&quot;, line 1, in &lt;module&gt; maxmintuple([1,5],[2,8]) TypeError: maxmintuple() takes 1 positional argument but 2 were given </code></pre> <p>Here's what I have, but it keeps saying</p> <p>maxmintuple() takes 1 positional argument but 2 were given</p> <p>Here's what I did:</p> <pre><code>def maxmintuple(m): max1 = m[O][O] min1 = m[O][O] for zero in m: for one in zero: if one &gt; max1: max1 = one if one &lt; min1: min1 = one return (min1,max1) </code></pre>
[ { "answer_id": 74480852, "author": "Khaled DELLAL", "author_id": 15852600, "author_profile": "https://Stackoverflow.com/users/15852600", "pm_score": 2, "selected": false, "text": "def maxmintuple(m):\n\n min1 = min(m[0])\n max1 = max(m[1])\n\n return (min1,max1)\n" }, { "answer_id": 74480868, "author": "Vishnu Vinod", "author_id": 13460070, "author_profile": "https://Stackoverflow.com/users/13460070", "pm_score": 1, "selected": false, "text": "maxmintuple([[1,5],[2,8]])" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20420123/" ]
74,480,755
<pre><code>let obj = { one : 1, two : 2, three : 3 } </code></pre> <p>I want output like this :</p> <pre><code>let obj ={ three: 3, two : 2, one : 1 } </code></pre> <p>let keys = Object.keys(obj);</p> <p>obj = {...keys.reverse()}</p> <p>but it has errors</p>
[ { "answer_id": 74480804, "author": "Brr Switch", "author_id": 5145745, "author_profile": "https://Stackoverflow.com/users/5145745", "pm_score": 2, "selected": true, "text": "const obj = {\n one : 1, \n two : 2, \n three : 3\n};\n\n// ️ ['3', '2', '1']\nconst reversedKeys = Object.keys(obj).reverse();\n\nreversedKeys.forEach(key => {\n console.log(key, obj[key]); \n});" }, { "answer_id": 74480836, "author": "Brother58697", "author_id": 17804016, "author_profile": "https://Stackoverflow.com/users/17804016", "pm_score": 2, "selected": false, "text": "Object.entries" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20493210/" ]
74,480,766
<p>I'm trying to find the number of palindromes in a certain range using the Python code below:</p> <pre class="lang-py prettyprint-override"><code>def test(n,m): return len([i for i in range(n,m+1) if str(i) == str(i)[::-1]]) </code></pre> <p>Can anyone discover any other ways to make this code simpler in order to reduce its time complexity, as well as any potential missing conditions that my function may not have addressed?</p> <p>Some recommendations to enhance the temporal complexity and mark on conditions that I haven't handled.</p>
[ { "answer_id": 74480903, "author": "Edward Peters", "author_id": 6016064, "author_profile": "https://Stackoverflow.com/users/6016064", "pm_score": 2, "selected": false, "text": "O(2^n)" }, { "answer_id": 74500621, "author": "Arbaz ali", "author_id": 15316256, "author_profile": "https://Stackoverflow.com/users/15316256", "pm_score": 2, "selected": true, "text": "def getFirstDigit(x) :\n while (x >= 10) :\n x //= 10\n return x\n\n\ndef getCountWithSameStartAndEndFrom1(x) :\n if (x < 10):\n return x\n tens = x // 10\n res = tens + 9\n firstDigit = getFirstDigit(x)\n lastDigit = x % 10\n\n\n if (lastDigit < firstDigit) :\n res = res - 1\n\n return res\n\n\ndef getCountWithSameStartAndEnd(start, end) :\n return (getCountWithSameStartAndEndFrom1(end) -\n getCountWithSameStartAndEndFrom1(start - 1))" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20309866/" ]
74,480,775
<p>I'm trying to extract text from a local image with Python and Vision, based off <a href="https://cloud.google.com/vision/docs/ocr" rel="nofollow noreferrer">Cloud Vision API: Detect text in images</a>.</p> <p>This is the function to extract text:</p> <pre class="lang-py prettyprint-override"><code>def detect_text(path):     &quot;&quot;&quot;Detects text in the file.&quot;&quot;&quot;     from google.cloud import vision     import io     client = vision.ImageAnnotatorClient() with io.open(path, 'rb') as image_file:         content = image_file.read() image = vision.Image(content=content) response = client.text_detection(image=image)     texts = response.text_annotations </code></pre> <p>It works, but I'd like to specify the use of features like <code>TEXT_DETECTION</code> instead of the default <code>DOCUMENT_TEXT_DETECTION</code> feature, as well as specify language hints. How would I do that? The <code>text_detection</code> function doesn't seem to take such parameters.</p>
[ { "answer_id": 74481100, "author": "BeeFriedman", "author_id": 13949270, "author_profile": "https://Stackoverflow.com/users/13949270", "pm_score": 1, "selected": true, "text": "request = {\n \"image\": {\n \"source\": {\n \"image_uri\": \"IMAGE_URL\"\n }\n }, \n \"features\": [\n {\n \"type\": \"TEXT_DETECTION\"\n }\n ]\n \"imageContext\": {\n \"languageHints\": [\"en-t-i0-handwrit\"]\n }\n}\n" }, { "answer_id": 74481514, "author": "Nestor Ceniza Jr", "author_id": 19378826, "author_profile": "https://Stackoverflow.com/users/19378826", "pm_score": 1, "selected": false, "text": "response = client.text_detection(image=image,\nimage_context={\"language_hints\": [\"en\"]})\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20532012/" ]
74,480,783
<p>I'm new to learning react and have been having problems getting the array to filter using the .filter() method. I'm trying to create a grocery list and I keep getting the error message &quot;Cannot read properties of null (reading 'filter')&quot; Can someone please assist me on getting this work? Here is the code that I have.</p> <pre><code>import Header from './Header'; import SearchItem from './SearchItem'; import AddItem from './AddItem'; import Content from './Content'; import Footer from './Footer'; import { useState, useEffect } from 'react'; function App() { const [items, setItems] = useState(JSON.parse(localStorage.getItem('shoppinglist'))); const [newItem, setNewItem] = useState('') const [search, setSearch] = useState('') console.log('before useEffect') //useEffect looks to it's dependency and if the dependency changes then it will run the anonymous function useEffect(() =&gt; { console.log('inside useEffect') },[items]) const setAndSaveItems = (newItems) =&gt; { setItems(newItems); localStorage.setItem('shoppinglist', JSON.stringify(newItems)); } console.log('after useEffect') const addItem = (item) =&gt; { const id = items.length ? items[items.length - 1].id + 1 : 1; const myNewItem = { id, checked: false, item }; const listItems = [...items, myNewItem]; setAndSaveItems(listItems); } const handleCheck = (id) =&gt; { const listItems = items.map((item) =&gt; item.id === id ? { ...item, checked: !item.checked } : item); setAndSaveItems(listItems); } const handleDelete = (id) =&gt; { const listItems = items.filter((item) =&gt; item.id !== id); setAndSaveItems(listItems); } const handleSubmit = (e) =&gt; { e.preventDefault(); if (!newItem) return; addItem(newItem); setNewItem(''); } return ( &lt;div className=&quot;App&quot;&gt; &lt;Header title=&quot;Grocery List&quot; /&gt; &lt;AddItem newItem={newItem} setNewItem={setNewItem} handleSubmit={handleSubmit} /&gt; &lt;SearchItem search={search} setSearch={setSearch} /&gt; &lt;Content items={items.filter(item =&gt; ((item.item).toLowerCase()).includes(search.toLowerCase()))} handleCheck={handleCheck} handleDelete={handleDelete} /&gt; &lt;Footer length={items.length} /&gt; &lt;/div&gt; ); } export default App; </code></pre>
[ { "answer_id": 74481100, "author": "BeeFriedman", "author_id": 13949270, "author_profile": "https://Stackoverflow.com/users/13949270", "pm_score": 1, "selected": true, "text": "request = {\n \"image\": {\n \"source\": {\n \"image_uri\": \"IMAGE_URL\"\n }\n }, \n \"features\": [\n {\n \"type\": \"TEXT_DETECTION\"\n }\n ]\n \"imageContext\": {\n \"languageHints\": [\"en-t-i0-handwrit\"]\n }\n}\n" }, { "answer_id": 74481514, "author": "Nestor Ceniza Jr", "author_id": 19378826, "author_profile": "https://Stackoverflow.com/users/19378826", "pm_score": 1, "selected": false, "text": "response = client.text_detection(image=image,\nimage_context={\"language_hints\": [\"en\"]})\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16791112/" ]
74,480,815
<p>I have two buttons that show two different components when toggling them. For UX reasons (to know which component is showing) I would like to style the buttons according to if the value of the state is true or false (give them an underline and a darker color if the state is true). Is this possible in any way?</p> <p>This is my GitHub repo: <a href="https://github.com/uohman/Portfolio2022" rel="nofollow noreferrer">https://github.com/uohman/Portfolio2022</a></p> <p>And this is the component where I handle the buttons:</p> <p>`</p> <pre><code>import React, { useState } from 'react' import ReactDOM from 'react-dom'; import { Subheading } from 'GlobalStyles'; import { FrontendProjects } from './FrontendProjects' import { GraphicDesignProjects } from './GraphicDesignProjects'; import 'index.css' export const FeaturedProjects = () =&gt; { const [buttons, setButtons] = useState([ { label: 'Development', value: true }, { label: 'Graphic design', value: false } ]); const handleButtonsChange = () =&gt; (label) =&gt; { const newButtonsState = buttons.map((button) =&gt; { if (button.label === label) { return (button = { label: button.label, value: true }); } return { label: button.label, value: false }; }); setButtons(newButtonsState); }; return ( &lt;&gt; &lt;Subheading&gt;&lt;span&gt;Featured projects&lt;/span&gt;&lt;/Subheading&gt; &lt;SpecialButton {...{ buttons, setButtons, handleButtonsChange }} /&gt; {buttons[0].value &amp;&amp; &lt;FrontendProjects /&gt;} {buttons[1].value &amp;&amp; &lt;GraphicDesignProjects /&gt;} &lt;/&gt; ); }; const SpecialButton = ({ buttons, setButtons, handleButtonsChange }) =&gt; { return ( &lt;div className=&quot;button-container&quot;&gt; {buttons.map((button, index) =&gt; ( &lt;button key={`${button.label}-${index}`} onClick={() =&gt; handleButtonsChange({ buttons, setButtons })(button.label)}&gt; {button.label.toUpperCase()} &lt;/button&gt; ))} &lt;/div&gt; ); }; const rootElement = document.getElementById('root'); ReactDOM.render(&lt;FeaturedProjects /&gt;, rootElement); </code></pre> <p>`</p> <p>I've given the buttons the pseudo element :focus and that nearly solves my problem, but still as a default the buttons are the same color although it is one of the components that is showing. Thankful for suggestions on how to solve this!</p>
[ { "answer_id": 74481100, "author": "BeeFriedman", "author_id": 13949270, "author_profile": "https://Stackoverflow.com/users/13949270", "pm_score": 1, "selected": true, "text": "request = {\n \"image\": {\n \"source\": {\n \"image_uri\": \"IMAGE_URL\"\n }\n }, \n \"features\": [\n {\n \"type\": \"TEXT_DETECTION\"\n }\n ]\n \"imageContext\": {\n \"languageHints\": [\"en-t-i0-handwrit\"]\n }\n}\n" }, { "answer_id": 74481514, "author": "Nestor Ceniza Jr", "author_id": 19378826, "author_profile": "https://Stackoverflow.com/users/19378826", "pm_score": 1, "selected": false, "text": "response = client.text_detection(image=image,\nimage_context={\"language_hints\": [\"en\"]})\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19388493/" ]
74,480,816
<p>I currently have an action that creates a new link between an object of <code>type A</code>, named <code>OA</code>, and an object of <code>type B</code>, named <code>OB</code>.</p> <p>Our workflow has a constraint such that any object of <code>type B</code> can at most, be linked to 4 objects of <code>type A</code>. As such, I would like to define a submission criterion in the action such that submission is blocked if OB is already linked to 4 objects of <code>type A</code>.</p> <p>I couldn't find a straightforward way to do this using the Action configuration UI. How could I accomplish this?</p>
[ { "answer_id": 74480827, "author": "Austin Atmaja", "author_id": 19819281, "author_profile": "https://Stackoverflow.com/users/19819281", "pm_score": 1, "selected": false, "text": "type A" }, { "answer_id": 74488295, "author": "Logan Rhyne", "author_id": 14320825, "author_profile": "https://Stackoverflow.com/users/14320825", "pm_score": 0, "selected": false, "text": "UserFacingError" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19819281/" ]
74,480,818
<p>I'm currently a web developer boot camp student and I am working on a project. I know there is a way to simplify this function but I can't seem to grasp it. What is the way to simplify this entire thing into a for loop so I don't have to do this to every element? I am calling a weather API and applying them to the HTMl. Also, I am using the querySelector as for some reason, JQuery doesn't want to allow me to use the $.</p> <p><strong>HTML</strong></p> <pre><code> &lt;div class=&quot;row bottom&quot;&gt; &lt;div class=&quot;col&quot;&gt;&lt;span class=&quot;subtitle&quot;&gt;-Temperature-&lt;/span&gt;&lt;/div&gt; &lt;div class=&quot;col&quot;&gt; &lt;div class=&quot;row&quot; id=&quot;date1&quot;&gt;Sun&lt;/div&gt; &lt;div class=&quot;row data&quot; id=&quot;date1Temp&quot;&gt;&lt;b&gt;-4&amp;deg;&lt;/b&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;col&quot;&gt; &lt;div class=&quot;row&quot; id=&quot;date2&quot;&gt;Mon&lt;/div&gt; &lt;div class=&quot;row data&quot; id=&quot;date2Temp&quot;&gt;&lt;b&gt;-5&amp;deg;&lt;/b&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;col&quot;&gt; &lt;div class=&quot;row&quot; id=&quot;date3&quot;&gt;Tue&lt;/div&gt; &lt;div class=&quot;row data&quot; id=&quot;date3Temp&quot;&gt;&lt;b&gt;-10&amp;deg;&lt;/b&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;col&quot;&gt; &lt;div class=&quot;row&quot; id=&quot;date4&quot;&gt;Wed&lt;/div&gt; &lt;div class=&quot;row data&quot; id=&quot;date4Temp&quot;&gt;&lt;b&gt;-4&amp;deg;&lt;/b&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;col&quot;&gt; &lt;div class=&quot;row&quot; id=&quot;date5&quot;&gt;Thu&lt;/div&gt; &lt;div class=&quot;row data&quot; id=&quot;date5Temp&quot;&gt;&lt;b&gt;-2&amp;deg;&lt;/b&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;col&quot;&gt; &lt;hr /&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>JS</strong></p> <pre><code>let fiveDayWeather = function (weatherValue) { const date1 = document.querySelector(&quot;#date1&quot;); const date2 = document.querySelector(&quot;#date2&quot;); const date3 = document.querySelector(&quot;#date3&quot;); const date4 = document.querySelector(&quot;#date4&quot;); const date5 = document.querySelector(&quot;#date5&quot;); const date1Temp = document.querySelector(&quot;#date1Temp&quot;); const date2Temp = document.querySelector(&quot;#date2Temp&quot;); const date3Temp = document.querySelector(&quot;#date3Temp&quot;); const date4Temp = document.querySelector(&quot;#date4Temp&quot;); const date5Temp = document.querySelector(&quot;#date5Temp&quot;); let todaysMonth = dayjs().$M; let tomorrow = dayjs().$D + 1; let twoDaysAfter = dayjs().$D + 2; let threeDaysAfter = dayjs().$D + 3; let fourDaysAfter = dayjs().$D + 4; let fiveDaysAfter = dayjs().$D + 5; date1.innerText = `${todaysMonth}/${tomorrow}`; date1Temp.innerText = weatherValue.list[1].main.temp + &quot;\u00B0 F&quot;; date2.innerText = `${todaysMonth}/${twoDaysAfter}`; date2Temp.innerText = weatherValue.list[2].main.temp + &quot;\u00B0 F&quot;; date3.innerText = `${todaysMonth}/${threeDaysAfter}`; date3Temp.innerText = weatherValue.list[3].main.temp + &quot;\u00B0 F&quot;; date4.innerText = `${todaysMonth}/${fourDaysAfter}`; date4Temp.innerText = weatherValue.list[4].main.temp + &quot;\u00B0 F&quot;; date5.innerText = `${todaysMonth}/${fiveDaysAfter}`; date5Temp.innerText = weatherValue.list[5].main.temp + &quot;\u00B0 F&quot;; </code></pre>
[ { "answer_id": 74480926, "author": "Fabio Almeida", "author_id": 4719158, "author_profile": "https://Stackoverflow.com/users/4719158", "pm_score": 2, "selected": false, "text": "let fiveDayWeather = function (weatherValue) {\n let todaysMonth = dayjs().$M;\n [...Array(5).keys()] // generate array with indexes[ 0, 1, 2, 3, 4]\n .map((k) => `date${k + 1}`) // map each element to the format \"date1\" \"date2\" etc\n .forEach((id, index) => { // iterate the array with both the generated ids in the format you want and the index\n // get the elements\n const date = document.getElementById(id);\n const dateTemp = document.getElementById(id + \"Temp\");\n // set the day\n const day = dayjs().$D + index + 1;\n // edit html content\n date.innerText = `${todaysMonth}/${day}`;\n dateTemp.innerText = weatherValue.list[index + 1].main.temp + \"\\u00B0 F\";\n });\n};\n\n" }, { "answer_id": 74480983, "author": "Rory McCrossan", "author_id": 519413, "author_profile": "https://Stackoverflow.com/users/519413", "pm_score": 0, "selected": false, "text": "id" }, { "answer_id": 74481092, "author": "rlf89", "author_id": 8845767, "author_profile": "https://Stackoverflow.com/users/8845767", "pm_score": 2, "selected": true, "text": "let fiveDayWeather = function (weatherValue) {\n\n let todaysMonth = dayjs().$M;\n\n for( let i = 1; i < 6; i++ ){\n\n document.querySelector( \"#date\" + i ).innerText = `${todaysMonth}/${ dayjs().$D + i }`;\n document.querySelector( \"#date\" + i + \"Temp\" ).innerText = weatherValue.list[i].main.temp + \"\\u00B0 F\";\n }\n}\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20116550/" ]
74,480,823
<p>I'm trying to create a heading in two colors, black and white. The color change should occur in the letter, so I can't use span. The Heading is &quot;Modern Art Gallery&quot;. I want the change to happen in the letter 'n'. (See example image below.)</p> <p>I tried to use a filter but that didn't work. Now I am trying to use two headings, one in white and one in black, but when I position them on top of each other I only see one of them, depending on the z-index.</p> <p><a href="https://i.stack.imgur.com/dqZAq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dqZAq.png" alt="example" /></a></p>
[ { "answer_id": 74480986, "author": "chvndb", "author_id": 4035939, "author_profile": "https://Stackoverflow.com/users/4035939", "pm_score": 1, "selected": false, "text": "* { margin: 0; padding: 0 }\n\nheader {\n overflow: hidden;\n height: 100vh;\n background: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/2017/17_04_cat_bg_03.jpg) 50%/ cover\n}\n\nh2 {\n height: inherit;\n background: inherit;\n -webkit-background-clip: text;\n background-clip: text;\n color: transparent;\n font: 900 35vmin/50vh cookie, cursive;\n text-align: center;\n filter: invert(1) grayscale(1) contrast(9);\n}" }, { "answer_id": 74481079, "author": "A Haworth", "author_id": 10867454, "author_profile": "https://Stackoverflow.com/users/10867454", "pm_score": 2, "selected": false, "text": ".container {\n width: 100vw;\n height: 100vh;\n background: white;\n background-image: linear-gradient(to right, black 0 50%, white 50% 100%);\n display: flex;\n justify-content: center;\n align-items: center;\n}\n\nh1 {\n mix-blend-mode: difference;\n color: white;\n}" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19113047/" ]
74,480,824
<p>I created these two arrays</p> <pre><code>students = np.array([['Hannah'],['Alonzo'], ['Antoinette'], ['Latasha'], ['Phil']]) grades = np.array([[86, 94], [83, 79], [97, 95], [90, 87], [73, 76]]) </code></pre> <p>how do I select all rows from grade based on the student name, for example Alonzo?</p> <p>I tried to select it all using index but for some reason the syntax was wrong, and I'm not sure how to select it.</p>
[ { "answer_id": 74480869, "author": "Edward Peters", "author_id": 6016064, "author_profile": "https://Stackoverflow.com/users/6016064", "pm_score": 0, "selected": false, "text": "dictionary" }, { "answer_id": 74480883, "author": "eshirvana", "author_id": 1367454, "author_profile": "https://Stackoverflow.com/users/1367454", "pm_score": 0, "selected": false, "text": "find = 'Alonzo'\n\nfor i,student in enumerate(students):\n if student == find:\n print(grades[i])\n break\n" }, { "answer_id": 74480911, "author": "Ricardo", "author_id": 16353662, "author_profile": "https://Stackoverflow.com/users/16353662", "pm_score": 0, "selected": false, "text": "students = np.array([['Hannah'],['Alonzo'], ['Antoinette'], ['Latasha'], ['Phil']])\ngrades = np.array([[86, 94], [83, 79], [97, 95], [90, 87], [73, 76]])\ngrades[(students == ['Alonzo']).flatten()]\n" }, { "answer_id": 74480951, "author": "Jamiu Shaibu", "author_id": 19290081, "author_profile": "https://Stackoverflow.com/users/19290081", "pm_score": 1, "selected": false, "text": "import numpy as np\nstudents = np.array([['Hannah'],['Alonzo'], ['Antoinette'], ['Latasha'], ['Phil']])\n\ngrades = np.array([[86, 94], [83, 79], [97, 95], [90, 87], [73, 76]])\n\nfor index,student in enumerate(students):\n if student == 'Alonzo':\n print(grades[index])\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18787236/" ]
74,480,834
<p>I am stuck in a seemingly easy task. Imagine the following <code>data.table</code>:</p> <pre class="lang-r prettyprint-override"><code>dt1 &lt;- data.table(ID = as.factor(c(&quot;202E&quot;, &quot;202E&quot;, &quot;202E&quot;)), timestamp = as.POSIXct(c(&quot;2017-05-02 00:00:00&quot;, &quot;2017-05-02 00:15:00&quot;, &quot;2017-05-02 00:30:00&quot;)), acceleration_raw = c(&quot;-0.703 0.656 0.164 -0.703 0.656 0.164 -0.703 0.656 0.164 -0.703 0.656 0.164 -0.703 0.656 0.164 -0.703 0.656 0.164 -0.703 0.656 0.164 -0.703 0.656 0.164 -0.703 0.656 0.164 -0.703 0.656 0.164 -0.703 0.656 0.164 -0.703 0.656 0.164 -0.703 0.656 0.164 -0.703 0.656 0.164 -0.703 0.656 0.164 -0.703 0.656 0.164 -0.703 0.656 0.164 -0.703 0.656 0.164 -0.703 0.656 0.164 -0.703 0.656 0.164 -0.703 0.656 0.164 -0.727 0.656 0.164 -0.703 0.656 0.164 -0.703 0.656 0.164 -0.727 0.656 0.164 -0.703 0.656 0.164 -0.703 0.656 0.164 -0.703 0.656 0.164 -0.703 0.656 0.164 -0.703 0.656 0.164 -0.703 0.656 0.164 -0.703 0.656 0.164 -0.703 0.656 0.164 -0.703 0.656 0.164 -0.703 0.656 0.141 -0.703 0.656 0.164 -0.703 0.656 0.141 -0.703 0.656 0.141 -0.703 0.656 0.141 -0.703 0.656 0.141&quot;, &quot;-0.703 0.680 0.117 -0.680 0.680 0.117 -0.680 0.680 0.117 -0.680 0.680 0.117 -0.680 0.680 0.117 -0.680 0.680 0.117 -0.680 0.680 0.117 -0.703 0.680 0.117 -0.703 0.680 0.117 -0.703 0.680 0.117 -0.680 0.680 0.117 -0.703 0.680 0.117 -0.680 0.680 0.117 -0.703 0.680 0.117 -0.680 0.680 0.117 -0.703 0.680 0.117 -0.680 0.680 0.117 -0.680 0.680 0.117 -0.680 0.680 0.117 -0.680 0.680 0.117 -0.703 0.680 0.117 -0.703 0.680 0.117 -0.703 0.680 0.117 -0.703 0.680 0.117 -0.703 0.680 0.117 -0.703 0.680 0.117 -0.703 0.680 0.117 -0.680 0.680 0.117 -0.680 0.680 0.117 -0.703 0.680 0.117 -0.703 0.680 0.117 -0.703 0.680 0.117 -0.703 0.680 0.117 -0.703 0.680 0.117 -0.703 0.680 0.117 -0.703 0.680 0.117 -0.703 0.680 0.117 -0.703 0.680 0.117 -0.703 0.680 0.117 -0.703 0.680 0.117&quot;, &quot;-0.750 0.586 0.117 -0.773 0.586 0.117 -0.773 0.609 0.117 -0.773 0.586 0.117 -0.773 0.586 0.117 -0.773 0.586 0.117 -0.773 0.586 0.117 -0.773 0.586 0.117 -0.773 0.586 0.141 -0.773 0.586 0.141 -0.773 0.586 0.141 -0.773 0.586 0.141 -0.773 0.586 0.141 -0.773 0.586 0.141 -0.773 0.586 0.141 -0.773 0.586 0.141 -0.773 0.586 0.141 -0.773 0.586 0.141 -0.773 0.586 0.141 -0.773 0.586 0.141 -0.773 0.586 0.141 -0.750 0.586 0.141 -0.773 0.586 0.141 -0.773 0.586 0.141 -0.773 0.586 0.141 -0.773 0.586 0.117 -0.773 0.586 0.141 -0.773 0.586 0.117 -0.773 0.586 0.117 -0.773 0.586 0.117 -0.773 0.586 0.117 -0.773 0.586 0.117 -0.773 0.586 0.117 -0.773 0.586 0.141 -0.773 0.586 0.117 -0.773 0.586 0.117 -0.773 0.586 0.117 -0.773 0.586 0.117 -0.773 0.586 0.117 -0.773 0.586 0.117&quot;)) </code></pre> <p><sup>Created on 2022-11-17 with <a href="https://reprex.tidyverse.org" rel="nofollow noreferrer">reprex v2.0.2</a></sup></p> <p>The idea is that I want to separate the <code>acceleration_raw</code> column into 3 different ones: <code>acc_x</code>, <code>acc_y</code> and <code>acc_z</code>. Each row of <code>acceleration_raw</code> is a string of characters, eventually leading to 120 numeric observations. I want to separate <code>acceleration_raw</code> and then take every the value from the first row and forth with a step of 3 and put it to <code>acc_x</code>, every value from the second row and forth and put it to <code>acc_y</code>, and finally every value from the third row and on and put it to <code>acc_z</code>.</p> <p>I tried to first separate <code>acceleration_raw</code> with <code>separate_rows</code> from <code>dplyr</code>:</p> <pre class="lang-r prettyprint-override"><code>library('tidyverse') library('data.table') dt1 &lt;- dt1 %&gt;% separate_rows(acceleration_raw, sep = &quot; &quot;, convert = F) </code></pre> <p><sup>Created on 2022-11-17 with <a href="https://reprex.tidyverse.org" rel="nofollow noreferrer">reprex v2.0.2</a></sup></p> <p>And after that:</p> <pre class="lang-r prettyprint-override"><code>library('tidyverse') library('data.table') dt1 &lt;- dt1 %&gt;% separate_rows(acceleration_raw, sep = &quot; &quot;, convert = F) %&gt;% mutate(acc_x = seq(acceleration_raw, from = 1, to = length(dt1), by = 3), acc_y = seq(acceleration_raw, from = 2, to = length(dt1), by = 3), acc_z = seq(acceleration_raw, from = 3, to = length(dt1), by = 3)) #&gt; Warning in seq.default(acceleration_raw, from = 1, to = length(dt1), by = 3): #&gt; first element used of 'length.out' argument #&gt; Error in `mutate()`: #&gt; ! Problem while computing `acc_x = seq(acceleration_raw, from = 1, to = #&gt; length(dt1), by = 3)`. #&gt; Caused by error in `ceiling()`: #&gt; ! non-numeric argument to mathematical function </code></pre> <p><sup>Created on 2022-11-17 with <a href="https://reprex.tidyverse.org" rel="nofollow noreferrer">reprex v2.0.2</a></sup></p> <p>Any suggestions on how to proceed?</p>
[ { "answer_id": 74480869, "author": "Edward Peters", "author_id": 6016064, "author_profile": "https://Stackoverflow.com/users/6016064", "pm_score": 0, "selected": false, "text": "dictionary" }, { "answer_id": 74480883, "author": "eshirvana", "author_id": 1367454, "author_profile": "https://Stackoverflow.com/users/1367454", "pm_score": 0, "selected": false, "text": "find = 'Alonzo'\n\nfor i,student in enumerate(students):\n if student == find:\n print(grades[i])\n break\n" }, { "answer_id": 74480911, "author": "Ricardo", "author_id": 16353662, "author_profile": "https://Stackoverflow.com/users/16353662", "pm_score": 0, "selected": false, "text": "students = np.array([['Hannah'],['Alonzo'], ['Antoinette'], ['Latasha'], ['Phil']])\ngrades = np.array([[86, 94], [83, 79], [97, 95], [90, 87], [73, 76]])\ngrades[(students == ['Alonzo']).flatten()]\n" }, { "answer_id": 74480951, "author": "Jamiu Shaibu", "author_id": 19290081, "author_profile": "https://Stackoverflow.com/users/19290081", "pm_score": 1, "selected": false, "text": "import numpy as np\nstudents = np.array([['Hannah'],['Alonzo'], ['Antoinette'], ['Latasha'], ['Phil']])\n\ngrades = np.array([[86, 94], [83, 79], [97, 95], [90, 87], [73, 76]])\n\nfor index,student in enumerate(students):\n if student == 'Alonzo':\n print(grades[index])\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19031038/" ]
74,480,916
<p>I'm currently trying to create a navbar for my website. The navbar is implemented using a <code>ul</code> container which is set to <code>display: flex</code>. Most of the items inside this <code>flexbox</code> are <code>li</code> tags containing anchor elements, but the first <code>li</code> contains an <code>svg</code> (a logo).</p> <p>I'm trying to get the <code>svg</code> to responsively scale to the same height as the anchor elements by utilizing the implicit <code>align-items: stretch</code> of the <code>ul</code>. I would like the width to be automatically calculated using the original aspect ratio of the <code>svg</code> and the height.</p> <p>I was able to get the <code>svg</code> to scale to the correct height by adding <code>height: 100%</code> to itself and its parent <code>&lt;a&gt;</code> tag. This has had the unintended side effect of making the parent <code>li</code> have a width of <code>0</code>. This causes the <code>flexbox</code> to space the elements incorrectly. I've tried in Chrome and Firefox and had the same result regardless, so it seems likely this is intended functionality. I've attached a code snippet below showing the behavior.</p> <p>Can someone help explain to me how I can fix this without requiring hard-coded values and still fulfilling the requirements above?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>nav&gt;ul { display: flex; flex-direction: row; justify-content: center; align-items: stretch; list-style: none; gap: 1em; } nav&gt;ul&gt;li { display: inline-block; text-align: center; } nav&gt;ul&gt;li&gt;a { display: inline-block; text-decoration: none; padding: 0; } nav&gt;ul&gt;li&gt;a:not(.logo-container&gt;a) { color: white; background-color: gray; padding: 2em; } .logo-container&gt;a { height: 100%; } .nav-logo { height: 100%; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;body&gt; &lt;header&gt; &lt;nav&gt; &lt;ul&gt; &lt;li class="logo-container"&gt; &lt;a href="index.html"&gt; &lt;svg class="nav-logo" id="a" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 164.81 281"&gt;&lt;defs&gt;&lt;style&gt;.b{fill:#4098ff;}.c{fill:#1463b2;}.d{fill:#0b2c54;}&lt;/style&gt;&lt;/defs&gt;&lt;path class="d" d="M1.96,47.61v92.87l53.63,30.95v61.93l-26.8-15.49v-30.92L1.99,171.46v61.93l80.44,46.44V94.05L1.96,47.61Zm53.63,92.9l-26.8-15.49v-30.98l26.8,15.49v30.98Z"/&gt;&lt;polygon class="b" points="28.79 186.95 55.59 171.46 28.79 155.97 1.96 171.46 28.79 186.95"/&gt;&lt;polygon class="c" points="28.79 217.9 55.59 202.41 55.59 171.46 28.79 186.95 28.79 217.9"/&gt;&lt;polygon class="b" points="55.59 233.39 55.59 202.41 28.79 217.9 55.59 233.39"/&gt;&lt;polygon class="c" points="28.79 125.03 55.59 109.54 28.79 94.05 28.79 125.03"/&gt;&lt;polygon class="b" points="55.59 140.51 55.59 109.54 28.79 125.03 55.59 140.51"/&gt;&lt;path class="c" d="M82.42,94.05v185.78l26.8-15.49v-92.87l53.63-30.95V47.61l-80.44,46.44Zm53.6,30.98l-26.8,15.49v-30.95l26.8-15.49v30.95Z"/&gt;&lt;polygon class="b" points="109.22 140.51 136.03 125.03 109.22 109.54 109.22 140.51"/&gt;&lt;polygon class="d" points="136.03 94.05 136.03 125.03 109.22 109.54 136.03 94.05"/&gt;&lt;polygon class="b" points="1.96 47.61 82.42 94.05 162.86 47.61 82.42 1.17 1.96 47.61"/&gt;&lt;/svg&gt; &lt;/a&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="index.html"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="about.html"&gt;About&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="contact.html"&gt;Contact&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;/header&gt; &lt;/body&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74480869, "author": "Edward Peters", "author_id": 6016064, "author_profile": "https://Stackoverflow.com/users/6016064", "pm_score": 0, "selected": false, "text": "dictionary" }, { "answer_id": 74480883, "author": "eshirvana", "author_id": 1367454, "author_profile": "https://Stackoverflow.com/users/1367454", "pm_score": 0, "selected": false, "text": "find = 'Alonzo'\n\nfor i,student in enumerate(students):\n if student == find:\n print(grades[i])\n break\n" }, { "answer_id": 74480911, "author": "Ricardo", "author_id": 16353662, "author_profile": "https://Stackoverflow.com/users/16353662", "pm_score": 0, "selected": false, "text": "students = np.array([['Hannah'],['Alonzo'], ['Antoinette'], ['Latasha'], ['Phil']])\ngrades = np.array([[86, 94], [83, 79], [97, 95], [90, 87], [73, 76]])\ngrades[(students == ['Alonzo']).flatten()]\n" }, { "answer_id": 74480951, "author": "Jamiu Shaibu", "author_id": 19290081, "author_profile": "https://Stackoverflow.com/users/19290081", "pm_score": 1, "selected": false, "text": "import numpy as np\nstudents = np.array([['Hannah'],['Alonzo'], ['Antoinette'], ['Latasha'], ['Phil']])\n\ngrades = np.array([[86, 94], [83, 79], [97, 95], [90, 87], [73, 76]])\n\nfor index,student in enumerate(students):\n if student == 'Alonzo':\n print(grades[index])\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19072633/" ]
74,480,919
<p>This may be very basic, but I'm trying to get the exact number of records for a query in Oracle SQL.</p> <p>Since the platform doesn't allow to get big files as an export, I need to divide the output in parts, but I want to know how many records I have in each year for example.</p> <p>This is the query:</p> <pre><code>select a.item1, c.item2, c.item3, d.date1, d.date2, c.amount1, c.amount2, c.ID1, c.ID2 from Table1 a, Table2 b, Table3 c, Table4 d where a.ID1 = b.ID1 and b.ID1 = c.ID1 and c.ID1 = d.ID1 and (d.ID4 = 'abc1' or d.ID4 = 'abc2' or d.ID4 = 'abc3') and trunc(d.date1) between to_date('20210101', 'YYYYMMDD') and to_date('20211231', 'YYYYMMDD') </code></pre> <p>The query runs fine in test mode, but in prod I get that my output is too big, that´s why I want to know how many records I get per year.</p> <p>I'm expecting to see how many records per year I have with this specific query.</p>
[ { "answer_id": 74480956, "author": "Bohemian", "author_id": 256196, "author_profile": "https://Stackoverflow.com/users/256196", "pm_score": -1, "selected": true, "text": "count(*)" }, { "answer_id": 74481136, "author": "ardai", "author_id": 20522477, "author_profile": "https://Stackoverflow.com/users/20522477", "pm_score": 1, "selected": false, "text": "select to_char(d.date1,'YYYY') , count(*) \nfrom Table1 a, Table2 b, Table3 c, Table4 d\nwhere a.ID1 = b.ID1\nand b.ID1 = c.ID1\nand c.ID1 = d.ID1\nand (d.ID4 = 'abc1'\nor d.ID4 = 'abc2'\nor d.ID4 = 'abc3')\ngroup by to_char(d.date1,'YYYY')\n" }, { "answer_id": 74482120, "author": "Littlefoot", "author_id": 9097906, "author_profile": "https://Stackoverflow.com/users/9097906", "pm_score": 0, "selected": false, "text": "select extract(year from d.date1) as year,\n count(*)\nfrom table1 a join table2 b on a.id1 = b.id1\n join table3 c on c.id1 = b.id1\n join table4 d on d.id1 = c.id1\nwhere d.id4 in ('abc1', 'abc2', 'abc3')\ngroup by extract(year from d.date1)\norder by extract(year from d.date1);\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11904865/" ]
74,480,923
<p>EF Core 6 introduced the ability to auto-include navigations (<a href="https://learn.microsoft.com/en-us/ef/core/querying/related-data/eager#model-configuration-for-auto-including-navigations" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/ef/core/querying/related-data/eager#model-configuration-for-auto-including-navigations</a>).I have a model that is related to multiple tables and I would like to configure it to auto-include multiple related tables but have been unable to figure out how to do it. Is this supported?</p> <p>This is the current setup.</p> <pre><code> modelBuilder.Entity&lt;ExampleModel&gt;() .UseXminAsConcurrencyToken() .Navigation(e =&gt; e.ExampleModelRelatedItem1).AutoInclude() .AutoInclude(); </code></pre> <p>I have tried variations such as</p> <pre><code> modelBuilder.Entity&lt;ExampleModel&gt;() .UseXminAsConcurrencyToken() .Navigation(e =&gt; e.ExampleModelRelatedItem1).AutoInclude() .Navigation(e =&gt; e.ExampleModelRelatedItem2).AutoInclude() .AutoInclude(); </code></pre> <p>but can't find anything that works.</p>
[ { "answer_id": 74525852, "author": "Gabor", "author_id": 6208915, "author_profile": "https://Stackoverflow.com/users/6208915", "pm_score": 0, "selected": false, "text": ".AutoInclude()" }, { "answer_id": 74552909, "author": "Ivan Stoev", "author_id": 5202563, "author_profile": "https://Stackoverflow.com/users/5202563", "pm_score": 3, "selected": true, "text": "EntityTypeBuilder<T>" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13706650/" ]
74,480,932
<p>I want to write a program that asks the user for a message, then converts the message using the telephony codes, codes that translate each letter into a specific word. Here is sample output from the program:</p> <blockquote> <p>This program will translate a message using telephony codes. What is your message? I love you, mom! India Lima Oscar Victor Echo Yankee Oscar Uniform Mike Oscar Mike</p> </blockquote> <p>The solution I can think of is to replace the letter a to alfa and then b and then rest of the list but it is just time consuming; My question is: how can I use a for loop (maybe?) to set conditions and to convert all letters?</p> <pre><code>Basically you need to convert every letter into a new word using the dictionaries </code></pre> <p>&quot;A&quot;: &quot;Alfa&quot;, &quot;B&quot;: &quot;Bravo&quot;, &quot;C&quot;: &quot;Charlie&quot;, &quot;D&quot;: &quot;Delta&quot;, &quot;E&quot;: &quot;Echo&quot;, &quot;F&quot;: &quot;Foxtrot&quot;, &quot;G&quot;: &quot;Golf&quot;, &quot;H&quot;: &quot;Hotel&quot;, &quot;I&quot;: &quot;India&quot;, &quot;J&quot;: &quot;Juliett&quot;, &quot;K&quot;: &quot;Kilo&quot;, &quot;L&quot;: &quot;Lima&quot;, &quot;M&quot;: &quot;Mike&quot;, &quot;N&quot;: &quot;November&quot;, &quot;O&quot;: &quot;Oscar&quot;, &quot;P&quot;: &quot;Papa&quot;, &quot;Q&quot;: &quot;Quebec&quot;, &quot;R&quot;: &quot;Romeo&quot;, &quot;S&quot;: &quot;Sierra&quot;, &quot;T&quot;: &quot;Tango&quot;, &quot;U&quot;: &quot;Uniform&quot;, &quot;V&quot;: &quot;Victor&quot;, &quot;W&quot;: &quot;Whiskey&quot;, &quot;X&quot;: &quot;X-ray&quot;, &quot;Y&quot;: &quot;Yankee&quot;, &quot;Z&quot;: &quot;Zulu&quot;,</p> <pre><code> </code></pre>
[ { "answer_id": 74480975, "author": "CharlieBONS", "author_id": 20529340, "author_profile": "https://Stackoverflow.com/users/20529340", "pm_score": 1, "selected": false, "text": "for letter in list(word):\n if output == '':\n output = dictionary[letter]\n else:\n output = output + ' ' + dictionary[letter]\n\n" }, { "answer_id": 74481007, "author": "Ricardo", "author_id": 16353662, "author_profile": "https://Stackoverflow.com/users/16353662", "pm_score": 0, "selected": false, "text": "sample = \"This program will translate a message using telephony codes. What is your message? I love you, mom! India Lima Oscar Victor Echo Yankee Oscar Uniform Mike Oscar Mike\"\n\nfor letter, word in {\"A\": \"Alfa\", \"B\": \"Bravo\", \"C\": \"Charlie\", \"D\": \"Delta\", \"E\": \"Echo\", \"F\": \"Foxtrot\", \"G\": \"Golf\", \"H\": \"Hotel\", \"I\": \"India\", \"J\": \"Juliett\", \"K\": \"Kilo\", \"L\": \"Lima\", \"M\": \"Mike\", \"N\": \"November\", \"O\": \"Oscar\", \"P\": \"Papa\", \"Q\": \"Quebec\", \"R\": \"Romeo\", \"S\": \"Sierra\", \"T\": \"Tango\", \"U\": \"Uniform\", \"V\": \"Victor\", \"W\": \"Whiskey\", \"X\": \"X-ray\", \"Y\": \"Yankee\", \"Z\": \"Zulu\"}.items():\n sample = sample.replace(word, letter)\nsample\n>>> 'This program will translate a message using telephony codes. What is your message? I love you, mom! I L O V E Y O U M O M'\n" }, { "answer_id": 74481053, "author": "Reuben Jacob Mathew", "author_id": 11358838, "author_profile": "https://Stackoverflow.com/users/11358838", "pm_score": 0, "selected": false, "text": "lookup = {\",\": 'com',\"A\": \"Alfa\", \"B\": \"Bravo\", \"C\": \"Charlie\", \"D\": \"Delta\", \"E\": \"Echo\", \"F\": \"Foxtrot\", \"G\": \"Golf\", \"H\": \"Hotel\", \"I\": \"India\", \"J\": \"Juliett\", \"K\": \"Kilo\", \"L\": \"Lima\", \"M\": \"Mike\", \"N\": \"November\", \"O\": \"Oscar\", \"P\": \"Papa\", \"Q\": \"Quebec\", \"R\": \"Romeo\", \"S\": \"Sierra\", \"T\": \"Tango\", \"U\": \"Uniform\", \"V\": \"Victor\", \"W\": \"Whiskey\", \"X\": \"X-ray\", \"Y\": \"Yankee\", \"Z\": \"Zulu\"}\n#here punctuations have been removed before hand\nst = \"This program will translate a message using telephony codes What is your message I love you mom India Lima Oscar Victor Echo Yankee Oscar Uniform Mike Oscar Mike\".upper()\nst = st.replace(' ', ',') #replacing spaces with comas\nprint(''.join(list(map(lambda x:lookup[x], st))))\n" } ]
2022/11/17
[ "https://Stackoverflow.com/questions/74480932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20533197/" ]