qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,524,159
<p>I am trying to pass a concatenated columns from a LINQ statement to a select list using view bag.</p> <p>Controller:</p> <pre><code>var translators = bidsinfo1.Select(x =&gt; new { Name = x.TranslatorFirstName + &quot; &quot; + x.TranslatorLastName} ).ToList(); ViewBag.TranslatorList = translators; </code></pre> <p>View:</p> <pre><code>&lt;div class=&quot;form-group&quot;&gt; &lt;select class=&quot;form-control&quot; asp-items=&quot;new SelectList(ViewBag.TranslatorList)&quot;&gt; &lt;option&gt;Select Translator&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; </code></pre> <p>But in the select list when i run the project it's showing the values like this { Name = harvey specter }, please any suggestion?</p>
[ { "answer_id": 74524975, "author": "Marko E", "author_id": 8343484, "author_profile": "https://Stackoverflow.com/users/8343484", "pm_score": 2, "selected": false, "text": "data \"aws_vpc\" \"accepter\" {\n provider = aws.accepter # <--- missing aliased provider\n id = var.accepter_vpc_id\n}\n provider \"aws\" {\n alias = \"accepter\"\n region = \"us-east-1\" # make sure the region is right\n}\n" }, { "answer_id": 74589935, "author": "NinjaCloud", "author_id": 20432287, "author_profile": "https://Stackoverflow.com/users/20432287", "pm_score": 0, "selected": false, "text": "provider \"aws\" {\n region = \"us-east-1\"\n\n # Requester's credentials.\n}\n\nprovider \"aws\" {\n alias = \"peer\"\n region = \"us-west-2\"\n\n # Accepter's credentials.\n}" }, { "answer_id": 74590259, "author": "Pawel Piwosz", "author_id": 20614302, "author_profile": "https://Stackoverflow.com/users/20614302", "pm_score": 0, "selected": false, "text": "provider \"aws\" {\n region = \"us-east-1\"\n alias = \"accepter\"\n}\n provider = aws.accepter data \"aws_vpc\" \"accepter\"" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15726579/" ]
74,524,178
<p>I'm having a problem getting string part in ElasticSearch. Below is the configuration of index.</p> <pre><code>PUT exemplo { &quot;settings&quot;: { &quot;analysis&quot;: { &quot;analyzer&quot;: { &quot;portuguese_br&quot;: { &quot;type&quot;: &quot;portuguese&quot; } } } }, &quot;mappings&quot;: { &quot;properties&quot;: { &quot;id&quot;: { &quot;type&quot;: &quot;integer&quot; }, &quot;content&quot;: { &quot;type&quot;: &quot;text&quot;, &quot;analyzer&quot;: &quot;portuguese_br&quot; } } } } </code></pre> <p>There is a document with the following content in the index &quot;exemplo&quot;:</p> <pre><code>h2 style margin 0 0 8px font size 16px color 064a7a 1 Síntese Resumo Descrição do cliente h2 div id headertipodocumento1 style min height 40px position relative class editable mce content body contenteditable true spellcheck false p eu encaminho uma Carta ao ReI </code></pre> <p>I can't get the document with the following request:</p> <pre><code>GET exemplo/_search { &quot;from&quot;: 0, &quot;size&quot;: 1, &quot;query&quot;: { &quot;bool&quot;: { &quot;must&quot;: [ {&quot;regexp&quot;: {&quot;content&quot;: &quot;.*caminho.*&quot;}} ] } } } </code></pre> <p>There is a part of content with the word &quot;encaminho&quot;. I'm searching for &quot;caminho&quot; and not getting any result.</p> <p>Am I doing something wrong in regexp?</p>
[ { "answer_id": 74524975, "author": "Marko E", "author_id": 8343484, "author_profile": "https://Stackoverflow.com/users/8343484", "pm_score": 2, "selected": false, "text": "data \"aws_vpc\" \"accepter\" {\n provider = aws.accepter # <--- missing aliased provider\n id = var.accepter_vpc_id\n}\n provider \"aws\" {\n alias = \"accepter\"\n region = \"us-east-1\" # make sure the region is right\n}\n" }, { "answer_id": 74589935, "author": "NinjaCloud", "author_id": 20432287, "author_profile": "https://Stackoverflow.com/users/20432287", "pm_score": 0, "selected": false, "text": "provider \"aws\" {\n region = \"us-east-1\"\n\n # Requester's credentials.\n}\n\nprovider \"aws\" {\n alias = \"peer\"\n region = \"us-west-2\"\n\n # Accepter's credentials.\n}" }, { "answer_id": 74590259, "author": "Pawel Piwosz", "author_id": 20614302, "author_profile": "https://Stackoverflow.com/users/20614302", "pm_score": 0, "selected": false, "text": "provider \"aws\" {\n region = \"us-east-1\"\n alias = \"accepter\"\n}\n provider = aws.accepter data \"aws_vpc\" \"accepter\"" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5936418/" ]
74,524,232
<p>Given a string of numbers like 123456, I want to find all the possibilities they can be paired in by 2 or by itself. For example, from the string <code>123456</code> I would like to get the following:</p> <pre><code>12 3 4 5 6, 12 34 5 6, 1 23 4 56, etc. </code></pre> <p>The nearest I was able to come to was this:</p> <pre class="lang-py prettyprint-override"><code>strr = list(&quot;123456&quot;) x = list(&quot;123456&quot;) for i in range(int(len(strr)/2)): newlist = [] for j in range(i): newlist.append(x[j]) newlist.append(x[i] + x[i+1]) for j in range(len(x))[i+2:]: newlist.append(x[j]) x = newlist.copy() b = x.copy() for f in range(len(b))[i:]: if f == i: print(b) continue b[f] = b[f - 1][1] + b[f] b[f - 1] = b[f - 1][0] print(b) </code></pre> <p>This code gives the output:</p> <p><img src="https://i.stack.imgur.com/tk7On.png" alt="output" /></p>
[ { "answer_id": 74524975, "author": "Marko E", "author_id": 8343484, "author_profile": "https://Stackoverflow.com/users/8343484", "pm_score": 2, "selected": false, "text": "data \"aws_vpc\" \"accepter\" {\n provider = aws.accepter # <--- missing aliased provider\n id = var.accepter_vpc_id\n}\n provider \"aws\" {\n alias = \"accepter\"\n region = \"us-east-1\" # make sure the region is right\n}\n" }, { "answer_id": 74589935, "author": "NinjaCloud", "author_id": 20432287, "author_profile": "https://Stackoverflow.com/users/20432287", "pm_score": 0, "selected": false, "text": "provider \"aws\" {\n region = \"us-east-1\"\n\n # Requester's credentials.\n}\n\nprovider \"aws\" {\n alias = \"peer\"\n region = \"us-west-2\"\n\n # Accepter's credentials.\n}" }, { "answer_id": 74590259, "author": "Pawel Piwosz", "author_id": 20614302, "author_profile": "https://Stackoverflow.com/users/20614302", "pm_score": 0, "selected": false, "text": "provider \"aws\" {\n region = \"us-east-1\"\n alias = \"accepter\"\n}\n provider = aws.accepter data \"aws_vpc\" \"accepter\"" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20566173/" ]
74,524,245
<p>I receive the error message:</p> <blockquote> <p>django.urls.exceptions.NoReverseMatch: Reverse for 'journalrep' with arguments '('',)' not found. 2 pattern(s) tried: ['reports/journalrep/(?P[^/]+)/(?P[^/]+)\Z', 'reports/journalrep/\Z']</p> </blockquote> <p>My urls.py contains:</p> <pre><code>from django.urls import path from . import views urlpatterns = [ path('', views.index, name='reports'), path('sumlist/', views.summary_list,name='sumlist'), path('overallsummary',views.overallsummary,name='overallsummary'), path('checkreg', views.checkreg, name='checkreg'), path('checkdet/&lt;chkno&gt;/', views.checkdet, name='checkdet'), path('journalrep/', views.journalrep, name='journalrep'), path('journalrep/&lt;column&gt;/&lt;direction&gt;', views.journalrep, name='journalrep'), path('journaldet/&lt;tranid&gt;', views.journaldet, name='journaldet'), path('accountrep', views.accountrep, name='accountrep') ] </code></pre> <p>The view that renders the template is a function view:</p> <pre><code>@login_required def journalrep(request,column = 'date', direction = 'D'): ''' Produce journal register Will display information for a chart of accounts account if provided. If the value is 0 all journal entries will be shown ''' # # Get list of accounts (Chart of acconts) to be used for account selection box coa = ChartOfAccounts.objects.all().filter(COA_account__gt=0) coa_account = request.session.get('coa_account', None) if len(request.GET) != 0: coa_account = request.GET.get('coa_account') else: if coa_account == None: coa_account = '0' if direction == 'D': direction = '-' else: direction = &quot;&quot; if coa_account == '0': journal = Journal.objects.all().order_by(direction + column) else: journal = Journal.objects.filter(account__COA_account = coa_account).order_by(direction + column) context = { 'coa' : coa, 'journal' : journal , 'coa_account' : Decimal(coa_account)} request.session['coa_account'] = coa_account return render(request, 'reports/journal.html', context) </code></pre> <p>And the template that is rendered is:</p> <pre><code>&lt;div class=&quot;container shadow min-vh-100 py-2&quot;&gt; &lt;h2&gt;Journal Register&lt;/h2&gt; &lt;select name=&quot;coa_account&quot; hx-get=&quot;{% url 'journalrep' row.transactionID %}&quot; hx-target=&quot;#requestcontent&quot; &gt; &lt;option value=&quot;0&quot;&gt;All&lt;/option&gt; {% for option in coa %} &lt;option value=&quot;{{option.COA_account}}&quot; {% if option.COA_account == coa_account %} selected {% endif %}&gt; {{option.COA_account_name}} {% if option.COA_account_subgroup != &quot;&quot; %} - {{option.COA_account_subgroup}} {% endif %} &lt;/option&gt; {% endfor %} &lt;/select&gt; &lt;div class=&quot;table-responsive&quot;&gt; &lt;table class=&quot;table table-hover &quot;&gt; &lt;thead&gt; &lt;tr&gt; &lt;th scope=&quot;col&quot;&gt;&lt;/th&gt; &lt;th scope=&quot;col&quot;&gt;Date &lt;br&gt; &lt;a hx-get=&quot;{% url 'journalrep' 'date' 'D' %}&quot; hx-target=&quot;#requestcontent&quot; &gt; &lt;i class=&quot;bi bi-sort-alpha-down&quot;&gt; &lt;/i&gt; &lt;/a&gt; &lt;a hx-get=&quot;{% url 'journalrep' 'date' 'A' %}&quot; hx-target=&quot;#requestcontent&quot; &gt; &lt;i class=&quot;bi bi-sort-alpha-up&quot; &gt;&lt;/i&gt; &lt;/a&gt; &lt;/th&gt; &lt;th scope=&quot;col&quot;&gt;Account&lt;br&gt;&amp;nbsp; &lt;/th&gt; &lt;th scope=&quot;col&quot;&gt;Description&lt;br&gt;&amp;nbsp;&lt;/th&gt; &lt;th scope=&quot;col&quot;&gt;Amount&lt;br&gt; &lt;a hx-get=&quot;{% url 'journalrep' 'amount' 'D' %}&quot; hx-target=&quot;#requestcontent&quot; &gt; &lt;i class=&quot;bi bi-sort-alpha-down&quot;&gt; &lt;/i&gt; &lt;/a&gt; &lt;a hx-get=&quot;{% url 'journalrep' 'amount' 'A' %}&quot; hx-target=&quot;#requestcontent&quot; &gt; &lt;i class=&quot;bi bi-sort-alpha-up&quot; &gt;&lt;/i&gt; &lt;/a&gt; &lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; {% for row in journal %} &lt;tr data-bs-toggle=&quot;collapse&quot; data-bs-target=&quot;#detail-&quot;&gt; &lt;th scope=&quot;row&quot;&gt; {% if request.user.is_superuser %} &lt;button hx-get=&quot;{% url 'journaldet' row.transactionID %}&quot; hx-target=&quot;#dialog&quot; &gt; &lt;i class=&quot;bi bi-eye&quot;&gt;&lt;/i&gt; &lt;/button&gt; {% else %} &amp;nbsp; {% endif %} &lt;/th&gt; &lt;td&gt;{{ row.date }}&lt;/td&gt; &lt;td&gt; {{ row.account.COA_account}}&lt;br&gt; {{ row.account.COA_account_name}} &lt;/td&gt; &lt;td&gt; {{ row.description }} {% if row.transactionID != &quot;&quot; %} &lt;br&gt;{{ row.transactionID}} {% endif %} &lt;/td&gt; &lt;td align=&quot;right&quot;&gt;${{ row.amount | floatformat:2 }}&lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id=&quot;modal&quot; class=&quot;modal fade&quot;&gt; &lt;div id=&quot;dialog&quot; class=&quot;modal-dialog&quot; hx-target=&quot;this&quot;&gt;&lt;/div&gt; &lt;/div&gt; &lt;script&gt; const modal = new bootstrap.Modal(document.getElementById(&quot;modal&quot;)) htmx.on(&quot;htmx:afterSwap&quot;, (e) =&gt; { // Response targeting #dialog =&gt; show the modal if (e.detail.target.id == &quot;dialog&quot;) { modal.show() } }) &lt;/script&gt; </code></pre>
[ { "answer_id": 74524975, "author": "Marko E", "author_id": 8343484, "author_profile": "https://Stackoverflow.com/users/8343484", "pm_score": 2, "selected": false, "text": "data \"aws_vpc\" \"accepter\" {\n provider = aws.accepter # <--- missing aliased provider\n id = var.accepter_vpc_id\n}\n provider \"aws\" {\n alias = \"accepter\"\n region = \"us-east-1\" # make sure the region is right\n}\n" }, { "answer_id": 74589935, "author": "NinjaCloud", "author_id": 20432287, "author_profile": "https://Stackoverflow.com/users/20432287", "pm_score": 0, "selected": false, "text": "provider \"aws\" {\n region = \"us-east-1\"\n\n # Requester's credentials.\n}\n\nprovider \"aws\" {\n alias = \"peer\"\n region = \"us-west-2\"\n\n # Accepter's credentials.\n}" }, { "answer_id": 74590259, "author": "Pawel Piwosz", "author_id": 20614302, "author_profile": "https://Stackoverflow.com/users/20614302", "pm_score": 0, "selected": false, "text": "provider \"aws\" {\n region = \"us-east-1\"\n alias = \"accepter\"\n}\n provider = aws.accepter data \"aws_vpc\" \"accepter\"" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14016548/" ]
74,524,271
<p>I receive a date like 1.01.2022 h:00, m:00, s:00, ms: 00</p> <p>What is the best approach to get the date at the end of the day, something like: 01.01.2022 h:23, m:59, s:59, ms: 999?</p> <p>I tried those 2 ways:</p> <p><code>var endOfDay = new TimeSpan(0, 23, 59, 59, 999);</code><br /> <code> time = time.Add(endOfDay);</code></p> <p>and</p> <p><code>time = time.AddDays(1).AddMilliseconds(-1);</code></p>
[ { "answer_id": 74524333, "author": "Kit", "author_id": 64348, "author_profile": "https://Stackoverflow.com/users/64348", "pm_score": 3, "selected": true, "text": "dateAndTime dateAndTime.Date.AddDays(1).AddTicks(-1);\n" }, { "answer_id": 74524410, "author": "Dmitry Bychenko", "author_id": 2319407, "author_profile": "https://Stackoverflow.com/users/2319407", "pm_score": 1, "selected": false, "text": ">= < if (timeOfQuestion >= day.Date && timeOfQuestion < day.Date.AddDays(1)) {\n ...\n } \n endOfDays = time.AddDays(1).AddMilliseconds(-1) day.Date.AddMilliseconds(999.5) double" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14938011/" ]
74,524,280
<p>I have a legacy system interfacing issue that my team has elected to solve by standing up a .NET 7 <a href="https://learn.microsoft.com/en-us/aspnet/core/fundamentals/minimal-apis?view=aspnetcore-7.0" rel="nofollow noreferrer">Minimal API</a> which needs to accept a file upload. It should work for small and large files (let's say at least 500 MiB). The API will be called from a legacy system using HttpClient in a .NET Framework 4.7.1 app.</p> <p>I can't quite seem to figure out how to design the signature of the Minimal API and how to call it with HttpClient in a way that totally works. It's something I've been hacking at on and off for several days, and haven't documented all of my approaches, but suffice it to say there have been varying results involving, among other things:</p> <ul> <li>4XX and 500 errors returned by the HTTP call</li> <li>An assortment of exceptions on either side</li> <li>Calls that throw and never hit a breakpoint on the API side</li> <li>Calls that get through but the <code>Stream</code> on the API end is not what I expect</li> <li>Errors being different depending on whether the file being uploaded is small or large</li> <li>Text files being persisted on the server that contain some of the HTTP headers in addition to their original contents</li> </ul> <p>On the Minimal API side, I've tried all sorts of things in the signature (<code>IFormFile</code>, <code>Stream</code>, <code>PipeReader</code>, <code>HttpRequest</code>). On the calling side, I've tried several approaches (messing with headers, using the <a href="https://github.com/tmenier/Flurl" rel="nofollow noreferrer">Flurl</a> library, various content encodings and MIME types, multipart, etc).</p> <p>This seems like it should be dead simple, so I'm trying to wipe the slate clean here, start with an example of something that partially works, and hope someone might be able to illuminate the path forward for me.</p> <p>Example of Minimal API:</p> <pre><code>// IDocumentStorageManager is an injected dependency that takes an int and a Stream and returns a string of the newly uploaded file's URI app.MapPost( &quot;DocumentStorage/CreateDocument2/{documentId:int}&quot;, async (PipeReader pipeReader, int documentId, IDocumentStorageManager documentStorageManager) =&gt; { using var ms = new MemoryStream(); await pipeReader.CopyToAsync(ms); ms.Position = 0; return await documentStorageManager.CreateDocument(documentId, ms); }); </code></pre> <p>Call the Minimal API using HttpClient:</p> <pre><code> // filePath is the path on local disk, uri is the Minimal API's URI private static async Task&lt;string&gt; UploadWithHttpClient2(string filePath, string uri) { var fileStream = File.Open(filePath, FileMode.Open); var content = new StreamContent(fileStream); var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, uri); var httpClient = new HttpClient(); httpRequestMessage.Content = content; httpClient.Timeout = TimeSpan.FromMinutes(5); var result = await httpClient.SendAsync(httpRequestMessage); return await result.Content.ReadAsStringAsync(); } </code></pre> <p>In the particular example above, a small (6 bytes) .txt file is uploaded without issue. However, a large (619 MiB) .tif file runs into problems on the call to <code>httpClient.SendAsync</code> which results in the following set of nested <code>Exceptions</code>:</p> <pre><code>System.Net.Http.HttpRequestException - &quot;Error while copying content to a stream.&quot; System.IO.IOException - &quot;Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host..&quot; System.Net.Sockets.SocketException - &quot;An existing connection was forcibly closed by the remote host.&quot; </code></pre> <p>What's a decent way of writing a Minimal API and calling it with <code>HttpClient</code> that will work for small and large files?</p>
[ { "answer_id": 74554205, "author": "Wolfspirit", "author_id": 5193262, "author_profile": "https://Stackoverflow.com/users/5193262", "pm_score": 2, "selected": false, "text": "app.MapPost(\n \"DocumentStorage/CreateDocument2/{documentId:int}\",\n [RequestSizeLimit(1_000_000_000)] async (PipeReader pipeReader, int documentId) =>\n {\n using var ms = new MemoryStream();\n await pipeReader.CopyToAsync(ms);\n ms.Position = 0;\n return \"\";\n });\n builder.WebHost.UseKestrel(o => o.Limits.MaxRequestBodySize = null);\n" }, { "answer_id": 74674435, "author": "davidfowl", "author_id": 45091, "author_profile": "https://Stackoverflow.com/users/45091", "pm_score": 0, "selected": false, "text": "RequestSizeLimit IHttpMaxRequestBodySizeFeature Stream CreateDocument app.MapPost(\n \"DocumentStorage/CreateDocument2/{documentId:int}\",\n async (Stream stream, int documentId, IDocumentStorageManager documentStorageManager) =>\n {\n return await documentStorageManager.CreateDocument(documentId, stream);\n })\n .AddEndpointFilter((context, next) =>\n {\n const int MaxBytes = 1024 * 1024 * 1024;\n\n var maxRequestBodySizeFeature = context.HttpContext.Features.Get<IHttpMaxRequestBodySizeFeature>();\n\n if (maxRequestBodySizeFeature is not null and { IsReadOnly: true })\n {\n maxRequestBodySizeFeature.MaxRequestBodySize = MaxBytes;\n }\n\n return next(context);\n });\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3241128/" ]
74,524,281
<p>I'm using Java Springboot to read the inbox of a Microsoft Exchange account (I am already able to send emails programmatically). When I try to read the inbox folder I receive a general error:</p> <pre><code>javax.mail.MessagingException: Connection dropped by server? </code></pre> <p>Username and password are of course correct.</p> <p>I use the following configuration:</p> <pre><code> Properties mailProps = new Properties(); mailProps.setProperty(&quot;mail.transport.protocol&quot;,&quot;smtp&quot;); mailProps.setProperty(&quot;mail.smtp.auth&quot;,&quot;true&quot;); mailProps.setProperty(&quot;mail.smtp.starttls.enable&quot;,&quot;true&quot;); mailProps.setProperty(&quot;mail.debug&quot;,&quot;false&quot;); mailProps.setProperty(&quot;mail.smtp.sasl.mechanisms.oauth2.oauthToken&quot;, password); Session session = Session.getDefaultInstance(mailProps); Store store = session.getStore(&quot;imaps&quot;); store.connect(&quot;outlook.office365.com&quot;, 143, username, password); //username and password are omitted Folder emailFolder = store.getFolder(&quot;inbox&quot;); emailFolder.open(Folder.READ_ONLY); </code></pre> <p>UPDATE: Since I can get the inbox from the Thunderbird client, I set up the code following the configuration on Thunderbird. Now I have:</p> <pre><code>DEBUG: getProvider() returning javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle] DEBUG IMAPS: mail.imap.fetchsize: 16384 DEBUG IMAPS: mail.imap.ignorebodystructuresize: false DEBUG IMAPS: mail.imap.statuscachetimeout: 1000 DEBUG IMAPS: mail.imap.appendbuffersize: -1 DEBUG IMAPS: mail.imap.minidletime: 10 DEBUG IMAPS: enable STARTTLS DEBUG IMAPS: closeFoldersOnStoreFailure DEBUG IMAPS: trying to connect to host &quot;outlook.office365.com&quot;, port 143, isSSL true javax.mail.MessagingException: Unsupported or unrecognized SSL message at it.spring.platform.services.communication.mail.MailTest.read(MailTest.java:53) </code></pre> <p>For the sake of clarity and completeness I add the full Spring code I wrote to read the inbox:</p> <pre><code>import javax.mail.MessagingException; import javax.mail.Store; public class JavaMailReader { private Store store; private String username; private String password; private String host; private int port; private String inbox; public JavaMailReader(Store store, String host, int port, String username, String password, String inbox) { this.host=host; this.port=port; this.store=store; this.username=username; this.password=password; this.inbox=inbox; this.port = port; } public void connect() throws MessagingException { store.connect(host, port, username, password); } public Store getStore() { return store; } public String getInboxFolderName() { return this.inbox; } } @Bean public JavaMailReader emailReader(@Value(&quot;imaps&quot;) String protocol, @Value(&quot;${mailreceiver.mail.host}&quot;) String host, @Value(&quot;${mailreceiver.mail.port}&quot;) Integer port, @Value(&quot;${mailreceiver.mail.password}&quot;) String password, @Value(&quot;${mailreceiver.mail.username}&quot;) String username) throws NoSuchProviderException, MessagingException { Properties mailProps = new Properties(); mailProps.setProperty(&quot;mail.transport.protocol&quot;,&quot;imaps&quot;); mailProps.setProperty(&quot;mail.imaps.auth&quot;,&quot;true&quot;); mailProps.setProperty(&quot;mail.debug&quot;,&quot;true&quot;); mailProps.setProperty(&quot;mail.imaps.sasl.mechanisms.oauth2.oauthToken&quot;, password); Session session = Session.getDefaultInstance(mailProps); Store store = session.getStore(protocol); return new JavaMailReader (store, host, port, username, password, &quot;inbox&quot;); } //testing @Test public void read() throws NoSuchProviderException, MessagingException { Message[] messages = mailService.getInbox(); //getInbox(&quot;Inbox&quot;) Message found=null; for(Message m: messages) { if(m.getSubject().equalsIgnoreCase(subject)) { found=m; break; } } assertNotNull(found); mailService.closeReader(); } </code></pre> <p>UPDATE 2: As suggested, I changed the port to 993 and removed starttls:</p> <pre><code> Properties mailProps = new Properties(); mailProps.setProperty(&quot;mail.transport.protocol&quot;,&quot;imaps&quot;); mailProps.setProperty(&quot;mail.imaps.auth&quot;,&quot;true&quot;); mailProps.setProperty(&quot;mail.debug&quot;,&quot;true&quot;); maililProps. setProperty(&quot;mail.imaps.sasl.mechanisms.oauth2.oauthToken&quot;, password); Session session = Session.getDefaultInstance(mailProps); Store store = session.getStore(protocol); return new JavaMailReader (store, host, port, username, password, &quot;inbox&quot;); </code></pre> <p>Now I have the error:</p> <pre><code>DEBUG IMAPS: trying to connect to host &quot;outlook.office365.com&quot;, port 993, isSSL true * OK The Microsoft Exchange IMAP4 service is ready. [ a string here omitted for security reason==] A0 CAPABILITY * CAPABILITY IMAP4 IMAP4rev1 AUTH=PLAIN AUTH=XOAUTH2 SASL-IR UIDPLUS ID UNSELECT CHILDREN IDLE NAMESPACE LITERAL+ A0 OK CAPABILITY completed. DEBUG IMAPS: AUTH: PLAIN DEBUG IMAPS: AUTH: XOAUTH2 DEBUG IMAPS: protocolConnect login, host=outlook.office365.com, user= the user-email-here, password=&lt;non-null&gt; DEBUG IMAPS: AUTHENTICATE PLAIN command trace suppressed DEBUG IMAPS: AUTHENTICATE PLAIN command result: A1 NO AUTHENTICATE failed. Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 3.159 s javax.mail.AuthenticationFailedException: AUTHENTICATE failed. </code></pre>
[ { "answer_id": 74584561, "author": "tquadrat", "author_id": 1554195, "author_profile": "https://Stackoverflow.com/users/1554195", "pm_score": 0, "selected": false, "text": "Properties mailProps = new Properties();\nmailProps.setProperty(\"mail.transport.protocol\",\"imaps\");\nmailProps.setProperty(\"mail.imaps.auth\",\"true\");\nmailProps.setProperty(\"mail.imaps.starttls.enable\",\"true\");\nmailProps.setProperty(\"mail.debug\",\"false\"); \nmailProps.setProperty(\"mail.imaps.sasl.mechanisms.oauth2.oauthToken\", password);\nSession session = Session.getDefaultInstance(mailProps); \nStore store = session.getStore(\"imaps\"); \nstore.connect(\"outlook.office365.com\", 143, username, password); //username and password are omitted\nFolder emailFolder = store.getFolder(\"inbox\");\nemailFolder.open(Folder.READ_ONLY);\n" }, { "answer_id": 74610916, "author": "Tasos P.", "author_id": 1505146, "author_profile": "https://Stackoverflow.com/users/1505146", "pm_score": 3, "selected": true, "text": " trying to connect to host \"outlook.office365.com\", port 143, isSSL true * OK The Microsoft Exchange IMAP4 service is ready Unsupported or unrecognized SSL message 993 STARTTLS" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2260835/" ]
74,524,297
<p>I just created an indicator and also backtested it using strategy tester. Now I wish to run it automated with a 3rd party application. How can i add their webhook url in alert programmatically? any code snippets would be amazing!! I am new to pinescript</p>
[ { "answer_id": 74584561, "author": "tquadrat", "author_id": 1554195, "author_profile": "https://Stackoverflow.com/users/1554195", "pm_score": 0, "selected": false, "text": "Properties mailProps = new Properties();\nmailProps.setProperty(\"mail.transport.protocol\",\"imaps\");\nmailProps.setProperty(\"mail.imaps.auth\",\"true\");\nmailProps.setProperty(\"mail.imaps.starttls.enable\",\"true\");\nmailProps.setProperty(\"mail.debug\",\"false\"); \nmailProps.setProperty(\"mail.imaps.sasl.mechanisms.oauth2.oauthToken\", password);\nSession session = Session.getDefaultInstance(mailProps); \nStore store = session.getStore(\"imaps\"); \nstore.connect(\"outlook.office365.com\", 143, username, password); //username and password are omitted\nFolder emailFolder = store.getFolder(\"inbox\");\nemailFolder.open(Folder.READ_ONLY);\n" }, { "answer_id": 74610916, "author": "Tasos P.", "author_id": 1505146, "author_profile": "https://Stackoverflow.com/users/1505146", "pm_score": 3, "selected": true, "text": " trying to connect to host \"outlook.office365.com\", port 143, isSSL true * OK The Microsoft Exchange IMAP4 service is ready Unsupported or unrecognized SSL message 993 STARTTLS" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20537640/" ]
74,524,306
<p>For example there is a list:</p> <pre><code>list = [{'brand': 'Ford', 'Model': 'Mustang', 'year': 1964}, {'brand': 'Nissan', 'model': 'Skyline', 'year': 1969} ...] </code></pre> <p>I want to count there are how many model from each. How can I do it?</p> <p>By the way sorry for the bad formatting I am new here yet.</p> <p>I tried this method:</p> <pre><code>model_count = {} for i in list: if i['Model'] in model_count: model_count[i] += 1 else: model_count[i] = 1 </code></pre> <p>And I got this error: TypeError: unhashable type: 'dict'</p>
[ { "answer_id": 74584561, "author": "tquadrat", "author_id": 1554195, "author_profile": "https://Stackoverflow.com/users/1554195", "pm_score": 0, "selected": false, "text": "Properties mailProps = new Properties();\nmailProps.setProperty(\"mail.transport.protocol\",\"imaps\");\nmailProps.setProperty(\"mail.imaps.auth\",\"true\");\nmailProps.setProperty(\"mail.imaps.starttls.enable\",\"true\");\nmailProps.setProperty(\"mail.debug\",\"false\"); \nmailProps.setProperty(\"mail.imaps.sasl.mechanisms.oauth2.oauthToken\", password);\nSession session = Session.getDefaultInstance(mailProps); \nStore store = session.getStore(\"imaps\"); \nstore.connect(\"outlook.office365.com\", 143, username, password); //username and password are omitted\nFolder emailFolder = store.getFolder(\"inbox\");\nemailFolder.open(Folder.READ_ONLY);\n" }, { "answer_id": 74610916, "author": "Tasos P.", "author_id": 1505146, "author_profile": "https://Stackoverflow.com/users/1505146", "pm_score": 3, "selected": true, "text": " trying to connect to host \"outlook.office365.com\", port 143, isSSL true * OK The Microsoft Exchange IMAP4 service is ready Unsupported or unrecognized SSL message 993 STARTTLS" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20566223/" ]
74,524,342
<p>Trying to click next button from navigation bar of website &quot;https://uk.trustpilot.com/categories/bars_cafes?subcategories=cafe&quot; using selenium in python.</p> <pre><code>from selenium.webdriver import Chrome from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.common.by import By from bs4 import BeautifulSoup import time URL = &quot;https://uk.trustpilot.com/categories/bars_cafes?subcategories=cafe&quot; driver = Chrome(ChromeDriverManager().install()) class Scraper: def __init__(self, website): self.website = website def get_website(self): return driver.get(self.website) def ignore_cookie(self): try: ignore_cookies = driver.find_element(by=By.XPATH, value='//*[@id=&quot;onetrust-reject-all- handler&quot;]') ignore_cookies.click() except AttributeError: pass def next_page(self): driver.find_element(by=By.NAME, value=&quot;pagination-button-next&quot;).click() </code></pre> <p>The ignore cookie function works fine. But next_page function scrolls to the next button but does not click it.</p>
[ { "answer_id": 74525183, "author": "Barry the Platipus", "author_id": 19475185, "author_profile": "https://Stackoverflow.com/users/19475185", "pm_score": 1, "selected": false, "text": "from selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nimport time as t\n next_page wait = WebDriverWait(driver, 25)\n\nnext_page_button = wait.until(EC.element_to_be_clickable((By.XPATH, '//a[@name=\"pagination-button-next\"]')))\nnext_page_button.location_once_scrolled_into_view\nt.sleep(2)\nnext_page_button.click()\n" }, { "answer_id": 74529234, "author": "MITHU", "author_id": 7180194, "author_profile": "https://Stackoverflow.com/users/7180194", "pm_score": 0, "selected": false, "text": "from selenium.webdriver import Chrome\nfrom selenium.webdriver.common.by import By\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\nurl = \"https://uk.trustpilot.com/categories/bars_cafes?subcategories=cafe\"\n\nclass Scraper:\n def __init__(self, website):\n self.driver = Chrome(ChromeDriverManager().install())\n self.driver.get(website)\n self.wait = WebDriverWait(self.driver,20)\n\n\n def ignore_cookie(self):\n self.driver.find_element(By.CSS_SELECTOR, \"button[class^='onetrust-close-btn-handler']\").click()\n\n\n def fetch_content(self):\n while True:\n for item in self.driver.find_elements(By.CSS_SELECTOR, \"section > [class*='card_card']\"):\n shop_name = item.find_element(By.CSS_SELECTOR, \"a[name='business-unit-card'] p[class*='displayName']\").text\n yield shop_name\n\n try:\n self.next_page()\n self.wait.until(EC.staleness_of(item))\n except Exception as err:\n self.driver.quit()\n return\n\n\n def next_page(self):\n next_page = self.driver.find_element(By.CSS_SELECTOR, \"a[name='pagination-button-next']\")\n self.driver.execute_script(\"arguments[0].click();\", next_page)\n\n\nscrape = Scraper(url)\nscrape.ignore_cookie()\nfor title in scrape.fetch_content():\n print(title)\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18483849/" ]
74,524,351
<p>Hello I'm using the code below which is from: <a href="https://mui.com/material-ui/react-autocomplete/#country-select" rel="nofollow noreferrer">https://mui.com/material-ui/react-autocomplete/#country-select</a> to create my countries select dropdown however I can not figure out how to get a default value of the Unite States selected so that when it loads it now longer says select a country but selects the us as the default value. Thank you!</p> <pre><code>import * as React from &quot;react&quot;; import Box from &quot;@mui/material/Box&quot;; import TextField from &quot;@mui/material/TextField&quot;; import Autocomplete from &quot;@mui/material/Autocomplete&quot;; import InputAdornment from &quot;@mui/material/InputAdornment&quot;; export default function CountrySelect() { const [value, setValue] = React.useState(null); const [open, setOpen] = React.useState(false); return ( &lt;Autocomplete id=&quot;country-select-demo&quot; value={value} onChange={(event, newValue) =&gt; { setValue(newValue); }} sx={{ }} options={countries} autoHighlight defaultValue={{ code: 'US', label: 'United States', phone: '1', suggested: true, }} open={open} onOpen={() =&gt; setOpen(true)} onClose={() =&gt; setOpen(false)} getOptionLabel={(option) =&gt; option.label} renderOption={(props, option) =&gt; ( &lt;Box component=&quot;li&quot; sx={{ &quot;&amp; &gt; img&quot;: { mr: 2, flexShrink: 0 } }} {...props} &gt; &lt;img loading=&quot;lazy&quot; width=&quot;20&quot; src={`https://flagcdn.com/w20/${option.code.toLowerCase()}.png`} srcSet={`https://flagcdn.com/w40/${option.code.toLowerCase()}.png 2x`} alt=&quot;&quot; /&gt; {option.label} ({option.code}) +{option.phone} &lt;/Box&gt; )} renderInput={(params) =&gt; ( &lt;TextField {...params} label=&quot;Choose a country&quot; inputProps={{ ...params.inputProps, autoComplete: &quot;new-password&quot; // disable autocomplete and autofill }} InputProps={{ ...params.InputProps, startAdornment: value ? ( &lt;InputAdornment position=&quot;start&quot; onClick={() =&gt; setOpen(true)}&gt; &lt;img loading=&quot;lazy&quot; width=&quot;20&quot; src={`https://flagcdn.com/w20/${value.code.toLowerCase()}.png`} srcSet={`https://flagcdn.com/w40/${value.code.toLowerCase()}.png 2x`} alt=&quot;&quot; /&gt; &lt;/InputAdornment&gt; ) : null }} /&gt; )} /&gt; ); } // From https://bitbucket.org/atlassian/atlaskit-mk-2/raw/4ad0e56649c3e6c973e226b7efaeb28cb240ccb0/packages/core/select/src/data/countries.js const countries = [ { code: &quot;AD&quot;, label: &quot;Andorra&quot;, phone: &quot;376&quot; }, { code: &quot;AE&quot;, label: &quot;United Arab Emirates&quot;, phone: &quot;971&quot; }, { code: &quot;AF&quot;, label: &quot;Afghanistan&quot;, phone: &quot;93&quot; }, { code: &quot;AG&quot;, label: &quot;Antigua and Barbuda&quot;, phone: &quot;1-268&quot; }, { code: &quot;AI&quot;, label: &quot;Anguilla&quot;, phone: &quot;1-264&quot; }, { code: &quot;AL&quot;, label: &quot;Albania&quot;, phone: &quot;355&quot; }, { code: &quot;AM&quot;, label: &quot;Armenia&quot;, phone: &quot;374&quot; }, { code: &quot;AO&quot;, label: &quot;Angola&quot;, phone: &quot;244&quot; }, { code: &quot;AQ&quot;, label: &quot;Antarctica&quot;, phone: &quot;672&quot; }, { code: &quot;AR&quot;, label: &quot;Argentina&quot;, phone: &quot;54&quot; }, { code: &quot;AS&quot;, label: &quot;American Samoa&quot;, phone: &quot;1-684&quot; }, { code: &quot;AT&quot;, label: &quot;Austria&quot;, phone: &quot;43&quot; }, { code: &quot;AU&quot;, label: &quot;Australia&quot;, phone: &quot;61&quot;, suggested: true }, { code: &quot;AW&quot;, label: &quot;Aruba&quot;, phone: &quot;297&quot; }, { code: &quot;AX&quot;, label: &quot;Alland Islands&quot;, phone: &quot;358&quot; }, { code: &quot;AZ&quot;, label: &quot;Azerbaijan&quot;, phone: &quot;994&quot; }, { code: &quot;BA&quot;, label: &quot;Bosnia and Herzegovina&quot;, phone: &quot;387&quot; }, { code: &quot;BB&quot;, label: &quot;Barbados&quot;, phone: &quot;1-246&quot; }, { code: &quot;BD&quot;, label: &quot;Bangladesh&quot;, phone: &quot;880&quot; }, { code: &quot;BE&quot;, label: &quot;Belgium&quot;, phone: &quot;32&quot; }, { code: &quot;BF&quot;, label: &quot;Burkina Faso&quot;, phone: &quot;226&quot; }, { code: &quot;BG&quot;, label: &quot;Bulgaria&quot;, phone: &quot;359&quot; }, { code: &quot;BH&quot;, label: &quot;Bahrain&quot;, phone: &quot;973&quot; }, { code: &quot;BI&quot;, label: &quot;Burundi&quot;, phone: &quot;257&quot; }, { code: &quot;BJ&quot;, label: &quot;Benin&quot;, phone: &quot;229&quot; }, { code: &quot;BL&quot;, label: &quot;Saint Barthelemy&quot;, phone: &quot;590&quot; }, { code: &quot;BM&quot;, label: &quot;Bermuda&quot;, phone: &quot;1-441&quot; }, { code: &quot;BN&quot;, label: &quot;Brunei Darussalam&quot;, phone: &quot;673&quot; }, { code: &quot;BO&quot;, label: &quot;Bolivia&quot;, phone: &quot;591&quot; }, { code: &quot;BR&quot;, label: &quot;Brazil&quot;, phone: &quot;55&quot; }, { code: &quot;BS&quot;, label: &quot;Bahamas&quot;, phone: &quot;1-242&quot; }, { code: &quot;BT&quot;, label: &quot;Bhutan&quot;, phone: &quot;975&quot; }, { code: &quot;BV&quot;, label: &quot;Bouvet Island&quot;, phone: &quot;47&quot; }, { code: &quot;BW&quot;, label: &quot;Botswana&quot;, phone: &quot;267&quot; }, { code: &quot;BY&quot;, label: &quot;Belarus&quot;, phone: &quot;375&quot; }, { code: &quot;BZ&quot;, label: &quot;Belize&quot;, phone: &quot;501&quot; }, { code: &quot;CA&quot;, label: &quot;Canada&quot;, phone: &quot;1&quot;, suggested: true }, { code: &quot;CC&quot;, label: &quot;Cocos (Keeling) Islands&quot;, phone: &quot;61&quot; }, { code: &quot;CD&quot;, label: &quot;Congo, Democratic Republic of the&quot;, phone: &quot;243&quot; }, { code: &quot;CF&quot;, label: &quot;Central African Republic&quot;, phone: &quot;236&quot; }, { code: &quot;CG&quot;, label: &quot;Congo, Republic of the&quot;, phone: &quot;242&quot; }, { code: &quot;CH&quot;, label: &quot;Switzerland&quot;, phone: &quot;41&quot; }, { code: &quot;CI&quot;, label: &quot;Cote d'Ivoire&quot;, phone: &quot;225&quot; }, { code: &quot;CK&quot;, label: &quot;Cook Islands&quot;, phone: &quot;682&quot; }, { code: &quot;CL&quot;, label: &quot;Chile&quot;, phone: &quot;56&quot; }, { code: &quot;CM&quot;, label: &quot;Cameroon&quot;, phone: &quot;237&quot; }, { code: &quot;CN&quot;, label: &quot;China&quot;, phone: &quot;86&quot; }, { code: &quot;CO&quot;, label: &quot;Colombia&quot;, phone: &quot;57&quot; }, { code: &quot;CR&quot;, label: &quot;Costa Rica&quot;, phone: &quot;506&quot; }, { code: &quot;CU&quot;, label: &quot;Cuba&quot;, phone: &quot;53&quot; }, { code: &quot;CV&quot;, label: &quot;Cape Verde&quot;, phone: &quot;238&quot; }, { code: &quot;CW&quot;, label: &quot;Curacao&quot;, phone: &quot;599&quot; }, { code: &quot;CX&quot;, label: &quot;Christmas Island&quot;, phone: &quot;61&quot; }, { code: &quot;CY&quot;, label: &quot;Cyprus&quot;, phone: &quot;357&quot; }, { code: &quot;CZ&quot;, label: &quot;Czech Republic&quot;, phone: &quot;420&quot; }, { code: &quot;DE&quot;, label: &quot;Germany&quot;, phone: &quot;49&quot;, suggested: true }, { code: &quot;DJ&quot;, label: &quot;Djibouti&quot;, phone: &quot;253&quot; }, { code: &quot;DK&quot;, label: &quot;Denmark&quot;, phone: &quot;45&quot; }, { code: &quot;DM&quot;, label: &quot;Dominica&quot;, phone: &quot;1-767&quot; }, { code: &quot;DO&quot;, label: &quot;Dominican Republic&quot;, phone: &quot;1-809&quot; }, { code: &quot;DZ&quot;, label: &quot;Algeria&quot;, phone: &quot;213&quot; }, { code: &quot;EC&quot;, label: &quot;Ecuador&quot;, phone: &quot;593&quot; }, { code: &quot;EE&quot;, label: &quot;Estonia&quot;, phone: &quot;372&quot; }, { code: &quot;EG&quot;, label: &quot;Egypt&quot;, phone: &quot;20&quot; }, { code: &quot;EH&quot;, label: &quot;Western Sahara&quot;, phone: &quot;212&quot; }, { code: &quot;ER&quot;, label: &quot;Eritrea&quot;, phone: &quot;291&quot; }, { code: &quot;ES&quot;, label: &quot;Spain&quot;, phone: &quot;34&quot; }, { code: &quot;ET&quot;, label: &quot;Ethiopia&quot;, phone: &quot;251&quot; }, { code: &quot;FI&quot;, label: &quot;Finland&quot;, phone: &quot;358&quot; }, { code: &quot;FJ&quot;, label: &quot;Fiji&quot;, phone: &quot;679&quot; }, { code: &quot;FK&quot;, label: &quot;Falkland Islands (Malvinas)&quot;, phone: &quot;500&quot; }, { code: &quot;FM&quot;, label: &quot;Micronesia, Federated States of&quot;, phone: &quot;691&quot; }, { code: &quot;FO&quot;, label: &quot;Faroe Islands&quot;, phone: &quot;298&quot; }, { code: &quot;FR&quot;, label: &quot;France&quot;, phone: &quot;33&quot;, suggested: true }, { code: &quot;GA&quot;, label: &quot;Gabon&quot;, phone: &quot;241&quot; }, { code: &quot;GB&quot;, label: &quot;United Kingdom&quot;, phone: &quot;44&quot; }, { code: &quot;GD&quot;, label: &quot;Grenada&quot;, phone: &quot;1-473&quot; }, { code: &quot;GE&quot;, label: &quot;Georgia&quot;, phone: &quot;995&quot; }, { code: &quot;GF&quot;, label: &quot;French Guiana&quot;, phone: &quot;594&quot; }, { code: &quot;GG&quot;, label: &quot;Guernsey&quot;, phone: &quot;44&quot; }, { code: &quot;GH&quot;, label: &quot;Ghana&quot;, phone: &quot;233&quot; }, { code: &quot;GI&quot;, label: &quot;Gibraltar&quot;, phone: &quot;350&quot; }, { code: &quot;GL&quot;, label: &quot;Greenland&quot;, phone: &quot;299&quot; }, { code: &quot;GM&quot;, label: &quot;Gambia&quot;, phone: &quot;220&quot; }, { code: &quot;GN&quot;, label: &quot;Guinea&quot;, phone: &quot;224&quot; }, { code: &quot;GP&quot;, label: &quot;Guadeloupe&quot;, phone: &quot;590&quot; }, { code: &quot;GQ&quot;, label: &quot;Equatorial Guinea&quot;, phone: &quot;240&quot; }, { code: &quot;GR&quot;, label: &quot;Greece&quot;, phone: &quot;30&quot; }, { code: &quot;GS&quot;, label: &quot;South Georgia and the South Sandwich Islands&quot;, phone: &quot;500&quot; }, { code: &quot;GT&quot;, label: &quot;Guatemala&quot;, phone: &quot;502&quot; }, { code: &quot;GU&quot;, label: &quot;Guam&quot;, phone: &quot;1-671&quot; }, { code: &quot;GW&quot;, label: &quot;Guinea-Bissau&quot;, phone: &quot;245&quot; }, { code: &quot;GY&quot;, label: &quot;Guyana&quot;, phone: &quot;592&quot; }, { code: &quot;HK&quot;, label: &quot;Hong Kong&quot;, phone: &quot;852&quot; }, { code: &quot;HM&quot;, label: &quot;Heard Island and McDonald Islands&quot;, phone: &quot;672&quot; }, { code: &quot;HN&quot;, label: &quot;Honduras&quot;, phone: &quot;504&quot; }, { code: &quot;HR&quot;, label: &quot;Croatia&quot;, phone: &quot;385&quot; }, { code: &quot;HT&quot;, label: &quot;Haiti&quot;, phone: &quot;509&quot; }, { code: &quot;HU&quot;, label: &quot;Hungary&quot;, phone: &quot;36&quot; }, { code: &quot;ID&quot;, label: &quot;Indonesia&quot;, phone: &quot;62&quot; }, { code: &quot;IE&quot;, label: &quot;Ireland&quot;, phone: &quot;353&quot; }, { code: &quot;IL&quot;, label: &quot;Israel&quot;, phone: &quot;972&quot; }, { code: &quot;IM&quot;, label: &quot;Isle of Man&quot;, phone: &quot;44&quot; }, { code: &quot;IN&quot;, label: &quot;India&quot;, phone: &quot;91&quot; }, { code: &quot;IO&quot;, label: &quot;British Indian Ocean Territory&quot;, phone: &quot;246&quot; }, { code: &quot;IQ&quot;, label: &quot;Iraq&quot;, phone: &quot;964&quot; }, { code: &quot;IR&quot;, label: &quot;Iran, Islamic Republic of&quot;, phone: &quot;98&quot; }, { code: &quot;IS&quot;, label: &quot;Iceland&quot;, phone: &quot;354&quot; }, { code: &quot;IT&quot;, label: &quot;Italy&quot;, phone: &quot;39&quot; }, { code: &quot;JE&quot;, label: &quot;Jersey&quot;, phone: &quot;44&quot; }, { code: &quot;JM&quot;, label: &quot;Jamaica&quot;, phone: &quot;1-876&quot; }, { code: &quot;JO&quot;, label: &quot;Jordan&quot;, phone: &quot;962&quot; }, { code: &quot;JP&quot;, label: &quot;Japan&quot;, phone: &quot;81&quot;, suggested: true }, { code: &quot;KE&quot;, label: &quot;Kenya&quot;, phone: &quot;254&quot; }, { code: &quot;KG&quot;, label: &quot;Kyrgyzstan&quot;, phone: &quot;996&quot; }, { code: &quot;KH&quot;, label: &quot;Cambodia&quot;, phone: &quot;855&quot; }, { code: &quot;KI&quot;, label: &quot;Kiribati&quot;, phone: &quot;686&quot; }, { code: &quot;KM&quot;, label: &quot;Comoros&quot;, phone: &quot;269&quot; }, { code: &quot;KN&quot;, label: &quot;Saint Kitts and Nevis&quot;, phone: &quot;1-869&quot; }, { code: &quot;KP&quot;, label: &quot;Korea, Democratic People's Republic of&quot;, phone: &quot;850&quot; }, { code: &quot;KR&quot;, label: &quot;Korea, Republic of&quot;, phone: &quot;82&quot; }, { code: &quot;KW&quot;, label: &quot;Kuwait&quot;, phone: &quot;965&quot; }, { code: &quot;KY&quot;, label: &quot;Cayman Islands&quot;, phone: &quot;1-345&quot; }, { code: &quot;KZ&quot;, label: &quot;Kazakhstan&quot;, phone: &quot;7&quot; }, { code: &quot;LA&quot;, label: &quot;Lao People's Democratic Republic&quot;, phone: &quot;856&quot; }, { code: &quot;LB&quot;, label: &quot;Lebanon&quot;, phone: &quot;961&quot; }, { code: &quot;LC&quot;, label: &quot;Saint Lucia&quot;, phone: &quot;1-758&quot; }, { code: &quot;LI&quot;, label: &quot;Liechtenstein&quot;, phone: &quot;423&quot; }, { code: &quot;LK&quot;, label: &quot;Sri Lanka&quot;, phone: &quot;94&quot; }, { code: &quot;LR&quot;, label: &quot;Liberia&quot;, phone: &quot;231&quot; }, { code: &quot;LS&quot;, label: &quot;Lesotho&quot;, phone: &quot;266&quot; }, { code: &quot;LT&quot;, label: &quot;Lithuania&quot;, phone: &quot;370&quot; }, { code: &quot;LU&quot;, label: &quot;Luxembourg&quot;, phone: &quot;352&quot; }, { code: &quot;LV&quot;, label: &quot;Latvia&quot;, phone: &quot;371&quot; }, { code: &quot;LY&quot;, label: &quot;Libya&quot;, phone: &quot;218&quot; }, { code: &quot;MA&quot;, label: &quot;Morocco&quot;, phone: &quot;212&quot; }, { code: &quot;MC&quot;, label: &quot;Monaco&quot;, phone: &quot;377&quot; }, { code: &quot;MD&quot;, label: &quot;Moldova, Republic of&quot;, phone: &quot;373&quot; }, { code: &quot;ME&quot;, label: &quot;Montenegro&quot;, phone: &quot;382&quot; }, { code: &quot;MF&quot;, label: &quot;Saint Martin (French part)&quot;, phone: &quot;590&quot; }, { code: &quot;MG&quot;, label: &quot;Madagascar&quot;, phone: &quot;261&quot; }, { code: &quot;MH&quot;, label: &quot;Marshall Islands&quot;, phone: &quot;692&quot; }, { code: &quot;MK&quot;, label: &quot;Macedonia, the Former Yugoslav Republic of&quot;, phone: &quot;389&quot; }, { code: &quot;ML&quot;, label: &quot;Mali&quot;, phone: &quot;223&quot; }, { code: &quot;MM&quot;, label: &quot;Myanmar&quot;, phone: &quot;95&quot; }, { code: &quot;MN&quot;, label: &quot;Mongolia&quot;, phone: &quot;976&quot; }, { code: &quot;MO&quot;, label: &quot;Macao&quot;, phone: &quot;853&quot; }, { code: &quot;MP&quot;, label: &quot;Northern Mariana Islands&quot;, phone: &quot;1-670&quot; }, { code: &quot;MQ&quot;, label: &quot;Martinique&quot;, phone: &quot;596&quot; }, { code: &quot;MR&quot;, label: &quot;Mauritania&quot;, phone: &quot;222&quot; }, { code: &quot;MS&quot;, label: &quot;Montserrat&quot;, phone: &quot;1-664&quot; }, { code: &quot;MT&quot;, label: &quot;Malta&quot;, phone: &quot;356&quot; }, { code: &quot;MU&quot;, label: &quot;Mauritius&quot;, phone: &quot;230&quot; }, { code: &quot;MV&quot;, label: &quot;Maldives&quot;, phone: &quot;960&quot; }, { code: &quot;MW&quot;, label: &quot;Malawi&quot;, phone: &quot;265&quot; }, { code: &quot;MX&quot;, label: &quot;Mexico&quot;, phone: &quot;52&quot; }, { code: &quot;MY&quot;, label: &quot;Malaysia&quot;, phone: &quot;60&quot; }, { code: &quot;MZ&quot;, label: &quot;Mozambique&quot;, phone: &quot;258&quot; }, { code: &quot;NA&quot;, label: &quot;Namibia&quot;, phone: &quot;264&quot; }, { code: &quot;NC&quot;, label: &quot;New Caledonia&quot;, phone: &quot;687&quot; }, { code: &quot;NE&quot;, label: &quot;Niger&quot;, phone: &quot;227&quot; }, { code: &quot;NF&quot;, label: &quot;Norfolk Island&quot;, phone: &quot;672&quot; }, { code: &quot;NG&quot;, label: &quot;Nigeria&quot;, phone: &quot;234&quot; }, { code: &quot;NI&quot;, label: &quot;Nicaragua&quot;, phone: &quot;505&quot; }, { code: &quot;NL&quot;, label: &quot;Netherlands&quot;, phone: &quot;31&quot; }, { code: &quot;NO&quot;, label: &quot;Norway&quot;, phone: &quot;47&quot; }, { code: &quot;NP&quot;, label: &quot;Nepal&quot;, phone: &quot;977&quot; }, { code: &quot;NR&quot;, label: &quot;Nauru&quot;, phone: &quot;674&quot; }, { code: &quot;NU&quot;, label: &quot;Niue&quot;, phone: &quot;683&quot; }, { code: &quot;NZ&quot;, label: &quot;New Zealand&quot;, phone: &quot;64&quot; }, { code: &quot;OM&quot;, label: &quot;Oman&quot;, phone: &quot;968&quot; }, { code: &quot;PA&quot;, label: &quot;Panama&quot;, phone: &quot;507&quot; }, { code: &quot;PE&quot;, label: &quot;Peru&quot;, phone: &quot;51&quot; }, { code: &quot;PF&quot;, label: &quot;French Polynesia&quot;, phone: &quot;689&quot; }, { code: &quot;PG&quot;, label: &quot;Papua New Guinea&quot;, phone: &quot;675&quot; }, { code: &quot;PH&quot;, label: &quot;Philippines&quot;, phone: &quot;63&quot; }, { code: &quot;PK&quot;, label: &quot;Pakistan&quot;, phone: &quot;92&quot; }, { code: &quot;PL&quot;, label: &quot;Poland&quot;, phone: &quot;48&quot; }, { code: &quot;PM&quot;, label: &quot;Saint Pierre and Miquelon&quot;, phone: &quot;508&quot; }, { code: &quot;PN&quot;, label: &quot;Pitcairn&quot;, phone: &quot;870&quot; }, { code: &quot;PR&quot;, label: &quot;Puerto Rico&quot;, phone: &quot;1&quot; }, { code: &quot;PS&quot;, label: &quot;Palestine, State of&quot;, phone: &quot;970&quot; }, { code: &quot;PT&quot;, label: &quot;Portugal&quot;, phone: &quot;351&quot; }, { code: &quot;PW&quot;, label: &quot;Palau&quot;, phone: &quot;680&quot; }, { code: &quot;PY&quot;, label: &quot;Paraguay&quot;, phone: &quot;595&quot; }, { code: &quot;QA&quot;, label: &quot;Qatar&quot;, phone: &quot;974&quot; }, { code: &quot;RE&quot;, label: &quot;Reunion&quot;, phone: &quot;262&quot; }, { code: &quot;RO&quot;, label: &quot;Romania&quot;, phone: &quot;40&quot; }, { code: &quot;RS&quot;, label: &quot;Serbia&quot;, phone: &quot;381&quot; }, { code: &quot;RU&quot;, label: &quot;Russian Federation&quot;, phone: &quot;7&quot; }, { code: &quot;RW&quot;, label: &quot;Rwanda&quot;, phone: &quot;250&quot; }, { code: &quot;SA&quot;, label: &quot;Saudi Arabia&quot;, phone: &quot;966&quot; }, { code: &quot;SB&quot;, label: &quot;Solomon Islands&quot;, phone: &quot;677&quot; }, { code: &quot;SC&quot;, label: &quot;Seychelles&quot;, phone: &quot;248&quot; }, { code: &quot;SD&quot;, label: &quot;Sudan&quot;, phone: &quot;249&quot; }, { code: &quot;SE&quot;, label: &quot;Sweden&quot;, phone: &quot;46&quot; }, { code: &quot;SG&quot;, label: &quot;Singapore&quot;, phone: &quot;65&quot; }, { code: &quot;SH&quot;, label: &quot;Saint Helena&quot;, phone: &quot;290&quot; }, { code: &quot;SI&quot;, label: &quot;Slovenia&quot;, phone: &quot;386&quot; }, { code: &quot;SJ&quot;, label: &quot;Svalbard and Jan Mayen&quot;, phone: &quot;47&quot; }, { code: &quot;SK&quot;, label: &quot;Slovakia&quot;, phone: &quot;421&quot; }, { code: &quot;SL&quot;, label: &quot;Sierra Leone&quot;, phone: &quot;232&quot; }, { code: &quot;SM&quot;, label: &quot;San Marino&quot;, phone: &quot;378&quot; }, { code: &quot;SN&quot;, label: &quot;Senegal&quot;, phone: &quot;221&quot; }, { code: &quot;SO&quot;, label: &quot;Somalia&quot;, phone: &quot;252&quot; }, { code: &quot;SR&quot;, label: &quot;Suriname&quot;, phone: &quot;597&quot; }, { code: &quot;SS&quot;, label: &quot;South Sudan&quot;, phone: &quot;211&quot; }, { code: &quot;ST&quot;, label: &quot;Sao Tome and Principe&quot;, phone: &quot;239&quot; }, { code: &quot;SV&quot;, label: &quot;El Salvador&quot;, phone: &quot;503&quot; }, { code: &quot;SX&quot;, label: &quot;Sint Maarten (Dutch part)&quot;, phone: &quot;1-721&quot; }, { code: &quot;SY&quot;, label: &quot;Syrian Arab Republic&quot;, phone: &quot;963&quot; }, { code: &quot;SZ&quot;, label: &quot;Swaziland&quot;, phone: &quot;268&quot; }, { code: &quot;TC&quot;, label: &quot;Turks and Caicos Islands&quot;, phone: &quot;1-649&quot; }, { code: &quot;TD&quot;, label: &quot;Chad&quot;, phone: &quot;235&quot; }, { code: &quot;TF&quot;, label: &quot;French Southern Territories&quot;, phone: &quot;262&quot; }, { code: &quot;TG&quot;, label: &quot;Togo&quot;, phone: &quot;228&quot; }, { code: &quot;TH&quot;, label: &quot;Thailand&quot;, phone: &quot;66&quot; }, { code: &quot;TJ&quot;, label: &quot;Tajikistan&quot;, phone: &quot;992&quot; }, { code: &quot;TK&quot;, label: &quot;Tokelau&quot;, phone: &quot;690&quot; }, { code: &quot;TL&quot;, label: &quot;Timor-Leste&quot;, phone: &quot;670&quot; }, { code: &quot;TM&quot;, label: &quot;Turkmenistan&quot;, phone: &quot;993&quot; }, { code: &quot;TN&quot;, label: &quot;Tunisia&quot;, phone: &quot;216&quot; }, { code: &quot;TO&quot;, label: &quot;Tonga&quot;, phone: &quot;676&quot; }, { code: &quot;TR&quot;, label: &quot;Turkey&quot;, phone: &quot;90&quot; }, { code: &quot;TT&quot;, label: &quot;Trinidad and Tobago&quot;, phone: &quot;1-868&quot; }, { code: &quot;TV&quot;, label: &quot;Tuvalu&quot;, phone: &quot;688&quot; }, { code: &quot;TW&quot;, label: &quot;Taiwan, Province of China&quot;, phone: &quot;886&quot; }, { code: &quot;TZ&quot;, label: &quot;United Republic of Tanzania&quot;, phone: &quot;255&quot; }, { code: &quot;UA&quot;, label: &quot;Ukraine&quot;, phone: &quot;380&quot; }, { code: &quot;UG&quot;, label: &quot;Uganda&quot;, phone: &quot;256&quot; }, { code: &quot;US&quot;, label: &quot;United States&quot;, phone: &quot;1&quot;, suggested: true }, { code: &quot;UY&quot;, label: &quot;Uruguay&quot;, phone: &quot;598&quot; }, { code: &quot;UZ&quot;, label: &quot;Uzbekistan&quot;, phone: &quot;998&quot; }, { code: &quot;VA&quot;, label: &quot;Holy See (Vatican City State)&quot;, phone: &quot;379&quot; }, { code: &quot;VC&quot;, label: &quot;Saint Vincent and the Grenadines&quot;, phone: &quot;1-784&quot; }, { code: &quot;VE&quot;, label: &quot;Venezuela&quot;, phone: &quot;58&quot; }, { code: &quot;VG&quot;, label: &quot;British Virgin Islands&quot;, phone: &quot;1-284&quot; }, { code: &quot;VI&quot;, label: &quot;US Virgin Islands&quot;, phone: &quot;1-340&quot; }, { code: &quot;VN&quot;, label: &quot;Vietnam&quot;, phone: &quot;84&quot; }, { code: &quot;VU&quot;, label: &quot;Vanuatu&quot;, phone: &quot;678&quot; }, { code: &quot;WF&quot;, label: &quot;Wallis and Futuna&quot;, phone: &quot;681&quot; }, { code: &quot;WS&quot;, label: &quot;Samoa&quot;, phone: &quot;685&quot; }, { code: &quot;XK&quot;, label: &quot;Kosovo&quot;, phone: &quot;383&quot; }, { code: &quot;YE&quot;, label: &quot;Yemen&quot;, phone: &quot;967&quot; }, { code: &quot;YT&quot;, label: &quot;Mayotte&quot;, phone: &quot;262&quot; }, { code: &quot;ZA&quot;, label: &quot;South Africa&quot;, phone: &quot;27&quot; }, { code: &quot;ZM&quot;, label: &quot;Zambia&quot;, phone: &quot;260&quot; }, { code: &quot;ZW&quot;, label: &quot;Zimbabwe&quot;, phone: &quot;263&quot; } ]; </code></pre>
[ { "answer_id": 74524426, "author": "Blundering Philosopher", "author_id": 2430414, "author_profile": "https://Stackoverflow.com/users/2430414", "pm_score": 1, "selected": false, "text": "Autocomplete defaultValue <Autocomplete\n id=\"country-select-demo\"\n options={countries}\n defaultValue={{\n code: 'AE',\n label: 'United Arab Emirates',\n phone: '971',\n }}\n ...{otherProps}\n/>\n demo.tsx" }, { "answer_id": 74524643, "author": "Jawad Fadel", "author_id": 12626795, "author_profile": "https://Stackoverflow.com/users/12626795", "pm_score": 3, "selected": true, "text": " <Autocomplete\n id=\"country-select-demo\"\n **remove this ---->** value={value}\n **remove this ---->** onChange={(event, newValue) => {\n setValue(newValue);\n }}\n sx={{ }}\n options={countries}\n autoHighlight\n defaultValue={{\n code: 'US',\n label: 'United States',\n phone: '1',\n suggested: true,\n }}\n open={open}\n onOpen={() => setOpen(true)}\n onClose={() => setOpen(false)}\n getOptionLabel={(option) => option.label}\n....\n/>\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3827252/" ]
74,524,362
<p>Hello I am trying to create a new instance of a class via reflection:</p> <p>In the example below the following applies:</p> <ol> <li>This is a method in a subclass of Arg1</li> <li>Data is an object which stores class references which are associated with each other</li> </ol> <pre><code> public &lt;T extends Arg2, S extends Arg1&gt; Foo getFoo(@NotNull Data&lt;T, S&gt; data) { Class&lt;?&gt;[] classes = new Class&lt;?&gt;[]{data.getArg1(), data.getArg2()}; T entity = getArg2(data); try { Class&lt;? extends Foo&gt; clazz = data.getFoo(); Constructor&lt;? extends Foo&gt; constructor = clazz.getDeclaredConstructor(classes); constructor.setAccessible(true); Object[] objects = new Object[]{this, entity}; return constructor.newInstance(objects); } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException | ClassNotFoundException e) { throw new RuntimeException(e); } } </code></pre> <p>This code works when the provided arguments are from the same class loader, yet the code fails when the arguments are from different class loaders. As such, multiple Class Loaders as arguments causes the failure of the method.</p> <p>Is there any way I can get Java to accept my Arguments from multiple class loaders?</p> <p>Edit: The reason I have multiple class loaders is due to the fact that I load external jar files which were compiled against this applications API into the application using a custom <code>URLClassLoader</code>.</p> <p>As to the minimal reproducible example, I cannot at this time provide an example as this is private code which I do not own. The owner of the code would have to give me express permission to upload such an extensive chunk of the code (It's a bunch of classes that are essentially the cornerstone to the entire application). I can and will run any and all suggestions though and will forward this post to the owner for their approval.</p> <p>Any help is much appreciated :)</p> <p>Edit 2:</p> <p>Here the code with debug messages:</p> <pre><code> public &lt;T extends Arg2, S extends Arg1&gt; Foo getFoo(@NotNull Data&lt;T, S&gt; data) { Class&lt;?&gt;[] classes = new Class&lt;?&gt;[]{data.getArg1(), data.getArg2()}; T entity = getArg2(data); try { Class&lt;? extends Foo&gt; clazz = data.getFoo(); System.out.println(clazz.getClassLoader()); Constructor&lt;? extends Foo&gt; constructor = clazz.getDeclaredConstructor(classes); constructor.setAccessible(true); System.out.println(this.getClass().getClassLoader()); System.out.println(entity.getClassLoader()); Object[] objects = new Object[]{this, entity}; return constructor.newInstance(objects); } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException | ClassNotFoundException e) { throw new RuntimeException(e); } } </code></pre> <p>Given that Arg1, Arg2 and Foo are Classes which are part of the base application, the output is as follows:</p> <pre><code>jdk.internal.loader.ClassLoaders$AppClassLoader@1d44bcfa jdk.internal.loader.ClassLoaders$AppClassLoader@1d44bcfa jdk.internal.loader.ClassLoaders$AppClassLoader@1d44bcfa </code></pre> <p>Given that Arg1 and Foo are Classes which are from the same external Jar File and Arg2 remains a class that is part of the base application:</p> <pre><code>Class Loader for a single jar file Joined Class Loader for all jar files jdk.internal.loader.ClassLoaders$AppClassLoader@1d44bcfa java.lang.IllegalArgumentException: argument type mismatch at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:na] at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:77) ~[na:na] at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:na] at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499) ~[na:na] at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480) ~[na:na] </code></pre> <p>Note: These are the only two use cases</p>
[ { "answer_id": 74642297, "author": "Mr.Typo", "author_id": 14790684, "author_profile": "https://Stackoverflow.com/users/14790684", "pm_score": 2, "selected": true, "text": "ClassLoaders Foo app ClassLoader Foo ClassLoader import com.google.gson.Gson;\n\nimport java.io.ByteArrayOutputStream;\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\n\npublic class Test {\n\n public static void main(String[] args) throws Exception {\n var customClassLoader = new CustomClassLoader();\n \n ////////////////////// normal reflection //////////////////////\n Test.class.getMethod(\"foo\", Foo.class).invoke(null, new Foo()); // equivalent to foo(new Foo);\n \n ////////////////////// instantiating a new Foo obj from a custom class loader //////////////////////\n var foo = customClassLoader.findClass(Foo.class.getName()).getDeclaredConstructor().newInstance();\n \n try {\n ////////////////////// calling foo by passing a Foo obj from different ClassLoader //////////////////////\n Test.class.getMethod(\"foo\", Foo.class).invoke(null, foo); // yields java.lang.IllegalArgumentException: argument type mismatch!\n } catch (IllegalArgumentException e) {\n System.err.println(e);\n }\n \n ////////////////////// workaround, using gson to serialize the obj //////////////////////\n var gson = new Gson();\n Foo serializedFoo = gson.fromJson(gson.toJson(foo), Foo.class);\n Test.class.getMethod(\"foo\", Foo.class).invoke(null, serializedFoo); // no exception\n }\n\n public static void foo(Foo foo) {\n System.out.println(\"Test#foo: \" + foo.getClass().getClassLoader().getName());\n }\n\n public static class Foo {\n }\n\n public static class CustomClassLoader extends ClassLoader {\n\n public CustomClassLoader() {\n super(\"custom\", getSystemClassLoader());\n }\n\n @Override\n public Class<?> findClass(String name) throws ClassFormatError {\n InputStream inputStream = getClass().getClassLoader().getResourceAsStream(name.replace('.', File.separatorChar) + \".class\");\n ByteArrayOutputStream byteStream = new ByteArrayOutputStream();\n int nextValue;\n try {\n while ((nextValue = inputStream.read()) != -1) byteStream.write(nextValue);\n inputStream.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n var data = byteStream.toByteArray();\n return defineClass(name, data, 0, data.length);\n }\n }\n\n}\n import java.io.ByteArrayOutputStream;\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\n\npublic class Test {\n\n public static void main(String[] args) throws Exception {\n var customClassLoader = new CustomClassLoader();\n\n Test.class.getMethod(\"foo\", Object.class).invoke(null, new Foo());\n var foo = customClassLoader.findClass(Foo.class.getName()).getDeclaredConstructor().newInstance();\n\n Test.class.getMethod(\"foo\", Object.class).invoke(null, foo);\n }\n\n public static void foo(Object foo) throws Exception {\n if (foo.getClass().getClassLoader() instanceof CustomClassLoader) {\n foo.getClass().getMethod(\"sayFoo\").invoke(foo);\n } else {\n ((Foo) foo).sayFoo();\n }\n }\n\n public static class Foo {\n public void sayFoo() {\n System.out.println(\"Foo\");\n }\n }\n\n public static class CustomClassLoader extends ClassLoader {\n\n public CustomClassLoader() {\n super(\"custom\", getSystemClassLoader());\n }\n\n @Override\n public Class<?> findClass(String name) throws ClassFormatError {\n InputStream inputStream = getClass().getClassLoader().getResourceAsStream(name.replace('.', File.separatorChar) + \".class\");\n ByteArrayOutputStream byteStream = new ByteArrayOutputStream();\n int nextValue;\n try {\n while ((nextValue = inputStream.read()) != -1) byteStream.write(nextValue);\n inputStream.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n var data = byteStream.toByteArray();\n return defineClass(name, data, 0, data.length);\n }\n }\n\n}\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14774086/" ]
74,524,363
<p>im making a python script that can manage my google projects. im having a insue with one part when i try to exclude the project its can return to me many errors.</p> <p>i did a peace of code to get this exception:</p> <pre><code> try: # Initialize request argument(s) request = DeleteProjectRequest( name=project, ) self.project_manager.delete_project(request=request) except PermissionDenied as exc: # GCP returns PermissionDenied whether we actually does # not have permissions to perform the get_project call # or when the project does not exist. Due to this reason, # the PermissionDenied exception catch won't be deterministic. logger.error(f&quot;Project '{project_id}' does not exist&quot;, exc) return False </code></pre> <p>i need to get the error message of all types of errors i changed <code>except PermissionDenied as exc:</code> for <code>except Exception as exc:</code> and it works but i need to call the logger only if the error is <code>PermissionDenied</code> and in all cases i need to call another function passing the message as parameter like it <code>return_to_db(error_message)</code></p> <p>my question is. how can i run only the logger if the error is <code>PermissionDenied</code>?</p>
[ { "answer_id": 74524567, "author": "Mazlum Tosun", "author_id": 9261558, "author_profile": "https://Stackoverflow.com/users/9261558", "pm_score": 3, "selected": true, "text": "Python try:\n # Initialize request argument(s)\n\n request = DeleteProjectRequest(\n name=project,\n )\n self.project_manager.delete_project(request=request)\n\n except Exception as exc:\n if isinstance(exc, PermissionDenied):\n logger.error(f\"Project '{project_id}' does not exist\", exc)\n \n return False\n logger PermissionDenied" }, { "answer_id": 74525457, "author": "ti7", "author_id": 4541045, "author_profile": "https://Stackoverflow.com/users/4541045", "pm_score": 2, "selected": false, "text": "isinstance() Exception TypeError try:\n self.project_manager.delete_project(\n request=DeleteProjectRequest(name=project))\nexcept PermissionDenied as exc:\n # GCP returns PermissionDenied whether we actually does\n # not have permissions to perform the get_project call\n # or when the project does not exist. Due to this reason,\n # the PermissionDenied exception catch won't be deterministic.\n logger.error(f\"Project '{project_id}' does not exist\", exc)\nexcept Exception:\n # FIXME other handling to go here\n pass # fall to return False\nelse: # didn't raise\n return True\n# opportunity for finally: block here too\n\n# if any Exception was raised, continue to return False\nreturn False\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10413299/" ]
74,524,377
<p>What would the time complexity be for the below recursive function?</p> <p>I am using the the below T(n) but not sure if I created the correct equation for this function</p> <p>T(n)=T(n-1)+n -&gt; o(n^2)</p> <pre><code>public static int test2(int n){ if(n&lt;=0){ return 0; } for(int i =0; i&lt;=n; i++){ for(int j =0; j&lt;=n; j++){ System.out.println(&quot; in here &quot; + i + j); } test2(n-1); } return 1; } </code></pre>
[ { "answer_id": 74524724, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 0, "selected": false, "text": "O(n^2) test(n) n + 1 n = 2 t(2)\n / | \\\n / | \\\n t(1) t(1) t(1)\n / \\ / \\ / \\\n t(0) t(0) t(0) t(0) t(0) t(0) \n test(2) 9 test(3) 40 (n) * (n + 1 - 1) * (n + 1 - 2) * (n + 1 - 3) * ... until `n` doesn't turn to 1\n +1 n! O(n^2) O(n^2 * n!)\n" }, { "answer_id": 74524846, "author": "RunTimeError31415", "author_id": 19961014, "author_profile": "https://Stackoverflow.com/users/19961014", "pm_score": 0, "selected": false, "text": "T(n) = n * (T (n-1) + n)\n T(n) = n * T(n-1) + n^2\nT(n-1) = (n-1) * T(n-2) + (n-1)^2\nT(n-2) = (n-2) * T(n-3) + (n-2)^2\n.\n.\n.\nT(2) = 2 * T(1) + 2^2\nT(1) = 1 * T(0) + 1^2\n T (n) = n^2 + n*((n-1)^2) + n*(n-1)*((n-2)^2) + ... + n*(n-1)*(n-2)*(n-3)*...*(n-(n-3))*(2^2) + (2 * n!) \n" }, { "answer_id": 74525184, "author": "Yves Daoust", "author_id": 1196549, "author_profile": "https://Stackoverflow.com/users/1196549", "pm_score": 0, "selected": false, "text": "T(0) = C0\nT(n) =\n Σ{i=0..n}\n Σ{j=0..n}\n C1\n +\n T(n-1)\n + C2\n T(n) = (n+1).((n+1).C1 + T(n-1)) + C2 = (n+1).T(n-1) + (n+1)².C1 + C2\n C.(n+1)! T(n) = (n+1)!.U(n)\n (n+1)!.U(n) = (n+1).n!.U(n-1) + C1.(n+1)² + C2\n U(n) = U(n-1) + C1/(n-2)! + 2C1/(n-1)! + C2/(n+1)!\n T(n) ~ C(n+1)! = O((n+1)!)\n" }, { "answer_id": 74525296, "author": "Marko Taht", "author_id": 3071712, "author_profile": "https://Stackoverflow.com/users/3071712", "pm_score": 0, "selected": false, "text": "T(0) = 1\nT(1) = 2 * (2 + T(0)) = 2 * (2 + 1) = 2 * 3 = 6\nT(2) = 3 * (3 + T(1)) = 3 * (3 + 6) = 2 * 9 = 27\nT(3) = 4 * (4 + T(2)) = 4 * (4 + 27) = 4 * 31 = 124\n T(1) = 2 * (2 + T(0))\nT(2) = 3 * (3 + 2 * (2 + T(0)))\nT(3) = 4 * (4 + T(2)) = 4 * (4 + 3 * (3 + 2 * (2 + T(0))))\n...\nT(n) = (n+1) * (n+1 + T(n)) = (n+1) * (n+1 + n * (n + T(n -1))) =\n(n+1) * (n+1 + n * (n + (n-1) * ((n-1) + T(n-2))))\n T(n) = (n+1)^2 + (n+1)n*(n + T(n-1)) = (n+1)^2 + (n+1)n^2 + (n+1)n(n-1)*((n-1) + T(n-1)) = ... \n= (n+1)^2 + (n+1)n^2 + ... + (n+1)n(n-1)...2^2 + (n+1)! = Sum[iProduct[j,{j,i,n}],{i,2,n}] + (n+1)! \n (n+1)! +1 o(n!) n+1 i<=n i < n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10869670/" ]
74,524,384
<p>It's quite simple: I have</p> <ul> <li>a datadog-dashbaord</li> <li>a <a href="https://docs.datadoghq.com/dashboards/template_variables/" rel="nofollow noreferrer">template-variable</a> named <code>env</code>, which can have following values <code>['prod', 'test']</code></li> </ul> <p><a href="https://i.stack.imgur.com/9XFHl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9XFHl.png" alt="enter image description here" /></a></p> <p>And I want to display metrics based on the <code>env</code>:</p> <ul> <li><code>from</code>-resource for <code>test</code> is <code>unified-importer-test-sqsimportdlq11419573-xl6dn7o5wqtj</code></li> <li><code>from</code>-resource for <code>prod</code> is <code>unified-importer-prod-sqsimportdlq11419573-prmohksrvxxg</code></li> </ul> <p>So naturally I'd use following syntax: <code>unified-importer-$env.value-sqsimportdlq*</code></p> <p>But this does not display anything, nor shows it any error.</p> <p>This, however, works as expected: <code>unified-importer-test-sqsimportdlq*</code> (or <code>unified-importer-prod-sqsimportdlq*</code> respectively).</p> <p>It looks like asterisk in combination with wildcards is not working.</p> <p>Additionally, DD seems to dislike using two asterisks (as prefix and suffix): <a href="https://i.stack.imgur.com/r0KfN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/r0KfN.png" alt="enter image description here" /></a></p> <p>How can I leverage the template-var <code>env</code> easily in this situation?</p>
[ { "answer_id": 74524724, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 0, "selected": false, "text": "O(n^2) test(n) n + 1 n = 2 t(2)\n / | \\\n / | \\\n t(1) t(1) t(1)\n / \\ / \\ / \\\n t(0) t(0) t(0) t(0) t(0) t(0) \n test(2) 9 test(3) 40 (n) * (n + 1 - 1) * (n + 1 - 2) * (n + 1 - 3) * ... until `n` doesn't turn to 1\n +1 n! O(n^2) O(n^2 * n!)\n" }, { "answer_id": 74524846, "author": "RunTimeError31415", "author_id": 19961014, "author_profile": "https://Stackoverflow.com/users/19961014", "pm_score": 0, "selected": false, "text": "T(n) = n * (T (n-1) + n)\n T(n) = n * T(n-1) + n^2\nT(n-1) = (n-1) * T(n-2) + (n-1)^2\nT(n-2) = (n-2) * T(n-3) + (n-2)^2\n.\n.\n.\nT(2) = 2 * T(1) + 2^2\nT(1) = 1 * T(0) + 1^2\n T (n) = n^2 + n*((n-1)^2) + n*(n-1)*((n-2)^2) + ... + n*(n-1)*(n-2)*(n-3)*...*(n-(n-3))*(2^2) + (2 * n!) \n" }, { "answer_id": 74525184, "author": "Yves Daoust", "author_id": 1196549, "author_profile": "https://Stackoverflow.com/users/1196549", "pm_score": 0, "selected": false, "text": "T(0) = C0\nT(n) =\n Σ{i=0..n}\n Σ{j=0..n}\n C1\n +\n T(n-1)\n + C2\n T(n) = (n+1).((n+1).C1 + T(n-1)) + C2 = (n+1).T(n-1) + (n+1)².C1 + C2\n C.(n+1)! T(n) = (n+1)!.U(n)\n (n+1)!.U(n) = (n+1).n!.U(n-1) + C1.(n+1)² + C2\n U(n) = U(n-1) + C1/(n-2)! + 2C1/(n-1)! + C2/(n+1)!\n T(n) ~ C(n+1)! = O((n+1)!)\n" }, { "answer_id": 74525296, "author": "Marko Taht", "author_id": 3071712, "author_profile": "https://Stackoverflow.com/users/3071712", "pm_score": 0, "selected": false, "text": "T(0) = 1\nT(1) = 2 * (2 + T(0)) = 2 * (2 + 1) = 2 * 3 = 6\nT(2) = 3 * (3 + T(1)) = 3 * (3 + 6) = 2 * 9 = 27\nT(3) = 4 * (4 + T(2)) = 4 * (4 + 27) = 4 * 31 = 124\n T(1) = 2 * (2 + T(0))\nT(2) = 3 * (3 + 2 * (2 + T(0)))\nT(3) = 4 * (4 + T(2)) = 4 * (4 + 3 * (3 + 2 * (2 + T(0))))\n...\nT(n) = (n+1) * (n+1 + T(n)) = (n+1) * (n+1 + n * (n + T(n -1))) =\n(n+1) * (n+1 + n * (n + (n-1) * ((n-1) + T(n-2))))\n T(n) = (n+1)^2 + (n+1)n*(n + T(n-1)) = (n+1)^2 + (n+1)n^2 + (n+1)n(n-1)*((n-1) + T(n-1)) = ... \n= (n+1)^2 + (n+1)n^2 + ... + (n+1)n(n-1)...2^2 + (n+1)! = Sum[iProduct[j,{j,i,n}],{i,2,n}] + (n+1)! \n (n+1)! +1 o(n!) n+1 i<=n i < n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/842302/" ]
74,524,386
<p>I have an array of Ids, I need to iterate through all the Ids, and for each Ids of the array make an async call to retrieve a value from DB, then sums all the value gathered. I did something like this</p> <pre><code> let quantity = 0; for (const id of [1,2,3,4]) { const subQuantity = await getSubQuantityById(id); quantity += subQuantity; } </code></pre> <p>Is there a more elegant and coincise way to write this for in javascript?</p>
[ { "answer_id": 74524496, "author": "Thomas Zimmermann", "author_id": 13527621, "author_profile": "https://Stackoverflow.com/users/13527621", "pm_score": 1, "selected": false, "text": "async forEach for let totalQuantity = 0;\nfor (const id of arrayOfIds) {\n totalQuantity += await getSubQuantityById(id);\n}\n += await (await Promise.all([1,2,3,4].map(i => getSubQuantityById(id))).reduce((p, c) => p + c, 0)\n" }, { "answer_id": 74527533, "author": "vitaly-t", "author_id": 1102051, "author_profile": "https://Stackoverflow.com/users/1102051", "pm_score": 0, "selected": false, "text": "import {pipeAsync, map, wait, reduce} from 'iter-ops';\n\nconst i = pipeAsync(\n [1, 2, 3, 4], // your list of id-s\n map(getSubQuantityById), // remap ids into async requests\n wait(), // resolve requests\n reduce((a, c) => a + c) // calculate the sum\n); //=> AsyncIterableExt<number>\n (async function () {\n console.log(await i.first); //=> the sum\n})();\n" }, { "answer_id": 74528368, "author": "Carsten Massmann", "author_id": 2610061, "author_profile": "https://Stackoverflow.com/users/2610061", "pm_score": 1, "selected": true, "text": "console.log .then() // a placeholder function for testing:\nfunction getSubQuantityById(i){\n return fetch(\"https://jsonplaceholder.typicode.com/users/\"+i).then(r=>r.json()).then(u=>+u.address.geo.lat);\n}\n\nPromise.all([1,2,3,4].map(id => getSubQuantityById(id)))\n .then(d=>d.reduce((p, c) => p + c,0))\n .then(console.log)" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18542993/" ]
74,524,389
<p>Let's say I have an example dataframe in the following format:</p> <pre><code>df &lt;- data.frame( c(1,2,3,1,2,3,1,2,3), c(3,3,3,2,2,2,1,1,1), c(23,23,34,134,134,NA,45,NA,NA) ) colnames(df) &lt;- c(&quot;id&quot;, &quot;year&quot;, &quot;fte_wage&quot;) df &lt;- df[is.na(df$fte_wage) == FALSE,] </code></pre> <p>I want to create a binary variable (let's say, a column named &quot;obs&quot;) if the individual was observed in the previous or not. I have tried the following:</p> <pre><code>library(dplyr) df2 &lt;- df %&gt;% arrange(id, year) %&gt;% group_by(id) %&gt;% rowwise() %&gt;% mutate(obs = ifelse((lag(year) %in% df[df$id == id,]$year &amp; year &gt; lag(year)), 1, 0)) </code></pre> <p>Which generates a column of only 0 values. If I remove the second condition the code works, but then it misinterprets the lag(year) command, as it takes values from different individuals as well.</p> <p>My desired output would be a dataframe in the following format:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>year</th> <th>fte_wage</th> <th>ob</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>1</td> <td>23</td> <td>0</td> </tr> <tr> <td>1</td> <td>2</td> <td>23</td> <td>1</td> </tr> <tr> <td>1</td> <td>3</td> <td>43</td> <td>1</td> </tr> <tr> <td>2</td> <td>1</td> <td>54</td> <td>0</td> </tr> <tr> <td>2</td> <td>2</td> <td>32</td> <td>1</td> </tr> <tr> <td>3</td> <td>1</td> <td>56</td> <td>0</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74524481, "author": "Dan Adams", "author_id": 13210554, "author_profile": "https://Stackoverflow.com/users/13210554", "pm_score": 2, "selected": true, "text": "group_by(id) row_number() > 1 library(tidyverse)\n\ndf <- data.frame(\"id\" = c(1,2,3,1,2,3,1,2,3),\n \"year\" = c(3,3,3,2,2,2,1,1,1),\n \"fte_wage\" = c(23,23,34,134,134,NA,45,NA,NA))\n\ndf %>% \n drop_na(fte_wage) %>% \n arrange(id, year) %>%\n group_by(id) %>% \n mutate(obs = as.numeric(row_number() > 1))\n#> # A tibble: 6 × 4\n#> # Groups: id [3]\n#> id year fte_wage obs\n#> <dbl> <dbl> <dbl> <dbl>\n#> 1 1 1 45 0\n#> 2 1 2 134 1\n#> 3 1 3 23 1\n#> 4 2 2 134 0\n#> 5 2 3 23 1\n#> 6 3 3 34 0\n" }, { "answer_id": 74524548, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 0, "selected": false, "text": "dplyr library(dplyr)\n\ndf %>% \n na.omit() %>% \n arrange(id, year) %>% \n mutate(obs = (lag(id, default=F) == id) * 1)\n id year fte_wage obs\n1 1 1 45 0\n2 1 2 134 1\n3 1 3 23 1\n4 2 2 134 0\n5 2 3 23 1\n6 3 3 34 0\n" }, { "answer_id": 74524549, "author": "arg0naut91", "author_id": 8389003, "author_profile": "https://Stackoverflow.com/users/8389003", "pm_score": 0, "selected": false, "text": "diff library(dplyr)\n\ndf %>%\n group_by(id) %>%\n arrange(id, year) %>%\n mutate(obs = +(c(0, diff(year)) == 1L))\n # A tibble: 6 x 4\n# Groups: id [3]\n id year fte_wage obs\n <dbl> <dbl> <dbl> <dbl>\n1 1 1 45 0\n2 1 2 134 1\n3 1 3 23 1\n4 2 2 134 0\n5 2 3 23 1\n6 3 3 34 0\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14232205/" ]
74,524,402
<p>I am trying to use Java to read a file, scan for Unicode as an escape sequence, convert to English readable, then write the replacement to the file. As an example I make a similar script. The normalizer works if the input is a string, but if I build the string through an array or from a stringBuilder the output is literally the string without any normalization. How can I use a stringBuilder to work with Java's normalizer?</p> <p>ex:</p> <pre><code> import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.text.Normalizer; import java.util.regex.Pattern; public class Main { public static void main(String[] args) { String broke = &quot;&quot;; String[] testArr = {&quot;\\&quot;,&quot;u&quot;,&quot;0&quot;,&quot;0&quot;,&quot;e&quot;,&quot;0&quot;}; for(int i = 0; i &lt; 6; i++) { broke+=testArr[i]; } String works = &quot;\u00e0&quot;; System.out.println(&quot;broke: &quot; + broke); System.out.println(&quot;works: &quot; + works); String temp = Normalizer.normalize(works, Normalizer.Form.NFD); System.out.println(&quot;temp:&quot; + temp); Pattern pattern = Pattern.compile(&quot;\\p{InCombiningDiacriticalMarks}+&quot;); String fixedUnicode = pattern.matcher(temp).replaceAll(&quot;&quot;); System.out.println(&quot;fixedUnicode: &quot; + fixedUnicode); } } </code></pre> <p>I notice Java automatically converts (String works = &quot;\u00e0&quot;;) in a syso to the appropriate unicode, but a string that also looks like &quot;\u00e0&quot; but build with a stringBuilder or an array shows (&quot;\u00e0&quot;) when using a syso</p>
[ { "answer_id": 74524481, "author": "Dan Adams", "author_id": 13210554, "author_profile": "https://Stackoverflow.com/users/13210554", "pm_score": 2, "selected": true, "text": "group_by(id) row_number() > 1 library(tidyverse)\n\ndf <- data.frame(\"id\" = c(1,2,3,1,2,3,1,2,3),\n \"year\" = c(3,3,3,2,2,2,1,1,1),\n \"fte_wage\" = c(23,23,34,134,134,NA,45,NA,NA))\n\ndf %>% \n drop_na(fte_wage) %>% \n arrange(id, year) %>%\n group_by(id) %>% \n mutate(obs = as.numeric(row_number() > 1))\n#> # A tibble: 6 × 4\n#> # Groups: id [3]\n#> id year fte_wage obs\n#> <dbl> <dbl> <dbl> <dbl>\n#> 1 1 1 45 0\n#> 2 1 2 134 1\n#> 3 1 3 23 1\n#> 4 2 2 134 0\n#> 5 2 3 23 1\n#> 6 3 3 34 0\n" }, { "answer_id": 74524548, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 0, "selected": false, "text": "dplyr library(dplyr)\n\ndf %>% \n na.omit() %>% \n arrange(id, year) %>% \n mutate(obs = (lag(id, default=F) == id) * 1)\n id year fte_wage obs\n1 1 1 45 0\n2 1 2 134 1\n3 1 3 23 1\n4 2 2 134 0\n5 2 3 23 1\n6 3 3 34 0\n" }, { "answer_id": 74524549, "author": "arg0naut91", "author_id": 8389003, "author_profile": "https://Stackoverflow.com/users/8389003", "pm_score": 0, "selected": false, "text": "diff library(dplyr)\n\ndf %>%\n group_by(id) %>%\n arrange(id, year) %>%\n mutate(obs = +(c(0, diff(year)) == 1L))\n # A tibble: 6 x 4\n# Groups: id [3]\n id year fte_wage obs\n <dbl> <dbl> <dbl> <dbl>\n1 1 1 45 0\n2 1 2 134 1\n3 1 3 23 1\n4 2 2 134 0\n5 2 3 23 1\n6 3 3 34 0\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19987639/" ]
74,524,413
<p>When using images in react, there is either a problem with typescript, or the image breaks on the site.</p> <p>To solve the problem, I tried:</p> <ol> <li>Add url-loader and file-loader to the webpack.config.js</li> </ol> <pre><code>const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const BUILD_PATH = path.resolve(__dirname, './build'); const SRC_PATH = path.resolve(__dirname, './src/'); const PUBLIC_PATH = path.resolve(__dirname, './public') module.exports = { entry: SRC_PATH + '/index.tsx', output: { path: BUILD_PATH, filename: 'bundle.js', }, mode: process.env.NODE_ENV || 'development', resolve: { modules: [path.resolve(__dirname, 'src'), 'node_modules'], extensions: [ '.tsx', '.ts', '.js' ], }, devServer: { static: PUBLIC_PATH, }, module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: ['babel-loader'] }, { test: /\.tsx?$/, exclude: /node_modules/, loader: 'ts-loader' }, { test: /\.(css|scss)$/, use: ['style-loader', 'css-loader', 'sass-loader'], }, { test: /\.module.css$/, use: [ { loader: &quot;css-loader&quot;, options: { modules: true, }, }, ], }, { test: /\.(jpg|png|svg)$/, loader: 'url-loader', options: { limit: 8192, }, }, { test: /\.(jpg|jpeg|png|gif|mp3|svg)$/, use: ['file-loader'] }, ], }, plugins: [ new HtmlWebpackPlugin({ template: path.join(__dirname, 'public', 'index.html'), }), ], }; </code></pre> <ol start="2"> <li>Import images as components</li> </ol> <pre><code>import React from 'react'; import logo from './header-logo.svg'; import styles from './Header.module.scss'; export const Header = () =&gt; { return &lt;header className={styles.header}&gt; &lt;img src={logo} /&gt; &lt;/header&gt; }; </code></pre> <ol start="3"> <li>Create the images.d.ts file in the src/types directory</li> </ol> <pre><code>declare module &quot;*.svg&quot; { const content: any; export default content; } </code></pre> <ol start="4"> <li>And I even tried svgr..</li> </ol> <p>But nothing helped. If I delete the images.d.ts file, typescript cannot detect the module when importing. When using images.d.ts, vscode does not show errors, but the picture is not displayed in the browser, and instead of the normal path, something strange data:image/svg+xml;base64,ZXhwb3J0IGRlZmF1bHQgX193ZWJwYWNrX3B1YmxpY19wYXRoX18gKyAiZWMzYzM1Nzg3YTljZTMyMzE4M2NmMzM2Y2EzMDBkOTkuc3ZnIjs=</p> <p>And just in case, I attach tsconfig.json</p> <pre><code>{ &quot;compilerOptions&quot;: { &quot;baseUrl&quot;: &quot;./&quot;, &quot;outDir&quot;: &quot;./build/&quot;, &quot;noImplicitAny&quot;: true, &quot;module&quot;: &quot;es6&quot;, &quot;target&quot;: &quot;es5&quot;, &quot;jsx&quot;: &quot;react&quot;, &quot;allowJs&quot;: true, &quot;allowSyntheticDefaultImports&quot;: true, &quot;moduleResolution&quot;: &quot;node&quot;, &quot;plugins&quot;: [ { &quot;name&quot;: &quot;typescript-plugin-css-modules&quot; }, ], }, } </code></pre> <p>I'm new to react so please don't judge strictly for stupid mistakes. I would appreciate any advice!</p>
[ { "answer_id": 74524481, "author": "Dan Adams", "author_id": 13210554, "author_profile": "https://Stackoverflow.com/users/13210554", "pm_score": 2, "selected": true, "text": "group_by(id) row_number() > 1 library(tidyverse)\n\ndf <- data.frame(\"id\" = c(1,2,3,1,2,3,1,2,3),\n \"year\" = c(3,3,3,2,2,2,1,1,1),\n \"fte_wage\" = c(23,23,34,134,134,NA,45,NA,NA))\n\ndf %>% \n drop_na(fte_wage) %>% \n arrange(id, year) %>%\n group_by(id) %>% \n mutate(obs = as.numeric(row_number() > 1))\n#> # A tibble: 6 × 4\n#> # Groups: id [3]\n#> id year fte_wage obs\n#> <dbl> <dbl> <dbl> <dbl>\n#> 1 1 1 45 0\n#> 2 1 2 134 1\n#> 3 1 3 23 1\n#> 4 2 2 134 0\n#> 5 2 3 23 1\n#> 6 3 3 34 0\n" }, { "answer_id": 74524548, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 0, "selected": false, "text": "dplyr library(dplyr)\n\ndf %>% \n na.omit() %>% \n arrange(id, year) %>% \n mutate(obs = (lag(id, default=F) == id) * 1)\n id year fte_wage obs\n1 1 1 45 0\n2 1 2 134 1\n3 1 3 23 1\n4 2 2 134 0\n5 2 3 23 1\n6 3 3 34 0\n" }, { "answer_id": 74524549, "author": "arg0naut91", "author_id": 8389003, "author_profile": "https://Stackoverflow.com/users/8389003", "pm_score": 0, "selected": false, "text": "diff library(dplyr)\n\ndf %>%\n group_by(id) %>%\n arrange(id, year) %>%\n mutate(obs = +(c(0, diff(year)) == 1L))\n # A tibble: 6 x 4\n# Groups: id [3]\n id year fte_wage obs\n <dbl> <dbl> <dbl> <dbl>\n1 1 1 45 0\n2 1 2 134 1\n3 1 3 23 1\n4 2 2 134 0\n5 2 3 23 1\n6 3 3 34 0\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20566211/" ]
74,524,425
<p>I want to change my image size with my style.css but it doesn't apply.</p> <p>Here is my style:</p> <pre><code> .headerImage { width: 100px; height: 100px; } </code></pre> <p>And here is how I'm trying to insert my image:</p> <pre><code>&lt;div class=&quot;headerImage&quot;&gt; &lt;img src=&quot;/images/header-image.png&quot; alt=&quot;your image&quot;&gt; &lt;/div&gt; </code></pre> <p>I tried this and it worked, but I want to have other images in different sizes. So this is not an option:</p> <pre><code>img { width: 100px; height: 100px; } </code></pre>
[ { "answer_id": 74524448, "author": "JellyTheTitan", "author_id": 20523676, "author_profile": "https://Stackoverflow.com/users/20523676", "pm_score": -1, "selected": false, "text": "<div> <div class=\"headerImage\">\n <img src=\"/images/header-image.png\" alt=\"your image\">\n</div>\n" }, { "answer_id": 74524523, "author": "TheDurbie", "author_id": 19612400, "author_profile": "https://Stackoverflow.com/users/19612400", "pm_score": 0, "selected": false, "text": "<div>\n <img class=\"headerImage\" src=\"/images/header-image.png\" alt=\"your image\">\n </div>\n" }, { "answer_id": 74524616, "author": "Inam", "author_id": 10731807, "author_profile": "https://Stackoverflow.com/users/10731807", "pm_score": 0, "selected": false, "text": ".headerImage img \n {\n width: 100px;\n height: 100px;\n }\n" }, { "answer_id": 74524825, "author": "ethry", "author_id": 16030830, "author_profile": "https://Stackoverflow.com/users/16030830", "pm_score": 1, "selected": true, "text": ".headerImage {\n width: 100px;\n height: 100px;\n} <div>\n <img class=\"headerImage\" src=\"//picsum.photos/1920/1080\" alt=\"your image\">\n</div> .headerImage img {\n width: 100px;\n height: 100px;\n} <div class=\"headerImage\">\n <img src=\"//picsum.photos/1920/1080\" alt=\"your image\">\n</div> .headerImage {\n width: 100%;\n height: 100%;\n}\n.headerImageWrapper {\n width: 100px;\n height: 100px;\n} <div class=\"headerImageWrapper\">\n <img class=\"headerImage\" src=\"//picsum.photos/1920/1080\" alt=\"your image\">\n </div>" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20548073/" ]
74,524,437
<p>I am trying to convert a string that is only 1s and 0s to a decimal value. The variable <code>value</code> is initialized to 0 and is never updated. I suspect the problem is that <code>binaryString[i]</code> is treated as a string and therefore the athematic function doesn't work. How can I fix this?</p> <pre><code>void binaryToDec(string binaryString, int value) { int binaryStringLength = binaryString.length(); for (int i = 0; i &lt; binaryStringLength; i++) { value += pow(2,i)+ binaryString[i]; } } </code></pre> <p>I tried to use basic type casting like <code>int(binaryString[i])</code> but that doesn't work.</p>
[ { "answer_id": 74524516, "author": "john", "author_id": 882003, "author_profile": "https://Stackoverflow.com/users/882003", "pm_score": 2, "selected": false, "text": "binaryString[i] '0' binaryString[i] - '0'\n pow(2,i) 1 << i\n + * value += (1 << i) * (binaryString[i] - '0');\n int binaryToDec(string binaryString)\n{\n int value = 0;\n ...\n return value;\n}\n value binaryString value" }, { "answer_id": 74525580, "author": "rturrado", "author_id": 260313, "author_profile": "https://Stackoverflow.com/users/260313", "pm_score": 0, "selected": false, "text": "ullong #include <bitset>\n#include <fmt/core.h>\n#include <stdexcept> // out_of_range\n\nauto binaryToDec(const std::string& binary) {\n if (binary.size() > 64) {\n throw std::out_of_range{ \"binary string is too big\" };\n }\n return std::bitset<64>{binary}.to_ullong();\n}\n\nint main() {\n try {\n std::string binary_1{\"101010\"};\n fmt::print(\"binary: {}, decimal: {}\\n\", binary_1, binaryToDec(binary_1));\n std::string binary_2{\n \"1111\"\"1111\"\"1111\"\"1111\"\n \"1111\"\"1111\"\"1111\"\"1111\"\n \"1111\"\"1111\"\"1111\"\"1111\"\n \"1111\"\"1111\"\"1111\"\"1111\"\n \"1\"\n };\n fmt::print(\"{}\\n\", binaryToDec(binary_2));\n } catch (const std::exception& e) {\n fmt::print(\"Error: {}.\\n\", e.what());\n }\n}\n\n// Outputs:\n//\n// binary: 101010, decimal: 42\n// Error: binary string is too big.\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14487175/" ]
74,524,438
<p>I've switched from .grid() to .place() in my program, so I decided to remove a frame that contained the grid widgets:</p> <pre><code>BackButtonR = Button(registerPage, text=&quot;Back&quot;, command=lambda: show_frame(Menu)) BackButtonR.grid(row=0, column=0, sticky=W) Button2F3 = Button(registerPage, text=&quot;Find&quot;) Button2F3.grid(row=1, column=1) Button3F3 = Button(registerPage, text=&quot;Calculate&quot;).grid(row=6, column=1) LabelTitleF3 = Label(registerPage, text=&quot;Calculate Buy Price&quot;).grid(row=0, column=3) label1F3 = Label(registerPage, text=&quot;Enter Ticker Symbol:&quot;).grid(row=1, column=0) label2F3 = Label(registerPage, text=&quot;Expected CAGR&quot;).grid(row=2, column=0) label3F3 = Label(registerPage, text=&quot;Years of Analysis&quot;).grid(row=3, column=0) label4F3 = Label(registerPage, text=&quot;Expected PE Ratio&quot;).grid(row=4, column=0) label5F3 = Label(registerPage, text=&quot;Desired Annual Return&quot;).grid(row=5, column=0) entry1F3 = Entry(registerPage, width=7).grid(row=1, column=1, padx=0) entry2F3 = Entry(registerPage).grid(row=2, column=1, pady=10, padx=0) entry3F3 = Entry(registerPage).grid(row=3, column=1, pady=10, padx=0) entry4F3 = Entry(registerPage).grid(row=4, column=1, pady=10, padx=0) entry5F3 = Entry(registerPage).grid(row=, column=1, pady=10, padx=0) </code></pre> <p>But weirdly, when I rerun my program everything turns blank. This shouldn't happen, since I've removed any reference to .grid(), so the program should be working fine with .place(). Here is my full code:</p> <pre><code>print(220+135) from tkinter import * root = Tk() root.title(&quot;Account Signup&quot;) DarkBlue = &quot;#2460A7&quot; LightBlue = &quot;#B3C7D6&quot; root.geometry('350x230') Menu = Frame(root) loginPage = Frame(root) registerPage = Frame(root) for AllFrames in (Menu, loginPage, registerPage): AllFrames.grid(row=0, column=0, sticky='nsew') AllFrames.configure(bg=LightBlue) def show_frame(frame): frame.tkraise() show_frame(Menu) # ============= Menu Page ========= Menu.grid_columnconfigure(0, weight=1) menuTitle = Label(Menu, text=&quot;Menu&quot;, font=(&quot;Arial&quot;, 25), bg=LightBlue) menuTitle.place(x=130, y=25) loginButton1 = Button(Menu, width=25, text=&quot;Login&quot;, command=lambda: show_frame(loginPage)) loginButton1.place(x=85, y=85) registerButton1 = Button(Menu, width=25, text=&quot;Register&quot;, command=lambda: show_frame(registerPage)) registerButton1.place(x=85, y=115) # ======== Login Page =========== loginUsernameL = Label(loginPage, text='Username').place(x=30, y=60) loginUsernameE = Entry(loginPage).place(x=120, y=60) loginPasswordL = Label(loginPage, text='Password').place(x=30, y=90) loginPasswordE = Entry(loginPage).place(x=120, y=90) backButton = Button(loginPage, text='Back', command=lambda: show_frame(Menu)).place(x=0, y=0) loginButton = Button(loginPage, text='Login', width=20).place(x=100, y=150) # ======== Register Page =========== root.mainloop() </code></pre> <p>Why is my program turning blank?</p>
[ { "answer_id": 74526634, "author": "acw1668", "author_id": 5317403, "author_profile": "https://Stackoverflow.com/users/5317403", "pm_score": 0, "selected": false, "text": "root.grid_rowconfigure(0, weight=1) root.grid_columnconfigure(0, weight=1) root Menu.grid_columnconfigure(0, weight=1) Menu .place()" }, { "answer_id": 74527800, "author": "Bryan Oakley", "author_id": 7432, "author_profile": "https://Stackoverflow.com/users/7432", "pm_score": 2, "selected": true, "text": "pack grid place place Menu loginPage registerPage place Menu place grid weight root.grid_rowconfigure(0, weight=1)\nroot.grid_columnconfigure(0, weight=1)\n grid pack place place" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17235593/" ]
74,524,444
<p><a href="https://soulandwolf.com.au/blog/what-is-document-flow/" rel="nofollow noreferrer">This website</a> uses the word &quot;Definition&quot; but never defines it:</p> <blockquote> <p>Document flow is the arrangement of page elements, as defined by CSS positioning statements, and the order of HTML elements. this is to say, how each Definition takes up space and how other elements position themselves accordingly.</p> </blockquote> <p>I need the literal words that I can replace the word &quot;Definition&quot; with in this sentence, and the sentence would still be saying the same thing.</p>
[ { "answer_id": 74526634, "author": "acw1668", "author_id": 5317403, "author_profile": "https://Stackoverflow.com/users/5317403", "pm_score": 0, "selected": false, "text": "root.grid_rowconfigure(0, weight=1) root.grid_columnconfigure(0, weight=1) root Menu.grid_columnconfigure(0, weight=1) Menu .place()" }, { "answer_id": 74527800, "author": "Bryan Oakley", "author_id": 7432, "author_profile": "https://Stackoverflow.com/users/7432", "pm_score": 2, "selected": true, "text": "pack grid place place Menu loginPage registerPage place Menu place grid weight root.grid_rowconfigure(0, weight=1)\nroot.grid_columnconfigure(0, weight=1)\n grid pack place place" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8386132/" ]
74,524,526
<p>could someone help with this? i have four articles and i want them to be organized like this:</p> <pre><code> first one second one third one fourth one </code></pre> <p>but i don't understand what is the problem??</p> <pre><code>body { background-color: #edefee; font-family: serif; margin-top: 3rem; margin-bottom: 3rem; margin-left: 5%; margin-right: 5%; } h1 { font-size: 3rem; } h2 { font-size: 2rem; } header &gt; img { display: block; margin-left: auto; margin-right: auto; } nav ul{ list-style: none; text-align: center; } nav li { display: inline-block; } section { display: flex; } article { flex: 1; } footer { display: flex; } footer div { flex: 1; } </code></pre> <p>my problem for the articles <a href="https://i.stack.imgur.com/JdUiw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JdUiw.png" alt="this is the result i want" /></a></p> <p>could someone help with this? i want this result and this is my code for css part</p>
[ { "answer_id": 74524884, "author": "itaycode", "author_id": 3726834, "author_profile": "https://Stackoverflow.com/users/3726834", "pm_score": 2, "selected": false, "text": ".container {\n display: grid; \n grid-template-columns: 1fr 1fr 1fr; \n grid-template-rows: 1fr 1fr; \n gap: 0px 0px; \n grid-template-areas: \n \". a1 .\"\n \"a2 a3 a4\"; \n}\n.a1 { grid-area: a1; }\n.a2 { grid-area: a2; }\n.a3 { grid-area: a3; }\n.a4 { grid-area: a4; }\n" }, { "answer_id": 74525200, "author": "Ahmad Alsamau", "author_id": 20566320, "author_profile": "https://Stackoverflow.com/users/20566320", "pm_score": 1, "selected": false, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <meta name=\"description\" content=\"\">\n <meta name=\"author\" content=\"\">\n <link rel=\"stylesheet\" href=\"style.css\">\n\n <title>Document</title>\n</head>\n<body>\n\n<header>\n <img src=\"logos/logo3.png\" alt=\"\" width=\"300px\" height=\"100px\">\n</header>\n\n\n\n<nav>\n <ul>\n <li><a href=\"\">Home</a></li>\n <li><a href=\"\">Menu</a></li>\n <li><a href=\"\">Book</a></li>\n <li><a href=\"\">About</a></li>\n </ul>\n</nav>\n\n\n\n<main>\n <section>\n <article class=\"art-fle\">\n <h1>Header 1</h1>\n <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Quaerat \ncorporis voluptate vel ab consectetur repudiandae sunt accusantium. \nPerspiciatis, minima voluptatem!</p>\n </article>\n </section>\n <section>\n <article class=\"art-fle\">\n <h2>Header 2</h2>\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. \nSimilique, enim ad architecto necessitatibus consectetur tempora.</p>\n </article>\n </section>\n <section>\n <article class=\"art-fle\">\n <h2>Header 3</h2>\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Beatae, \nautem! Modi voluptate officia facere voluptatibus!</p>\n </article>\n </section>\n <section>\n <article class=\"art-fle\">\n <h2>Header 4</h2>\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. \nPerferendis, veniam nam! Dicta dolorum officiis quas?</p>\n </article>\n </section>\n</main>\n\n<footer>\n <div>\n <img src=\"\">\n </div>\n <div>\n <p>Copyright Little Lemon</p>\n </div>\n</footer>\n</body>\n</html>\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20566320/" ]
74,524,527
<div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Route</th> <th>Incident</th> <th>delay_minute</th> </tr> </thead> <tbody> <tr> <td>63</td> <td>Operator</td> <td>60</td> </tr> <tr> <td>63</td> <td>Operator</td> <td>24</td> </tr> <tr> <td>63</td> <td>Mechanical</td> <td>89</td> </tr> <tr> <td>54</td> <td>Operator</td> <td>70</td> </tr> <tr> <td>54</td> <td>Sanitation</td> <td>34</td> </tr> <tr> <td>54</td> <td>Operator</td> <td>12</td> </tr> </tbody> </table> </div> <p>From the example table above, I want to return <strong>one row per route</strong> with their <strong>most common</strong> type/form of Incident. Such that it would look like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Route</th> <th>Incident</th> </tr> </thead> <tbody> <tr> <td>63</td> <td>Operator</td> </tr> <tr> <td>54</td> <td>Operator</td> </tr> </tbody> </table> </div> <p>I have tried the following query, but I am unsure whether or not it returns the most common form of Incident per route:</p> <pre><code>SELECT Route , Incident FROM bus_delay; </code></pre> <p>I have also attempted to use <code>COUNT(DISTINCT)</code> but I require the Incident type returned as string, per route:</p> <pre><code>SELECT DISTINCT Route , Incident , COUNT(Incident) AS count_incident FROM bus_delay GROUP BY Incident , Route; </code></pre> <p>How do I query such a table to return one row per Route, with that row only showing the most common form of Incident for that Route?</p>
[ { "answer_id": 74524669, "author": "Sergey", "author_id": 14535517, "author_profile": "https://Stackoverflow.com/users/14535517", "pm_score": 0, "selected": false, "text": "SELECT Z.Route,Z.Incident FROM\n(\n SELECT C.Route,C.Incident,\n ROW_NUMBER()OVER(PARTITION BY C.Route,C.Incident ORDER BY (SELECT NULL))XCOL\n FROM YOUR_TABLE AS C\n)Z WHERE Z.XCOL>1\n" }, { "answer_id": 74524734, "author": "nbk", "author_id": 5193536, "author_profile": "https://Stackoverflow.com/users/5193536", "pm_score": 0, "selected": false, "text": "WINDOW CTE WITH CTE as(\n SELECT\n Route, Incident, delay_minute,\n ROW_NUMBER() OVER(PARTITION BY Route, Inciden ORDER BY delay_minute DESC) rn\n FROM bus_delay)\nSELECT\nRoute, Incident, delay_minute\nFROM CTE WHERE rn = 1\n" }, { "answer_id": 74524893, "author": "ahmed", "author_id": 12705912, "author_profile": "https://Stackoverflow.com/users/12705912", "pm_score": 2, "selected": true, "text": "select Route, Incident\nfrom\n(\n select Route, Incident, \n row_number() over (partition by Route order by count(*) desc) rn\n from bus_delay\n group by Route, Incident\n) T\nwhere rn=1\n DENSE_RANK ROW_NUMBER" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18408564/" ]
74,524,544
<p>I'm trying to run stable diffusion on my local pc. It's a macbook pro m1. Even though I did follow every single step, I keep getting an import error. What might possibly be the reason and how may I fix it?</p> <p>ImportError: cannot import name 'WatermarkEncoder' from 'imWatermark'</p> <p>I was referring an online tutorial so I did end up searching through the comments. Found nothing so far.</p>
[ { "answer_id": 74590767, "author": "Kate Scshegoleva", "author_id": 20615086, "author_profile": "https://Stackoverflow.com/users/20615086", "pm_score": 0, "selected": false, "text": "from imWatermark import WatermarkEncoder from imwatermark import WatermarkEncoder" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10354991/" ]
74,524,574
<pre><code>class TaskInput: def __init__(self): self.cfg = my_config #### Question: How do I do this only once? class TaskA(TaskInput): def __init__(self): pass class TaskB (TaskInput): def __init__(self): pass </code></pre> <ul> <li>There are many tasks like <code>TaskA</code>, <code>TaskB</code> etc, they all are inherited from <code>TaskInput</code>.</li> <li><code>Tasks</code> also depend on something, let's say, a <code>configuration</code> which I only want to <strong>set ONCE</strong>.</li> <li>The code has multiple <code>Tasks</code> classes, like <code>TaskA</code>, <code>TaskB</code> etc. They all depend on this common <code>configuration</code>.</li> </ul> <p>One natural way would be to make this configuration a <code>class member</code> of <code>TaskInput</code>, ie, <code>TaskInput.cfg = my_config</code>, something that's initialized in <code>__init__()</code> of <code>TaskInput</code>.</p> <p>However, if it's a member of <code>TaskInput</code>, it'll get <code>executed</code> multiple times, every time a new <code>object</code> of type <code>TaskX</code> is created as all those <code>Tasks</code> are inherited from <code>TaskInput</code>.</p> <p>What's the best practice and best way to accomplish this in Python?</p>
[ { "answer_id": 74524676, "author": "kindall", "author_id": 416467, "author_profile": "https://Stackoverflow.com/users/416467", "pm_score": 2, "selected": false, "text": "__init__ class TaskInput:\n cfg = my_config\n self.cfg TaskInput" }, { "answer_id": 74526579, "author": "Olivier Gagnon", "author_id": 11860414, "author_profile": "https://Stackoverflow.com/users/11860414", "pm_score": 0, "selected": false, "text": "from copy import deepcopy\n\nclass TaskInput:\n _cfg = None # prefix with '_' to indicate it should be considered private\n \n def __init__(self, my_config=None):\n _cfg = _cfg or my_config\n \n @property\n def cfg(self):\n \"\"\" If you want to privatize it a bit more,\n make yourself a getter that returns a deep copy.\"\"\"\n return deepcopy(cfg)\n _cfg __init__() cfg() Project\n ├─ __init__.py\n ├─ settings.py\n ├─ module1.py\n └─ module2.py\n cfg = None\n from copy import deepcopy\nimport settings\n\nclass A:\n def __init__(self, cfg_=None):\n settings.cfg = settings.cfg or cfg_\n\n @property\n def cfg(self):\n return deepcopy(settings.cfg)\n \"\"\" The following classes won't be able to\noverwrite the config without importing\nfrom settings.py.\n\"\"\"\n\nfrom module1 import A\n\nclass B(A):\n pass\n\nclass C(A):\n def __init__(self):\n super().__init__(\"foobar\")\n b0 = B()\nb0.cfg\n# > None\n\nb1 = B({\"foo1\": \"bar1\"})\nb1.cfg\n# > {'foo1': 'bar1'}\n\nb2 = B({\"foo1\": \"bar2\", \"foo3\": \"bar3\"})\nb2.cfg\n# > {'foo1': 'bar1'}\n\ntry:\n b2.cfg = 1234\nexcept Exception as e:\n print(type(e), e)\n# > <class 'AttributeError'> can't set attribute\n\nb2.cfg\n# > {'foo1': 'bar1'}\n\nc = C(\"asdf\")\nc.cfg\n# > {'foo1': 'bar1'}\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/167814/" ]
74,524,585
<p>I have a <code>base.html</code> which my <code>options.html</code> extends from like this</p> <pre class="lang-html prettyprint-override"><code>//options.html {% extends &quot;webpage/base.html&quot; %} {% load static %} &lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;{% static 'webpage/options.css' %}&quot;&gt; {% block content %} &lt;div class=&quot;test&quot;&gt; foo &lt;/div&gt; {% endblock content %} </code></pre> <pre class="lang-html prettyprint-override"><code>//base.html {% load static %} &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;!-- Required meta tags --&gt; &lt;meta charset=&quot;utf-8&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1, shrink-to-fit=no&quot;&gt; &lt;!-- Bootstrap CSS --&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css&quot; integrity=&quot;sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm&quot; crossorigin=&quot;anonymous&quot;&gt; &lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;{% static 'webpage/base.css' %}&quot;&gt; &lt;!-- jQuery--&gt; &lt;script src=&quot;https://code.jquery.com/jquery-3.6.1.slim.js&quot; integrity=&quot;sha256-tXm+sa1uzsbFnbXt8GJqsgi2Tw+m4BLGDof6eUPjbtk=&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt; &lt;title&gt;:)&lt;/title&gt; &lt;/head&gt; &lt;body&gt; hello world {% block content %} {% endblock content %} &lt;!-- Optional JavaScript --&gt; &lt;!-- jQuery first, then Popper.js, then Bootstrap JS --&gt; &lt;script src=&quot;https://code.jquery.com/jquery-3.2.1.slim.min.js&quot; integrity=&quot;sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt; &lt;script src=&quot;https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js&quot; integrity=&quot;sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt; &lt;script src=&quot;https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js&quot; integrity=&quot;sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>the issue is that the CSS is not loaded/applied.</p> <p>In the web-console (when I run <code>python manage.py runserver</code>) and go to the &quot;options&quot; page, then I can see that the <code>webpage/base.css</code> is loaded (i.e <code>GET /static/webpage/base.css</code> is printed), but the <code>webpage/options.css</code> is not.</p> <p>I thought I had something wrong in the static- path, but if I move the</p> <p><code>&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;{% static 'webpage/options.css' %}&quot;&gt;</code> into my <code>base.html</code>(and go to my <code>home</code> page) then I see that <code>GET /static/webpage/options.css</code> is now printet and the css in there indeed takes effect.</p> <p>Why can it be that it is not loaded in the <code>options.html</code> file? Note, this question is not about CSS changes not taking effect (untill hard-refresh, cache clear etc.) but it seems like the file simply isn't getting loaded</p>
[ { "answer_id": 74524939, "author": "SamSparx", "author_id": 18799377, "author_profile": "https://Stackoverflow.com/users/18799377", "pm_score": 3, "selected": true, "text": "<head>\n...\n{% block htmlhead %}\n{% endblock htmlhead %}\n</head>\n {% block htmlhead %}\n{% load static %}\n<link rel=\"stylesheet\" type=\"text/css\" href=\"{% static 'webpage/options.css' %}\"> \n{% endblock htmlhead %}\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6224975/" ]
74,524,610
<p><strong>EDIT: although this question has been closed, it is helpful to note that the answers provided use a very different approach (with dplyr) than the original question asked in 2012(!). These new answers may be helpful for different users.</strong></p> <p>I have a datasets of sites with the min and max years when they were operational. But I want to expand this dataset so that each year the site was operational has a row.</p> <p>For example:</p> <pre><code>set.seed(42) df &lt;- data.frame( site = rep(LETTERS[1:10]), minY = sample(1980:1990, 10), maxY = sample(2000:2010, 10) ) df site minY maxY 1 A 1980 2007 2 B 1984 2006 3 C 1990 2003 4 D 1988 2000 5 E 1981 2004 6 F 1983 2005 7 G 1986 2008 8 H 1989 2001 9 I 1987 2009 10 J 1985 2010 </code></pre> <p>So in my final dataset Site A would have a 28 rows (one for each year it was operating).</p> <p>I've been trying to use the complete function, but I keep getting an error message:</p> <pre><code>complete(df, nesting(site), fill = list(value1 = minY, value2 = maxY)) Error in vec_is_list(replace) : object 'minY' not found </code></pre>
[ { "answer_id": 74524725, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 3, "selected": true, "text": "dplyr summarize library(dplyr)\n\ndf %>% \n rowwise() %>% \n summarize(site, year = seq(minY, maxY, 1))\n# A tibble: 210 × 2\n site year\n <chr> <dbl>\n 1 A 1980\n 2 A 1981\n 3 A 1982\n 4 A 1983\n 5 A 1984\n 6 A 1985\n 7 A 1986\n 8 A 1987\n 9 A 1988\n10 A 1989\n# … with 200 more rows\n" }, { "answer_id": 74524727, "author": "FactOREO", "author_id": 20462305, "author_profile": "https://Stackoverflow.com/users/20462305", "pm_score": 2, "selected": false, "text": "tidyr::uncount() df |>\n uncount(weights = maxY - minY + 1)\n dplyr::mutate() df |>\n uncount(weights = maxY - minY + 1) |>\n group_by(site) |>\n mutate(unique_year = seq.default(min(minY),max(maxY)))\n data.frame maxY minY" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3220999/" ]
74,524,638
<p>I currently have this how can I get it so it checks for a float and uses a while loop</p> <pre><code>def get_float(): number = input('Input a decimal number ') while number != float: print('bad input ') number = input('Input a decimal number ') else: return number get_float() </code></pre> <p>right now even if I enter a decimal number it says bad input and asks for another input</p>
[ { "answer_id": 74524666, "author": "Silvio Mayolo", "author_id": 2288659, "author_profile": "https://Stackoverflow.com/users/2288659", "pm_score": 2, "selected": false, "text": "def get_float():\n while True:\n number = input('Input a number ')\n try:\n return float(number)\n except ValueError:\n print('\\n bad input\\n ')\n" }, { "answer_id": 74524791, "author": "John Gordon", "author_id": 494134, "author_profile": "https://Stackoverflow.com/users/494134", "pm_score": 0, "selected": false, "text": "number = input('Input a decimal number ')\nwhile number != float:\n input() number number float float if type(number) != float number" }, { "answer_id": 74539534, "author": "Z-0", "author_id": 20566386, "author_profile": "https://Stackoverflow.com/users/20566386", "pm_score": 0, "selected": false, "text": "def get_float():\n while True:\n number = input('Input a decimal number ')\n try:\n if \".\" in number:\n floatnumber = float(number)\n print(floatnumber)\n break\n else:\n print(\"invalid number\")\n except ValueError as err:\n print(err)\n \n \nget_float() \n\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20566386/" ]
74,524,640
<p>I have to implement a mini-router in VHDL. The design requirements for this are:</p> <p><img src="https://i.stack.imgur.com/7zqJn.png" alt="design requirements" /></p> <p>I've written the implementation, and a testbench. However, looking at the simulation waveform, some of my initial signals are undefined and I'm not sure why.</p> <p><img src="https://i.stack.imgur.com/TuZ45.png" alt="enter image description here" /></p> <p>This is the source code:</p> <pre class="lang-vhdl prettyprint-override"><code> library IEEE; use IEEE.std_logic_1164.all; use IEEE.std_logic_unsigned.all; use IEEE.numeric_std.all; entity mini_router is port ( clk : in std_logic; reset : in std_logic; -- synchronous negative reset data1 : in std_logic_vector(9 downto 0); req1 : in std_logic; grant1 : out std_logic; data2 : in std_logic_vector(9 downto 0); req2 : in std_logic; grant2 : out std_logic; data_out : out std_logic_vector(7 downto 0); valid : out std_logic ); end entity; architecture arch of mini_router is signal aux : std_logic_vector(9 downto 0); signal aux1 : std_logic_vector(1 downto 0); signal aux2 : std_logic_vector(1 downto 0); signal aux_valid : std_logic; signal aux_grant1 : std_logic; signal aux_grant2 : std_logic; begin mini_router: process(clk) variable r : std_logic:= '1'; begin -- conta le volte in cui c'è stato data conflict if rising_edge(clk) then -- chiuso if reset = '0' then aux &lt;= (others =&gt; '0'); aux_valid &lt;= '0'; aux_grant1 &lt;= '0'; aux_grant2 &lt;= '0'; elsif reset = '1' then if (req1 xor req2) = '1' then --chiuso -- un solo req è alto if req1 ='1' then --chiuso aux &lt;= data1; aux_grant1 &lt;= '1'; aux_grant2 &lt;= '0'; aux_valid &lt;= '1'; else aux &lt;= data2; aux_grant1 &lt;= '0'; aux_grant2 &lt;= '1'; aux_valid &lt;= '1'; end if; ----entrambi i req sono alti elsif (req1 and req2) = '1' then -- chiuso if ((unsigned(aux1)) &gt; (unsigned(aux2))) then aux &lt;= data1; aux_grant1 &lt;= '1'; aux_grant2 &lt;= '0'; aux_valid &lt;= '1'; elsif ((unsigned(aux1)) &lt; (unsigned(aux2))) then aux &lt;= data2; aux_grant2 &lt;= '1'; aux_grant1 &lt;= '0'; aux_valid &lt;= '1'; elsif ((unsigned(aux1)) = (unsigned(aux2))) then -- stesso livello di priorità -- alternativa:(aux1 xnor aux2)=&quot;11&quot; if r = '1' then aux &lt;= data1; aux_grant1&lt;= '1'; aux_grant2 &lt;= '0'; aux_valid &lt;= '1'; r := not (r); else aux &lt;= data2; aux_grant2 &lt;= '1'; aux_grant1&lt;= '0'; aux_valid &lt;= '1'; r := not (r); end if; end if; elsif (req1 nor req2) = '1' then aux_valid &lt;= '0'; aux &lt;= (others =&gt; '0'); aux_grant1 &lt;= '0'; aux_grant2 &lt;= '0'; end if; end if; -- if del reset end if; -- if del clock end process; data_out &lt;= aux(9 downto 2); aux1 &lt;= data1 (1 downto 0); aux2 &lt;= data2 (1 downto 0); valid &lt;= aux_valid; grant1 &lt;= aux_grant1; grant2 &lt;= aux_grant2; end architecture; </code></pre> <p>This is the testbench:</p> <pre class="lang-vhdl prettyprint-override"><code>library IEEE; use IEEE.std_logic_1164.all; use IEEE.numeric_std.all; entity mini_router_tb is end mini_router_tb; architecture arc of mini_router_tb is constant T_CLK : time := 10 ns; --- frequenza di clock: 125 MHz signal clk_tb : std_logic := '1'; signal reset_tb : std_logic := '0'; -- reset attivo basso sincrono signal data1_tb : std_logic_vector(9 downto 0) := (others =&gt; '0'); signal req1_tb : std_logic:= '0'; signal grant1_tb : std_logic; signal data2_tb : std_logic_vector(9 downto 0) := (others =&gt; '0'); signal req2_tb : std_logic:= '0'; signal grant2_tb : std_logic; signal data_out_tb : std_logic_vector(7 downto 0); signal valid_tb : std_logic; signal end_sim : std_logic := '1'; -- signal to use to stop the simulation when there is nothing else to test component mini_router is port ( clk : in std_logic; reset : in std_logic; -- synchronous negative reset data1 : in std_logic_vector(9 downto 0); req1 : in std_logic; grant1 : out std_logic; data2 : in std_logic_vector(9 downto 0); req2 : in std_logic; grant2 : out std_logic; data_out : out std_logic_vector(7 downto 0); valid : out std_logic ); end component; begin clk_tb &lt;= (not(clk_tb)and(end_sim)) after T_CLK/2; DUT : mini_router port map ( clk =&gt; clk_tb, reset =&gt; reset_tb, data1 =&gt; data1_tb, req1 =&gt; req1_tb, grant1 =&gt; grant1_tb, data2 =&gt; data2_tb, req2 =&gt; req2_tb, grant2 =&gt; grant2_tb, data_out =&gt; data_out_tb, valid =&gt; valid_tb ); -- process used to make the testbench signals change synchronously with the rising edge of the clock stimuli_process: process(clk_tb,reset_tb) variable t : integer := 0; -- variabile che conta i cicli di clock begin if (rising_edge(clk_tb)) then case (t) is when 1 =&gt; data1_tb &lt;= (9 downto 3 =&gt; '0') &amp; &quot;100&quot;; -- data1= 4; data_out=0 per il reset data2_tb &lt;= (9 downto 4 =&gt; '0') &amp; &quot;1101&quot;;-- data2= 13; req1_tb &lt;= '1' ; req2_tb&lt;= '0'; when 2 =&gt; reset_tb &lt;= '1'; data1_tb &lt;= (9 downto 3 =&gt; '0') &amp; &quot;100&quot;; -- data1= 4; data_out=1 data2_tb &lt;= (9 downto 4 =&gt; '0') &amp; &quot;1101&quot;; -- data2= 13; req1_tb &lt;= '1' ; req2_tb&lt;= '0'; when 3 =&gt; data1_tb &lt;= (9 downto 3 =&gt; '0') &amp; &quot;100&quot;; -- data1= 4; data2_tb &lt;= (9 downto 4 =&gt; '0') &amp; &quot;1101&quot;;-- data2= 13; data_out=3 req1_tb &lt;= '0' ; req2_tb&lt;= '1'; when 4 =&gt; data1_tb &lt;= (9 downto 5 =&gt; '0') &amp; &quot;11100&quot;; --data1=28 data2_tb &lt;= (9 downto 4 =&gt; '0') &amp; &quot;1101&quot;; -- data2= 13; data_out=3 priorità maggiore req1_tb &lt;= '1' ; req2_tb&lt;= '1'; when 5 =&gt; data1_tb &lt;= (9 downto 5 =&gt; '0') &amp; &quot;00111&quot;; --data1=7; data_out=1 priorità maggiore data2_tb &lt;= (9 downto 5 =&gt; '0') &amp; &quot;11101&quot;; -- data2= 29; req1_tb &lt;= '1' ; req2_tb&lt;= '1'; when 6 =&gt; data1_tb &lt;= (9 downto 5 =&gt; '0') &amp; &quot;00111&quot;; --data1=7; data_out=1 data2_tb &lt;= (9 downto 5 =&gt; '0') &amp; &quot;11111&quot;; -- data2= 31; req1_tb &lt;= '1' ; req2_tb&lt;= '1'; when 7 =&gt; data1_tb &lt;= (9 downto 5 =&gt; '0') &amp; &quot;00111&quot;; --data_out=0; data2_tb &lt;= (9 downto 5 =&gt; '0') &amp; &quot;11111&quot;; req1_tb &lt;= '0' ; req2_tb&lt;= '0'; when 8 =&gt; data1_tb &lt;= (9 downto 5 =&gt; '0') &amp; &quot;10111&quot;; --data1=7; data_out non assunto=5 data2_tb &lt;= (9 downto 5 =&gt; '0') &amp; &quot;11111&quot;; -- data2= 31; data_out=7 req1_tb &lt;= '1' ; req2_tb&lt;= '1'; when 9 =&gt; end_sim &lt;= '0'; -- stops the simulation when t = 10 when others =&gt; null; -- non accade nulla negli altri casi end case; t := t + 1; end if; end process; end architecture; </code></pre>
[ { "answer_id": 74524931, "author": "the busybee", "author_id": 11294831, "author_profile": "https://Stackoverflow.com/users/11294831", "pm_score": 1, "selected": false, "text": "rising_edge(clk) if reset = '0' then\n -- reset statements\n elsif rising_edge(clk) then\n -- work statements\n end if;\n" }, { "answer_id": 74645637, "author": "PlayDough", "author_id": 4367824, "author_profile": "https://Stackoverflow.com/users/4367824", "pm_score": 0, "selected": false, "text": "U X -------------------------------------------------------------------\n -- logic state system (unresolved)\n -------------------------------------------------------------------\n type STD_ULOGIC is ( 'U', -- Uninitialized\n 'X', -- Forcing Unknown\n '0', -- Forcing 0\n '1', -- Forcing 1\n 'Z', -- High Impedance\n 'W', -- Weak Unknown\n 'L', -- Weak 0\n 'H', -- Weak 1\n '-' -- Don't care\n );\n --------------------------------\n std_logic std_ulogic std_logic U signal A : std_logic;\nsignal B : std_logic := '1';\n A U B 0 U X U X U" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20563102/" ]
74,524,687
<p>I’m checking to see if a token is not a phone number or email because it has to be one of those.</p> <p>I know how to do email:</p> <pre><code>Token NOT LIKE ‘%@%’ </code></pre> <p>Not sure how remove phone numbers that have 10 characters length.</p> <p>All is being coded in Oracle SQL.</p> <p>I tried:</p> <pre><code>TOKEN NOT LIKE ‘%@%’ AND LENGTH(TOKEN) &gt; 10 </code></pre> <p>I got one result back but is this properly check for others that aren’t a phone number token</p>
[ { "answer_id": 74524931, "author": "the busybee", "author_id": 11294831, "author_profile": "https://Stackoverflow.com/users/11294831", "pm_score": 1, "selected": false, "text": "rising_edge(clk) if reset = '0' then\n -- reset statements\n elsif rising_edge(clk) then\n -- work statements\n end if;\n" }, { "answer_id": 74645637, "author": "PlayDough", "author_id": 4367824, "author_profile": "https://Stackoverflow.com/users/4367824", "pm_score": 0, "selected": false, "text": "U X -------------------------------------------------------------------\n -- logic state system (unresolved)\n -------------------------------------------------------------------\n type STD_ULOGIC is ( 'U', -- Uninitialized\n 'X', -- Forcing Unknown\n '0', -- Forcing 0\n '1', -- Forcing 1\n 'Z', -- High Impedance\n 'W', -- Weak Unknown\n 'L', -- Weak 0\n 'H', -- Weak 1\n '-' -- Don't care\n );\n --------------------------------\n std_logic std_ulogic std_logic U signal A : std_logic;\nsignal B : std_logic := '1';\n A U B 0 U X U X U" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18431091/" ]
74,524,715
<p>I am trying to import a pandas dataframe in a Streamlit app (the goal being to run a Machine Learning model based on this dataframe when clicking a button). I use the usual way:</p> <pre><code>import pandas as pd import streamlit as st df = pd.read_csv('/data/metabolic_syndrome.csv') if (st.button('Click on this fancy button !')): st.warning(&quot;This was a bad choice.&quot;) </code></pre> <p>My path is the good one on my local machine, yet when I run the app on <code>localhost</code> it sends back this error:</p> <blockquote> <p>FileNotFoundError: [Errno 2] No such file or directory: '/data/metabolic_syndrome.csv'</p> </blockquote> <p>I may miss a key concept as I'm not a computer science specialist (such as saving the file somewhere else) yet the pathfile is the good one on my local machine, and I really don't understand what should I do here to have a proper import and run the app localy ? If that's useful, I'm on <code>iOS</code>.</p>
[ { "answer_id": 74524931, "author": "the busybee", "author_id": 11294831, "author_profile": "https://Stackoverflow.com/users/11294831", "pm_score": 1, "selected": false, "text": "rising_edge(clk) if reset = '0' then\n -- reset statements\n elsif rising_edge(clk) then\n -- work statements\n end if;\n" }, { "answer_id": 74645637, "author": "PlayDough", "author_id": 4367824, "author_profile": "https://Stackoverflow.com/users/4367824", "pm_score": 0, "selected": false, "text": "U X -------------------------------------------------------------------\n -- logic state system (unresolved)\n -------------------------------------------------------------------\n type STD_ULOGIC is ( 'U', -- Uninitialized\n 'X', -- Forcing Unknown\n '0', -- Forcing 0\n '1', -- Forcing 1\n 'Z', -- High Impedance\n 'W', -- Weak Unknown\n 'L', -- Weak 0\n 'H', -- Weak 1\n '-' -- Don't care\n );\n --------------------------------\n std_logic std_ulogic std_logic U signal A : std_logic;\nsignal B : std_logic := '1';\n A U B 0 U X U X U" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14820215/" ]
74,524,739
<p>I hope you are well. I am looking to convert the following XML URL into a pandas dataframe.</p> <p>You can view the XML here; <a href="https://clients2.google.com/complete/search?hl=en&amp;output=toolbar&amp;q=how%20garage%20doors" rel="nofollow noreferrer">https://clients2.google.com/complete/search?hl=en&amp;output=toolbar&amp;q=how%20garage%20doors</a></p> <p>Here is the Python 3 code here, which currently returns an empty dataframe.</p> <pre><code>from bs4 import BeautifulSoup import requests import pandas as pd response = requests.get('https://clients2.google.com/complete/search?hl=en&amp;output=toolbar&amp;q=how%20garage%20doors') bs = BeautifulSoup(response.text, ['xml']) print(bs) obs = bs.find_all(&quot;CompleteSuggestion&quot;) print(obs) df = pd.DataFrame(columns=['suggestion data','Keyword']) for node in obs: df = df.append({'suggestion data': node.get(&quot;suggestion data&quot;)}, ignore_index=True) df.head() </code></pre> <p>Any suggestions would be welcome. I am open to do it with other modules if there are any better alternatives.</p> <p>Also the expected output would be a dataframe containing a list of autosuggest search terms related to &quot;garage doors&quot;.</p> <p>I could not get Python ElementTree XML conversion to work.</p>
[ { "answer_id": 74524931, "author": "the busybee", "author_id": 11294831, "author_profile": "https://Stackoverflow.com/users/11294831", "pm_score": 1, "selected": false, "text": "rising_edge(clk) if reset = '0' then\n -- reset statements\n elsif rising_edge(clk) then\n -- work statements\n end if;\n" }, { "answer_id": 74645637, "author": "PlayDough", "author_id": 4367824, "author_profile": "https://Stackoverflow.com/users/4367824", "pm_score": 0, "selected": false, "text": "U X -------------------------------------------------------------------\n -- logic state system (unresolved)\n -------------------------------------------------------------------\n type STD_ULOGIC is ( 'U', -- Uninitialized\n 'X', -- Forcing Unknown\n '0', -- Forcing 0\n '1', -- Forcing 1\n 'Z', -- High Impedance\n 'W', -- Weak Unknown\n 'L', -- Weak 0\n 'H', -- Weak 1\n '-' -- Don't care\n );\n --------------------------------\n std_logic std_ulogic std_logic U signal A : std_logic;\nsignal B : std_logic := '1';\n A U B 0 U X U X U" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13056765/" ]
74,524,754
<p>I have a data frame like this and I am doing this on R. My problems can be divided into two steps.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>SUBID</th> <th>ABC</th> <th>BCD</th> <th>DEF</th> </tr> </thead> <tbody> <tr> <td>192838</td> <td>4</td> <td>-3</td> <td>2</td> </tr> <tr> <td>193928</td> <td>-6</td> <td>-2</td> <td>6</td> </tr> <tr> <td>205829</td> <td>4</td> <td>-5</td> <td>9</td> </tr> <tr> <td>201837</td> <td>3</td> <td>4</td> <td>4</td> </tr> </tbody> </table> </div> <p>I want to make a new variable that contains a list of the column names that has a negative value for each SUBID. The output should look something like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>SUBID</th> <th>ABC</th> <th>BCD</th> <th>DEF</th> <th>output</th> </tr> </thead> <tbody> <tr> <td>192838</td> <td>4</td> <td>-3</td> <td>2</td> <td>&quot;BCD&quot;</td> </tr> <tr> <td>193928</td> <td>-6</td> <td>-2</td> <td>6</td> <td>&quot;ABC&quot;,&quot;BCD&quot;</td> </tr> <tr> <td>205829</td> <td>4</td> <td>-5</td> <td>9</td> <td>&quot;BCD&quot;</td> </tr> <tr> <td>201837</td> <td>3</td> <td>4</td> <td>4</td> <td>&quot; &quot;</td> </tr> </tbody> </table> </div> <p>And then, in the second step, I would like to collapse the SUBID into a more general ID and get the number of unique strings from the output variable for each ID (I just need the number, the specific strings in the parenthesis are just for illustration).</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>SUBID</th> <th>output</th> </tr> </thead> <tbody> <tr> <td>19</td> <td>2 (&quot;ABC&quot;,&quot;BCD&quot;)</td> </tr> <tr> <td>20</td> <td>1 (&quot;BCD&quot;)</td> </tr> </tbody> </table> </div> <p>Those are the two steps that I thing should be done, but maybe there is a way that can skip the first step and goes to the second step directly that I don't know. I would appreciate any help since right now I am not sure where to start on this. Thank you!</p>
[ { "answer_id": 74524820, "author": "Jilber Urbina", "author_id": 1315767, "author_profile": "https://Stackoverflow.com/users/1315767", "pm_score": 2, "selected": false, "text": " df$output <-apply(df[,-1], 1, function(x) paste(names(df)[-1][x<0], collapse = \",\"))\n df\n SUBID ABC BCD DEF output\n1 192838 4 3 -2 DEF\n2 193928 -6 -2 6 ABC,BCD\n3 205829 4 -5 9 BCD\n4 201837 3 4 4 \n id <- sapply(strsplit(sub(\"\\\\W+\", \"\", df$output), split = \"\"), function(x){\n sum(!(duplicated(x) | duplicated(x, fromLast = TRUE)))\n} )\n\n\n data.frame(SUBID = substr(df$SUBID, 1,2), output = id, string = df$output)\n SUBID output string\n 1 19 3 DEF\n 2 19 2 ABC,BCD\n 3 20 3 BCD\n 4 20 0 \n string" }, { "answer_id": 74524944, "author": "arg0naut91", "author_id": 8389003, "author_profile": "https://Stackoverflow.com/users/8389003", "pm_score": 3, "selected": true, "text": "library(dplyr)\nlibrary(tidyr)\n\ndf <- df %>% pivot_longer(-SUBID)\n\ndf1 <- df %>%\n group_by(SUBID) %>%\n summarise(output = paste(name[value < 0L], collapse = ','))\n\ndf2 <- df %>%\n group_by(SUBID = substr(SUBID, 1, 2)) %>%\n summarise(output_count = n_distinct(name[value < 0L]),\n output = paste0(output_count, ' (', paste(name[value < 0L], collapse = ','), ')'))\n df1\n\n# A tibble: 4 x 2\n SUBID output \n <int> <chr> \n1 192838 \"BCD\" \n2 193928 \"ABC,BCD\"\n3 201837 \"\" \n4 205829 \"BCD\" \n\ndf2\n\n# A tibble: 2 x 3\n SUBID output_count output \n <chr> <int> <chr> \n1 19 2 2 (BCD,ABC,BCD)\n2 20 1 1 (BCD) \n" }, { "answer_id": 74536788, "author": "Dan Adams", "author_id": 13210554, "author_profile": "https://Stackoverflow.com/users/13210554", "pm_score": 0, "selected": false, "text": "dplyr::cur_data() names() tibble library(tidyverse)\n\nd <- structure(list(SUBID = c(192838, 193928, 205829, 201837), ABC = c(4, -6, 4, 3), BCD = c(-3, -2, -5, 4), DEF = c(2, 6, 9, 4)), row.names = c(NA, -4L), class = \"data.frame\")\n\nd %>% \n rowwise() %>%\n mutate(neg_col_names = list(names(cur_data())[cur_data() < 0])) %>% \n group_by(ID_grp = str_sub(SUBID, 1, 2)) %>% \n summarize(neg_col_count = n_distinct(unlist(c(neg_col_names))))\n\n#> # A tibble: 2 × 2\n#> ID_grp neg_col_count\n#> <chr> <int>\n#> 1 19 2\n#> 2 20 1\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20005378/" ]
74,524,792
<blockquote> <p><strong>A Challenging One: How to convert a singly linked list into a staggered linked list using C language?</strong> By Modifying the order of a linked list in the following pattern, adding the current node to the result list after every step:</p> <ul> <li>Start at the head</li> <li>Take two steps forward</li> <li>Take one step back</li> <li>Take three steps forward</li> <li>Go to step 3 unless outside end of list</li> <li>Add unvisited element at end of list to result, if any</li> </ul> </blockquote> <p><strong>Example 1 : Odd no. of elements</strong></p> <p>Input:</p> <pre class="lang-none prettyprint-override"><code>0-&gt;1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6-&gt;7-&gt;8-&gt;NULL </code></pre> <p>Output:</p> <pre class="lang-none prettyprint-override"><code>0-&gt;2-&gt;1-&gt;4-&gt;3-&gt;6-&gt;5-&gt;8-&gt;7-&gt;NULL </code></pre> <hr /> <p><strong>Example 2: Even no. of elements</strong></p> <p>Input:</p> <pre class="lang-none prettyprint-override"><code>0-&gt;1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6-&gt;7-&gt;NULL </code></pre> <p>Output:</p> <pre class="lang-none prettyprint-override"><code>0-&gt;2-&gt;1-&gt;4-&gt;3-&gt;6-&gt;5-&gt;7-&gt;NULL </code></pre> <hr /> <p>For one or two elements, return as is.</p> <p><strong>For 3 elements:</strong></p> <p>Input:</p> <pre class="lang-none prettyprint-override"><code>0-&gt;1-&gt;2 </code></pre> <p>Output:</p> <pre class="lang-none prettyprint-override"><code>0-&gt;2-&gt;1-&gt;NULL </code></pre> <hr /> <p>Here's what I tried but not running successfully on all input cases:</p> <pre><code>#include &lt;stdio.h&gt; struct Node { const int val; struct Node *next; }; void stagger(struct Node *head) { struct Node *curr, *slow, *fast='\0'; curr = head; if (curr == '\0') { printf(&quot;NULL&quot;); return; } if (curr-&gt;next == '\0' || curr-&gt;next-&gt;next == '\0') { while (curr) { printf(&quot;%d-&gt;&quot;,curr-&gt;val); curr = curr-&gt;next; } } else { while (fast) { printf(&quot;%d-&gt;&quot;,curr-&gt;val); //0-1 fast = slow-&gt;next-&gt;next; slow = curr-&gt;next; printf(&quot;%d-&gt;&quot;,fast-&gt;val); //2-1 printf(&quot;%d-&gt;&quot;,slow-&gt;val); //1-1 curr = slow-&gt;next-&gt;next; printf(&quot;%d-&gt;&quot;,curr-&gt;val); } } printf(&quot;NULL&quot;); } </code></pre>
[ { "answer_id": 74524820, "author": "Jilber Urbina", "author_id": 1315767, "author_profile": "https://Stackoverflow.com/users/1315767", "pm_score": 2, "selected": false, "text": " df$output <-apply(df[,-1], 1, function(x) paste(names(df)[-1][x<0], collapse = \",\"))\n df\n SUBID ABC BCD DEF output\n1 192838 4 3 -2 DEF\n2 193928 -6 -2 6 ABC,BCD\n3 205829 4 -5 9 BCD\n4 201837 3 4 4 \n id <- sapply(strsplit(sub(\"\\\\W+\", \"\", df$output), split = \"\"), function(x){\n sum(!(duplicated(x) | duplicated(x, fromLast = TRUE)))\n} )\n\n\n data.frame(SUBID = substr(df$SUBID, 1,2), output = id, string = df$output)\n SUBID output string\n 1 19 3 DEF\n 2 19 2 ABC,BCD\n 3 20 3 BCD\n 4 20 0 \n string" }, { "answer_id": 74524944, "author": "arg0naut91", "author_id": 8389003, "author_profile": "https://Stackoverflow.com/users/8389003", "pm_score": 3, "selected": true, "text": "library(dplyr)\nlibrary(tidyr)\n\ndf <- df %>% pivot_longer(-SUBID)\n\ndf1 <- df %>%\n group_by(SUBID) %>%\n summarise(output = paste(name[value < 0L], collapse = ','))\n\ndf2 <- df %>%\n group_by(SUBID = substr(SUBID, 1, 2)) %>%\n summarise(output_count = n_distinct(name[value < 0L]),\n output = paste0(output_count, ' (', paste(name[value < 0L], collapse = ','), ')'))\n df1\n\n# A tibble: 4 x 2\n SUBID output \n <int> <chr> \n1 192838 \"BCD\" \n2 193928 \"ABC,BCD\"\n3 201837 \"\" \n4 205829 \"BCD\" \n\ndf2\n\n# A tibble: 2 x 3\n SUBID output_count output \n <chr> <int> <chr> \n1 19 2 2 (BCD,ABC,BCD)\n2 20 1 1 (BCD) \n" }, { "answer_id": 74536788, "author": "Dan Adams", "author_id": 13210554, "author_profile": "https://Stackoverflow.com/users/13210554", "pm_score": 0, "selected": false, "text": "dplyr::cur_data() names() tibble library(tidyverse)\n\nd <- structure(list(SUBID = c(192838, 193928, 205829, 201837), ABC = c(4, -6, 4, 3), BCD = c(-3, -2, -5, 4), DEF = c(2, 6, 9, 4)), row.names = c(NA, -4L), class = \"data.frame\")\n\nd %>% \n rowwise() %>%\n mutate(neg_col_names = list(names(cur_data())[cur_data() < 0])) %>% \n group_by(ID_grp = str_sub(SUBID, 1, 2)) %>% \n summarize(neg_col_count = n_distinct(unlist(c(neg_col_names))))\n\n#> # A tibble: 2 × 2\n#> ID_grp neg_col_count\n#> <chr> <int>\n#> 1 19 2\n#> 2 20 1\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20021859/" ]
74,524,803
<p>I am having a hard time following this solution. I understand we set a prefix, and loop through the remainder of the array and keep chopping the prefix until prefix fully exists in each string but why are we doing <code>strs[i].indexOf(output) != 0</code> in the while loop?</p> <pre><code>public String longestCommonPrefix(String[] strs) { if(strs.length == 0) { return &quot;&quot;; } String output = strs[0]; for(int i = 1; i &lt; strs.length; i++) { while(strs[i].indexOf(output) != 0) { output = output.substring(0, output.length() - 1); } } return output; } </code></pre>
[ { "answer_id": 74524869, "author": "Joop Eggen", "author_id": 984823, "author_profile": "https://Stackoverflow.com/users/984823", "pm_score": 3, "selected": true, "text": "startWith while (!strs[i].startsWith(output)) {\n output = output.substring(0, output.length() - 1);\n }\n indexOf output strs[i] output" }, { "answer_id": 74524889, "author": "WJS", "author_id": 1552534, "author_profile": "https://Stackoverflow.com/users/1552534", "pm_score": 1, "selected": false, "text": "!= 0 > 0 -1 == 0 substring" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2624866/" ]
74,524,863
<p>I'm wondering if it has something that works like static variable inside a function in C.</p> <p>In C language we have this:</p> <pre><code>void next_x() { static int x = 0; x++; } </code></pre> <p>Variable <code>x</code> is declared and initialized inside a function. As far I know C - it can be used only in the scope of this function and it is initialized only in first call of this function.</p> <p>I need something like this in Kotlin. I have code similar to this:</p> <pre><code>private val x: Int = 0 fun getNextX() : Int { x++; return x; } </code></pre> <p>and I would like to have something like this:</p> <pre><code>fun getNextX() : Int { static val x: Int = 0 // this is not Kotlin code x++; return x; } </code></pre> <p>I want to:</p> <ol> <li>Limit <code>x</code> variable scope to emphasize that this object is only used by this function and protect it from changes from outside</li> <li>Initialize it only once</li> <li>Keep value/state between function calls</li> </ol> <p>Example above was simplified. In fact I need something like this for ArrayList with limited scope, but retaining state.</p> <p>I realize that we have singleton pattern which is almost perfect for such needs (except limited scope), but maybe Kotlin offers something else?</p>
[ { "answer_id": 74524949, "author": "Sweeper", "author_id": 5133585, "author_profile": "https://Stackoverflow.com/users/5133585", "pm_score": 2, "selected": false, "text": "object static invoke object NextX {\n private var x = 0\n operator fun invoke() = x++\n}\n object fun main() {\n println(NextX()) // 0\n println(NextX()) // 1\n println(NextX()) // 2\n}\n object x" }, { "answer_id": 74525084, "author": "Willi Mentzel", "author_id": 1788806, "author_profile": "https://Stackoverflow.com/users/1788806", "pm_score": 2, "selected": false, "text": "val foo: () -> Int = object {\n var x = 0\n fun createFunc() = fun() = x++\n}.createFunc()\n\nfoo() // 0\nfoo() // 1\n x private object" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1215291/" ]
74,524,880
<p>20/11/2022 12:00:52 2 X 15.95 15.95 USD 57 5 689 5 689 1 4111 0 Amazing Lego Team</p> <p>I need to get the position of No 4111 in the above text string, As an excel beginner any help will be greatly appreciated. Thanks.</p> <p>All of the Text Strings will have a 4 digit number like 4111 which i have to get the position for.</p> <p>Have tried using this formula to get four digit number in another column, LOOKUP(10^15,MID(A1,ROW(INDIRECT(&quot;1:&quot;&amp;LEN(A1))),5)+0) but I am looking to get position instead.</p> <p>I have tried using lookup but I could only go so far as a beginner.</p>
[ { "answer_id": 74524949, "author": "Sweeper", "author_id": 5133585, "author_profile": "https://Stackoverflow.com/users/5133585", "pm_score": 2, "selected": false, "text": "object static invoke object NextX {\n private var x = 0\n operator fun invoke() = x++\n}\n object fun main() {\n println(NextX()) // 0\n println(NextX()) // 1\n println(NextX()) // 2\n}\n object x" }, { "answer_id": 74525084, "author": "Willi Mentzel", "author_id": 1788806, "author_profile": "https://Stackoverflow.com/users/1788806", "pm_score": 2, "selected": false, "text": "val foo: () -> Int = object {\n var x = 0\n fun createFunc() = fun() = x++\n}.createFunc()\n\nfoo() // 0\nfoo() // 1\n x private object" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19833096/" ]
74,524,902
<p>The following:</p> <pre><code>print(type(0x01)) </code></pre> <p>Returns:</p> <pre><code>&lt;class 'int'&gt; </code></pre> <p>Whereas, the following:</p> <pre><code>print(0x01) </code></pre> <p>Returns</p> <pre><code>1 </code></pre> <p>Now let's say we have:</p> <pre><code>x = &quot;0x01&quot; </code></pre> <p>How do I convert x such that it returns 1 when printed?</p> <p>Thank you!</p>
[ { "answer_id": 74525063, "author": "user3273429", "author_id": 3273429, "author_profile": "https://Stackoverflow.com/users/3273429", "pm_score": 1, "selected": false, "text": "x = \"0x01\"\nprint(x)\nx = int(x, 16)\nprint(x)\n 0x01\n1\n" }, { "answer_id": 74546305, "author": "Rogith", "author_id": 15780868, "author_profile": "https://Stackoverflow.com/users/15780868", "pm_score": 0, "selected": false, "text": "x =\"0x01\"\nx = int(x, 16)\nprint(x)\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8840978/" ]
74,524,907
<p>So i have fresh Manjaro installation and only software i have is ws code and some bloatware.</p> <p>But when i want to search for extesions like C/C++ it find somethink but not what i need.</p> <p>This is what i get</p> <p><a href="https://i.stack.imgur.com/QAv8a.png" rel="nofollow noreferrer">my output</a></p> <p><a href="https://i.stack.imgur.com/lcn1P.png" rel="nofollow noreferrer">what i want</a></p> <p>I find something like product.json but i cannot find its location or anything. I tried reinstalling... nothing.</p> <p>Also I can't find it as .vsix file so i don't know what to do.</p> <p>Search for solution on internet.</p>
[ { "answer_id": 74525149, "author": "Berry", "author_id": 8996406, "author_profile": "https://Stackoverflow.com/users/8996406", "pm_score": 1, "selected": false, "text": "Extensions: Install from VSIX... ctrl + shift + p" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20371135/" ]
74,524,911
<pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;unistd.h&gt; #include &lt;ctype.h&gt; #include &lt;fcntl.h&gt; #define PATH_LINE 128 void get_pid(){ char full_path[PATH_LINE]=&quot;&quot;; int fd; char pid[6]; for(int i=0 ;i &lt;99999; i++){ fd =0; memset(full_path,0,PATH_LINE); strcat(full_path,PROC_PATH); sprintf(pid, &quot;%d&quot;, i); strcat(full_path,pid); fd = open(full_path, O_RDONLY); if(fd != -1){ printf(&quot;%s - fd [%d]\n&quot;, full_path, fd); } } } int main(void){ get_pid(); return 0; } </code></pre> <p>I expected this code to print all the PIDs I have on my computer.</p> <p>That is, it will try to open the folder /proc/PID and if it does not return an error, then it will print the PID.</p> <p>But, he prints me a lot of PIDs that don't really run on my computer...</p> <p>Is there an error in my code? I'm trying to do this without built-in structs.</p> <p>terminal output:</p> <p><a href="https://i.stack.imgur.com/PEddS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PEddS.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74525880, "author": "tedo3637", "author_id": 5740753, "author_profile": "https://Stackoverflow.com/users/5740753", "pm_score": 0, "selected": false, "text": "find /proc/ -maxdepth 1 -type d 2>/dev/null /proc/ close(fd); ulimit -n" }, { "answer_id": 74539346, "author": "Ted Lyngmo", "author_id": 7582247, "author_profile": "https://Stackoverflow.com/users/7582247", "pm_score": 1, "selected": false, "text": "0 99998 99998 opendir readdir closedir /proc #include <dirent.h> // opendir, readdir, closedir\n#include <sys/types.h>\n\n#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n\n// a function to check if a string consists of all digits\nbool all_digits(const char *str) {\n for(; *str != '\\0'; ++str) {\n if(!isdigit((unsigned char)*str)) {\n return false;\n }\n }\n return true;\n}\n\nint main(void) {\n DIR* dp = opendir(\"/proc\"); // open /proc\n if(dp) {\n struct dirent *curr; // see: man 3 readdir\n\n while((curr = readdir(dp))) { // read next directory entry\n if(all_digits(curr->d_name)) { // d_name holds the leaf name\n puts(curr->d_name); // only print if it only has digits\n }\n }\n\n closedir(dp); // finally close the directory\n }\n}\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20539260/" ]
74,524,913
<p>I've been asked to write what this codes does:</p> <pre><code>int main() { int var1,var2, *ptr; ptr=&amp;var1; var2=12; *ptr=var2; var1=var1/ *ptr; printf(&quot;%d %d&quot;, var1,var2); } </code></pre> <p>Now my question is what does this means. At first ptr stores the address of var1. Then var2 is defined as 12. the next step idk what it means and so with the last one. I finally i get printed 1 and 12. Not sure why.</p> <p>What i understood is that 12 is stored in ptr aswell. So as ptr has var1 address, var1 gets a value of 12 too. and so the finall step would be var1=12/12. And thats why i get 1 and 12 in my printf. This is just what i understood but i dont really get it and im not sure if its correct. Btw ty for undesrtanding.</p>
[ { "answer_id": 74524957, "author": "Eric Postpischil", "author_id": 298225, "author_profile": "https://Stackoverflow.com/users/298225", "pm_score": 3, "selected": true, "text": "ptr=&var1; &var1 var1 ptr = &var1 ptr var2 = 12; var2 *ptr = var2; var2 *ptr var2 *ptr ptr var1 *ptr var1 *ptr = var2 var1 var1 = var1 / *ptr; *ptr ptr var1 var1 / *ptr var1 *ptr var1 var1 / *ptr var1 = var1 / *ptr var1 printf(\"%d %d\", var1,var2); var1 var2 var1 var2" }, { "answer_id": 74524997, "author": "Vlad from Moscow", "author_id": 2877241, "author_profile": "https://Stackoverflow.com/users/2877241", "pm_score": 0, "selected": false, "text": "ptr var1 ptr=&var1;\n *ptr var1 var1 *ptr=var2;\nvar1=var1/ *ptr;\n var1 = var2;\nvar1 = var1 / var1;\n var2 12 var2=12;\n var1 1 var1 / var1 var1" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20524990/" ]
74,524,917
<p>I use R. I have dataframe like this:</p> <pre><code>dat &lt;- data.frame( group = c(1,1,1,1,1,1,2,2,2,2,2), horizon = c(1,3,5,6,7,10,1,3,5,9,10), value = c(1.0,0.9,0.8,0.6,0.3,0.0,0.5,0.6,0.8,0.9,0.8) other = c(a,a,a,a,a,a,b,b,b,b,b) ) </code></pre> <p>And i would like to add row for every horizon that is missing (2,4,8 and 9 for the first group and 2,4,6,7,8 for the second group). Values (value) for the missing horizons would be blank.</p> <p>I would like to get something like this:</p> <pre><code>datx &lt;- data.frame( group = c(1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2), horizon = c(1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10), value = c(1.0,&quot;na&quot;,0.9,&quot;na&quot;,0.8,0.6,0.3,&quot;na&quot;,&quot;na&quot;,0.0,0.5,&quot;na&quot;,0.6,&quot;na&quot;,0.8,&quot;na&quot;,&quot;na&quot;,&quot;na&quot;,0.9,0.8) other = c(a,a,a,a,a,a,a,a,a,a,b,b,b,b,b,b,b,b,b,b) ) </code></pre> <p>i.e. englarged dataset with new horizons, blank or &quot;na&quot; spaces in &quot;value&quot; variable and retained &quot;other&quot; variable.</p> <p>This is just an example. I am actually working with a much larger dataset.</p> <p>Without the groups, the problem would be much easier to solve, i would use something like this:</p> <pre><code>newdat &lt;- merge(data.frame(horizon=seq(1,10,1)),dat,all=TRUE) newdat &lt;- newdat[order(newdat$horizon),] </code></pre> <p>Thanks for help!</p>
[ { "answer_id": 74524957, "author": "Eric Postpischil", "author_id": 298225, "author_profile": "https://Stackoverflow.com/users/298225", "pm_score": 3, "selected": true, "text": "ptr=&var1; &var1 var1 ptr = &var1 ptr var2 = 12; var2 *ptr = var2; var2 *ptr var2 *ptr ptr var1 *ptr var1 *ptr = var2 var1 var1 = var1 / *ptr; *ptr ptr var1 var1 / *ptr var1 *ptr var1 var1 / *ptr var1 = var1 / *ptr var1 printf(\"%d %d\", var1,var2); var1 var2 var1 var2" }, { "answer_id": 74524997, "author": "Vlad from Moscow", "author_id": 2877241, "author_profile": "https://Stackoverflow.com/users/2877241", "pm_score": 0, "selected": false, "text": "ptr var1 ptr=&var1;\n *ptr var1 var1 *ptr=var2;\nvar1=var1/ *ptr;\n var1 = var2;\nvar1 = var1 / var1;\n var2 12 var2=12;\n var1 1 var1 / var1 var1" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20566156/" ]
74,524,974
<p>I making scroll animation progress bars, when the scroll reaches the element's width change from 0 to 78%. but there is one problem whenever I scroll again in the same height condition my width reset. I know why this happens. in fact, the range variable(i comment in JS) reassigns to 0 whenever I scroll, I don't know how to fix it. I read about Closures but couldn't understand how I must apply that to my code thanks for reading and for your time</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>//my js code const SEORange = document.getElementById("SEO"); window.addEventListener("scroll", () =&gt; { let top = SEORange.getBoundingClientRect().top; let range = 0; // the problem is here range will be reset //whenever I scroll if (top &lt; window.innerHeight * 0.905) { setInterval(() =&gt; { if (range == 78) { clearInterval; } else { range++; SEORange.style.width = range + "%"; } }, 10); } });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>/*css file*/ *{ height:100vh /*I add some height to see what happen if scroll*/ } #section2-text-container { justify-content: end; flex-basis: 50%; margin-top: 5%; } #section2-text-container form { margin-top: 10%; } .range-container { background-color: #000000; border-radius: 0 10px 10px 0; width: 90%; height: 8px; position: relative; } #section2-text-container input { appearance: none; -webkit-appearance: none; background-color: #64bfd2; width: 0; height: 4px; margin: 0 5% 0 0; position: absolute; inset: 0 0 0 0; } #section2-text-container input::-webkit-slider-thumb { appearance: none; -webkit-appearance: none; width: 0px; background: #010101; height: 0px; } #section2-text-container input::-moz-range-thumb { width: 0px; background: #04aa6d; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code> &lt;!--html file--&gt; &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;body&gt; &lt;div id="section2-text-container"&gt; &lt;form&gt; &lt;label for="SEO"&gt;SEO&lt;/label&gt;&lt;br&gt;&lt;br&gt; &lt;div class="range-container"&gt; &lt;input id="SEO" disabled type="range" value="0" /&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74525517, "author": "c0m1t", "author_id": 5289334, "author_profile": "https://Stackoverflow.com/users/5289334", "pm_score": 2, "selected": true, "text": "const SEORange = document.getElementById(\"SEO\");\nlet intervalId;\nlet range = 0;\n\nwindow.addEventListener(\"scroll\", () => {\n let top = SEORange.getBoundingClientRect().top;\n\n // If intervalId is set, it means the code has been ran once.\n if (top < window.innerHeight * 0.905 && !intervalId) {\n intervalId = setInterval(() => {\n if (range === 78) {\n clearInterval(intervalId);\n } else {\n range++;\n SEORange.style.width = range + \"%\";\n }\n }, 10);\n }\n})\n const SEORange2 = document.getElementById(\"SEO2\");\n\nwindow.addEventListener(\"scroll\", () => {\n let top = SEORange.getBoundingClientRect().top;\n\n if (top < window.innerHeight * 0.905) {\n SEORange2.classList.add(\"animate\");\n }\n});\n #SEO2 {\n height: 30px;\n width: 0;\n background-color: yellow;\n transition: width 780ms linear;\n}\n\n#SEO2.animate {\n width: 78%;\n}\n" }, { "answer_id": 74526218, "author": "Erfan Ta", "author_id": 17620112, "author_profile": "https://Stackoverflow.com/users/17620112", "pm_score": 0, "selected": false, "text": "const eagerToLearnRange = document.getElementById(\"eager-to-learn\");\nconst frontEndRange = document.getElementById(\"front-end\");\nconst SEORange = document.getElementById(\"SEO\");\n\n\nlet intervalId;\nwindow.addEventListener(\"scroll\", () => {\n let top = SEORange.getBoundingClientRect().top;\n let range = 0;\n if (top < window.innerHeight * 0.905 && !intervalId) {\n intervalId = setInterval(() => {\n if (range <= 20) {\n range++;\n SEORange.style.width = range + \"%\";\n frontEndRange.style.width = range + \"%\";\n eagerToLearnRange.style.width = range + \"%\";\n } else if (65 >= range && range >= 20) {\n frontEndRange.style.width = range + \"%\";\n eagerToLearnRange.style.width = range + \"%\";\n range++;\n } else if (65 <= range && range <= 100) {\n eagerToLearnRange.style.width = range + \"%\";\n range++;\n } else if (range === 100) {\n clearInterval(intervalId);\n }\n }, 10);\n }\n}); * { height:200vh /*add some height to show you effect */\n}\n\n#section2-text-container form {\n margin-top: 10%;\n}\n.range-container {\n background-color: #000000;\n border-radius: 0 10px 10px 0;\n width: 90%;\n height: 8px;\n position: relative;\n}\n#section2-text-container input {\n appearance: none;\n -webkit-appearance: none;\n background-color: #64bfd2;\n width: 0;\n height: 4px;\n margin: 0 5% 0 0;\n position: absolute;\n inset: 0 0 0 0;\n}\n\n#section2-text-container input::-webkit-slider-thumb {\n appearance: none;\n -webkit-appearance: none;\n width: 0px;\n height: 0px;\n}\n#section2-text-container input::-moz-range-thumb {\n width: 0px;\n height: 0px;\n\n} <DOCTYPE html>\n<html>\n<body>\n <div id=\"section2-text-container\">\n <form>\n <label for=\"eager-to-learn\">eager to learn</label> <br/><br/>\n <div class=\"range-container\">\n <input id=\"eager-to-learn\" disabled type=\"range\" value=\"0\" >\n </div>\n <br><br>\n <label for=\"front-end\">front-end</label><br><br>\n <div class=\"range-container\">\n <input id=\"front-end\" disabled type=\"range\" value=\"0\"/>\n </div>\n <br><br>\n <label for=\"SEO\">SEO</label>\n<br><br>\n <div class=\"range-container\">\n <input id=\"SEO\" disabled type=\"range\" value=\"0\"/>\n </div>\n </form>\n </div>\n</body>\n</html>" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17620112/" ]
74,524,983
<p>I want my site to look like this (not with the same text layout on the img) but the won't line up with the and there is a gap which I can't remove.</p> <p><a href="https://i.stack.imgur.com/7fwGP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7fwGP.png" alt="enter image description here" /></a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>body, html { margin: 0 auto; font-family: Verdana, Arial, Helvetica, sans-serif; } header { border: black 1px solid; border-top: none; max-width: 900px; font-size: 14px; margin: 0 auto; position: relative; max-height: 72px; } nav { font-size: 14pt; font-weight: bold; line-height: 2em; background-color: #6e99c9; max-height: 37px; color: white; border: black 1px solid; border-top: none; text-align: center; width: 900px; } a { text-decoration: none; color: white; } a:hover { text-decoration: underline; color: white; } .BannerText { font-weight: bold; color: white; margin-left: auto; margin-right: auto; } #BannerText1{ position: absolute; bottom: 8px; left: 16px; } #BannerText2{ position: absolute; bottom: 8px; right: 16px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;header&gt; &lt;img src="https://web.archive.org/web/20070223120252im_/http://www.roblox.com/images/banner2.png"&gt; &lt;a class="BannerText" id="BannerText1" href="/"&gt;ROBLOX.com&lt;/a&gt; &lt;a class="BannerText" id="BannerText2" href="/"&gt;Sign Up&lt;/a&gt; &lt;nav&gt; &lt;a href="/"&gt;Home&lt;/a&gt; &amp;nbsp;|&amp;nbsp; &lt;a href="/"&gt;Browse&lt;/a&gt; &amp;nbsp;|&amp;nbsp; &lt;a href="/"&gt;Games&lt;/a&gt; &amp;nbsp;|&amp;nbsp; &lt;/nav&gt; &lt;/header&gt;</code></pre> </div> </div> </p> <p>I've tried messing with the CSS and got slightly closer, but still didn't fully work. I've spent the past couple hours trying to fix this.</p>
[ { "answer_id": 74525144, "author": "Alen Vlahovljak", "author_id": 14085882, "author_profile": "https://Stackoverflow.com/users/14085882", "pm_score": 0, "selected": false, "text": "position: absolute body, html {\n margin: 0 auto;\n font-family: Verdana, Arial, Helvetica, sans-serif;\n}\n\nheader {\n border: black 1px solid;\n border-top: none;\n max-width: 900px;\n font-size: 14px;\n margin: 0 auto;\n position: relative;\n max-height: 72px;\n\n}\n\nnav {\n font-size: 14pt;\n font-weight: bold;\n line-height: 2em;\n background-color: #6e99c9;\n max-height: 37px;\n color: white;\n border: black 1px solid;\n border-top: none;\n text-align: center;\n width: 900px;\n}\n\n.links {\n position: absolute;\n height: 72px;\n justify-content: space-between;\n top: 0;\n display: flex;\n flex-direction: column;\n}\n\na {\n text-decoration: none;\n color: white;\n}\n\na:hover {\n text-decoration: underline;\n color: white;\n} <!doctype html>\n<html lang=\"en-US\">\n\n<head>\n <meta charset=\"utf-8\">\n <title></title>\n <meta name=\"description\" content=\"\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n \n <link rel=\"stylesheet\" href=\"css/main.css\">\n</head>\n\n<body>\n\n\n<header>\n <img src=\"https://web.archive.org/web/20070223120252im_/http://www.roblox.com/images/banner2.png\">\n <div class=\"links\">\n <a class=\"BannerText\" id=\"BannerText2\" href=\"/\">Sign Up</a>\n <a class=\"BannerText\" id=\"BannerText1\" href=\"/\">ROBLOX.com</a>\n </div>\n <nav>\n <a href=\"/\">Home</a>\n &nbsp;|&nbsp;\n <a href=\"/\">Browse</a>\n &nbsp;|&nbsp;\n <a href=\"/\">Games</a>\n &nbsp;|&nbsp;\n </nav>\n</header>\n</body>\n\n</html>" }, { "answer_id": 74525202, "author": "isherwood", "author_id": 1264804, "author_profile": "https://Stackoverflow.com/users/1264804", "pm_score": 2, "selected": true, "text": "body,\nhtml {\n margin: 0 auto;\n font-family: Verdana, Arial, Helvetica, sans-serif;\n}\n\nheader {\n border: black 1px solid;\n border-top: none;\n max-width: 900px;\n font-size: 14px;\n margin: 0 auto;\n position: relative;\n background-color: #397E79;\n background-image: url(https://web.archive.org/web/20070223120252im_/http://www.roblox.com/images/banner2.png);\n padding-top: 72px;\n}\n\nnav {\n font-size: 14pt;\n font-weight: bold;\n line-height: 2em;\n background-color: #6e99c9;\n max-height: 37px;\n color: white;\n border: black 1px solid;\n border-top: none;\n text-align: center;\n}\n\na {\n text-decoration: none;\n color: white;\n}\n\na:hover {\n text-decoration: underline;\n color: white;\n}\n\n.BannerText {\n font-weight: bold;\n color: white;\n margin-left: auto;\n margin-right: auto;\n}\n\n#BannerText1 {\n position: absolute;\n top: 48px;\n left: 16px;\n}\n\n#BannerText2 {\n position: absolute;\n top: 48px;\n right: 16px;\n} <header>\n <a class=\"BannerText\" id=\"BannerText1\" href=\"/\">ROBLOX.com</a>\n <a class=\"BannerText\" id=\"BannerText2\" href=\"/\">Sign Up</a>\n\n <nav>\n <a href=\"/\">Home</a> &nbsp;|&nbsp;\n <a href=\"/\">Browse</a> &nbsp;|&nbsp;\n <a href=\"/\">Games</a> &nbsp;|&nbsp;\n </nav>\n</header>" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74524983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19612400/" ]
74,525,000
<p>If in x or y is NA, I want to keep this row containing NA and discard the rows, where both, x and y are not NA. I tried with <code>dplyr::filter()</code>, <code>purrr::keep()</code> and more but nothing worked. It is essential to do that conditionally and not by the row number since my data set is too large for that.</p> <pre class="lang-r prettyprint-override"><code>library(tibble, quietly = T, warn.conflicts = F) library(dplyr, quietly = T, warn.conflicts = F) df &lt;- tribble( ~name, ~x, ~y, &quot;id_1&quot;, 1, NA, &quot;id_2&quot;, 3, NA, &quot;id_3&quot;, NA, 29, &quot;id_4&quot;, -99, 0, &quot;id_5&quot;, -98, 28, ) %&gt;% mutate(name = factor(name)) df #&gt; # A tibble: 5 x 3 #&gt; name x y #&gt; &lt;fct&gt; &lt;dbl&gt; &lt;dbl&gt; #&gt; 1 id_1 1 NA #&gt; 2 id_2 3 NA #&gt; 3 id_3 NA 29 #&gt; 4 id_4 -99 0 #&gt; 5 id_5 -98 28 </code></pre> <p><sup>Created on 2022-11-21 with <a href="https://reprex.tidyverse.org" rel="nofollow noreferrer">reprex v2.0.2</a></sup></p> <p>The target is to keep rows like 1 to 3.</p>
[ { "answer_id": 74525105, "author": "MrFlick", "author_id": 2372064, "author_profile": "https://Stackoverflow.com/users/2372064", "pm_score": 4, "selected": true, "text": "filter() if_any df %>% filter(if_any(everything(), is.na))\n df %>% filter(if_any(c(x, y), is.na))\ndf %>% filter(if_any(x:y, is.na))\ndf %>% filter(if_any(-name, is.na))\n" }, { "answer_id": 74525119, "author": "zx8754", "author_id": 680068, "author_profile": "https://Stackoverflow.com/users/680068", "pm_score": 2, "selected": false, "text": "df[ rowSums(is.na(df)) == 1, ]\n" }, { "answer_id": 74525315, "author": "Ruam Pimentel", "author_id": 13015865, "author_profile": "https://Stackoverflow.com/users/13015865", "pm_score": 2, "selected": false, "text": "df[!complete.cases(df),] \n\ndf[is.na(df$x) | is.na(df$y),] # if you want to specify specific columns\n library(hacksaw)\ndf %>% keep_na(x, y, .logic = 'OR')\n > # A tibble: 3 × 3\n> name x y\n> <fct> <dbl> <dbl>\n> 1 id_1 1 NA\n> 2 id_2 3 NA\n> 3 id_3 NA 29\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14736368/" ]
74,525,003
<p>I need to access <code>my_key</code> in a Pydantic <code>Field</code>, as shown below:</p> <pre><code> class MyModel(BaseModel): x: str = Field(default=None, my_key=7) def print_field_objects(self): for obj in self.something_something: # What do I use here print(obj.my_key) # ... so that i can use my_key? </code></pre> <p>I tried to see what <code>self</code> contains, like <code>self.__dict__</code> but I wasn't able to find it. Is it even possible to access <code>my_key</code>?</p> <p>I need it for my FastAPI endpoint.</p>
[ { "answer_id": 74525112, "author": "Hedde van der Heide", "author_id": 911519, "author_profile": "https://Stackoverflow.com/users/911519", "pm_score": 2, "selected": false, "text": "self.__class__.__fields__ self.x" }, { "answer_id": 74532350, "author": "Gino Mempin", "author_id": 2745495, "author_profile": "https://Stackoverflow.com/users/2745495", "pm_score": 2, "selected": true, "text": "BaseModel .schema() Field ** examples Field my_key In [4]: class MyModel(BaseModel):\n ...: x: str = Field(default=None, my_key=7)\n ...: \n\nIn [5]: MyModel.schema()\nOut[5]: \n{'title': 'MyModel',\n 'type': 'object',\n 'properties': {'x': {'title': 'X', 'my_key': 7, 'type': 'string'}}}\n ^^^^^^^^^^^^\n ||||||||||||\n In [21]: class MyModel(BaseModel):\n ...: x: str = Field(default=None, my_key=7)\n ...: y: int = Field(default=1, my_key=42)\n ...: \n ...: def print_field_objects(self):\n ...: for field_name, field in self.schema()[\"properties\"].items():\n ...: print(field[\"my_key\"])\n ...: \n\nIn [22]: m1 = MyModel()\n\nIn [23]: m1.print_field_objects()\n7\n42\n Field In [28]: m1 = MyModel()\n\nIn [29]: m1.print_field_objects()\n7\n42\n\nIn [30]: m2 = MyModel()\n\nIn [31]: m2.print_field_objects()\n7\n42\n my_key x In [35]: class MyModel(BaseModel):\n ...: x: str = Field(default=None, my_key=7)\n ...: y: int = Field(default=1, my_key=42)\n ...: \n ...: @classmethod\n ...: def print_field_objects(cls):\n ...: for field_name, field in cls.schema()[\"properties\"].items():\n ...: print(field_name, field.get(\"my_key\"))\n ...: \n\nIn [36]: MyModel.print_field_objects()\nx 7\ny 42\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19674402/" ]
74,525,008
<p>I am using windows</p> <pre><code> import cv2 ModuleNotFoundError: No module named 'cv2' </code></pre> <p>how to fix it?</p> <p>I tried</p> <pre><code>pip install opencv-contrib-python </code></pre> <pre><code>pip3 install opencv-python </code></pre> <pre><code>pip install opencv-python </code></pre> <p>etc etc, still did not work</p> <p>update: cv2 is fixed, but I am having a problem on mediapipe. it's showing like this:</p> <pre><code>ERROR: Could not find a version that satisfies the requirement mediapipe (from versions: none) ERROR: No matching distribution found for mediapipe WARNING: You are using pip version 21.3.1; however, version 22.3.1 is available. You should consider upgrading via the 'E:\python\Scripts\python.exe -m pip install --upgrade pip' command. </code></pre> <p>my python version is 3.11.0</p>
[ { "answer_id": 74525112, "author": "Hedde van der Heide", "author_id": 911519, "author_profile": "https://Stackoverflow.com/users/911519", "pm_score": 2, "selected": false, "text": "self.__class__.__fields__ self.x" }, { "answer_id": 74532350, "author": "Gino Mempin", "author_id": 2745495, "author_profile": "https://Stackoverflow.com/users/2745495", "pm_score": 2, "selected": true, "text": "BaseModel .schema() Field ** examples Field my_key In [4]: class MyModel(BaseModel):\n ...: x: str = Field(default=None, my_key=7)\n ...: \n\nIn [5]: MyModel.schema()\nOut[5]: \n{'title': 'MyModel',\n 'type': 'object',\n 'properties': {'x': {'title': 'X', 'my_key': 7, 'type': 'string'}}}\n ^^^^^^^^^^^^\n ||||||||||||\n In [21]: class MyModel(BaseModel):\n ...: x: str = Field(default=None, my_key=7)\n ...: y: int = Field(default=1, my_key=42)\n ...: \n ...: def print_field_objects(self):\n ...: for field_name, field in self.schema()[\"properties\"].items():\n ...: print(field[\"my_key\"])\n ...: \n\nIn [22]: m1 = MyModel()\n\nIn [23]: m1.print_field_objects()\n7\n42\n Field In [28]: m1 = MyModel()\n\nIn [29]: m1.print_field_objects()\n7\n42\n\nIn [30]: m2 = MyModel()\n\nIn [31]: m2.print_field_objects()\n7\n42\n my_key x In [35]: class MyModel(BaseModel):\n ...: x: str = Field(default=None, my_key=7)\n ...: y: int = Field(default=1, my_key=42)\n ...: \n ...: @classmethod\n ...: def print_field_objects(cls):\n ...: for field_name, field in cls.schema()[\"properties\"].items():\n ...: print(field_name, field.get(\"my_key\"))\n ...: \n\nIn [36]: MyModel.print_field_objects()\nx 7\ny 42\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17919391/" ]
74,525,059
<p>It's probably easiest to explain if I post some code:</p> <pre><code>&lt;article&gt; &lt;img class=&quot;service_pic&quot; src=&quot;image.png&quot; title=&quot;UNFILLED&quot; /&gt; &lt;!-- I WANT THIS (ODD) IMAGE FLOATED RIGHT --&gt; &lt;div class=&quot;service_text&quot;&gt; &lt;h2&gt;TITLE&lt;/h2&gt; &lt;p&gt;CONTENT&lt;/p&gt; &lt;/div&gt; &lt;/article&gt; &lt;article&gt; &lt;img class=&quot;service_pic&quot; src=&quot;image.png&quot; title=&quot;UNFILLED&quot; /&gt; &lt;!-- I WANT THIS (EVEN) ONE FLOATED LEFT --&gt; &lt;div class=&quot;service_text&quot;&gt; &lt;h2&gt;TITLE&lt;/h2&gt; &lt;p&gt;CONTENT&lt;/p&gt; &lt;/div&gt; &lt;/article&gt; &lt;article&gt; &lt;img class=&quot;service_pic&quot; src=&quot;image.png&quot; title=&quot;UNFILLED&quot; /&gt; &lt;!-- I WANT THIS (ODD) ONE FLOATED RIGHT AGAIN) --&gt; &lt;div class=&quot;service_text&quot;&gt; &lt;h2&gt;TITLE&lt;/h2&gt; &lt;p&gt;CONTENT&lt;/p&gt; &lt;/div&gt; &lt;/article&gt; </code></pre> <p>Thanks!</p> <p>I am aware of nth-child and nth-of-type but I don't know how to implement them. I know that I could theoretically add .left and .right to each service_pic and service_text but thats a lot of repetitive code. And its hard coded and must be edited every time a new is added.</p>
[ { "answer_id": 74525204, "author": "YasinDemirkol", "author_id": 20540015, "author_profile": "https://Stackoverflow.com/users/20540015", "pm_score": 1, "selected": false, "text": "article:nth-child(odd){\nfloat: right;\n}\n\narticle:nth-child(even){\nfloat: left;\n}\n" }, { "answer_id": 74545556, "author": "Cédric", "author_id": 17684809, "author_profile": "https://Stackoverflow.com/users/17684809", "pm_score": 0, "selected": false, "text": "article:nth-child(odd) article:nth-child(2n+1) article:nth-child(even) article:nth-child(2n) article {\n display: flex;\n align-items: center;\n border: 1px solid black;\n width: fit-content;\n margin: 10px;\n}\n\narticle .service_text {\n padding: 10px;\n}\n\narticle:nth-child(2n+1) img {\n order: 2;\n} <article>\n <img class=\"service_pic\" src=\"https://via.placeholder.com/100x200\" title=\"UNFILLED\" />\n <!-- I WANT THIS (ODD) IMAGE FLOATED RIGHT -->\n <div class=\"service_text\">\n <h2>TITLE</h2>\n <p>CONTENT</p>\n </div>\n</article>\n\n<article>\n <img class=\"service_pic\" src=\"https://via.placeholder.com/50x50\" title=\"UNFILLED\" />\n <!-- I WANT THIS (EVEN) ONE FLOATED LEFT -->\n <div class=\"service_text\">\n <h2>TITLE</h2>\n <p>CONTENT</p>\n </div>\n</article>\n\n<article>\n <img class=\"service_pic\" src=\"https://via.placeholder.com/200x100\" title=\"UNFILLED\" />\n <!-- I WANT THIS (ODD) ONE FLOATED RIGHT AGAIN) -->\n <div class=\"service_text\">\n <h2>TITLE</h2>\n <p>CONTENT</p>\n </div>\n</article>" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18522786/" ]
74,525,090
<p>I have a function that runs several commands and each of them take awhile to finish. I added <code>set -x</code> at the beginning so that I can see exactly which command is executing while it's running. Then at the end I disable it with <code>set +x</code>.</p> <pre><code>function toolong() { set -x; takes_a_long_time &amp;&amp;\ takes_also_a_long_time &amp;&amp;\ # &lt;=== Hangs here, for example takes_more time set +x; } </code></pre> <p>My problem is that sometimes I need to kill my process if one of the functions hangs or is taking too long. When that happens i'm left with a bunch of crap in my shell as <code>set +x</code> never got called.</p> <p>Is there a way to limit the scope of <code>set -x</code> only to the duration of a specific function or otherwise guarantee that <code>set +x</code> always gets called?</p>
[ { "answer_id": 74525211, "author": "KamilCuk", "author_id": 9072753, "author_profile": "https://Stackoverflow.com/users/9072753", "pm_score": 2, "selected": false, "text": "toolong() {\n (\n set -x;\n takes_a_long_time &&\n takes_also_a_long_time &&\n takes_more time\n )\n}\n toolong() (\n set -x;\n takes_a_long_time &&\n takes_also_a_long_time &&\n takes_more time\n)\n" }, { "answer_id": 74525294, "author": "Fravadona", "author_id": 3387716, "author_profile": "https://Stackoverflow.com/users/3387716", "pm_score": 1, "selected": false, "text": "trap toolong trap '[[ \" ${FUNCNAME[*]} \" == *\\ toolong\\ * ]] && set +x' INT\n trap 'set +x' INT\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/147390/" ]
74,525,116
<p>I have Russian and English language dictionary and I want to sync them dynamically.</p> <p>Let's say I have two objects:</p> <pre><code>const ru = { 'page.main.hello': 'Привет!' } </code></pre> <pre><code>const en = { 'page.main.hello': 'Hi!' } </code></pre> <p>If I add key to &quot;ru&quot; object then I need that TypeScript makes me change &quot;en&quot; object and add there the same key.</p> <pre><code>const ru = { 'page.main.hello': 'Привет!' } const en = { 'page.main.hello': 'Hi!', 'page.main.bye': 'Bye!' } </code></pre> <p>Needed result: This leads to typing errors because key 'page.main.bye' is not presented in &quot;ru&quot; dictionary.</p> <p>I've tried to do something like <code>ru: keyof typeof en</code> and <code>en: keyof typeof ru</code> but because of self reference it doesn't work.</p> <p>I do not want to choose one of the objects as base object because it won't solve the unsynced objects problem.</p>
[ { "answer_id": 74525199, "author": "Drew Pereli", "author_id": 6789286, "author_profile": "https://Stackoverflow.com/users/6789286", "pm_score": 1, "selected": true, "text": "interface Language {\n 'page.main.hello': string;\n 'page.main.bye': string;\n}\n\nconst ru: Language = {\n // Will raise type error because the 'page.main.bye' key is missing\n 'page.main.hello': 'Привет!'\n}\n\nconst en: Language = {\n 'page.main.hello': 'Hi!',\n 'page.main.bye': 'Bye!'\n}\n" }, { "answer_id": 74543865, "author": "Александр Невский", "author_id": 20566186, "author_profile": "https://Stackoverflow.com/users/20566186", "pm_score": 1, "selected": false, "text": "const ru: Record<keyof typeof en, string> = {\n 'page.main.hello': 'Привет!'\n}\n\n\nconst en = {\n 'page.main.hello': 'Hi!',\n 'page.main.bye': 'Bye!'\n}\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20566186/" ]
74,525,137
<p>i want to take a random string of the array and should count the consonants of the random string. Problem is it did not count the letters from array_rand() Here is what i get at this point:</p> <pre><code>&lt;?php $woerter = [&quot;Maus&quot;, &quot;Automobil&quot;, &quot;Schifffahrt&quot;, &quot;Hund&quot;, &quot;Katze&quot;, &quot;Ziege&quot;, &quot;Stanniolpapier&quot;, &quot;Elefant&quot;, &quot;Isopropylalkohol&quot;, &quot;Schwimmbad&quot;]; $random=array_rand($woerter); $konsonanten = [&quot;b&quot;,&quot;c&quot;,&quot;d&quot;,&quot;f&quot;,&quot;g&quot;,&quot;h&quot;,&quot;j&quot;,&quot;k&quot;,&quot;l&quot;,&quot;m&quot;,&quot;n&quot;,&quot;p&quot;,&quot;q&quot;,&quot;r&quot;,&quot;s&quot;,&quot;t&quot;,&quot;u&quot;,&quot;v&quot;,&quot;w&quot;,&quot;x&quot;,&quot;y&quot;,&quot;z&quot;, &quot;B&quot;,&quot;C&quot;,&quot;D&quot;,&quot;F&quot;,&quot;G&quot;,&quot;H&quot;,&quot;J&quot;,&quot;K&quot;,&quot;L&quot;,&quot;M&quot;,&quot;N&quot;,&quot;P&quot;,&quot;Q&quot;,&quot;R&quot;,&quot;S&quot;,&quot;T&quot;,&quot;U&quot;,&quot;V&quot;,&quot;W&quot;,&quot;X&quot;,&quot;Y&quot;,&quot;Z&quot;]; $zaehler = 0; if(in_array($woerter[$random], $konsonanten)) { $zaehler++; } echo &quot;Das Wort \&quot;$woerter[$random]\&quot; enthält $zaehler Zeichen, die keine Vokale sind.&quot;; ?&gt; </code></pre>
[ { "answer_id": 74525201, "author": "Barmar", "author_id": 1491895, "author_profile": "https://Stackoverflow.com/users/1491895", "pm_score": 3, "selected": true, "text": "$word = $woerter[$random];\nfor ($i = 0; $i < strlen($word); $i++) {\n if (in_array($word[$i], $konsonanten)) {\n $zaehler++;\n }\n}\n" }, { "answer_id": 74526806, "author": "mickmackusa", "author_id": 2943403, "author_profile": "https://Stackoverflow.com/users/2943403", "pm_score": 1, "selected": false, "text": "in_array() mb_strlen() strlen() foreach ($woerter as $word) {\n echo \"Consonants found in $word: \" . strlen(str_ireplace(['a', 'e', 'i', 'o', 'u'], '', $word)) . \"\\n\";\n}\n Consonants found in Maus: 2\nConsonants found in Automobil: 4\nConsonants found in Schifffahrt: 9\nConsonants found in Hund: 3\nConsonants found in Katze: 3\nConsonants found in Ziege: 2\nConsonants found in Stanniolpapier: 8\nConsonants found in Elefant: 4\nConsonants found in Isopropylalkohol: 10\nConsonants found in Schwimmbad: 8\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20342816/" ]
74,525,138
<p>I have a set of objects (product data) that I have sorted from an API - the objects contain repeat keys and repeat arrays of information as a product can have many categories and subcategories.</p> <pre><code>{ &quot;category&quot;:&quot;e-liquid&quot;, &quot;subcategories&quot;:[ { &quot;attributes&quot;:{ &quot;name&quot;:&quot;50ml&quot;, &quot;id&quot;:19 } }, { &quot;attributes&quot;:{ &quot;name&quot;:&quot;100ml&quot;, &quot;id&quot;:18 } }, ], } { &quot;category&quot;:&quot;e-liquid&quot;, &quot;subcategories&quot;:[ { &quot;attributes&quot;:{ &quot;name&quot;:&quot;50ml&quot;, &quot;id&quot;:19 } }, { &quot;attributes&quot;:{ &quot;name&quot;:&quot;100ml&quot;, &quot;id&quot;:18 } }, ], } { &quot;category&quot;:&quot;e-liquid&quot;, &quot;subcategories&quot;:[ { &quot;attributes&quot;:{ &quot;name&quot;:&quot;50ml&quot;, &quot;id&quot;:19 } } ] } { &quot;category&quot;:&quot;hardware&quot;, &quot;subcategories&quot;:[ { &quot;attributes&quot;:{ &quot;name&quot;:&quot;tanks&quot;, &quot;id&quot;:15 } } ] } { &quot;category&quot;:&quot;hardware&quot;, &quot;subcategories&quot;:[ { &quot;attributes&quot;:{ &quot;name&quot;:&quot;tanks&quot;, &quot;id&quot;:15 } }, { &quot;attributes&quot;:{ &quot;name&quot;:&quot;coils&quot;, &quot;id&quot;:14 } } ] } </code></pre> <p>Each JSON object above represents an individual product.</p> <p>I want to be able to merge/reduce all subcategories uniquely by their category key i.e. e-liquid, hardware or whatever else gets thrown at it into a singular flat object or array, one for each category I suppose. Something like:</p> <pre><code>{ &quot;category&quot;:&quot;e-liquid&quot;, &quot;subcategories&quot;:[ &quot;50ml&quot;, &quot;100ml&quot;, &quot;150ml&quot;, &quot;200ml&quot;, &quot;...anything else&quot; ] } { &quot;category&quot;: &quot;hardware&quot;, &quot;subcategories&quot;:[ &quot;coils&quot;, &quot;tanks&quot;, &quot;batteries&quot;, &quot;...whatever else&quot; ] } </code></pre> <p>Any insight is appreciated. Been searching stackoverflow for a while but nothing seems to have cropped up - already tried a few solutions from similarly worded questions, but often merges were too shallow, and I can't wrap my head around how I would deep merge (assuming that's what's needed here). My lodash isn't working in my nuxt config hence why I specifically am asking for non-lodash solutions if possible.</p>
[ { "answer_id": 74525480, "author": "Andrew Parks", "author_id": 5898421, "author_profile": "https://Stackoverflow.com/users/5898421", "pm_score": 2, "selected": true, "text": "const data = [{\"category\":\"e-liquid\",\"subcategories\":[{\"attributes\":{\"name\":\"50ml\",\"id\":19}},{\"attributes\":{\"name\":\"100ml\",\"id\":18}}]},{\"category\":\"e-liquid\",\"subcategories\":[{\"attributes\":{\"name\":\"50ml\",\"id\":19}},{\"attributes\":{\"name\":\"100ml\",\"id\":18}}]},{\"category\":\"e-liquid\",\"subcategories\":[{\"attributes\":{\"name\":\"50ml\",\"id\":19}}]},{\"category\":\"hardware\",\"subcategories\":[{\"attributes\":\"tanks\",\"id\":15}]},{\"category\":\"hardware\",\"subcategories\":[{\"attributes\":\"tanks\",\"id\":15},{\"attributes\":\"coils\",\"id\":14}]}];\n\nconst r = [...new Set(data.map(i=>i.category))].map(i=>({\n category:i,\n subcategories:[...new Set(data.filter(({category:c})=>c===i)\n .flatMap(({subcategories:s})=>s.map(({attributes:a})=>a.name??a)))]\n}));\n\nconsole.log(r);" }, { "answer_id": 74525490, "author": "Asraf", "author_id": 20361860, "author_profile": "https://Stackoverflow.com/users/20361860", "pm_score": 1, "selected": false, "text": "Set() const obj = [{ \"category\":\"e-liquid\", \"subcategories\":[ { \"attributes\":{ \"name\":\"50ml\", \"id\":19 } }, { \"attributes\":{ \"name\":\"100ml\", \"id\":18 } }, ], }, { \"category\":\"e-liquid\", \"subcategories\":[ { \"attributes\":{ \"name\":\"50ml\", \"id\":19 } }, { \"attributes\":{ \"name\":\"100ml\", \"id\":18 } }, ], }, { \"category\":\"e-liquid\", \"subcategories\":[ { \"attributes\":{ \"name\":\"50ml\", \"id\":19 } } ] }, { \"category\":\"hardware\", \"subcategories\":[ { \"attributes\":\"tanks\", \"id\":15 } ] }, { \"category\":\"hardware\", \"subcategories\":[ { \"attributes\":\"tanks\", \"id\":15 }, { \"attributes\":\"coils\", \"id\":14 }]}];\n\nconst subCat = item => item.map(it => it.attributes.name || it.attributes);\nconst res = obj.reduce((a, {category, subcategories}) => {\nif (a[category]) return {...a, [category]: {category, subcategories: [...new Set([...a[category].subcategories, ...subCat(subcategories)])]}}\n\nreturn {...a, [category]: {category, subcategories: [...new Set([...subCat(subcategories)])]}};\n},{});\n\nconsole.log(Object.values(res));" }, { "answer_id": 74525535, "author": "danh", "author_id": 294949, "author_profile": "https://Stackoverflow.com/users/294949", "pm_score": 0, "selected": false, "text": "subCatValue reduce const data = theAPIdata();\n\nconst subCatValue = {\n 'e-liquid': obj => obj.attributes.name,\n 'hardware': obj => obj.attributes\n}\n\nconst index = data.reduce((acc, product) => {\n acc[product.category] ??= { category: product.category, subcategories: [] };\n // subCatValue[product.category] is a function that plucks the value we need\n // mapping it over the subcategory array produces an array of salient values\n const values = product.subcategories.map(subCatValue[product.category]);\n acc[product.category].subcategories.push(...values) \n return acc;\n}, {});\n\nconst values = Object.values(index);\n\n// go through again, removing duplicate subcategories\nvalues.forEach(v => {\n v.subcategories = Array.from(new Set(v.subcategories))\n});\n\nconsole.log(values);\n\nfunction theAPIdata() {\n return [{\n \"category\": \"e-liquid\",\n \"subcategories\": [{\n \"attributes\": {\n \"name\": \"50ml\",\n \"id\": 19\n }\n },\n {\n \"attributes\": {\n \"name\": \"100ml\",\n \"id\": 18\n }\n },\n ],\n },\n\n {\n \"category\": \"e-liquid\",\n \"subcategories\": [{\n \"attributes\": {\n \"name\": \"50ml\",\n \"id\": 19\n }\n },\n {\n \"attributes\": {\n \"name\": \"100ml\",\n \"id\": 18\n }\n },\n ],\n },\n\n {\n \"category\": \"e-liquid\",\n \"subcategories\": [{\n \"attributes\": {\n \"name\": \"50ml\",\n \"id\": 19\n }\n }]\n },\n\n {\n \"category\": \"hardware\",\n \"subcategories\": [{\n \"attributes\": \"tanks\",\n \"id\": 15\n }]\n },\n\n {\n \"category\": \"hardware\",\n \"subcategories\": [{\n \"attributes\": \"tanks\",\n \"id\": 15\n },\n {\n \"attributes\": \"coils\",\n \"id\": 14\n }\n ]\n }\n ];\n}" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3430526/" ]
74,525,159
<p>I am extremely new to vba, I have a column A in sheet 1 and column B in sheet 2. I want if a cell in column A sheet 1 changes, then a cell in column B sheet 2 should change also.</p> <pre><code>Private Sub Worksheet_Change (ByVal Target As Range) If Not Intersect(Target, Range(&quot;A:A&quot;)) Is Nothing Then Sheets(&quot;Sheet2&quot;).Range(&quot;B:B&quot;).ClearContents End If End Sub </code></pre> <p>I have tried this but it just clears the whole column.</p> <p>Any help will be appreciated.</p>
[ { "answer_id": 74525480, "author": "Andrew Parks", "author_id": 5898421, "author_profile": "https://Stackoverflow.com/users/5898421", "pm_score": 2, "selected": true, "text": "const data = [{\"category\":\"e-liquid\",\"subcategories\":[{\"attributes\":{\"name\":\"50ml\",\"id\":19}},{\"attributes\":{\"name\":\"100ml\",\"id\":18}}]},{\"category\":\"e-liquid\",\"subcategories\":[{\"attributes\":{\"name\":\"50ml\",\"id\":19}},{\"attributes\":{\"name\":\"100ml\",\"id\":18}}]},{\"category\":\"e-liquid\",\"subcategories\":[{\"attributes\":{\"name\":\"50ml\",\"id\":19}}]},{\"category\":\"hardware\",\"subcategories\":[{\"attributes\":\"tanks\",\"id\":15}]},{\"category\":\"hardware\",\"subcategories\":[{\"attributes\":\"tanks\",\"id\":15},{\"attributes\":\"coils\",\"id\":14}]}];\n\nconst r = [...new Set(data.map(i=>i.category))].map(i=>({\n category:i,\n subcategories:[...new Set(data.filter(({category:c})=>c===i)\n .flatMap(({subcategories:s})=>s.map(({attributes:a})=>a.name??a)))]\n}));\n\nconsole.log(r);" }, { "answer_id": 74525490, "author": "Asraf", "author_id": 20361860, "author_profile": "https://Stackoverflow.com/users/20361860", "pm_score": 1, "selected": false, "text": "Set() const obj = [{ \"category\":\"e-liquid\", \"subcategories\":[ { \"attributes\":{ \"name\":\"50ml\", \"id\":19 } }, { \"attributes\":{ \"name\":\"100ml\", \"id\":18 } }, ], }, { \"category\":\"e-liquid\", \"subcategories\":[ { \"attributes\":{ \"name\":\"50ml\", \"id\":19 } }, { \"attributes\":{ \"name\":\"100ml\", \"id\":18 } }, ], }, { \"category\":\"e-liquid\", \"subcategories\":[ { \"attributes\":{ \"name\":\"50ml\", \"id\":19 } } ] }, { \"category\":\"hardware\", \"subcategories\":[ { \"attributes\":\"tanks\", \"id\":15 } ] }, { \"category\":\"hardware\", \"subcategories\":[ { \"attributes\":\"tanks\", \"id\":15 }, { \"attributes\":\"coils\", \"id\":14 }]}];\n\nconst subCat = item => item.map(it => it.attributes.name || it.attributes);\nconst res = obj.reduce((a, {category, subcategories}) => {\nif (a[category]) return {...a, [category]: {category, subcategories: [...new Set([...a[category].subcategories, ...subCat(subcategories)])]}}\n\nreturn {...a, [category]: {category, subcategories: [...new Set([...subCat(subcategories)])]}};\n},{});\n\nconsole.log(Object.values(res));" }, { "answer_id": 74525535, "author": "danh", "author_id": 294949, "author_profile": "https://Stackoverflow.com/users/294949", "pm_score": 0, "selected": false, "text": "subCatValue reduce const data = theAPIdata();\n\nconst subCatValue = {\n 'e-liquid': obj => obj.attributes.name,\n 'hardware': obj => obj.attributes\n}\n\nconst index = data.reduce((acc, product) => {\n acc[product.category] ??= { category: product.category, subcategories: [] };\n // subCatValue[product.category] is a function that plucks the value we need\n // mapping it over the subcategory array produces an array of salient values\n const values = product.subcategories.map(subCatValue[product.category]);\n acc[product.category].subcategories.push(...values) \n return acc;\n}, {});\n\nconst values = Object.values(index);\n\n// go through again, removing duplicate subcategories\nvalues.forEach(v => {\n v.subcategories = Array.from(new Set(v.subcategories))\n});\n\nconsole.log(values);\n\nfunction theAPIdata() {\n return [{\n \"category\": \"e-liquid\",\n \"subcategories\": [{\n \"attributes\": {\n \"name\": \"50ml\",\n \"id\": 19\n }\n },\n {\n \"attributes\": {\n \"name\": \"100ml\",\n \"id\": 18\n }\n },\n ],\n },\n\n {\n \"category\": \"e-liquid\",\n \"subcategories\": [{\n \"attributes\": {\n \"name\": \"50ml\",\n \"id\": 19\n }\n },\n {\n \"attributes\": {\n \"name\": \"100ml\",\n \"id\": 18\n }\n },\n ],\n },\n\n {\n \"category\": \"e-liquid\",\n \"subcategories\": [{\n \"attributes\": {\n \"name\": \"50ml\",\n \"id\": 19\n }\n }]\n },\n\n {\n \"category\": \"hardware\",\n \"subcategories\": [{\n \"attributes\": \"tanks\",\n \"id\": 15\n }]\n },\n\n {\n \"category\": \"hardware\",\n \"subcategories\": [{\n \"attributes\": \"tanks\",\n \"id\": 15\n },\n {\n \"attributes\": \"coils\",\n \"id\": 14\n }\n ]\n }\n ];\n}" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20566736/" ]
74,525,217
<p>I have a data.table with two columns &quot;From&quot; and &quot;To&quot; as follows:</p> <pre><code>data.table(From = c(1,1,1,1,2,2,2,2,3,3,3,4,4,5), To = c(3,4,5,6,3,4,5,6,4,5,6,5,6,6)) </code></pre> <p>The data.table will always be sorted as shown in the example above, with &quot;From&quot; and &quot;To&quot; values increasing from smallest to largest.</p> <p>I need to find a 'path' starting from the first 'From' (which will always be '1'), through to the last 'To' value, subject to always choosing the lowest 'To' value. In the above example, I would have 1 --&gt; 3, then 3 --&gt; 4, then 4 --&gt; 5, then finally 5 --&gt; 6.</p> <p>I then want to return in a vector 1, 3, 4, 5 and 6, representing the linked values.</p> <p>The only way that I can think of doing it is using a while or for loop and looping through each group of 'From' values and iteratively choosing the smallest. That seems inefficient though and will probably be very slow on my actual data set which is over 100,000 rows long.</p> <p>Are there any data.table-like solutions? I also thought that maybe igraph would have a method for this, but I must admit that I currently have pretty much zero knowledge of this function.</p> <p>Any help would be greatly appreciated.</p> <p>Thanks, Phil</p> <p>EDIT:</p> <p>Thanks for all the responses so far. My example / explanation wasn't a great one sorry, as I didn't explain that the 'From' / 'To' pairs don't need to go all the way through to the end value of the 'To' column.</p> <p>Using the example from the comments below:</p> <pre><code>dt &lt;- data.table(From = c(1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 5), To = c(3, 4, 5, 6, 3, 4, 5, 6, 5, 6, 6)) </code></pre> <p>The output would simply be a vector of c(1, 3), as it will start at 1, choose the lowest value which is 3, and then because there are no 'From' values of '3', it wouldn't continue any further.</p> <p>Another example:</p> <pre><code>dt &lt;- data.table(From = c(1,1,1,2,2,3,3,4,4), To = c(2,3,4,5,6,4,7,8,9)) </code></pre> <p>The intended output here is a vector c(1,2,5); following the path 1 --&gt; 2, then 2 --&gt; 5, at which point it stops as there is no '5' value in the &quot;From&quot; column.</p> <p>Hopefully that makes sense and apologies for the lack of clarity in the original question.</p> <p>Thanks, Phil</p>
[ { "answer_id": 74525414, "author": "ThomasIsCoding", "author_id": 12158757, "author_profile": "https://Stackoverflow.com/users/12158757", "pm_score": 3, "selected": true, "text": "dt %>%\n group_by(From) %>%\n slice_min(To) %>%\n graph_from_data_frame() %>%\n ego(\n order = sum((m <- membership(components(.))) == m[names(m) == \"1\"]),\n nodes = \"1\",\n mode = \"out\"\n ) %>%\n pluck(1) %>%\n names() %>%\n as.numeric()\n subcomponent dt %>%\n group_by(From) %>%\n slice_min(To) %>%\n graph_from_data_frame() %>%\n subcomponent(v = \"1\", mode = \"out\") %>%\n names() %>%\n as.integer()\n [1] 1 3\n [1] 1 2 5\n" }, { "answer_id": 74525840, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 2, "selected": false, "text": "shift NULL dt[, .(frst = first(To)), From][\n , if(all((frst %in% From)[1:(.N - 1)])){\n c(1, unique(frst[From == shift(frst, type = \"lag\", fill = T)]))}]\n[1] 1 3 4 5 6\n" }, { "answer_id": 74535142, "author": "jblood94", "author_id": 9463489, "author_profile": "https://Stackoverflow.com/users/9463489", "pm_score": 1, "selected": false, "text": "library(data.table)\nlibrary(igraph)\nlibrary(purrr)\n\ndt <- data.table(\n From = c(1, 1, 1, 1, 2, 2, 4, 5),\n To = c(3, 4, 5, 6, 4, 6, 6, 6)\n)\n\nfPath1 <- function(dt) {\n setorder(dt, From, To)[, wt := fifelse(rleid(To)==1,1,Inf), From] %>%\n graph_from_data_frame() %>%\n set_edge_attr(name = \"weight\", value = dt[, wt]) %>%\n shortest_paths(min(dt[, From]), max(dt[, To])) %>%\n pluck(1) %>%\n unlist(use.names = FALSE)\n}\n\nfPath2 <- function(dt) {\n dt[, .SD[which.min(To)], From] %>%\n graph_from_data_frame() %>%\n shortest_paths(min(dt[, From]), max(dt[, To])) %>%\n pluck(1) %>%\n unlist(use.names = FALSE)\n}\n\nfPath3 <- function(dt) {\n dt[, .(frst = first(To)), From][\n , if(all((frst %in% From)[1:(.N - 1)])){\n c(1, unique(frst[From == shift(frst, type = \"lag\", fill = T)]))}]\n}\n\nfPath1(dt)\n#> [1] 1 6\nfPath2(dt)\n#> Warning in shortest_paths(., min(dt[, From]), max(dt[, To])): At core/paths/\n#> unweighted.c:368 : Couldn't reach some vertices.\n#> integer(0)\nfPath3(dt)\n#> NULL\n igraph fPath4 <- function(dt) {\n g <- graph_from_data_frame(dt)\n E(g)$weight <- (dt$To - dt$From)^2\n as.integer(V(g)[shortest_paths(g, V(g)[1], V(g)[name == dt$To[nrow(dt)]])$vpath[[1]]]$name)\n}\n\nfPath4(dt)\n#> [1] 1 4 6\n" }, { "answer_id": 74552247, "author": "clp", "author_id": 3604103, "author_profile": "https://Stackoverflow.com/users/3604103", "pm_score": 0, "selected": false, "text": "n <- 1E6\ndf1 <- data.frame(from=sample(n), to=sample(n))\npath <- c()\nsystem.time(\nfor (i in seq(nrow(df1)) ){\n path[length(path) + 1] <- df1[i, \"to\"] # avoid copying.\n}\n)\nmean(path)\nlength(path)\n [1] 500000.5\n[1] 1000000\n ## Select min(To) by From.\nif (nrow(df) > 0) { df2 <- setNames(aggregate(df$To, list(df$From), \"min\"), c(\"From\", \"To\") )\n} else df2 <- df\n ## Let tt is maximal outgoing node upto now.\npath <- df2[1,1]\ntt <- df2[1,1]\nfor (i in seq_len(nrow(df2))){\n if (df2[i, 1] < tt) next\n else if (df2[i,1] == tt) { tt <- df2[i, 2]\n path[length(path) + 1] <- df2[i, 2]\n }\n else break\n}\nhead(path)\n [1] 1 3 4 5 6 , df as in first example.\n[1] 1 2 5 , df as in another example.\n" }, { "answer_id": 74589335, "author": "clp", "author_id": 3604103, "author_profile": "https://Stackoverflow.com/users/3604103", "pm_score": 2, "selected": false, "text": "Igraph subcomponents() graph_from_data_frame graph_from_edgelist(as.matrix(...)) dt2 <- setNames(aggregate(dt$To, list(dt$From), \"min\"), c(\"From\", \"To\") )\ng <- graph_from_edgelist(as.matrix(dt2), directed=TRUE) \nas.numeric(as_ids(subcomponent(g, 1, mode=\"out\")))\n dt2 <- setNames(aggregate(dt$To, list(dt$From), \"min\"), c(\"From\", \"To\") )\ng <- graph_from_data_frame(dt2, directed=TRUE) \nas.numeric(as_ids(subcomponent(g, 1, mode=\"out\")))\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6720088/" ]
74,525,244
<p>I am working on a page of mine. The aim is that when I click on the image of apples, everything except for the rest of my images gets set to a display of none.</p> <p>Here is my code:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>// hideAll() hides everything except the images in the fruits class. function hideAll() { let fruit = document.querySelectorAll("div.main div.fruits"); let mainContainer = document.querySelectorAll("div.main"); mainContainer[0].style.display = 'none'; for (i = 0; i &lt; fruit.length; i++) { fruit[i].style.display = 'block'; //fruit[i].style.setProperty('display', 'block', '!important'); //This did not work } }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.fruits { display: none; } img { width: 100px; height: 100px; } .Categories { padding: 5px 5px 5px 5px; background-color: red; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="main"&gt; &lt;h1&gt;Main Page&lt;/h1&gt; &lt;div class="base"&gt; &lt;h2&gt;Fruit Categories&lt;/h2&gt; &lt;div class="some-content"&gt; &lt;p&gt;This page contains some fruit information.&lt;/p&gt; &lt;div class="Categories"&gt; &lt;p&gt;We have apples, bananas, oranges, etc.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;img src="https://foodprint.org/wp-content/uploads/2018/10/IMG_3392-e1539129880189.jpg" onclick="hideAll();"&gt; &lt;div class="element-container"&gt; &lt;div class="fruits"&gt; &lt;img src="https://foodprint.org/wp-content/uploads/2018/10/IMG_3392-e1539129880189.jpg"&gt; &lt;/div&gt; &lt;div class="fruits"&gt; &lt;img src="https://foodprint.org/wp-content/uploads/2018/10/imageedit_127_5581342771.jpg"&gt; &lt;/div&gt; &lt;div class="fruits"&gt; &lt;img src="https://i0.wp.com/moodymoons.com/wp-content/uploads/2016/02/img_8986.jpg?fit=4560%2C3000&amp;ssl=1"&gt; &lt;/div&gt; &lt;div class="fruits"&gt; &lt;img src="https://www.naturalhealth365.com/wp-content/uploads/2016/04/blueberries.jpg"&gt; &lt;/div&gt; &lt;div class="fruits"&gt; &lt;img src="https://th.bing.com/th/id/OIP.gBifOTB-F-wBTx3bzYPiGgHaE-?pid=ImgDet&amp;rs=1"&gt; &lt;/div&gt; &lt;div class="fruits"&gt; &lt;img src="https://th.bing.com/th/id/OIP.3yrzbKoKIgyR7eBhHma26AHaGm?pid=ImgDet&amp;rs=1"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>Basically, all of the images contained within the div class of fruits (6 images in total) needs to get set to a display of &quot;block&quot;. Everything else gets set to a display of none (when the apple image is clicked).</p> <p>Since there are many divs (and nested divs) within the main class, I thought that I could set the entire main class to a display of none. Then, I could set all of the elements within the fruits class to a display of block. I even tried using the !important keyword within the fruits class to override the effect of setting everything within the main div to none but that did not seem to do the trick.</p> <p>Is there any way of targeting css for every descendant of a div except for the one specified?</p>
[ { "answer_id": 74525414, "author": "ThomasIsCoding", "author_id": 12158757, "author_profile": "https://Stackoverflow.com/users/12158757", "pm_score": 3, "selected": true, "text": "dt %>%\n group_by(From) %>%\n slice_min(To) %>%\n graph_from_data_frame() %>%\n ego(\n order = sum((m <- membership(components(.))) == m[names(m) == \"1\"]),\n nodes = \"1\",\n mode = \"out\"\n ) %>%\n pluck(1) %>%\n names() %>%\n as.numeric()\n subcomponent dt %>%\n group_by(From) %>%\n slice_min(To) %>%\n graph_from_data_frame() %>%\n subcomponent(v = \"1\", mode = \"out\") %>%\n names() %>%\n as.integer()\n [1] 1 3\n [1] 1 2 5\n" }, { "answer_id": 74525840, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 2, "selected": false, "text": "shift NULL dt[, .(frst = first(To)), From][\n , if(all((frst %in% From)[1:(.N - 1)])){\n c(1, unique(frst[From == shift(frst, type = \"lag\", fill = T)]))}]\n[1] 1 3 4 5 6\n" }, { "answer_id": 74535142, "author": "jblood94", "author_id": 9463489, "author_profile": "https://Stackoverflow.com/users/9463489", "pm_score": 1, "selected": false, "text": "library(data.table)\nlibrary(igraph)\nlibrary(purrr)\n\ndt <- data.table(\n From = c(1, 1, 1, 1, 2, 2, 4, 5),\n To = c(3, 4, 5, 6, 4, 6, 6, 6)\n)\n\nfPath1 <- function(dt) {\n setorder(dt, From, To)[, wt := fifelse(rleid(To)==1,1,Inf), From] %>%\n graph_from_data_frame() %>%\n set_edge_attr(name = \"weight\", value = dt[, wt]) %>%\n shortest_paths(min(dt[, From]), max(dt[, To])) %>%\n pluck(1) %>%\n unlist(use.names = FALSE)\n}\n\nfPath2 <- function(dt) {\n dt[, .SD[which.min(To)], From] %>%\n graph_from_data_frame() %>%\n shortest_paths(min(dt[, From]), max(dt[, To])) %>%\n pluck(1) %>%\n unlist(use.names = FALSE)\n}\n\nfPath3 <- function(dt) {\n dt[, .(frst = first(To)), From][\n , if(all((frst %in% From)[1:(.N - 1)])){\n c(1, unique(frst[From == shift(frst, type = \"lag\", fill = T)]))}]\n}\n\nfPath1(dt)\n#> [1] 1 6\nfPath2(dt)\n#> Warning in shortest_paths(., min(dt[, From]), max(dt[, To])): At core/paths/\n#> unweighted.c:368 : Couldn't reach some vertices.\n#> integer(0)\nfPath3(dt)\n#> NULL\n igraph fPath4 <- function(dt) {\n g <- graph_from_data_frame(dt)\n E(g)$weight <- (dt$To - dt$From)^2\n as.integer(V(g)[shortest_paths(g, V(g)[1], V(g)[name == dt$To[nrow(dt)]])$vpath[[1]]]$name)\n}\n\nfPath4(dt)\n#> [1] 1 4 6\n" }, { "answer_id": 74552247, "author": "clp", "author_id": 3604103, "author_profile": "https://Stackoverflow.com/users/3604103", "pm_score": 0, "selected": false, "text": "n <- 1E6\ndf1 <- data.frame(from=sample(n), to=sample(n))\npath <- c()\nsystem.time(\nfor (i in seq(nrow(df1)) ){\n path[length(path) + 1] <- df1[i, \"to\"] # avoid copying.\n}\n)\nmean(path)\nlength(path)\n [1] 500000.5\n[1] 1000000\n ## Select min(To) by From.\nif (nrow(df) > 0) { df2 <- setNames(aggregate(df$To, list(df$From), \"min\"), c(\"From\", \"To\") )\n} else df2 <- df\n ## Let tt is maximal outgoing node upto now.\npath <- df2[1,1]\ntt <- df2[1,1]\nfor (i in seq_len(nrow(df2))){\n if (df2[i, 1] < tt) next\n else if (df2[i,1] == tt) { tt <- df2[i, 2]\n path[length(path) + 1] <- df2[i, 2]\n }\n else break\n}\nhead(path)\n [1] 1 3 4 5 6 , df as in first example.\n[1] 1 2 5 , df as in another example.\n" }, { "answer_id": 74589335, "author": "clp", "author_id": 3604103, "author_profile": "https://Stackoverflow.com/users/3604103", "pm_score": 2, "selected": false, "text": "Igraph subcomponents() graph_from_data_frame graph_from_edgelist(as.matrix(...)) dt2 <- setNames(aggregate(dt$To, list(dt$From), \"min\"), c(\"From\", \"To\") )\ng <- graph_from_edgelist(as.matrix(dt2), directed=TRUE) \nas.numeric(as_ids(subcomponent(g, 1, mode=\"out\")))\n dt2 <- setNames(aggregate(dt$To, list(dt$From), \"min\"), c(\"From\", \"To\") )\ng <- graph_from_data_frame(dt2, directed=TRUE) \nas.numeric(as_ids(subcomponent(g, 1, mode=\"out\")))\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20132110/" ]
74,525,251
<p>When I try to get a product and command it I get &quot;Illuminate\Database\QueryException SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'name' cannot be null (SQL: insert into <code>commande</code> (<code>name</code>, <code>familyname</code>, <code>quantity</code>, <code>mobile</code>, <code>ville</code>, <code>adresse</code>, <code>id_product</code>, <code>user_id</code>, <code>updated_at</code>, <code>created_at</code>) values (?, ?, ?, ?, ?, ?, ?, ?, 2022-11-21 21:30:27, 2022-11-21 21:30:27))&quot; I am trying here to command a product where every product has a different user. I am using a foreign key in products table (user_id) and every command has a user to inspect it.</p> <p>This is my function in the controller:</p> <pre><code> public function getProduct($id, Request $request) { $product = Product::find($id); $commande = new AppCommande; $commande-&gt;name = $request-&gt;input('name'); $commande-&gt;familyname = $request-&gt;input('familyname'); $commande-&gt;quantity = $request-&gt;input('quantity'); $commande-&gt;mobile = $request-&gt;input('mobile'); $commande-&gt;ville = $request-&gt;input('ville'); $commande-&gt;adresse = $request-&gt;input('adresse'); $commande-&gt;id_product = $request-&gt;input('id_product'); $commande-&gt;user_id = $request-&gt;input('id_user'); $commande-&gt;save(); return view('product', ['product' =&gt; $product], ['commande' =&gt; $commande]); } </code></pre> <p>This is my route :</p> <pre><code> Route::get('/product/{id}', \[ 'uses' =\&gt; 'CommandeUserController@getProduct', 'as' =\&gt; 'product.single' \]); </code></pre> <p>and this is the view:</p> <pre><code>@extends('layouts.app') @section('content') &lt;div class=&quot;col-sm-6 col-md-4&quot;&gt; &lt;div class=&quot;thumbnail&quot;&gt; &lt;img src=&quot;{{ asset('uploads/product/'.$product-&gt;image) }}&quot; width=&quot;90px&quot; alt=&quot;image&quot;&gt; &lt;div class=&quot;caption&quot;&gt; &lt;h3&gt; {{$product-&gt;name}} &lt;/h3&gt; &lt;p class=&quot;discription&quot;&gt; {{$product-&gt;description}} &lt;/p&gt; &lt;div class=&quot;clearfix&quot;&gt; &lt;div class=&quot;pull-left price&quot;/&gt;$ {{$product-&gt;price}}&lt;/div&gt; {{-- &lt;a href= {{ route('commander', ['id' =&gt; $product-&gt;id ]) }} class=&quot;btn btn-danger pull-right&quot; role=&quot;button&quot;&gt;Commander ce produit&lt;/a&gt; --}} &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;card&quot;&gt; &lt;div class=&quot;card-header&quot;&gt; Create Commande &lt;/div&gt; &lt;div class=&quot;card-body&quot;&gt; &lt;form action=&quot;{{ route(&quot;admin.commandes.store&quot;) }}&quot; method=&quot;POST&quot; enctype=&quot;multipart/form-data&quot;&gt; @csrf &lt;div class=&quot;form-group {{ $errors-&gt;has('name') ? 'has-error' : '' }}&quot;&gt; &lt;label for=&quot;name&quot;&gt;Name&lt;/label&gt; &lt;input type=&quot;text&quot; id=&quot;name&quot; name=&quot;name&quot; class=&quot;form-control&quot; value=&quot;{{ old('name', isset($commande) ? $commande-&gt;name : '') }}&quot;&gt; @if($errors-&gt;has('name')) &lt;em class=&quot;invalid-feedback&quot;&gt; {{ $errors-&gt;first('name') }} &lt;/em&gt; @endif &lt;p class=&quot;helper-block&quot;&gt; {{ trans('global.product.fields.name_helper') }} &lt;/p&gt; &lt;/div&gt; &lt;div class=&quot;form-group {{ $errors-&gt;has('familyname') ? 'has-error' : '' }}&quot;&gt; &lt;label for=&quot;name&quot;&gt;Family Name&lt;/label&gt; &lt;input type=&quot;text&quot; id=&quot;familyname&quot; name=&quot;familyname&quot; class=&quot;form-control&quot; value=&quot;{{ old('familyname', isset($commande) ? $commande-&gt;familyname : '') }}&quot;&gt; @if($errors-&gt;has('name')) &lt;em class=&quot;invalid-feedback&quot;&gt; {{ $errors-&gt;first('name') }} &lt;/em&gt; @endif &lt;p class=&quot;helper-block&quot;&gt; {{ trans('global.product.fields.name_helper') }} &lt;/p&gt; &lt;/div&gt; &lt;div class=&quot;form-group {{ $errors-&gt;has('mobile') ? 'has-error' : '' }}&quot;&gt; &lt;label for=&quot;quantity&quot;&gt;Mobile&lt;/label&gt; &lt;input type=&quot;number&quot; id=&quot;mobile&quot; name=&quot;mobile&quot; class=&quot;form-control&quot; value=&quot;{{ old('mobile', isset($commande) ? $commande-&gt;mobile : '') }}&quot; step=&quot;1&quot;&gt; @if($errors-&gt;has('mobile')) &lt;em class=&quot;invalid-feedback&quot;&gt; {{ $errors-&gt;first('mobile') }} &lt;/em&gt; @endif &lt;p class=&quot;helper-block&quot;&gt; {{ trans('global.product.fields.price_helper') }} &lt;/p&gt; &lt;/div&gt; &lt;div class=&quot;form-group {{ $errors-&gt;has('quantity') ? 'has-error' : '' }}&quot;&gt; &lt;label for=&quot;quantity&quot;&gt;Quantity&lt;/label&gt; &lt;input type=&quot;number&quot; id=&quot;quantity&quot; name=&quot;quantity&quot; class=&quot;form-control&quot; value=&quot;{{ old('quantity', isset($commande) ? $commande-&gt;quantity : '') }}&quot; step=&quot;1&quot;&gt; @if($errors-&gt;has('price')) &lt;em class=&quot;invalid-feedback&quot;&gt; {{ $errors-&gt;first('price') }} &lt;/em&gt; @endif &lt;p class=&quot;helper-block&quot;&gt; {{ trans('global.product.fields.price_helper') }} &lt;/p&gt; &lt;/div&gt; &lt;div class=&quot;form-group {{ $errors-&gt;has('ville') ? 'has-error' : '' }}&quot;&gt; &lt;label for=&quot;ville&quot;&gt;City&lt;/label&gt; &lt;input type=&quot;text&quot; id=&quot;ville&quot; name=&quot;ville&quot; class=&quot;form-control&quot; value=&quot;{{ old('ville', isset($commande) ? $commande-&gt;familyname : '') }}&quot;&gt; @if($errors-&gt;has('ville')) &lt;em class=&quot;invalid-feedback&quot;&gt; {{ $errors-&gt;first('ville') }} &lt;/em&gt; @endif &lt;p class=&quot;helper-block&quot;&gt; {{ trans('global.product.fields.name_helper') }} &lt;/p&gt; &lt;/div&gt; &lt;div class=&quot;form-group {{ $errors-&gt;has('adresse') ? 'has-error' : '' }}&quot;&gt; &lt;label for=&quot;adress&quot;&gt;Adresse&lt;/label&gt; &lt;input type=&quot;text&quot; id=&quot;adresse&quot; name=&quot;adresse&quot; class=&quot;form-control&quot; value=&quot;{{ old('adresse', isset($commande) ? $commande-&gt;adresse : '') }}&quot;&gt; @if($errors-&gt;has('adresse')) &lt;em class=&quot;invalid-feedback&quot;&gt; {{ $errors-&gt;first('adresse') }} &lt;/em&gt; @endif &lt;p class=&quot;helper-block&quot;&gt; {{ trans('global.product.fields.name_helper') }} &lt;/p&gt; &lt;/div&gt; &lt;input type=&quot;hidden&quot; name=&quot;id_product&quot; value=&quot; {{ $product-&gt;id }}&quot; /&gt; &lt;input type=&quot;hidden&quot; name=&quot;user_id&quot; value=&quot; {{ $product-&gt;user_id }}&quot; /&gt; &lt;input class=&quot;btn btn-danger&quot; type=&quot;submit&quot; value=&quot;{{ trans('global.save') }}&quot;&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; @endsection </code></pre>
[ { "answer_id": 74526774, "author": "Dicky Agusputra", "author_id": 8859333, "author_profile": "https://Stackoverflow.com/users/8859333", "pm_score": -1, "selected": false, "text": "$commande = new AppComande();\n" }, { "answer_id": 74602048, "author": "Malik Kadri", "author_id": 11281627, "author_profile": "https://Stackoverflow.com/users/11281627", "pm_score": 1, "selected": true, "text": " public function getProduct($id, Request $request)\n{\n\n $product = Product::find($id);\n\n\n return view('product', ['product' => $product]);\n\n}\n public function store(StoreProductRequest $request)\n{\n\n $user_id=auth()->user()->id;\n $commande = new AppCommande();\n\n $commande->name = $request->input('name');\n $commande->familyname = $request->input('familyname');\n $commande->quantity = $request->input('quantity');\n $commande->mobile = $request->input('mobile');\n $commande->ville = $request->input('ville');\n $commande->adresse = $request->input('adresse');\n $commande->id_product = $request->input('id_product');\n $commande->user_id=$user_id;\n $commande->save();\n\n\n return redirect('/commandeuser/confirm')->with('status', 'commande ajoutée!');\n\n}\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11281627/" ]
74,525,259
<p>:)</p> <p>I am starting a new Laravel project with <a href="https://lighthouse-php.com/" rel="nofollow noreferrer">Lighthouse</a> and have been problems with resolving non root fields.<br /> According to the <a href="https://lighthouse-php.com/5/the-basics/fields.html#resolving-non-root-fields" rel="nofollow noreferrer">documentation</a> here for each of the fields that have complex types, there should be a model and a query provided for the field.<br /> So in this example I have a <code>Version</code> object which has two subfields: <code>appVersion</code> and <code>apiVersion</code>. Here is what I have in my <code>schema.graphql</code> file:</p> <pre><code>type Query { version: Version } type Version { appVersion: String apiVersion: String } </code></pre> <p>And in addition, here is my model for <code>Version</code>:</p> <pre><code>&lt;?php namespace App\Models; class Version { private string $appVersion; private string $apiVersion; public function __construct() { $composer = file_get_contents('../composer.json'); $content = json_decode($composer, true); $this-&gt;appVersion = $content['app-version']; $this-&gt;apiVersion = $content['version']; } public function getAppVersion() : string { return $this-&gt;appVersion; } public function getApiVersion() : string { return $this-&gt;apiVersion; } function export() : array { return [ 'app' =&gt; $this-&gt;getAppVersion(), 'api' =&gt; $this-&gt;getApiVersion(), ]; } } </code></pre> <p>And the Query file for <code>Version</code>:</p> <pre><code>&lt;?php namespace App\GraphQL\Queries; use GraphQL\Type\Definition\ResolveInfo; use Nuwave\Lighthouse\Support\Contracts\GraphQLContext; final class Version { public function __invoke ($version, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) { return $version-&gt;export()[$resolveInfo-&gt;fieldName]; } } </code></pre> <p>However the <code>$version</code> seems to be always null when I try to query version using the following:</p> <pre><code>{ version { appVersion } } </code></pre> <p>And I cannot figure our why. I tried to follow the docs as best as I could, but I am probably missing something really simple here :/ I should also mention that querying simple fields (like fields that don't have a sub selection) works here for me. Any help would be much appreciated :)</p> <p>I implemented a graphql resolver, however the models were not resolved correctly.</p>
[ { "answer_id": 74529495, "author": "mostafa", "author_id": 19372996, "author_profile": "https://Stackoverflow.com/users/19372996", "pm_score": 0, "selected": false, "text": "type Query {\n version: Version @field(resolver: \"App\\GraphQL\\Queries\\Version\")\n}\n" }, { "answer_id": 74531521, "author": "Konstantin Duczek", "author_id": 19328980, "author_profile": "https://Stackoverflow.com/users/19328980", "pm_score": 1, "selected": false, "text": "<?php\n\nnamespace App\\GraphQL\\Queries;\n\nuse GraphQL\\Type\\Definition\\ResolveInfo;\nuse Nuwave\\Lighthouse\\Support\\Contracts\\GraphQLContext;\n\nfinal class Version {\n\n public function __invoke ($version, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) {\n $composer = file_get_contents('../composer.json');\n $content = json_decode($composer, true);\n\n return [\n 'appVersion' => $content['app-version'],\n 'apiVersion' => $content['version'],\n ];\n }\n}\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8092143/" ]
74,525,272
<p>I have a method defined that wraps fetch in order to automatically handle certain edge cases and provide a unified response class alerting system. I don't want to automatically parse responses as json (the platform will not only be requesting JSON) and came up with the idea to add to the fetch method's prototype a .json call to auto-parse and coerce the promise but found that I couldn't use the prototype when calling integratedFetch.json(//etc). Is is possible to add such a static method?</p> <p>Example code:</p> <pre><code>const integratedFetch: ( input: RequestInfo, init?: RequestInit | undefined, options?: Partial&lt;IntegratedFetchOptions&gt; ) =&gt; Promise&lt;Response&gt; = (input, init, options) =&gt; { return fetch(input, init).then(async (response) =&gt; { const { status } = response; const responseClass = getResponseClass(response); if (responseClass) { switch (Number(responseClass) as ResponseClass) { case ResponseClass.Informational: //etc case ResponseClass.Successful: //etc default: throw Error(`Response class ${responseClass} unrecognized`); } } return Promise.resolve(response); }); }; integratedFetch.prototype.json = &lt;T&gt;(input: RequestInfo, init?: RequestInit | undefined, options?: Partial&lt;IntegratedFetchOptions&gt;) =&gt; integratedFetch(input, init, options).then((response) =&gt; response.json() as Promise&lt;T&gt;); </code></pre> <p>With expected usage to be:</p> <pre><code>integratedFetch.json&lt;MyType&gt;(//request) -vs- integratedFetch(//request).then(r =&gt; r.json() as Promise&lt;T&gt;) </code></pre> <p>The current problem being that using <code>integratedFetch.json()</code> gives the error &quot;Property 'json' does not exist on type '(input: RequestInfo, init?: RequestInit | undefined, options?: Partial | undefined) =&gt; Promise&lt;...&gt;'.ts(2339)&quot;</p>
[ { "answer_id": 74525434, "author": "Alex Wayne", "author_id": 62076, "author_profile": "https://Stackoverflow.com/users/62076", "pm_score": 1, "selected": false, "text": "prototype const foo = () => 123\nfoo.bar = () => 'hello'\n\nfoo() // 123\nfoo.bar() // \"hello\"\n" }, { "answer_id": 74526044, "author": "C Bauer", "author_id": 82333, "author_profile": "https://Stackoverflow.com/users/82333", "pm_score": 0, "selected": false, "text": "type FetchParams = (input: RequestInfo, init?: RequestInit | undefined, options?: Partial<IntegratedFetchOptions>) => Promise<Response>;\ntype StaticParams = <T>(input: RequestInfo, init?: RequestInit | undefined, options?: Partial<IntegratedFetchOptions>) => Promise<T>;\n\n//Create an aggregate typedef which allows for the static methods on the object definition\ntype IntegratedFetch = FetchParams & { json: StaticParams };\n\nconst integratedFetch: IntegratedFetch = (input, init, options) => { //the previous implementation\n\n\nintegratedFetch.json = <T>(input: RequestInfo, init?: RequestInit | undefined, options?: Partial<IntegratedFetchOptions>) =>\n integratedFetch(input, init, options).then((response) => response.json() as Promise<T>);\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82333/" ]
74,525,295
<p>I made a SearchViewController with tableView. I put some data in tableView from server (pictures of cats). But now I want to show not only all pictures, but also filtered by certain categories images. For this I suppose I need to push my second array with category's images into the tableView. I guess that to achieve this goal I need to reload tableView and change its dataSource, but how to realize it correctly I don't understand.</p> <p><a href="https://i.stack.imgur.com/Vi5NH.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Vi5NH.jpg" alt="enter image description here" /></a></p> <ol> <li><p>Here is the method to get all pictures of cats</p> <pre><code> func fetchData() { guard let endPoint = // myEndpoint else { return } endpoint.queryItems = queryParameters.map({ (key, value) in URLQueryItem(name: key, value: value) // some parameters }) guard let url = endpoint.url else { return } var request = URLRequest(url: url) request.setValue(ApiClient.Identifiers.apiKey, forHTTPHeaderField: &quot;x-api-key&quot;) let task = URLSession.shared.dataTask(with: request) { data, response, error in DispatchQueue.main.async { if error != nil { print(error.debugDescription) } else { do { let myData = try JSONDecoder().decode([CatModel].self, from: data!) self.catsModel = myData // catsModel is an array with struct with cats info (breed, category, id, etc.) self.tableView.dataSource = myData as? any UITableViewDataSource self.tableView.reloadData() } catch let error { print(error) } } } } task.resume() </code></pre> </li> </ol> <p>}</p> <ol start="2"> <li><p>Here is the method for filter by categories id :</p> <pre>func fetchCategoryData(categoryID: Int) { let endpoint = URLComponents // url components guard let url = endpoint?.url else { return } var request = URLRequest(url: url) request.setValue(ApiClient.Identifiers.apiKey, forHTTPHeaderField: "x-api-key") let task = URLSession.shared.dataTask(with: request) { data, response, error in DispatchQueue.main.async { if error != nil { print(error.debugDescription) } else { do { let myData = try JSONDecoder().decode([CatModel].self, from: data!) self.catsModel = myData self.tableView.reloadData() } catch let error { print(error) } } } } task.resume() } </li> <li><p>In CategoryViewController I made this method:</p> <code> func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let searchViewController = SearchViewController() let cat = catsModel[indexPath.row] searchViewController.fetchCategoryData(categoryID: cat.id) // this line works, but in fetchCategoryData doesn't happenings the reload of tableView with new data </code></pre> <p>}</p> </li> </ol> <p>Thank you very much!</p>
[ { "answer_id": 74612857, "author": "teja_D", "author_id": 9109095, "author_profile": "https://Stackoverflow.com/users/9109095", "pm_score": 0, "selected": false, "text": "self.tableView.dataSource = myData as? any UITableViewDataSource\n self.tableView.dataSource = self\n" }, { "answer_id": 74614896, "author": "DonMag", "author_id": 6257435, "author_profile": "https://Stackoverflow.com/users/6257435", "pm_score": 2, "selected": false, "text": "self.catsModel = myData self.tableView.dataSource = myData as? any UITableViewDataSource var allCats: [CatModel] = []\nvar filteredCats: [CatModel] = []\n self self.tableView.dataSource = self\n allCats filteredCats self.filteredCats = self.allCats.filter({ $0.id == selectedFilterID })\n func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {\n if selectedFilterID == nil {\n return allCats.count\n }\n return filteredCats.count\n}\n\nfunc tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {\n let cell = tableView.dequeueReusableCell(withIdentifier: \"c\", for: indexPath) as! CatCell\n\n var thisCat: CatModel!\n\n if selectedFilterID == nil {\n thisCat = allCats[indexPath.row]\n } else {\n thisCat = filteredCats[indexPath.row]\n }\n\n // set the cell's values / properties\n\n return cell\n}\n filteredCats allCats func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {\n return allCats.count\n}\n\nfunc tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {\n let cell = tableView.dequeueReusableCell(withIdentifier: \"c\", for: indexPath) as! CatCell\n\n let thisCat = allCats[indexPath.row]\n\n // set the cell's values / properties\n\n return cell\n}\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14506424/" ]
74,525,297
<p>I am a bit rusty in HTML and CSS. Can somebody suggest, how to create a line(in in the middle, and text on left and right?</p> <p><img src="https://i.stack.imgur.com/R6Xh8.png" alt="Center" /></p> <p>Ive tried one div with left: 50; second div right:50 and text align right</p>
[ { "answer_id": 74525336, "author": "Oliver Kucharzewski", "author_id": 1224963, "author_profile": "https://Stackoverflow.com/users/1224963", "pm_score": 2, "selected": false, "text": "border-left: 1px solid black;\nleft: 35%;\ntop: 0;\nbottom: 0;\nposition: absolute;\n position: relative;" }, { "answer_id": 74549222, "author": "susgreg", "author_id": 19127095, "author_profile": "https://Stackoverflow.com/users/19127095", "pm_score": 1, "selected": false, "text": ".parent {\n position: fixed;\n top: 50%;\n left: 50%;\n -webkit-transform: translate(-50%, -50%);\n transform: translate(-50%, -50%);\n color: white;\n}\n.left {\n float: left;\n line-height: 50px;\n font-size: 1.5em;\n padding-right: 15px;\n font-weight: bold;\n}\n.right {\n overflow:hidden;\n line-height: 50px;\n padding-left: 15px;\n border-left: 1px rgb(46, 46, 46) solid;\n width:fit-content;\n}\n" }, { "answer_id": 74549409, "author": "Loïc Monard", "author_id": 7935545, "author_profile": "https://Stackoverflow.com/users/7935545", "pm_score": 3, "selected": true, "text": "html,body {\n margin: 0;\n font-family: sans-serif\n}\n#container {\n height: 100vh;\n width: 100vw;\n background: #000;\n display: flex;\n justify-content: center;\n gap: 10px;\n align-items: center;\n color: #fff;\n}\n.border {\n height: 1rem;\n border-right: 1px solid #8d8d8d;\n}\n.small {\n font-size: 12px;\n} <div id=\"container\">\n <span>500</span>\n <div class=\"border\"></div>\n <span class=\"small\">internal server error</span>\n</div>" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19127095/" ]
74,525,304
<p>pretty new to python, but I'm trying to have the mouse click on a point within an image using PyAutoGUI. However the project requires I simulate a &quot;human pattern&quot;. So what I'm going for is an &quot;accurate-like&quot; accuracy, where most of the points are in the middle and it gets more sparse the further away the click is, simulating missclicks or room for error. So that not every click is exactly on the point in the centre. Check the simulated clickmap below:</p> <p><a href="https://i.stack.imgur.com/Z5yXz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Z5yXz.png" alt="clickmap" /></a></p> <p>(where red is the most clicked area and green is the least - each click is represented by a pixel)</p> <pre class="lang-py prettyprint-override"><code>import pyautogui pyautogui.click(pos.x,pos.y) </code></pre> <p>Given that I have the x and y position, what's the best way to achieve this kind of somewhat random pattern the most efficient way?</p>
[ { "answer_id": 74525336, "author": "Oliver Kucharzewski", "author_id": 1224963, "author_profile": "https://Stackoverflow.com/users/1224963", "pm_score": 2, "selected": false, "text": "border-left: 1px solid black;\nleft: 35%;\ntop: 0;\nbottom: 0;\nposition: absolute;\n position: relative;" }, { "answer_id": 74549222, "author": "susgreg", "author_id": 19127095, "author_profile": "https://Stackoverflow.com/users/19127095", "pm_score": 1, "selected": false, "text": ".parent {\n position: fixed;\n top: 50%;\n left: 50%;\n -webkit-transform: translate(-50%, -50%);\n transform: translate(-50%, -50%);\n color: white;\n}\n.left {\n float: left;\n line-height: 50px;\n font-size: 1.5em;\n padding-right: 15px;\n font-weight: bold;\n}\n.right {\n overflow:hidden;\n line-height: 50px;\n padding-left: 15px;\n border-left: 1px rgb(46, 46, 46) solid;\n width:fit-content;\n}\n" }, { "answer_id": 74549409, "author": "Loïc Monard", "author_id": 7935545, "author_profile": "https://Stackoverflow.com/users/7935545", "pm_score": 3, "selected": true, "text": "html,body {\n margin: 0;\n font-family: sans-serif\n}\n#container {\n height: 100vh;\n width: 100vw;\n background: #000;\n display: flex;\n justify-content: center;\n gap: 10px;\n align-items: center;\n color: #fff;\n}\n.border {\n height: 1rem;\n border-right: 1px solid #8d8d8d;\n}\n.small {\n font-size: 12px;\n} <div id=\"container\">\n <span>500</span>\n <div class=\"border\"></div>\n <span class=\"small\">internal server error</span>\n</div>" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872757/" ]
74,525,311
<pre><code>L1 = ['a','b','c','a','b','c'] L2 = ['Cat','Fish','Crow','Dog','Frog','Eagle'] Desired Output 1: D1 = {'a':['Cat','Dog'], 'b':['Fish','Frog'], 'c':['Crow','Eagle']} Desired Output 2: DF1 = A B C Cat Fish Crow Dog Frog Eagle </code></pre> <p>I only used from a to c for reference, I've more than 100 columns in DataFrame.</p> <p>Could someone please help me with this?</p>
[ { "answer_id": 74525354, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 3, "selected": true, "text": "L1 = [\"a\", \"b\", \"c\", \"a\", \"b\", \"c\"]\nL2 = [\"Cat\", \"Fish\", \"Crow\", \"Dog\", \"Frog\", \"Eagle\"]\n\nout = {}\nfor a, b in zip(L1, L2):\n out.setdefault(a, []).append(b)\n\nprint(out)\n {\"a\": [\"Cat\", \"Dog\"], \"b\": [\"Fish\", \"Frog\"], \"c\": [\"Crow\", \"Eagle\"]}\n out_df = pd.DataFrame(out)\nout_df.columns = out_df.columns.str.upper()\n\nprint(out_df)\n A B C\n0 Cat Fish Crow\n1 Dog Frog Eagle\n" }, { "answer_id": 74526909, "author": "rhug123", "author_id": 13802115, "author_profile": "https://Stackoverflow.com/users/13802115", "pm_score": 0, "selected": false, "text": "l = list(set(l1))\nd = {key:[] for key in l}\nfor i,j in zip(l1,l2):\n d.get(i).append(j)\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20566834/" ]
74,525,326
<p>I am trying to save a dict as json in azure data lake/databricks however I am getting a File not found error. Any clue what I am doing wrong?</p> <pre><code>import json test_config = { &quot;expectations&quot;: [ { &quot;kwargs&quot;: { &quot;column&quot;: &quot;role&quot;, &quot;value_set&quot;: [ &quot;BBV&quot;, &quot;GEM&quot; ] }, &quot;expectation_type&quot;: &quot;expect_column_distinct_values_to_be_in_set&quot;, &quot;meta&quot;: {} }] } path = '/mnt/lake/enriched/checks/' json_file = 'test_idm_expectations.json' with open(path+json_file, &quot;w&quot;) as fp: json.dump(test_config , fp) </code></pre> <p>And the error I am getting is:</p> <pre><code>FileNotFoundError: [Errno 2] No such file or directory: &quot;/mnt/lake/enriched/checks/test_idm_expectations.json&quot; </code></pre> <p>Variations of the path with <code>/dbfs/mnt/lake/enriched/checks/</code> or <code>dbfs:mnt/lake/enriched/checks/</code> also do not work.</p> <p>Any help would be super appreciated. Thanks!</p>
[ { "answer_id": 74525507, "author": "Remzinho", "author_id": 2484591, "author_profile": "https://Stackoverflow.com/users/2484591", "pm_score": 1, "selected": false, "text": "os.path.ismount json.dumps indent=2" }, { "answer_id": 74529798, "author": "Rakesh Govindula", "author_id": 18836744, "author_profile": "https://Stackoverflow.com/users/18836744", "pm_score": 1, "selected": false, "text": "sourcefolder1 mysample1.json sourcefolder /dbfs/mnt/folder/ /mnt/folder/ open()" }, { "answer_id": 74530710, "author": "mizzlosis", "author_id": 9473505, "author_profile": "https://Stackoverflow.com/users/9473505", "pm_score": 0, "selected": false, "text": "if not os.path.exists(path):\n os.mkdir(path)\n\nwith open(path+json_file, \"w\") as fp:\n json.dump(test_config , fp)\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9473505/" ]
74,525,368
<p>I would like to patch a class in Python in unit testing. The main code is this (<code>mymath.py</code>):</p> <pre><code>class MyMath: def my_add(self, a, b): return a + b def add_three_and_two(): my_math = MyMath() return my_math.my_add(3, 2) </code></pre> <p>The test class is this:</p> <pre><code>import unittest from unittest.mock import patch import mymath class TestMyMath(unittest.TestCase): @patch('mymath.MyMath') def test_add_three_and_two(self, mymath_mock): mymath_mock.my_add.return_value = 5 result = mymath.add_three_and_two() mymath_mock.my_add.assert_called_once_with(3, 2) self.assertEqual(5, result) unittest.main() </code></pre> <p>I am getting the following error:</p> <pre><code>AssertionError: Expected 'my_add' to be called once. Called 0 times. </code></pre> <p>The last assert would also fail:</p> <pre><code>AssertionError: 5 != &lt;MagicMock name='MyMath().my_add()' id='3006283127328'&gt; </code></pre> <p>I would expect that the above test passes. What I did wrong?</p> <p>UPDATE: Restrictions:</p> <ul> <li>I would not change the tested part if possible. (I am curious if it is even possible, and this is the point of the question.)</li> <li>If not possible, then I want the least amount of change in the to be tested part. Especially I want to keep the <code>my_add()</code> function non-static.</li> </ul>
[ { "answer_id": 74525521, "author": "Yaakov Bressler", "author_id": 10521959, "author_profile": "https://Stackoverflow.com/users/10521959", "pm_score": 2, "selected": false, "text": "my_add self my_add class MyMath:\n\n @classmethod\n def my_add(cls, a, b):\n return a + b\n\ndef add_three_and_two():\n return MyMath.my_add(3, 2)\n\n import unittest\nfrom unittest.mock import patch, MagicMock\nimport mymath\n\n\nclass TestMyMath(unittest.TestCase):\n\n @patch('mymath.MyMath')\n def test_add_three_and_two(self, mymath_mock):\n\n # Mock what `mymath` would return \n mymath_mock.my_add.return_value = 5\n\n # We are patching, not stubbing, so use the real thing\n result = mymath.add_three_and_two()\n mymath.MyMath.my_add.assert_called_once_with(3, 2)\n self.assertEqual(5, result)\n\n\nunittest.main()\n" }, { "answer_id": 74660899, "author": "chepner", "author_id": 1126841, "author_profile": "https://Stackoverflow.com/users/1126841", "pm_score": 0, "selected": false, "text": "class TestMyMath(unittest.TestCase):\n @patch.object(mymath.MyMath, 'my_add')\n def test_add_three_and_two(self, m):\n m.return_value = 5\n\n result = mymath.add_three_and_two()\n\n m.assert_called_once_with(3, 2)\n self.assertEqual(5, result)\n my_math.my_add Mock return_value Mock patch.object" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19280082/" ]
74,525,386
<p>I'm currently learning about arrays and the different ways to manipulate them. I was asked to: &quot;multiply 5 to the given array using the forEach function&quot;</p> <p>Here is my code so far.</p> <p>It looks as if everything works when I console.log in the forEach function, but when I log the console for the array it's read as undefined.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>let multiplyArray = [1, 11, 7, 3, 8, 2, 3, 2, 10, 3, 6, 2, 5]; function multiplyNumbers() { let numbers; multiplyArray.forEach(function(element) { let fiveTimesNum; fiveTimesNum = (element * 5); element = fiveTimesNum; console.log(element) }); console.log('The array(element) value is read out correctly, but when I console log the array its value is ↓') return numbers } multiplyArray = (multiplyNumbers()); console.log(multiplyArray);</code></pre> </div> </div> </p>
[ { "answer_id": 74525418, "author": "Oliver Kucharzewski", "author_id": 1224963, "author_profile": "https://Stackoverflow.com/users/1224963", "pm_score": 1, "selected": false, "text": "let multiplyArray = [1, 11, 7, 3, 8, 2, 3, 2, 10, 3, 6, 2, 5];\n\nfunction multiplyNumbers() {\n multiplyArray.forEach(function(element) {\n let fiveTimesNum;\n fiveTimesNum = (element * 5);\n element = fiveTimesNum;\n console.log(element)\n });\n console.log('The array(element) value is read out correctly, but when I console log the array its value is ↓')\n return multiplyArray\n}\nmultiplyArray = (multiplyNumbers());\nconsole.log(multiplyArray);" }, { "answer_id": 74525508, "author": "Carsten Massmann", "author_id": 2610061, "author_profile": "https://Stackoverflow.com/users/2610061", "pm_score": 2, "selected": true, "text": "multiplyArray let multiplyArray = [1, 11, 7, 3, 8, 2, 3, 2, 10, 3, 6, 2, 5];\n\nmultiplyArray.forEach(function(n,i,a){a[i]=5*n;});\n\nconsole.log(multiplyArray);" }, { "answer_id": 74525527, "author": "pete", "author_id": 2069697, "author_profile": "https://Stackoverflow.com/users/2069697", "pm_score": 2, "selected": false, "text": "let multiplyArray = [1, 11, 7, 3, 8, 2, 3, 2, 10, 3, 6, 2, 5];\nmultiplyArray.forEach(function(val, i, arr){\n arr[i] = val*5;\n})\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9277512/" ]
74,525,402
<p>I have a class 'Foo' (not under my control) which I wish to use as a key in a kotlin (java) hashmap. The problem is that the 'equals' method for 'Foo' does value equivalence. For my situation value equivalence is too loose. I need object equivalence.</p> <p>What are the ways to force force the use of object equivalence on the keys?</p> <p>I am thinking something like...</p> <pre class="lang-kotlin prettyprint-override"><code>data class Foo(val prop: String) data class Bar(val prop: String) fun main() { val fooMap = mutableMapOf&lt;Any, Bar&gt;() val fooA = Foo(&quot;common value&quot;) val fooB = Foo(&quot;common value&quot;) fooMap[fooA] = Bar(&quot;different A&quot;) fooMap[fooB] = Bar(&quot;different B&quot;) println(&quot;${fooMap.keys} ${fooMap.values}&quot;) } </code></pre> <p>This results in a fooMap with only one entry, when I expect two.</p> <pre><code>[Foo(prop=common value)] [Bar(prop=different B)] </code></pre>
[ { "answer_id": 74525458, "author": "AterLux", "author_id": 4931630, "author_profile": "https://Stackoverflow.com/users/4931630", "pm_score": 4, "selected": true, "text": "IdentityHashMap equals hashCode" }, { "answer_id": 74525738, "author": "phreed", "author_id": 345427, "author_profile": "https://Stackoverflow.com/users/345427", "pm_score": 0, "selected": false, "text": "data class Identity<T>(private val delegate: T) {\n override fun equals(other: Any?): Boolean {\n return delegate === other\n }\n}\nfun <K,V> mutableIdentityMapOf(): MutableMap<Identity<K>,V> {\n return mutableMapOf()\n}\n\n\ndata class Foo(val prop: String)\ndata class Bar(val prop: String)\n\nfun main() {\n val fooMap = mutableIdentityMapOf<Foo, Bar>()\n\n val fooA = Foo(\"common value\")\n val fooB = Foo(\"common value\")\n\n fooMap[Identity(fooA)] = Bar(\"different A\")\n fooMap[Identity(fooB)] = Bar(\"different B\")\n println(\"${fooMap.keys} ${fooMap.values}\")\n}\n" }, { "answer_id": 74525754, "author": "broot", "author_id": 448875, "author_profile": "https://Stackoverflow.com/users/448875", "pm_score": 0, "selected": false, "text": "IdentityHashMap equals() data class FooKey(val foo: Foo) {\n override fun equals(other: Any?) = foo === (other as? FooKey)?.foo\n}\n\n\nfun main() {\n val fooMap = mutableMapOf<FooKey, Bar>()\n\n val fooA = Foo(\"common value\")\n val fooB = Foo(\"common value\")\n\n fooMap[FooKey(fooA)] = Bar(\"different A\")\n fooMap[FooKey(fooB)] = Bar(\"different B\")\n println(\"${fooMap.keys} ${fooMap.values}\")\n}\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/345427/" ]
74,525,412
<p>The first table below shows how much each person owes and who pays it (it's part of a larger model so I simplified it for our purposes here).</p> <p>Our goal in the second table below is to give a sum when both the column and row value match.</p> <p>For example: A (column C) paid $244.17 (D36:H48) in expenses for B (row 35).</p> <p>Where am I wrong here? I have tried different methods suggested here.</p> <p><a href="https://i.stack.imgur.com/kIVDs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kIVDs.png" alt="Table" /></a></p>
[ { "answer_id": 74526482, "author": "JB-007", "author_id": 13607672, "author_profile": "https://Stackoverflow.com/users/13607672", "pm_score": 0, "selected": false, "text": "=SUM($C$4:$E$6*($C$3:$E$3=C$8)*($B$4:$B$6=$B9))\n" }, { "answer_id": 74527082, "author": "David Leal", "author_id": 6237093, "author_profile": "https://Stackoverflow.com/users/6237093", "pm_score": 2, "selected": true, "text": "I3 =MMULT(N(TRANSPOSE($A$3:$A$15=H3)),IF($B$3:$F$15=\"\", 0, $B$3:$F$15))\n LET =LET(set, $B$3:$F$15, MMULT(N(TRANSPOSE($A$3:$A$15=H3)),IF(set=\"\", 0, set))\n MMULT TRANSPOSE TOROW $ H3 I2:M2 H3:H7" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19740382/" ]
74,525,432
<p>There is an array of arrays filled with numbers and letters. I want to collect the isolated ones in array of arrays. So, for example, if I call a function called findIsolated(type, matrix) with the &quot;M&quot; type and the matrix shown below, I would like it to return an array of arrays: [ [ {x:0,y:0},{x:0,y:1} ],[ {x:4,y:3},{x:4,y:4},{x:4,y:5} ] ]</p> <p>If I called the function with findIsolated(&quot;V&quot;,matrix) it would return an array of array which has all the Vs in it.</p> <p>matrix:</p> <p><a href="https://i.stack.imgur.com/f3lqw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/f3lqw.png" alt="matrix" /></a></p> <p>findIsolated(&quot;M&quot;,matrix) expected output:</p> <p><a href="https://i.stack.imgur.com/j1s4Y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/j1s4Y.png" alt="expected output" /></a></p> <p>How do I do this recursively? Honestly, I couldn't even figure out one step, so I don't write a minrep.</p>
[ { "answer_id": 74528327, "author": "Peter Thoeny", "author_id": 7475450, "author_profile": "https://Stackoverflow.com/users/7475450", "pm_score": 1, "selected": false, "text": "function findIsolated(target, matrix) {\n let result = [];\n matrix.forEach((row, rIdx) => {\n row.forEach((char, cIdx) => {\n // only look at target char:\n if(char === target) {\n let found = false;\n // check if the cell to the left is the same as the target char:\n if(cIdx > 0 && row[cIdx - 1] === target) {\n // search result set if cell to the left is already listed:\n result.forEach(set => {\n if(set.x === cIdx -1 && set.y === rIdx) {\n // found it, so add this coordinate to the set:\n set.push({ x: rIdx, y: cIdx});\n found = true;\n }\n });\n }\n // check if the cell above is the same as the target char:\n if(!found && rIdx > 0 && matrix[rIdx - 1][cIdx] === target) {\n // search result set if cell to above is already listed:\n result.forEach(set => {\n if(set.x === cIdx && set.y === rIdx - 1) {\n // found it, so add this coordinate to the set:\n set.push({ x: rIdx, y: cIdx});\n found = true;\n }\n });\n }\n if(!found) {\n // target char has not been found in result, so start a new set\n let set = [ { x: rIdx, y: cIdx} ];\n result.push([ set ]);\n }\n }\n });\n });\n return result;\n}\n\nconst matrix = [\n [ 'M', 'M', '0', 'V', 'V', '0' ], \n [ '0', '0', '0', 'V', '0', '0' ], \n [ '0', 'V', 'V', 'V', '0', '0' ], \n [ '0', 'V', 'V', '0', '0', '0' ], \n [ '0', '0', '0', 'M', 'M', 'M' ], \n [ '0', '0', '0', '0', '0', '0' ], \n];\nconsole.log('M: ' + JSON.stringify(findIsolated('M', matrix)));\nconsole.log('V: ' + JSON.stringify(findIsolated('V', matrix))); M: [[[{\"x\":0,\"y\":0}]],[[{\"x\":0,\"y\":1}]],[[{\"x\":4,\"y\":3}]],[[{\"x\":4,\"y\":4}]],[[{\"x\":4,\"y\":5}]]]\nV: [[[{\"x\":0,\"y\":3}]],[[{\"x\":0,\"y\":4}]],[[{\"x\":1,\"y\":3}]],[[{\"x\":2,\"y\":1}]],[[{\"x\":2,\"y\":2}]],[[{\"x\":2,\"y\":3}]],[[{\"x\":3,\"y\":1}]],[[{\"x\":3,\"y\":2}]]]\n" }, { "answer_id": 74531463, "author": "PizzaPeet", "author_id": 12783473, "author_profile": "https://Stackoverflow.com/users/12783473", "pm_score": 0, "selected": false, "text": "const findIsolated = (type, _map) => {\n const map = JSON.parse(JSON.stringify(_map));\n map.forEach((row, rowIndex) => {\n row.forEach((cell, cellIndex) => {\n map[rowIndex][cellIndex] = { value: cell, x: rowIndex, y: cellIndex, visited: false }\n })\n })\n\n const isolatedsOfType = [];\n map.flat().forEach(element => {\n if (element.value === type && !element.visited) {\n let separateArrays = [];\n traverse(element, type, map, separateArrays);\n isolatedsOfType.push(separateArrays);\n }\n })\n\n return isolatedsOfType;\n}\n\nconst traverse = (item, type, map, separateArrays) => {\n map[item.x][item.y].visited = true;\n separateArrays.push({ x: item.x, y: item.y });\n traverseNeighbors(item, type, map).forEach(neighbor => {\n if (!neighbor.visited) {\n traverse(neighbor, type, map, separateArrays);\n }\n })\n}\n\nconst traverseNeighbors = (item, type, map) => {\n const neighbors = [];\n\n if(item.x - 1 >= 0){\n neighbors.push({x: item.x-1, y: item.y ,value: map[item.x-1][item.y]});\n }\n if(item.y - 1 >= 0){\n neighbors.push({x: item.x, y: item.y-1 ,value: map[item.x][item.y-1]});\n }\n if (item.x + 1 < map.length && map[item.x + 1][item.y].value === type) {\n neighbors.push(map[item.x + 1][item.y]);\n }\n if (item.y + 1 < map.length && map[item.x][item.y + 1].value === type) {\n neighbors.push(map[item.x][item.y + 1]);\n }\n\n return neighbors;\n}\n\nconst matrix = [\n [\"M\", \"M\", \"0\", \"V\", \"V\", \"0\"],\n [\"0\", \"0\", \"0\", \"V\", \"0\", \"0\"],\n [\"0\", \"V\", \"V\", \"V\", \"0\", \"0\"],\n [\"0\", \"V\", \"V\", \"0\", \"0\", \"0\"],\n [\"0\", \"0\", \"0\", \"M\", \"M\", \"M\"],\n [\"0\", \"M\", \"0\", \"0\", \"0\", \"0\"],\n];\n\nconsole.log(findIsolated(\"M\", matrix))\n [\n [ { x: 0, y: 0 }, { x: 0, y: 1 } ],\n [ { x: 4, y: 3 }, { x: 4, y: 4 }, { x: 4, y: 5 } ]\n]\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12783473/" ]
74,525,433
<p>I am creating something like google drive or some cloud using PHP and HTML where you can save your files but i have problem with saving files to binary code and uploading it to database. I mean i want to do something like that:</p> <p>User is uploading file by form in html -&gt; converting file to binary -&gt; saving it in database. User can download his file by some button or smh like that -&gt; file is converting from binary to file.</p> <p>I tried with doing a script what will save bin code in my database but when i am trying to send some files i am getting error like that:</p> <pre><code>Fatal error: Uncaught TypeError: fopen(): Argument #1 ($filename) must be of type string, array given in C:\xampp\htdocs\fileshub\src\send_file.php:12 Stack trace: #0 C:\xampp\htdocs\fileshub\src\send_file.php(12): fopen(Array, 'rb') #1 {main} thrown in C:\xampp\htdocs\fileshub\src\send_file.php on line 12 </code></pre> <p>This is my form in html:</p> <pre class="lang-html prettyprint-override"><code>&lt;form class=&quot;upload-form&quot; action=&quot;./src/send_file.php&quot; method=&quot;post&quot; enctype=&quot;multipart/form-data&quot;&gt;&lt;br&gt; &lt;input type=&quot;text&quot; name=&quot;filename&quot; id=&quot;filename&quot; placeholder=&quot;File name&quot;&gt; &lt;input type=&quot;file&quot; name=&quot;file&quot; id=&quot;file&quot;&gt;&lt;br&gt; &lt;button type=&quot;sumbit&quot; class=&quot;submit&quot;&gt;Submit&lt;/button&gt; &lt;/form&gt; </code></pre> <p>And this is my script in php:</p> <pre class="lang-php prettyprint-override"><code>&lt;?php session_start(); include &quot;../src/db_conn.php&quot;; if(isset($_SESSION['id'])) { $id = $_SESSION['id']; // id usera $filename = $_POST['filename']; // nazwa pliku $file = $_FILES['file']; $data = fopen ($file, 'rb'); $size = filesize ($file); $contents = fread ($data, $size); fclose ($data); $binfile = base64_encode($contents); if(!$filename|| !$file) { header(&quot;Location: ../index.php?error=Enter your data!&quot;); exit(); } else { $check = &quot;SELECT bin_code FROM files WHERE user_id = '$id' AND bin_code = '$binfile' AND file_name = '$filename'&quot;; $result = mysqli_query($conn, $check); if(mysqli_num_rows($result) === 1){ header(&quot;Location: ../index.php?error=Your file exsist.&quot;); exit(); }else { $save = &quot;INSERT INTO files (user_id, file_name, bin_code) values('$id', '$filename', $binfile)&quot;; $saveresult = mysqli_query($conn, $save); $saveresult; header(&quot;Location: ../index.php?error=Your file has been saved&quot;); exit(); } } } ?&gt; </code></pre> <p>db_conn:</p> <pre><code>&lt;?php $server = &quot;localhost&quot;; $user =&quot;root&quot;; $password = &quot;&quot;; $db = &quot;fileshub&quot;; $conn = mysqli_connect($server, $user, $password, $db); ?&gt; </code></pre> <p>If you know any solutions for my problem please help :)</p> <p><a href="https://i.stack.imgur.com/lGASe.png" rel="nofollow noreferrer">Files table</a> <a href="https://i.stack.imgur.com/lYIyU.png" rel="nofollow noreferrer">Users table and example user</a></p>
[ { "answer_id": 74528327, "author": "Peter Thoeny", "author_id": 7475450, "author_profile": "https://Stackoverflow.com/users/7475450", "pm_score": 1, "selected": false, "text": "function findIsolated(target, matrix) {\n let result = [];\n matrix.forEach((row, rIdx) => {\n row.forEach((char, cIdx) => {\n // only look at target char:\n if(char === target) {\n let found = false;\n // check if the cell to the left is the same as the target char:\n if(cIdx > 0 && row[cIdx - 1] === target) {\n // search result set if cell to the left is already listed:\n result.forEach(set => {\n if(set.x === cIdx -1 && set.y === rIdx) {\n // found it, so add this coordinate to the set:\n set.push({ x: rIdx, y: cIdx});\n found = true;\n }\n });\n }\n // check if the cell above is the same as the target char:\n if(!found && rIdx > 0 && matrix[rIdx - 1][cIdx] === target) {\n // search result set if cell to above is already listed:\n result.forEach(set => {\n if(set.x === cIdx && set.y === rIdx - 1) {\n // found it, so add this coordinate to the set:\n set.push({ x: rIdx, y: cIdx});\n found = true;\n }\n });\n }\n if(!found) {\n // target char has not been found in result, so start a new set\n let set = [ { x: rIdx, y: cIdx} ];\n result.push([ set ]);\n }\n }\n });\n });\n return result;\n}\n\nconst matrix = [\n [ 'M', 'M', '0', 'V', 'V', '0' ], \n [ '0', '0', '0', 'V', '0', '0' ], \n [ '0', 'V', 'V', 'V', '0', '0' ], \n [ '0', 'V', 'V', '0', '0', '0' ], \n [ '0', '0', '0', 'M', 'M', 'M' ], \n [ '0', '0', '0', '0', '0', '0' ], \n];\nconsole.log('M: ' + JSON.stringify(findIsolated('M', matrix)));\nconsole.log('V: ' + JSON.stringify(findIsolated('V', matrix))); M: [[[{\"x\":0,\"y\":0}]],[[{\"x\":0,\"y\":1}]],[[{\"x\":4,\"y\":3}]],[[{\"x\":4,\"y\":4}]],[[{\"x\":4,\"y\":5}]]]\nV: [[[{\"x\":0,\"y\":3}]],[[{\"x\":0,\"y\":4}]],[[{\"x\":1,\"y\":3}]],[[{\"x\":2,\"y\":1}]],[[{\"x\":2,\"y\":2}]],[[{\"x\":2,\"y\":3}]],[[{\"x\":3,\"y\":1}]],[[{\"x\":3,\"y\":2}]]]\n" }, { "answer_id": 74531463, "author": "PizzaPeet", "author_id": 12783473, "author_profile": "https://Stackoverflow.com/users/12783473", "pm_score": 0, "selected": false, "text": "const findIsolated = (type, _map) => {\n const map = JSON.parse(JSON.stringify(_map));\n map.forEach((row, rowIndex) => {\n row.forEach((cell, cellIndex) => {\n map[rowIndex][cellIndex] = { value: cell, x: rowIndex, y: cellIndex, visited: false }\n })\n })\n\n const isolatedsOfType = [];\n map.flat().forEach(element => {\n if (element.value === type && !element.visited) {\n let separateArrays = [];\n traverse(element, type, map, separateArrays);\n isolatedsOfType.push(separateArrays);\n }\n })\n\n return isolatedsOfType;\n}\n\nconst traverse = (item, type, map, separateArrays) => {\n map[item.x][item.y].visited = true;\n separateArrays.push({ x: item.x, y: item.y });\n traverseNeighbors(item, type, map).forEach(neighbor => {\n if (!neighbor.visited) {\n traverse(neighbor, type, map, separateArrays);\n }\n })\n}\n\nconst traverseNeighbors = (item, type, map) => {\n const neighbors = [];\n\n if(item.x - 1 >= 0){\n neighbors.push({x: item.x-1, y: item.y ,value: map[item.x-1][item.y]});\n }\n if(item.y - 1 >= 0){\n neighbors.push({x: item.x, y: item.y-1 ,value: map[item.x][item.y-1]});\n }\n if (item.x + 1 < map.length && map[item.x + 1][item.y].value === type) {\n neighbors.push(map[item.x + 1][item.y]);\n }\n if (item.y + 1 < map.length && map[item.x][item.y + 1].value === type) {\n neighbors.push(map[item.x][item.y + 1]);\n }\n\n return neighbors;\n}\n\nconst matrix = [\n [\"M\", \"M\", \"0\", \"V\", \"V\", \"0\"],\n [\"0\", \"0\", \"0\", \"V\", \"0\", \"0\"],\n [\"0\", \"V\", \"V\", \"V\", \"0\", \"0\"],\n [\"0\", \"V\", \"V\", \"0\", \"0\", \"0\"],\n [\"0\", \"0\", \"0\", \"M\", \"M\", \"M\"],\n [\"0\", \"M\", \"0\", \"0\", \"0\", \"0\"],\n];\n\nconsole.log(findIsolated(\"M\", matrix))\n [\n [ { x: 0, y: 0 }, { x: 0, y: 1 } ],\n [ { x: 4, y: 3 }, { x: 4, y: 4 }, { x: 4, y: 5 } ]\n]\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20557059/" ]
74,525,437
<p>I can't figure our how to delete rows with duplicated value of the column dates and, choose to delete the row which has missing value (NA) of inst, grouped by id.</p> <p>A minimal working example of my data is :</p> <pre><code>id &lt;- c(&quot;N101&quot;, &quot;N102&quot;, &quot;N103&quot;, &quot;N103&quot;, &quot;N103&quot;, &quot;N103&quot;, &quot;N104&quot;, &quot;N105&quot;, &quot;N107&quot;, &quot;N107&quot;, &quot;N108&quot;, &quot;N109&quot;, &quot;N110&quot;, &quot;N111&quot;, &quot;N112&quot;, &quot;N113&quot;, &quot;N114&quot;, &quot;N115&quot;, &quot;N116&quot;, &quot;N116&quot;) inst &lt;- c(&quot;angers&quot;, &quot;strasbourg&quot;, NA, &quot;angers&quot;, &quot;montpellier&quot;, NA, &quot;rouen&quot;, &quot;limoges&quot;, NA, &quot;brest&quot;, &quot;stanne&quot;, &quot;aphp_psl&quot;, &quot;stanne&quot;, &quot;strasbourg&quot;, &quot;clairval&quot;, &quot;stanne&quot;, &quot;stanne&quot;, &quot;caen&quot;, NA, &quot;brest&quot;) dates &lt;- c(&quot;2008-07-13&quot;, &quot;2008-02-13&quot;, &quot;2008-05-13&quot;, &quot;2008-05-13&quot;, &quot;2010-12-14&quot;, &quot;2011-12-19&quot;, &quot;2013-11-12&quot;, &quot;2014-01-31&quot;, &quot;2008-06-13&quot;, &quot;2009-06-09&quot;, &quot;2009-03-10&quot;, &quot;2008-12-10&quot;, &quot;2010-04-15&quot;, &quot;2008-01-13&quot;, &quot;2017-03-13&quot;, &quot;2014-05-14&quot;, &quot;2012-05-15&quot;, &quot;2009-10-22&quot;, &quot;2010-10-18&quot;, &quot;2011-05-03&quot;) df1 &lt;- data.frame (id, inst, dates) &gt; df1 id inst dates 1 N101 angers 2008-07-13 2 N102 strasbourg 2008-02-13 3 N103 &lt;NA&gt; 2008-05-13 4 N103 angers 2008-05-13 5 N103 montpellier 2010-12-14 6 N103 &lt;NA&gt; 2011-12-19 7 N104 rouen 2013-11-12 8 N105 limoges 2014-01-31 9 N107 &lt;NA&gt; 2008-06-13 10 N107 brest 2009-06-09 11 N108 stanne 2009-03-10 12 N109 aphp_psl 2008-12-10 13 N110 stanne 2010-04-15 14 N111 strasbourg 2008-01-13 15 N112 clairval 2017-03-13 16 N113 stanne 2014-05-14 17 N114 stanne 2012-05-15 18 N115 caen 2009-10-22 19 N116 &lt;NA&gt; 2010-10-18 20 N116 brest 2011-05-03 </code></pre> <p>In the MWE above, the row 3 <code>3 N103 &lt;NA&gt; 2008-05-13</code> should be deleted and produce the df:</p> <pre><code>id &lt;- c(&quot;N101&quot;, &quot;N102&quot;, &quot;N103&quot;, &quot;N103&quot;, &quot;N103&quot;, &quot;N104&quot;, &quot;N105&quot;, &quot;N107&quot;, &quot;N107&quot;, &quot;N108&quot;, &quot;N109&quot;, &quot;N110&quot;, &quot;N111&quot;, &quot;N112&quot;, &quot;N113&quot;, &quot;N114&quot;, &quot;N115&quot;, &quot;N116&quot;, &quot;N116&quot;) inst &lt;- c(&quot;angers&quot;, &quot;strasbourg&quot;, &quot;angers&quot;, &quot;montpellier&quot;, NA, &quot;rouen&quot;, &quot;limoges&quot;, NA, &quot;brest&quot;, &quot;stanne&quot;, &quot;aphp_psl&quot;, &quot;stanne&quot;, &quot;strasbourg&quot;, &quot;clairval&quot;, &quot;stanne&quot;, &quot;stanne&quot;, &quot;caen&quot;, NA, &quot;brest&quot;) dates &lt;- c(&quot;2008-07-13&quot;, &quot;2008-02-13&quot;, &quot;2008-05-13&quot;, &quot;2010-12-14&quot;, &quot;2011-12-19&quot;, &quot;2013-11-12&quot;, &quot;2014-01-31&quot;, &quot;2008-06-13&quot;, &quot;2009-06-09&quot;, &quot;2009-03-10&quot;, &quot;2008-12-10&quot;, &quot;2010-04-15&quot;, &quot;2008-01-13&quot;, &quot;2017-03-13&quot;, &quot;2014-05-14&quot;, &quot;2012-05-15&quot;, &quot;2009-10-22&quot;, &quot;2010-10-18&quot;, &quot;2011-05-03&quot;) df2 &lt;- data.frame (id, inst, dates) &gt; df2 id inst dates 1 N101 angers 2008-07-13 2 N102 strasbourg 2008-02-13 3 N103 angers 2008-05-13 4 N103 montpellier 2010-12-14 5 N103 &lt;NA&gt; 2011-12-19 6 N104 rouen 2013-11-12 7 N105 limoges 2014-01-31 8 N107 &lt;NA&gt; 2008-06-13 9 N107 brest 2009-06-09 10 N108 stanne 2009-03-10 11 N109 aphp_psl 2008-12-10 12 N110 stanne 2010-04-15 13 N111 strasbourg 2008-01-13 14 N112 clairval 2017-03-13 15 N113 stanne 2014-05-14 16 N114 stanne 2012-05-15 17 N115 caen 2009-10-22 18 N116 &lt;NA&gt; 2010-10-18 19 N116 brest 2011-05-03 </code></pre> <p>Any idea ?</p> <p>Thank you for your help.</p>
[ { "answer_id": 74525532, "author": "thelatemail", "author_id": 496803, "author_profile": "https://Stackoverflow.com/users/496803", "pm_score": 2, "selected": false, "text": "o <- order(df1$id, df1$dates, is.na(df1$inst))\ndf1[o,][!duplicated(df1[o, c(\"id\",\"dates\")]),]\n# id inst dates\n#1 N101 angers 2008-07-13\n#2 N102 strasbourg 2008-02-13\n#4 N103 angers 2008-05-13\n#5 N103 montpellier 2010-12-14\n#6 N103 <NA> 2011-12-19\n#7 N104 rouen 2013-11-12\n#8 N105 limoges 2014-01-31\n#9 N107 <NA> 2008-06-13\n#10 N107 brest 2009-06-09\n#11 N108 stanne 2009-03-10\n#12 N109 aphp_psl 2008-12-10\n#13 N110 stanne 2010-04-15\n#14 N111 strasbourg 2008-01-13\n#15 N112 clairval 2017-03-13\n#16 N113 stanne 2014-05-14\n#17 N114 stanne 2012-05-15\n#18 N115 caen 2009-10-22\n#19 N116 <NA> 2010-10-18\n#20 N116 brest 2011-05-03\n df1 %>%\n arrange(id, dates, is.na(inst)) %>%\n filter(!duplicated(select(., id, dates)))\n" }, { "answer_id": 74525561, "author": "arg0naut91", "author_id": 8389003, "author_profile": "https://Stackoverflow.com/users/8389003", "pm_score": 2, "selected": false, "text": "dplyr library(dplyr)\n\ndf1 %>%\n group_by(id, dates) %>%\n filter(!(is.na(inst) & n() > 1L))\n # A tibble: 19 x 3\n# Groups: id, dates [19]\n id inst dates \n <fct> <fct> <fct> \n 1 N101 angers 2008-07-13\n 2 N102 strasbourg 2008-02-13\n 3 N103 angers 2008-05-13\n 4 N103 montpellier 2010-12-14\n 5 N103 NA 2011-12-19\n 6 N104 rouen 2013-11-12\n 7 N105 limoges 2014-01-31\n 8 N107 NA 2008-06-13\n 9 N107 brest 2009-06-09\n10 N108 stanne 2009-03-10\n11 N109 aphp_psl 2008-12-10\n12 N110 stanne 2010-04-15\n13 N111 strasbourg 2008-01-13\n14 N112 clairval 2017-03-13\n15 N113 stanne 2014-05-14\n16 N114 stanne 2012-05-15\n17 N115 caen 2009-10-22\n18 N116 NA 2010-10-18\n19 N116 brest 2011-05-03\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2856536/" ]
74,525,449
<p>I'm getting an error while translating a site using the ngx translate package. core.mjs:7643 ERROR Error: NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'May add up less than 3 characters'. Current value: 'Use at least 3 symbols'. When simply translating the page, I get an error that the expression has been changed after validation. How can I fix this behaviour?</p> <p>My component:</p> <pre><code>&lt;app-welcome-form&gt; &lt;form (submit)=&quot;userRegister($event)&quot; class=&quot;container&quot; [formGroup]=&quot;form&quot;&gt; &lt;mat-form-field hintLabel=&quot;{{ 'SIGNUP.USERNAME_HINT' | translate: { value: 3 } }}&quot; appearance=&quot;fill&quot; &gt; &lt;mat-label&gt;{{ &quot;SIGNUP.USERNAME&quot; | translate }}&lt;/mat-label&gt; &lt;input matInput #input placeholder=&quot;{{ 'SIGNUP.USERNAME' | translate }}&quot; name=&quot;username&quot; formControlName=&quot;username&quot; /&gt; &lt;/mat-form-field&gt; &lt;app-password-field titleOfField=&quot;{{ 'SIGNUP.PASSWORD' | translate }}&quot; [hintLabel]=&quot;'SIGNUP.PASSWORD_HINT' | translate: { value: 6 }&quot; [name]=&quot;'password'&quot; [formCtrl]=&quot;$any(form.controls['password'])&quot; &gt;&lt;/app-password-field&gt; &lt;app-password-field titleOfField=&quot;{{ 'SIGNUP.CONFIRMATION' | translate }}&quot; [hintLabel]=&quot;'SIGNUP.PASSWORD_HINT' | translate: { value: 6 }&quot; [name]=&quot;'password'&quot; [formCtrl]=&quot;$any(form.controls['passwordConfirmation'])&quot; &gt;&lt;/app-password-field&gt; &lt;button class=&quot;signup-btn&quot; mat-raised-button color=&quot;primary&quot; type=&quot;submit&quot;&gt; {{ &quot;SIGNUP.SIGNUP&quot; | translate }} &lt;/button&gt; &lt;/form&gt; &lt;p class=&quot;is-member&quot;&gt;{{ &quot;SIGNUP.MEMBER&quot; | translate }}&lt;/p&gt; &lt;a [routerLink]=&quot;'/' + loginPath&quot;&gt;{{ &quot;SIGNUP.SIGNIN&quot; | translate }}&lt;/a&gt; &lt;app-language-switcher&gt;&lt;/app-language-switcher&gt; &lt;/app-welcome-form&gt; </code></pre> <p>And function that translate it (simple function for a visual example):</p> <pre><code>ngOnInit(): void { this.translateService.use('en'); } changeLanguage() { if (this.language === 'en') { this.translateService.use('en'); } this.translateService.use('ua'); } </code></pre> <p>Any ideas would be helpful.</p>
[ { "answer_id": 74525532, "author": "thelatemail", "author_id": 496803, "author_profile": "https://Stackoverflow.com/users/496803", "pm_score": 2, "selected": false, "text": "o <- order(df1$id, df1$dates, is.na(df1$inst))\ndf1[o,][!duplicated(df1[o, c(\"id\",\"dates\")]),]\n# id inst dates\n#1 N101 angers 2008-07-13\n#2 N102 strasbourg 2008-02-13\n#4 N103 angers 2008-05-13\n#5 N103 montpellier 2010-12-14\n#6 N103 <NA> 2011-12-19\n#7 N104 rouen 2013-11-12\n#8 N105 limoges 2014-01-31\n#9 N107 <NA> 2008-06-13\n#10 N107 brest 2009-06-09\n#11 N108 stanne 2009-03-10\n#12 N109 aphp_psl 2008-12-10\n#13 N110 stanne 2010-04-15\n#14 N111 strasbourg 2008-01-13\n#15 N112 clairval 2017-03-13\n#16 N113 stanne 2014-05-14\n#17 N114 stanne 2012-05-15\n#18 N115 caen 2009-10-22\n#19 N116 <NA> 2010-10-18\n#20 N116 brest 2011-05-03\n df1 %>%\n arrange(id, dates, is.na(inst)) %>%\n filter(!duplicated(select(., id, dates)))\n" }, { "answer_id": 74525561, "author": "arg0naut91", "author_id": 8389003, "author_profile": "https://Stackoverflow.com/users/8389003", "pm_score": 2, "selected": false, "text": "dplyr library(dplyr)\n\ndf1 %>%\n group_by(id, dates) %>%\n filter(!(is.na(inst) & n() > 1L))\n # A tibble: 19 x 3\n# Groups: id, dates [19]\n id inst dates \n <fct> <fct> <fct> \n 1 N101 angers 2008-07-13\n 2 N102 strasbourg 2008-02-13\n 3 N103 angers 2008-05-13\n 4 N103 montpellier 2010-12-14\n 5 N103 NA 2011-12-19\n 6 N104 rouen 2013-11-12\n 7 N105 limoges 2014-01-31\n 8 N107 NA 2008-06-13\n 9 N107 brest 2009-06-09\n10 N108 stanne 2009-03-10\n11 N109 aphp_psl 2008-12-10\n12 N110 stanne 2010-04-15\n13 N111 strasbourg 2008-01-13\n14 N112 clairval 2017-03-13\n15 N113 stanne 2014-05-14\n16 N114 stanne 2012-05-15\n17 N115 caen 2009-10-22\n18 N116 NA 2010-10-18\n19 N116 brest 2011-05-03\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20466118/" ]
74,525,477
<p>I have two arrays--one of strings and one of objects. I find duplicates in the first array and get a count. I want to add the integer value i found in the counts object to the pbentry using the Product2Id as the key. I honestly haven't been able to figure it out and hours of google-fu has resulted in nothing.</p> <p>but the amount of those id values in count will always be equal to the amount of product2Id in pbentry.</p> <p>Desired outcome:</p> <pre><code>[{&quot;Id&quot;:&quot;01u8D00000105oqQAA&quot;,&quot;Product2Id&quot;:&quot;01t8D000001fDfjQAE&quot;,&quot;Count&quot;:&quot;3&quot;}, {&quot;Id&quot;:&quot;01u8D00000105oxQAA&quot;,&quot;Product2Id&quot;:&quot;01t8D000001fDfqQAE&quot;,&quot;Count&quot;:&quot;1&quot;}, {&quot;Id&quot;:&quot;01u8D00000105p2QAA&quot;,&quot;Product2Id&quot;:&quot;01t8D000001fDfvQAE&quot;,&quot;Count&quot;:&quot;1&quot;}, {&quot;Id&quot;:&quot;01u8D000003WBH5QAO&quot;,&quot;Product2Id&quot;:&quot;01t1O000004XyR0QAK&quot;,&quot;Count&quot;:&quot;2&quot;}, {&quot;Id&quot;:&quot;01u8D000003WBH0QAO&quot;,&quot;Product2Id&quot;:&quot;01t8D000001hKF1QAM&quot;,&quot;Count&quot;:&quot;1&quot;}....]; </code></pre> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>let counts = {}; let array = ["01t8D0000014jiuQAA", "01t5Y000006VydJQAS", "01t8D000001fDfjQAE", "01t8D000001fDfjQAE", "01t8D000001hKF1QAM", "01t1O000004XyR0QAK", "01t14000006956yAAA", "01t1O000004XyR0QAK", "01t8D000001fDfqQAE", "01t8D000001f1yeQAA", "01t8D000001fDfvQAE", "01t8D000001fDfjQAE"]; let pbentry = [{"Id":"01u8D000003WBHAQA4","Product2Id":"01t14000006956yAAA"},{"Id":"01u8D000003WBH5QAO","Product2Id":"01t1O000004XyR0QAK"}, {"Id":"01u8D000000zEfiQAE","Product2Id":"01t5Y000006VydJQAS"},{"Id":"01u8D000003WBGqQAO","Product2Id":"01t8D0000014jiuQAA"}, {"Id":"01u8D000003WBHyQAO","Product2Id":"01t8D000001f1yeQAA"},{"Id":"01u8D00000105oqQAA","Product2Id":"01t8D000001fDfjQAE"}, {"Id":"01u8D00000105oxQAA","Product2Id":"01t8D000001fDfqQAE"},{"Id":"01u8D00000105p2QAA","Product2Id":"01t8D000001fDfvQAE"}, {"Id":"01u8D000003WBH0QAO","Product2Id":"01t8D000001hKF1QAM"}]; array.forEach(function (x) { counts[x] = (counts[x] || 0) + 1; }); console.log(pbentry)</code></pre> </div> </div> </p>
[ { "answer_id": 74525625, "author": "jsN00b", "author_id": 13658816, "author_profile": "https://Stackoverflow.com/users/13658816", "pm_score": -1, "selected": false, "text": "const myTransform = (countArr, infoArr) => (\n // iterate over the infoArr\n infoArr?.map(({Product2Id, ...rest}) => ({\n // populate Product2Id & other fields as-is\n ...rest, Product2Id,\n // set-up \"Count\" using \"countArr\" (by filtering for particular Product2Id\n // and getting the length of the filtered array)\n Count: countArr?.filter(x => x === Product2Id)?.length,\n }))\n);\n\nlet counts = {};\nlet myArray = [\"01t8D0000014jiuQAA\", \"01t5Y000006VydJQAS\", \"01t8D000001fDfjQAE\", \"01t8D000001fDfjQAE\", \"01t8D000001hKF1QAM\",\n \"01t1O000004XyR0QAK\", \"01t14000006956yAAA\", \"01t1O000004XyR0QAK\", \"01t8D000001fDfqQAE\", \"01t8D000001f1yeQAA\",\n \"01t8D000001fDfvQAE\", \"01t8D000001fDfjQAE\"\n];\n\n\nlet pbentry = [{\n \"Id\": \"01u8D000003WBHAQA4\",\n \"Product2Id\": \"01t14000006956yAAA\"\n }, {\n \"Id\": \"01u8D000003WBH5QAO\",\n \"Product2Id\": \"01t1O000004XyR0QAK\"\n },\n {\n \"Id\": \"01u8D000000zEfiQAE\",\n \"Product2Id\": \"01t5Y000006VydJQAS\"\n }, {\n \"Id\": \"01u8D000003WBGqQAO\",\n \"Product2Id\": \"01t8D0000014jiuQAA\"\n },\n {\n \"Id\": \"01u8D000003WBHyQAO\",\n \"Product2Id\": \"01t8D000001f1yeQAA\"\n }, {\n \"Id\": \"01u8D00000105oqQAA\",\n \"Product2Id\": \"01t8D000001fDfjQAE\"\n },\n {\n \"Id\": \"01u8D00000105oxQAA\",\n \"Product2Id\": \"01t8D000001fDfqQAE\"\n }, {\n \"Id\": \"01u8D00000105p2QAA\",\n \"Product2Id\": \"01t8D000001fDfvQAE\"\n },\n {\n \"Id\": \"01u8D000003WBH0QAO\",\n \"Product2Id\": \"01t8D000001hKF1QAM\"\n }\n];\n\nconsole.log(\n 'counting unique ids:\\n',\n myTransform(myArray, pbentry)\n); .as-console-wrapper {\n max-height: 100% !important;\n top: 0\n}" }, { "answer_id": 74525628, "author": "Joundill", "author_id": 6632744, "author_profile": "https://Stackoverflow.com/users/6632744", "pm_score": 0, "selected": false, "text": "pbentry pbentry = pbentry.map(pb => ({...pb, Count: counts[pb.Product2Id] || 0}))\n let counts = {}; \nlet array = [\"01t8D0000014jiuQAA\", \"01t5Y000006VydJQAS\", \"01t8D000001fDfjQAE\", \"01t8D000001fDfjQAE\", \"01t8D000001hKF1QAM\", \"01t1O000004XyR0QAK\", \"01t14000006956yAAA\", \"01t1O000004XyR0QAK\", \"01t8D000001fDfqQAE\", \"01t8D000001f1yeQAA\", \"01t8D000001fDfvQAE\", \"01t8D000001fDfjQAE\"];\nlet pbentry = [{\"Id\":\"01u8D000003WBHAQA4\",\"Product2Id\":\"01t14000006956yAAA\"},{\"Id\":\"01u8D000003WBH5QAO\",\"Product2Id\":\"01t1O000004XyR0QAK\"}, {\"Id\":\"01u8D000000zEfiQAE\",\"Product2Id\":\"01t5Y000006VydJQAS\"},{\"Id\":\"01u8D000003WBGqQAO\",\"Product2Id\":\"01t8D0000014jiuQAA\"},\n{\"Id\":\"01u8D000003WBHyQAO\",\"Product2Id\":\"01t8D000001f1yeQAA\"},{\"Id\":\"01u8D00000105oqQAA\",\"Product2Id\":\"01t8D000001fDfjQAE\"}, {\"Id\":\"01u8D00000105oxQAA\",\"Product2Id\":\"01t8D000001fDfqQAE\"},{\"Id\":\"01u8D00000105p2QAA\",\"Product2Id\":\"01t8D000001fDfvQAE\"}, {\"Id\":\"01u8D000003WBH0QAO\",\"Product2Id\":\"01t8D000001hKF1QAM\"}];\n\narray.forEach(function (x) { counts[x] = (counts[x] || 0) + 1; }); \n\npbentry = pbentry.map(pb => ({...pb, Count: counts[pb.Product2Id] || 0}))\n\nconsole.log(pbentry)" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10101412/" ]
74,525,492
<p>Suppose, I have a float value [<code>-12.3456</code>]. I want to show it like [<code> -12.34</code>].</p> <p>I wrote the following:</p> <pre><code> public override string ToString() { return $&quot;{x:0.00, 8}{y:0.00, 8}{z:0.00, 8}&quot;; } </code></pre> <p>but, the output is not what I expect.</p> <p>How can I do this?</p>
[ { "answer_id": 74525575, "author": "user366312", "author_id": 159072, "author_profile": "https://Stackoverflow.com/users/159072", "pm_score": 0, "selected": false, "text": "using System;\n\npublic class HelloWorld\n{\n public static void Main(string[] args)\n {\n Console.WriteLine (\"[{0, 10:0.00}]\", -12.3456);\n }\n}\n" }, { "answer_id": 74527964, "author": "vivek nuna", "author_id": 6527049, "author_profile": "https://Stackoverflow.com/users/6527049", "pm_score": 1, "selected": false, "text": "float f = (float)-12.3456;\nstring str = f.ToString(\"0.00\").PadLeft(8);\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/159072/" ]
74,525,506
<p>I created a form where a user selects options from a checkbox list. So when a user selects an option in the checkbox, I use a function to show the value of the input field using onchange within inner HTML. My question is, how do we remove that same inner HTML content if the user un-selects those options? So when the user toggles back and forth, it either appears or when un-selected, the value gets removed. Thanks</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function functionOne() { var x = document.getElementById("wheels").value; document.getElementById("demo").innerHTML = x; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;input type="checkbox" id="wheels" onchange="functionOne()" value="feature 1"&gt; &lt;div id="demo"&gt;&lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74525550, "author": "epascarello", "author_id": 14104, "author_profile": "https://Stackoverflow.com/users/14104", "pm_score": 2, "selected": true, "text": "function functionOne(cb) {\n var x = cb.checked ? cb.value : '';\n document.getElementById(\"demo\").innerHTML = x;\n\n} <input type=\"checkbox\" id=\"wheels\" onchange=\"functionOne(this)\" value=\"feature 1\">\n\n<div id=\"demo\"></div>" }, { "answer_id": 74525567, "author": "dbonev", "author_id": 4200334, "author_profile": "https://Stackoverflow.com/users/4200334", "pm_score": 1, "selected": false, "text": "document.getElementById(\"demo\").innerHTML = '';\n" }, { "answer_id": 74525637, "author": "Andy", "author_id": 1377002, "author_profile": "https://Stackoverflow.com/users/1377002", "pm_score": 0, "selected": false, "text": "checked true false if/else demo textContent innerHTML // Cache the elements\nconst wheels = document.getElementById('wheels');\nconst demo = document.getElementById('demo');\n\n// Add a listener to the wheels element which calls the\n// handler when it changes\nwheels.addEventListener('change', handleChange);\n\n// Here `this` refers to the clicked element. If its\n// checked property is `true` set the text content of\n// `demo` to its value, otherwise use an empty string instead\nfunction handleChange() {\n if (this.checked) {\n demo.textContent = this.value;\n } else {\n demo.textContent = '';\n }\n} <input type=\"checkbox\" id=\"wheels\" value=\"feature 1\">\n<div id=\"demo\"></div>" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16513652/" ]
74,525,516
<p>I am trying to compare column values of each rows of dataframe with predefined list of dictionary, and do filtering. I tried <code>pandas</code> to compare column value by row-wise with list of dictionary, but it is not quite working, I got type error. I think I may need to convert dataframe into dictionary then compare it with list of dictionary then convert back to dataframe with new column added, but this still not giving my desired output. Does anyone suggest possible workaround on this? How can we do this easily in python</p> <p><strong>working minimal example</strong></p> <pre><code>import pandas as pd indf=pd.DataFrame.from_dict(indf_dict) indf_lst=indf.to_dict(orient='records') matches=[] for each in rules_list: for row in indf_lst: if row in each: matches.append(row) </code></pre> <p>I tried <code>pandas</code> approach to check column values of every rows in <code>rules_list</code> but the attempt is not successful. Now I tried to convert <code>indf</code> dataframe to dictionary and compare two dictionary, but I have type error as follow:</p> <pre><code>TypeError Traceback (most recent call last) Input In [11], in &lt;cell line: 12&gt;() 12 for each in rules_list: 13 for row in indf_lst: ---&gt; 14 if row in each: 15 matches.append(row) TypeError: unhashable type: 'dict' </code></pre> <p><strong>objective</strong></p> <p>I need to compare columns of every rows with list of dictionary <code>rules_list</code>, and add new column which shows found match or not. How this can be done in python?</p> <p><strong>updated desired output</strong></p> <p>here is my desired output where I want to add two new columns when columns values hit match with list of dictionary <code>rules_list</code> that I defined.</p> <pre><code>output={'code0':{0:('5'),1:'nan',2:('98'),3:('98'),4:'nan',5:('15'),6:('40'),7:('52'),8:('52'),9:('40'),10:('52'),11:('52'),12:('58')},'code1':{0:('Agr','Serv'),1:('VA','HC','NIH','SAP','AUS','HOL','ATT','COL','UCL'),2:('ATT','NC'),3:('ATT','VA','NC'),4:('VA','HC','NIH','ATT','COL','UCL'),5:('Agr'),6:'nan',7:('NC'),8:('NC'),9:('VA'),10:('NC'),11:('NC'),12:('CE')},'code2':{0:'nan',1:'nan',2:('103','104','105','106','31'),3:('104','105'),4:'nan',5:('5'),6:'nan',7:('109'),8:('109'),9:('11'),10:('109'),11:('109'),12:('109')},'code3':{0:('90'),1:'nan',2:('810'),3:('810'),4:'nan',5:('58'),6:('518'),7:('610','620','682','642','621','611'),8:('620','682','642','611'),9:('113','174','131','115'),10:('612','790','110'),11:('612','110'),12:('423','114')},'code4':{0:('1'),1:'nan',2:('computerscience'),3:('computerscience'),4:'nan',5:('fishing'),6:'nan',7:('biology'),8:('biology'),9:'nan',10:('biology'),11:('biology'),12:'nan'},'code5':{0:'nan',1:'nan',2:'nan',3:'nan',4:'nan',5:'nan',6:'nan',7:'nan',8:'nan',9:('11','19','31'),10:('12','16','18','19'),11:('12','18','19'),12:('31')},'code6':{0:'nan',1:'nan',2:'nan',3:'nan',4:'nan',5:'nan',6:('594'),7:('712','479','297','639','452','172'),8:('712','479','297'),9:('164','157','388','158'),10:('285','295','236','239','269','284','237'),11:('285','295','237'),12:('372','238')},'isHit':{0:False,1:True,2:True,3:True,4:True,5:False,6:True,7:True,8:True,9:True,10:True,11:True,12:True},'rules_desc':{0:'None',1:'rules1',2:'rules2',3:'rules2',4:'rules1',5:'None',6:'rules12',7:'rules21',8:'rules21',9:'rules4',10:'rules3',11:'rules3',12:'rules5'}} outdf=pd.DataFrame.from_dict(output) </code></pre> <p>how can I achieve this sort of mapping value from each cell of dataframe to list of dictionary? should I handle this in pandas or convert them into list then compare it? any possible thoughts? Anything close to above desired output should be fine.</p>
[ { "answer_id": 74525925, "author": "Tim Roberts", "author_id": 1883316, "author_profile": "https://Stackoverflow.com/users/1883316", "pm_score": 1, "selected": false, "text": "all {0:'5',2:'98'...} 0 2 for row in indf_dict:\n for rno,rule in enumerate(rules_list):\n print(\"New rule\", rno)\n match = all( val in row[key].values() for key,val in rule.items() if key in row)\n if match:\n print(\"Rule\", rno, \"matches\")\n New rule 0\nRule 0 matches\nNew rule 1\nRule 1 matches\nNew rule 2\nRule 2 matches\nNew rule 3\nNew rule 4\nRule 4 matches\nNew rule 5\nNew rule 6\nRule 6 matches\nNew rule 7\nNew rule 8\nRule 8 matches\nNew rule 9\nRule 9 matches\n" }, { "answer_id": 74527064, "author": "Claudio", "author_id": 7711283, "author_profile": "https://Stackoverflow.com/users/7711283", "pm_score": 3, "selected": true, "text": "from pprint import pprint\nimport pandas as pd\nfrom collections import defaultdict\n# ----------------------------------------------------------------------\nrules_list=rules_dict=[{'code1':('VA','HC','NIH','SAP','AUS','HOL','ATT','COL','UCL'),'rules_desc':'rules1'},{'code0':('40'),'code3':('518'),'code6':('594'),'rules_desc':'rules12'},{'code0':('98'),'code1':('ATT','NC'),'code2':('103','104','105','106','31'),'code3':('810'),'code4':('computerscience'),'rules_desc':'rules2'},{'code0':('98'),'code1':('ATT','VA','NC'),'code2':('104','105','106','31'),'code4':('computerscience'),'rules_desc':'rules2'},{'code0':('52'),'code1':('NC'),'code2':('109'),'code3':('610','620','682','642','621','611'),'code4':('biology'),'code6':('712','479','297','639','452','172'),'rules_desc':'rules2'},{'code0':('52'),'code1':('NC'),'code2':('109'),'code3':('396','340','394','393','240'),'code4':('biology'),'code5':('12','18'),'rules_desc':'rules2'},{'code0':('52'),'code1':('NC'),'code2':('109'),'code3':('612','790','110'),'code4':('biology'),'code5':('12','16','18','19'),'code6':('285','295','236','239','269','284','237'),'rules_desc':'rules3'},{'code0':('52'),'code1':('NC'),'code2':('109'),'code3':('730','320','350','379','812','374'),'code4':('biology'),'code5':('12','18','19'),'rules_desc':'rules3'},{'code0':('40'),'code1':('VA'),'code2':('11'),'code3':('113','174','131','115'),'code5':('11','19','31'),'code6':('164','157','388','158'),'rules_desc':'rules4'},{'code0':('58'),'code1':('CE'),'code2':('109'),'code3':('423','114'),'code5':('31'),'code6':('372','238'),'rules_desc':'rules5'}]\n# codeNname : 'code1', 'code2', 'code3', ..., 'code6'\n# ruleNname : 'rules1', 'rules12', 'rules2', ..., 'rules5'\n# ruleDescrKey : 'rules_desc'\n# dictRulesSpec : dictionary { codeNname:value {1,N} ... , rulesDct_ruleKey:ruleNname }\n# dictCodes : dictionary { codeNname:value, codeNname:value, ... }\n# Rules : List [ dictRulesSpec, dictRulesSpec, ... ]\n# dictRules : { ruleNname:[codeNname, codeNnameValue], ... }\nRules = rules_list\nruleDescrKey = 'rules_desc'\ndictRules = defaultdict(list)\nfor dictRulesSpec in Rules:\n ruleNname = dictRulesSpec.pop(ruleDescrKey)\n # dictRulesSpec without ruleDescrKey item has only Codes as keys, so:\n dictCodes = dictRulesSpec \n for codeNname, codeNnameValue in dictCodes.items(): \n dictRules[ruleNname].append( (codeNname, codeNnameValue) ) \nprint(f'{Rules=}')\nprint(f'{dictRules=}')\nprint(' ------------- ')\n# ----------------------------------------------------------------------\nindf_dict={'code0':{0:('5'),1:'nan',2:('98'),3:('98'),4:'',5:('15'),6:('40'),7:('52'),8:('52'),9:('40'),10:('52'),11:('52'),12:('58')},'code1':{0:('Agr','Serv'),1:('VA','HC','NIH','SAP','AUS','HOL','ATT','COL','UCL'),2:('ATT','NC'),3:('ATT','VA','NC'),4:('VA','HC','NIH','ATT','COL','UCL'),5:('Agr'),6:'nan',7:('NC'),8:('NC'),9:('VA'),10:('NC'),11:('NC'),12:('CE')},'code2':{0:'nan',1:'nan',2:('103','104','105','106','31'),3:('104','105'),4:'nan',5:('5'),6:'nan',7:('109'),8:('109'),9:('11'),10:('109'),11:('109'),12:('109')},'code3':{0:('90'),1:'nan',2:('810'),3:('810'),4:'nan',5:('58'),6:('518'),7:('610','620','682','642','621','611'),8:('620','682','642','611'),9:('113','174','131','115'),10:('612','790','110'),11:('612','110'),12:('423','114')},'code4':{0:('1'),1:'nan',2:('computerscience'),3:('computerscience'),4:'nan',5:('fishing'),6:'nan',7:('biology'),8:('biology'),9:'nan',10:('biology'),11:('biology'),12:'nan'},'code5':{0:'nan',1:'nan',2:'nan',3:'nan',4:'nan',5:'nan',6:'nan',7:'nan',8:'nan',9:('11','19','31'),10:('12','16','18','19'),11:('12','18','19'),12:'31'},'code6':{0:'nan',1:'nan',2:'nan',3:'nan',4:'nan',5:'nan',6:'594',7:('712','479','297','639','452','172'),8:('712','479','297'),9:('164','157','388','158'),10:('285','295','236','239','269','284','237'),11:('285','295','237'),12:('372','238')}}\ndictDataRowsByCodeNname = indf_dict\ndf_dictDataRowsByCodeNname = pd.DataFrame.from_dict(dictDataRowsByCodeNname)\nprint(f'{dictDataRowsByCodeNname=}')\nlistDataRowsByRow = df_dictDataRowsByCodeNname.to_dict(orient='records')\nprint(f'{listDataRowsByRow=}')\nprint(' ------------- ')\nisHit_Column = []\nrules_desc_Column = []\n# The loop below tests for only one hit within the rule ...\nfor dctDataRow in listDataRowsByRow: \n isHit = False\n for ruleNname, listTuplesCodeNnameValue in dictRules.items():\n if isHit:\n break\n for codeNname, codeNnameValue in listTuplesCodeNnameValue:\n if isHit:\n break\n else:\n if dctDataRow[codeNname] == codeNnameValue: \n isHit = True\n bckpRuleNname = ruleNname\n break\n rules_desc_Column.append( bckpRuleNname if isHit else None)\n isHit_Column.append(isHit)\n\nprint(f'{rules_desc_Column = }')\nprint(f'{isHit_Column = }') \nprint('================================')\ndf_dictDataRowsByCodeNname['isHit'] = isHit_Column\ndf_dictDataRowsByCodeNname['rules_desc'] = rules_desc_Column\nprint(df_dictDataRowsByCodeNname)\nprint('================================')\n\nisHit_Column = []\nrules_desc_Column = []\n# The loop below tests for all hits within the rule and\n# lists all rules that apply in case of hits: \nfor dctDataRow in listDataRowsByRow: \n lstRulesWithHits = []\n for ruleNname, listTuplesCodeNnameValue in dictRules.items():\n ruleItemsWithHits = 0\n for codeNname, codeNnameValue in listTuplesCodeNnameValue:\n if dctDataRow[codeNname] == codeNnameValue: \n ruleItemsWithHits += 1\n if ruleItemsWithHits == len(listTuplesCodeNnameValue):\n lstRulesWithHits.append(ruleNname)\n isHit = bool(lstRulesWithHits)\n rules_desc_Column.append( lstRulesWithHits if isHit else None)\n isHit_Column.append(isHit)\ndf_dictDataRowsByCodeNname['isHit'] = isHit_Column\ndf_dictDataRowsByCodeNname['rules_desc'] = rules_desc_Column\nprint(df_dictDataRowsByCodeNname)\nprint('================================')\n Rules=[{'code1': ('VA', 'HC', 'NIH', 'SAP', 'AUS', 'HOL', 'ATT', 'COL', 'UCL')}, {'code0': '40', 'code3': '518', 'code6': '594'}, {'code0': '98', 'code1': ('ATT', 'NC'), 'code2': ('103', '104', '105', '106', '31'), 'code3': '810', 'code4': 'computerscience'}, {'code0': '98', 'code1': ('ATT', 'VA', 'NC'), 'code2': ('104', '105', '106', '31'), 'code4': 'computerscience'}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('610', '620', '682', '642', '621', '611'), 'code4': 'biology', 'code6': ('712', '479', '297', '639', '452', '172')}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('396', '340', '394', '393', '240'), 'code4': 'biology', 'code5': ('12', '18')}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('612', '790', '110'), 'code4': 'biology', 'code5': ('12', '16', '18', '19'), 'code6': ('285', '295', '236', '239', '269', '284', '237')}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('730', '320', '350', '379', '812', '374'), 'code4': 'biology', 'code5': ('12', '18', '19')}, {'code0': '40', 'code1': 'VA', 'code2': '11', 'code3': ('113', '174', '131', '115'), 'code5': ('11', '19', '31'), 'code6': ('164', '157', '388', '158')}, {'code0': '58', 'code1': 'CE', 'code2': '109', 'code3': ('423', '114'), 'code5': '31', 'code6': ('372', '238')}]\ndictRules=defaultdict(<class 'list'>, {'rules1': [('code1', ('VA', 'HC', 'NIH', 'SAP', 'AUS', 'HOL', 'ATT', 'COL', 'UCL'))], 'rules12': [('code0', '40'), ('code3', '518'), ('code6', '594')], 'rules2': [('code0', '98'), ('code1', ('ATT', 'NC')), ('code2', ('103', '104', '105', '106', '31')), ('code3', '810'), ('code4', 'computerscience'), ('code0', '98'), ('code1', ('ATT', 'VA', 'NC')), ('code2', ('104', '105', '106', '31')), ('code4', 'computerscience'), ('code0', '52'), ('code1', 'NC'), ('code2', '109'), ('code3', ('610', '620', '682', '642', '621', '611')), ('code4', 'biology'), ('code6', ('712', '479', '297', '639', '452', '172')), ('code0', '52'), ('code1', 'NC'), ('code2', '109'), ('code3', ('396', '340', '394', '393', '240')), ('code4', 'biology'), ('code5', ('12', '18'))], 'rules3': [('code0', '52'), ('code1', 'NC'), ('code2', '109'), ('code3', ('612', '790', '110')), ('code4', 'biology'), ('code5', ('12', '16', '18', '19')), ('code6', ('285', '295', '236', '239', '269', '284', '237')), ('code0', '52'), ('code1', 'NC'), ('code2', '109'), ('code3', ('730', '320', '350', '379', '812', '374')), ('code4', 'biology'), ('code5', ('12', '18', '19'))], 'rules4': [('code0', '40'), ('code1', 'VA'), ('code2', '11'), ('code3', ('113', '174', '131', '115')), ('code5', ('11', '19', '31')), ('code6', ('164', '157', '388', '158'))], 'rules5': [('code0', '58'), ('code1', 'CE'), ('code2', '109'), ('code3', ('423', '114')), ('code5', '31'), ('code6', ('372', '238'))]})\n ------------- \ndictDataRowsByCodeNname={'code0': {0: '5', 1: 'nan', 2: '98', 3: '98', 4: '', 5: '15', 6: '40', 7: '52', 8: '52', 9: '40', 10: '52', 11: '52', 12: '58'}, 'code1': {0: ('Agr', 'Serv'), 1: ('VA', 'HC', 'NIH', 'SAP', 'AUS', 'HOL', 'ATT', 'COL', 'UCL'), 2: ('ATT', 'NC'), 3: ('ATT', 'VA', 'NC'), 4: ('VA', 'HC', 'NIH', 'ATT', 'COL', 'UCL'), 5: 'Agr', 6: 'nan', 7: 'NC', 8: 'NC', 9: 'VA', 10: 'NC', 11: 'NC', 12: 'CE'}, 'code2': {0: 'nan', 1: 'nan', 2: ('103', '104', '105', '106', '31'), 3: ('104', '105'), 4: 'nan', 5: '5', 6: 'nan', 7: '109', 8: '109', 9: '11', 10: '109', 11: '109', 12: '109'}, 'code3': {0: '90', 1: 'nan', 2: '810', 3: '810', 4: 'nan', 5: '58', 6: '518', 7: ('610', '620', '682', '642', '621', '611'), 8: ('620', '682', '642', '611'), 9: ('113', '174', '131', '115'), 10: ('612', '790', '110'), 11: ('612', '110'), 12: ('423', '114')}, 'code4': {0: '1', 1: 'nan', 2: 'computerscience', 3: 'computerscience', 4: 'nan', 5: 'fishing', 6: 'nan', 7: 'biology', 8: 'biology', 9: 'nan', 10: 'biology', 11: 'biology', 12: 'nan'}, 'code5': {0: 'nan', 1: 'nan', 2: 'nan', 3: 'nan', 4: 'nan', 5: 'nan', 6: 'nan', 7: 'nan', 8: 'nan', 9: ('11', '19', '31'), 10: ('12', '16', '18', '19'), 11: ('12', '18', '19'), 12: '31'}, 'code6': {0: 'nan', 1: 'nan', 2: 'nan', 3: 'nan', 4: 'nan', 5: 'nan', 6: '594', 7: ('712', '479', '297', '639', '452', '172'), 8: ('712', '479', '297'), 9: ('164', '157', '388', '158'), 10: ('285', '295', '236', '239', '269', '284', '237'), 11: ('285', '295', '237'), 12: ('372', '238')}}\nlistDataRowsByRow=[{'code0': '5', 'code1': ('Agr', 'Serv'), 'code2': 'nan', 'code3': '90', 'code4': '1', 'code5': 'nan', 'code6': 'nan'}, {'code0': 'nan', 'code1': ('VA', 'HC', 'NIH', 'SAP', 'AUS', 'HOL', 'ATT', 'COL', 'UCL'), 'code2': 'nan', 'code3': 'nan', 'code4': 'nan', 'code5': 'nan', 'code6': 'nan'}, {'code0': '98', 'code1': ('ATT', 'NC'), 'code2': ('103', '104', '105', '106', '31'), 'code3': '810', 'code4': 'computerscience', 'code5': 'nan', 'code6': 'nan'}, {'code0': '98', 'code1': ('ATT', 'VA', 'NC'), 'code2': ('104', '105'), 'code3': '810', 'code4': 'computerscience', 'code5': 'nan', 'code6': 'nan'}, {'code0': '', 'code1': ('VA', 'HC', 'NIH', 'ATT', 'COL', 'UCL'), 'code2': 'nan', 'code3': 'nan', 'code4': 'nan', 'code5': 'nan', 'code6': 'nan'}, {'code0': '15', 'code1': 'Agr', 'code2': '5', 'code3': '58', 'code4': 'fishing', 'code5': 'nan', 'code6': 'nan'}, {'code0': '40', 'code1': 'nan', 'code2': 'nan', 'code3': '518', 'code4': 'nan', 'code5': 'nan', 'code6': '594'}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('610', '620', '682', '642', '621', '611'), 'code4': 'biology', 'code5': 'nan', 'code6': ('712', '479', '297', '639', '452', '172')}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('620', '682', '642', '611'), 'code4': 'biology', 'code5': 'nan', 'code6': ('712', '479', '297')}, {'code0': '40', 'code1': 'VA', 'code2': '11', 'code3': ('113', '174', '131', '115'), 'code4': 'nan', 'code5': ('11', '19', '31'), 'code6': ('164', '157', '388', '158')}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('612', '790', '110'), 'code4': 'biology', 'code5': ('12', '16', '18', '19'), 'code6': ('285', '295', '236', '239', '269', '284', '237')}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('612', '110'), 'code4': 'biology', 'code5': ('12', '18', '19'), 'code6': ('285', '295', '237')}, {'code0': '58', 'code1': 'CE', 'code2': '109', 'code3': ('423', '114'), 'code4': 'nan', 'code5': '31', 'code6': ('372', '238')}]\n ------------- \nrules_desc_Column = [None, 'rules12', 'rules3', 'rules3', None, None, 'rules2', 'rules3', 'rules3', 'rules2', 'rules3', 'rules3', 'rules3']\nisHit_Column = [False, True, True, True, False, False, True, True, True, True, True, True, True]\n================================\n code0 code1 ... isHit rules_desc\n0 5 (Agr, Serv) ... False None\n1 nan (VA, HC, NIH, SAP, AUS, HOL, ATT, COL, UCL) ... True rules12\n2 98 (ATT, NC) ... True rules3\n3 98 (ATT, VA, NC) ... True rules3\n4 (VA, HC, NIH, ATT, COL, UCL) ... False None\n5 15 Agr ... False None\n6 40 nan ... True rules2\n7 52 NC ... True rules3\n8 52 NC ... True rules3\n9 40 VA ... True rules2\n10 52 NC ... True rules3\n11 52 NC ... True rules3\n12 58 CE ... True rules3\n\n[13 rows x 9 columns]\n================================\n code0 code1 ... isHit rules_desc\n0 5 (Agr, Serv) ... False None\n1 nan (VA, HC, NIH, SAP, AUS, HOL, ATT, COL, UCL) ... True [rules1]\n2 98 (ATT, NC) ... False None\n3 98 (ATT, VA, NC) ... False None\n4 (VA, HC, NIH, ATT, COL, UCL) ... False None\n5 15 Agr ... False None\n6 40 nan ... True [rules12]\n7 52 NC ... False None\n8 52 NC ... False None\n9 40 VA ... True [rules4]\n10 52 NC ... False None\n11 52 NC ... False None\n12 58 CE ... True [rules5]\n\n[13 rows x 9 columns]\n================================\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7114383/" ]
74,525,533
<p>*/ write a function daysPastThisYear that takes the current date as the name of the current month and the current day, e.g., daysPastThisYear(month: &quot;May&quot;, day: 12), and returns how many days have past since the beginning of the year. Use a &quot;while&quot; loop. Ignore leap years. You may user the following list and dictionary defined: let monthNames = [&quot;January&quot;, &quot;February&quot;, &quot;March&quot;, &quot;April&quot;, &quot;May&quot;, &quot;June&quot;, &quot;July&quot;, &quot;August&quot;, &quot;September&quot;, &quot;October&quot;, &quot;November&quot;, &quot;December&quot;] let monthDays = [&quot;January&quot;: 31, &quot;February&quot;: 29, &quot;March&quot;: 31, &quot;April&quot;: 30, &quot;May&quot;: 31, &quot;June&quot;: 30, &quot;July&quot;: 31, &quot;August&quot;: 31, &quot;September&quot;: 30, &quot;October&quot;: 31, &quot;November&quot;: 30, &quot;December&quot;: 31]</p> <pre><code>E.g. print(daysPastThisYear(month: &quot;January&quot;, day: 12)) // prints 12 </code></pre> <p>*/</p> <pre><code>//My code so far: func daysPastThisYear(monthNames: [String], monthDays: [String:Int]) -&gt; Int { let monthNames = [&quot;January&quot;, &quot;February&quot;, &quot;March&quot;, &quot;April&quot;, &quot;May&quot;, &quot;June&quot;, &quot;July&quot;, &quot;August&quot;, &quot;September&quot;, &quot;October&quot;, &quot;November&quot;, &quot;December&quot;] let monthDays = [&quot;January&quot;: 31, &quot;February&quot;: 29, &quot;March&quot;: 31, &quot;April&quot;: 30, &quot;May&quot;: 31, &quot;June&quot;: 30, &quot;July&quot;: 31, &quot;August&quot;: 31, &quot;September&quot;: 30, &quot;October&quot;: 31, &quot;November&quot;: 30, &quot;December&quot;: 31] var i = 0 while month != monthNames[i] { i ++ } totalDays = 0 while i &gt; 0 { totalDays = totalDays + monthDays[i - 1] -= i totalDays = totalDays + day print(totalDays) } } print(daysPastThisYear(month: &quot;January&quot;, day: 12)) </code></pre> <p>Im an new to coding</p> <p>Tried to calculate the number of accumulated days implementing two while loops</p> <p>Multiple errors when attemtong to run</p>
[ { "answer_id": 74525925, "author": "Tim Roberts", "author_id": 1883316, "author_profile": "https://Stackoverflow.com/users/1883316", "pm_score": 1, "selected": false, "text": "all {0:'5',2:'98'...} 0 2 for row in indf_dict:\n for rno,rule in enumerate(rules_list):\n print(\"New rule\", rno)\n match = all( val in row[key].values() for key,val in rule.items() if key in row)\n if match:\n print(\"Rule\", rno, \"matches\")\n New rule 0\nRule 0 matches\nNew rule 1\nRule 1 matches\nNew rule 2\nRule 2 matches\nNew rule 3\nNew rule 4\nRule 4 matches\nNew rule 5\nNew rule 6\nRule 6 matches\nNew rule 7\nNew rule 8\nRule 8 matches\nNew rule 9\nRule 9 matches\n" }, { "answer_id": 74527064, "author": "Claudio", "author_id": 7711283, "author_profile": "https://Stackoverflow.com/users/7711283", "pm_score": 3, "selected": true, "text": "from pprint import pprint\nimport pandas as pd\nfrom collections import defaultdict\n# ----------------------------------------------------------------------\nrules_list=rules_dict=[{'code1':('VA','HC','NIH','SAP','AUS','HOL','ATT','COL','UCL'),'rules_desc':'rules1'},{'code0':('40'),'code3':('518'),'code6':('594'),'rules_desc':'rules12'},{'code0':('98'),'code1':('ATT','NC'),'code2':('103','104','105','106','31'),'code3':('810'),'code4':('computerscience'),'rules_desc':'rules2'},{'code0':('98'),'code1':('ATT','VA','NC'),'code2':('104','105','106','31'),'code4':('computerscience'),'rules_desc':'rules2'},{'code0':('52'),'code1':('NC'),'code2':('109'),'code3':('610','620','682','642','621','611'),'code4':('biology'),'code6':('712','479','297','639','452','172'),'rules_desc':'rules2'},{'code0':('52'),'code1':('NC'),'code2':('109'),'code3':('396','340','394','393','240'),'code4':('biology'),'code5':('12','18'),'rules_desc':'rules2'},{'code0':('52'),'code1':('NC'),'code2':('109'),'code3':('612','790','110'),'code4':('biology'),'code5':('12','16','18','19'),'code6':('285','295','236','239','269','284','237'),'rules_desc':'rules3'},{'code0':('52'),'code1':('NC'),'code2':('109'),'code3':('730','320','350','379','812','374'),'code4':('biology'),'code5':('12','18','19'),'rules_desc':'rules3'},{'code0':('40'),'code1':('VA'),'code2':('11'),'code3':('113','174','131','115'),'code5':('11','19','31'),'code6':('164','157','388','158'),'rules_desc':'rules4'},{'code0':('58'),'code1':('CE'),'code2':('109'),'code3':('423','114'),'code5':('31'),'code6':('372','238'),'rules_desc':'rules5'}]\n# codeNname : 'code1', 'code2', 'code3', ..., 'code6'\n# ruleNname : 'rules1', 'rules12', 'rules2', ..., 'rules5'\n# ruleDescrKey : 'rules_desc'\n# dictRulesSpec : dictionary { codeNname:value {1,N} ... , rulesDct_ruleKey:ruleNname }\n# dictCodes : dictionary { codeNname:value, codeNname:value, ... }\n# Rules : List [ dictRulesSpec, dictRulesSpec, ... ]\n# dictRules : { ruleNname:[codeNname, codeNnameValue], ... }\nRules = rules_list\nruleDescrKey = 'rules_desc'\ndictRules = defaultdict(list)\nfor dictRulesSpec in Rules:\n ruleNname = dictRulesSpec.pop(ruleDescrKey)\n # dictRulesSpec without ruleDescrKey item has only Codes as keys, so:\n dictCodes = dictRulesSpec \n for codeNname, codeNnameValue in dictCodes.items(): \n dictRules[ruleNname].append( (codeNname, codeNnameValue) ) \nprint(f'{Rules=}')\nprint(f'{dictRules=}')\nprint(' ------------- ')\n# ----------------------------------------------------------------------\nindf_dict={'code0':{0:('5'),1:'nan',2:('98'),3:('98'),4:'',5:('15'),6:('40'),7:('52'),8:('52'),9:('40'),10:('52'),11:('52'),12:('58')},'code1':{0:('Agr','Serv'),1:('VA','HC','NIH','SAP','AUS','HOL','ATT','COL','UCL'),2:('ATT','NC'),3:('ATT','VA','NC'),4:('VA','HC','NIH','ATT','COL','UCL'),5:('Agr'),6:'nan',7:('NC'),8:('NC'),9:('VA'),10:('NC'),11:('NC'),12:('CE')},'code2':{0:'nan',1:'nan',2:('103','104','105','106','31'),3:('104','105'),4:'nan',5:('5'),6:'nan',7:('109'),8:('109'),9:('11'),10:('109'),11:('109'),12:('109')},'code3':{0:('90'),1:'nan',2:('810'),3:('810'),4:'nan',5:('58'),6:('518'),7:('610','620','682','642','621','611'),8:('620','682','642','611'),9:('113','174','131','115'),10:('612','790','110'),11:('612','110'),12:('423','114')},'code4':{0:('1'),1:'nan',2:('computerscience'),3:('computerscience'),4:'nan',5:('fishing'),6:'nan',7:('biology'),8:('biology'),9:'nan',10:('biology'),11:('biology'),12:'nan'},'code5':{0:'nan',1:'nan',2:'nan',3:'nan',4:'nan',5:'nan',6:'nan',7:'nan',8:'nan',9:('11','19','31'),10:('12','16','18','19'),11:('12','18','19'),12:'31'},'code6':{0:'nan',1:'nan',2:'nan',3:'nan',4:'nan',5:'nan',6:'594',7:('712','479','297','639','452','172'),8:('712','479','297'),9:('164','157','388','158'),10:('285','295','236','239','269','284','237'),11:('285','295','237'),12:('372','238')}}\ndictDataRowsByCodeNname = indf_dict\ndf_dictDataRowsByCodeNname = pd.DataFrame.from_dict(dictDataRowsByCodeNname)\nprint(f'{dictDataRowsByCodeNname=}')\nlistDataRowsByRow = df_dictDataRowsByCodeNname.to_dict(orient='records')\nprint(f'{listDataRowsByRow=}')\nprint(' ------------- ')\nisHit_Column = []\nrules_desc_Column = []\n# The loop below tests for only one hit within the rule ...\nfor dctDataRow in listDataRowsByRow: \n isHit = False\n for ruleNname, listTuplesCodeNnameValue in dictRules.items():\n if isHit:\n break\n for codeNname, codeNnameValue in listTuplesCodeNnameValue:\n if isHit:\n break\n else:\n if dctDataRow[codeNname] == codeNnameValue: \n isHit = True\n bckpRuleNname = ruleNname\n break\n rules_desc_Column.append( bckpRuleNname if isHit else None)\n isHit_Column.append(isHit)\n\nprint(f'{rules_desc_Column = }')\nprint(f'{isHit_Column = }') \nprint('================================')\ndf_dictDataRowsByCodeNname['isHit'] = isHit_Column\ndf_dictDataRowsByCodeNname['rules_desc'] = rules_desc_Column\nprint(df_dictDataRowsByCodeNname)\nprint('================================')\n\nisHit_Column = []\nrules_desc_Column = []\n# The loop below tests for all hits within the rule and\n# lists all rules that apply in case of hits: \nfor dctDataRow in listDataRowsByRow: \n lstRulesWithHits = []\n for ruleNname, listTuplesCodeNnameValue in dictRules.items():\n ruleItemsWithHits = 0\n for codeNname, codeNnameValue in listTuplesCodeNnameValue:\n if dctDataRow[codeNname] == codeNnameValue: \n ruleItemsWithHits += 1\n if ruleItemsWithHits == len(listTuplesCodeNnameValue):\n lstRulesWithHits.append(ruleNname)\n isHit = bool(lstRulesWithHits)\n rules_desc_Column.append( lstRulesWithHits if isHit else None)\n isHit_Column.append(isHit)\ndf_dictDataRowsByCodeNname['isHit'] = isHit_Column\ndf_dictDataRowsByCodeNname['rules_desc'] = rules_desc_Column\nprint(df_dictDataRowsByCodeNname)\nprint('================================')\n Rules=[{'code1': ('VA', 'HC', 'NIH', 'SAP', 'AUS', 'HOL', 'ATT', 'COL', 'UCL')}, {'code0': '40', 'code3': '518', 'code6': '594'}, {'code0': '98', 'code1': ('ATT', 'NC'), 'code2': ('103', '104', '105', '106', '31'), 'code3': '810', 'code4': 'computerscience'}, {'code0': '98', 'code1': ('ATT', 'VA', 'NC'), 'code2': ('104', '105', '106', '31'), 'code4': 'computerscience'}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('610', '620', '682', '642', '621', '611'), 'code4': 'biology', 'code6': ('712', '479', '297', '639', '452', '172')}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('396', '340', '394', '393', '240'), 'code4': 'biology', 'code5': ('12', '18')}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('612', '790', '110'), 'code4': 'biology', 'code5': ('12', '16', '18', '19'), 'code6': ('285', '295', '236', '239', '269', '284', '237')}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('730', '320', '350', '379', '812', '374'), 'code4': 'biology', 'code5': ('12', '18', '19')}, {'code0': '40', 'code1': 'VA', 'code2': '11', 'code3': ('113', '174', '131', '115'), 'code5': ('11', '19', '31'), 'code6': ('164', '157', '388', '158')}, {'code0': '58', 'code1': 'CE', 'code2': '109', 'code3': ('423', '114'), 'code5': '31', 'code6': ('372', '238')}]\ndictRules=defaultdict(<class 'list'>, {'rules1': [('code1', ('VA', 'HC', 'NIH', 'SAP', 'AUS', 'HOL', 'ATT', 'COL', 'UCL'))], 'rules12': [('code0', '40'), ('code3', '518'), ('code6', '594')], 'rules2': [('code0', '98'), ('code1', ('ATT', 'NC')), ('code2', ('103', '104', '105', '106', '31')), ('code3', '810'), ('code4', 'computerscience'), ('code0', '98'), ('code1', ('ATT', 'VA', 'NC')), ('code2', ('104', '105', '106', '31')), ('code4', 'computerscience'), ('code0', '52'), ('code1', 'NC'), ('code2', '109'), ('code3', ('610', '620', '682', '642', '621', '611')), ('code4', 'biology'), ('code6', ('712', '479', '297', '639', '452', '172')), ('code0', '52'), ('code1', 'NC'), ('code2', '109'), ('code3', ('396', '340', '394', '393', '240')), ('code4', 'biology'), ('code5', ('12', '18'))], 'rules3': [('code0', '52'), ('code1', 'NC'), ('code2', '109'), ('code3', ('612', '790', '110')), ('code4', 'biology'), ('code5', ('12', '16', '18', '19')), ('code6', ('285', '295', '236', '239', '269', '284', '237')), ('code0', '52'), ('code1', 'NC'), ('code2', '109'), ('code3', ('730', '320', '350', '379', '812', '374')), ('code4', 'biology'), ('code5', ('12', '18', '19'))], 'rules4': [('code0', '40'), ('code1', 'VA'), ('code2', '11'), ('code3', ('113', '174', '131', '115')), ('code5', ('11', '19', '31')), ('code6', ('164', '157', '388', '158'))], 'rules5': [('code0', '58'), ('code1', 'CE'), ('code2', '109'), ('code3', ('423', '114')), ('code5', '31'), ('code6', ('372', '238'))]})\n ------------- \ndictDataRowsByCodeNname={'code0': {0: '5', 1: 'nan', 2: '98', 3: '98', 4: '', 5: '15', 6: '40', 7: '52', 8: '52', 9: '40', 10: '52', 11: '52', 12: '58'}, 'code1': {0: ('Agr', 'Serv'), 1: ('VA', 'HC', 'NIH', 'SAP', 'AUS', 'HOL', 'ATT', 'COL', 'UCL'), 2: ('ATT', 'NC'), 3: ('ATT', 'VA', 'NC'), 4: ('VA', 'HC', 'NIH', 'ATT', 'COL', 'UCL'), 5: 'Agr', 6: 'nan', 7: 'NC', 8: 'NC', 9: 'VA', 10: 'NC', 11: 'NC', 12: 'CE'}, 'code2': {0: 'nan', 1: 'nan', 2: ('103', '104', '105', '106', '31'), 3: ('104', '105'), 4: 'nan', 5: '5', 6: 'nan', 7: '109', 8: '109', 9: '11', 10: '109', 11: '109', 12: '109'}, 'code3': {0: '90', 1: 'nan', 2: '810', 3: '810', 4: 'nan', 5: '58', 6: '518', 7: ('610', '620', '682', '642', '621', '611'), 8: ('620', '682', '642', '611'), 9: ('113', '174', '131', '115'), 10: ('612', '790', '110'), 11: ('612', '110'), 12: ('423', '114')}, 'code4': {0: '1', 1: 'nan', 2: 'computerscience', 3: 'computerscience', 4: 'nan', 5: 'fishing', 6: 'nan', 7: 'biology', 8: 'biology', 9: 'nan', 10: 'biology', 11: 'biology', 12: 'nan'}, 'code5': {0: 'nan', 1: 'nan', 2: 'nan', 3: 'nan', 4: 'nan', 5: 'nan', 6: 'nan', 7: 'nan', 8: 'nan', 9: ('11', '19', '31'), 10: ('12', '16', '18', '19'), 11: ('12', '18', '19'), 12: '31'}, 'code6': {0: 'nan', 1: 'nan', 2: 'nan', 3: 'nan', 4: 'nan', 5: 'nan', 6: '594', 7: ('712', '479', '297', '639', '452', '172'), 8: ('712', '479', '297'), 9: ('164', '157', '388', '158'), 10: ('285', '295', '236', '239', '269', '284', '237'), 11: ('285', '295', '237'), 12: ('372', '238')}}\nlistDataRowsByRow=[{'code0': '5', 'code1': ('Agr', 'Serv'), 'code2': 'nan', 'code3': '90', 'code4': '1', 'code5': 'nan', 'code6': 'nan'}, {'code0': 'nan', 'code1': ('VA', 'HC', 'NIH', 'SAP', 'AUS', 'HOL', 'ATT', 'COL', 'UCL'), 'code2': 'nan', 'code3': 'nan', 'code4': 'nan', 'code5': 'nan', 'code6': 'nan'}, {'code0': '98', 'code1': ('ATT', 'NC'), 'code2': ('103', '104', '105', '106', '31'), 'code3': '810', 'code4': 'computerscience', 'code5': 'nan', 'code6': 'nan'}, {'code0': '98', 'code1': ('ATT', 'VA', 'NC'), 'code2': ('104', '105'), 'code3': '810', 'code4': 'computerscience', 'code5': 'nan', 'code6': 'nan'}, {'code0': '', 'code1': ('VA', 'HC', 'NIH', 'ATT', 'COL', 'UCL'), 'code2': 'nan', 'code3': 'nan', 'code4': 'nan', 'code5': 'nan', 'code6': 'nan'}, {'code0': '15', 'code1': 'Agr', 'code2': '5', 'code3': '58', 'code4': 'fishing', 'code5': 'nan', 'code6': 'nan'}, {'code0': '40', 'code1': 'nan', 'code2': 'nan', 'code3': '518', 'code4': 'nan', 'code5': 'nan', 'code6': '594'}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('610', '620', '682', '642', '621', '611'), 'code4': 'biology', 'code5': 'nan', 'code6': ('712', '479', '297', '639', '452', '172')}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('620', '682', '642', '611'), 'code4': 'biology', 'code5': 'nan', 'code6': ('712', '479', '297')}, {'code0': '40', 'code1': 'VA', 'code2': '11', 'code3': ('113', '174', '131', '115'), 'code4': 'nan', 'code5': ('11', '19', '31'), 'code6': ('164', '157', '388', '158')}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('612', '790', '110'), 'code4': 'biology', 'code5': ('12', '16', '18', '19'), 'code6': ('285', '295', '236', '239', '269', '284', '237')}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('612', '110'), 'code4': 'biology', 'code5': ('12', '18', '19'), 'code6': ('285', '295', '237')}, {'code0': '58', 'code1': 'CE', 'code2': '109', 'code3': ('423', '114'), 'code4': 'nan', 'code5': '31', 'code6': ('372', '238')}]\n ------------- \nrules_desc_Column = [None, 'rules12', 'rules3', 'rules3', None, None, 'rules2', 'rules3', 'rules3', 'rules2', 'rules3', 'rules3', 'rules3']\nisHit_Column = [False, True, True, True, False, False, True, True, True, True, True, True, True]\n================================\n code0 code1 ... isHit rules_desc\n0 5 (Agr, Serv) ... False None\n1 nan (VA, HC, NIH, SAP, AUS, HOL, ATT, COL, UCL) ... True rules12\n2 98 (ATT, NC) ... True rules3\n3 98 (ATT, VA, NC) ... True rules3\n4 (VA, HC, NIH, ATT, COL, UCL) ... False None\n5 15 Agr ... False None\n6 40 nan ... True rules2\n7 52 NC ... True rules3\n8 52 NC ... True rules3\n9 40 VA ... True rules2\n10 52 NC ... True rules3\n11 52 NC ... True rules3\n12 58 CE ... True rules3\n\n[13 rows x 9 columns]\n================================\n code0 code1 ... isHit rules_desc\n0 5 (Agr, Serv) ... False None\n1 nan (VA, HC, NIH, SAP, AUS, HOL, ATT, COL, UCL) ... True [rules1]\n2 98 (ATT, NC) ... False None\n3 98 (ATT, VA, NC) ... False None\n4 (VA, HC, NIH, ATT, COL, UCL) ... False None\n5 15 Agr ... False None\n6 40 nan ... True [rules12]\n7 52 NC ... False None\n8 52 NC ... False None\n9 40 VA ... True [rules4]\n10 52 NC ... False None\n11 52 NC ... False None\n12 58 CE ... True [rules5]\n\n[13 rows x 9 columns]\n================================\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20543632/" ]
74,525,555
<p>I want my integer variable to be rounded to 4 decimal places. A number like 3.345679 should be represented as 3.3457.Additionally, the value zero must be represented as 0 and not any other representation.(e.g., -0.0, 0.0, 0.00000). Additionally, I do not want to add extra 0s to floating point numbers. For example, 3.9 should be represented as 3.9, not as 3.9000</p>
[ { "answer_id": 74525925, "author": "Tim Roberts", "author_id": 1883316, "author_profile": "https://Stackoverflow.com/users/1883316", "pm_score": 1, "selected": false, "text": "all {0:'5',2:'98'...} 0 2 for row in indf_dict:\n for rno,rule in enumerate(rules_list):\n print(\"New rule\", rno)\n match = all( val in row[key].values() for key,val in rule.items() if key in row)\n if match:\n print(\"Rule\", rno, \"matches\")\n New rule 0\nRule 0 matches\nNew rule 1\nRule 1 matches\nNew rule 2\nRule 2 matches\nNew rule 3\nNew rule 4\nRule 4 matches\nNew rule 5\nNew rule 6\nRule 6 matches\nNew rule 7\nNew rule 8\nRule 8 matches\nNew rule 9\nRule 9 matches\n" }, { "answer_id": 74527064, "author": "Claudio", "author_id": 7711283, "author_profile": "https://Stackoverflow.com/users/7711283", "pm_score": 3, "selected": true, "text": "from pprint import pprint\nimport pandas as pd\nfrom collections import defaultdict\n# ----------------------------------------------------------------------\nrules_list=rules_dict=[{'code1':('VA','HC','NIH','SAP','AUS','HOL','ATT','COL','UCL'),'rules_desc':'rules1'},{'code0':('40'),'code3':('518'),'code6':('594'),'rules_desc':'rules12'},{'code0':('98'),'code1':('ATT','NC'),'code2':('103','104','105','106','31'),'code3':('810'),'code4':('computerscience'),'rules_desc':'rules2'},{'code0':('98'),'code1':('ATT','VA','NC'),'code2':('104','105','106','31'),'code4':('computerscience'),'rules_desc':'rules2'},{'code0':('52'),'code1':('NC'),'code2':('109'),'code3':('610','620','682','642','621','611'),'code4':('biology'),'code6':('712','479','297','639','452','172'),'rules_desc':'rules2'},{'code0':('52'),'code1':('NC'),'code2':('109'),'code3':('396','340','394','393','240'),'code4':('biology'),'code5':('12','18'),'rules_desc':'rules2'},{'code0':('52'),'code1':('NC'),'code2':('109'),'code3':('612','790','110'),'code4':('biology'),'code5':('12','16','18','19'),'code6':('285','295','236','239','269','284','237'),'rules_desc':'rules3'},{'code0':('52'),'code1':('NC'),'code2':('109'),'code3':('730','320','350','379','812','374'),'code4':('biology'),'code5':('12','18','19'),'rules_desc':'rules3'},{'code0':('40'),'code1':('VA'),'code2':('11'),'code3':('113','174','131','115'),'code5':('11','19','31'),'code6':('164','157','388','158'),'rules_desc':'rules4'},{'code0':('58'),'code1':('CE'),'code2':('109'),'code3':('423','114'),'code5':('31'),'code6':('372','238'),'rules_desc':'rules5'}]\n# codeNname : 'code1', 'code2', 'code3', ..., 'code6'\n# ruleNname : 'rules1', 'rules12', 'rules2', ..., 'rules5'\n# ruleDescrKey : 'rules_desc'\n# dictRulesSpec : dictionary { codeNname:value {1,N} ... , rulesDct_ruleKey:ruleNname }\n# dictCodes : dictionary { codeNname:value, codeNname:value, ... }\n# Rules : List [ dictRulesSpec, dictRulesSpec, ... ]\n# dictRules : { ruleNname:[codeNname, codeNnameValue], ... }\nRules = rules_list\nruleDescrKey = 'rules_desc'\ndictRules = defaultdict(list)\nfor dictRulesSpec in Rules:\n ruleNname = dictRulesSpec.pop(ruleDescrKey)\n # dictRulesSpec without ruleDescrKey item has only Codes as keys, so:\n dictCodes = dictRulesSpec \n for codeNname, codeNnameValue in dictCodes.items(): \n dictRules[ruleNname].append( (codeNname, codeNnameValue) ) \nprint(f'{Rules=}')\nprint(f'{dictRules=}')\nprint(' ------------- ')\n# ----------------------------------------------------------------------\nindf_dict={'code0':{0:('5'),1:'nan',2:('98'),3:('98'),4:'',5:('15'),6:('40'),7:('52'),8:('52'),9:('40'),10:('52'),11:('52'),12:('58')},'code1':{0:('Agr','Serv'),1:('VA','HC','NIH','SAP','AUS','HOL','ATT','COL','UCL'),2:('ATT','NC'),3:('ATT','VA','NC'),4:('VA','HC','NIH','ATT','COL','UCL'),5:('Agr'),6:'nan',7:('NC'),8:('NC'),9:('VA'),10:('NC'),11:('NC'),12:('CE')},'code2':{0:'nan',1:'nan',2:('103','104','105','106','31'),3:('104','105'),4:'nan',5:('5'),6:'nan',7:('109'),8:('109'),9:('11'),10:('109'),11:('109'),12:('109')},'code3':{0:('90'),1:'nan',2:('810'),3:('810'),4:'nan',5:('58'),6:('518'),7:('610','620','682','642','621','611'),8:('620','682','642','611'),9:('113','174','131','115'),10:('612','790','110'),11:('612','110'),12:('423','114')},'code4':{0:('1'),1:'nan',2:('computerscience'),3:('computerscience'),4:'nan',5:('fishing'),6:'nan',7:('biology'),8:('biology'),9:'nan',10:('biology'),11:('biology'),12:'nan'},'code5':{0:'nan',1:'nan',2:'nan',3:'nan',4:'nan',5:'nan',6:'nan',7:'nan',8:'nan',9:('11','19','31'),10:('12','16','18','19'),11:('12','18','19'),12:'31'},'code6':{0:'nan',1:'nan',2:'nan',3:'nan',4:'nan',5:'nan',6:'594',7:('712','479','297','639','452','172'),8:('712','479','297'),9:('164','157','388','158'),10:('285','295','236','239','269','284','237'),11:('285','295','237'),12:('372','238')}}\ndictDataRowsByCodeNname = indf_dict\ndf_dictDataRowsByCodeNname = pd.DataFrame.from_dict(dictDataRowsByCodeNname)\nprint(f'{dictDataRowsByCodeNname=}')\nlistDataRowsByRow = df_dictDataRowsByCodeNname.to_dict(orient='records')\nprint(f'{listDataRowsByRow=}')\nprint(' ------------- ')\nisHit_Column = []\nrules_desc_Column = []\n# The loop below tests for only one hit within the rule ...\nfor dctDataRow in listDataRowsByRow: \n isHit = False\n for ruleNname, listTuplesCodeNnameValue in dictRules.items():\n if isHit:\n break\n for codeNname, codeNnameValue in listTuplesCodeNnameValue:\n if isHit:\n break\n else:\n if dctDataRow[codeNname] == codeNnameValue: \n isHit = True\n bckpRuleNname = ruleNname\n break\n rules_desc_Column.append( bckpRuleNname if isHit else None)\n isHit_Column.append(isHit)\n\nprint(f'{rules_desc_Column = }')\nprint(f'{isHit_Column = }') \nprint('================================')\ndf_dictDataRowsByCodeNname['isHit'] = isHit_Column\ndf_dictDataRowsByCodeNname['rules_desc'] = rules_desc_Column\nprint(df_dictDataRowsByCodeNname)\nprint('================================')\n\nisHit_Column = []\nrules_desc_Column = []\n# The loop below tests for all hits within the rule and\n# lists all rules that apply in case of hits: \nfor dctDataRow in listDataRowsByRow: \n lstRulesWithHits = []\n for ruleNname, listTuplesCodeNnameValue in dictRules.items():\n ruleItemsWithHits = 0\n for codeNname, codeNnameValue in listTuplesCodeNnameValue:\n if dctDataRow[codeNname] == codeNnameValue: \n ruleItemsWithHits += 1\n if ruleItemsWithHits == len(listTuplesCodeNnameValue):\n lstRulesWithHits.append(ruleNname)\n isHit = bool(lstRulesWithHits)\n rules_desc_Column.append( lstRulesWithHits if isHit else None)\n isHit_Column.append(isHit)\ndf_dictDataRowsByCodeNname['isHit'] = isHit_Column\ndf_dictDataRowsByCodeNname['rules_desc'] = rules_desc_Column\nprint(df_dictDataRowsByCodeNname)\nprint('================================')\n Rules=[{'code1': ('VA', 'HC', 'NIH', 'SAP', 'AUS', 'HOL', 'ATT', 'COL', 'UCL')}, {'code0': '40', 'code3': '518', 'code6': '594'}, {'code0': '98', 'code1': ('ATT', 'NC'), 'code2': ('103', '104', '105', '106', '31'), 'code3': '810', 'code4': 'computerscience'}, {'code0': '98', 'code1': ('ATT', 'VA', 'NC'), 'code2': ('104', '105', '106', '31'), 'code4': 'computerscience'}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('610', '620', '682', '642', '621', '611'), 'code4': 'biology', 'code6': ('712', '479', '297', '639', '452', '172')}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('396', '340', '394', '393', '240'), 'code4': 'biology', 'code5': ('12', '18')}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('612', '790', '110'), 'code4': 'biology', 'code5': ('12', '16', '18', '19'), 'code6': ('285', '295', '236', '239', '269', '284', '237')}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('730', '320', '350', '379', '812', '374'), 'code4': 'biology', 'code5': ('12', '18', '19')}, {'code0': '40', 'code1': 'VA', 'code2': '11', 'code3': ('113', '174', '131', '115'), 'code5': ('11', '19', '31'), 'code6': ('164', '157', '388', '158')}, {'code0': '58', 'code1': 'CE', 'code2': '109', 'code3': ('423', '114'), 'code5': '31', 'code6': ('372', '238')}]\ndictRules=defaultdict(<class 'list'>, {'rules1': [('code1', ('VA', 'HC', 'NIH', 'SAP', 'AUS', 'HOL', 'ATT', 'COL', 'UCL'))], 'rules12': [('code0', '40'), ('code3', '518'), ('code6', '594')], 'rules2': [('code0', '98'), ('code1', ('ATT', 'NC')), ('code2', ('103', '104', '105', '106', '31')), ('code3', '810'), ('code4', 'computerscience'), ('code0', '98'), ('code1', ('ATT', 'VA', 'NC')), ('code2', ('104', '105', '106', '31')), ('code4', 'computerscience'), ('code0', '52'), ('code1', 'NC'), ('code2', '109'), ('code3', ('610', '620', '682', '642', '621', '611')), ('code4', 'biology'), ('code6', ('712', '479', '297', '639', '452', '172')), ('code0', '52'), ('code1', 'NC'), ('code2', '109'), ('code3', ('396', '340', '394', '393', '240')), ('code4', 'biology'), ('code5', ('12', '18'))], 'rules3': [('code0', '52'), ('code1', 'NC'), ('code2', '109'), ('code3', ('612', '790', '110')), ('code4', 'biology'), ('code5', ('12', '16', '18', '19')), ('code6', ('285', '295', '236', '239', '269', '284', '237')), ('code0', '52'), ('code1', 'NC'), ('code2', '109'), ('code3', ('730', '320', '350', '379', '812', '374')), ('code4', 'biology'), ('code5', ('12', '18', '19'))], 'rules4': [('code0', '40'), ('code1', 'VA'), ('code2', '11'), ('code3', ('113', '174', '131', '115')), ('code5', ('11', '19', '31')), ('code6', ('164', '157', '388', '158'))], 'rules5': [('code0', '58'), ('code1', 'CE'), ('code2', '109'), ('code3', ('423', '114')), ('code5', '31'), ('code6', ('372', '238'))]})\n ------------- \ndictDataRowsByCodeNname={'code0': {0: '5', 1: 'nan', 2: '98', 3: '98', 4: '', 5: '15', 6: '40', 7: '52', 8: '52', 9: '40', 10: '52', 11: '52', 12: '58'}, 'code1': {0: ('Agr', 'Serv'), 1: ('VA', 'HC', 'NIH', 'SAP', 'AUS', 'HOL', 'ATT', 'COL', 'UCL'), 2: ('ATT', 'NC'), 3: ('ATT', 'VA', 'NC'), 4: ('VA', 'HC', 'NIH', 'ATT', 'COL', 'UCL'), 5: 'Agr', 6: 'nan', 7: 'NC', 8: 'NC', 9: 'VA', 10: 'NC', 11: 'NC', 12: 'CE'}, 'code2': {0: 'nan', 1: 'nan', 2: ('103', '104', '105', '106', '31'), 3: ('104', '105'), 4: 'nan', 5: '5', 6: 'nan', 7: '109', 8: '109', 9: '11', 10: '109', 11: '109', 12: '109'}, 'code3': {0: '90', 1: 'nan', 2: '810', 3: '810', 4: 'nan', 5: '58', 6: '518', 7: ('610', '620', '682', '642', '621', '611'), 8: ('620', '682', '642', '611'), 9: ('113', '174', '131', '115'), 10: ('612', '790', '110'), 11: ('612', '110'), 12: ('423', '114')}, 'code4': {0: '1', 1: 'nan', 2: 'computerscience', 3: 'computerscience', 4: 'nan', 5: 'fishing', 6: 'nan', 7: 'biology', 8: 'biology', 9: 'nan', 10: 'biology', 11: 'biology', 12: 'nan'}, 'code5': {0: 'nan', 1: 'nan', 2: 'nan', 3: 'nan', 4: 'nan', 5: 'nan', 6: 'nan', 7: 'nan', 8: 'nan', 9: ('11', '19', '31'), 10: ('12', '16', '18', '19'), 11: ('12', '18', '19'), 12: '31'}, 'code6': {0: 'nan', 1: 'nan', 2: 'nan', 3: 'nan', 4: 'nan', 5: 'nan', 6: '594', 7: ('712', '479', '297', '639', '452', '172'), 8: ('712', '479', '297'), 9: ('164', '157', '388', '158'), 10: ('285', '295', '236', '239', '269', '284', '237'), 11: ('285', '295', '237'), 12: ('372', '238')}}\nlistDataRowsByRow=[{'code0': '5', 'code1': ('Agr', 'Serv'), 'code2': 'nan', 'code3': '90', 'code4': '1', 'code5': 'nan', 'code6': 'nan'}, {'code0': 'nan', 'code1': ('VA', 'HC', 'NIH', 'SAP', 'AUS', 'HOL', 'ATT', 'COL', 'UCL'), 'code2': 'nan', 'code3': 'nan', 'code4': 'nan', 'code5': 'nan', 'code6': 'nan'}, {'code0': '98', 'code1': ('ATT', 'NC'), 'code2': ('103', '104', '105', '106', '31'), 'code3': '810', 'code4': 'computerscience', 'code5': 'nan', 'code6': 'nan'}, {'code0': '98', 'code1': ('ATT', 'VA', 'NC'), 'code2': ('104', '105'), 'code3': '810', 'code4': 'computerscience', 'code5': 'nan', 'code6': 'nan'}, {'code0': '', 'code1': ('VA', 'HC', 'NIH', 'ATT', 'COL', 'UCL'), 'code2': 'nan', 'code3': 'nan', 'code4': 'nan', 'code5': 'nan', 'code6': 'nan'}, {'code0': '15', 'code1': 'Agr', 'code2': '5', 'code3': '58', 'code4': 'fishing', 'code5': 'nan', 'code6': 'nan'}, {'code0': '40', 'code1': 'nan', 'code2': 'nan', 'code3': '518', 'code4': 'nan', 'code5': 'nan', 'code6': '594'}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('610', '620', '682', '642', '621', '611'), 'code4': 'biology', 'code5': 'nan', 'code6': ('712', '479', '297', '639', '452', '172')}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('620', '682', '642', '611'), 'code4': 'biology', 'code5': 'nan', 'code6': ('712', '479', '297')}, {'code0': '40', 'code1': 'VA', 'code2': '11', 'code3': ('113', '174', '131', '115'), 'code4': 'nan', 'code5': ('11', '19', '31'), 'code6': ('164', '157', '388', '158')}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('612', '790', '110'), 'code4': 'biology', 'code5': ('12', '16', '18', '19'), 'code6': ('285', '295', '236', '239', '269', '284', '237')}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('612', '110'), 'code4': 'biology', 'code5': ('12', '18', '19'), 'code6': ('285', '295', '237')}, {'code0': '58', 'code1': 'CE', 'code2': '109', 'code3': ('423', '114'), 'code4': 'nan', 'code5': '31', 'code6': ('372', '238')}]\n ------------- \nrules_desc_Column = [None, 'rules12', 'rules3', 'rules3', None, None, 'rules2', 'rules3', 'rules3', 'rules2', 'rules3', 'rules3', 'rules3']\nisHit_Column = [False, True, True, True, False, False, True, True, True, True, True, True, True]\n================================\n code0 code1 ... isHit rules_desc\n0 5 (Agr, Serv) ... False None\n1 nan (VA, HC, NIH, SAP, AUS, HOL, ATT, COL, UCL) ... True rules12\n2 98 (ATT, NC) ... True rules3\n3 98 (ATT, VA, NC) ... True rules3\n4 (VA, HC, NIH, ATT, COL, UCL) ... False None\n5 15 Agr ... False None\n6 40 nan ... True rules2\n7 52 NC ... True rules3\n8 52 NC ... True rules3\n9 40 VA ... True rules2\n10 52 NC ... True rules3\n11 52 NC ... True rules3\n12 58 CE ... True rules3\n\n[13 rows x 9 columns]\n================================\n code0 code1 ... isHit rules_desc\n0 5 (Agr, Serv) ... False None\n1 nan (VA, HC, NIH, SAP, AUS, HOL, ATT, COL, UCL) ... True [rules1]\n2 98 (ATT, NC) ... False None\n3 98 (ATT, VA, NC) ... False None\n4 (VA, HC, NIH, ATT, COL, UCL) ... False None\n5 15 Agr ... False None\n6 40 nan ... True [rules12]\n7 52 NC ... False None\n8 52 NC ... False None\n9 40 VA ... True [rules4]\n10 52 NC ... False None\n11 52 NC ... False None\n12 58 CE ... True [rules5]\n\n[13 rows x 9 columns]\n================================\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20562561/" ]
74,525,646
<p>so basically my dir looks like this:</p> <p>/node:</p> <p>~/libs/lib.js</p> <p>~/projects/main/script.js</p> <p>and i want to import (the entire file) &quot;lib&quot; [\Node\libs\lib.js] into &quot;script&quot; [\Node\Projects\main\script.js], how do i do that?</p> <p>thanks in advance, -Gzrespect</p>
[ { "answer_id": 74525925, "author": "Tim Roberts", "author_id": 1883316, "author_profile": "https://Stackoverflow.com/users/1883316", "pm_score": 1, "selected": false, "text": "all {0:'5',2:'98'...} 0 2 for row in indf_dict:\n for rno,rule in enumerate(rules_list):\n print(\"New rule\", rno)\n match = all( val in row[key].values() for key,val in rule.items() if key in row)\n if match:\n print(\"Rule\", rno, \"matches\")\n New rule 0\nRule 0 matches\nNew rule 1\nRule 1 matches\nNew rule 2\nRule 2 matches\nNew rule 3\nNew rule 4\nRule 4 matches\nNew rule 5\nNew rule 6\nRule 6 matches\nNew rule 7\nNew rule 8\nRule 8 matches\nNew rule 9\nRule 9 matches\n" }, { "answer_id": 74527064, "author": "Claudio", "author_id": 7711283, "author_profile": "https://Stackoverflow.com/users/7711283", "pm_score": 3, "selected": true, "text": "from pprint import pprint\nimport pandas as pd\nfrom collections import defaultdict\n# ----------------------------------------------------------------------\nrules_list=rules_dict=[{'code1':('VA','HC','NIH','SAP','AUS','HOL','ATT','COL','UCL'),'rules_desc':'rules1'},{'code0':('40'),'code3':('518'),'code6':('594'),'rules_desc':'rules12'},{'code0':('98'),'code1':('ATT','NC'),'code2':('103','104','105','106','31'),'code3':('810'),'code4':('computerscience'),'rules_desc':'rules2'},{'code0':('98'),'code1':('ATT','VA','NC'),'code2':('104','105','106','31'),'code4':('computerscience'),'rules_desc':'rules2'},{'code0':('52'),'code1':('NC'),'code2':('109'),'code3':('610','620','682','642','621','611'),'code4':('biology'),'code6':('712','479','297','639','452','172'),'rules_desc':'rules2'},{'code0':('52'),'code1':('NC'),'code2':('109'),'code3':('396','340','394','393','240'),'code4':('biology'),'code5':('12','18'),'rules_desc':'rules2'},{'code0':('52'),'code1':('NC'),'code2':('109'),'code3':('612','790','110'),'code4':('biology'),'code5':('12','16','18','19'),'code6':('285','295','236','239','269','284','237'),'rules_desc':'rules3'},{'code0':('52'),'code1':('NC'),'code2':('109'),'code3':('730','320','350','379','812','374'),'code4':('biology'),'code5':('12','18','19'),'rules_desc':'rules3'},{'code0':('40'),'code1':('VA'),'code2':('11'),'code3':('113','174','131','115'),'code5':('11','19','31'),'code6':('164','157','388','158'),'rules_desc':'rules4'},{'code0':('58'),'code1':('CE'),'code2':('109'),'code3':('423','114'),'code5':('31'),'code6':('372','238'),'rules_desc':'rules5'}]\n# codeNname : 'code1', 'code2', 'code3', ..., 'code6'\n# ruleNname : 'rules1', 'rules12', 'rules2', ..., 'rules5'\n# ruleDescrKey : 'rules_desc'\n# dictRulesSpec : dictionary { codeNname:value {1,N} ... , rulesDct_ruleKey:ruleNname }\n# dictCodes : dictionary { codeNname:value, codeNname:value, ... }\n# Rules : List [ dictRulesSpec, dictRulesSpec, ... ]\n# dictRules : { ruleNname:[codeNname, codeNnameValue], ... }\nRules = rules_list\nruleDescrKey = 'rules_desc'\ndictRules = defaultdict(list)\nfor dictRulesSpec in Rules:\n ruleNname = dictRulesSpec.pop(ruleDescrKey)\n # dictRulesSpec without ruleDescrKey item has only Codes as keys, so:\n dictCodes = dictRulesSpec \n for codeNname, codeNnameValue in dictCodes.items(): \n dictRules[ruleNname].append( (codeNname, codeNnameValue) ) \nprint(f'{Rules=}')\nprint(f'{dictRules=}')\nprint(' ------------- ')\n# ----------------------------------------------------------------------\nindf_dict={'code0':{0:('5'),1:'nan',2:('98'),3:('98'),4:'',5:('15'),6:('40'),7:('52'),8:('52'),9:('40'),10:('52'),11:('52'),12:('58')},'code1':{0:('Agr','Serv'),1:('VA','HC','NIH','SAP','AUS','HOL','ATT','COL','UCL'),2:('ATT','NC'),3:('ATT','VA','NC'),4:('VA','HC','NIH','ATT','COL','UCL'),5:('Agr'),6:'nan',7:('NC'),8:('NC'),9:('VA'),10:('NC'),11:('NC'),12:('CE')},'code2':{0:'nan',1:'nan',2:('103','104','105','106','31'),3:('104','105'),4:'nan',5:('5'),6:'nan',7:('109'),8:('109'),9:('11'),10:('109'),11:('109'),12:('109')},'code3':{0:('90'),1:'nan',2:('810'),3:('810'),4:'nan',5:('58'),6:('518'),7:('610','620','682','642','621','611'),8:('620','682','642','611'),9:('113','174','131','115'),10:('612','790','110'),11:('612','110'),12:('423','114')},'code4':{0:('1'),1:'nan',2:('computerscience'),3:('computerscience'),4:'nan',5:('fishing'),6:'nan',7:('biology'),8:('biology'),9:'nan',10:('biology'),11:('biology'),12:'nan'},'code5':{0:'nan',1:'nan',2:'nan',3:'nan',4:'nan',5:'nan',6:'nan',7:'nan',8:'nan',9:('11','19','31'),10:('12','16','18','19'),11:('12','18','19'),12:'31'},'code6':{0:'nan',1:'nan',2:'nan',3:'nan',4:'nan',5:'nan',6:'594',7:('712','479','297','639','452','172'),8:('712','479','297'),9:('164','157','388','158'),10:('285','295','236','239','269','284','237'),11:('285','295','237'),12:('372','238')}}\ndictDataRowsByCodeNname = indf_dict\ndf_dictDataRowsByCodeNname = pd.DataFrame.from_dict(dictDataRowsByCodeNname)\nprint(f'{dictDataRowsByCodeNname=}')\nlistDataRowsByRow = df_dictDataRowsByCodeNname.to_dict(orient='records')\nprint(f'{listDataRowsByRow=}')\nprint(' ------------- ')\nisHit_Column = []\nrules_desc_Column = []\n# The loop below tests for only one hit within the rule ...\nfor dctDataRow in listDataRowsByRow: \n isHit = False\n for ruleNname, listTuplesCodeNnameValue in dictRules.items():\n if isHit:\n break\n for codeNname, codeNnameValue in listTuplesCodeNnameValue:\n if isHit:\n break\n else:\n if dctDataRow[codeNname] == codeNnameValue: \n isHit = True\n bckpRuleNname = ruleNname\n break\n rules_desc_Column.append( bckpRuleNname if isHit else None)\n isHit_Column.append(isHit)\n\nprint(f'{rules_desc_Column = }')\nprint(f'{isHit_Column = }') \nprint('================================')\ndf_dictDataRowsByCodeNname['isHit'] = isHit_Column\ndf_dictDataRowsByCodeNname['rules_desc'] = rules_desc_Column\nprint(df_dictDataRowsByCodeNname)\nprint('================================')\n\nisHit_Column = []\nrules_desc_Column = []\n# The loop below tests for all hits within the rule and\n# lists all rules that apply in case of hits: \nfor dctDataRow in listDataRowsByRow: \n lstRulesWithHits = []\n for ruleNname, listTuplesCodeNnameValue in dictRules.items():\n ruleItemsWithHits = 0\n for codeNname, codeNnameValue in listTuplesCodeNnameValue:\n if dctDataRow[codeNname] == codeNnameValue: \n ruleItemsWithHits += 1\n if ruleItemsWithHits == len(listTuplesCodeNnameValue):\n lstRulesWithHits.append(ruleNname)\n isHit = bool(lstRulesWithHits)\n rules_desc_Column.append( lstRulesWithHits if isHit else None)\n isHit_Column.append(isHit)\ndf_dictDataRowsByCodeNname['isHit'] = isHit_Column\ndf_dictDataRowsByCodeNname['rules_desc'] = rules_desc_Column\nprint(df_dictDataRowsByCodeNname)\nprint('================================')\n Rules=[{'code1': ('VA', 'HC', 'NIH', 'SAP', 'AUS', 'HOL', 'ATT', 'COL', 'UCL')}, {'code0': '40', 'code3': '518', 'code6': '594'}, {'code0': '98', 'code1': ('ATT', 'NC'), 'code2': ('103', '104', '105', '106', '31'), 'code3': '810', 'code4': 'computerscience'}, {'code0': '98', 'code1': ('ATT', 'VA', 'NC'), 'code2': ('104', '105', '106', '31'), 'code4': 'computerscience'}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('610', '620', '682', '642', '621', '611'), 'code4': 'biology', 'code6': ('712', '479', '297', '639', '452', '172')}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('396', '340', '394', '393', '240'), 'code4': 'biology', 'code5': ('12', '18')}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('612', '790', '110'), 'code4': 'biology', 'code5': ('12', '16', '18', '19'), 'code6': ('285', '295', '236', '239', '269', '284', '237')}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('730', '320', '350', '379', '812', '374'), 'code4': 'biology', 'code5': ('12', '18', '19')}, {'code0': '40', 'code1': 'VA', 'code2': '11', 'code3': ('113', '174', '131', '115'), 'code5': ('11', '19', '31'), 'code6': ('164', '157', '388', '158')}, {'code0': '58', 'code1': 'CE', 'code2': '109', 'code3': ('423', '114'), 'code5': '31', 'code6': ('372', '238')}]\ndictRules=defaultdict(<class 'list'>, {'rules1': [('code1', ('VA', 'HC', 'NIH', 'SAP', 'AUS', 'HOL', 'ATT', 'COL', 'UCL'))], 'rules12': [('code0', '40'), ('code3', '518'), ('code6', '594')], 'rules2': [('code0', '98'), ('code1', ('ATT', 'NC')), ('code2', ('103', '104', '105', '106', '31')), ('code3', '810'), ('code4', 'computerscience'), ('code0', '98'), ('code1', ('ATT', 'VA', 'NC')), ('code2', ('104', '105', '106', '31')), ('code4', 'computerscience'), ('code0', '52'), ('code1', 'NC'), ('code2', '109'), ('code3', ('610', '620', '682', '642', '621', '611')), ('code4', 'biology'), ('code6', ('712', '479', '297', '639', '452', '172')), ('code0', '52'), ('code1', 'NC'), ('code2', '109'), ('code3', ('396', '340', '394', '393', '240')), ('code4', 'biology'), ('code5', ('12', '18'))], 'rules3': [('code0', '52'), ('code1', 'NC'), ('code2', '109'), ('code3', ('612', '790', '110')), ('code4', 'biology'), ('code5', ('12', '16', '18', '19')), ('code6', ('285', '295', '236', '239', '269', '284', '237')), ('code0', '52'), ('code1', 'NC'), ('code2', '109'), ('code3', ('730', '320', '350', '379', '812', '374')), ('code4', 'biology'), ('code5', ('12', '18', '19'))], 'rules4': [('code0', '40'), ('code1', 'VA'), ('code2', '11'), ('code3', ('113', '174', '131', '115')), ('code5', ('11', '19', '31')), ('code6', ('164', '157', '388', '158'))], 'rules5': [('code0', '58'), ('code1', 'CE'), ('code2', '109'), ('code3', ('423', '114')), ('code5', '31'), ('code6', ('372', '238'))]})\n ------------- \ndictDataRowsByCodeNname={'code0': {0: '5', 1: 'nan', 2: '98', 3: '98', 4: '', 5: '15', 6: '40', 7: '52', 8: '52', 9: '40', 10: '52', 11: '52', 12: '58'}, 'code1': {0: ('Agr', 'Serv'), 1: ('VA', 'HC', 'NIH', 'SAP', 'AUS', 'HOL', 'ATT', 'COL', 'UCL'), 2: ('ATT', 'NC'), 3: ('ATT', 'VA', 'NC'), 4: ('VA', 'HC', 'NIH', 'ATT', 'COL', 'UCL'), 5: 'Agr', 6: 'nan', 7: 'NC', 8: 'NC', 9: 'VA', 10: 'NC', 11: 'NC', 12: 'CE'}, 'code2': {0: 'nan', 1: 'nan', 2: ('103', '104', '105', '106', '31'), 3: ('104', '105'), 4: 'nan', 5: '5', 6: 'nan', 7: '109', 8: '109', 9: '11', 10: '109', 11: '109', 12: '109'}, 'code3': {0: '90', 1: 'nan', 2: '810', 3: '810', 4: 'nan', 5: '58', 6: '518', 7: ('610', '620', '682', '642', '621', '611'), 8: ('620', '682', '642', '611'), 9: ('113', '174', '131', '115'), 10: ('612', '790', '110'), 11: ('612', '110'), 12: ('423', '114')}, 'code4': {0: '1', 1: 'nan', 2: 'computerscience', 3: 'computerscience', 4: 'nan', 5: 'fishing', 6: 'nan', 7: 'biology', 8: 'biology', 9: 'nan', 10: 'biology', 11: 'biology', 12: 'nan'}, 'code5': {0: 'nan', 1: 'nan', 2: 'nan', 3: 'nan', 4: 'nan', 5: 'nan', 6: 'nan', 7: 'nan', 8: 'nan', 9: ('11', '19', '31'), 10: ('12', '16', '18', '19'), 11: ('12', '18', '19'), 12: '31'}, 'code6': {0: 'nan', 1: 'nan', 2: 'nan', 3: 'nan', 4: 'nan', 5: 'nan', 6: '594', 7: ('712', '479', '297', '639', '452', '172'), 8: ('712', '479', '297'), 9: ('164', '157', '388', '158'), 10: ('285', '295', '236', '239', '269', '284', '237'), 11: ('285', '295', '237'), 12: ('372', '238')}}\nlistDataRowsByRow=[{'code0': '5', 'code1': ('Agr', 'Serv'), 'code2': 'nan', 'code3': '90', 'code4': '1', 'code5': 'nan', 'code6': 'nan'}, {'code0': 'nan', 'code1': ('VA', 'HC', 'NIH', 'SAP', 'AUS', 'HOL', 'ATT', 'COL', 'UCL'), 'code2': 'nan', 'code3': 'nan', 'code4': 'nan', 'code5': 'nan', 'code6': 'nan'}, {'code0': '98', 'code1': ('ATT', 'NC'), 'code2': ('103', '104', '105', '106', '31'), 'code3': '810', 'code4': 'computerscience', 'code5': 'nan', 'code6': 'nan'}, {'code0': '98', 'code1': ('ATT', 'VA', 'NC'), 'code2': ('104', '105'), 'code3': '810', 'code4': 'computerscience', 'code5': 'nan', 'code6': 'nan'}, {'code0': '', 'code1': ('VA', 'HC', 'NIH', 'ATT', 'COL', 'UCL'), 'code2': 'nan', 'code3': 'nan', 'code4': 'nan', 'code5': 'nan', 'code6': 'nan'}, {'code0': '15', 'code1': 'Agr', 'code2': '5', 'code3': '58', 'code4': 'fishing', 'code5': 'nan', 'code6': 'nan'}, {'code0': '40', 'code1': 'nan', 'code2': 'nan', 'code3': '518', 'code4': 'nan', 'code5': 'nan', 'code6': '594'}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('610', '620', '682', '642', '621', '611'), 'code4': 'biology', 'code5': 'nan', 'code6': ('712', '479', '297', '639', '452', '172')}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('620', '682', '642', '611'), 'code4': 'biology', 'code5': 'nan', 'code6': ('712', '479', '297')}, {'code0': '40', 'code1': 'VA', 'code2': '11', 'code3': ('113', '174', '131', '115'), 'code4': 'nan', 'code5': ('11', '19', '31'), 'code6': ('164', '157', '388', '158')}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('612', '790', '110'), 'code4': 'biology', 'code5': ('12', '16', '18', '19'), 'code6': ('285', '295', '236', '239', '269', '284', '237')}, {'code0': '52', 'code1': 'NC', 'code2': '109', 'code3': ('612', '110'), 'code4': 'biology', 'code5': ('12', '18', '19'), 'code6': ('285', '295', '237')}, {'code0': '58', 'code1': 'CE', 'code2': '109', 'code3': ('423', '114'), 'code4': 'nan', 'code5': '31', 'code6': ('372', '238')}]\n ------------- \nrules_desc_Column = [None, 'rules12', 'rules3', 'rules3', None, None, 'rules2', 'rules3', 'rules3', 'rules2', 'rules3', 'rules3', 'rules3']\nisHit_Column = [False, True, True, True, False, False, True, True, True, True, True, True, True]\n================================\n code0 code1 ... isHit rules_desc\n0 5 (Agr, Serv) ... False None\n1 nan (VA, HC, NIH, SAP, AUS, HOL, ATT, COL, UCL) ... True rules12\n2 98 (ATT, NC) ... True rules3\n3 98 (ATT, VA, NC) ... True rules3\n4 (VA, HC, NIH, ATT, COL, UCL) ... False None\n5 15 Agr ... False None\n6 40 nan ... True rules2\n7 52 NC ... True rules3\n8 52 NC ... True rules3\n9 40 VA ... True rules2\n10 52 NC ... True rules3\n11 52 NC ... True rules3\n12 58 CE ... True rules3\n\n[13 rows x 9 columns]\n================================\n code0 code1 ... isHit rules_desc\n0 5 (Agr, Serv) ... False None\n1 nan (VA, HC, NIH, SAP, AUS, HOL, ATT, COL, UCL) ... True [rules1]\n2 98 (ATT, NC) ... False None\n3 98 (ATT, VA, NC) ... False None\n4 (VA, HC, NIH, ATT, COL, UCL) ... False None\n5 15 Agr ... False None\n6 40 nan ... True [rules12]\n7 52 NC ... False None\n8 52 NC ... False None\n9 40 VA ... True [rules4]\n10 52 NC ... False None\n11 52 NC ... False None\n12 58 CE ... True [rules5]\n\n[13 rows x 9 columns]\n================================\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20540822/" ]
74,525,648
<p>I started learning Ruby from scratch, from the preliminary preparation there is a certain knowledge of HTML and CSS. For training I use Code Academy. I have questions and can't always find an answer I can understand I need help understanding the following:</p> <pre><code>user_input = gets.chomp user_input.downcase! </code></pre> <p>Explain why user_input is equivalent to gets.chomp and what that means, thanks in advance!</p>
[ { "answer_id": 74526261, "author": "tadman", "author_id": 87189, "author_profile": "https://Stackoverflow.com/users/87189", "pm_score": 2, "selected": false, "text": "= x = 1\ny = x\n y x x=y nil gets String chomp downcase gets.chomp" }, { "answer_id": 74536549, "author": "Abhishek Sarkar", "author_id": 2606208, "author_profile": "https://Stackoverflow.com/users/2606208", "pm_score": 0, "selected": false, "text": " user_input = gets # will return the value entered by the user\n user_input = user_input.chomp # will remove the trailing \\n\n \n # A more idiomatic way to achieve the above steps in a single line\n user_input = gets.chomp\n\n # Finally downcase\n user_input.downcase!\n\n\n # By that same principle the entire code can be written in a single line\n user_input = gets.chomp.downcase\n String chomp downcase String String.new(\"hello\") == \"hello\" # true\n# \"hello\".chomp is same as String.new(\"hello\").chomp\n\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18877788/" ]
74,525,668
<p>I have a text that I use for taking data. I want to take this &quot;line&quot; and make it numpy list. My data is string but it has numbers and E letters. Because of this I can't convert it to float and taking it to list.</p> <pre><code>import numpy as np import re with open(&quot;FEMMeshGmsh.inp&quot;, &quot;r&quot;) as file: for line in file.readlines(): if &quot;+&quot; in line: line = line[:-1] a = np.array(line) print(a) </code></pre> <pre><code>10,1,0.0000000000000E+00 11,1,0.0000000000000E+00 26,1,0.0000000000000E+00 27,1,0.0000000000000E+00 80,1,6.2500000000000E+01 152,1,0.0000000000000E+00 153,1,0.0000000000000E+00 154,1,0.0000000000000E+00 155,1,6.2500000000000E+01 156,1,6.2500000000000E+01 157,1,6.2500000000000E+01 158,1,6.2500000000000E+01 159,1,0.0000000000000E+00 160,1,0.0000000000000E+00 161,1,0.0000000000000E+00 162,1,6.2500000000000E+01 163,1,6.2500000000000E+01 164,1,6.2500000000000E+01 165,1,6.2500000000000E+01 166,1,6.2500000000000E+01 424,1,1.2500000000000E+02 425,1,1.2500000000000E+02 426,1,1.2500000000000E+02 427,1,1.2500000000000E+02 428,1,1.2500000000000E+02 429,1,1.2500000000000E+02 430,1,1.2500000000000E+02 </code></pre> <p>I tried this code but the output is not in the list. I tried to convert this string to float using astype. But I took ValueError: could not convert string to float: '10,1,0.0000000000000E+00' this error.</p>
[ { "answer_id": 74526261, "author": "tadman", "author_id": 87189, "author_profile": "https://Stackoverflow.com/users/87189", "pm_score": 2, "selected": false, "text": "= x = 1\ny = x\n y x x=y nil gets String chomp downcase gets.chomp" }, { "answer_id": 74536549, "author": "Abhishek Sarkar", "author_id": 2606208, "author_profile": "https://Stackoverflow.com/users/2606208", "pm_score": 0, "selected": false, "text": " user_input = gets # will return the value entered by the user\n user_input = user_input.chomp # will remove the trailing \\n\n \n # A more idiomatic way to achieve the above steps in a single line\n user_input = gets.chomp\n\n # Finally downcase\n user_input.downcase!\n\n\n # By that same principle the entire code can be written in a single line\n user_input = gets.chomp.downcase\n String chomp downcase String String.new(\"hello\") == \"hello\" # true\n# \"hello\".chomp is same as String.new(\"hello\").chomp\n\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14613755/" ]
74,525,689
<p>I want to print pattern like this, but it prints like second one?</p> <pre><code> * * * * * * * * * * * * * * * </code></pre> <p><a href="https://i.stack.imgur.com/fJ0jK.png" rel="nofollow noreferrer">enter image description here</a> -- here is my script</p> <pre><code>* * * * * * * * * * * * * * * </code></pre>
[ { "answer_id": 74526261, "author": "tadman", "author_id": 87189, "author_profile": "https://Stackoverflow.com/users/87189", "pm_score": 2, "selected": false, "text": "= x = 1\ny = x\n y x x=y nil gets String chomp downcase gets.chomp" }, { "answer_id": 74536549, "author": "Abhishek Sarkar", "author_id": 2606208, "author_profile": "https://Stackoverflow.com/users/2606208", "pm_score": 0, "selected": false, "text": " user_input = gets # will return the value entered by the user\n user_input = user_input.chomp # will remove the trailing \\n\n \n # A more idiomatic way to achieve the above steps in a single line\n user_input = gets.chomp\n\n # Finally downcase\n user_input.downcase!\n\n\n # By that same principle the entire code can be written in a single line\n user_input = gets.chomp.downcase\n String chomp downcase String String.new(\"hello\") == \"hello\" # true\n# \"hello\".chomp is same as String.new(\"hello\").chomp\n\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19529424/" ]
74,525,746
<p>How do i get both of the values from each map into another map? One map has the name of the ingredient as key. keywordsToIds has the ID as value and firstCounter has the occurance of the ingredient as value. I want to have a map of ID as key and occurance as value. The keys work but the values don't. I hope someone can help me out. I am very new to maps and arraylists.</p> <pre><code>Map&lt;String, Long&gt; keywordsToIds Map&lt;String, Integer&gt; firstCounter Map&lt;Long, Integer&gt; idAndCount = new HashMap&lt;&gt;(); for (Map.Entry&lt;String, Integer&gt; entry : firstCounter.entrySet()) if (keywordsToIds.containsKey(entry.getKey())){ idAndCount.put(keywordsToIds.get(entry.getKey()), firstCounter.get(entry.getValue())); } return idAndCount; </code></pre> <pre><code>@Test @DisplayName(&quot;can detect multiple occurrences of ingredients&quot;) void testCounting() { // Input-Daten: String inputLine = &quot;Ich hätte gerne einen Vollkorn Burger mit Cheddar-Käse Cheddar-Käse und noch mehr Cheddar-Käse&quot;; Map&lt;String, Long&gt; keywordsToIds = Map.of( &quot;Vollkorn&quot;, 19L, &quot;Cheddar-Käse&quot;, 87L, &quot;Rindfleisch&quot;, 77L); Map&lt;Long, Integer&gt; expected = Map.of( 19L, 1, 87L, 3); Map&lt;Long, Integer&gt; actual = sut.idsAndCountFromInput(inputLine, keywordsToIds); assertEquals(expected, actual); } </code></pre> <pre><code>expected: &lt;{19=1, 87=3}&gt; but was: &lt;{19=null, 87=null}&gt; Expected :{19=1, 87=3} Actual :{19=null, 87=null} </code></pre> <p>I have tried the loop above, where i say if the key of the one map contains the key of the other map, put the value of keywordsToIds as key and value of firstCounter as value.</p>
[ { "answer_id": 74526261, "author": "tadman", "author_id": 87189, "author_profile": "https://Stackoverflow.com/users/87189", "pm_score": 2, "selected": false, "text": "= x = 1\ny = x\n y x x=y nil gets String chomp downcase gets.chomp" }, { "answer_id": 74536549, "author": "Abhishek Sarkar", "author_id": 2606208, "author_profile": "https://Stackoverflow.com/users/2606208", "pm_score": 0, "selected": false, "text": " user_input = gets # will return the value entered by the user\n user_input = user_input.chomp # will remove the trailing \\n\n \n # A more idiomatic way to achieve the above steps in a single line\n user_input = gets.chomp\n\n # Finally downcase\n user_input.downcase!\n\n\n # By that same principle the entire code can be written in a single line\n user_input = gets.chomp.downcase\n String chomp downcase String String.new(\"hello\") == \"hello\" # true\n# \"hello\".chomp is same as String.new(\"hello\").chomp\n\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20242740/" ]
74,525,749
<p>To place a video in one or more categories I have the following tables:</p> <ul> <li><code>Video (id, url, title, viewCount) </code> ~1,000,000 rows</li> <li><code>VideoCategory (id, videoId, categoryId</code> ~6,000,000 rows</li> <li><code>Category (id, name)</code> ~200 rows</li> </ul> <p>Index on <code>VideoCategory(categoryId, videoId)</code><br /> Unique Index on <code>Category(name)</code></p> <p>The following query, to get 10 most viewed videos in the 'Cars' category is too slow (~5.5 sec). The 'Cars' category contains 200,000 videos.</p> <pre class="lang-sql prettyprint-override"><code>SELECT v.* FROM Video v JOIN VideoCategory vc ON vc.videoId = v.id JOIN Category c ON vc.categoryId = c.id WHERE c.name = 'Cars' ORDER BY v.viewCount DESC LIMIT 10 </code></pre> <p>When querying a category that only contains 100 videos it takes ~0.05 sec.</p> <p><code>EXPLAIN</code> of query for 'Cars' category.</p> <pre><code>+------+-------------+-------+--------+------------------------------------+--------------------+---------+-----------------------+--------+----------------------------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +------+-------------+-------+--------+------------------------------------+--------------------+---------+-----------------------+--------+----------------------------------------------+ | 1 | SIMPLE | c | const | name_UNIQUE | name_UNIQUE | 322 | const | 1 | Using index; Using temporary; Using filesort | | 1 | SIMPLE | vc | ref | fk_Category_idx,category_video_idx | category_video_idx | 8 | const | 493988 | Using index | | 1 | SIMPLE | v | eq_ref | PRIMARY | PRIMARY | 8 | VideoDB.vc.videoId | 1 | Using where | +------+-------------+-------+--------+------------------------------------+--------------------+---------+-----------------------+--------+----------------------------------------------+ </code></pre> <p>How can I speed it up (hopefully 0.1 sec. or less)? Leaving out the <code>ORDER BY</code> has a massive impact but it obviously doesn't give me the result I want.</p> <p><strong>Update</strong><br /> I played around with <code>STRAIGHT_JOIN</code> and observed some interesting things with the following query:</p> <pre class="lang-sql prettyprint-override"><code>SELECT v.* FROM Video v STRAIGHT_JOIN VideoCategory vc ON v.id = vc.videoId WHERE vc.categoryId = (SELECT id FROM Category WHERE name = 'Cars') ORDER BY v.viewCount ASC LIMIT 10 </code></pre> <p>It returns in 0.011 sec! I also removed the <code>JOIN Category c</code> and replaced it with <code>WHERE vc.categoryId = (SELECT id FROM Category WHERE name = 'Cars')</code> which returns immediately with 0 results if the <code>Category.name</code> doesn't exist.</p> <p>Unfortunately just throwing in a <code>STRAIGHT_JOIN</code> doesn't fix everything, it is only fast(er) for categories with ~1000+ videos, the more videos the faster it seems. For a category containing less than 100 videos it gets extremely slow, taking out the <code>STRAIGHT_JOIN</code> makes it very fast again.</p> <p>For a query this simple I expected the planner to find the optimal path. What's going on here?</p> <p>Another observation is that changing the order from <code>ASC</code> to <code>DESC</code> will make the query slower again for some categories but not for other? (e.g. ASC will take 0.01 sec. and DESC will take 0.8 sec.)</p>
[ { "answer_id": 74526261, "author": "tadman", "author_id": 87189, "author_profile": "https://Stackoverflow.com/users/87189", "pm_score": 2, "selected": false, "text": "= x = 1\ny = x\n y x x=y nil gets String chomp downcase gets.chomp" }, { "answer_id": 74536549, "author": "Abhishek Sarkar", "author_id": 2606208, "author_profile": "https://Stackoverflow.com/users/2606208", "pm_score": 0, "selected": false, "text": " user_input = gets # will return the value entered by the user\n user_input = user_input.chomp # will remove the trailing \\n\n \n # A more idiomatic way to achieve the above steps in a single line\n user_input = gets.chomp\n\n # Finally downcase\n user_input.downcase!\n\n\n # By that same principle the entire code can be written in a single line\n user_input = gets.chomp.downcase\n String chomp downcase String String.new(\"hello\") == \"hello\" # true\n# \"hello\".chomp is same as String.new(\"hello\").chomp\n\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20566879/" ]
74,525,775
<pre><code>SELECT SP.SITE, SYS.COMPANY, SYS.ADDRESS, SP.CUSTOMER, SP.STATUS, DATEDIFF(MONTH,SP.MEMBERSINCE, SP.EXPIRES) AS MONTH_COUNT CASE WHEN(MONTH_COUNT = 0 THEN MONTH_COUNT = DATEDIFF(DAY,SP.MEMBERSINCE, SP.EXPIRES) AS DAY_COUNT) ELSE NULL END FROM SALEPASSES AS SP INNER JOIN SYSTEM AS SYS ON SYS.SITE = SP.SITE WHERE STATUS IN (7,27,29); </code></pre> <p>I am still trying to understand SQL. Is this the right order to have everything? I'm assuming my datediff() is unable to work because it's inside case when. What I am trying to do, is get the day count if month_count is less than 1 (meaning it's less than one month and we need to count the days between the dates instead). I need month_count to run first to see if doing the day_count would even be necessary. Please give me feedback, I'm new and trying to learn!</p>
[ { "answer_id": 74525820, "author": "Stu", "author_id": 15332650, "author_profile": "https://Stackoverflow.com/users/15332650", "pm_score": 1, "selected": false, "text": "Case DAY_COUNT =\n CASE WHEN DATEDIFF(MONTH,SP.MEMBERSINCE, SP.EXPIRES) = 0 \n THEN DATEDIFF(DAY,SP.MEMBERSINCE, SP.EXPIRES)) \n ELSE NULL END\n else null" }, { "answer_id": 74525944, "author": "MatBailie", "author_id": 53341, "author_profile": "https://Stackoverflow.com/users/53341", "pm_score": 0, "selected": false, "text": "SELECT\n *,\n CASE WHEN MonthCount = 0 THEN foo ELSE NULL END AS DayCount\nFROM\n(\n SELECT\n *,\n bar AS MonthCount\n FROM\n x\n)\n AS derive_month\n SELECT\n x.*,\n MonthCount,\n CASE WHEN MonthCount = 0 THEN foo ELSE NULL END AS DayCount\nFROM\n x\nCROSS APPLY\n(\n SELECT\n bar AS MonthCount\n)\n AS derive_month\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20567178/" ]
74,525,780
<p>I want to create a graph with date and time on the x axis and values on the y axis. This works if the data has 'x' as the key in the data. My data has the label 'date_time' as the key. I have tried to specify the the name of the key using the xAxisKey parameter in the parsing options but this results in a blank chart.</p> <p>This is my code:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var xyValues = [{ date_time: '2022-11-13 23:00:00', value: 2.3 }, { date_time: '2022-11-14 00:00:00', value: 3.1 }, { date_time: '2022-11-14 01:00:00', value: 4.5 }, { date_time: '2022-11-14 02:00:00', value: 5.1 }, { date_time: '2022-11-14 09:00:00', value: 5.5 } ] new Chart('myChart', { type: 'line', data: { datasets: [{ data: xyValues }] }, options: { parsing: { xAxisKey: 'date_time', yAxis: 'value' }, scales: { xAxes: [{ type: 'time' }] } } });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdn.jsdelivr.net/npm/chart.js/dist/chart.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"&gt;&lt;/script&gt; &lt;canvas id="myChart"&gt;&lt;/canvas&gt;</code></pre> </div> </div> </p> <p>How should the parsing be coded so that key from the data is correctly parsed as the x values?</p>
[ { "answer_id": 74525820, "author": "Stu", "author_id": 15332650, "author_profile": "https://Stackoverflow.com/users/15332650", "pm_score": 1, "selected": false, "text": "Case DAY_COUNT =\n CASE WHEN DATEDIFF(MONTH,SP.MEMBERSINCE, SP.EXPIRES) = 0 \n THEN DATEDIFF(DAY,SP.MEMBERSINCE, SP.EXPIRES)) \n ELSE NULL END\n else null" }, { "answer_id": 74525944, "author": "MatBailie", "author_id": 53341, "author_profile": "https://Stackoverflow.com/users/53341", "pm_score": 0, "selected": false, "text": "SELECT\n *,\n CASE WHEN MonthCount = 0 THEN foo ELSE NULL END AS DayCount\nFROM\n(\n SELECT\n *,\n bar AS MonthCount\n FROM\n x\n)\n AS derive_month\n SELECT\n x.*,\n MonthCount,\n CASE WHEN MonthCount = 0 THEN foo ELSE NULL END AS DayCount\nFROM\n x\nCROSS APPLY\n(\n SELECT\n bar AS MonthCount\n)\n AS derive_month\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5097329/" ]
74,525,811
<p>I am processing strings in R which are supposed to contain zero or one pair of parentheses. If there are nested parentheses I need to delete the inner pair. Here is an example where I need to delete the parentheses around <em>big bent nachos</em> but not the other/outer parentheses.</p> <pre><code>test &lt;- c( &quot;Record ID&quot;, &quot;What is the best food? (choice=Nachos)&quot;, &quot;What is the best food? (choice=Tacos (big bent nachos))&quot;, &quot;What is the best food? (choice=Chips with stuff)&quot;, &quot;Complete?&quot; ) </code></pre> <p>I know I can kill all the parentheses with the <code>stringr</code> package using <code>str_remove_all()</code>:</p> <pre><code>test |&gt; stringr::str_remove_all(stringr::fixed(&quot;)&quot;)) |&gt; stringr::str_remove_all(stringr::fixed(&quot;(&quot;)) </code></pre> <p>but I don't have the RegEx skills to pick the inner parentheses. I found a <a href="https://stackoverflow.com/questions/31546777/use-regex-to-remove-outer-parentheses-from-nested-expression-but-leave-inner-pa">SO post that is close</a> but it removes the outer parentheses and I cant untangle it to remove the inner.</p>
[ { "answer_id": 74525875, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 1, "selected": false, "text": "gsub() output <- gsub(\"\\\\(\\\\s*(.*?)\\\\s*\\\\(.*?\\\\)(.*?)\\\\s*\\\\)\", \"(\\\\1\\\\2)\", test)\noutput\n\n[1] \"Record ID\" \n[2] \"What is the best food? (choice=Nachos)\" \n[3] \"What is the best food? (choice=Tacos)\" \n[4] \"What is the best food? (choice=Chips with stuff)\"\n[5] \"Complete?\"\n test <- c(\n \"Record ID\", \n \"What is the best food? (choice=Nachos)\", \n \"What is the best food? (choice=Tacos (big bent nachos))\", \n \"What is the best food? (choice=Chips with stuff)\", \n \"Complete?\"\n)\n" }, { "answer_id": 74525896, "author": "Josh White", "author_id": 20289207, "author_profile": "https://Stackoverflow.com/users/20289207", "pm_score": 3, "selected": true, "text": "test |>\n stringr::str_replace_all(\"(\\\\().*\\\\(\", \"\\\\1\") |> # remove inner open brackets\n stringr::str_remove_all(\"\\\\)(?=.*\\\\))\") # remove inner closed brackets\n [1] \"Record ID\" \n[2] \"What is the best food? (choice=Nachos)\" \n[3] \"What is the best food? (big bent nachos)\" \n[4] \"What is the best food? (choice=Chips with stuff)\"\n[5] \"Complete?\"\n test |>\n stringr::str_replace(\"\\\\((.*)\\\\(\", \"(\\\\1\") |> # remove inner open brackets\n stringr::str_remove_all(\"\\\\)(?=.*\\\\))\") # remove inner outer brackets\n [1] \"Record ID\" \n[2] \"What is the best food? (choice=Nachos)\" \n[3] \"What is the best food? (choice=Tacos big bent nachos)\"\n[4] \"What is the best food? (choice=Chips with stuff)\" \n[5] \"Complete?\" \n" }, { "answer_id": 74525923, "author": "Dave2e", "author_id": 5792244, "author_profile": "https://Stackoverflow.com/users/5792244", "pm_score": 1, "selected": false, "text": "test <- c(\n \"Record ID\", \n \"What is the best food? (choice=Nachos)\", \n \"What is the best food? (choice=Tacos (big bent nachos))\", \n \"What is the best food? (choice=Chips with stuff)\", \n \"Complete?\"\n) \n\ntest <- gsub(\"(\\\\(.*)\\\\(\", \"\\\\1\", test)\n# ( \\\\(.* ) - first group starts with '(' then zero or more characters following that first '('\n# \\\\( - middle part look of a another '('\n\n# \"\\\\1\" replace the found group with the part from the first group\n\ntest <-gsub(\"\\\\)(.*\\\\))\", \"\\\\1\", test)\n#similer to first part\ntest\n\n[1] \"Record ID\" \n[2] \"What is the best food? (choice=Nachos)\" \n[3] \"What is the best food? (choice=Tacos big bent nachos)\"\n[4] \"What is the best food? (choice=Chips with stuff)\" \n[5] \"Complete?\" \n" }, { "answer_id": 74526750, "author": "bobble bubble", "author_id": 5527985, "author_profile": "https://Stackoverflow.com/users/5527985", "pm_score": 2, "selected": false, "text": "( ) test <- gsub(\"\\\\(([^)(]*)\\\\)(?=[^)(]*(?:\\\\([^)(]*\\\\)[^)(]*)*\\\\))\", \"\\\\1\", test, perl=T)\n \\1 ( ) ( ) ) test <- gsub(\"(?:\\\\G(?!^)|\\\\()[^)(]*+\\\\K(\\\\(((?>[^)(]+|(?1))*)\\\\))\", \"\\\\2\", test, perl=T)\n \\2 (?:\\G(?!^)|\\() \\G [^)(]*+\\K \\K (\\(((?>[^)(]+|(?1))*)\\)) (?1) ( ) ) \\G" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8729030/" ]
74,525,813
<p>i have a table with number :</p> <pre><code>&lt;td id=&quot;table-number&quot;&gt;{{ $loop-&gt;index + 1 }}&lt;/td&gt; </code></pre> <p>now i want to get the number of &quot;9&quot; from the table row</p> <p>Here is what i do :</p> <pre><code>const number = document.getElementById('table-number'); if(number.textContent.includes('9')) { console.log('heyhey'); } </code></pre> <p>but it returns nothing. So, what should i do? I expect to get the table number.</p> <p>ok guys, i got the answer at this <a href="https://stackoverflow.com/questions/58390633/jquery-find-td-with-exact-number-from-list">post</a>, sorry i didnt serach thoroughly. Need to upgrade my google skils</p>
[ { "answer_id": 74525875, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 1, "selected": false, "text": "gsub() output <- gsub(\"\\\\(\\\\s*(.*?)\\\\s*\\\\(.*?\\\\)(.*?)\\\\s*\\\\)\", \"(\\\\1\\\\2)\", test)\noutput\n\n[1] \"Record ID\" \n[2] \"What is the best food? (choice=Nachos)\" \n[3] \"What is the best food? (choice=Tacos)\" \n[4] \"What is the best food? (choice=Chips with stuff)\"\n[5] \"Complete?\"\n test <- c(\n \"Record ID\", \n \"What is the best food? (choice=Nachos)\", \n \"What is the best food? (choice=Tacos (big bent nachos))\", \n \"What is the best food? (choice=Chips with stuff)\", \n \"Complete?\"\n)\n" }, { "answer_id": 74525896, "author": "Josh White", "author_id": 20289207, "author_profile": "https://Stackoverflow.com/users/20289207", "pm_score": 3, "selected": true, "text": "test |>\n stringr::str_replace_all(\"(\\\\().*\\\\(\", \"\\\\1\") |> # remove inner open brackets\n stringr::str_remove_all(\"\\\\)(?=.*\\\\))\") # remove inner closed brackets\n [1] \"Record ID\" \n[2] \"What is the best food? (choice=Nachos)\" \n[3] \"What is the best food? (big bent nachos)\" \n[4] \"What is the best food? (choice=Chips with stuff)\"\n[5] \"Complete?\"\n test |>\n stringr::str_replace(\"\\\\((.*)\\\\(\", \"(\\\\1\") |> # remove inner open brackets\n stringr::str_remove_all(\"\\\\)(?=.*\\\\))\") # remove inner outer brackets\n [1] \"Record ID\" \n[2] \"What is the best food? (choice=Nachos)\" \n[3] \"What is the best food? (choice=Tacos big bent nachos)\"\n[4] \"What is the best food? (choice=Chips with stuff)\" \n[5] \"Complete?\" \n" }, { "answer_id": 74525923, "author": "Dave2e", "author_id": 5792244, "author_profile": "https://Stackoverflow.com/users/5792244", "pm_score": 1, "selected": false, "text": "test <- c(\n \"Record ID\", \n \"What is the best food? (choice=Nachos)\", \n \"What is the best food? (choice=Tacos (big bent nachos))\", \n \"What is the best food? (choice=Chips with stuff)\", \n \"Complete?\"\n) \n\ntest <- gsub(\"(\\\\(.*)\\\\(\", \"\\\\1\", test)\n# ( \\\\(.* ) - first group starts with '(' then zero or more characters following that first '('\n# \\\\( - middle part look of a another '('\n\n# \"\\\\1\" replace the found group with the part from the first group\n\ntest <-gsub(\"\\\\)(.*\\\\))\", \"\\\\1\", test)\n#similer to first part\ntest\n\n[1] \"Record ID\" \n[2] \"What is the best food? (choice=Nachos)\" \n[3] \"What is the best food? (choice=Tacos big bent nachos)\"\n[4] \"What is the best food? (choice=Chips with stuff)\" \n[5] \"Complete?\" \n" }, { "answer_id": 74526750, "author": "bobble bubble", "author_id": 5527985, "author_profile": "https://Stackoverflow.com/users/5527985", "pm_score": 2, "selected": false, "text": "( ) test <- gsub(\"\\\\(([^)(]*)\\\\)(?=[^)(]*(?:\\\\([^)(]*\\\\)[^)(]*)*\\\\))\", \"\\\\1\", test, perl=T)\n \\1 ( ) ( ) ) test <- gsub(\"(?:\\\\G(?!^)|\\\\()[^)(]*+\\\\K(\\\\(((?>[^)(]+|(?1))*)\\\\))\", \"\\\\2\", test, perl=T)\n \\2 (?:\\G(?!^)|\\() \\G [^)(]*+\\K \\K (\\(((?>[^)(]+|(?1))*)\\)) (?1) ( ) ) \\G" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5663877/" ]
74,525,830
<p>I am attempting to find recursively all files with the extension .raw and then sort them in ascending order of CreationTime. After that, I would like to copy each file to a new directory where the names are IMG_001_0001.jpg ... IMG_001_0099.jpg where I am using 4 digits in ascending order. It is important that the file name IMG_001_0001.jpg is the first one created and if there are 99 files, IMG_001_0099.jpg is the last file created.</p> <p>I tried this:</p> <pre><code>Get-ChildItem 'F:\Downloads\raw-20221121T200702Z-001.zip' -Recurse -include *.raw | Sort-Object CreationTime | ForEach-Object {copy $_.FullName F:\Downloads\raw-20221121T200702Z-001.zip/test/IMG_001_$($_.ReadCount).jpg} </code></pre>
[ { "answer_id": 74526056, "author": "Santiago Squarzon", "author_id": 15339544, "author_profile": "https://Stackoverflow.com/users/15339544", "pm_score": 2, "selected": false, "text": "$count = @{ Value = 0 }\nGet-ChildItem 'F:\\Downloads\\raw-20221121T200702Z-001.zip' -Recurse -Filter *.raw |\n Sort-Object CreationTime | Copy-Item -Destination {\n 'F:\\Downloads\\raw-20221121T200702Z-001.zip/test/IMG_001_{0:D4}.jpg' -f\n $count['Value']++\n }\n D4 ForEach-Object /test/ \\test\\" }, { "answer_id": 74527367, "author": "Ralph Sch", "author_id": 20551048, "author_profile": "https://Stackoverflow.com/users/20551048", "pm_score": 0, "selected": false, "text": "[int] Get-Childitem $ziproot ='F:\\input_folder'\n$count = 0\n$candidates = Get-ChildItem -Recurse -Filter '*.raw' |\nSort-Object CreationTime\n\nForEach($file in $candidates)\n{\ncopy-item -source $_.FullName -Destination ('{0}/test/IMG_001_{1:D4}{2}' -f $ziproot,++$count, $_.Extension )\n}\n foreach($var in $list) {commands}" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5373636/" ]
74,525,850
<p>I have the following code:</p> <pre><code>struct ContentView: View { @State var show = false var body: some View { VStack { ZStack { Color.black if show { RoundedRectangle(cornerRadius: 20) .fill(.brown) .transition(.opacity) } } Button { withAnimation(.easeInOut(duration: 1)) { show.toggle() } } label: { Text(&quot;TRIGGER&quot;) } } } } </code></pre> <p>I want the RoundedRectangle to fade in and out. <strong>Right now it only fades in</strong>. This is a simplified version of a more complex view setup I have. Depending on the state I may have the view I want to fade in or not. So, I am looking for a way to fade in (like it works now) but then also fade out so that the view is totally removed from the hierarchy and not just hidden or something.</p> <p>How can I have this code also fade OUT the view and not only fade in?</p> <p>As a reference I followed this approach:</p> <p><a href="https://swiftui-lab.com/advanced-transitions/" rel="nofollow noreferrer">https://swiftui-lab.com/advanced-transitions/</a></p> <pre><code>.... if show { LabelView() .animation(.easeInOut(duration: 1.0)) .transition(.opacity) } Spacer() Button(&quot;Animate&quot;) { self.show.toggle() }.padding(20) .... </code></pre> <p>But, in my case it is NOT fading out.</p>
[ { "answer_id": 74525965, "author": "flanker", "author_id": 3218273, "author_profile": "https://Stackoverflow.com/users/3218273", "pm_score": 0, "selected": false, "text": "struct ContentView: View {\n @State var show = false\n \n var body: some View {\n VStack {\n ZStack {\n Color.black\n (RoundedRectangle(cornerRadius: 20)\n .fill(.brown)\n .opacity(show ? 1 : 0)\n )\n }\n \n Button {\n withAnimation(.easeInOut(duration: 1)) {\n show.toggle()\n }\n } label: {\n Text(\"TRIGGER\")\n }\n }\n }\n}\n ZStack {\n Color.black\n show ? (RoundedRectangle(cornerRadius: 20)\n .fill(.brown)\n .zIndex(1). //kudos to @aheze for this!\n\n ).onDisappear{print(\"gone\")}\n : nil\n }\n" }, { "answer_id": 74526283, "author": "aheze", "author_id": 14351818, "author_profile": "https://Stackoverflow.com/users/14351818", "pm_score": 3, "selected": true, "text": "ZStack zIndex RoundedRectangle(cornerRadius: 20)\n .fill(.brown)\n .transition(.opacity)\n .zIndex(1) /// here!\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/728246/" ]
74,525,861
<p>I am working on a python practice, it is about trying to check the availability of products in a json file, the condition is that if Key is equal to 1, then it means that producs is available, so if the product is available, then print key names. The Json format looks like:</p> <pre><code>product={&quot;FooBox&quot;: &quot;1&quot;, &quot;ZeroB&quot;: &quot;0&quot;, &quot;Birk&quot;: &quot;1&quot;, &quot;pjy&quot;: &quot;0&quot;, &quot;dimbo&quot;: &quot;1&quot;} </code></pre> <p>I would like to get something like following: Acording to preview file, if Key value is &quot;1&quot; then return Key Name, like following:</p> <pre><code>&quot;Foobox&quot;,&quot;Birk&quot;,&quot;dimbo&quot; </code></pre> <p>Could someone help me to explain how I can get this working?</p> <p>I tried using somethink like:</p> <pre><code>product='[&quot;FooBox&quot;: &quot;1&quot;, &quot;ZeroB&quot;: &quot;0&quot;, &quot;Birk&quot;: &quot;1&quot;, &quot;pjy&quot;: &quot;0&quot;, &quot;dimbo&quot;: &quot;1&quot;]' for x in product: if x==&quot;1&quot;: print(x) else: print(&quot;Not Available&quot;) </code></pre> <p>But is output is just the number &quot;1&quot; not the key name, which is what I require.</p>
[ { "answer_id": 74525894, "author": "Barmar", "author_id": 1491895, "author_profile": "https://Stackoverflow.com/users/1491895", "pm_score": 2, "selected": true, "text": "product for x in product: x product.items() product={\"FooBox\": \"1\", \"ZeroB\": \"0\", \"Birk\": \"1\", \"pjy\": \"0\", \"dimbo\": \"1\"}\n\navailable = [name for name, avail in product.items() if avail == \"1\"]\nprint(available)\n" }, { "answer_id": 74525898, "author": "John Gordon", "author_id": 494134, "author_profile": "https://Stackoverflow.com/users/494134", "pm_score": 0, "selected": false, "text": "for key,value in product.items():\n if value == \"1\":\n print(key)\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20567162/" ]
74,525,863
<p>I'm trying to update an elevated PowerShell script that's using StartProcess on a BAT file that runs RunAs on PowerShell.exe to run another PowerShell script without elevation in order to clone a git repository so that the directory is created in a way that a normal non-elevated user will be able to use.</p> <ul> <li>Elevated PS1: Start-Process <ul> <li>=&gt; Elevated .BAT: RunAs /trustlevel:0x20000 <ul> <li>=&gt; Non-elevated PS1</li> </ul> </li> </ul> </li> </ul> <p>This is failing in some environments and I can't figure out why so I'm trying to figure out how to capture stdout and stderr from all levels of this process, but I'm not seeing the error or any output. I can capture it down to the BAT file level, but I can't seem to see anything that's happening within the inner-most Powershell script.</p> <p>This seems like an awful lot of work just to programmatically clone a Git repository from an elevated process. Is there a way to make this work or is there an easier way?</p> <p><strong>EDIT:</strong> Just learned that this solution was broken as of Windows 11 Update 22H2: <a href="https://superuser.com/questions/1749696/parameter-is-incorrect-when-using-runas-with-trustlevel-after-windows-11-22h2">https://superuser.com/questions/1749696/parameter-is-incorrect-when-using-runas-with-trustlevel-after-windows-11-22h2</a> but the workaround is to use the /machine switch when running RunAs.</p>
[ { "answer_id": 74621096, "author": "BlueMonkMN", "author_id": 78162, "author_profile": "https://Stackoverflow.com/users/78162", "pm_score": 1, "selected": false, "text": "function IsAdmin{\n $currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())\n $Is64 = [Environment]::Is64BitOperatingSystem\n if ($currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {\n Write-Output \"Running with elevated privileges. (64-bit=$Is64)\"\n } else {\n Write-Output \"Running without elevated privileges. (64-bit=$Is64)\"\n }\n}\n\nIsAdmin\nWrite-Output \"Running $PSScriptRoot\\test.bat\"\nStart-Process -FilePath \"$PSScriptRoot\\test.bat\" -ArgumentList \"C:\\\" -NoNewWindow\n$np = new-object System.IO.Pipes.NamedPipeClientStream('.','SAMPipe', [System.IO.Pipes.PipeDirection]::In,[System.IO.Pipes.PipeOptions]::None,[System.Security.Principal.TokenImpersonationLevel]::Impersonation)\n$np.Connect()\n$sr = new-object System.IO.StreamReader($np)\nwhile ($l=$sr.ReadLine()) {\n Write-Output $l\n}\n$sr.Close()\n$np.Close()\n runas /machine:amd64 /trustlevel:0x20000 \"powershell -command %~dp0test2.ps1 -drive %1 >dummy.txt\"\n param([string]$drive)\n\nfunction IsAdmin{\n $currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())\n $Is64 = [Environment]::Is64BitOperatingSystem\n if ($currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {\n Write-Output \"Running with elevated privileges. (64-bit=$Is64)\"\n } else {\n Write-Output \"Running without elevated privileges. (64-bit=$Is64)\"\n }\n}\n\nfunction Setup-Test{\n Write-Output \"Testing Powershell with Parameter Drive=$drive\"\n git config --global user.name\n cd bob\n Write-Error \"Error Line 1\nError Line 2\"\n Write-Error \"Error Line 3\"\n $d = 3/0\n Write-Output \"Done Testing Powershell\"\n}\n\n$np = New-Object System.IO.Pipes.NamedPipeServerStream('SAMPipe',[System.IO.Pipes.PipeDirection]::Out)\n$np.WaitForConnection()\n$sw = New-Object System.IO.StreamWriter($np)\n$sw.WriteLine('Begin Non-Elevated Process Pipe')\nInvoke-Command -ScriptBlock {\n try {\n IsAdmin\n Setup-Test\n } catch {\n Write-Error $_\n } \n} -ErrorVariable errVar -OutVariable out\nforeach ($line in $out){\n $sw.WriteLine($line)\n}\nforeach ($line in $errVar) {\n $sw.WriteLine($line)\n}\n$sw.WriteLine('End Non-Elevated Process Pipe')\n$sw.Close()\n$np.Close()\n Running with elevated privileges. (64-bit=True)\nRunning C:\\Users\\bmarty\\source\\PowerShellTest\\test.bat\n\nC:\\Users\\bmarty\\source\\PowerShellTest>runas /machine:amd64 /trustlevel:0x20000 \"powershell -command C:\\Users\\bmarty\\source\\PowerShellTest\\test2.ps1 -drive C:\\ >dummy.txt\"\nBegin Non-Elevated Process Pipe\nRunning without elevated privileges. (64-bit=True)\nTesting Powershell with Parameter Drive=C:\\\nBen Marty\nCannot find path 'C:\\Users\\bmarty\\source\\PowerShellTest\\bob' because it does not exist.\nError Line 1\nError Line 2\nError Line 3\nAttempted to divide by zero.\nSystem.Management.Automation.RuntimeException: Attempted to divide by zero. ---> System.DivideByZeroException: Attempted to divide by zero.\n --- End of inner exception stack trace ---\n at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception)\n at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame)\n at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)\n at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)\nAttempted to divide by zero.\nAttempted to divide by zero.\nEnd Non-Elevated Process Pipe\nDone running\n" }, { "answer_id": 74632803, "author": "mklement0", "author_id": 45375, "author_profile": "https://Stackoverflow.com/users/45375", "pm_score": 2, "selected": true, "text": "runas.exe Start-Process -Wait System.IO.Pipes.NamedPipeClientStream runas.exe test2.ps1 Start-Process -Wait test2.ps1 System.IO.Pipes.NamedPipeClientStream test.ps1 function IsAdmin{\n $currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())\n $Is64 = [Environment]::Is64BitOperatingSystem\n if ($currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {\n Write-Output \"Running with elevated privileges. (64-bit=$Is64)\"\n } else {\n Write-Output \"Running without elevated privileges. (64-bit=$Is64)\"\n }\n}\n\nIsAdmin\n\n# Create a temporary file in which to capture the output from the \n# PowerShell child process launched by runas.exe.\n$outFile = New-TemporaryFile\n\n# Use Start-Process -Wait to directly invoke runas.exe,\n# which doesn't just wait for runas.exe ITSELF to exit, but also\n# waits for its CHILD processes.\n# This ensures that execution is blocked until the other PowerShell script exits too. \nStart-Process -Wait runas.exe @\"\n/machine:amd64 /trustlevel:0x20000 \"powershell -c & \\\"$PSScriptRoot\\test2.ps1\\\" -drive C:\\ *> \\\"$outFile\\\"\"\n\"@\n\n# Now $outFile contains all output produced by the other PowerShell script.\nWrite-Verbose -Verbose \"Output from the runas.exe-launched PowerShell script:\"\nGet-Content -LiteralPath $outFile\n\n$outFile | Remove-Item # Clean up.\n test2.ps1 param([string]$drive)\n\nfunction IsAdmin{\n $currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())\n $Is64 = [Environment]::Is64BitOperatingSystem\n if ($currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {\n Write-Output \"Running with elevated privileges. (64-bit=$Is64)\"\n } else {\n Write-Output \"Running without elevated privileges. (64-bit=$Is64)\"\n }\n}\n\nfunction Setup-Test{\n Write-Output \"Testing Powershell with Parameter Drive=$drive\"\n git config --global user.name\n cd bob\n Write-Error \"Error Line 1\nError Line 2\"\n Write-Error \"Error Line 3\"\n $d = 3/0\n Write-Output \"Done Testing Powershell\"\n}\n\nIsAdmin\nSetup-Test\n" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78162/" ]
74,525,865
<p>Hi I am just starting to learn cpp and I have two examples of getting the size of a vector in the for statements both seem to work but which is right and why? sizeof(vector) or vector.size()?</p> <p>Thanks</p> <p>Brian</p> <pre><code>void print_vector(vector&lt;string&gt; vector_to_print){ cout &lt;&lt; &quot;\nCars vector = &quot;; for(int i = 0; i &lt; sizeof(vector_to_print); i++){ cout &lt;&lt; vector_to_print[i]; (i &lt; vector_to_print.size()-1) ? (cout &lt;&lt; &quot;, &quot;) : (cout &lt;&lt; endl); // ? the tenrary operator is an if statement (?) do one outcome (:) or the other } } </code></pre> <pre><code>void print_vector(vector &lt;string&gt; vector_to_print){ cout &lt;&lt; &quot;\nVector contents = &quot;; for( int i = 0; i &lt; (vector_to_print.size()); i++ ){ cout &lt;&lt; vector_to_print[i]; (i &lt; (vector_to_print.size()-1)) ? (cout &lt;&lt; &quot;, &quot;) : (cout &lt;&lt; endl); } } </code></pre> <p>Both seem to work I try to rewrite the same code from memory each day for a week to help me learn it and I couldn't quite get the sizeof() to work so I googled it and the example I found used .size() but when I got home and checked what I did yesterday I had used sizeof().</p>
[ { "answer_id": 74526013, "author": "tedo3637", "author_id": 5740753, "author_profile": "https://Stackoverflow.com/users/5740753", "pm_score": 0, "selected": false, "text": ".size() .size() sizeof() vector size_t .size()" }, { "answer_id": 74526081, "author": "wigi426", "author_id": 12518633, "author_profile": "https://Stackoverflow.com/users/12518633", "pm_score": 3, "selected": true, "text": "std::vector<std::string> std::strings sizeof(vector_to_print) std::vector<std::string> vec{\"hello\",\"world\"};\nstd::cout << sizeof(vec) << '\\n';\nvec.push_back(\"!\");\nstd::cout << sizeof(vec);\n sizeof(vec) sizeof(vec) sizeof .size()" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15510512/" ]
74,525,869
<h1>The Ask:</h1> <p>Please help me understand my conceptual error in the use of <code>scale_x_binned()</code> in ggplot2 as it relates to centering breaks beneath the appropriate bin in a <code>geom_histogram()</code>.</p> <h2>Starting Example:</h2> <pre class="lang-r prettyprint-override"><code>library(ggplot2) df &lt;- data.frame(hour = sample(seq(0,23), 150, replace = TRUE)) # The data is just the integer values of the 24-hour clock in a day. It is # **NOT** continuous data. ggplot(df, aes(x = hour)) + geom_histogram(bins = 24, fill = &quot;grey60&quot;, color = &quot;red&quot;) </code></pre> <p><img src="https://i.imgur.com/WVEhPB7.png" alt="" /></p> <p>This produces a histogram with labels properly centered beneath the bin for which it belongs, but I want to label each hour, 0 - 23.</p> <p>To do that, I thought I would assign breaks using <code>scale_x_binned()</code> as demonstrated below.</p> <h2>Now I try to add the breaks:</h2> <pre class="lang-r prettyprint-override"><code>ggplot(df, aes(x = hour)) + geom_histogram(bins = 24, fill = &quot;grey60&quot;, color = &quot;red&quot;) + scale_x_binned(name = &quot;Hour of Day&quot;, breaks = seq(0,23)) #&gt; Warning: Removed 1 rows containing missing values (`geom_bar()`). </code></pre> <p><img src="https://i.imgur.com/qawFVm7.png" alt="" /></p> <p>This returns the number of labels I wanted, but they are not centered beneath the bins as desired. I also get the warning message for missing values associated with <code>geom_bar()</code>.</p> <p>I believe I am overwriting the <code>bins = 24</code> from the <code>geom_histogram()</code> call when I use the <code>scale_x_binned()</code> call afterward, but I don't understand exactly what is causing <code>geom_histogram()</code> to be centered in the first case that I am wrecking with my new call. I'd really like to have that clarified as I am not seeing my error when I read the associated help pages.</p> <h1>EDIT:</h1> <p>The &quot;Starting Example&quot; essentially works (bins are centered) except for the number of labels I ultimately want. If you built the ggplot2 layer differently, what is the equivalent code? That is, instead of:</p> <pre class="lang-r prettyprint-override"><code>ggplot(df, aes(x = hour)) + geom_histogram(bins = 24, fill = &quot;grey60&quot;, color = &quot;red&quot;) </code></pre> <p>the call was instead built <strong>something like</strong>:</p> <pre class="lang-r prettyprint-override"><code>ggplot(df, aes(x = hour)) + geom_histogram(fill = &quot;grey60&quot;, color = &quot;red&quot;) + scale_x_binned(n.breaks = 24) # I know this isn't right, but akin to this. </code></pre> <p>or maybe</p> <pre class="lang-r prettyprint-override"><code>ggplot(df, aes(x = hour)) + stat_bin(bins = 24, center = 0, fill = &quot;grey60&quot;, color = &quot;red&quot;) </code></pre>
[ { "answer_id": 74526013, "author": "tedo3637", "author_id": 5740753, "author_profile": "https://Stackoverflow.com/users/5740753", "pm_score": 0, "selected": false, "text": ".size() .size() sizeof() vector size_t .size()" }, { "answer_id": 74526081, "author": "wigi426", "author_id": 12518633, "author_profile": "https://Stackoverflow.com/users/12518633", "pm_score": 3, "selected": true, "text": "std::vector<std::string> std::strings sizeof(vector_to_print) std::vector<std::string> vec{\"hello\",\"world\"};\nstd::cout << sizeof(vec) << '\\n';\nvec.push_back(\"!\");\nstd::cout << sizeof(vec);\n sizeof(vec) sizeof(vec) sizeof .size()" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3601357/" ]
74,525,884
<p>In jQuery - how can I check to see if a <code>&lt;li&gt;</code> that follows another has a class or not.</p> <p>Markup is:</p> <pre><code>&lt;ul&gt; &lt;li&gt;&lt;a href&quot;#&quot;&gt;Title 1&lt;/a&gt;&lt;/li&gt; &lt;li class=&quot;LI_sector_child&quot;&gt;&lt;a href&quot;#&quot;&gt;Title 2&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href&quot;#&quot;&gt;Title 3&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href&quot;#&quot;&gt;Title 4&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>So, I want to be able to target the 3rd li element as shown above (Title 3) so I can add a class to that.</p> <p>So, I am looking to find 2 LI's that are next to each other in the DOM that don't have the class &quot;LI_sector_child&quot; applied.</p> <p>Note - I cant use nth-child / nth-of-type as the UL is generated dynamically each time.</p>
[ { "answer_id": 74526013, "author": "tedo3637", "author_id": 5740753, "author_profile": "https://Stackoverflow.com/users/5740753", "pm_score": 0, "selected": false, "text": ".size() .size() sizeof() vector size_t .size()" }, { "answer_id": 74526081, "author": "wigi426", "author_id": 12518633, "author_profile": "https://Stackoverflow.com/users/12518633", "pm_score": 3, "selected": true, "text": "std::vector<std::string> std::strings sizeof(vector_to_print) std::vector<std::string> vec{\"hello\",\"world\"};\nstd::cout << sizeof(vec) << '\\n';\nvec.push_back(\"!\");\nstd::cout << sizeof(vec);\n sizeof(vec) sizeof(vec) sizeof .size()" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1197577/" ]
74,525,911
<p>This started about a month ago, that random images in my browser have been replaced by crazy things, usually a seagull picture. It is very distracting.</p> <p>I've tried everything. Chrome, Firefox, Safari. I've cleared all my internet history.</p>
[ { "answer_id": 74526013, "author": "tedo3637", "author_id": 5740753, "author_profile": "https://Stackoverflow.com/users/5740753", "pm_score": 0, "selected": false, "text": ".size() .size() sizeof() vector size_t .size()" }, { "answer_id": 74526081, "author": "wigi426", "author_id": 12518633, "author_profile": "https://Stackoverflow.com/users/12518633", "pm_score": 3, "selected": true, "text": "std::vector<std::string> std::strings sizeof(vector_to_print) std::vector<std::string> vec{\"hello\",\"world\"};\nstd::cout << sizeof(vec) << '\\n';\nvec.push_back(\"!\");\nstd::cout << sizeof(vec);\n sizeof(vec) sizeof(vec) sizeof .size()" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20567305/" ]
74,525,954
<p>Needing help for a RegEx (using Oracle REGEXP_LIKE) to identify strings that:</p> <ol> <li>Start with any of the following:</li> </ol> <ul> <li>P</li> <li>C</li> <li>(P)</li> <li>(C)</li> <li>©</li> </ul> <ol start="2"> <li>are then followed by a space</li> <li>are then followed by any 4-digit numbers, where the first 2 digits in the number are 19 or 20.</li> <li>are then followed by a space</li> <li>are then followed by any other text</li> </ol> <p>Sample matches:</p> <ul> <li>(P) 2004 XYZ Company</li> <li>P 2018 This is some random text</li> <li>(C) 1994 More Random Text</li> </ul> <p>Sample non-matches:</p> <ul> <li>(P) XYZ Company</li> <li>P1976,Just Wow</li> <li>(C) 1856 Too Late For Gold</li> </ul> <p>I've started with</p> <pre><code>^[PC©]\s+ </code></pre> <p>but, as a beginner, am stumped with how to handle the (P) and (C) cases, much less the complexities that follow with the year values.</p>
[ { "answer_id": 74526013, "author": "tedo3637", "author_id": 5740753, "author_profile": "https://Stackoverflow.com/users/5740753", "pm_score": 0, "selected": false, "text": ".size() .size() sizeof() vector size_t .size()" }, { "answer_id": 74526081, "author": "wigi426", "author_id": 12518633, "author_profile": "https://Stackoverflow.com/users/12518633", "pm_score": 3, "selected": true, "text": "std::vector<std::string> std::strings sizeof(vector_to_print) std::vector<std::string> vec{\"hello\",\"world\"};\nstd::cout << sizeof(vec) << '\\n';\nvec.push_back(\"!\");\nstd::cout << sizeof(vec);\n sizeof(vec) sizeof(vec) sizeof .size()" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20567274/" ]
74,525,967
<p>I have the following line in a file that I need to replace 2 parts of. This is the original line:</p> <pre><code>'display min(min(sindex,lon=%lon1%,lon=%lon2%),lat=%lat1%,lat=%lat2%)' </code></pre> <p>I need to replace it with this:</p> <pre><code>'display amin(actualPrecip,lon=%lon1%,lon=%lon2%,lat=%lat1%,lat=%lat2%)' </code></pre> <p>I used regexr.com to generate this regex to match the 2 parts, but not sure what to do with it. Basically I need to use sed to do an inplace replacement.</p> <pre><code>('display min\(min)|(\)\,) </code></pre> <p>That generated this on regexr.com:<br /> '<code>display min(min</code>(sindex,lon=%lon1%,lon=%lon2%<code>),</code>lat=%lat1%,lat=%lat2%)'<br /> So the first part needs to be replaced with <code>'display amin(</code> and 2nd match needs to be replaced with just a comma. Is there an easy way to do this using sed?</p> <p>Cheers, Mike</p>
[ { "answer_id": 74526013, "author": "tedo3637", "author_id": 5740753, "author_profile": "https://Stackoverflow.com/users/5740753", "pm_score": 0, "selected": false, "text": ".size() .size() sizeof() vector size_t .size()" }, { "answer_id": 74526081, "author": "wigi426", "author_id": 12518633, "author_profile": "https://Stackoverflow.com/users/12518633", "pm_score": 3, "selected": true, "text": "std::vector<std::string> std::strings sizeof(vector_to_print) std::vector<std::string> vec{\"hello\",\"world\"};\nstd::cout << sizeof(vec) << '\\n';\nvec.push_back(\"!\");\nstd::cout << sizeof(vec);\n sizeof(vec) sizeof(vec) sizeof .size()" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10422281/" ]
74,525,993
<p>I am trying to create a sign up with Django but after filling the form, I keep getting this <code>ValueError at /register</code> as an error requesting that the username be set. I am new to Django and I don't seem to understand what is expected. Below are my codes for signup form, the views.py and the resulting error respectively</p> <p>Signup form:</p> <pre><code>{% for message in messages %} &lt;h5&gt;{{message}}&lt;/h5&gt; {% endfor %} &lt;form method=&quot;POST&quot; action=&quot;register&quot; name=&quot;registerForm&quot;&gt; {% csrf_token %} &lt;p&gt;Username:&lt;/p&gt; &lt;input type=&quot;text&quot; name=&quot;username &quot;/&gt; &lt;p&gt;Email:&lt;/p&gt; &lt;input type=&quot;email&quot; name=&quot;email &quot;/&gt; &lt;p&gt;Password:&lt;/p&gt; &lt;input type=&quot;password&quot; name=&quot;password&quot;/&gt; &lt;p&gt;Repeat Password:&lt;/p&gt; &lt;input type=&quot;password&quot; name=&quot;confirm_password&quot;/&gt;&lt;br&gt; &lt;input type=&quot;submit&quot;/&gt; &lt;/form&gt; </code></pre> <p>views.py</p> <pre><code>def register(request): if request.method == 'POST': username = request.POST.get('username') email = request.POST.get('email') password = request.POST.get('password') confirm_password = request.POST.get('confirm_password') if password==confirm_password: if User.objects.filter(username=username).exists(): messages.info(request, 'Username Taken') return redirect('register') elif User.objects.filter(email=email).exists(): messages.info(request, 'Email Taken') return redirect('register') else: user = User.objects.create_user(username=username, email=email, password=password) user.save() return redirect('/') else: messages.info(request, 'Password does not match') return redirect('register') else: return render(request, 'register.html') </code></pre> <p>Error:</p> <pre><code>ValueError at /register The given username must be set Request Method: POST Request URL: http://127.0.0.1:8000/register Django Version: 4.1.3 Exception Type: ValueError Exception Value: The given username must be set Exception Location: C:\Users\User\Envs\myapp\lib\site-packages\django\contrib\auth\models.py, line 144, in _create_user Raised during: myapp.views.register Python Executable: C:\Users\User\Envs\myapp\Scripts\python.exe Python Version: 3.10.4 Python Path: ['C:\\Users\\User\\Desktop\\Python_journey\\djangoTut\\myproject', 'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python310\\python310.zip', 'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python310\\DLLs', 'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python310', 'C:\\Users\\User\\Envs\\myapp', 'C:\\Users\\User\\Envs\\myapp\\lib\\site-packages'] Server time: Tue, 22 Nov 2022 07:17:35 +0000 </code></pre>
[ { "answer_id": 74526013, "author": "tedo3637", "author_id": 5740753, "author_profile": "https://Stackoverflow.com/users/5740753", "pm_score": 0, "selected": false, "text": ".size() .size() sizeof() vector size_t .size()" }, { "answer_id": 74526081, "author": "wigi426", "author_id": 12518633, "author_profile": "https://Stackoverflow.com/users/12518633", "pm_score": 3, "selected": true, "text": "std::vector<std::string> std::strings sizeof(vector_to_print) std::vector<std::string> vec{\"hello\",\"world\"};\nstd::cout << sizeof(vec) << '\\n';\nvec.push_back(\"!\");\nstd::cout << sizeof(vec);\n sizeof(vec) sizeof(vec) sizeof .size()" } ]
2022/11/21
[ "https://Stackoverflow.com/questions/74525993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20567350/" ]