qid
int64
4
22.2M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,378,814
<p>A paper now in page proofs has been modified by the copy editor to have figure tags (e.g. 'A', 'B', ...) in <strong>bold</strong>, while the rest of the label is normal. For example &quot;<strong>A</strong> matches &gt; 30&quot;, &quot;<strong>B</strong> matches &gt; 60&quot;. I cannot figure out how to get facet_wrap() labeller to bold only part of the label string. I have not figured out how to get labeller=label_parsed to accept my bold string with &gt;= in it.</p>
[ { "answer_id": 74379017, "author": "CryptoFool", "author_id": 7631480, "author_profile": "https://Stackoverflow.com/users/7631480", "pm_score": 2, "selected": true, "text": "valuecheck()" }, { "answer_id": 74379095, "author": "frankfalse", "author_id": 18108367, "author_profile": "https://Stackoverflow.com/users/18108367", "pm_score": 1, "selected": false, "text": "#Write a Python program to delete an existing item from the array\n\n#function used to check for valid input\ndef valuecheck(checker):\n loopx = True\n while loopx:\n try:\n if (int(checker)>=0 and int(checker)<=4):\n loopx = False\n else:\n checker = input(\"Value isn't a valid input, try again: \")\n except Exception as ex:\n checker = input(\"Value isn't a valid input, try again: \")\n return checker\n\n#the example array is defined and printed\nmyarray = ['i', [1, 3, 5, 7, 9]]\nprint(myarray[1])\n\n#input defined and checked by the loop\ndeletion = input(\"Please input the index of the element you want to remove (0 through 4). Indexes for the elements start at 0, increasing left to right: \")\ndeletion = valuecheck(deletion)\n\n#pop is then used to remove the value with index \"deletion\" from the array\nmyarray[1].pop(int(deletion))\n#finally the new array is printed\nprint (\"This is the new array:\",myarray[1])\n" }, { "answer_id": 74379231, "author": "Gábor Fekete", "author_id": 6464041, "author_profile": "https://Stackoverflow.com/users/6464041", "pm_score": 0, "selected": false, "text": "def valuecheck():\n prompt = \"Please input the index of the element you want to remove (0 through 4). Indexes for the elements start at 0, increasing left to right: \"\n while True:\n try:\n checker = int(input(prompt))\n if 0 <= checker <= 4:\n return checker\n prompt = \"Value isn't in range [0,4], try again: \"\n except ValueError:\n prompt = \"Value isn't a valid integer, try again: \"\n\n#the example array is defined and printed\nmyarray = ['i', [1, 3, 5, 7, 9]]\nprint(myarray[1])\n\n#input defined and checked by the loop\ndeletion = valuecheck()\n\n#pop is then used to remove the value with index \"deletion\" from the array\nmyarray[1].pop(deletion)\n#finally the new array is printed\nprint (\"This is the new array:\",myarray[1])\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74378814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10332171/" ]
74,378,826
<pre><code>LocalDate beginDate = LocalDate.now() .with(ChronoField.DAY_OF_WEEK, 1) .atStartOfDay() .minusDays(8) .toLocalDate(); </code></pre> <p>I am getting the previous week begin date using the above code line. However I want to add HH:MM:SS format to this. I have tried different ways to get this. Tried using LocalDateTime instead of Localdate. But could not find <code>atStartOfDay()</code> method for LocalDateTime. Help me to add HH:MM:SS to <code>beginDate</code> variable</p>
[ { "answer_id": 74378868, "author": "Arkady Dymkov", "author_id": 20446959, "author_profile": "https://Stackoverflow.com/users/20446959", "pm_score": -1, "selected": false, "text": "@DateTimeFormat(\"HH:MM:SS\")\n@JsonFormat(\"HH:MM:SS\")\n" }, { "answer_id": 74379096, "author": "Basil Bourque", "author_id": 642706, "author_profile": "https://Stackoverflow.com/users/642706", "pm_score": 2, "selected": false, "text": "LocalDate // Represents a date only, without a time of day, without a time zone or offset. \n.now( ZoneId.of( \"Asia/Amman\" ) ) // Returns a `LocalDate`. \n.minusDays( 8 ) // Returns another `LocalDate` object. \n.atStartOfDay( ZoneId.of( \"Asia/Amman\" ) ) // Returns a `ZonedDateTime`. \n.toString() // Returns a `String` object, with text in standard ISO 8601 format wisely extended to append the name of time zone in brackets. \n" }, { "answer_id": 74379269, "author": "Christoph Dahlen", "author_id": 20370596, "author_profile": "https://Stackoverflow.com/users/20370596", "pm_score": 0, "selected": false, "text": "LocalDateTime\n .of(LocalDate.now().with(ChronoField.DAY_OF_WEEK, 1), LocalTime.MIDNIGHT)\n .minusWeeks(1)\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74378826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20406891/" ]
74,378,858
<pre><code>export interface team { football:Football table-tennis:TableTennis } export interface Football{ goalPost:any ball:any } export interface TableTennis{ bat:any ball:any } </code></pre>
[ { "answer_id": 74378868, "author": "Arkady Dymkov", "author_id": 20446959, "author_profile": "https://Stackoverflow.com/users/20446959", "pm_score": -1, "selected": false, "text": "@DateTimeFormat(\"HH:MM:SS\")\n@JsonFormat(\"HH:MM:SS\")\n" }, { "answer_id": 74379096, "author": "Basil Bourque", "author_id": 642706, "author_profile": "https://Stackoverflow.com/users/642706", "pm_score": 2, "selected": false, "text": "LocalDate // Represents a date only, without a time of day, without a time zone or offset. \n.now( ZoneId.of( \"Asia/Amman\" ) ) // Returns a `LocalDate`. \n.minusDays( 8 ) // Returns another `LocalDate` object. \n.atStartOfDay( ZoneId.of( \"Asia/Amman\" ) ) // Returns a `ZonedDateTime`. \n.toString() // Returns a `String` object, with text in standard ISO 8601 format wisely extended to append the name of time zone in brackets. \n" }, { "answer_id": 74379269, "author": "Christoph Dahlen", "author_id": 20370596, "author_profile": "https://Stackoverflow.com/users/20370596", "pm_score": 0, "selected": false, "text": "LocalDateTime\n .of(LocalDate.now().with(ChronoField.DAY_OF_WEEK, 1), LocalTime.MIDNIGHT)\n .minusWeeks(1)\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74378858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7375694/" ]
74,378,899
<p>This will not work for some reason. I have no idea why it doesnt work</p> <pre><code># adds an event @client.event async def on_message(message): # so i dont have to say message.content a lot msg = message.content # if a message starts with !dm create a dm channel with the specified user if msg.content.startswith(&quot;!dm&quot;): await create_dm('user') </code></pre>
[ { "answer_id": 74378868, "author": "Arkady Dymkov", "author_id": 20446959, "author_profile": "https://Stackoverflow.com/users/20446959", "pm_score": -1, "selected": false, "text": "@DateTimeFormat(\"HH:MM:SS\")\n@JsonFormat(\"HH:MM:SS\")\n" }, { "answer_id": 74379096, "author": "Basil Bourque", "author_id": 642706, "author_profile": "https://Stackoverflow.com/users/642706", "pm_score": 2, "selected": false, "text": "LocalDate // Represents a date only, without a time of day, without a time zone or offset. \n.now( ZoneId.of( \"Asia/Amman\" ) ) // Returns a `LocalDate`. \n.minusDays( 8 ) // Returns another `LocalDate` object. \n.atStartOfDay( ZoneId.of( \"Asia/Amman\" ) ) // Returns a `ZonedDateTime`. \n.toString() // Returns a `String` object, with text in standard ISO 8601 format wisely extended to append the name of time zone in brackets. \n" }, { "answer_id": 74379269, "author": "Christoph Dahlen", "author_id": 20370596, "author_profile": "https://Stackoverflow.com/users/20370596", "pm_score": 0, "selected": false, "text": "LocalDateTime\n .of(LocalDate.now().with(ChronoField.DAY_OF_WEEK, 1), LocalTime.MIDNIGHT)\n .minusWeeks(1)\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74378899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17205965/" ]
74,378,910
<p>I am creating two dataframes, that I set equal to eachother based on an index field. So each frame has the same indices on both sides and I sort them as well. I want to return the differences between these fields, so as to catch any of the rows that have 'updated' since the last run. But I am getting a weird result.</p> <pre><code> df1.compare(df2) </code></pre> <p><a href="https://i.stack.imgur.com/XleTX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XleTX.png" alt="enter image description here" /></a></p> <p>I fail to see any differences here, and when I manually look at the id's involved I do not see any changes at all. What could be causing this?</p>
[ { "answer_id": 74378868, "author": "Arkady Dymkov", "author_id": 20446959, "author_profile": "https://Stackoverflow.com/users/20446959", "pm_score": -1, "selected": false, "text": "@DateTimeFormat(\"HH:MM:SS\")\n@JsonFormat(\"HH:MM:SS\")\n" }, { "answer_id": 74379096, "author": "Basil Bourque", "author_id": 642706, "author_profile": "https://Stackoverflow.com/users/642706", "pm_score": 2, "selected": false, "text": "LocalDate // Represents a date only, without a time of day, without a time zone or offset. \n.now( ZoneId.of( \"Asia/Amman\" ) ) // Returns a `LocalDate`. \n.minusDays( 8 ) // Returns another `LocalDate` object. \n.atStartOfDay( ZoneId.of( \"Asia/Amman\" ) ) // Returns a `ZonedDateTime`. \n.toString() // Returns a `String` object, with text in standard ISO 8601 format wisely extended to append the name of time zone in brackets. \n" }, { "answer_id": 74379269, "author": "Christoph Dahlen", "author_id": 20370596, "author_profile": "https://Stackoverflow.com/users/20370596", "pm_score": 0, "selected": false, "text": "LocalDateTime\n .of(LocalDate.now().with(ChronoField.DAY_OF_WEEK, 1), LocalTime.MIDNIGHT)\n .minusWeeks(1)\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74378910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3486773/" ]
74,378,923
<p>I am trying to create a neat legend in Pyplot. So far I have this:</p> <p><a href="https://i.stack.imgur.com/jKZvC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jKZvC.png" alt="Legend" /></a></p> <pre><code> fig = plt.figure() ax = plt.gca() marker_size = [20.0, 40.0, 60.0, 100.0, 150.0] marker_color = ['black', 'red', 'pink', 'white', 'yellow'] ranges = [0.0, 1.5, 20.0, 60.0, 500.0] marker_edge_thickness = 1.2 s = [(m ** 2) / 100.0 for m in marker_size] scatter_kwargs = {'edgecolors' : 'k', 'linewidths' : marker_edge_thickness} for i in range(len(marker_size)): if i == (len(marker_size) - 1): label_str = '{:&gt;5.1f} $\leq$ H$_2$'.format(ranges[i]) else: label_str = '{:&gt;5.1f} $\leq$ H$_2$ &lt; {:&gt;5.1f}'.format(ranges[i], ranges[i + 1]) ax.scatter([], [], s = s[i], c = marker_color[i], label = label_str, **scatter_kwargs) #ax.legend(prop={'family': 'monospace'}) ax.legend() plt.show() </code></pre> <p>It is ok but the symbols don't align properly between the rows. I would like to align the rows at multiple points, with alignment on the decimal points, the less-than and greater-than symbols, and the H2. I could use a monotype font (as per this answer: <a href="https://stackoverflow.com/q/37353663/19979370">Adding internal spaces in pyplot legend</a>), but this is ugly and seems to be incompatible with the subscript 2 in H2. This would be possible in LaTeX (e.g. using the <code>alignat</code> environment); is it possible in Pyplot?</p>
[ { "answer_id": 74379514, "author": "JohanC", "author_id": 12046409, "author_profile": "https://Stackoverflow.com/users/12046409", "pm_score": 3, "selected": true, "text": "'\\u2007'" }, { "answer_id": 74379654, "author": "Ben Grossmann", "author_id": 2476977, "author_profile": "https://Stackoverflow.com/users/2476977", "pm_score": 2, "selected": false, "text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nfig = plt.figure()\nax = plt.gca()\n\nmarker_size = [20.0, 40.0, 60.0, 100.0, 150.0] \nmarker_color = ['black', 'red', 'pink', 'white', 'yellow'] \n\nranges = [0.0, 1.5, 20.0, 60.0, 500.0] \nnum_digits = [1,1,2,2,3]\n\nmarker_edge_thickness = 1.2 \ns = [(m ** 2) / 100.0 for m in marker_size] \nscatter_kwargs = {'edgecolors' : 'k', 'linewidths' : marker_edge_thickness} \n\nfor i in range(len(marker_size)): \n if i == (len(marker_size) - 1): \n label_str = '{:.1f}$\\leq \\mathregular{}$'.format(ranges[i],r'{\\ H_2\\ }') \n else: \n label_str = '{:>5.1f}$\\leq \\mathregular{}<${:>5.1f}'.format(ranges[i], r'{\\ H_2\\ }',ranges[i + 1])\n ax.scatter([], [], s = s[i], c = marker_color[i], \n label = label_str, **scatter_kwargs) \n\nax.legend(prop={'family': 'monospace'}) \n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74378923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19979370/" ]
74,378,973
<p>I have a dataframe, where I extract a certain subset:</p> <pre><code>tmp &lt;- mtcars |&gt; select(disp, hp) </code></pre> <p>then I make some data manipulation</p> <pre><code>tmp$disp &lt;- tmp$disp*0 tmp$hp &lt;- tmp$hp*2 </code></pre> <p>Now I want to reintegrate the changes into the original How?</p> <p>Of course I could work on the original df in the first place but I just want to know how to replace all values from a df by a subset.</p> <p>I want to keep the order of the column names and if possible I don't want to use any index. I also assume there are use cases where the select query is long.</p>
[ { "answer_id": 74379514, "author": "JohanC", "author_id": 12046409, "author_profile": "https://Stackoverflow.com/users/12046409", "pm_score": 3, "selected": true, "text": "'\\u2007'" }, { "answer_id": 74379654, "author": "Ben Grossmann", "author_id": 2476977, "author_profile": "https://Stackoverflow.com/users/2476977", "pm_score": 2, "selected": false, "text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nfig = plt.figure()\nax = plt.gca()\n\nmarker_size = [20.0, 40.0, 60.0, 100.0, 150.0] \nmarker_color = ['black', 'red', 'pink', 'white', 'yellow'] \n\nranges = [0.0, 1.5, 20.0, 60.0, 500.0] \nnum_digits = [1,1,2,2,3]\n\nmarker_edge_thickness = 1.2 \ns = [(m ** 2) / 100.0 for m in marker_size] \nscatter_kwargs = {'edgecolors' : 'k', 'linewidths' : marker_edge_thickness} \n\nfor i in range(len(marker_size)): \n if i == (len(marker_size) - 1): \n label_str = '{:.1f}$\\leq \\mathregular{}$'.format(ranges[i],r'{\\ H_2\\ }') \n else: \n label_str = '{:>5.1f}$\\leq \\mathregular{}<${:>5.1f}'.format(ranges[i], r'{\\ H_2\\ }',ranges[i + 1])\n ax.scatter([], [], s = s[i], c = marker_color[i], \n label = label_str, **scatter_kwargs) \n\nax.legend(prop={'family': 'monospace'}) \n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74378973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2032712/" ]
74,378,980
<p>Java LibGdx Box2d</p> <p>I would like to make body borders invisible or at least different color. One body should work as sensor and thus not be visible on the screen. I could not find a valid answer for that in hours and I cannot believe there is no such option in this library so I assume I must have missed one liner somewhere in Docs.</p> <p>I would like to make this square transparent/invisible or at least different color but still keep it to discover movement of these circles.</p> <p><a href="https://i.stack.imgur.com/M0xgd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/M0xgd.png" alt="enter image description here" /></a></p> <p>Looking over stackoverflow and googling it in docs.</p> <p>Closest things I found: <a href="https://stackoverflow.com/questions/47381020/make-invisible-body-line-box2d-libgdx">Make invisible body line box2d libgdx</a></p> <p>so maybe the only solution to this is setting some flags in render method or unique render methods for each body?</p>
[ { "answer_id": 74379514, "author": "JohanC", "author_id": 12046409, "author_profile": "https://Stackoverflow.com/users/12046409", "pm_score": 3, "selected": true, "text": "'\\u2007'" }, { "answer_id": 74379654, "author": "Ben Grossmann", "author_id": 2476977, "author_profile": "https://Stackoverflow.com/users/2476977", "pm_score": 2, "selected": false, "text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nfig = plt.figure()\nax = plt.gca()\n\nmarker_size = [20.0, 40.0, 60.0, 100.0, 150.0] \nmarker_color = ['black', 'red', 'pink', 'white', 'yellow'] \n\nranges = [0.0, 1.5, 20.0, 60.0, 500.0] \nnum_digits = [1,1,2,2,3]\n\nmarker_edge_thickness = 1.2 \ns = [(m ** 2) / 100.0 for m in marker_size] \nscatter_kwargs = {'edgecolors' : 'k', 'linewidths' : marker_edge_thickness} \n\nfor i in range(len(marker_size)): \n if i == (len(marker_size) - 1): \n label_str = '{:.1f}$\\leq \\mathregular{}$'.format(ranges[i],r'{\\ H_2\\ }') \n else: \n label_str = '{:>5.1f}$\\leq \\mathregular{}<${:>5.1f}'.format(ranges[i], r'{\\ H_2\\ }',ranges[i + 1])\n ax.scatter([], [], s = s[i], c = marker_color[i], \n label = label_str, **scatter_kwargs) \n\nax.legend(prop={'family': 'monospace'}) \n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74378980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13211194/" ]
74,379,021
<p>I'm tring to make a clean Flask App which use SQLAlchemy and Multi-Threading.</p> <p>I've read the doc : <a href="https://docs.sqlalchemy.org/en/14/orm/contextual.html#thread-local-scope" rel="nofollow noreferrer">https://docs.sqlalchemy.org/en/14/orm/contextual.html#thread-local-scope</a> but can't manage to make it work successfully.</p> <p>SQL Alchemy is initate directly at the app <strong><strong>init</strong>.py</strong> file with something like that :</p> <pre><code>db = SQLAlchemy(app) session_factory = sessionmaker( bind=db.engine, autocommit=False, autoflush=False) DBSession = scoped_session( session_factory ) </code></pre> <p>And in another file, which <strong>is not</strong> some Flask routes, on a Class :</p> <pre><code>from blabla import DBSession class Worker(Thread): def __init__(self): Thread.__init__(self) self.dbsession = DBSession() def run(self): self.dbsession.query(...) </code></pre> <p>When I run my app, multiple Worker Class is running at the same time. Then I'm facing lot of errors like :</p> <pre><code>sqlalchemy.exc.InternalError: (pymysql.err.InternalError) Packet sequence number wrong - got 54 expected 1 </code></pre> <p>What I am doing wrong ?</p> <p>Thanks a lot in advance for your time !</p>
[ { "answer_id": 74379514, "author": "JohanC", "author_id": 12046409, "author_profile": "https://Stackoverflow.com/users/12046409", "pm_score": 3, "selected": true, "text": "'\\u2007'" }, { "answer_id": 74379654, "author": "Ben Grossmann", "author_id": 2476977, "author_profile": "https://Stackoverflow.com/users/2476977", "pm_score": 2, "selected": false, "text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nfig = plt.figure()\nax = plt.gca()\n\nmarker_size = [20.0, 40.0, 60.0, 100.0, 150.0] \nmarker_color = ['black', 'red', 'pink', 'white', 'yellow'] \n\nranges = [0.0, 1.5, 20.0, 60.0, 500.0] \nnum_digits = [1,1,2,2,3]\n\nmarker_edge_thickness = 1.2 \ns = [(m ** 2) / 100.0 for m in marker_size] \nscatter_kwargs = {'edgecolors' : 'k', 'linewidths' : marker_edge_thickness} \n\nfor i in range(len(marker_size)): \n if i == (len(marker_size) - 1): \n label_str = '{:.1f}$\\leq \\mathregular{}$'.format(ranges[i],r'{\\ H_2\\ }') \n else: \n label_str = '{:>5.1f}$\\leq \\mathregular{}<${:>5.1f}'.format(ranges[i], r'{\\ H_2\\ }',ranges[i + 1])\n ax.scatter([], [], s = s[i], c = marker_color[i], \n label = label_str, **scatter_kwargs) \n\nax.legend(prop={'family': 'monospace'}) \n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2373259/" ]
74,379,026
<p>I'm trying to set up a GCP Cloud Function to generate the email verification link using <code>admin.auth().generateEmailVerificationLink</code>, but it throws the error:</p> <pre><code>Error: Credential implementation provided to initializeApp() via the &quot;credential&quot; property has insufficient permission to access the requested resource. See https://firebase.google.com/docs/admin/setup for details on how to authenticate this SDK with appropriate permissions. </code></pre> <p>I was able to reproduce this error with the following Cloud Function code:</p> <p><strong>index.js:</strong></p> <pre><code>const admin = require('firebase-admin'); admin.initializeApp(); exports.helloWorld = (req, res) =&gt; { execute(res); }; const execute = async (res) =&gt; { const email = 'test@test.com'; const url = 'https://example.firebaseapp.com'; const link = await admin.auth().generateEmailVerificationLink(email, { url }); console.log(link); res.status(200).send(link); }; </code></pre> <p><strong>package.json:</strong></p> <pre><code>{ &quot;name&quot;: &quot;sample-http&quot;, &quot;version&quot;: &quot;0.0.1&quot;, &quot;dependencies&quot;: { &quot;firebase-admin&quot;: &quot;^10.0.2&quot; } } </code></pre> <p>My Firebase Admin Service Account (<code>firebase-adminsdk-XXX@example.iam.gserviceaccount.com</code>) has the roles:</p> <ul> <li>Firebase Admin SDK Administrator Service Agent</li> <li>Service Account Token Creator</li> </ul> <p>I also viewed the API Key in Firebase Console, found it in GCP (<code>Browser key (auto created by Firebase)</code>, and see that it has the following APIs selected:</p> <ul> <li>Cloud Firestore API</li> <li>Cloud Functions API</li> <li>Firebase Installations API</li> <li>Token Service API</li> <li>Identity Toolkit API</li> </ul> <p>I tried following the provided link (<a href="https://firebase.google.com/docs/admin/setup" rel="nofollow noreferrer">https://firebase.google.com/docs/admin/setup</a>), but it seems specific to setting up <code>admin</code> outside of a GCP Cloud Function (see <a href="https://firebase.google.com/docs/admin/setup#initialize-without-parameters" rel="nofollow noreferrer">https://firebase.google.com/docs/admin/setup#initialize-without-parameters</a>). I also read through <a href="https://firebase.google.com/docs/auth/admin/email-action-links" rel="nofollow noreferrer">https://firebase.google.com/docs/auth/admin/email-action-links</a>, but there were no helpful details that I could find.</p> <p>I tried using <code>functions.https.onCall</code> instead of the regular GCP exports.</p> <p>I tried setting <code>FIREBASE_CONFIG={&quot;projectId&quot;:&quot;example&quot;,&quot;storageBucket&quot;:&quot;example.appspot.com&quot;,&quot;locationId&quot;:&quot;&lt;my-region&gt;&quot;}</code> and <code>GCLOUD_PROJECT=example</code> as runtime env vars.</p>
[ { "answer_id": 74380501, "author": "Alexander N.", "author_id": 3946096, "author_profile": "https://Stackoverflow.com/users/3946096", "pm_score": 0, "selected": false, "text": "FIREBASE_CONFIG" }, { "answer_id": 74381937, "author": "Ryan Saunders", "author_id": 6090140, "author_profile": "https://Stackoverflow.com/users/6090140", "pm_score": 2, "selected": false, "text": "firebase-adminsdk-XXX@example.iam.gserviceaccount.com" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6090140/" ]
74,379,039
<p>Hi everyone I would like to display for each element all of its sub-documents.</p> <pre><code> &lt;div&gt;&lt;ul&gt;{designModdulles.map((designModdulle)=&gt;&lt;li key={designModdulle.epreuves.nature_epreuve}&gt;{designModdulle.epreuves.nature_epreuve}&lt;/li&gt;) }&lt;/ul&gt;&lt;/div&gt; ``` I wanted the sub documents to be displayed` in a map but i had: Warning: Each child in a list should have a unique &quot;key&quot; prop. </code></pre>
[ { "answer_id": 74380501, "author": "Alexander N.", "author_id": 3946096, "author_profile": "https://Stackoverflow.com/users/3946096", "pm_score": 0, "selected": false, "text": "FIREBASE_CONFIG" }, { "answer_id": 74381937, "author": "Ryan Saunders", "author_id": 6090140, "author_profile": "https://Stackoverflow.com/users/6090140", "pm_score": 2, "selected": false, "text": "firebase-adminsdk-XXX@example.iam.gserviceaccount.com" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17161829/" ]
74,379,088
<p>There's an object below named cricket mania consisting of net runs and points scored by different countries. I am trying to write a code in JS to sort the teams according to their Points first, and if they have the same points, use Net Run as the tiebreaker. In our case, its the Bangladesh and Nepal that has scored same points, so we will be considering the net runs of those two countries which are -1.176 of Bangladesh and -0.849 of Nepal. Since Nepal has got the highest net runs, we will arrange Nepal's net runs first. I have sorted the points but I am unable to figure out how do I replace the similar points by using net runs. I need the below array to be logged in to the console [ '3', '4', '5', '6', '-0.849', '-1.176' ].I would surely appreciate the time the people of this community would take to solve this little doubt that I am stucked in and would be more than happy to have someone to aid me out in this process of learning :)</p> <p><a href="https://codepen.io/suha_ain77/pen/OJEWowp?editors=0010" rel="nofollow noreferrer">This is the link to my codepen </a></p> <p>``</p> <pre><code> const cricketMania = { India: { netRuns: &quot;1.319&quot;, points: &quot;8&quot; }, Pakistan: { netRuns: &quot;1.028&quot;, points: &quot;6&quot; }, Saudi: { netRuns: &quot;0.874&quot;, points: &quot;5&quot; }, Nepal: { netRuns: &quot;-0.849&quot;, points: &quot;4&quot; }, Bangladesh: { netRuns: &quot;-1.176&quot;, points: &quot;4&quot; }, Zimbabwe: { netRuns: &quot;-1.138&quot;, points: &quot;3&quot; } }; var point = []; // [ '8', '6', '5', '8', '4', '3' ] for (let m in cricketMania) { point.push(cricketMania[m][&quot;points&quot;]); } var sortedpoints = point.sort((a, b) =&gt; a - b); document.write(sortedpoints); //[ '3', '4', '5', '6', '8', '8' ] </code></pre> <p>``</p>
[ { "answer_id": 74379433, "author": "Alexey Zelenin", "author_id": 6290921, "author_profile": "https://Stackoverflow.com/users/6290921", "pm_score": 2, "selected": true, "text": "asArray.sort((a, b) => (a.points * 100 + a.netRuns) - (b.points * 100 + b.netRuns));\n" }, { "answer_id": 74385723, "author": "Rohìt Jíndal", "author_id": 4116300, "author_profile": "https://Stackoverflow.com/users/4116300", "pm_score": 0, "selected": false, "text": "Object.values()" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17526212/" ]
74,379,093
<pre><code>//1 print(&quot;abc&quot;.replaceAllMapped(RegExp(&quot;(.).+&quot;), (m) =&gt; &quot;${m[1]}&quot;)); //printed &quot;a&quot; //2 var r = r&quot;${m[1]}&quot;; //variables from outside print(&quot;abc&quot;.replaceAllMapped(RegExp(&quot;(.).+&quot;), (m) =&gt; r)); //printed &quot;${m[1]}&quot; //How can I get the same result &quot;a&quot; as the first example </code></pre> <p><strong>How can I get the same result as the first example</strong></p> <p>I'm new to Dart lang and don't know what keywords to search for this.</p> <p>Thank you.</p> <p>I tried this, but maybe it's not a better way?</p> <pre><code> var r = r&quot;${m[1]}&quot;; print(&quot;abc&quot;.replaceAllMapped(RegExp(&quot;(.).+&quot;), (m) { var r2 = r; for (var i = 0; i &lt;= m.groupCount; i++) { r2 = r2.replaceAll(&quot;\${m[$i]}&quot;, m[i]!); } return r2; })); </code></pre>
[ { "answer_id": 74379433, "author": "Alexey Zelenin", "author_id": 6290921, "author_profile": "https://Stackoverflow.com/users/6290921", "pm_score": 2, "selected": true, "text": "asArray.sort((a, b) => (a.points * 100 + a.netRuns) - (b.points * 100 + b.netRuns));\n" }, { "answer_id": 74385723, "author": "Rohìt Jíndal", "author_id": 4116300, "author_profile": "https://Stackoverflow.com/users/4116300", "pm_score": 0, "selected": false, "text": "Object.values()" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20461337/" ]
74,379,123
<p>I am just starting to learn C. Any help is appreciated!</p> <p>I have an array of pointers to a struct, and I want to use the built-in <a href="https://en.cppreference.com/w/c/algorithm/qsort" rel="nofollow noreferrer">qsort function</a> to sort the array according to values in the structs the pointers point to. I am trying to use a compare function as demonstrated in the <a href="https://en.cppreference.com/w/c/algorithm/qsort" rel="nofollow noreferrer">official docs</a>.</p> <p>The following version fails:</p> <pre><code>int compare_nodes(const void* a, const void* b){ const struct ListNode * ptr1 = ((const struct ListNode *) a); const struct ListNode * ptr2 = ((const struct ListNode *) b); // const struct ListNode * ptr1 = *((const struct ListNode **) a); // const struct ListNode * ptr2 = *((const struct ListNode **) b); int arg1 = ptr1 -&gt; val; int arg2 = ptr2 -&gt; val; if(arg1 &lt; arg2) return -1; if(arg1 &gt; arg2) return 1; return 0; } </code></pre> <p>This version succeeds:</p> <pre><code> int compare_nodes(const void* a, const void* b){ // const struct ListNode * ptr1 = ((const struct ListNode *) a); // const struct ListNode * ptr2 = ((const struct ListNode *) b); const struct ListNode * ptr1 = *((const struct ListNode **) a); const struct ListNode * ptr2 = *((const struct ListNode **) b); int arg1 = ptr1 -&gt; val; int arg2 = ptr2 -&gt; val; if(arg1 &lt; arg2) return -1; if(arg1 &gt; arg2) return 1; return 0; } </code></pre> <p>I do not understand the difference between the two versions:</p> <ol> <li>If casting only tells the compiler how to interpret the address the pointer points to, what is the problem in version 1? Is it not enough to tell the compiler to interpret the pointer to void as a pointer to struct ListNode? Why do I need to add a layer of indirection with casting, just to then remove one layer with dereferencing?</li> <li>Does C's pass-by-value play any role here? I could not think of any reason why by myself.</li> </ol> <p>I found the following resources about this question. Although they seemed to explain this problem (especially resource 6), I did not understand them:</p> <ol> <li><p><a href="https://stackoverflow.com/questions/17260527/what-are-the-rules-for-casting-pointers-in-c">What are the rules for casting pointers in C?</a></p> </li> <li><p><a href="https://stackoverflow.com/questions/14373924/typecasting-of-pointers-in-c">Typecasting of pointers in C</a></p> </li> <li><p><a href="https://stackoverflow.com/questions/51364499/pointer-type-casting-and-dereferencing">Pointer type casting and dereferencing</a></p> </li> <li><p><a href="https://stackoverflow.com/questions/17260527/what-are-the-rules-for-casting-pointers-in-c">What are the rules for casting pointers in C?</a></p> </li> <li><p><a href="https://stackoverflow.com/questions/13746136/what-does-a-c-cast-really-do">What does a C cast really do?</a></p> </li> <li><p><a href="https://cboard.cprogramming.com/c-programming/102056-casting-pointer-pointer.html" rel="nofollow noreferrer">https://cboard.cprogramming.com/c-programming/102056-casting-pointer-pointer.html</a></p> </li> </ol> <p>Here's the full code:</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;stddef.h&gt; #include &lt;stdio.h&gt; struct ListNode { int val; struct ListNode *next; }; int calc_list_length(struct ListNode * head){ int target = 0; struct ListNode * tmp = head; while (tmp) { target++; tmp = tmp -&gt; next; } return target; } int compare_nodes(const void* a, const void* b){ // const struct ListNode * ptr1 = ((const struct ListNode *) a); // const struct ListNode * ptr2 = ((const struct ListNode *) b); const struct ListNode * ptr1 = *((const struct ListNode **) a); const struct ListNode * ptr2 = *((const struct ListNode **) b); int arg1 = ptr1 -&gt; val; int arg2 = ptr2 -&gt; val; if(arg1 &lt; arg2) return -1; if(arg1 &gt; arg2) return 1; return 0; } struct ListNode* sortList(struct ListNode* head){ if(!head) return NULL; int list_length = calc_list_length(head); struct ListNode * tmp = head; struct ListNode * arr[list_length]; for (int i = 0; i &lt; list_length; i++) { arr[i] = tmp; tmp = tmp -&gt; next; } for (int i = 0; i &lt; list_length; i++) { printf(&quot;%d &quot;, arr[i] -&gt; val); } printf(&quot;\n&quot;); qsort(arr, list_length, sizeof(struct ListNode *), compare_nodes); for (int i = 0; i &lt; list_length; i++) { printf(&quot;%d &quot;, arr[i] -&gt; val); } printf(&quot;\n&quot;); } int main(){ // [2,1,4,3] struct ListNode node4 = {.val = 3, . next = NULL}; struct ListNode * ptr4 = &amp;node4; struct ListNode node3 = {.val = 4, .next = ptr4}; struct ListNode * ptr3 = &amp;node3; struct ListNode node2 = {.val = 1, .next = ptr3}; struct ListNode * ptr2 = &amp;node2; struct ListNode node1 = {.val = 2, .next = ptr2}; struct ListNode * ptr1 = &amp;node1; sortList(ptr1); getchar(); return 0; } </code></pre> <p>Thanks in advance. I hope you point me in the right direction.</p>
[ { "answer_id": 74379178, "author": "Some programmer dude", "author_id": 440558, "author_profile": "https://Stackoverflow.com/users/440558", "pm_score": 2, "selected": false, "text": "qsort" }, { "answer_id": 74379491, "author": "Vlad from Moscow", "author_id": 2877241, "author_profile": "https://Stackoverflow.com/users/2877241", "pm_score": 2, "selected": true, "text": "void qsort(void *base, size_t nmemb, size_t size, \n int (*compar)(const void *, const void *));\n" }, { "answer_id": 74503023, "author": "newacct", "author_id": 86989, "author_profile": "https://Stackoverflow.com/users/86989", "pm_score": 0, "selected": false, "text": "qsort()" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8552542/" ]
74,379,162
<p>I'm looking to stack the indices of some columns on top of one another, this is what I currently have:</p> <pre class="lang-py prettyprint-override"><code> Buy Buy Currency Sell Sell Currency Date 2013-12-31 100 CAD 100 USD 2014-01-02 200 USD 200 CAD 2014-01-03 300 CAD 300 USD 2014-01-06 400 USD 400 CAD </code></pre> <p>This is what I'm looking to achieve:</p> <pre class="lang-py prettyprint-override"><code>Buy/Sell Buy/Sell Currency 100 USD 100 CAD 200 CAD 200 USD 300 USD 300 CAD </code></pre> <p>And so on. Basically want to take the values in &quot;Buy&quot; and &quot;Buy Currency&quot; and stack their values in the &quot;Sell&quot; and &quot;Sell Currency&quot; columns, one after the other.</p> <p>And so on. I should mention that my data frame has 10 columns in total so using</p> <pre class="lang-py prettyprint-override"><code>df_pl.stack(level=0) </code></pre> <p>doesn't seem to work.</p>
[ { "answer_id": 74379178, "author": "Some programmer dude", "author_id": 440558, "author_profile": "https://Stackoverflow.com/users/440558", "pm_score": 2, "selected": false, "text": "qsort" }, { "answer_id": 74379491, "author": "Vlad from Moscow", "author_id": 2877241, "author_profile": "https://Stackoverflow.com/users/2877241", "pm_score": 2, "selected": true, "text": "void qsort(void *base, size_t nmemb, size_t size, \n int (*compar)(const void *, const void *));\n" }, { "answer_id": 74503023, "author": "newacct", "author_id": 86989, "author_profile": "https://Stackoverflow.com/users/86989", "pm_score": 0, "selected": false, "text": "qsort()" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4731636/" ]
74,379,181
<p>So i have a main function that calls two other functions, one of witch i have to await for result, so each funtion needs to be called separatly as they are trigered in different parts of the code, but test1 funct can run in parallel and i don't need the result, but test2 needs to provide a result.</p> <p>I like for both functions to run in parallel..</p> <p>this is my code so far.. cant get the two request to happen in parallel.</p> <pre><code>function test1() { yourUrl = 'http://www.google.com/' var xhr = new XMLHttpRequest(); xhr.open(&quot;POST&quot;, yourUrl, true); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onload = function(e) { console.log('get pedido') } xhr.send() } async function test2() { yourUrl = 'http://www.google.com' var xhr = new XMLHttpRequest(); xhr.open(&quot;POST&quot;, yourUrl, true); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onload = function(e) { console.log('get precio') } xhr.send() return true } async function main() { test1() await test2() } main() </code></pre>
[ { "answer_id": 74379455, "author": "Totigamer 2004", "author_id": 16471853, "author_profile": "https://Stackoverflow.com/users/16471853", "pm_score": 0, "selected": false, "text": "function getData(yourUrl, method=\"POST\"){\n return new Promise((resolve, reject) => \n var xhr = new XMLHttpRequest();\n xhr.open(method, yourUrl, true);\n xhr.setRequestHeader('Content-Type', 'application/json');\n xhr.onload = function(e) {\n console.log('get pedido')\n resolve() //PASS DATA TO NEXT .then\n } \n xhr.send()\n )\n}\n\n \nfunction test1(){\n\n yourUrl = 'http://www.google.com/'\n return getData(yourUrl)\n\n}\n\nfunction test2(){\n yourUrl = 'http://www.google.com/'\n return getData(yourUrl)\n}\n\nfunction main(){\n Promise.all([test1,test2])\n .then(res => console.log(res[0], res[1])\n}\n\n//EASIER SOLUTION \n\nfunction test1(){\n const yourUrl = 'http://www.google.com/';\n return fetch(yourUrl)\n .then(res => res.json())\n // if plain text res.text()\n}\nfunction test2(){\n const yourUrl = 'http://www.google.com'\n return fetch(yourUrl)\n .then(res => res.json())\n // if plain text res.text()\n}\nfunction main(){\n Promise.all([test1,test2])\n .then(res => console.log(res[0], res[1])\n}" }, { "answer_id": 74379477, "author": "Barmar", "author_id": 1491895, "author_profile": "https://Stackoverflow.com/users/1491895", "pm_score": 2, "selected": true, "text": "test2" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8459020/" ]
74,379,192
<p>I want to get ID value of this HTML markup.</p> <p>Example: 123</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 id_query = document.querySelector("div.elementor-element-429a9ef"); var id_value = id_query.getElementsByTagName("div")[0].id; console.log(id_query, id_value)</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="elementor-column elementor-col-33 elementor-inner-column elementor-element elementor-element-c44908c" data-id="c44908c" data-element_type="column"&gt; &lt;div class="elementor-widget-wrap elementor-element-populated"&gt; &lt;div class="elementor-element elementor-element-429a9ef elementor-widget elementor-widget-heading" data-id="429a9ef" data-element_type="widget" id="1646" data-widget_type="heading.default"&gt; &lt;div class="elementor-widget-container"&gt; &lt;div class="elementor-heading-title elementor-size-default"&gt;2021-10-10 13:00:00&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74379256, "author": "isherwood", "author_id": 1264804, "author_profile": "https://Stackoverflow.com/users/1264804", "pm_score": 2, "selected": false, "text": "querySelector" }, { "answer_id": 74379257, "author": "Roman Zenia", "author_id": 18704880, "author_profile": "https://Stackoverflow.com/users/18704880", "pm_score": 1, "selected": false, "text": "var id_query = document.querySelector(\"div.elementor-element-429a9ef\");\n\nconsole.log(id_query.id)\nconsole.log(id_query.dataset.id)" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19808840/" ]
74,379,216
<p>I have the following HTML/CSS code for displaying an image and a block of text side by side over a full-width background image.</p> <pre><code>&lt;section style=&quot;position: static; background-color: black; margin: 0; padding: 0; width: 100%; background-image: url(&quot;background.jpg&quot;); background-repeat: no-repeat; background-size: 100%;&quot;&gt; &lt;img style=&quot;float: left; width: 50%; margin: 1%;&quot; src=&quot;overlay-image.jpg&quot; alt=&quot;Image overlaid on background image.&quot;&gt; &lt;p style=&quot;color:white;&quot;&gt;Text overlaid on background image.&lt;/p&gt; &lt;section&gt; </code></pre> <p>The trouble is, only the top portion of the background-image that is overlaid by the text shows.</p> <p>Is it possible to make the background image show its vertical portion as much as the overlaid image height?</p> <p>I've tried &quot;background-size: cover&quot;. In Google Chrome Version 107.0.5304.88 (Official Build) (64-bit), and Mozilla FireFox 106.0.5 (64-bit), the result is the same as above; only the portion of the background image overlaid by text, not image, show.</p>
[ { "answer_id": 74379917, "author": "Coder1979", "author_id": 11089218, "author_profile": "https://Stackoverflow.com/users/11089218", "pm_score": 0, "selected": false, "text": "<section style=\"position: static; background-color: black; margin: 0; padding: 0; width: 100%; background-image: url(\"background.jpg\"); background-repeat: no-repeat; background-size: 100%; display: flex;\">\n\n<img style=\"flex: 50%; margin: 1%;\" src=\"overlay-image.jpg\" alt=\"Image overlaid on background image.\">\n\n<div style=\"flex: 50%; text-align: left; margin: 1%;\">\n<p style=\"color:white;\">Text overlaid on background image.</p>\n</div>\n<section>\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11089218/" ]
74,379,227
<p>I am working on creating a simple desktop program in Java, and I want to upload files via this program to Dropbox, but the problem is that the access token has a short life (temporary), how can I make the access token have a long life, or if I can use the App key and App secret?</p> <p>I need a simple solution like a method or a java example.</p> <p>Is there anything better than Dropbox in this aspect and more flexible?</p> <p>Thanks for any help.</p> <p>This method works fine but the access token expires after a few hours</p> <pre><code> private void testUplaod() throws FileNotFoundException, IOException, DbxException { DbxClientV2 client; DbxRequestConfig config = new DbxRequestConfig(&quot;dropbox/TestUplaod&quot;); try (InputStream in = new FileInputStream(&quot;D:\\t1.txt&quot;)) { client = new DbxClientV2(config, ACCESS_TOKEN); FileMetadata metadata = client.files().uploadBuilder(&quot;/t1.txt&quot;) .uploadAndFinish(in); } </code></pre> <p>I was expecting it would work sustainably.</p>
[ { "answer_id": 74379917, "author": "Coder1979", "author_id": 11089218, "author_profile": "https://Stackoverflow.com/users/11089218", "pm_score": 0, "selected": false, "text": "<section style=\"position: static; background-color: black; margin: 0; padding: 0; width: 100%; background-image: url(\"background.jpg\"); background-repeat: no-repeat; background-size: 100%; display: flex;\">\n\n<img style=\"flex: 50%; margin: 1%;\" src=\"overlay-image.jpg\" alt=\"Image overlaid on background image.\">\n\n<div style=\"flex: 50%; text-align: left; margin: 1%;\">\n<p style=\"color:white;\">Text overlaid on background image.</p>\n</div>\n<section>\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13898091/" ]
74,379,233
<p>Working with a function to write to breakdown a large dataset into grouped files</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>State</th> <th>col1</th> <th>col2</th> </tr> </thead> <tbody> <tr> <td>MI</td> <td>a</td> <td>e</td> </tr> <tr> <td>MI</td> <td>b</td> <td>f</td> </tr> <tr> <td>OH</td> <td>c</td> <td>g</td> </tr> <tr> <td>OH</td> <td>d</td> <td>h</td> </tr> </tbody> </table> </div> <p>Output is currently working and parsing out files as MI.csv &amp; OH.csv</p> <pre><code>by(df, df$State, FUN=function(i) write.csv(i, paste0(i$State[1], &quot;.csv&quot;), na = &quot;&quot;, row.names = FALSE)) </code></pre> <p>How can I run this function or run it again on MI.csv to write all grouped values in col1 into new files? ie a.csv is ~/MI/a.csv, b is ~/MI/b.csv</p> <p>Tried different variations of block below</p> <pre><code>by(df, df$State, FUN=function(i) write.csv(i, paste0(i$State[1], &quot;~/*.csv&quot;), na = &quot;&quot;, row.names = FALSE)) </code></pre>
[ { "answer_id": 74379917, "author": "Coder1979", "author_id": 11089218, "author_profile": "https://Stackoverflow.com/users/11089218", "pm_score": 0, "selected": false, "text": "<section style=\"position: static; background-color: black; margin: 0; padding: 0; width: 100%; background-image: url(\"background.jpg\"); background-repeat: no-repeat; background-size: 100%; display: flex;\">\n\n<img style=\"flex: 50%; margin: 1%;\" src=\"overlay-image.jpg\" alt=\"Image overlaid on background image.\">\n\n<div style=\"flex: 50%; text-align: left; margin: 1%;\">\n<p style=\"color:white;\">Text overlaid on background image.</p>\n</div>\n<section>\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11021160/" ]
74,379,235
<p>I need to select the paragraph before the read more so that I can expand the height to the full height of the paragraph. I don't know how I can select it with the :focus selector</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>.main { background: red; } button:focus **select the one div** { background: pink; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="main"&gt; &lt;div class="one"&gt;&lt;p&gt;This is a paragraph. Extra words, Bla Bla........&lt;/P&gt;&lt;/div&gt; &lt;button&gt;Read More&lt;button&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74379917, "author": "Coder1979", "author_id": 11089218, "author_profile": "https://Stackoverflow.com/users/11089218", "pm_score": 0, "selected": false, "text": "<section style=\"position: static; background-color: black; margin: 0; padding: 0; width: 100%; background-image: url(\"background.jpg\"); background-repeat: no-repeat; background-size: 100%; display: flex;\">\n\n<img style=\"flex: 50%; margin: 1%;\" src=\"overlay-image.jpg\" alt=\"Image overlaid on background image.\">\n\n<div style=\"flex: 50%; text-align: left; margin: 1%;\">\n<p style=\"color:white;\">Text overlaid on background image.</p>\n</div>\n<section>\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20461570/" ]
74,379,244
<p>Warning: DOMDocument::loadXML(): CData section not finished public function add() { $this-&gt;load-&gt;language(' in Entity, line: 584 in /home/s/syperdgq/syperdgq.beget.tech/public_html/admin/controller/marketplace/modification.php on line 467Warning: DOMDocument::loadXML(): Premature end of data in tag add line 371 in Entity, line: 584 in /home/s/syperdgq/syperdgq.beget.tech/public_html/admin/controller/marketplace/modification.php on line 467Warning: DOMDocument::loadXML(): Premature end of data in tag operation line 367 in Entity, line: 584 in /home/s/syperdgq/syperdgq.beget.tech/public_html/admin/controller/marketplace/modification.php on line 467Warning: DOMDocument::loadXML(): Premature end of data in tag file line 44 in Entity, line: 584 in /home/s/syperdgq/syperdgq.beget.tech/public_html/admin/controller/marketplace/modification.php on line 467Warning: DOMDocument::loadXML(): Premature end of data in tag modification line 2 in Entity, line: 584 in /home/s/syperdgq/syperdgq.beget.tech/public_html/admin/controller/marketplace/modification.php on line 467Notice: Trying to get property 'textContent' of non-object in /home/s/syperdgq/syperdgq.beget.tech/public_html/admin/controller/marketplace/modification.php on line 470</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;modification&gt; &lt;name&gt;Modification Manager&lt;/name&gt; &lt;code&gt;modification_manager&lt;/code&gt; &lt;version&gt;3.0.4&lt;/version&gt; &lt;author&gt;Opencart-templates&lt;/author&gt; &lt;link&gt;http://www.opencart-templates.co.uk/modification-manager&lt;/link&gt; &lt;file path=&quot;admin/language/en-gb/marketplace/modification.php&quot;&gt; &lt;operation&gt; &lt;search index=&quot;0&quot;&gt;&lt;![CDATA[&lt;?php]]&gt;&lt;/search&gt; &lt;add position=&quot;after&quot;&gt;&lt;![CDATA[ $_['tab_error'] = 'Error'; $_['tab_files'] = 'Files'; $_['text_add'] = 'Add Modification'; $_['text_edit'] = 'Edit Modification: %s'; $_['text_enabled'] = 'Enabled'; $_['text_disabled'] = 'Disabled'; $_['entry_author'] = 'Author'; $_['entry_name'] = 'Name'; $_['entry_xml'] = 'XML'; $_['button_filter'] = 'Filter'; $_['button_reset'] = 'Reset'; $_['button_download'] = 'Download'; $_['column_date_modified'] = 'Last Modified'; $_['error_warning'] = 'There has been an error. Please check your data and try again'; $_['error_required'] = 'This field is required'; $_['error_name'] = 'Missing name tag'; $_['error_code'] = 'Missing code tag'; $_['error_exists'] = 'Modification \'%s\' is already using the same code: %s!';]]&gt;&lt;/add&gt; &lt;/operation&gt; &lt;/file&gt; &lt;file path=&quot;admin/controller/marketplace/modification.php&quot;&gt; &lt;operation&gt; &lt;search index=&quot;0&quot;&gt;&lt;![CDATA[public function index() {]]&gt;&lt;/search&gt; &lt;add position=&quot;after&quot;&gt;&lt;![CDATA[ $this-&gt;load-&gt;model('extension/module/modification_manager'); $this-&gt;model_extension_module_modification_manager-&gt;install(); ]]&gt;&lt;/add&gt; &lt;/operation&gt; &lt;operation&gt; &lt;search&gt;&lt;![CDATA[$this-&gt;model_setting_modification]]&gt;&lt;/search&gt; &lt;add position=&quot;before&quot;&gt;&lt;![CDATA[$this-&gt;load-&gt;model('extension/module/modification_manager'); ]]&gt;&lt;/add&gt; &lt;/operation&gt; &lt;operation&gt; &lt;search&gt;&lt;![CDATA[$this-&gt;model_setting_modification-&gt;]]&gt;&lt;/search&gt; &lt;add position=&quot;replace&quot;&gt;&lt;![CDATA[$this-&gt;model_extension_module_modification_manager-&gt;]]&gt;&lt;/add&gt; &lt;/operation&gt; &lt;operation&gt; &lt;search index=&quot;0&quot;&gt;&lt;![CDATA[$sort = 'name';]]&gt;&lt;/search&gt; &lt;add position=&quot;replace&quot;&gt;&lt;![CDATA[$sort = 'date_modified';]]&gt;&lt;/add&gt; &lt;/operation&gt; &lt;operation&gt; &lt;search index=&quot;0&quot;&gt;&lt;![CDATA[$order = 'ASC';]]&gt;&lt;/search&gt; &lt;add position=&quot;replace&quot;&gt;&lt;![CDATA[$order = 'DESC';]]&gt;&lt;/add&gt; &lt;/operation&gt; &lt;operation&gt; &lt;search index=&quot;0&quot;&gt;&lt;![CDATA[$handle = fopen(DIR_LOGS . 'ocmod.log', 'w+');]]&gt;&lt;/search&gt; &lt;add position=&quot;before&quot;&gt;&lt;![CDATA[ fclose($handle); $handle = fopen(DIR_LOGS . 'ocmod_error.log', 'w+');]]&gt;&lt;/add&gt; &lt;/operation&gt; &lt;operation&gt; &lt;search index=&quot;0&quot;&gt;&lt;![CDATA[$maintenance = $this-&gt;config-&gt;get('config_maintenance');]]&gt;&lt;/search&gt; &lt;add position=&quot;after&quot;&gt;&lt;![CDATA[ // Clear logs on refresh $handle = fopen(DIR_LOGS . 'ocmod.log', 'w+'); fclose($handle); $handle = fopen(DIR_LOGS . 'ocmod_error.log', 'w+'); fclose($handle); ]]&gt;&lt;/add&gt; &lt;/operation&gt; &lt;operation&gt; &lt;search index=&quot;0&quot;&gt;&lt;![CDATA[$data['breadcrumbs'] = array();]]&gt;&lt;/search&gt; &lt;add position=&quot;before&quot;&gt;&lt;![CDATA[ $this-&gt;load-&gt;model('extension/module/modification_manager'); if (isset($this-&gt;request-&gt;get['filter_name'])) { $filter_name = $this-&gt;request-&gt;get['filter_name']; } else { $filter_name = null; } if (isset($this-&gt;request-&gt;get['filter_xml'])) { $filter_xml = $this-&gt;request-&gt;get['filter_xml']; } else { $filter_xml = null; } if (isset($this-&gt;request-&gt;get['filter_author'])) { $filter_author = $this-&gt;request-&gt;get['filter_author']; } else { $filter_author = null; } $url = $this-&gt;getListUrlParams(); $data['add'] = $this-&gt;url-&gt;link('marketplace/modification/add', 'user_token=' . $this-&gt;session-&gt;data['user_token'] . $url, true); $data['clear_log'] = $this-&gt;url-&gt;link('marketplace/modification/clearlog', 'user_token=' . $this-&gt;session-&gt;data['user_token'] . $url, true); $data['filter_action'] = $this-&gt;url-&gt;link('marketplace/modification', 'user_token=' . $this-&gt;session-&gt;data['user_token'], true); $data['reset_url'] = $this-&gt;url-&gt;link('marketplace/modification', 'user_token=' . $this-&gt;session-&gt;data['user_token'], true); $data['tab_files'] = $this-&gt;language-&gt;get('tab_files'); $data['tab_error'] = $this-&gt;language-&gt;get('tab_error');]]&gt;&lt;/add&gt; &lt;/operation&gt; &lt;operation&gt; &lt;search index=&quot;0&quot;&gt;&lt;![CDATA[$data['sort_name'] =]]&gt;&lt;/search&gt; &lt;add position=&quot;before&quot;&gt;&lt;![CDATA[ if (isset($this-&gt;request-&gt;get['filter_name'])) { $url .= '&amp;filter_name=' . urlencode(html_entity_decode($this-&gt;request-&gt;get['filter_name'], ENT_QUOTES, 'UTF-8')); } if (isset($this-&gt;request-&gt;get['filter_author'])) { $url .= '&amp;filter_author=' . urlencode(html_entity_decode($this-&gt;request-&gt;get['filter_author'], ENT_QUOTES, 'UTF-8')); } if (isset($this-&gt;request-&gt;get['filter_xml'])) { $url .= '&amp;filter_xml=' . urlencode(html_entity_decode($this-&gt;request-&gt;get['filter_xml'], ENT_QUOTES, 'UTF-8')); } $data['sort_date_modified'] = $this-&gt;url-&gt;link('marketplace/modification', 'user_token=' . $this-&gt;session-&gt;data['user_token'] . '&amp;sort=date_modified' . $url, true);]]&gt;&lt;/add&gt; &lt;/operation&gt; &lt;operation&gt; &lt;search index=&quot;0&quot;&gt;&lt;![CDATA[$filter_data = array(]]&gt;&lt;/search&gt; &lt;add position=&quot;after&quot;&gt;&lt;![CDATA[ 'filter_name' =&gt; $filter_name, 'filter_author' =&gt; $filter_author, 'filter_xml' =&gt; $filter_xml,]]&gt;&lt;/add&gt; &lt;/operation&gt; &lt;operation&gt; &lt;search index=&quot;0&quot;&gt;&lt;![CDATA[$data['modifications'][] = array(]]&gt;&lt;/search&gt; &lt;add position=&quot;after&quot;&gt;&lt;![CDATA[ 'date_modified' =&gt; $result['date_modified'] &amp;&amp; $result['date_modified'] != '0000-00-00 00:00:00' ? date(date('Ymd') == date('Ymd', strtotime($result['date_modified'])) ? 'G:i' : $this-&gt;language-&gt;get('date_format_short'), strtotime($result['date_modified'])) : null, 'edit' =&gt; $this-&gt;url-&gt;link('marketplace/modification/edit', 'user_token=' . $this-&gt;session-&gt;data['user_token'] . '&amp;modification_id=' . $result['modification_id'] . $url, true), 'download' =&gt; $this-&gt;url-&gt;link('marketplace/modification/download', 'user_token=' . $this-&gt;session-&gt;data['user_token'] . '&amp;modification_id=' . $result['modification_id'] , true),]]&gt;&lt;/add&gt; &lt;/operation&gt; &lt;operation&gt; &lt;search index=&quot;0&quot;&gt;&lt;![CDATA[$pagination = new Pagination();]]&gt;&lt;/search&gt; &lt;add position=&quot;before&quot;&gt;&lt;![CDATA[ if (isset($this-&gt;request-&gt;get['filter_name'])) { $url .= '&amp;filter_name=' . urlencode(html_entity_decode($this-&gt;request-&gt;get['filter_name'], ENT_QUOTES, 'UTF-8')); } if (isset($this-&gt;request-&gt;get['filter_author'])) { $url .= '&amp;filter_author=' . urlencode(html_entity_decode($this-&gt;request-&gt;get['filter_author'], ENT_QUOTES, 'UTF-8')); } if (isset($this-&gt;request-&gt;get['filter_xml'])) { $url .= '&amp;filter_xml=' . urlencode(html_entity_decode($this-&gt;request-&gt;get['filter_xml'], ENT_QUOTES, 'UTF-8')); }]]&gt;&lt;/add&gt; &lt;/operation&gt; &lt;operation&gt; &lt;search index=&quot;0&quot;&gt;&lt;![CDATA[$data['clear_log'] =]]&gt;&lt;/search&gt; &lt;add position=&quot;before&quot;&gt;&lt;![CDATA[ $data['filter_name'] = $filter_name; $data['filter_author'] = $filter_author; $data['filter_xml'] = $filter_xml; $data['modified_files'] = array(); $modified_files = self::modifiedFiles(DIR_MODIFICATION); $modification_files = $this-&gt;getModificationXmlFiles(); foreach($modified_files as $modified_file) { if(isset($modification_files[$modified_file])){ $modifications = $modification_files[$modified_file]; } else { $modifications = array(); } $data['modified_files'][] = array( 'file' =&gt; $modified_file, 'modifications' =&gt; $modifications ); } // Error log $error_file = DIR_LOGS . 'ocmod_error.log'; if (file_exists($error_file)) { $data['error_log'] = htmlentities(file_get_contents($error_file, FILE_USE_INCLUDE_PATH, null)); } else { $data['error_log'] = ''; } ]]&gt;&lt;/add&gt; &lt;/operation&gt; &lt;operation&gt; &lt;search index=&quot;0&quot;&gt;&lt;![CDATA[$this-&gt;load-&gt;view('marketplace/modification']]&gt;&lt;/search&gt; &lt;add position=&quot;replace&quot;&gt;&lt;![CDATA[$this-&gt;load-&gt;view('extension/module/modification_manager/list']]&gt;&lt;/add&gt; &lt;/operation&gt; &lt;operation&gt; &lt;search index=&quot;0&quot;&gt;&lt;![CDATA[$this-&gt;response-&gt;redirect($this-&gt;url-&gt;link(!empty($data['redirect']) ? $data['redirect'] : 'marketplace/modification', 'user_token=' . $this-&gt;session-&gt;data['user_token'] . $url, true));]]&gt;&lt;/search&gt; &lt;ignoreif position=&quot;replace&quot;&gt;&lt;![CDATA[if (!empty($data['redirect'])) {]]&gt;&lt;/ignoreif&gt; &lt;add position=&quot;replace&quot;&gt;&lt;![CDATA[$url = $this-&gt;getListUrlParams(); if (!empty($data['redirect'])) { $redirect = $data['redirect']; } elseif (!empty($this-&gt;request-&gt;get['redirect'])) { $redirect = $this-&gt;request-&gt;get['redirect']; } else { $redirect = 'marketplace/modification'; } $this-&gt;response-&gt;redirect($this-&gt;url-&gt;link($redirect, 'user_token=' . $this-&gt;session-&gt;data['user_token'] . $url, true));]]&gt;&lt;/add&gt; &lt;/operation&gt; &lt;operation&gt; &lt;search index=&quot;0&quot;&gt;&lt;![CDATA[if ($this-&gt;validate()) {]]&gt;&lt;/search&gt; &lt;add position=&quot;after&quot;&gt;&lt;![CDATA[ $error_log = array(); // Clear vqmod cache $vqmod_path = substr(DIR_SYSTEM, 0, -7) . 'vqmod/'; if (file_exists($vqmod_path)) { $vqmod_cache = glob($vqmod_path.'vqcache/vq*'); if ($vqmod_cache) { foreach ($vqmod_cache as $file) { if (file_exists($file)) { @unlink($file); } } } if (file_exists($vqmod_path.'mods.cache')) { @unlink($vqmod_path.'mods.cache'); } if (file_exists($vqmod_path.'checked.cache')) { @unlink($vqmod_path.'checked.cache'); } } ]]&gt;&lt;/add&gt; &lt;/operation&gt; &lt;operation&gt; &lt;search index=&quot;0&quot;&gt;&lt;![CDATA[$log[] = 'MOD:]]&gt;&lt;/search&gt; &lt;add position=&quot;after&quot;&gt;&lt;![CDATA[ $error_log_mod = 'MOD: ' . $dom-&gt;getElementsByTagName('name')-&gt;item(0)-&gt;textContent; ]]&gt;&lt;/add&gt; &lt;/operation&gt; &lt;operation&gt; &lt;search index=&quot;0&quot;&gt;&lt;![CDATA[$operations = $file-&gt;getElementsByTagName('operation');]]&gt;&lt;/search&gt; &lt;add position=&quot;after&quot;&gt;&lt;![CDATA[ $file_error = $file-&gt;getAttribute('error');]]&gt;&lt;/add&gt; &lt;/operation&gt; &lt;operation&gt; &lt;search index=&quot;0&quot;&gt;&lt;![CDATA[$files = glob($path, GLOB_BRACE);]]&gt;&lt;/search&gt; &lt;add position=&quot;after&quot;&gt;&lt;![CDATA[ if (!$files) { if ($file_error != 'skip') { $error_log[] = '----------------------------------------------------------------'; $error_log[] = $error_log_mod; $error_log[] = 'MISSING FILE!'; $error_log[] = $path; } }]]&gt;&lt;/add&gt; &lt;/operation&gt; &lt;operation&gt; &lt;search index=&quot;0&quot;&gt;&lt;![CDATA[if (!$status) {]]&gt;&lt;/search&gt; &lt;add position=&quot;after&quot;&gt;&lt;![CDATA[ if ($error != 'skip') { $error_log[] = &quot;\n&quot;; $error_log[] = $error_log_mod; $error_log[] = 'NOT FOUND!'; $error_log[] = 'CODE: ' . $search; $error_log[] = 'FILE: ' . $key; }]]&gt;&lt;/add&gt; &lt;/operation&gt; &lt;operation&gt; &lt;search index=&quot;0&quot;&gt;&lt;![CDATA[$ocmod-&gt;write(implode(&quot;\n&quot;, $log));]]&gt;&lt;/search&gt; &lt;add position=&quot;after&quot;&gt;&lt;![CDATA[ if ($error_log) { $ocmod = new Log('ocmod_error.log'); $ocmod-&gt;write(implode(&quot;\n&quot;, $error_log)); }]]&gt;&lt;/add&gt; &lt;/operation&gt; &lt;operation&gt; &lt;search index=&quot;0&quot;&gt;&lt;![CDATA[protected function validate(]]&gt;&lt;/search&gt; &lt;add position=&quot;before&quot;&gt;&lt;![CDATA[ public function add() { $this-&gt;load-&gt;language('marketplace/modification'); $this-&gt;load-&gt;model('extension/module/modification_manager'); if (($this-&gt;request-&gt;server['REQUEST_METHOD'] == 'POST') &amp;&amp; $this-&gt;validateForm()) { $xml = html_entity_decode($this-&gt;request-&gt;post['xml'], ENT_QUOTES, 'UTF-8'); $dom = new DOMDocument('1.0', 'UTF-8'); $dom-&gt;preserveWhiteSpace = false; $dom-&gt;loadXml($xml); $data = array( 'version' =&gt; '', 'author' =&gt; '', 'link' =&gt; '', 'status' =&gt; 1 ); $data['xml'] = $xml; $data['name'] = $dom-&gt;getElementsByTagName('name')-&gt;item(0)-&gt;textContent; $data['code'] = $dom-&gt;getElementsByTagName('code')-&gt;item(0)-&gt;textContent; if ($dom-&gt;getElementsByTagName('version')-&gt;length) { $data['version'] = $dom-&gt;getElementsByTagName('version')-&gt;item(0)-&gt;textContent; } if ($dom-&gt;getElementsByTagName('author')-&gt;length) { $data['author'] = $dom-&gt;getElementsByTagName('author')-&gt;item(0)-&gt;textContent; } $this-&gt;model_extension_module_modification_manager-&gt;addModification($data); $modification_id = $this-&gt;db-&gt;getLastId(); $this-&gt;session-&gt;data['success'] = $this-&gt;language-&gt;get('text_success'); $this-&gt;response-&gt;redirect($this-&gt;url-&gt;link('marketplace/modification/edit', 'user_token=' . $this-&gt;session-&gt;data['user_token'] . $this-&gt;getListUrlParams(array('modification_id' =&gt; $modification_id)), true)); } $this-&gt;getForm(); } public function edit() { $this-&gt;load-&gt;language('marketplace/modification'); $this-&gt;load-&gt;model('extension/module/modification_manager'); if (($this-&gt;request-&gt;server['REQUEST_METHOD'] == 'POST') &amp;&amp; !empty($this-&gt;request-&gt;get['modification_id']) &amp;&amp; $this-&gt;validateForm()) { $modification_id = $this-&gt;request-&gt;get['modification_id']; $xml = html_entity_decode($this-&gt;request-&gt;post['xml'], ENT_QUOTES, 'UTF-8'); $dom = new DOMDocument('1.0', 'UTF-8'); $dom-&gt;preserveWhiteSpace = false; $dom-&gt;loadXml($xml); $data = array(); $data['xml'] = $xml; $data['name'] = $dom-&gt;getElementsByTagName('name')-&gt;item(0)-&gt;textContent; $data['code'] = $dom-&gt;getElementsByTagName('code')-&gt;item(0)-&gt;textContent; if ($dom-&gt;getElementsByTagName('version')-&gt;length) { $data['version'] = $dom-&gt;getElementsByTagName('version')-&gt;item(0)-&gt;textContent; } else { $data['version'] = ''; } if ($dom-&gt;getElementsByTagName('author')-&gt;length) { $data['author'] = $dom-&gt;getElementsByTagName('author')-&gt;item(0)-&gt;textContent; } else { $data['author'] = ''; } if ($dom-&gt;getElementsByTagName('link')-&gt;length) { $data['link'] = $dom-&gt;getElementsByTagName('link')-&gt;item(0)-&gt;textContent; } else { $data['link'] = ''; } $this-&gt;model_extension_module_modification_manager-&gt;editModification($modification_id, $data); $url = $this-&gt;getListUrlParams(array('modification_id' =&gt; $modification_id)); if (isset($this-&gt;request-&gt;get['refresh'])) { $this-&gt;response-&gt;redirect($this-&gt;url-&gt;link('marketplace/modification/refresh', 'user_token=' . $this-&gt;session-&gt;data['user_token'] . $url, true)); } if ($this-&gt;db-&gt;countAffected()) { $this-&gt;session-&gt;data['success'] = $this-&gt;language-&gt;get('text_success'); $this-&gt;response-&gt;redirect($this-&gt;url-&gt;link('marketplace/modification/edit', 'user_token=' . $this-&gt;session-&gt;data['user_token'] . $url, true)); } } $this-&gt;getForm(); } public function download() { if (!$this-&gt;user-&gt;hasPermission('modify', 'marketplace/modification')) { $this-&gt;response-&gt;redirect($this-&gt;url-&gt;link('marketplace/modification', 'user_token=' . $this-&gt;session-&gt;data['user_token'], true)); } if (isset($this-&gt;request-&gt;get['modification_id'])) { $modification_id = $this-&gt;request-&gt;get['modification_id']; } else { $modification_id = 0; } $this-&gt;load-&gt;model('extension/module/modification_manager'); $modification = $this-&gt;model_extension_module_modification_manager-&gt;getModification($modification_id); if ($modification) { $filename = $modification['code'] . '.ocmod.xml'; $file = $modification['xml']; ob_start(); echo $file; $download = ob_get_contents(); $size = ob_get_length(); ob_end_clean(); if (!headers_sent()) { if (!empty($modification['xml'])) { header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename=&quot;' . $filename . '&quot;'); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: ' . $size); if (ob_get_level()) { ob_end_clean(); } echo $download; exit(); } else { exit($this-&gt;language-&gt;get('error_file')); } } else { exit($this-&gt;language-&gt;get('error_headers')); } } else { $this-&gt;response-&gt;redirect($this-&gt;url-&gt;link('marketplace/modification', 'user_token=' . $this-&gt;session-&gt;data['user_token'] . $url, true)); } } public function getForm() { $data['heading_title'] = $this-&gt;language-&gt;get('heading_title'); $data['text_enabled'] = $this-&gt;language-&gt;get('text_enabled'); $data['text_disabled'] = $this-&gt;language-&gt;get('text_disabled'); $data['button_save'] = $this-&gt;language-&gt;get('button_save'); $data['button_download'] = $this-&gt;language-&gt;get('button_download'); $data['button_refresh'] = $this-&gt;language-&gt;get('button_refresh'); $data['button_cancel'] = $this-&gt;language-&gt;get('button_cancel'); if (isset($this-&gt;error['warning'])) { $data['error_warning'] = $this-&gt;error['warning']; } elseif (!empty($this-&gt;error)) { $data['error_warning'] = $this-&gt;language-&gt;get('error_warning'); } else { $data['error_warning'] = ''; } if (isset($this-&gt;session-&gt;data['success'])) { $data['success'] = $this-&gt;session-&gt;data['success']; unset($this-&gt;session-&gt;data['success']); } else { $data['success'] = false; } if (isset($this-&gt;error['xml'])) { $data['error_xml'] = $this-&gt;error['xml']; } $data['breadcrumbs'] = array(); $data['breadcrumbs'][] = array( 'text' =&gt; $this-&gt;language-&gt;get('text_home'), 'href' =&gt; $this-&gt;url-&gt;link('common/dashboard', 'user_token=' . $this-&gt;session-&gt;data['user_token'], true) ); $data['breadcrumbs'][] = array( 'text' =&gt; $this-&gt;language-&gt;get('heading_title'), 'href' =&gt; $this-&gt;url-&gt;link('marketplace/modification', 'user_token=' . $this-&gt;session-&gt;data['user_token'] . $this-&gt;getListUrlParams(), true) ); if (isset($this-&gt;request-&gt;get['modification_id'])) { $this-&gt;load-&gt;model('extension/module/modification_manager'); $modification_info = $this-&gt;model_extension_module_modification_manager-&gt;getModification($this-&gt;request-&gt;get['modification_id']); if (!$modification_info) exit; $data['text_form'] = sprintf($this-&gt;language-&gt;get('text_edit'), $modification_info['name']); $data['action'] = $this-&gt;url-&gt;link('marketplace/modification/edit', '&amp;modification_id=' . $modification_info['modification_id'] . '&amp;user_token=' . $this-&gt;session-&gt;data['user_token'], true); $data['refresh'] = $this-&gt;url-&gt;link('marketplace/modification/edit', '&amp;modification_id=' . $modification_info['modification_id'] . '&amp;refresh=1&amp;user_token=' . $this-&gt;session-&gt;data['user_token'], true); $this-&gt;document-&gt;setTitle($modification_info['name'] . ' </code></pre>
[ { "answer_id": 74379917, "author": "Coder1979", "author_id": 11089218, "author_profile": "https://Stackoverflow.com/users/11089218", "pm_score": 0, "selected": false, "text": "<section style=\"position: static; background-color: black; margin: 0; padding: 0; width: 100%; background-image: url(\"background.jpg\"); background-repeat: no-repeat; background-size: 100%; display: flex;\">\n\n<img style=\"flex: 50%; margin: 1%;\" src=\"overlay-image.jpg\" alt=\"Image overlaid on background image.\">\n\n<div style=\"flex: 50%; text-align: left; margin: 1%;\">\n<p style=\"color:white;\">Text overlaid on background image.</p>\n</div>\n<section>\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20461598/" ]
74,379,268
<p>I was reading the following on .NET 7 and <a href="https://learn.microsoft.com/en-us/dotnet/standard/generics/math" rel="nofollow noreferrer"><code>INumber</code></a>:</p> <p>It gave an example of adding two INumber generic values, which I tried to replicate in F# to no success.</p> <pre><code>let add&lt;'T when 'T :&gt; INumber&lt;'T&gt;&gt; (left : 'T) (right: 'T) : 'T = left + right </code></pre> <p>This gives &quot;The declared type parameter 'T cannot be resolved at run time. When I try a different way, to be super clear:</p> <pre><code>let add&lt;'T when 'T :&gt; INumber&lt;'T&gt;&gt; (left : 'T) (right: 'T) : 'T = INumber&lt;'T&gt;.``+`` left right </code></pre> <p>&quot;INumber&lt;'T'&gt;.<code>+</code> is not defined.&quot;</p> <p>Please can someone help me understand how to make this work, and provide the correct format for something like this?</p>
[ { "answer_id": 74379917, "author": "Coder1979", "author_id": 11089218, "author_profile": "https://Stackoverflow.com/users/11089218", "pm_score": 0, "selected": false, "text": "<section style=\"position: static; background-color: black; margin: 0; padding: 0; width: 100%; background-image: url(\"background.jpg\"); background-repeat: no-repeat; background-size: 100%; display: flex;\">\n\n<img style=\"flex: 50%; margin: 1%;\" src=\"overlay-image.jpg\" alt=\"Image overlaid on background image.\">\n\n<div style=\"flex: 50%; text-align: left; margin: 1%;\">\n<p style=\"color:white;\">Text overlaid on background image.</p>\n</div>\n<section>\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8541861/" ]
74,379,285
<p>I am new to Spring boot and sorry in case it's very basic but I am posting as I have tried other ways and checked similar threads as well.</p> <p>If I use below code it's returning correct response</p> <pre><code>ResponseEntity&lt;String&gt; responseEntityString = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class); </code></pre> <p>Output</p> <pre><code>[{&quot;Id&quot;:&quot;123aa&quot;,&quot;TenId&quot;:5198,&quot;Name&quot;:&quot;test&quot;,&quot;Description&quot;:&quot;test11&quot;,&quot;Tags&quot;:[]}] </code></pre> <p>Now I have created workspace class like below (getter/setter/arg constructor and no-arg construcntor is also there)</p> <pre><code>public class Workspace { private String Id; private String TenId; private String Name; private String Description; private List&lt;String&gt; Tags; } </code></pre> <p>Now I execute the below code -</p> <pre><code>ResponseEntity&lt;List&lt;Workspace&gt;&gt; response = restTemplate.exchange( url, HttpMethod.GET, requestEntity, new ParameterizedTypeReference&lt;List&lt;Workspace&gt;&gt;(){}); List&lt;Workspace&gt; employees = response.getBody(); employees.stream().forEach(entry -&gt; System.out.println(entry.getId() + &quot;: &quot; + entry.getName())); </code></pre> <p>It's returning</p> <pre><code>null: null </code></pre> <p>Below is returning true</p> <pre><code>System.out.println(&quot;Value &quot;+ response.hasBody()); </code></pre> <p>Below is returning - New Values [com.pratik.model.Workspace@3cbf1ba4]</p> <pre><code>New Values [com.pratik.model.Workspace@3cbf1ba4] </code></pre> <p>So please advise what needs to change to get the values</p> <p>================================================================ Initialized resttemplate bean like below</p> <pre><code> public class app1 { static RestTemplate restTemplate = new RestTemplate(); static String url = url; public static void main(String[] args) { SpringApplication.run(app1.class, args); getCallSample(); } </code></pre> <p>===============================================================</p> <p>Update on the latest code</p> <pre><code>ResponseEntity&lt;Workspace[]&gt; responseNew = restTemplate .exchange( url, HttpMethod.GET, requestEntity, Workspace[].class); Workspace [] employees1 = responseNew.getBody(); List&lt;Workspace&gt; list = Arrays.asList(employees1); list.stream().forEach(entry -&gt; System.out.println(entry.getId() + &quot;: &quot; + entry.getName())); </code></pre> <p>Still the response is</p> <pre><code>null: null </code></pre> <p>=============================================================== Another update When tried with String.class it's returning</p> <pre><code>[{&quot;Id&quot;:&quot;abc&quot;,&quot;TenId&quot;:11,&quot;Name&quot;:&quot;tt1 Workspace&quot;,&quot;Description&quot;:&quot;testtenant Workspace (System Generated)&quot;,&quot;Tags&quot;:[]}] </code></pre> <p>But when using workspace class - it's returning -</p> <pre><code>[Id=null, TenId=null, Name=null, Description=null, Tags=null, getId()=null, getTenId()=null, getName()=null, getDescription()=null, getTags()=null] </code></pre> <p>So is using Workspace[].class would be the right method ?</p>
[ { "answer_id": 74382490, "author": "Luiggi Mendoza", "author_id": 1065197, "author_profile": "https://Stackoverflow.com/users/1065197", "pm_score": 1, "selected": false, "text": "static RestTemplate restTemplate = new RestTemplate();" }, { "answer_id": 74385264, "author": "Pranav", "author_id": 18569862, "author_profile": "https://Stackoverflow.com/users/18569862", "pm_score": 0, "selected": false, "text": "public class Root{\n @JsonProperty(\"Id\") \n public String id;\n @JsonProperty(\"TenantId\") \n public int tenantId;\n @JsonProperty(\"Name\") \n public String name;\n @JsonProperty(\"Description\") \n public String description;\n @JsonProperty(\"Tags\") \n public ArrayList<Object> tags;\n}\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18569862/" ]
74,379,302
<p>I have an array of the vowels in the alphabet and the user should enter a letter. This letter has to be checked if its in the array of vowels or not If it is found in the array of vowels then print letter is a vowel else print letter is a constant.</p> <h1><strong>My problem is that</strong></h1> <p>when I enter a letter it tests this letter 5 times (the size of the array) until it finds it and prints letter is a vowel but it also prints 4 times letter is a constant because it goes through the array letter by letter. Check the code:</p> <pre><code> public static void main(String[] args){ Scanner g = new Scanner(System.in); char[] Vowels = {'A','I','O','U','E'}; System.out.println(&quot;Enter a letter: &quot;); char L = g.next().charAt(0); for(int i = 0;i&lt;Vowels.length;i++){ if(L==Vowels[i]){ System.out.println(L+&quot; is a vowel&quot;); break; } else System.out.println(L+&quot; is a constant&quot;); } } } </code></pre>
[ { "answer_id": 74379402, "author": "Dean", "author_id": 20461571, "author_profile": "https://Stackoverflow.com/users/20461571", "pm_score": 0, "selected": false, "text": "public static void main(String[] args){\n Scanner g = new Scanner(System.in);\n char[] Vowels = {'A','I','O','U','E'};\n System.out.println(\"Enter a letter: \");\n char L = g.next().charAt(0);\n boolean isVowel = false;\n for(int i = 0;i<Vowels.length;i++){\n if(L==Vowels[i]){\n System.out.println(L+\" is a vowel\");\n isVowel = true;\n break;\n }\n\n }\n if (!isVowel) {\n System.out.println(L+\" is a constant\");\n }\n }\n" }, { "answer_id": 74379432, "author": "CryptoFool", "author_id": 7631480, "author_profile": "https://Stackoverflow.com/users/7631480", "pm_score": 1, "selected": false, "text": "public static void main(String[] args){\n System.out.println(\"Enter a letter: \");\n Scanner g = new Scanner(System.in);\n char[] vowels = {'A','I','O','U','E'};\n char l = g.next().toUpperCase(Locale.ROOT).charAt(0);\n int i;\n for (i = 0;i<vowels.length;i++) {\n if (l == vowels[i]) {\n System.out.println(l + \" is a vowel\");\n break;\n }\n }\n if (i == vowels.length)\n System.out.println(l + \" is a constant\");\n}\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20079157/" ]
74,379,318
<p>I have the following code in Flutter. The variable checkValue is set to false and the variable newValue is optional, so I have to check if it is null or not. Then, I change checkValue to the value of newValue inside the setState() method. My problem is that it jumps the setState() method and does not change the value.</p> <p>Can anyone tell me why that happens?</p> <pre><code>CheckboxListTile( title: const Text('Preferences'), value: checkValue, onChanged: (newValue) { if (newValue != null) { setState() { checkValue = newValue; } } }, controlAffinity: ListTileControlAffinity.leading, ), </code></pre> <p>I have tried to set the value with a condition like that:</p> <pre><code>CheckboxListTile( title: const Text('Preferences'), value: checkValue, onChanged: (newValue) { if (newValue != null) { setState() { checkValue = newValue ? true : false; } } }, controlAffinity: ListTileControlAffinity.leading, ), </code></pre> <p>It was normal it doesn´t work xD</p>
[ { "answer_id": 74379337, "author": "Yeasin Sheikh", "author_id": 10157127, "author_profile": "https://Stackoverflow.com/users/10157127", "pm_score": 2, "selected": false, "text": "setState" }, { "answer_id": 74379682, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 0, "selected": false, "text": "SetState" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20461528/" ]
74,379,348
<pre><code> return Scaffold( body: Center( child: Row( crossAxisAlignment: CrossAxisAlignment.center, children: [ Container( color: Colors.red, width: MediaQuery.of(context).size.width, height: MediaQuery.of(context).size.height, child: Center( child: SelectGroupCard(context, titles: titles, ids: ids, onTap: (title, id) { setState(() { cardGroupResult = title + &quot; &quot; + id; }); }), ), ), ], ), </code></pre> <p><a href="https://i.stack.imgur.com/by1Fz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/by1Fz.png" alt="enter image description here" /></a></p> <p>There are several cards as seen in the picture. I want to get these right out. I even want to be able to show these cards in the middle of the page, in 3 columns, 4 rows.</p>
[ { "answer_id": 74379337, "author": "Yeasin Sheikh", "author_id": 10157127, "author_profile": "https://Stackoverflow.com/users/10157127", "pm_score": 2, "selected": false, "text": "setState" }, { "answer_id": 74379682, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 0, "selected": false, "text": "SetState" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17906689/" ]
74,379,355
<p>I have the following SVG:</p> <pre><code>&lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot; viewBox=&quot;0 0 40 40&quot;&gt;&lt;g id=&quot;Page-1&quot; fill=&quot;none&quot; fill-rule=&quot;evenodd&quot;&gt;&lt;g id=&quot;Artboard-5&quot; fill=&quot;#000000&quot;&gt;&lt;path id=&quot;Combined-Shape&quot; d=&quot;M0 38.59l2.83-2.83 1.41 1.41L1.41 40H0v-1.41zM0 1.4l2.83 2.83 1.41-1.41L1.41 0H0v1.41zM38.59 40l-2.83-2.83 1.41-1.41L40 38.59V40h-1.41zM40 1.41l-2.83 2.83-1.41-1.41L38.59 0H40v1.41zM20 18.6l2.83-2.83 1.41 1.41L21.41 20l2.83 2.83-1.41 1.41L20 21.41l-2.83 2.83-1.41-1.41L18.59 20l-2.83-2.83 1.41-1.41L20 18.59z&quot;/&gt;&lt;/g&gt;&lt;/g&gt;&lt;/svg&gt; </code></pre> <p>Which is like this:</p> <p><a href="https://i.stack.imgur.com/zS1nW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zS1nW.png" alt="enter image description here" /></a></p> <p>And the pattern should look like this</p> <p><a href="https://i.stack.imgur.com/ENAkP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ENAkP.png" alt="enter image description here" /></a></p> <p>However, in Highcharts it looks like this: (note that it seems that 2/3 of the left side of the svg are cut off)</p> <p><a href="https://i.stack.imgur.com/wrMsa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wrMsa.png" alt="enter image description here" /></a></p> <p>Why is this? I've tried different sizes for width and height and couldn't make it work.</p> <pre><code>const linePattern = &quot;M0 38.59l2.83-2.83 1.41 1.41L1.41 40H0v-1.41zM0 1.4l2.83 2.83 1.41-1.41L1.41 0H0v1.41zM38.59 40l-2.83-2.83 1.41-1.41L40 38.59V40h-1.41zM40 1.41l-2.83 2.83-1.41-1.41L38.59 0H40v1.41zM20 18.6l2.83-2.83 1.41 1.41L21.41 20l2.83 2.83-1.41 1.41L20 21.41l-2.83 2.83-1.41-1.41L18.59 20l-2.83-2.83 1.41-1.41L20 18.59z&quot;; const patternOptions :PatternOptionsObject = { aspectRatio: 0, backgroundColor: &quot;red&quot;, color: '#907000', image: &quot;&quot;, opacity: 0.5, // path: { // d: linePattern, // fill: '#102045' // }, patternTransform: &quot;&quot;, path: { d: linePattern, stroke: &quot;white&quot;, fill: &quot;evenodd&quot; }, width: 30, height: 30 } const patternObject : PatternObject = { pattern: patternOptions }; if (options.series.length) { options.series[0].data[0].color = patternObject; // modifying the first row for testing purposes } </code></pre>
[ { "answer_id": 74379919, "author": "JorgeeFG", "author_id": 1335189, "author_profile": "https://Stackoverflow.com/users/1335189", "pm_score": 0, "selected": false, "text": "20x20" }, { "answer_id": 74386921, "author": "Sebastian Hajdus", "author_id": 12171673, "author_profile": "https://Stackoverflow.com/users/12171673", "pm_score": 1, "selected": false, "text": "color: {\n pattern: {\n aspectRatio: 0.9,\n path: {\n //d: linePattern,\n //d: 'M 3 3 L 8 3 L 8 8 Z',\n d: 'M 10,30 A 20,20 0,0,1 50,30 A 20,20 0,0,1 90,30 Q 90,60 50,90 Q 10,60 10,30 z',\n strokeWidth: 3,\n stroke: 'red'\n },\n color: '#f0f0f0',\n width: 100,\n height: 100\n }\n},\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1335189/" ]
74,379,357
<p>I'm building a blog app and in this instance I want to create a new post. I created a controller with @GetMapping and @PostMapping with value &quot;/posts/new&quot;. I used <code>th:action = &quot;@{'/posts/new'}&quot;</code> <code>(LINE 14)</code> in thymeleaf but when I start the web app, and access the localhost:8080/posts/new it gives the 404 error that the url is not found, but it is there...I double checked spelling, code...pretty much everything but just can't seem to figure out what mistake did I make. Here is the code:</p> <p>post_new.html</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot; xmlns:th=&quot;http://www.thymeleaf.org&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;utf-8&quot;&gt; &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt; &lt;title&gt;Blog :: New Post&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div class=&quot;container&quot;&gt; &lt;a th:href=&quot;@{/}&quot;&gt;Home&lt;/a&gt; &lt;form action=&quot;#&quot; th:action=&quot;@{'/posts/new'}&quot; th:object=&quot;${post}&quot;&gt; &lt;input type=&quot;hidden&quot; th:field=&quot;*{account}&quot; /&gt; &lt;input type=&quot;hidden&quot; th:field=&quot;*{createdAt}&quot; /&gt; &lt;h2&gt;Write new post&lt;/h2&gt; &lt;div&gt; &lt;label for=&quot;new-post-title&quot;&gt;Title&lt;/label&gt; &lt;input id=&quot;new-post-title&quot; type=&quot;text&quot; th:field=&quot;*{title}&quot; placeholder=&quot;Title&quot;/&gt; &lt;/div&gt; &lt;div&gt; &lt;label for=&quot;new-post-body&quot;&gt;Body&lt;/label&gt; &lt;textarea id=&quot;new-post-body&quot; th:field=&quot;*{body}&quot;&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;button type=&quot;submit&quot;&gt;Publish post&lt;/button&gt; &lt;/form&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>PostController.java</p> <pre><code>package com.hellion.writeup.controller; import com.hellion.writeup.models.Account; import com.hellion.writeup.models.Post; import com.hellion.writeup.service.AccountService; import com.hellion.writeup.service.PostService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import java.util.Optional; @Controller public class PostController { @Autowired private PostService postService; @Autowired private AccountService accountService; @GetMapping(&quot;/posts/{id}&quot;) public String getPost(@PathVariable Long id, Model model) { Post post = postService.getPost(id, model); if (post != null) { model.addAttribute(&quot;post&quot;, post); return &quot;post&quot;; } else { return &quot;404&quot;; } } @GetMapping(&quot;/posts/new&quot;) public String createNewPost(Model model){ return postService.createNewPost(model); } @PostMapping(&quot;/posts/new&quot;) public String saveNewPost(@ModelAttribute Post post){ postService.save(post); return &quot;redirect:/posts/&quot; + post.getId(); } } </code></pre> <p>PostService.java</p> <pre><code>package com.hellion.writeup.service; import com.hellion.writeup.models.Account; import com.hellion.writeup.models.Post; import com.hellion.writeup.repository.PostRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.ui.Model; import java.time.LocalDateTime; import java.util.List; import java.util.Optional; @Service public class PostService { @Autowired private PostRepository postRepository; @Autowired private AccountService accountService;; public Optional&lt;Post&gt; getById(Long id) { return postRepository.findById(id); } public List&lt;Post&gt; getAll() { return postRepository.findAll(); } public Post save(Post post) { if (post.getId() == null) { post.setCreatedAt(LocalDateTime.now()); } return postRepository.save(post); } public Post getPost(Long id, Model model) { Optional&lt;Post&gt; optionalPost = getById(id); if (optionalPost.isPresent()) { Post post = optionalPost.get(); return post; } return null; } public String createNewPost(Model model){ Optional&lt;Account&gt; optionalAccount = accountService.findByEmail(&quot;user.user@domain.com&quot;); if(optionalAccount.isPresent()){ Post post = new Post(); post.setAccount(optionalAccount.get()); model.addAttribute(&quot;post&quot;, post); return &quot;post_new&quot;; }else{ return &quot;404&quot;; } } } </code></pre> <p>post.html</p> <pre><code>&lt;!DOCTYPE HTML&gt; &lt;html land= &quot;en&quot; xmlns:th=&quot;http://www.thymeleaf.org&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;utf-8&quot;&gt; &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE-edge&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt; &lt;link th:href=&quot;@{/styles/style.css}&quot; rel=&quot;stylesheet&quot; /&gt; &lt;title&gt;Writeup :: Post&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div class =&quot;container&quot;&gt; &lt;a th:href=&quot;@{'/'}&quot;&gt;Home&lt;/a&gt; &lt;div class=&quot;post&quot;&gt; &lt;h2 th:text=&quot;${post.title}&quot;&gt;Title&lt;/h2&gt; &lt;h5 th:text=&quot;'Written by: ' + ${post.account.getFirstName()}&quot;&gt;Account First Name&lt;/h5&gt; &lt;h5 th:text=&quot;'Created on: ' + ${post.createdAt}&quot;&gt;Created At&lt;/h5&gt; &lt;p th:text=&quot;${post.body}&quot;&gt;Body text&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "answer_id": 74379919, "author": "JorgeeFG", "author_id": 1335189, "author_profile": "https://Stackoverflow.com/users/1335189", "pm_score": 0, "selected": false, "text": "20x20" }, { "answer_id": 74386921, "author": "Sebastian Hajdus", "author_id": 12171673, "author_profile": "https://Stackoverflow.com/users/12171673", "pm_score": 1, "selected": false, "text": "color: {\n pattern: {\n aspectRatio: 0.9,\n path: {\n //d: linePattern,\n //d: 'M 3 3 L 8 3 L 8 8 Z',\n d: 'M 10,30 A 20,20 0,0,1 50,30 A 20,20 0,0,1 90,30 Q 90,60 50,90 Q 10,60 10,30 z',\n strokeWidth: 3,\n stroke: 'red'\n },\n color: '#f0f0f0',\n width: 100,\n height: 100\n }\n},\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13372981/" ]
74,379,372
<pre><code>### Import specification function required - for some reason if I do just &quot;import random&quot; from random import randint moves = [&quot;rock&quot;, &quot;paper&quot;, &quot;scissors&quot;] ### While pretty much is used so we can play over and over. while True: computer = moves[randint(0,2)] player = input(&quot;Choose rock, paper or scissors, or 'end' to finish the game: &quot;).lower() ### Break the loop if player wants to end if player == &quot;end&quot;: print(&quot;The game is over&quot;) break ### All possible iterations. elif player == computer: print(&quot;It's a tie!&quot;) elif player == &quot;rock&quot;: if computer == &quot;paper&quot;: print(&quot;You lose!&quot;, computer, &quot;beats&quot;, player) else: print(&quot;You win!&quot;, player, &quot;beats&quot;, computer) elif player == &quot;paper&quot;: if computer == &quot;scissors&quot;: print(&quot;You lose!&quot;, computer, &quot;beats&quot;, player) else: print(&quot;You win!&quot;, player, &quot;beats&quot;, computer) elif player == &quot;scissors&quot;: if computer == &quot;rock&quot;: print(&quot;You lose!&quot;, computer, &quot;beats&quot;, player) else: print(&quot;You win!&quot;, player, &quot;beats&quot;, computer) ### This is to let the player know they typed in the wrong thing and re do it. else: print(&quot;Check your spelling and try again&quot;) </code></pre> <p>I made this code and have tried other ways to simplify but none of them seem to work as intended.</p> <p>Any help refining/condensing the code with some explanations/guidance would be much appreciated.</p> <p>This is my 3rd-day learning python so I'm not familiar with any of the more advanced python commands you may know.</p>
[ { "answer_id": 74379538, "author": "Link_jon", "author_id": 20461445, "author_profile": "https://Stackoverflow.com/users/20461445", "pm_score": 1, "selected": true, "text": "player = input(\"...\")\nplayer = player.lower() # -- Strings in python act akin to arrays, and this changes all\n # -- characters in the string lowercase\n" }, { "answer_id": 74379588, "author": "blackbrandt", "author_id": 5763413, "author_profile": "https://Stackoverflow.com/users/5763413", "pm_score": 1, "selected": false, "text": "import random as r\ninput(\"Enter rock, paper, or scissors\")\nprint(r.choice([\"You won!\", \"You lost!\", \"Tie!\"]))\n" }, { "answer_id": 74379731, "author": "oribro", "author_id": 10703543, "author_profile": "https://Stackoverflow.com/users/10703543", "pm_score": 0, "selected": false, "text": "def is_win(player, computer):\n if player == computer:\n print('Tie')\n elif player == 'rock' and computer == 'scissors' or\nplayer == 'paper' and computer == 'rock' or\n# Rest of win conditions here\n print('Win')\n else:\n print('Lose')\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20461369/" ]
74,379,381
<p>I have this piece of code that helps me to sort a linked list whose nodes contain a singular word. From my understanding of insertion sort, I've managed to come up with this which works fine, but there is a part where I've copied from online and need help in understanding it.</p> <pre><code>Node* insertion_sort(Node* head) { Node* dummy; dummy= malloc(sizeof(Node)); if (dummy == NULL) { printf(&quot;Memory allocation error&quot;); } dummy-&gt;next = head; Node* last_sorted = head; Node* current = head-&gt;next; while (current != NULL) { if(strcmp(last_sorted, current) &lt;= 0) { last_sorted = current; } else { Node* prev = dummy; while (strcmp(prev-&gt;next-&gt;word, current) &lt; 0) { prev = prev-&gt;next; } last_sorted-&gt;next = current-&gt;next; current-&gt;next = prev-&gt;next; prev-&gt;next = current; } current = last_sorted-&gt;next; } return dummy-&gt;next; } </code></pre> <p>In the line</p> <pre><code>prev-&gt;next = current; </code></pre> <p>Why would it also change the value of where my dummy node points to? Wouldn't the 2 nodes be independent of one another? I suspect this is due to how pointers work as this is very new territory for me.</p> <p>I have tried running through the debugger and saw the changes but I do not understand why/how does this occur.</p>
[ { "answer_id": 74379538, "author": "Link_jon", "author_id": 20461445, "author_profile": "https://Stackoverflow.com/users/20461445", "pm_score": 1, "selected": true, "text": "player = input(\"...\")\nplayer = player.lower() # -- Strings in python act akin to arrays, and this changes all\n # -- characters in the string lowercase\n" }, { "answer_id": 74379588, "author": "blackbrandt", "author_id": 5763413, "author_profile": "https://Stackoverflow.com/users/5763413", "pm_score": 1, "selected": false, "text": "import random as r\ninput(\"Enter rock, paper, or scissors\")\nprint(r.choice([\"You won!\", \"You lost!\", \"Tie!\"]))\n" }, { "answer_id": 74379731, "author": "oribro", "author_id": 10703543, "author_profile": "https://Stackoverflow.com/users/10703543", "pm_score": 0, "selected": false, "text": "def is_win(player, computer):\n if player == computer:\n print('Tie')\n elif player == 'rock' and computer == 'scissors' or\nplayer == 'paper' and computer == 'rock' or\n# Rest of win conditions here\n print('Win')\n else:\n print('Lose')\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12255131/" ]
74,379,382
<p>I'm finishing AI50's tic tac toe, everything seems to be working, including the minimax algorithm but I came across a play (which almost always repeats itself), when the following steps occur as I am the X player:</p> <p>[2][2] : X</p> <p>[0][0] : O</p> <p>[0][2] : X</p> <p>[2][0] : O</p> <p>At this point i place the final X between the previous two at [1][2], yet I don't win, the game goes on and O places it's third at [1][0] and wins the game. If I'm playing as player O, similar can happen when the AI doesnt place it's 3rd winning mark in the middle but puts it between my 2 to block me from winning.</p> <p>Is the problem with my Minimax function or the winner function fails to detect ?</p> <p>Apart from this I have won other games and the AI can win too in other scenarios, everything seems to be fine.</p> <p>Here is my code:</p> <pre><code>&quot;&quot;&quot; Tic Tac Toe Player &quot;&quot;&quot; import math from random import randint from copy import deepcopy X = &quot;X&quot; O = &quot;O&quot; EMPTY = None def initial_state(): &quot;&quot;&quot; Returns starting state of the board. &quot;&quot;&quot; return [[EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY]] def player(board): &quot;&quot;&quot; Returns player who has the next turn on a board. &quot;&quot;&quot; x_count = 0 o_count = 0 for i in range(3): for j in range(3): if board[i][j] == X: x_count += 1 if board[i][j] == O: o_count += 1 if x_count == o_count: return X else: return O def actions(board): &quot;&quot;&quot; Returns set of all possible actions (i, j) available on the board. &quot;&quot;&quot; possible_actions = set() for i in range(3): for j in range(3): if board[i][j] == EMPTY: possible_actions.add((i, j)) return possible_actions def result(board, action): &quot;&quot;&quot; Returns the board that results from making move (i, j) on the board. &quot;&quot;&quot; copied_board = deepcopy(board) if copied_board[action[0]][action[1]] == EMPTY: copied_board[action[0]][action[1]] = player(board) else: raise Exception(&quot;Not a valid move&quot;) return copied_board def winner(board): &quot;&quot;&quot; Returns the winner of the game, if there is one. &quot;&quot;&quot; # Check horizontally and vertically for i in range(3): if board[i][0] == board[i][1] == board[i][2]: return board[i][0] elif board[0][i] == board[1][i] == board[2][i]: return board[0][i] # Check diagonally if board[0][0] == board[1][1] == board[2][2]: return board[0][0] elif board[2][0] == board[1][1] == board[0][2]: return board[2][0] # Return None if tie, as in none of the above conditions were met else: return None def terminal(board): &quot;&quot;&quot; Returns True if game is over, False otherwise. &quot;&quot;&quot; if winner(board) == X or winner(board) == O or (winner(board) == None and len(actions(board)) == 0): return True else: return False def utility(board): &quot;&quot;&quot; Returns 1 if X has won the game, -1 if O has won, 0 otherwise. &quot;&quot;&quot; if winner(board) == X: return 1 elif winner(board) == O: return -1 else: return 0 def minimax(board): &quot;&quot;&quot; Returns the optimal move for the current player on the board. &quot;&quot;&quot; # Check for terminal state if terminal(board): return None # If X's turn elif player(board) == X: options = [] for action in actions(board): score = min_value(result(board, action)) # Store options in list options.append([score, action]) # Return highest value action return sorted(options, reverse=True)[0][1] # If O's turn else: options = [] for action in actions(board): score = max_value(result(board, action)) # Store options in list options.append([score, action]) # Return lowest value action return sorted(options)[0][1] def max_value(board): &quot;&quot;&quot; Returns the highest value option of a min-value result &quot;&quot;&quot; # Check for terminal state if terminal(board): return utility(board) # Loop through possible steps v = -math.inf for action in actions(board): v = max(v, min_value(result(board, action))) return v def min_value(board): &quot;&quot;&quot; Returns the smallest value option of a max-value result &quot;&quot;&quot; # Check for terminal state if terminal(board): return utility(board) # Loop through possible steps v = math.inf for action in actions(board): v = min(v, max_value(result(board, action))) return v </code></pre>
[ { "answer_id": 74379551, "author": "NoDakker", "author_id": 6032177, "author_profile": "https://Stackoverflow.com/users/6032177", "pm_score": -1, "selected": false, "text": "def winner(board):\n \"\"\"\n Returns the winner of the game, if there is one.\n \"\"\" \n # Check horizontally and vertically\n for i in range(3):\n if board[i][0] == board[i][1] == board[i][2]:\n return board[i][0]\n\n elif board[0][i] == board[1][i] == board[2][i]:\n return board[0][i]\n\n # Check diagonally\n if board[0][0] == board[1][1] == board[2][2]:\n return board[0][0]\n\n elif board[2][0] == board[1][1] == board[0][2]:\n return board[2][0]\n \n # Return None if tie, as in none of the above conditions were met\n else:\n return None\n" }, { "answer_id": 74380603, "author": "trincot", "author_id": 5459839, "author_profile": "https://Stackoverflow.com/users/5459839", "pm_score": 1, "selected": true, "text": "winner" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19635809/" ]
74,379,387
<p>I am working on cleaning data I scrapped and one of the columns is in for of dictionary in a list. How can I extract the values of the list in new column. The column name is &quot;age &quot; as shown in the screenshot.</p> <p>Best regards</p> <p>I have tried using pandas extract function but did not work.</p> <p>df['age_claen'] = dff['age'].str.fullmatch('age_message')</p> <p><a href="https://i.stack.imgur.com/EalLm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EalLm.jpg" alt="screenshot from jupyter notebook" /></a></p>
[ { "answer_id": 74379551, "author": "NoDakker", "author_id": 6032177, "author_profile": "https://Stackoverflow.com/users/6032177", "pm_score": -1, "selected": false, "text": "def winner(board):\n \"\"\"\n Returns the winner of the game, if there is one.\n \"\"\" \n # Check horizontally and vertically\n for i in range(3):\n if board[i][0] == board[i][1] == board[i][2]:\n return board[i][0]\n\n elif board[0][i] == board[1][i] == board[2][i]:\n return board[0][i]\n\n # Check diagonally\n if board[0][0] == board[1][1] == board[2][2]:\n return board[0][0]\n\n elif board[2][0] == board[1][1] == board[0][2]:\n return board[2][0]\n \n # Return None if tie, as in none of the above conditions were met\n else:\n return None\n" }, { "answer_id": 74380603, "author": "trincot", "author_id": 5459839, "author_profile": "https://Stackoverflow.com/users/5459839", "pm_score": 1, "selected": true, "text": "winner" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10194913/" ]
74,379,390
<p>// I have a struct model for Notes</p> <pre><code>struct NotesModel{ var groupName: String // sections in tableView var info: [NotesInfo] // rows in respective sections in tableView } struct NotesInfo{ var groupName: String var image: String var notesTitle: String var notesDescription: String var notesDate: String } // 1) this is my ViewController(FirstVC) var arrayNotes = [NotesModel]() // array that will be used to populate tableView var info1 = [NotesInfo]() var info2 = [NotesInfo]() var info3 = [NotesInfo]() // I have appended data in arrayNotes info1.append(NotesInfo(groupName: &quot;ABC&quot;, image: &quot;img1&quot;, notesTitle: &quot;Public Notes&quot;, notesDescription: &quot;Public Notes are for xyz use...&quot;, notesDate: &quot;17/08/2020&quot;)) info1.append(NotesInfo(groupName: &quot;ABC&quot;, image: &quot;img1&quot;, notesTitle: &quot;Public Notes(A)&quot;, notesDescription: &quot;Public Notes are for xyz use...&quot;, notesDate: &quot;19/08/2020&quot;)) arrayNotes.append(NotesModel(groupName: &quot;ABC&quot;, info: info1)) info2.append(NotesInfo(groupName: &quot;XYZ&quot;, image: &quot;img2&quot;, notesTitle: &quot;My Notes&quot;, notesDescription: &quot;My Notes include...&quot;, notesDate: &quot;25/08/2020&quot;)) arrayNotes.append(NotesModel(groupName: &quot;XYZ&quot;, info: info2)) info3.append(NotesInfo(groupName: &quot;PQR&quot;, image: &quot;img3&quot;, notesTitle: &quot;Notes Example&quot;, notesDescription: &quot;Notes Example here..&quot;, notesDate: &quot;25/08/2020&quot;)) arrayNotes.append(NotesModel(groupName: &quot;PQR&quot;, info: info2)) // I have a TableView on ViewController to present NotesModel data // MARK: - Number of Sections in TableView func numberOfSections(in tableView: UITableView) -&gt; Int { return arrayNotes.count // returns 3 } // MARK: - HeaderView in Section func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -&gt; UIView? { let headerCell = Bundle.main.loadNibNamed(&quot;HeaderCell&quot;, owner: self, options: nil)?.first as! HeaderCell let dict = arrayNotes[section] headerCell.lblGroupName.text = dict.groupName // &quot;ABC&quot;, &quot;XYZ&quot;, &quot;PQR&quot; let info = dict.info for values in info{ headerCell.imgGroup.image = UIImage(named: values.image) // &quot;img1&quot;, &quot;img2&quot;, &quot;img3&quot; } return headerCell } // MARK: - Number of Rows in TableView func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int { return arrayNotes[section].info.count // &quot;ABC&quot; -&gt; 2 rows, &quot;XYZ&quot; -&gt; 1 row, &quot;PQR&quot; -&gt; 1 row } // MARK: - Cell For Row At in TableView func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: &quot;NotesCell&quot;, for: indexPath) as! NotesCell cell.selectedBackgroundView = UIView() cell.selectedBackgroundView?.backgroundColor = .systemBackground let dict = arrayNotes[indexPath.section] let info = dict.info[indexPath.row] cell.lblNotesTitle.text = info.notesTitle cell.lblNotesDescription.text = info.notesDescription cell.lblNotesDate.text = info.notesDate return cell } // MARK: - Button Create New Note Event func createNewNotesButton(_ sender: UIButton){ let storyBoard = UIStoryboard(name: &quot;NotesStoryBoard&quot;, bundle: nil) let createNewNotesVC = storyBoard.instantiateViewController(withIdentifier: &quot;CreateNewNotesVC&quot;) as! CreateNewNotesVC createNewNotesVC.delegate = self self.navigationController?.pushViewController(createNewNotesVC, animated: true) } // MARK: - Create New Notes Protocol Conformance func passNewNotesModel(object: NotesModel) { for item in arrayNotes{ if item.groupName == object.groupName{ print(&quot;same section&quot;) var ogInfo = item.info let addedInfo = object.info ogInfo.append(contentsOf: addedInfo) print(&quot;ogInfo after appending --&gt; \(ogInfo)&quot;) arrayNotes.append(NotesModel(groupName: item.groupName, info: ogInfo)) // I want to append rows in section that already exist on ViewController, there is already 3 sections with different number of rows but this doesn't append in respective section but creates new section every time }else{ print(&quot;different section&quot;) arrayNotes.append(object) // and if section doesn't exist here on ViewController then create new section and add rows in it. but this adds multiple sections } } self.tableViewNotes.reloadData() } </code></pre> <ol start="2"> <li><p>this is my CreateNewNotesVC(SecondVC)</p> <p>// MARK: - Protocol Create New Notes for NotesModel</p> <p>protocol CreateNewNotesModel { func passNewNotesModel(object: NotesModel) }</p> <p>var newNotesModel: NotesModel!</p> <p>var delegate: CreateNewNotesModel?</p> </li> </ol> <p>here i have textFields and &quot;SUBMIT&quot; button, on &quot;SUBMIT&quot; button click, pass NotesModel object and popView to firstVC and tableView on firstVC should be updated with newly created model object.</p> <p>also there is one drop down menu here from which i have to select note's group name say there are 6 different group names, which represents section in tableView, if i choose &quot;ABC&quot; group name from drop down menu then on ViewController(firstVC) data should be append in &quot;ABC&quot; section in tableView, if i choose &quot;OMG&quot; group name from drop down which doesn't exist on ViewController(firstVC), then new section should be created.</p> <pre><code>// MARK: - Button Submit Event @IBAction func btnSubmit_Event(\_ sender: Any) { var info = [NotesInfo]() info.append(NotesInfo(groupName: txtSelectGroup.text ?? &quot;&quot;, image: ImageString, notesTitle: txtNotesTitle.text ?? &quot;&quot;, notesDescription: txtNotesDescription.text ?? &quot;&quot;, notesDate: txtNotesDate.text ?? &quot;&quot;)) newNotesModel = (NotesModel(groupName: txtSelectGroup.text ?? &quot;&quot;, info: info)) delegate?.passNewNotesModel(object: newNotesModel) self.navigationController?.popViewController(animated: true) } </code></pre> <p>i want to append data in respective sections, my code is generating section every time due to for loop, i have no idea how to append data in respective section, any help would be really appreciated ! Thank You.</p> <pre><code> // UPDATE: as per WeyHan Ng suggestion: for item in arrayNotes{ var ogInfo = item.info let addedInfo = object.info ogInfo.append(contentsOf: addedInfo) print(&quot;ogInfo after appending --&gt; \(ogInfo)&quot;) if item.groupName == object.groupName{ print(&quot;same section&quot;) let index = arrayNotes.firstIndex(where: { $0.groupName == object.groupName})! print(index) arrayNotes[index].info = ogInfo // this is solved }else{ print(&quot;different section&quot;) arrayNotes.append(object) // ISSUE: appending more than one section every time } } self.tableViewConsultantMilestones.reloadData() </code></pre>
[ { "answer_id": 74379551, "author": "NoDakker", "author_id": 6032177, "author_profile": "https://Stackoverflow.com/users/6032177", "pm_score": -1, "selected": false, "text": "def winner(board):\n \"\"\"\n Returns the winner of the game, if there is one.\n \"\"\" \n # Check horizontally and vertically\n for i in range(3):\n if board[i][0] == board[i][1] == board[i][2]:\n return board[i][0]\n\n elif board[0][i] == board[1][i] == board[2][i]:\n return board[0][i]\n\n # Check diagonally\n if board[0][0] == board[1][1] == board[2][2]:\n return board[0][0]\n\n elif board[2][0] == board[1][1] == board[0][2]:\n return board[2][0]\n \n # Return None if tie, as in none of the above conditions were met\n else:\n return None\n" }, { "answer_id": 74380603, "author": "trincot", "author_id": 5459839, "author_profile": "https://Stackoverflow.com/users/5459839", "pm_score": 1, "selected": true, "text": "winner" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20452635/" ]
74,379,411
<p>In my Controller, I have</p> <pre><code>@RequestParam boolean flag </code></pre> <p>This allows the caller of my API to pass &quot;true&quot;, &quot;yes&quot;, &quot;on&quot; or &quot;1&quot; to represent true.</p> <p>However, I want to access this flag in my <code>HandlerInterceptor</code> too. There, all I have is an <code>HttpServletRequest</code>, and I have to access my flag as</p> <pre><code>boolean flag = Boolean.parseBoolean(request.getParameter(&quot;flag&quot;)); </code></pre> <p>This is not ideal, because <code>parseBoolean</code> only considers the string &quot;true&quot; to be true. If the API caller passes &quot;yes&quot;, &quot;on&quot; or &quot;1&quot; then the interceptor will treat the value as false and the controller will treat it as true.</p> <p>I don't want to hard code into my application the string values that Spring considers true, because if they change in a future release we are back to square 1.</p> <p>Is there a way to get consistent boolean value in both interceptor and controller?</p>
[ { "answer_id": 74381132, "author": "Ashish Patil", "author_id": 5014221, "author_profile": "https://Stackoverflow.com/users/5014221", "pm_score": 1, "selected": false, "text": " System.setProperty(\"true\", \"true\");\n System.setProperty(\"one\", \"true\");\n System.setProperty(\"1\", \"true\");\n System.setProperty(\"yes\", \"true\");\n\n boolean b = Boolean.getBoolean(\"yes\");\n System.out.println(b);\n" }, { "answer_id": 74389332, "author": "k314159", "author_id": 13963086, "author_profile": "https://Stackoverflow.com/users/13963086", "pm_score": 0, "selected": false, "text": "boolean flag = DefaultConversionService.getSharedInstance().convert(\n request.getParameter(\"flag\"),\n Boolean.class);\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13963086/" ]
74,379,424
<p>I've made a simple task in Webpack to bundle all my JS files. The console log shows that the file was created succesfully but it doesn't work when load the html page.</p> <p>Here is the code:</p> <pre><code>const path = require('path'); const TerserPlugin = require(&quot;terser-webpack-plugin&quot;); module.exports = { entry:[ '/src/assets/js/libraries/aos.js', '/src/assets/js/libraries/jquery.mask.js', '/src/assets/js/libraries/slick.js', '/src/assets/js/scripts/email.js', '/src/assets/js/scripts/google-analytics.js', '/src/assets/js/scripts/modernizr-3.11.2.min.js', '/src/assets/js/scripts/scripts.js', ], output: { path: path.resolve(__dirname, './public/core/assets/js'), filename: 'bundle.js' }, optimization: { minimize: true, minimizer: [new TerserPlugin()], }, module: { rules: [ { test: /\.js$/, exclude: /(node_modules)/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'] } } }], }, watch: true, mode: 'production' } </code></pre> <p>This is what the console shows (everything seems to compile fine):</p> <pre><code>$ npm run build &gt; project@1.0.0 build &gt; webpack --config webpack.config.js asset bundle.js 161 KiB [emitted] [minimized] (name: main) 1 related asset runtime modules 123 bytes 1 module modules by path ./src/assets/js/ 126 KiB modules by path ./src/assets/js/scripts/*.js 13.5 KiB ./src/assets/js/scripts/email.js 393 bytes [built] [code generated] ./src/assets/js/scripts/google-analytics.js 209 bytes [built] [code generated] ./src/assets/js/scripts/modernizr-3.11.2.min.js 11.7 KiB [built] [code generated] ./src/assets/js/scripts/scripts.js 1.22 KiB [built] [code generated] modules by path ./src/assets/js/libraries/*.js 113 KiB ./src/assets/js/libraries/aos.js 21 KiB [built] [code generated] ./src/assets/js/libraries/jquery.mask.js 19.5 KiB [built] [code generated] ./src/assets/js/libraries/slick.js 72.2 KiB [built] [code generated] ./node_modules/jquery/dist/jquery.js 283 KiB [built] [code generated] webpack 5.74.0 compiled successfully in 3199 ms </code></pre> <p>As you can see it's a very basic task.</p> <p>All the paths into my html page are correct (I tested without the Webpack). But just don't work when I bundle with Webpack.</p>
[ { "answer_id": 74381132, "author": "Ashish Patil", "author_id": 5014221, "author_profile": "https://Stackoverflow.com/users/5014221", "pm_score": 1, "selected": false, "text": " System.setProperty(\"true\", \"true\");\n System.setProperty(\"one\", \"true\");\n System.setProperty(\"1\", \"true\");\n System.setProperty(\"yes\", \"true\");\n\n boolean b = Boolean.getBoolean(\"yes\");\n System.out.println(b);\n" }, { "answer_id": 74389332, "author": "k314159", "author_id": 13963086, "author_profile": "https://Stackoverflow.com/users/13963086", "pm_score": 0, "selected": false, "text": "boolean flag = DefaultConversionService.getSharedInstance().convert(\n request.getParameter(\"flag\"),\n Boolean.class);\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20461496/" ]
74,379,448
<p>I have an example list of numbers:</p> <pre><code>888* 8* 8.88* 88.88* 88888.888* 899900 8.89 0.08 80 89899 50 32 30.8 0.081 0.8 8.1 </code></pre> <p>and I only want to match those that have only 8's. I put an asterisk for the ones I only want and the others should be ignored.</p> <p>I tried this but could only get partially what I wanted.</p> <pre><code>num &lt;- c(888, 8, 8.88, 88.88, 88888.888, 899900, 8.89, 0.08, 80, 89899, 50, 32, 30.8, 0.081, 0.8, 8.1) grepl('^8+[^\\.]*[^0-7|9]*', num) </code></pre>
[ { "answer_id": 74379488, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 1, "selected": false, "text": " grep(\"^8+([.]8+)?$\", as.character(num), value = TRUE)\n[1] \"888\" \"8\" \"8.88\" \"88.88\" \"88888.888\"\n" }, { "answer_id": 74379543, "author": "G. Grothendieck", "author_id": 516548, "author_profile": "https://Stackoverflow.com/users/516548", "pm_score": 2, "selected": false, "text": "# there cannot be anything other than 8 and dot \n!grepl(\"[^8.]\", L)\n## [1] TRUE TRUE TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE\n## [13] FALSE FALSE FALSE FALSE\n\n# if we remove 8's and dot's there should be nothing left\nnchar(gsub(\"[8.]\", \"\", L)) == 0\n## [1] TRUE TRUE TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE\n## [13] FALSE FALSE FALSE FALSE\n\n# trim off all 8's and dots and nothing should be left\n!nzchar(trimws(L, whitespace = \"[8.]\"))\n## [1] TRUE TRUE TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE\n## [13] FALSE FALSE FALSE FALSE\n" }, { "answer_id": 74379581, "author": "zephryl", "author_id": 17303805, "author_profile": "https://Stackoverflow.com/users/17303805", "pm_score": 3, "selected": true, "text": "grep(\"^[8.]+$\", num, value = TRUE)\n# \"888\" \"8\" \"8.88\" \"88.88\" \"88888.888\"\n" }, { "answer_id": 74379992, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 1, "selected": false, "text": "grep(\"^8+\\\\.*8*$\", as.character(num), value=T)\n[1] \"888\" \"8\" \"8.88\" \"88.88\" \"88888.888\"\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8864308/" ]
74,379,482
<p>I'm trying to calculate IRR by group using the package &quot;jrvFinance&quot; - function &quot;irr&quot; but i don't know how.</p> <p>I have this for only 1 group:</p> <p>example:</p> <pre><code>pr1 &lt;- data.frame(idC=1,period = 0:12, cf = c(-10000,1623.8,1630.47,1637.88,1646.09,1655.21,1665.32,1676.54,1688.99,1702.81,1718.14,1735.15,1753.97)) irr1 &lt;- pr1 %&gt;% select(cf) %&gt;% .[[1]] %&gt;% irr() pr1&lt;-pr1 %&gt;%mutate(calculate=irr1) </code></pre> <p>But i have a data.frame with several groups (idC), how can i get the same result by group in the same data.frame? in this example i only use 2 groups (idC column)</p> <pre><code>pr1 &lt;- data.frame(idC=1,period = 0:12, cf = c(-10000,1623.8,1630.47,1637.88,1646.09,1655.21,1665.32,1676.54,1688.99,1702.81,1718.14,1735.15,1753.97)) pr2&lt;-data.frame(idC=2,period = 0:12, cf = c(-10000,1555.79,1562.19,1569.22,1576.93,1585.40,1594.7,1604.91,1616.12,1628.43,1641.94,1656.79,1673.02)) full_pr=rbind(pr1,pr2) </code></pre> <p>result I need for full_pr:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>idC</th> <th>period</th> <th>cf</th> <th>calculate</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>0</td> <td>-10000</td> <td>0.1263736</td> </tr> <tr> <td>1</td> <td>1</td> <td>1623.8</td> <td>0.1263736</td> </tr> <tr> <td>1</td> <td>2</td> <td>1630.47</td> <td>0.1263736</td> </tr> <tr> <td>1</td> <td>3</td> <td>1637.88</td> <td>0.1263736</td> </tr> <tr> <td>1</td> <td>4</td> <td>1646.09</td> <td>0.1263736</td> </tr> <tr> <td>1</td> <td>5</td> <td>1655.21</td> <td>0.1263736</td> </tr> <tr> <td>1</td> <td>6</td> <td>1665.32</td> <td>0.1263736</td> </tr> <tr> <td>1</td> <td>7</td> <td>1676.54</td> <td>0.1263736</td> </tr> <tr> <td>1</td> <td>8</td> <td>1688.99</td> <td>0.1263736</td> </tr> <tr> <td>1</td> <td>9</td> <td>1702.81</td> <td>0.1263736</td> </tr> <tr> <td>1</td> <td>10</td> <td>1718.14</td> <td>0.1263736</td> </tr> <tr> <td>1</td> <td>11</td> <td>1735.15</td> <td>0.1263736</td> </tr> <tr> <td>1</td> <td>12</td> <td>1753.97</td> <td>0.1263736</td> </tr> <tr> <td>2</td> <td>0</td> <td>-10000</td> <td>0.1170392</td> </tr> <tr> <td>2</td> <td>1</td> <td>1555.79</td> <td>0.1170392</td> </tr> <tr> <td>2</td> <td>2</td> <td>1562.19</td> <td>0.1170392</td> </tr> <tr> <td>2</td> <td>3</td> <td>1569.22</td> <td>0.1170392</td> </tr> <tr> <td>2</td> <td>4</td> <td>1576.93</td> <td>0.1170392</td> </tr> <tr> <td>2</td> <td>5</td> <td>1585.4</td> <td>0.1170392</td> </tr> <tr> <td>2</td> <td>6</td> <td>1594.7</td> <td>0.1170392</td> </tr> <tr> <td>2</td> <td>7</td> <td>1604.91</td> <td>0.1170392</td> </tr> <tr> <td>2</td> <td>8</td> <td>1616.12</td> <td>0.1170392</td> </tr> <tr> <td>2</td> <td>9</td> <td>1628.43</td> <td>0.1170392</td> </tr> <tr> <td>2</td> <td>10</td> <td>1641.94</td> <td>0.1170392</td> </tr> <tr> <td>2</td> <td>11</td> <td>1656.79</td> <td>0.1170392</td> </tr> <tr> <td>2</td> <td>12</td> <td>1673.02</td> <td>0.1170392</td> </tr> </tbody> </table> </div> <pre><code></code></pre>
[ { "answer_id": 74379524, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 2, "selected": false, "text": "library(jrvFinance)\nlibrary(dplyr)\nfull_pr <- full_pr %>%\n group_by(idC) %>%\n mutate(calculate = irr(cf)) %>% \n ungroup\n" }, { "answer_id": 74382224, "author": "Kat", "author_id": 5329073, "author_profile": "https://Stackoverflow.com/users/5329073", "pm_score": 2, "selected": true, "text": "as.data.frame()" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19839146/" ]
74,379,484
<p>I'm making a game and the player spawn is off I've tried tutorials and I haven't found anything here is my code and a photo I've tried playing with the code But I can't seem to find how to change my player spawn please can help I'm stuck <a href="https://i.stack.imgur.com/HkK1I.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HkK1I.png" alt="enter image description here" /></a></p> <pre><code>from pickle import FALSE import pygame from pygame.locals import * pygame.init() Clock = pygame.time.Clock() fps = 60 screen_width = 800 screen_height = 800 screen = pygame.display.set_mode((screen_width,screen_height)) pygame.display.set_caption('Platformer') #define game variables tile_size = 40 #load images bg_img = pygame.image.load(&quot;sky.png&quot;) sun_img = pygame.image.load(&quot;sun.png&quot;) #draw player onto the screen class Player(): def __init__(self, x, y): self.images_right = [] self.images_left = [] self.index = 0 self.count = 0 for num in range (1,3): img_right = pygame.image.load(f'guy{num}.png') img_right = pygame.transform.scale(img_right, (30, 60)) img_left = pygame.transform.flip(img_right, True, False) self.images_right.append(img_right) self.images_left.append(img_left) self.image = self.images_right[self.index] self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y self.width = self.image.get_width() self.height = self.image.get_height() self.vel_y = 0 self.jumped = False self.direction = 0 def update(self): dx = 0 dy = 0 walk_cooldown = 15 #draw player onto the screen key = pygame.key.get_pressed() if key[pygame.K_SPACE] and self.jumped == False: self.vel_y = -15 self.jumped = True if key[pygame.K_SPACE] == False: self.jumped = False if key[pygame.K_RIGHT]: dx += 5 self.count += 1 self.direction = 1 if key[pygame.K_LEFT]: dx -= 5 self.count += 1 self.direction = -1 if key[pygame.K_LEFT] == False and key[pygame.K_RIGHT] == False: self.counter = 0 self.index = 0 if self.direction == 1: self.image = self.images_right[self.index] if self.direction == -1: self.image = self.images_left[self.index] #handle Animation if self.count &gt; walk_cooldown: self.count = 0 self.index += 1 if self.index &gt;= len(self.images_right): self.index = 0 if self.direction == 1: self.image = self.images_right[self.index] if self.direction == -1: self.image = self.images_left[self.index] #add gravity self.vel_y += 1.5 if self.vel_y &gt; 10: self.vel_y = 10 dy += self.vel_y #check for collision for tile in world.tile_list: # check for collision in yt direction if tile[1].colliderect(self.rect.x, self.rect.y + dy, self.width, self.height): # check if below the ground i.e jumping if self.vel_y &lt; 0: dy = tile[1].bottom - self.rect.top if self.vel_y &gt;= 0: dy = tile[1].top - self.rect.bottom #update player coordinates self.rect.x += dx self.rect.y += dy if self.rect.bottom &gt; screen_height: self.rect.bottom = screen_height dy = 0 screen.blit(self.image, self.rect) pygame.draw.rect(screen, (255, 0, 255), self.rect, 2) class World(): def __init__(self, data): self.tile_list = [] #load images dirt_img = pygame.image.load(&quot;dirt.png&quot;) grass_img = pygame.image.load(&quot;grass.png&quot;) row_count = 0 for row in data: col_count = 0 for tile in row: if tile == 1: img = pygame.transform.scale(dirt_img, (tile_size, tile_size)) img_rect = img.get_rect() img_rect.x = col_count * tile_size img_rect.y = row_count * tile_size tile = (img, img_rect) self.tile_list.append(tile) if tile == 2: img = pygame.transform.scale(grass_img, (tile_size, tile_size)) img_rect = img.get_rect() img_rect.x = col_count * tile_size img_rect.y = row_count * tile_size tile = (img, img_rect) self.tile_list.append(tile) col_count += 1 row_count += 1 def draw(self): for tile in self.tile_list: screen.blit(tile[0], tile[1]) pygame.draw.rect(screen, (255, 255, 255), tile[1], 2 ) world_data = world_data = [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,], [1, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 1,], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 2, 2, 1,], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 5, 0, 0, 0, 1,], [1, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 2, 2, 2, 0, 0, 0, 0, 0, 1,], [1, 7, 0, 0, 2, 2, 2, 0, 0, 0, 2, 1, 0, 0, 0, 0, 0, 0, 0, 1,], [1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 7, 0, 0, 0, 0, 1,], [1, 0, 2, 0, 0, 7, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,], [1, 0, 0, 2, 0, 0, 4, 0, 0, 0, 0, 3, 0, 0, 3, 0, 0, 0, 0, 1,], [1, 0, 0, 0, 0, 0, 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 1,], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 7, 0, 0, 0, 0, 0, 0, 1,], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 2, 2, 2, 2, 2, 1,], [1, 0, 0, 0, 0, 0, 2, 2, 2, 6, 6, 6, 6, 6, 1, 1, 1, 1, 1, 1,], [1, 0, 0, 0, 0, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,], [1, 0, 0, 0, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,], [1, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,] ] player = Player(100, screen_height - 130) world = World(world_data) run = True while run: Clock.tick(fps) screen.blit(bg_img, (0,0)) screen.blit(sun_img, (100,100)) world.draw() player.update() for event in pygame.event.get(): if event.type == pygame.QUIT: run = False pygame.display.update() pygame.quit() </code></pre> <p>I thought the player spawn was under the world data list but that was where he was spawining left too right He isnt spawning on the tile that I have made</p>
[ { "answer_id": 74379524, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 2, "selected": false, "text": "library(jrvFinance)\nlibrary(dplyr)\nfull_pr <- full_pr %>%\n group_by(idC) %>%\n mutate(calculate = irr(cf)) %>% \n ungroup\n" }, { "answer_id": 74382224, "author": "Kat", "author_id": 5329073, "author_profile": "https://Stackoverflow.com/users/5329073", "pm_score": 2, "selected": true, "text": "as.data.frame()" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20218281/" ]
74,379,523
<p>I am taking the data from backend for that I am using the async function. But the data contains some duplicate elements so I need to remove them and get those data in DOM. Can we do that. If yes can you explain how to do that.</p> <pre><code>function Productpage(){ const [data, setData] = useState([]) let navigate = useNavigate() let getproducts = async () =&gt; { let res = await axios.get(`${env.apiurl}/users/products`) console.log(data) if (res.data.statusCode === 200) { setData(res.data.data) } else { alert(res.data.message) } } console.log(data) useEffect(() =&gt; { getproducts() }, []) return &lt;&gt; &lt;div&gt; { data.map((e,i)=&gt;{ return &lt;div key={i} onClick={()=&gt;navigate(`${e.producttype}`)} &gt; &lt;Card style={{width:&quot;100%&quot;, height:&quot;250px&quot;}}&gt; &lt;CardImg alt=&quot;Card image cap&quot; src={e.url} top width=&quot;50%&quot; height=&quot;60%&quot; /&gt; &lt;CardBody&gt; &lt;CardTitle tag=&quot;h5&quot;&gt; {e.producttype} &lt;/CardTitle&gt; &lt;/CardBody&gt; &lt;/Card&gt; &lt;/div&gt; }) } &lt;/div&gt; &lt;/&gt; } </code></pre> <p>Here data comes from backend and from that data only needed to print partcular values like url and product type in DOM only <strong>without any duplicate values for the product type</strong>.</p>
[ { "answer_id": 74379524, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 2, "selected": false, "text": "library(jrvFinance)\nlibrary(dplyr)\nfull_pr <- full_pr %>%\n group_by(idC) %>%\n mutate(calculate = irr(cf)) %>% \n ungroup\n" }, { "answer_id": 74382224, "author": "Kat", "author_id": 5329073, "author_profile": "https://Stackoverflow.com/users/5329073", "pm_score": 2, "selected": true, "text": "as.data.frame()" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12884905/" ]
74,379,531
<p>I'm a college student who has an android phone and wants to use the sidechat app (sidechat.lol), which is only available on iPhone. I'm trying to create an API wrapper for sidechat's API which will allow me to use it on Android (or on the web), but I'm not quite sure how to discover the api endpoints. (As far as I'm aware, there is no official public API) Is there a simple way to do this, or do I need to do packet-sniffing on an iPhone running the app? If I do need to sniff some packets, what's the best software for doing so?</p>
[ { "answer_id": 74379524, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 2, "selected": false, "text": "library(jrvFinance)\nlibrary(dplyr)\nfull_pr <- full_pr %>%\n group_by(idC) %>%\n mutate(calculate = irr(cf)) %>% \n ungroup\n" }, { "answer_id": 74382224, "author": "Kat", "author_id": 5329073, "author_profile": "https://Stackoverflow.com/users/5329073", "pm_score": 2, "selected": true, "text": "as.data.frame()" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10039784/" ]
74,379,540
<p>I have a stackblitz <a href="https://stackblitz.com/edit/react-ts-dxzkov?file=App.tsx,style.css" rel="nofollow noreferrer">here</a></p> <p>Super simple but I'm stuck</p> <p>I have a div container containing 6 divs</p> <p>I need the position the red div on the right of the container but still keep the layout of the divs.</p> <p>If I try <code>position: absolute; right: 0;</code> or <code>float: right;</code></p> <p>all the div's collapse on top of each other.</p> <p>How can I position the even divs on the right and keep the structure</p> <pre><code>* { font-family: sans-serif; } .wrap { border: 1px solid grey; position: relative; width: 400px; } .wrap div:nth-child(even) { background: red; /* position: absolute; right: 0; */ /* float: right; */ } .block { background: #aaa; width: 200px; padding: 10px; margin-bottom: 5px; color: white; } </code></pre>
[ { "answer_id": 74379637, "author": "Alexis", "author_id": 13986485, "author_profile": "https://Stackoverflow.com/users/13986485", "pm_score": 1, "selected": false, "text": "align-self" }, { "answer_id": 74379649, "author": "Roman Zenia", "author_id": 18704880, "author_profile": "https://Stackoverflow.com/users/18704880", "pm_score": 0, "selected": false, "text": ".block.two {\n position: relative;\n left: 100%;\n transform: translateX(-100%);\n}\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4378588/" ]
74,379,576
<p>I'm making an Arduino reverse stopwatch..but Seems to have a problem with millis() function Whenever I upload the code on Arduino the millis starts running itself..how can I keep it at 0 until I call the millis. or any alternatives to solve it...</p> <pre><code>#include &quot;SevSeg.h&quot; int button1 = 11; int button2 = 12; int button3 = 13; int value = 10; int timer = 0; bool n = true; SevSeg Display; void setup() { Serial.begin(9600); byte numDigits = 2; byte digitPins[] = {9,8}; byte segmentPins[] = {10,2, 3, 4, 5, 6, 7,1}; bool resistorsOnSegments = true; bool updateWithDelays = true; byte hardwareConfig = COMMON_ANODE; Display.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments); Display.setBrightness(100); } </code></pre> <pre><code> void loop() { Display.setNumber(value, 1); Display.refreshDisplay(); if (digitalRead(11)==HIGH){ Start(value); } } void Start(int value){ while(n){ unsigned long timerGlobal = millis(); Display.setNumber(value-timerGlobal/1000, 1); Display.refreshDisplay(); if ((value-timerGlobal/1000) == 0){ n = false; } } } </code></pre>
[ { "answer_id": 74379659, "author": "0___________", "author_id": 6110094, "author_profile": "https://Stackoverflow.com/users/6110094", "pm_score": 1, "selected": false, "text": "extern volatile unsigned long timer0_millis;\n" }, { "answer_id": 74649568, "author": "RUBEN ESTRADA MARMOLEJO", "author_id": 18571788, "author_profile": "https://Stackoverflow.com/users/18571788", "pm_score": 0, "selected": false, "text": "//#include \"SevSeg.h\"\n int button1 = 11;\n int button2 = 12;\n int button3 = 13;\n int value = 10;\n int timer = 0;\n bool n = true;\n\n //Added\n int currentTime = 0;\n long int t0 = 0;\n long int t1 = 0;\n\n //SevSeg Display;\n void setup() {\n Serial.begin(9600);\n byte numDigits = 2;\n byte digitPins[] = {9,8};\n byte segmentPins[] = {10,2, 3, 4, 5, 6, 7,1};\n bool resistorsOnSegments = true;\n bool updateWithDelays = true;\n //byte hardwareConfig = COMMON_ANODE;\n //Display.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments);\n //Display.setBrightness(100);\n \n\n\n }\n void loop() {\n //Display.setNumber(value, 1);\n // Display.refreshDisplay();\n \n if (digitalRead(11)==HIGH){\n Start(value);\n } \n }\n\n\n void Start(int value){ \n t0 = millis();\n while(n){\n t1 = millis();\n if(t1 > (1000+t0)){\n //has passed 1 second\n currentTime++;\n if(value-currentTime == 0){\n n = false;\n }\n \n }\n unsigned long timerGlobal = t1-t0;\n //Display.setNumber(value-timerGlobal/1000, 1);\n //Display.refreshDisplay();\n \n \n }\n \n }\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16805360/" ]
74,379,577
<p>How to remove part of a tree but keep the files and directories in python?</p> <p>I have paths like this:</p> <pre><code>r&quot;C:\User\Desktop\g1sr56g41f2d3s1gf\Document\A\file1.txt&quot; r&quot;C:\User\Desktop\g1sr56g41f2d3s1gf\Document\B\C\file2.txt&quot; r&quot;C:\User\Desktop\g1sr56g41f2d3s1gf\file3.txt&quot; r&quot;C:\User\Desktop\F2F31DS5FDSF1S2F3DS2F1D23\file4.txt&quot; r&quot;C:\User\Desktop\g1sr56g41f2d3s1gf\Document\B\C\file5.txt&quot; r&quot;C:\User\Desktop\g1sr56g41f2d3s1gf\Document\D\E\file6.txt&quot; </code></pre> <p>I want to move them to:</p> <pre><code>r&quot;C:\User\Desktop\Document\A\file1.txt&quot; r&quot;C:\User\Desktop\Document\B\C\file2.txt&quot; r&quot;C:\User\Desktop\file3.txt&quot; r&quot;C:\User\Desktop\file4.txt&quot; r&quot;C:\User\Desktop\Document\B\C\file5.txt&quot; r&quot;C:\User\Desktop\Document\D\E\file6.txt&quot; </code></pre>
[ { "answer_id": 74379659, "author": "0___________", "author_id": 6110094, "author_profile": "https://Stackoverflow.com/users/6110094", "pm_score": 1, "selected": false, "text": "extern volatile unsigned long timer0_millis;\n" }, { "answer_id": 74649568, "author": "RUBEN ESTRADA MARMOLEJO", "author_id": 18571788, "author_profile": "https://Stackoverflow.com/users/18571788", "pm_score": 0, "selected": false, "text": "//#include \"SevSeg.h\"\n int button1 = 11;\n int button2 = 12;\n int button3 = 13;\n int value = 10;\n int timer = 0;\n bool n = true;\n\n //Added\n int currentTime = 0;\n long int t0 = 0;\n long int t1 = 0;\n\n //SevSeg Display;\n void setup() {\n Serial.begin(9600);\n byte numDigits = 2;\n byte digitPins[] = {9,8};\n byte segmentPins[] = {10,2, 3, 4, 5, 6, 7,1};\n bool resistorsOnSegments = true;\n bool updateWithDelays = true;\n //byte hardwareConfig = COMMON_ANODE;\n //Display.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments);\n //Display.setBrightness(100);\n \n\n\n }\n void loop() {\n //Display.setNumber(value, 1);\n // Display.refreshDisplay();\n \n if (digitalRead(11)==HIGH){\n Start(value);\n } \n }\n\n\n void Start(int value){ \n t0 = millis();\n while(n){\n t1 = millis();\n if(t1 > (1000+t0)){\n //has passed 1 second\n currentTime++;\n if(value-currentTime == 0){\n n = false;\n }\n \n }\n unsigned long timerGlobal = t1-t0;\n //Display.setNumber(value-timerGlobal/1000, 1);\n //Display.refreshDisplay();\n \n \n }\n \n }\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16958187/" ]
74,379,585
<p>I have the following table <strong>process_table</strong></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>table</th> <th>index</th> </tr> </thead> <tbody> <tr> <td>TABLE_001</td> <td>1</td> </tr> <tr> <td>TABLE_002</td> <td>2</td> </tr> <tr> <td>TABLE_003</td> <td>3</td> </tr> <tr> <td>TABLE_004</td> <td>4</td> </tr> </tbody> </table> </div> <p>And a macro for create tables that i called type_a tables, using lines from process_table.</p> <p>So, for example, when input was <strong>TABLE_001</strong> will generate <strong>TABLE_001_A</strong>.</p> <pre><code>%macro create_table_type_a(table_name); proc sql; create table temp.&amp;table_name._A as select /*some process*/ from &amp;table_name quit; %mend create_table_type_a; </code></pre> <p>And then I run</p> <pre><code>data _null_; set process_table; call execute('%create_table_type_a('||table||')'); run; </code></pre> <p>Well, I have two doubts.</p> <p>1 - Does SAS process the macro sequential, one line after other, or is parallelized? I didn't find the answer on internet.</p> <p>2 - If It was not parallelized, is it possible do it using the same startegy? The tables to be processed are huge, and i dont know how to parallize the process on SAS.</p> <p>Thanks.</p>
[ { "answer_id": 74379659, "author": "0___________", "author_id": 6110094, "author_profile": "https://Stackoverflow.com/users/6110094", "pm_score": 1, "selected": false, "text": "extern volatile unsigned long timer0_millis;\n" }, { "answer_id": 74649568, "author": "RUBEN ESTRADA MARMOLEJO", "author_id": 18571788, "author_profile": "https://Stackoverflow.com/users/18571788", "pm_score": 0, "selected": false, "text": "//#include \"SevSeg.h\"\n int button1 = 11;\n int button2 = 12;\n int button3 = 13;\n int value = 10;\n int timer = 0;\n bool n = true;\n\n //Added\n int currentTime = 0;\n long int t0 = 0;\n long int t1 = 0;\n\n //SevSeg Display;\n void setup() {\n Serial.begin(9600);\n byte numDigits = 2;\n byte digitPins[] = {9,8};\n byte segmentPins[] = {10,2, 3, 4, 5, 6, 7,1};\n bool resistorsOnSegments = true;\n bool updateWithDelays = true;\n //byte hardwareConfig = COMMON_ANODE;\n //Display.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments);\n //Display.setBrightness(100);\n \n\n\n }\n void loop() {\n //Display.setNumber(value, 1);\n // Display.refreshDisplay();\n \n if (digitalRead(11)==HIGH){\n Start(value);\n } \n }\n\n\n void Start(int value){ \n t0 = millis();\n while(n){\n t1 = millis();\n if(t1 > (1000+t0)){\n //has passed 1 second\n currentTime++;\n if(value-currentTime == 0){\n n = false;\n }\n \n }\n unsigned long timerGlobal = t1-t0;\n //Display.setNumber(value-timerGlobal/1000, 1);\n //Display.refreshDisplay();\n \n \n }\n \n }\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/491637/" ]
74,379,587
<p>I am trying to write a Google Apps Script function which scans every row of my spreadsheet, and if column 36 has a specific string, will look at column 31, column 23, etc. of that row to create an array with the data in these columns.</p> <p>I think it will ultimately require an array updating function inside an if statement inside a loop.</p> <ol> <li>Loop through every row of column 36</li> <li>If string matches target string</li> <li>Add row's data to an array</li> <li>Update another sheet with data from this array</li> </ol> <p>Thank you!</p> <p>Here is what I've tried so far:</p> <p>`</p> <pre><code> function myFunction() { var sheet = SpreadsheetApp.getActive().getSheetByName(&quot;Database&quot;); var range = sheet.getRange(2, 36).getValue(); Logger.log(range); } </code></pre> <p>`</p>
[ { "answer_id": 74379659, "author": "0___________", "author_id": 6110094, "author_profile": "https://Stackoverflow.com/users/6110094", "pm_score": 1, "selected": false, "text": "extern volatile unsigned long timer0_millis;\n" }, { "answer_id": 74649568, "author": "RUBEN ESTRADA MARMOLEJO", "author_id": 18571788, "author_profile": "https://Stackoverflow.com/users/18571788", "pm_score": 0, "selected": false, "text": "//#include \"SevSeg.h\"\n int button1 = 11;\n int button2 = 12;\n int button3 = 13;\n int value = 10;\n int timer = 0;\n bool n = true;\n\n //Added\n int currentTime = 0;\n long int t0 = 0;\n long int t1 = 0;\n\n //SevSeg Display;\n void setup() {\n Serial.begin(9600);\n byte numDigits = 2;\n byte digitPins[] = {9,8};\n byte segmentPins[] = {10,2, 3, 4, 5, 6, 7,1};\n bool resistorsOnSegments = true;\n bool updateWithDelays = true;\n //byte hardwareConfig = COMMON_ANODE;\n //Display.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments);\n //Display.setBrightness(100);\n \n\n\n }\n void loop() {\n //Display.setNumber(value, 1);\n // Display.refreshDisplay();\n \n if (digitalRead(11)==HIGH){\n Start(value);\n } \n }\n\n\n void Start(int value){ \n t0 = millis();\n while(n){\n t1 = millis();\n if(t1 > (1000+t0)){\n //has passed 1 second\n currentTime++;\n if(value-currentTime == 0){\n n = false;\n }\n \n }\n unsigned long timerGlobal = t1-t0;\n //Display.setNumber(value-timerGlobal/1000, 1);\n //Display.refreshDisplay();\n \n \n }\n \n }\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10461633/" ]
74,379,590
<p>My problem is I want create code in html/CSS which adjust automatically the website (blocks+content) whenever I minimize the browser window. <strong>e.g.</strong> I've got the problem of <em>text overflow</em> in the block which I created, when I minimize the browser window.</p> <p>I want the block element to adjust to the length of my content.</p> <p><strong>Problem</strong> There is a text overflow in the block element, which I marked as a green block with a solid border style.</p> <p><strong>I tried</strong> Sure I can solve it with overflow: auto; but it's an ugly solution.</p> <p><strong>I want</strong> The block to adjust itself to the length of the text and vice versa</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>.p1 { background-color: green; border-style: solid; float: left; width: auto; height: 100px; } .block { display: block; width: 180px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;header&gt; &lt;h1&gt;Title&lt;/h1&gt; &lt;nav&gt;&lt;/nav&gt; &lt;/header&gt; &lt;main&gt; &lt;article class="p1"&gt; &lt;div class="block"&gt; &lt;h4&gt;Paragraph I&lt;/h4&gt; &lt;p&gt; Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. &lt;/p&gt; &lt;/div&gt; &lt;/article&gt; &lt;/main&gt; &lt;footer&gt;&lt;/footer&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74379659, "author": "0___________", "author_id": 6110094, "author_profile": "https://Stackoverflow.com/users/6110094", "pm_score": 1, "selected": false, "text": "extern volatile unsigned long timer0_millis;\n" }, { "answer_id": 74649568, "author": "RUBEN ESTRADA MARMOLEJO", "author_id": 18571788, "author_profile": "https://Stackoverflow.com/users/18571788", "pm_score": 0, "selected": false, "text": "//#include \"SevSeg.h\"\n int button1 = 11;\n int button2 = 12;\n int button3 = 13;\n int value = 10;\n int timer = 0;\n bool n = true;\n\n //Added\n int currentTime = 0;\n long int t0 = 0;\n long int t1 = 0;\n\n //SevSeg Display;\n void setup() {\n Serial.begin(9600);\n byte numDigits = 2;\n byte digitPins[] = {9,8};\n byte segmentPins[] = {10,2, 3, 4, 5, 6, 7,1};\n bool resistorsOnSegments = true;\n bool updateWithDelays = true;\n //byte hardwareConfig = COMMON_ANODE;\n //Display.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments);\n //Display.setBrightness(100);\n \n\n\n }\n void loop() {\n //Display.setNumber(value, 1);\n // Display.refreshDisplay();\n \n if (digitalRead(11)==HIGH){\n Start(value);\n } \n }\n\n\n void Start(int value){ \n t0 = millis();\n while(n){\n t1 = millis();\n if(t1 > (1000+t0)){\n //has passed 1 second\n currentTime++;\n if(value-currentTime == 0){\n n = false;\n }\n \n }\n unsigned long timerGlobal = t1-t0;\n //Display.setNumber(value-timerGlobal/1000, 1);\n //Display.refreshDisplay();\n \n \n }\n \n }\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20461760/" ]
74,379,639
<p>here I have tried to rewrite the query with cte cuz of good readability but when I try to rewrite the data is mismatched how to solve the problem for this?</p> <p>Query;</p> <pre><code>select count(1) as rage_tap from ue_summary.summary_funnel_1066 s join user_tasks_metadata utm on utm.asi = s.asi join user_tasks ut on ut.id = utm.user_task_id where s.seq_no = 1 and s.created_at between '2022-09-27 00:00:00' and '2022-10-27 00:00:00' and ut.is_ragetap = 1 Explain plan ; *************************** 1. row *************************** id: 1 select_type: SIMPLE table: ut partitions: NULL type: ref possible_keys: PRIMARY,idx_ir key: idx_ir key_len: 1 ref: const rows: 8413412 filtered: 100.00 Extra: Using index *************************** 2. row *************************** id: 1 select_type: SIMPLE table: utm partitions: NULL type: ref possible_keys: id_asi,asi key: id_asi key_len: 8 ref: ue_stage.ut.id rows: 1 filtered: 100.00 Extra: Using index *************************** 3. row *************************** id: 1 select_type: SIMPLE table: s partitions: NULL type: eq_ref possible_keys: PRIMARY,unique_asi_seq_no,seq_no_date,created_at,idx_combo,idx_seq_created_asi key: unique_asi_seq_no key_len: 12 ref: ue_stage.utm.asi,const rows: 1 filtered: 50.00 Extra: Using where; Using index </code></pre> <p>Table structure;</p> <pre><code>Create Table: CREATE TABLE `summary_funnel_1066` ( `funnel_id` int DEFAULT NULL, `app_id` int DEFAULT NULL, `platform` int DEFAULT NULL, `app_version_id` int NOT NULL, `seq_no` int NOT NULL, `property_id` bigint DEFAULT NULL, `property_name` varchar(255) DEFAULT NULL, `property_type` varchar(50) DEFAULT NULL, `asi` bigint NOT NULL, `created_at` datetime NOT NULL, `capture_time_relative` decimal(15,4) DEFAULT NULL, `last_event_id` bigint DEFAULT NULL, `last_event_name` varchar(100) DEFAULT NULL, `last_message_id` bigint DEFAULT NULL, `last_message_name` varchar(100) DEFAULT NULL, `last_tag_id` bigint DEFAULT NULL, `last_tag_name` varchar(100) DEFAULT NULL, `is_crash` tinyint DEFAULT NULL, `is_anr` tinyint DEFAULT NULL, `is_ragetap` tinyint DEFAULT NULL, `last_error_type_id` bigint DEFAULT NULL, `last_error_type` varchar(100) DEFAULT NULL, `screen_id` bigint DEFAULT NULL, `screen_name` varchar(100) DEFAULT NULL, `last_screen_id` bigint DEFAULT NULL, `last_screen_name` varchar(100) DEFAULT NULL, `user_task_id` bigint DEFAULT NULL, `ue_id` bigint DEFAULT NULL, PRIMARY KEY (`asi`,`seq_no`,`created_at`,`app_version_id`), UNIQUE KEY `unique_asi_seq_no` (`asi`,`seq_no`), KEY `seq_no_date` (`seq_no`,`created_at`), KEY `last_ids` (`last_screen_id`,`last_event_id`), KEY `idx_seq_created_asi`(seq_no,created_at,asi), KEY `created_at` (`created_at`), KEY `idx_combo` (`seq_no`,`property_id`,`property_name`,`created_at`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 Table: user_tasks_metadata Create Table: CREATE TABLE `user_tasks_metadata` ( `id` bigint NOT NULL AUTO_INCREMENT, `user_task_id` bigint NOT NULL, `device_id` bigint NOT NULL, `custom_user_id` bigint DEFAULT NULL, `asi` bigint NOT NULL DEFAULT '0', `session_id` varchar(300) DEFAULT NULL, `model` bigint DEFAULT NULL, `api_level` varchar(300) DEFAULT NULL, `app_version_id` bigint NOT NULL DEFAULT '0', `os_version` bigint DEFAULT NULL, `location` bigint DEFAULT NULL, `connection_speed` varchar(10) DEFAULT NULL, `network_operator` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8_general_ci DEFAULT NULL, `config_response` tinyint DEFAULT '1', `total_internal_memory` double(12,5) DEFAULT NULL, `available_internal_memory` double(12,5) DEFAULT NULL, `total_ram` double(12,5) DEFAULT NULL, `available_ram` double(12,5) DEFAULT NULL, `framework` varchar(45) DEFAULT '', `ue_sdk_version` mediumint DEFAULT NULL, `crash_type` bigint DEFAULT NULL, `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `user_profile_id` bigint DEFAULT NULL, `associated_custom_user_id` bigint DEFAULT NULL, `first_usr_interaction` bigint DEFAULT NULL, `app_launch_type` varchar(45) DEFAULT '', `app_launch_time` bigint DEFAULT '0', PRIMARY KEY (`id`), KEY `session_metadata_filter_idx` (`custom_user_id`,`device_id`), KEY `usertask_fk_idx` (`user_task_id`), KEY `idx_app_version` (`app_version_id`), KEY `asi_idx` (`asi`), KEY `device_id` (`device_id`), KEY `user_profile_id` (`user_profile_id`), KEY `id_asi` (`user_task_id`,`asi`), KEY `asi` (`asi`) ) ENGINE=InnoDB AUTO_INCREMENT=2252872743 DEFAULT CHARSET=latin1 Table: user_tasks Create Table: CREATE TABLE `user_tasks` ( `id` bigint NOT NULL AUTO_INCREMENT, `app_id` bigint NOT NULL, `status` tinyint NOT NULL DEFAULT '0', `app_version` varchar(100) DEFAULT NULL, `platform` tinyint NOT NULL DEFAULT '1', `exception_type` tinyint NOT NULL DEFAULT '0', `error_count` smallint NOT NULL DEFAULT '0', `crash_type` varchar(300) DEFAULT NULL, `crash_log` varchar(300) DEFAULT NULL, `avg_signal_level` int DEFAULT '0', `is_read` tinyint(1) NOT NULL DEFAULT '0', `is_important` tinyint(1) NOT NULL DEFAULT '0', `is_video_available` tinyint(1) NOT NULL DEFAULT '0', `is_video_played` tinyint(1) NOT NULL DEFAULT '0', `is_ex` tinyint(1) NOT NULL DEFAULT '0', `is_ragetap` tinyint(1) NOT NULL DEFAULT '0', `session_start_time` datetime DEFAULT NULL, `network_type` tinyint NOT NULL DEFAULT '0', `s3_video_url` varchar(255) DEFAULT NULL, `image_format` tinyint DEFAULT '0', `ue_release_version` smallint NOT NULL DEFAULT '0', `created_at` datetime NOT NULL, `updated_at` datetime DEFAULT NULL, `batch_created_at` datetime DEFAULT NULL, `sys_creation_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), KEY `session_filter_idx_2` (`app_id`,`platform`,`created_at`,`exception_type`,`app_version`), KEY `batch_created_idx` (`app_id`,`platform`,`batch_created_at`), KEY `app_id_created_at` (`app_id`,`created_at`), KEY `id_app_id` (`app_id`), KEY `idx_ir` (`is_ragetap`) ) ENGINE=InnoDB AUTO_INCREMENT=1648177712 DEFAULT CHARSET=latin1 </code></pre> <p>rewritten query;</p> <pre><code>with cte1 as ( select asi,count(1) as rage_tap from ue_summary.summary_funnel_1066 where s.seq_no = 1 and s.created_at between '2022-09-27 00:00:00' and '2022-10-27 00:00:00' ), cte2 as ( select id, count(*) 'rage_tap1' from user_tasks ut where is_ragetap = 1 ) select cte1.*,cte2.* from cte1 inner join user_tasks_metadata utm on utm.asi = cte1.asi inner join cte2 on b.id = utm.user_task_id </code></pre> <p>I need like below output;</p> <pre><code>+----------+ | rage_tap | +----------+ | 1812564 | +----------+ </code></pre> <p>It takes time to search so I choose cte, I have tried with subquery but it does not work and it takes around 30 sec - 1.14 min.</p> <p>as per this, I have indexed the column but also takes time : <a href="https://stackoverflow.com/questions/74232835/slow-performance-of-query-and-scanning-many-rows/74241052#74241052">slow performance of query and scanning many rows</a></p> <p>is there any other way to optimize it?</p>
[ { "answer_id": 74379659, "author": "0___________", "author_id": 6110094, "author_profile": "https://Stackoverflow.com/users/6110094", "pm_score": 1, "selected": false, "text": "extern volatile unsigned long timer0_millis;\n" }, { "answer_id": 74649568, "author": "RUBEN ESTRADA MARMOLEJO", "author_id": 18571788, "author_profile": "https://Stackoverflow.com/users/18571788", "pm_score": 0, "selected": false, "text": "//#include \"SevSeg.h\"\n int button1 = 11;\n int button2 = 12;\n int button3 = 13;\n int value = 10;\n int timer = 0;\n bool n = true;\n\n //Added\n int currentTime = 0;\n long int t0 = 0;\n long int t1 = 0;\n\n //SevSeg Display;\n void setup() {\n Serial.begin(9600);\n byte numDigits = 2;\n byte digitPins[] = {9,8};\n byte segmentPins[] = {10,2, 3, 4, 5, 6, 7,1};\n bool resistorsOnSegments = true;\n bool updateWithDelays = true;\n //byte hardwareConfig = COMMON_ANODE;\n //Display.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments);\n //Display.setBrightness(100);\n \n\n\n }\n void loop() {\n //Display.setNumber(value, 1);\n // Display.refreshDisplay();\n \n if (digitalRead(11)==HIGH){\n Start(value);\n } \n }\n\n\n void Start(int value){ \n t0 = millis();\n while(n){\n t1 = millis();\n if(t1 > (1000+t0)){\n //has passed 1 second\n currentTime++;\n if(value-currentTime == 0){\n n = false;\n }\n \n }\n unsigned long timerGlobal = t1-t0;\n //Display.setNumber(value-timerGlobal/1000, 1);\n //Display.refreshDisplay();\n \n \n }\n \n }\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20051145/" ]
74,379,718
<p>I have around 40 million records in my elasticsearch index. I want to calculate <strong>count of distinct values for combination of 2 fields.</strong></p> <p>Example for given set of documents:</p> <pre><code>[ { &quot;JobId&quot; : 2, &quot;DesigId&quot; : 12 }, { &quot;JobId&quot; : 2, &quot;DesigId&quot; : 4 }, { &quot;JobId&quot; : 3, &quot;DesigId&quot; : 5 }, { &quot;JobId&quot; : 2, &quot;DesigId&quot; : 4 }, { &quot;JobId&quot; : 3, &quot;DesigId&quot; : 5 } ] </code></pre> <p>For above example, I should get the <strong>count = 3</strong> as only 3 distinct values exists : [(2,12),(2,4),(3,5)]</p> <p>I tried using <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-cardinality-aggregation.html" rel="nofollow noreferrer">cardinality</a> aggregation for this but that provides an <strong>approximate count</strong>. I want to calculate the <strong>exact count accurately.</strong></p> <p>Below is the query which I used using cardinality aggregation:</p> <pre><code>&quot;aggs&quot;: { &quot;counts&quot;: { &quot;cardinality&quot;: { &quot;script&quot;: &quot;doc['JobId'].value + ',' + doc['DesigId'].value&quot;, &quot;precision_threshold&quot;: 40000 } } } </code></pre> <p>I also tried using <strong>composite aggregation</strong> on combination of 2 fields using <strong>after key</strong> and counting the overall size of buckets but that process is really time taking and my query is getting timed out.</p> <p><strong>Is there any optimal way to achieve it?</strong></p>
[ { "answer_id": 74379659, "author": "0___________", "author_id": 6110094, "author_profile": "https://Stackoverflow.com/users/6110094", "pm_score": 1, "selected": false, "text": "extern volatile unsigned long timer0_millis;\n" }, { "answer_id": 74649568, "author": "RUBEN ESTRADA MARMOLEJO", "author_id": 18571788, "author_profile": "https://Stackoverflow.com/users/18571788", "pm_score": 0, "selected": false, "text": "//#include \"SevSeg.h\"\n int button1 = 11;\n int button2 = 12;\n int button3 = 13;\n int value = 10;\n int timer = 0;\n bool n = true;\n\n //Added\n int currentTime = 0;\n long int t0 = 0;\n long int t1 = 0;\n\n //SevSeg Display;\n void setup() {\n Serial.begin(9600);\n byte numDigits = 2;\n byte digitPins[] = {9,8};\n byte segmentPins[] = {10,2, 3, 4, 5, 6, 7,1};\n bool resistorsOnSegments = true;\n bool updateWithDelays = true;\n //byte hardwareConfig = COMMON_ANODE;\n //Display.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments);\n //Display.setBrightness(100);\n \n\n\n }\n void loop() {\n //Display.setNumber(value, 1);\n // Display.refreshDisplay();\n \n if (digitalRead(11)==HIGH){\n Start(value);\n } \n }\n\n\n void Start(int value){ \n t0 = millis();\n while(n){\n t1 = millis();\n if(t1 > (1000+t0)){\n //has passed 1 second\n currentTime++;\n if(value-currentTime == 0){\n n = false;\n }\n \n }\n unsigned long timerGlobal = t1-t0;\n //Display.setNumber(value-timerGlobal/1000, 1);\n //Display.refreshDisplay();\n \n \n }\n \n }\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13378772/" ]
74,379,742
<p>Hi guuys Im trying to scrape some information about a shoe of zalando and save the price, the title, the day and the hour in differents variables using Seleinum webdriver.This is my code:</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.by import By import csv DRIVER_PATH = 'C:\chromedriver.exe' driver = webdriver.Chrome(executable_path=DRIVER_PATH) driver.get('https://www.zalando.es/release-calendar/zapatillas-mujer/') #Get the data of product 1 (If I change the /div/div[1]/div and I choose another number, it will get ther data of other shoe) product_1 = driver.find_element(By.XPATH, '//*[@id=&quot;release-calendar&quot;]/div/div[1]/div') element_text = product_1.text print(element_text) </code></pre> <p>When I print the element_text of the next code I get a lot of information about the product. I want to safe this in diferent variables so I tried one thing (keep reading)</p> <p>109,95 € Nike Sportswear WMNS DUNK LOW CZ 10 de noviembre de 2022, 8:15 Recordármelo</p> <p>So the thing is that after this little code works, I tried to split the data adding this code to then safe the diferent types of data in diferent variables, but I had a problem:</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.by import By import csv DRIVER_PATH = 'C:\chromedriver.exe' driver = webdriver.Chrome(executable_path=DRIVER_PATH) driver.get('https://www.zalando.es/release-calendar/zapatillas-mujer/') #Select product 1 product_1 = driver.find_element(By.XPATH, '//*[@id=&quot;release-calendar&quot;]/div/div[1]/div') element_text = product_1.text #Split the data element_text_split = element_text.split() #Price 1 --&gt; Result=109.95 price_1 =element_text_split[0] print(price_1) #Result=109,95 #Title 1 --&gt; Result=€ title_1 =element_text_split[1] print(title_1) </code></pre> <p>The result of this 2 prints are: &quot;109.95&quot; and &quot;€&quot;</p> <p>I was thinking that the element_text_split[1] was Nike Sportswear but no, its the € sign because Im splitting the data by the spaces between them.</p> <p>This is a big problem if I want to get the title of the shoe because the names doesnt have the sames spaces between them like : Nike Dunk Low Cz or Air Jordan One Mid 1</p> <p>How can I resolve this problem??Thaanks</p>
[ { "answer_id": 74380259, "author": "Jaky Ruby", "author_id": 10050775, "author_profile": "https://Stackoverflow.com/users/10050775", "pm_score": 2, "selected": true, "text": "# Needed libs\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\n# We create the driver\nDRIVER_PATH = 'C:\\chromedriver.exe'\ndriver = webdriver.Chrome(executable_path=DRIVER_PATH)\n\n# We maximize the window\ndriver.maximize_window()\n\n# We navigate to the url\nurl='https://www.zalando.es/release-calendar/zapatillas-mujer/'\ndriver.get(url)\n\n# We save a list of elements that are products (search for that xpath in the page and you will see what kind of element it is)\nproducts = WebDriverWait(driver, 20).until(EC.presence_of_all_elements_located((By.XPATH, \"//div[@id='release-calendar']//div[contains(@data-cid,'cid')]\")))\n\n# We make a loop for that list and for each of then we take the price, the brand, the model and the date.\nfor i, product in enumerate(products):\n price = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, f\"//div[@data-cid='cid{i+1}']/div[2]\"))).text\n brand = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, f\"//div[@data-cid='cid{i+1}']/div[3]\"))).text\n model = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, f\"//div[@data-cid='cid{i+1}']/div[4]\"))).text\n date = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, f\"//div[@data-cid='cid{i+1}']/div[5]\"))).text\n url = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, f\"//div[@data-cid='cid{i+1}']//a\"))).get_attribute(\"href\")\n image = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, f\"//div[@data-cid='cid{i+1}']//img\"))).get_attribute(\"src\")\n print(f\"\"\"{price}\n{brand}\n{model}\n{date}\n{url}\n{image}\n\"\"\")\n" }, { "answer_id": 74381204, "author": "Fazlul", "author_id": 12848411, "author_profile": "https://Stackoverflow.com/users/12848411", "pm_score": 0, "selected": false, "text": "from selenium import webdriver\nimport time\nfrom bs4 import BeautifulSoup\nfrom selenium.webdriver.chrome.service import Service\nimport pandas as pd\nwebdriver_service = Service(\"./chromedriver\") #Your chromedriver path\ndriver = webdriver.Chrome(service=webdriver_service)\n\nd = []\ndriver.get('https://www.zalando.es/release-calendar/zapatillas-mujer/')\ndriver.maximize_window()\ntime.sleep(5)\n\nsoup = BeautifulSoup(driver.page_source,\"html.parser\")\nprice= [x.get_text(strip=True) for x in soup.select('.Wqd6Qu + div')]\n#print(price)\ntitle= [x.get_text(strip=True) for x in soup.select('.Wqd6Qu + div + div + div')]\n#print(title)\n\ndate = [x.get_text(strip=True).split(',')[0] for x in soup.select('.Wqd6Qu + div + div + div + div')]\n#print(date)\n\n\nhour = [x.get_text(strip=True).split(',')[1] for x in soup.select('.Wqd6Qu + div + div + div + div')]\n#print(hour)\n\n\ncols = ['title', 'price', 'date', 'hour']\n \ndf = pd.DataFrame(data=list(zip(title,price,date,hour)), columns=cols)\nprint(df)\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16179319/" ]
74,379,743
<p>How would I go about implementing the onclick animation seen on this Google login form?</p> <p>As you click the button box, the placeholder text shrinks and moves to the top left and the button border forms around the text.</p> <p><a href="https://accounts.google.com/v3/signin/identifier?dsh=S906398310%3A1668018211534020&amp;flowName=GlifWebSignIn&amp;flowEntry=ServiceLogin&amp;ifkv=ARgdvAv8SiraKrw6QlE0WDM_jQ_IMyyYjxsvr8JLQ_L2BGzFth9-H3ZsW5aunSdhTVq1iMWqAgCTtg" rel="nofollow noreferrer">https://accounts.google.com/v3/signin/identifier?dsh=S906398310%3A1668018211534020&amp;flowName=GlifWebSignIn&amp;flowEntry=ServiceLogin&amp;ifkv=ARgdvAv8SiraKrw6QlE0WDM_jQ_IMyyYjxsvr8JLQ_L2BGzFth9-H3ZsW5aunSdhTVq1iMWqAgCTtg</a></p>
[ { "answer_id": 74379874, "author": "kumorin", "author_id": 16501128, "author_profile": "https://Stackoverflow.com/users/16501128", "pm_score": 2, "selected": true, "text": "<style>\n input:focus ~ .floating-label,\n input:not(:focus):valid ~ .floating-label{\n top: -6px;\n left: 0.5rem;\n padding: 0.5rem;\n font-size: 11px;\n opacity: 1;\n }\n\n .inputText {\n font-size: 14px;\n width: 200px;\n height: 35px;\n outline: 1px!important;\n }\n\n .floating-label {\n position: absolute;\n pointer-events: none;\n left: 1rem;\n transform: translateY(-50%);\n top: 50%;\n background: white;\n transition: 0.2s ease all;\n }\n\n</style>\n\n<div style=\"position:relative; display:inline;\">\n <input type=\"text\" class=\"inputText\" required/>\n <span class=\"floating-label\">Your email address</span>\n </div>\n \n" }, { "answer_id": 74379995, "author": "TrueStoryShort", "author_id": 20117831, "author_profile": "https://Stackoverflow.com/users/20117831", "pm_score": 0, "selected": false, "text": " <style>\n .wrapper {\n width: 100%;\n height: 50vh;\n display: flex;\n justify-content: center;\n align-items: center;\n }\n .wrapper .your-label {\n position: absolute;\n }\n\n #input:focus ~ .your-label,\n #input:valid ~ .your-label {\n background-color: yellow;\n color: blue;\n transform: translateY(-1rem);\n scale: 0.8;\n }\n </style>\n <body>\n <div class=\"wrapper\">\n <input id=\"input\" type=\"text\" required />\n <label class=\"your-label\" for=\"input\">Your Text</label>\n </div>\n </body>\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379743", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19991177/" ]
74,379,779
<p>I have a dataframe that lists political mandates with their start and end year. The question I want to answer is &quot;How many people (person_id) have had mandates that overlap in terms of years active?</p> <p>I've tried sequencing the active years as vectors, and then grouping and summarising by intersecting the vectors of active years.</p> <p>My input table</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>person_id</th> <th>start_year</th> <th>end_year</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>6</td> <td>1987</td> <td>1992</td> </tr> <tr> <td>2</td> <td>6</td> <td>1989</td> <td>1995</td> </tr> </tbody> </table> </div> <pre><code>mandates_active &lt;- mandates %&gt;% mutate(active_years = map2(mandate_start_year, mandate_end_year, seq)) </code></pre> <p>I get an additional column with the sequenced active years:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>person_id</th> <th>start_year</th> <th>end_year</th> <th>active_years</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>6</td> <td>1987</td> <td>1992</td> <td>[1987, 1988, 1989 ...]</td> </tr> <tr> <td>2</td> <td>6</td> <td>1989</td> <td>1995</td> <td>[1989, 1990, 1991 ...]</td> </tr> </tbody> </table> </div> <p>Then I try to group this bz person_id and summarise by intersecting the active years list, but I need two arguments for the intersect function, hence this doesn't work:</p> <pre><code>mandates_test &lt;- mandates_active %&gt;% group_by(person_id) %&gt;% summarise(intersect(active_years)) </code></pre> <p>My output would show which person_ids have had multiple mandates during overlapping years.</p>
[ { "answer_id": 74380037, "author": "Ric Villalba", "author_id": 6912817, "author_profile": "https://Stackoverflow.com/users/6912817", "pm_score": 0, "selected": false, "text": "library(dplyr)\nlibrary(tidyr)\n\nset.seed(123)\n#Data example\nstart_year <- sample(1957:2003, 12, T)\nend_year <- start_year + sample(1:4, 12,T) \ndata <- data.frame(person_id = 1:12, start_year, end_year)\n\ndata\n#> person_id start_year end_year\n#> 1 1 1987 1990\n#> 2 2 1971 1974\n#> 3 3 1970 1971\n#> 4 4 1959 1963\n#> 5 5 1998 1999\n#> 6 6 1999 2000\n#> 7 7 1993 1994\n#> 8 8 1970 1973\n#> 9 9 1981 1985\n#> 10 10 1982 1984\n#> 11 11 1983 1986\n#> 12 12 1961 1963\n\n# Unroll the intervals into registers:\npers_years <- data %>% rowwise() %>% \n mutate(years = list(start_year:end_year)) %>% \n unnest(years) \n" }, { "answer_id": 74380292, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 1, "selected": false, "text": "data.frame(df %>%\n rowwise() %>%\n summarize(id, person_id, f = seq(start_year, end_year, 1)) %>%\n group_by(person_id) %>%\n summarize(overlapping_years = list(f[duplicated(f)])))\n person_id overlapping_years\n1 6 1989, 1990, 1991, 1992\n2 7\n3 8 1992\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20451876/" ]
74,379,799
<p>I'm trying to compare a value in list to a integer. can someone help how to do that</p> <pre><code>list = [1] if list == number: print(number) </code></pre> <p>I want some thing like above, how to do</p>
[ { "answer_id": 74380037, "author": "Ric Villalba", "author_id": 6912817, "author_profile": "https://Stackoverflow.com/users/6912817", "pm_score": 0, "selected": false, "text": "library(dplyr)\nlibrary(tidyr)\n\nset.seed(123)\n#Data example\nstart_year <- sample(1957:2003, 12, T)\nend_year <- start_year + sample(1:4, 12,T) \ndata <- data.frame(person_id = 1:12, start_year, end_year)\n\ndata\n#> person_id start_year end_year\n#> 1 1 1987 1990\n#> 2 2 1971 1974\n#> 3 3 1970 1971\n#> 4 4 1959 1963\n#> 5 5 1998 1999\n#> 6 6 1999 2000\n#> 7 7 1993 1994\n#> 8 8 1970 1973\n#> 9 9 1981 1985\n#> 10 10 1982 1984\n#> 11 11 1983 1986\n#> 12 12 1961 1963\n\n# Unroll the intervals into registers:\npers_years <- data %>% rowwise() %>% \n mutate(years = list(start_year:end_year)) %>% \n unnest(years) \n" }, { "answer_id": 74380292, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 1, "selected": false, "text": "data.frame(df %>%\n rowwise() %>%\n summarize(id, person_id, f = seq(start_year, end_year, 1)) %>%\n group_by(person_id) %>%\n summarize(overlapping_years = list(f[duplicated(f)])))\n person_id overlapping_years\n1 6 1989, 1990, 1991, 1992\n2 7\n3 8 1992\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16600302/" ]
74,379,809
<p>The entire error:</p> <blockquote> <p>The foreign key property 'Appointment.CustomerId1' was created in a shadow state because a conflicting property with the simple name 'CustomerId' exists in the entity type, but is either not mapped, is already used for another relationship, or is incompatible with the associated primary key type.</p> </blockquote> <p>Tables:</p> <p><a href="https://i.stack.imgur.com/JlJtj.png" rel="nofollow noreferrer">Appointment </a></p> <p><a href="https://i.stack.imgur.com/Jim7x.png" rel="nofollow noreferrer">User</a></p> <p>In the Appointment table, I had 2 FKs: one pointing to the Customer Table (Id Column) and the other to Employee Table (Id Column). See the picture at the BEFORE section. But now, because I will have all users (customer + employee) in the same table User, it has to change. That means that in the Appointment table I need to have 2 FKs but both need to point to the same table User, and the Id column. I want the CustomerId and EmployeeId to point to the Id from the User.</p> <p>It creates 3 extra columns: UserId, CustomerId1, and EmployeeId1--which I don't want. I only used Conventions for the relationships, no Data Annotations or Fluent API.</p> <p>There are 3 things that can cause the error:</p> <ul> <li> <ol> <li>not mapped</li> </ol> </li> <li> <ol start="2"> <li>already used for another relationship</li> </ol> </li> <li> <ol start="3"> <li>incompatible with the associated primary key type</li> </ol> </li> </ul> <p>By my understanding</p> <ul> <li> <ol start="3"> <li>is not my case, because the data type is the same (string).</li> </ol> </li> <li> <ol start="2"> <li>is not my case because I have no other relationship.</li> </ol> </li> <li> <ol> <li>There might be a problem but I'm not sure. I might need to add some Fluent Api for this mapping. This is what I've tried but it's not working: <a href="https://i.stack.imgur.com/UFrC6.png" rel="nofollow noreferrer">https://i.stack.imgur.com/UFrC6.png</a></li> </ol> </li> </ul> <p>Bi-directional method:</p> <p>User class:</p> <pre><code>public ICollection&lt;Appointment&gt; AppointmentCustomers { get; set; } public ICollection&lt;Appointment&gt; AppointmentEmployees { get; set; } </code></pre> <p>Appointment class:</p> <pre><code>public string CustomerId { get; set; } [ForeignKey(&quot;CustomerId&quot;)] public User Customer { get; set; } public string EmployeeId { get; set; } [ForeignKey(&quot;EmployeeId&quot;)] public User Employee { get; set; } </code></pre> <p>OnModelCreating method:</p> <pre><code>builder.Entity&lt;Appointment&gt;() .HasOne(u =&gt; u.Customer) .WithMany(app =&gt; app.AppointmentCustomers) .HasForeignKey(u =&gt; u.CustomerId) .OnDelete(DeleteBehavior.NoAction); builder.Entity&lt;Appointment&gt;() .HasOne(u =&gt; u.Employee) .WithMany(app =&gt; app.AppointmentEmployees) .HasForeignKey(u =&gt; u.EmployeeId) .OnDelete(DeleteBehavior.NoAction); </code></pre>
[ { "answer_id": 74381351, "author": "Steve Py", "author_id": 423497, "author_profile": "https://Stackoverflow.com/users/423497", "pm_score": 3, "selected": true, "text": "[ForeignKey]" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16711792/" ]
74,379,846
<p>I can add to the <code>context</code> in the <code>serve</code> method for a page, and get the context variable in the page template. I cannot seem to add to the context in <code>get_context</code>; or, access it in the page template. This is stumping me.</p> <p>I'd like to add a variable or two to the context using the get_context function, and access that in the page template.</p> <pre><code># If request.user is authenticated AND is registered for this event # set that in the context # ###---THIS DOES SEEM TO ADD TO CONTEXT, OR # ###---IF IT DOES, THEN CANNOT ACCESS IT IN THE TEMPLATE--### # def get_context(self, request, *args, **kwargs): # # pdb.set_trace() # context = super(EventPage, self).get_context(request, *args, **kwargs) # if request.user.is_authenticated: # # pdb.set_trace() # for attendee in self.event.eventattendee_set.all(): # if attendee.email == request.user.email: # # user is an attendee for this event # context[&quot;is_attendee&quot;] = True # break # context[&quot;hello&quot;] = &quot;hello&quot; # return context </code></pre>
[ { "answer_id": 74381351, "author": "Steve Py", "author_id": 423497, "author_profile": "https://Stackoverflow.com/users/423497", "pm_score": 3, "selected": true, "text": "[ForeignKey]" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20460884/" ]
74,379,850
<p>I am learning about data handling in python, trying to handle weather data from each day of October. The data is from a local csv. I Iterate for day of the month and iterating for each hour inside of it. I have a class object handling data for each day. The class object is being initialized right after the iteration of each day. The issue is, that this object doesn't get re-initialized after each iteration. I have made som test object below it. The one differens between the test object and the object is, that the object is an object inside of a subfolder containing all my data handling. The object contains a list of data container class objects, whose origin is in the same directory.</p> <p>-- Main class --</p> <p>`</p> <pre><code>import os import csv from Data.VejrData import * #Test class class Ekstra: streng: str = &quot;&quot; class Vejr: currentDirectory: str = os.getcwd() dataDirectory: str = 'Data/vejrdata/' folder = os.listdir(currentDirectory+&quot;/&quot;+dataDirectory) days: list[VejrData] = [] def __init__(self): self.main() def fetchData(self): for file in self.folder: vejrData = VejrData() #Error! #For each file vejrData should be reset, but doesn't #For each file(31 iterations), all rows from the 32 iterations are being added(25 each * 31 = 248000 sets of data) #Testing string = &quot;&quot; string += &quot;New day&quot; print(string) #Testing if the same happens with an empty class object. ekstra = Ekstra() ekstra.streng += &quot;New day&quot; print(ekstra.streng) #This variable from class object does get reset. #VejrData doesn't. #Opens datafile from a specifik date. with open(f&quot;{self.dataDirectory}{file}&quot;, 'r') as data: csvreader = csv.reader(data) number = 0 for row in csvreader: number += 1 index: int = 0 #iterates each element of data in a string. for textData in row[0].split(&quot;;&quot;): vejrData.constructData(index, textData) index += 1 self.days.append(vejrData) def main(self): self.fetchData() print(len(self.days)) for day in self.days: print(len(day.timeData)) vejr = Vejr() </code></pre> <p>` printing from main function results in: len(self.days) = 32 Length of set of hourly data in each day = 775 for all of the 32 days. 775/25(24 + 1 header) = 31</p> <p>-- Data Handling -- `</p> <pre><code>from .TimeData import TimeData #https://docs.python.org/3/tutorial/modules.html#intra-package-references class VejrData: #Lists containing hourly data timeData: list[TimeData] = [] #Variable retrieving data before being added to list. DataBuilder: None #Distributing data from index: index 0 = time data, index 1 = prec data ... def constructData(self,index: int, data): #https://www.freecodecamp.org/news/python-switch-statement-switch-case-example/ match index: case 0: self.DataBuilder = TimeData() self.DataBuilder.tid = data case 1: self.DataBuilder.prec = data case 2: self.DataBuilder.metp = data case 3: self.DataBuilder.megrtp = data case 4: self.DataBuilder.mesotp10 = data case 5: self.DataBuilder.meanwv = data self.timeData.append(self.DataBuilder) self.DataBuilder = None case _: print(f&quot;Error - Index not at index: {index}, is out of range.&quot;) </code></pre> <p>`</p> <p>-- Container class -- `</p> <pre><code>class TimeData: tid: int prec: float metp: float megrtp: float mesotp10: float meanwv: float </code></pre> <p>`</p> <p>The structure is as such /Vejr.py, /Data/VejrData &amp; /Data/TimeData. No errors related to the pathing occurs. I could just give it a new variable at the end of each loop, but that seems off, to be doing what the loop is supposed to do.</p> <p>I have tried testing whether re-initialization isn't intended to be happening in for loops. I created some objects to see whether or not they would be affected by it. I started with string variable. As the string variable was re-initialized I tried with another class object located in the same file, changed a variable inside of it and saw it re-initialize as well.</p> <p>So variables and class objects are intended to be re-initialized in each iteration.</p>
[ { "answer_id": 74381351, "author": "Steve Py", "author_id": 423497, "author_profile": "https://Stackoverflow.com/users/423497", "pm_score": 3, "selected": true, "text": "[ForeignKey]" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7343017/" ]
74,379,867
<p>I am making something which allows logged user to report their lost items to the firestore firebase. Now what I've done successfully registers details of the user's report to the 'reports'collection.</p> <p>but everytime the same user reports another item, the details of previously reported item gets overwritten. I want it in such a way that the new report gets added to the same collection, without overwriting the previous one. Something like in an array, in which when u add an item, it doesn't get overwritten, but adds to the array</p> <p>i have done this</p> <pre><code> await setDoc(doc(db,&quot;reports&quot;,auth.currentUser.uid),{ description: descref.current.value, email: auth.currentUser.email, timestamp: serverTimestamp(), }).then(async () =&gt;{ if (image) { const storageRef = ref(storage,`images/${ image.name + auth.currentUser.uid }`) const uploadTask = uploadBytesResumable(storageRef,image); setimage(null); uploadTask.on( 'state_changed', null, (err) =&gt; console.log(err), () =&gt; { // download url getDownloadURL(uploadTask.snapshot.ref).then(async (url) =&gt; { console.log(url); //adding the image URL to collection await setDoc(doc(db,'reports', auth.currentUser.uid ),{imgurl:url},{merge:true}); It looks like this [(https://i.stack.imgur.com/SYo73.png)](https://i.stack.imgur.com/SYo73.png) </code></pre> <pre><code>but whenever i upload new data, the previous one gets overwritten. </code></pre> <p>what i want is this</p> <pre><code>{   &quot;posts&quot;: {     &quot;0&quot;: {       &quot;author&quot;: &quot;gracehop&quot;,       &quot;title&quot;: &quot;Announcing COBOL, a New Programming Language&quot;     },     &quot;1&quot;: {       &quot;author&quot;: &quot;alanisawesome&quot;,       &quot;title&quot;: &quot;The Turing Machine&quot;     }   } } </code></pre> <p>can anyone help how to do this?</p>
[ { "answer_id": 74381351, "author": "Steve Py", "author_id": 423497, "author_profile": "https://Stackoverflow.com/users/423497", "pm_score": 3, "selected": true, "text": "[ForeignKey]" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20359012/" ]
74,379,871
<p>I am trying running a code in Android Studio, but always I run the code, get this error:</p> <p>Error: No named parameter with the name 'controller'.</p> <pre><code>TextEditingController nota1Controller = TextEditingController(); </code></pre> <pre><code>nota1Controller.text = &quot;&quot;; </code></pre> <pre><code>double nota1 = double.parse(nota1Controller.text); </code></pre> <pre><code>TextField( keyboardType: TextInputType.number, decoration: InputDecoration( labelText: &quot;Nota 1&quot;, labelStyle: TextStyle(color: Colors.green), controller: nota1Controller,// &lt;-- HERE IT'S THE &quot;CONTROLLER&quot; ), textAlign: TextAlign.center, style: TextStyle(color: Colors.green, fontSize: 25.0), ), </code></pre> <p>I navigate in a lot of sites, but I can't find a solution</p>
[ { "answer_id": 74380008, "author": "7eg", "author_id": 13311722, "author_profile": "https://Stackoverflow.com/users/13311722", "pm_score": 1, "selected": false, "text": " TextField(\n keyboardType: TextInputType.number,\n decoration: InputDecoration(\n labelText: \"Nota 1\",\n labelStyle: TextStyle(color: Colors.green),\n controller: nota1Controller, <-- HERE IT'S THE \"CONTROLLER\"\n ),\n textAlign: TextAlign.center,\n style: TextStyle(color: Colors.green, fontSize: 25.0),\n),\n" }, { "answer_id": 74380014, "author": "Rohan Jariwala", "author_id": 13954519, "author_profile": "https://Stackoverflow.com/users/13954519", "pm_score": 1, "selected": true, "text": "TextField(\n controller: nota1Controller,//<-- HERE IT'S THE \"CONTROLLER\"\nkeyboardType: TextInputType.number,\n decoration: InputDecoration(\n labelText: \"Nota 1\",\n labelStyle: TextStyle(color: Colors.green),\n ),\n textAlign: TextAlign.center,\n style: TextStyle(color: Colors.green, fontSize: 25.0),\n ),\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18042322/" ]
74,379,880
<p>I'm trying to join a table onto another table. The gimmick here is that the column from the table contains a long string. Something like this:</p> <pre><code> PageNumber-190-ChapterTitle-HelloThere PageNumber-19-ChapterTitle-NotToday </code></pre> <p>I have another table that has a list of page numbers and whether or not I want to keep those pages, for example:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Page Number</th> <th>Keep Flag</th> </tr> </thead> <tbody> <tr> <td>190</td> <td>Y</td> </tr> <tr> <td>19</td> <td>N</td> </tr> </tbody> </table> </div> <p>I want to be able to return a query that contains the long string but only if the page number exists somewhere in the string. The problem I have is that, when using a LIKE statement to join:</p> <pre><code>JOIN t2 ON t1.string LIKE '%' + t2.page_number + '%' WHERE keep_flag = 'Y' </code></pre> <p>It will still return both results for whatever reason. The column of &quot;Keep Flag&quot; in the results query will change to &quot;Y&quot; for page 19 even though it shouldn't be in the results.</p> <p>I obviously don't think LIKE is the best way to JOIN given that '19' is LIKE '190'. What else can I do here?</p>
[ { "answer_id": 74379983, "author": "nbk", "author_id": 5193536, "author_profile": "https://Stackoverflow.com/users/5193536", "pm_score": 0, "selected": false, "text": "CREATE TABLE tab1\n ([str] varchar(38))\n;\n \nINSERT INTO tab1\n ([str])\nVALUES\n ('PageNumber-190-ChapterTitle-HelloThere'),\n ('PageNumber-19-ChapterTitle-NotToday')\n;\n\n" }, { "answer_id": 74380097, "author": "Yitzhak Khabinsky", "author_id": 1932311, "author_profile": "https://Stackoverflow.com/users/1932311", "pm_score": 1, "selected": false, "text": "JOIN" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18485985/" ]
74,379,893
<p>I have a Picker with menu style presenting a label with an icon and text. When applying a padding to any views containing the picker, the picker will behave as though there is not enough space and run to multiple lines even though there is enough space.</p> <p>Sample Code</p> <pre><code>struct ContentView: View { let options = [ &quot;Some Long Text&quot; ] private var selectedOption: Binding&lt;String&gt; = .constant(&quot;Some Long Text&quot;) var body: some View { HStack { Text(&quot;Some Text&quot;) Picker(&quot;Work Type&quot;, selection: selectedOption) { ForEach(self.options, id: \.self) { Label($0, systemImage: &quot;pencil.tip.crop.circle&quot;) } }.pickerStyle(.menu) } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { VStack { ContentView() ContentView() .padding() } } } </code></pre> <p><a href="https://i.stack.imgur.com/Tkyx5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Tkyx5.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74388243, "author": "Mischa", "author_id": 2062785, "author_profile": "https://Stackoverflow.com/users/2062785", "pm_score": 1, "selected": false, "text": "fixedSize()" }, { "answer_id": 74388419, "author": "Cheezzhead", "author_id": 2542661, "author_profile": "https://Stackoverflow.com/users/2542661", "pm_score": 0, "selected": false, "text": "HStack" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1684508/" ]
74,379,906
<p>I have an issue with react navigation. I would like to have the same behavior as the linkedIn app has. I mean, in that app, you can open the settings page from the drawer in differents tabs. You can open it from the first tab, second one... and so on. and at the end you get multiple instances.</p> <p>I am not able to reproduce this behavior</p> <p>My navigation is: One drawer with one drawer screen (one Tab navigator inside). 3 tabs screens inside that Tab navigator. Each one contains a stack. I have set the same screens in that screen. For example I want to share the Profile, so I have one profile screen in each tab.</p> <p>In the customDrawer I navigate to screens name, but here is the problem. React navigation does not know what stack should call before calling the right screen. And I cannot find a way to know the current mounted stack so I cannot set it dinamically in order to do inside the custom drawer:</p> <pre><code> onPress={() =&gt; props.navigation.navigate(Routes.student.home.STACK, { screen: Routes.student.SETTINGS }) } </code></pre> <p>Thanks!</p> <p><code>App.tsx</code></p> <pre><code>/* eslint-disable react-native/no-inline-styles */ import 'react-native-gesture-handler'; import React from 'react'; import { Text } from 'react-native'; import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'; import { createDrawerNavigator, DrawerContentScrollView, DrawerItem, } from '@react-navigation/drawer'; import { NavigationContainer } from '@react-navigation/native'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { StatusBar } from 'expo-status-bar'; import HomeStackScreen from '@pages/Home'; import { Routes } from '@src/constants/routes'; import { PracticalStackScreen } from '@src/pages/Practical/Practical'; import { TheoryStackScreen } from '@src/pages/Theory/Theory'; // Create a client const queryClient = new QueryClient(); const Tab = createBottomTabNavigator(); const Drawer = createDrawerNavigator(); const TabNavigator = () =&gt; { return ( &lt;Tab.Navigator screenOptions={{ headerShown: false }} initialRouteName={Routes.student.home.STACK} &gt; &lt;Tab.Screen name={Routes.student.theory.STACK} component={TheoryStackScreen} options={{ title: 'TEÓRICO' }} /&gt; &lt;Tab.Screen name={Routes.student.home.STACK} component={HomeStackScreen} options={{ title: '' }} /&gt; &lt;Tab.Screen name={Routes.student.practical.STACK} component={PracticalStackScreen} options={{ title: 'PRÁCTICO' }} /&gt; &lt;/Tab.Navigator&gt; ); }; function CustomDrawerContent(props: any) { console.log('props ', props); return ( &lt;DrawerContentScrollView {...props}&gt; &lt;Text&gt;Mi cuenta&lt;/Text&gt; &lt;DrawerItem label='Configuración' onPress={() =&gt; props.navigation.navigate(Routes.student.SETTINGS)} /&gt; &lt;DrawerItem label='Métodos de pago' onPress={() =&gt; props.navigation.navigate(Routes.student.PAYMENT)} /&gt; &lt;Text&gt;Social&lt;/Text&gt; &lt;DrawerItem label='Tiktok' onPress={() =&gt; props.navigation.navigate(Routes.student.PROFILE)} /&gt; &lt;Text&gt;Ayuda&lt;/Text&gt; &lt;DrawerItem label='Preguntas frecuentes' onPress={() =&gt; props.navigation.navigate(Routes.student.FAQ)} /&gt; &lt;DrawerItem label='Atención al alumno' onPress={() =&gt; props.navigation.navigate(Routes.student.STUDENT_SUPPORT)} /&gt; &lt;/DrawerContentScrollView&gt; ); } const DrawerNavigation = () =&gt; { return ( &lt;Drawer.Navigator useLegacyImplementation={true} drawerContent={(props) =&gt; &lt;CustomDrawerContent {...props} /&gt;} initialRouteName={Routes.student.home.STACK} &gt; &lt;Drawer.Screen name={Routes.MAIN_TAB} component={TabNavigator} /&gt; &lt;/Drawer.Navigator&gt; ); }; export default function App() { return ( &lt;QueryClientProvider client={queryClient}&gt; &lt;StatusBar /&gt; &lt;NavigationContainer&gt; &lt;DrawerNavigation /&gt; &lt;/NavigationContainer&gt; &lt;/QueryClientProvider&gt; ); } </code></pre> <p><code>Home.tsx</code></p> <pre><code>/* eslint-disable react-native/no-color-literals */ import React from 'react'; import { StyleSheet, Text, View, Pressable } from 'react-native'; import { createNativeStackNavigator } from '@react-navigation/native-stack'; import { Routes } from '@src/constants/routes'; import Faq from '../Faq'; import Payment from '../Payment'; import Profile from '../Profile'; import Settings from '../Settings'; import StudentSupport from '../StudentSupport'; const HomeStack = createNativeStackNavigator(); export const HomeStackScreen = (): JSX.Element =&gt; { return ( &lt;HomeStack.Navigator screenOptions={{ headerStyle: { backgroundColor: 'red' }, headerShown: false }} &gt; &lt;HomeStack.Screen name={Routes.student.home.MAIN} component={Home} /&gt; &lt;HomeStack.Screen name={Routes.student.PROFILE} component={Profile} /&gt; &lt;HomeStack.Screen name={Routes.student.SETTINGS} component={Settings} /&gt; &lt;HomeStack.Screen name={Routes.student.PAYMENT} component={Payment} /&gt; &lt;HomeStack.Screen name={Routes.student.FAQ} component={Faq} /&gt; &lt;HomeStack.Screen name={Routes.student.STUDENT_SUPPORT} component={StudentSupport} /&gt; &lt;/HomeStack.Navigator&gt; ); }; export const Home = ({ navigation }: any): JSX.Element =&gt; ( &lt;View style={styles.container}&gt; &lt;Text&gt;Home Screen&lt;/Text&gt; &lt;Pressable style={styles.button} onPress={() =&gt; navigation.navigate(Routes.student.PROFILE)}&gt; &lt;Text style={styles.text}&gt;Perfil&lt;/Text&gt; &lt;/Pressable&gt; &lt;/View&gt; ); const backgroundColor = '#fff'; const styles = StyleSheet.create({ button: { alignItems: 'center', backgroundColor: 'grey', borderRadius: 4, elevation: 3, justifyContent: 'center', paddingHorizontal: 32, paddingVertical: 12, }, container: { alignItems: 'center', backgroundColor, flex: 1, justifyContent: 'center', }, text: { color: 'white', fontSize: 16, fontWeight: 'bold', letterSpacing: 0.25, lineHeight: 21, }, }); </code></pre> <p><code>Theroy.tsx</code></p> <pre><code>import React from 'react'; import { Button, StyleSheet, Text, View } from 'react-native'; import { createNativeStackNavigator } from '@react-navigation/native-stack'; import { Routes } from '@src/constants/routes'; import Faq from '../Faq'; import Payment from '../Payment'; import Profile from '../Profile'; import Settings from '../Settings'; import StudentSupport from '../StudentSupport'; const TheoryStack = createNativeStackNavigator(); export const TheoryStackScreen = (): JSX.Element =&gt; { return ( &lt;TheoryStack.Navigator screenOptions={{ headerStyle: { backgroundColor: 'red' }, headerShown: false }} &gt; &lt;TheoryStack.Screen name={Routes.student.theory.MAIN} component={Theory} /&gt; &lt;TheoryStack.Screen name={Routes.student.PROFILE} component={Profile} /&gt; &lt;TheoryStack.Screen name={Routes.student.SETTINGS} component={Settings} /&gt; &lt;TheoryStack.Screen name={Routes.student.PAYMENT} component={Payment} /&gt; &lt;TheoryStack.Screen name={Routes.student.FAQ} component={Faq} /&gt; &lt;TheoryStack.Screen name={Routes.student.STUDENT_SUPPORT} component={StudentSupport} /&gt; &lt;/TheoryStack.Navigator&gt; ); }; export function Theory({ navigation }: any): JSX.Element { return ( &lt;View style={styles.container}&gt; &lt;Text&gt;Theory Screen&lt;/Text&gt; &lt;Button title='Go to Home' onPress={() =&gt; navigation.navigate(Routes.student.home.STACK)} /&gt; &lt;Button title='Go to Practical' onPress={() =&gt; navigation.navigate(Routes.student.practical.STACK)} /&gt; &lt;Button title='Go to Profile' onPress={() =&gt; navigation.navigate(Routes.student.home.STACK, { screen: Routes.student.PROFILE }) } /&gt; &lt;/View&gt; ); } const backgroundColor = '#fff'; const styles = StyleSheet.create({ container: { alignItems: 'center', backgroundColor, flex: 1, justifyContent: 'center', }, }); </code></pre> <p><code>Practical.tsx</code></p> <pre><code>import React from 'react'; import { Button, StyleSheet, Text, View } from 'react-native'; import { createNativeStackNavigator } from '@react-navigation/native-stack'; import { Routes } from '@src/constants/routes'; import Faq from '../Faq'; import Payment from '../Payment'; import Profile from '../Profile'; import Settings from '../Settings'; import StudentSupport from '../StudentSupport'; const PracticalStack = createNativeStackNavigator(); export const PracticalStackScreen = (): JSX.Element =&gt; { return ( &lt;PracticalStack.Navigator screenOptions={{ headerStyle: { backgroundColor: 'red' }, headerShown: false }} &gt; &lt;PracticalStack.Screen name={Routes.student.practical.MAIN} component={Practical} /&gt; &lt;PracticalStack.Screen name={Routes.student.PROFILE} component={Profile} /&gt; &lt;PracticalStack.Screen name={Routes.student.SETTINGS} component={Settings} /&gt; &lt;PracticalStack.Screen name={Routes.student.PAYMENT} component={Payment} /&gt; &lt;PracticalStack.Screen name={Routes.student.FAQ} component={Faq} /&gt; &lt;PracticalStack.Screen name={Routes.student.STUDENT_SUPPORT} component={StudentSupport} /&gt; &lt;/PracticalStack.Navigator&gt; ); }; export function Practical({ navigation }: any): JSX.Element { return ( &lt;View style={styles.container}&gt; &lt;Text&gt;Practical Screen&lt;/Text&gt; &lt;Button title='Go to Home' onPress={() =&gt; navigation.navigate(Routes.student.home.STACK)} /&gt; &lt;Button title='Go to Theory' onPress={() =&gt; navigation.navigate(Routes.student.theory.STACK)} /&gt; &lt;Button title='Go to Profile' onPress={() =&gt; navigation.navigate(Routes.student.home.STACK, { screen: Routes.student.PROFILE }) } /&gt; &lt;/View&gt; ); } const backgroundColor = '#fff'; const styles = StyleSheet.create({ container: { alignItems: 'center', backgroundColor, flex: 1, justifyContent: 'center', }, }); </code></pre>
[ { "answer_id": 74388243, "author": "Mischa", "author_id": 2062785, "author_profile": "https://Stackoverflow.com/users/2062785", "pm_score": 1, "selected": false, "text": "fixedSize()" }, { "answer_id": 74388419, "author": "Cheezzhead", "author_id": 2542661, "author_profile": "https://Stackoverflow.com/users/2542661", "pm_score": 0, "selected": false, "text": "HStack" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9747939/" ]
74,379,933
<p>I have my array with data referring to different subjects divided in 3 different groups</p> <p><code>A = ([12, 13, 15], [13, 16, 18], [15, 15, 17])</code></p> <p>I want to append these to 3 different arrays, but I don't want to do it &quot;manually&quot; since I should use this code for bigger set of data. So, I was looking for a way to create as many arrays as the amount of subjects (in this case 3) assigning to them different &quot;names&quot;.</p> <p>Looking on this site I ended up using a dictionary and this is what I did</p> <pre><code>number_of_groups = len(A) </code></pre> <pre><code>groups = {&quot;group&quot; + str(i+1) : [] for i in range(number_of_groups)} </code></pre> <p>and this is the output:</p> <p><code>{'group1': [], 'group2': [], 'group3': []}</code></p> <p>now I wasn't able to append to each of them the 3 different set of data. I expect to have:</p> <p><code>{'group1': [12, 13, 15], 'group2': [13, 16, 18], 'group3': [15, 15, 17]}</code></p> <p>I tried this (I know is not a good way to do it...)</p> <pre><code>for n in A: for key in paths: paths[key].append(n) </code></pre> <p>output:</p> <pre><code>{'group1': [array([12, 13, 15]),array([13, 16, 18]),array([15, 15, 17])], </code></pre> <pre><code>'group2': [array([12, 13, 15]),array([13, 16, 18]),array([15, 15, 17])], </code></pre> <pre><code>'group3': [array([12, 13, 15]),array([13, 16, 18]),array([15, 15, 17])]} </code></pre>
[ { "answer_id": 74388243, "author": "Mischa", "author_id": 2062785, "author_profile": "https://Stackoverflow.com/users/2062785", "pm_score": 1, "selected": false, "text": "fixedSize()" }, { "answer_id": 74388419, "author": "Cheezzhead", "author_id": 2542661, "author_profile": "https://Stackoverflow.com/users/2542661", "pm_score": 0, "selected": false, "text": "HStack" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19719303/" ]
74,379,944
<p>After clicking on the FavoriteIcon inside the ExamplesCard all the icons turn red instead of just one icon. I'm using useState to change icon state value between true and false and style to change icon color.</p> <p><strong>Componenet ExamplesCard.tsx</strong></p> <pre><code>import * as React from &quot;react&quot;; import { Box, Card, CardActionArea, CardActions, CardContent, CardMedia, Grid, Typography } from &quot;@mui/material&quot;; import FavoriteIcon from &quot;@mui/icons-material/Favorite&quot;; import { ButtonProps } from &quot;./ButtonProps&quot;; import data from &quot;./data/data.json&quot;; import { useState } from &quot;react&quot;; export default function ExemplesCard() { const [iconFavorite, setIconFavorite] = useState(false); const ChangeColorFavorite = () =&gt; { setIconFavorite(!iconFavorite); }; return ( &lt;Box sx={{ flexGrow: 1, margin: &quot;0 2rem&quot; }}&gt; &lt;Grid container justifyContent=&quot;center&quot; spacing={{ xs: 8, sm: 8, md: 8, lg: 8, xl: 8 }} className=&quot;GRID1&quot; &gt; {data.map((item) =&gt; { return ( &lt;Grid item xs={12} sm={6} md={4} lg={3} xl={2} sx={{ display: &quot;flex&quot;, justifyContent: &quot;center&quot;, marginTop: &quot;1rem&quot; }} &gt; &lt;Card key={item.id} sx={{ p: &quot;1rem&quot;, boxShadow: 4, maxWidth: { xs: &quot;250px&quot;, sm: &quot;250px&quot;, md: &quot;280px&quot;, lg: &quot;300px&quot;, xl: &quot;300px&quot; } }} &gt; &lt;CardActionArea&gt; &lt;CardMedia component=&quot;img&quot; height=&quot;140&quot; image={item.img} /&gt; &lt;CardContent&gt; &lt;Typography gutterBottom variant=&quot;h5&quot; component=&quot;div&quot;&gt; {item.title} &lt;/Typography&gt; &lt;Typography variant=&quot;body2&quot; color=&quot;text.secondary&quot;&gt; Lizards are a widespread group of squamate reptiles, with over 6,000 species, ranging across all continents except Antarctica &lt;/Typography&gt; &lt;/CardContent&gt; &lt;/CardActionArea&gt; &lt;CardActions&gt; &lt;ButtonProps size=&quot;small&quot; endIcon={ &lt;FavoriteIcon onClick={ChangeColorFavorite} style={{ color: iconFavorite ? &quot;red&quot; : &quot;white&quot; }} /&gt; } &gt; Favorite &lt;/ButtonProps&gt; &lt;/CardActions&gt; &lt;/Card&gt; &lt;/Grid&gt; ); })} &lt;/Grid&gt; &lt;/Box&gt; ); } </code></pre> <p>I used the useState to store the current value of the icon (true or false), however, it was not enough to leave only the icon clicked in red. When clicking on the FavoriteIcon I expected that only the icon clicked would turn red.</p> <p><a href="https://codesandbox.io/s/menu-responsivo-forked-v0dnw9?file=/ExemplesCard.tsx" rel="nofollow noreferrer">Code link in codesanbox</a></p>
[ { "answer_id": 74388243, "author": "Mischa", "author_id": 2062785, "author_profile": "https://Stackoverflow.com/users/2062785", "pm_score": 1, "selected": false, "text": "fixedSize()" }, { "answer_id": 74388419, "author": "Cheezzhead", "author_id": 2542661, "author_profile": "https://Stackoverflow.com/users/2542661", "pm_score": 0, "selected": false, "text": "HStack" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20335073/" ]
74,379,974
<p>I have 2 generators. One has a nested generator, and the other has a nested list comprehension.</p> <pre><code>// list of variables variables = [] nestedGen = (x for x in (y for y in variables)) nestedList = (x for x in [y for y in variables]) </code></pre> <p>Both generators can be simplified to remove nesting, but are they identical in terms of function unchanged?</p>
[ { "answer_id": 74388243, "author": "Mischa", "author_id": 2062785, "author_profile": "https://Stackoverflow.com/users/2062785", "pm_score": 1, "selected": false, "text": "fixedSize()" }, { "answer_id": 74388419, "author": "Cheezzhead", "author_id": 2542661, "author_profile": "https://Stackoverflow.com/users/2542661", "pm_score": 0, "selected": false, "text": "HStack" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15318873/" ]
74,379,985
<p>I want to change State with child elements in React. However, when I click once, it is not immediately updated. Click twice, it shows the correct answer.</p> <p>How to update async?</p> <pre><code>export default function Example() { const onClick = async () =&gt; { console.log('a', test) // should be 'b', but console log 'a' } const [test, setTest] = useState('a') return ( &lt;ClickExample setTest={setTest} onClick={onClick} /&gt; ) } </code></pre> <pre><code>export default function ClickExample() { const next = useCallback( (alphabet: string) =&gt; { setTest(alphabet) onClick() }, [onClick, setTest], ) return &lt;SelectButton onClick={() =&gt; next('b')} /&gt; } </code></pre>
[ { "answer_id": 74388243, "author": "Mischa", "author_id": 2062785, "author_profile": "https://Stackoverflow.com/users/2062785", "pm_score": 1, "selected": false, "text": "fixedSize()" }, { "answer_id": 74388419, "author": "Cheezzhead", "author_id": 2542661, "author_profile": "https://Stackoverflow.com/users/2542661", "pm_score": 0, "selected": false, "text": "HStack" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74379985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9315566/" ]
74,380,061
<p>Been trying to get started with using Python procedures in Snowflake. I have another basic procedure that works fine, but I can't get this part working. I am hoping to filter a dataframe, but getting this weird error.</p> <pre><code>[P0000][100357] Python Interpreter Error: Traceback (most recent call last): File &quot;_udf_code.py&quot;, line 6, in run File &quot;/usr/lib/python_udf/de--0d/lib/python3.8/site-packages/snowflake/snowpark/_internal/telemetry.py&quot;, line 133, in wrap result = func(*args, **kwar ... </code></pre> <p>Here is the stored procedure, its fairly simple</p> <pre><code>CREATE OR REPLACE PROCEDURE utility.procedure.RECREATE_STALE_STREAM_PYTHON() RETURNS STRING LANGUAGE PYTHON RUNTIME_VERSION = '3.8' PACKAGES = ('snowflake-snowpark-python') HANDLER = 'run' AS $$ from snowflake.snowpark.functions import col def run(session): show_streams = &quot;show streams in account;&quot; streams = session.sql(show_streams) stale_streams = streams.filter(col('stale') == 'true').collect(); return stale_streams $$; </code></pre> <p>Thanks in advance</p> <p>I have tried everything I can think of, nothing seems to work</p>
[ { "answer_id": 74388243, "author": "Mischa", "author_id": 2062785, "author_profile": "https://Stackoverflow.com/users/2062785", "pm_score": 1, "selected": false, "text": "fixedSize()" }, { "answer_id": 74388419, "author": "Cheezzhead", "author_id": 2542661, "author_profile": "https://Stackoverflow.com/users/2542661", "pm_score": 0, "selected": false, "text": "HStack" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74380061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18208164/" ]
74,380,065
<pre><code> import string 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' import random from random import randint Number_of_emailname_letters = randint(3,10) Number_of_emailDomain_letters = randint(5,15) Email_name = 'pt1' Email_Domain = 'ptd1' def Email_name(): if Number_of_emailname_letters == 3: Email_name = pt1, pt2, pt3 elif Number_of_emailname_letters == 4: Email_name = pt1, pt2, pt3, pt4 elif Number_of_emailname_letters == 5: Email_name = pt1, pt2, pt3, pt4, pt5 elif Number_of_emailname_letters == 6: Email_name = pt1, pt2, pt3, pt4, pt5, pt6 elif Number_of_emailname_letters == 7: Email_name = pt1,pt2, pt3, pt4, pt5,pt6, pt7 elif Number_of_emailname_letters == 8: Email_name = pt1, pt2, pt3, pt4, pt5, pt6, pt7, pt8 elif Number_of_emailname_letters == 9: Email_name = pt1, pt2, pt3, pt4, pt5, pt6, pt7, pt8, pt9, elif Number_of_emailname_letters == 10: Email_name = pt1, pt2, pt3, pt4, pt5, pt6, pt7, pt8, pt9, pt10 def Email_Domain(): if Number_of_emailDomain_letters == 5: Email_Domain = ptd1, ptd2, ptd3, ptd4, ptd5 elif Number_of_emailDomain_letters == 6: Email_Domain = ptd1, ptd2, ptd3, ptd4, ptd5, ptd6 elif Number_of_emailDomain_letters == 7: Email_Domain = ptd1, ptd2, ptd3, ptd4, ptd5, ptd6, ptd7 elif Number_of_emailDomain_letters == 8: Email_Domain = ptd1, ptd2, ptd3, ptd4, ptd5, ptd6, ptd7, ptd8 elif Number_of_emailDomain_letters == 9: Email_Domain = ptd1, ptd2, ptd3, ptd4, ptd5, ptd6, ptd7, ptd8, ptd9 elif Number_of_emailDomain_letters == 10: Email_Domain = ptd1, ptd2, ptd3, ptd4, ptd5, ptd6, ptd7, ptd8, ptd9, ptd10 elif Number_of_emailDomain_letters == 11: Email_Domain = ptd1, ptd2, ptd3, ptd4, ptd5, ptd6, ptd7, ptd8, ptd9, ptd10, ptd11 elif Number_of_emailDomain_letters == 12: Email_Domain = ptd1, ptd2, ptd3, ptd4, ptd5, ptd6, ptd7, ptd8, ptd9, ptd10, ptd11, ptd12 elif Number_of_emailDomain_letters == 13: Email_Domain = ptd1, ptd2, ptd3, ptd4, ptd5, ptd6, ptd7, ptd8, ptd9, ptd10, ptd11, ptd12, ptd13 elif Number_of_emailDomain_letters == 14: Email_Domain = ptd1, ptd2, ptd3, ptd4, ptd5, ptd6, ptd7, ptd8, ptd9, ptd10, ptd11, ptd12, ptd13, ptd14 elif Number_of_emailDomain_letters == 15: Email_Domain = ptd1, ptd2, ptd3, ptd4, ptd5, ptd6, ptd7, ptd8, ptd9, ptd10, ptd11, ptd12, ptd13, ptd14, ptd15 # Email name generator pt1 = random.choice(string.ascii_letters) pt2 = random.choice(string.ascii_letters) pt3 = random.choice(string.ascii_letters) pt4 = random.choice(string.ascii_letters) pt5 = random.choice(string.ascii_letters) pt6 = random.choice(string.ascii_letters) pt7 = random.choice(string.ascii_letters) pt8 = random.choice(string.ascii_letters) pt9 = random.choice(string.ascii_letters) pt10 = random.choice(string.ascii_letters) Email_name() # Email Domain generator ptd1 = random.choice(string.ascii_letters) ptd2 = random.choice(string.ascii_letters) ptd3 = random.choice(string.ascii_letters) ptd4 = random.choice(string.ascii_letters) ptd5 = random.choice(string.ascii_letters) ptd6 = random.choice(string.ascii_letters) ptd7 = random.choice(string.ascii_letters) ptd8 = random.choice(string.ascii_letters) ptd9 = random.choice(string.ascii_letters) ptd10 = random.choice(string.ascii_letters) ptd11 = random.choice(string.ascii_letters) ptd12 = random.choice(string.ascii_letters) ptd13 = random.choice(string.ascii_letters) ptd14 = random.choice(string.ascii_letters) ptd15 = random.choice(string.ascii_letters) Email_Domain() print(Email_name,&quot;@&quot;,Email_Domain, &quot;.com&quot;) </code></pre> <p>So, this is my code to create a randomized email and output it. I can't get it all to output in some clean way.I have tried setting a variable to a function, but that didn't get me what i wanted. what i want to happen is get an output something like <code>afgre@seruera.com</code> and i can't get that. what i got was <code>&lt;function Email_name at 0x7f53299c7130&gt; @ &lt;function Email_Domain at 0x7f5329861900&gt; .com</code> and I've tried setting a variable to a function but then i just get something like</p> <pre><code>'a, S, V, i' 'G, h, k, L,I, t' none @ none .com </code></pre> <p>How can i get what i want to get?</p>
[ { "answer_id": 74388243, "author": "Mischa", "author_id": 2062785, "author_profile": "https://Stackoverflow.com/users/2062785", "pm_score": 1, "selected": false, "text": "fixedSize()" }, { "answer_id": 74388419, "author": "Cheezzhead", "author_id": 2542661, "author_profile": "https://Stackoverflow.com/users/2542661", "pm_score": 0, "selected": false, "text": "HStack" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74380065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15292744/" ]
74,380,113
<p>I'm working with Moment JS in my Nuxt JS project. I'm building a countdown timer which needs to count down to a specific date &amp; time, ideally, I need it to display the same countdown information based on timezone in the user's country, I need it to countdown to a date &amp; time in Europe/London though.</p> <p>This is my method:</p> <pre class="lang-js prettyprint-override"><code>/* ** Set time left */ setCountdown () { var date = this.$moment.utc(this.endDate).format() console.log(date) const end = this.$moment.utc(date).local() const timeLeft = this.$moment(end.diff(this.$moment())) const daysLeft = end.diff(this.$moment(), 'days') this.countdown.days = daysLeft this.countdown.hours = timeLeft.format('HH') this.countdown.minutes = timeLeft.format('mm') this.countdown.seconds = timeLeft.format('ss') }, </code></pre> <p>The date I want to countdown to is: <strong>2022-11-09 20:00:00</strong> and the time in my country right now is <strong>2022-11-09 19:00:00</strong>, despite putting <code>this.$moment.tz.guess()</code> within the <code>end</code> date, it still shows 2 hours away, where am I missing my timezone from in my code?</p>
[ { "answer_id": 74388243, "author": "Mischa", "author_id": 2062785, "author_profile": "https://Stackoverflow.com/users/2062785", "pm_score": 1, "selected": false, "text": "fixedSize()" }, { "answer_id": 74388419, "author": "Cheezzhead", "author_id": 2542661, "author_profile": "https://Stackoverflow.com/users/2542661", "pm_score": 0, "selected": false, "text": "HStack" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74380113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9982090/" ]
74,380,134
<pre><code>adb exec-out screencap -p &gt; screen.png </code></pre> <p>This used to work on my Chromecast with Google TV while playing video (no DRM) when it was running on Android 10. After upgrading to Android 12, it just produces a completely white image (with correct screen resolution; with no other view widgets either). This is the case when playing videos using MX Player, YouTube and other apps using ExoPlayer.</p> <p>Can I get <code>screencap</code> to work as it did or another way to take screenshots?</p>
[ { "answer_id": 74388243, "author": "Mischa", "author_id": 2062785, "author_profile": "https://Stackoverflow.com/users/2062785", "pm_score": 1, "selected": false, "text": "fixedSize()" }, { "answer_id": 74388419, "author": "Cheezzhead", "author_id": 2542661, "author_profile": "https://Stackoverflow.com/users/2542661", "pm_score": 0, "selected": false, "text": "HStack" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74380134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20462031/" ]
74,380,157
<p>I have the following code:</p> <pre><code>parser = argparse.ArgumentParser(description='') parser.add_argument('-l', '--login', action='store_true') parser.add_argument('FILTER1') parser.add_argument('FILTER2') parser.add_argument('FILTER3') </code></pre> <p>I'd like &quot;--login&quot; to be mutually exclusive from FILTER1, FILTER2, FILTER3. Also, FILTER1, FILTER2, FILTER3 are all required when any of the 3 are mentioned.</p> <p>So either:</p> <pre><code>cli FILTER1 FILTER2 FILTER3 </code></pre> <p>OR</p> <pre><code>cli --login </code></pre>
[ { "answer_id": 74380503, "author": "wjandrea", "author_id": 4518341, "author_profile": "https://Stackoverflow.com/users/4518341", "pm_score": 2, "selected": false, "text": "nargs=3" }, { "answer_id": 74380784, "author": "Jasmijn", "author_id": 573255, "author_profile": "https://Stackoverflow.com/users/573255", "pm_score": 0, "selected": false, "text": "ArgumentParser.add_mutually_exclusive_group" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74380157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8799182/" ]
74,380,184
<p>I just want to have the message 'no actors' if the name is NULL. How can I do this?</p> <pre><code>SELECT length, title, LISTAGG(SUBSTR(first_name, 1, 1) || '. ' || last_name, ', ') WITHIN GROUP (ORDER BY last_name) AS ACTORS -- 'no actors' if first_name is NULL FROM film INNER JOIN film_actor USING (film_id) INNER JOIN actor USING (actor_id) WHERE release_year = 1991 GROUP BY title, length ORDER BY length DESC; </code></pre> <p>I have tried it with NVL in the LISTAGG function, but I cannot get rid of the point '.' of the concatenation. Is there another way to do this?</p>
[ { "answer_id": 74380503, "author": "wjandrea", "author_id": 4518341, "author_profile": "https://Stackoverflow.com/users/4518341", "pm_score": 2, "selected": false, "text": "nargs=3" }, { "answer_id": 74380784, "author": "Jasmijn", "author_id": 573255, "author_profile": "https://Stackoverflow.com/users/573255", "pm_score": 0, "selected": false, "text": "ArgumentParser.add_mutually_exclusive_group" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74380184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20197912/" ]
74,380,231
<p>I am writing a small DirectShow application in C++,</p> <p>and i'm have a lot of trouble fetching the data of the recorded audio.</p> <p>What i'm trying to achieve :</p> <p><strong>Microphone-&gt;Avi MUX filter-&gt;Data buffer-&gt;send buffer to server-&gt; write data to an Avi file</strong></p> <p>How can this be done ? How can I fetch the raw buffer from the Avi Mux filter?</p> <p>Help would be much appreciated</p> <p>My current filter graph is built as follow, and it works:</p> <p><strong>Microphone -&gt; Avi MUX filter -&gt; File writer</strong></p> <p>This filter graph flow works fine, and i'm able to hear the recording.</p>
[ { "answer_id": 74380503, "author": "wjandrea", "author_id": 4518341, "author_profile": "https://Stackoverflow.com/users/4518341", "pm_score": 2, "selected": false, "text": "nargs=3" }, { "answer_id": 74380784, "author": "Jasmijn", "author_id": 573255, "author_profile": "https://Stackoverflow.com/users/573255", "pm_score": 0, "selected": false, "text": "ArgumentParser.add_mutually_exclusive_group" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74380231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18277419/" ]
74,380,235
<p>I am running a function with string similarity to find the similarity of the strings in the list. But I want to do this in a synchronized way by using multi threads in this list.</p> <p>Each thread does the whole task by itself. I want to do the task once, with multiple thread</p> <pre><code> public class Runn implements Runnable { public void run() { synchronized (LOCK){ newList=listExe.getStringList(); try { int i=1; for (String s: newList) { //System.out.println(s); //System.out.println(newList.get(i)); System.out.println(&quot;Similarity &quot;+ solution.findSimilarityRatio(s,newList.get(i))); System.out.println(Thread.currentThread().getName()); System.out.println(); i++; if(i==newList.size()){ break; } } Thread.sleep(200); } catch (Exception e){ e.printStackTrace(); System.out.println(e.getMessage()); } } } } public static void main(String[] args) { Runn runnable=new Runn(); ExecutorService pool= Executors.newFixedThreadPool(10); for (int i=0;i&lt;10;i++){ pool.execute(runnable); } } </code></pre>
[ { "answer_id": 74380888, "author": "Alexander Pavlov", "author_id": 998126, "author_profile": "https://Stackoverflow.com/users/998126", "pm_score": 2, "selected": true, "text": "public static void main(String[]args){\n final ConcurrentLinkedQueue<String> queue=new ConcurrentLinkedQueue<>();\n // fill the queue\n // ...\n\n final String s = ...; //\n\n Runnable runnable=()->{\n try {\n for (String i =queue.poll(); i != null; i=queue.poll()) {\n System.out.println(\"Similarity \" + solution.findSimilarityRatio(s, i));\n System.out.println(Thread.currentThread().getName());\n System.out.println();\n }\n } catch (Exception e){\n e.printStackTrace();\n System.out.println(e.getMessage());\n }\n };\n \n ExecutorService pool=Executors.newFixedThreadPool(10);\n\n for(int i=0;i<10;i++){\n pool.execute(runnable);\n }\n}\n\n" }, { "answer_id": 74381030, "author": "Gray", "author_id": 179850, "author_profile": "https://Stackoverflow.com/users/179850", "pm_score": 2, "selected": false, "text": "Runnable" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74380235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20142626/" ]
74,380,242
<p>I'm working with a very long list of numbers, say 1.5 billion. I need a way to specify a percentage of numbers that I want to keep, and the rest discard. Now I know I can use a Random Number Generator to randomly decide if I should keep it or not, but the problem is that I need the numbers to keep/discard to always be the same. Meaning, if I run the program and it decides to discard indexes 2, 5, and 10, the next time I run the program, it must discard 2, 5, and 10 as well. This is very important.</p> <p>I'm also facing an issue with memory. To generate a huge list of bools to determine which numbers are discarded and which are not (if we decided to go that way, for example), the profiler says the program uses around 15gb of memory, which is already too much considering I have yet another list of 1.5 billion numbers. Here's my code for that if that matters:</p> <pre><code> static bool[] GenerateShouldAddList(int totalCombos, decimal percentToAdd) { Random RNG = new Random(); bool[] bools = new bool[totalCombos]; int percent = (int)(percentToAdd * 100); for (int i = 0; i &lt; totalCombos; i++) { int randNum = RNG.Next(0, 101); bools[i] = randNum &lt; percent; } return bools; } </code></pre> <p>So I'm thinking, to avoid making a huge list, is there a way to make a function that will take in the index number (say index 5364), the total numbers (1.5 billion) and the percentage that you want to keep, and then return to me whether I should add that specific index or not? And if I run each index one at a time through that function, I should only be left with the percentage of numbers I specified. And most importantly, this function should always return the same result for the same index (if the totalNumbers and the percentage don't change). I'm thinking this isn't possible, but I also have hope there's people on here that are much smarter than me. Any help is appreciated!</p>
[ { "answer_id": 74380507, "author": "Dmitry Bychenko", "author_id": 2319407, "author_profile": "https://Stackoverflow.com/users/2319407", "pm_score": 2, "selected": false, "text": "IEnumerable<T>" }, { "answer_id": 74381019, "author": "Pete Kirkham", "author_id": 1527, "author_profile": "https://Stackoverflow.com/users/1527", "pm_score": 0, "selected": false, "text": "is_kept(index=2, percent=50)" }, { "answer_id": 74381526, "author": "TJ Rockefeller", "author_id": 4708150, "author_profile": "https://Stackoverflow.com/users/4708150", "pm_score": 2, "selected": true, "text": "using System.Security.Cryptography;\n\npublic static class ToKeepOrNotToKeep\n{\n private static readonly MD5 _md5 = MD5.Create();\n\n public static bool AtIndex(int index, double percentToKeep)\n {\n var byteArray = BitConverter.GetBytes(index);\n var hash = _md5.ComputeHash(byteArray);\n //I know that the hash is 16 bytes, and here we are converting\n //only the first 8 bytes to a ulong, but it's still random and\n //should work just as well as if we used all 16 bytes for our\n //threshold test\n var number = BitConverter.ToUInt64(hash, 0);\n var threshold = ulong.MaxValue * percentToKeep;\n\n if (number <= threshold)\n return true;\n else\n return false;\n }\n}\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74380242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19693550/" ]
74,380,270
<pre><code>@Test void interruptedExceptionThrownByCompletableFutures() throws InterruptedException, ExecutionException { //given when(patientsClient.getPatientTreatmentDetails(RPT_TOKEN, &quot;123&quot;, CLINICAL_ID)) .thenReturn(createPatientTreatmentDetails()); CompletableFuture&lt;List&lt;HDTreatmentOrder&gt;&gt; hdFuture = spy(CompletableFuture.completedFuture(Collections.emptyList())); when(hdFuture.get()).thenThrow(new InterruptedException()); CompletableFuture&lt;List&lt;PDTreatmentOrder&gt;&gt; pdFuture = spy(CompletableFuture.completedFuture(Collections.emptyList())); when(pdFuture.get()).thenThrow(new InterruptedException()); when(hdService.getData(any(), any())).thenReturn(hdFuture); when(pdService.getData(any(), any())).thenReturn(pdFuture); when(tDService.getData(RPT_TOKEN, &quot;123&quot;, filter)).thenReturn(CompletableFuture.completedFuture(new PatientTreatmentDetails())); //then assertThrows(PatientOrderException.class, () -&gt; treatmentOrderService.getTreatmentOrders(&quot;123&quot;, filter, RPT_TOKEN)); } </code></pre> <p>This is treatMentOrderService public class TreatmentOrderService {</p> <pre><code>private final HDTreatmentOrderService hdService; private final PDTreatmentOrderService pdService; private final TreatmentDetailsService tDService; private final TreatmentOrderTransform transformer; private final DenodoLastTreatmentDetailsService denodoLastTreatmentDetailsService; CompletableFuture&lt;List&lt;PDTreatmentOrder&gt;&gt; pdFuture = pdService.getData(mpi, filter); try { if (filter.isIncludeTreatmentDetails() &amp;&amp; StringUtils.isNotEmpty(filter.getClinicId())) { CompletableFuture&lt;PatientTreatmentDetails&gt; tDFuture = tDService.getData(rptToken, mpi, filter); CompletableFuture.allOf(hdFuture, pdFuture, tDFuture).join(); return transformer.transform(hdFuture.get(), pdFuture.get(), tDFuture.get(), filter); } else { CompletableFuture.allOf(hdFuture, pdFuture).join(); return transformer.transform(hdFuture.get(), pdFuture.get(), null, filter); } } catch (InterruptedException e) { log.error(&quot;InterruptedException: &quot;, e); Thread.currentThread().interrupt(); throw new PatientOrderException(&quot;Failed executing async tasks: &quot; + e.getMessage()); } catch (ExecutionException e) { log.error(&quot;ExecutionException: &quot;, e); throw new PatientOrderException(&quot;Failed executing async tasks: &quot; + e.getMessage()); } } </code></pre> <p>}</p> <pre><code>Nov 09, 2022 12:44:51 PM org.junit.platform.launcher.core.EngineDiscoveryOrchestrator lambda$logTestDescriptorExclusionReasons$7 INFO: 0 containers and 20 tests were Method or class mismatch PatientTreatmentDetails cannot be returned by toString() toString() should return String *** If you're unsure why you're getting above error read on. Due to the nature of the syntax above problem might occur because: 1. This exception *might* occur in wrongly written multi-threaded tests. Please refer to Mockito FAQ on limitations of concurrency testing. 2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method. org.mockito.exceptions.misusing.WrongTypeOfReturnValue: PatientTreatmentDetails cannot be returned by toString() toString() should return String *** If you're unsure why you're getting above error read on. Due to the nature of the syntax above problem might occur because: 1. This exception *might* occur in wrongly written multi-threaded tests. Please refer to Mockito FAQ on limitations of concurrency testing. 2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method. at app//com.davita.ehr.orders.patientorder.service.TreatmentOrderServiceTest.setup(TreatmentOrderServiceTest.java:84) at java.base@17.0.2/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base@17.0.2/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) at java.base@17.0.2/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base@17.0.2/java.lang.reflect.Method.invoke(Method.java:568) at app//org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:725) at app//org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60) at app//org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131) at app//org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149) at app//org.junit.jupiter.engine.extension.TimeoutExtension.interceptLifecycleMethod(TimeoutExtension.java:126) at app//org.junit.jupiter.engine.extension.TimeoutExtension.interceptBeforeEachMethod(TimeoutExtension.java:76) at app//org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115) at app//org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105) at app//org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106) at app//org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64) at app//org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45) at app//org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37) at app//org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104) at app//org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98) at app//org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeMethodInExtensionContext(ClassBasedTestDescriptor.java:506) at app//org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$synthesizeBeforeEachMethodAdapter$21(ClassBasedTestDescriptor.java:491) at app//org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeBeforeEachMethods$3(TestMethodTestDescriptor.java:171) at app//org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeBeforeMethodsOrCallbacksUntilExceptionOccurs$6(TestMethodTestDescriptor.java:199) at app//org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at app//org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeBeforeMethodsOrCallbacksUntilExceptionOccurs(TestMethodTestDescriptor.java:199) at app//org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeBeforeEachMethods(TestMethodTestDescriptor.java:168) at app//org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:131) at app//org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:66) at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151) at app//org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141) at app//org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139) at app//org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138) at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95) at java.base@17.0.2/java.util.ArrayList.forEach(ArrayList.java:1511) at app//org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41) at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155) at app//org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141) at app//org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139) at app//org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138) at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95) at java.base@17.0.2/java.util.ArrayList.forEach(ArrayList.java:1511) at app//org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41) at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155) at app//org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141) at app//org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139) at app//org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138) at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95) at app//org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35) at app//org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57) at app//org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:108) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52) at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:96) at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:75) at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.processAllTestClasses(JUnitPlatformTestClassProcessor.java:99) at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.access$000(JUnitPlatformTestClassProcessor.java:79) at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor.stop(JUnitPlatformTestClassProcessor.java:75) at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61) at java.base@17.0.2/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base@17.0.2/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) at java.base@17.0.2/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base@17.0.2/java.lang.reflect.Method.invoke(Method.java:568) at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36) at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24) at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33) at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94) at jdk.proxy2/jdk.proxy2.$Proxy5.stop(Unknown Source) at org.gradle.api.internal.tasks.testing.worker.TestWorker$3.run(TestWorker.java:193) at org.gradle.api.internal.tasks.testing.worker.TestWorker.executeAndMaintainThreadName(TestWorker.java:129) at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:100) at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:60) at org.gradle.process.internal.worker.child.ActionExecutionWorker.execute(ActionExecutionWorker.java:56) at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:133) at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:71) at app//worker.org.gradle.process.internal.worker.GradleWorkerMain.run(GradleWorkerMain.java:69) at app//worker.org.gradle.process.internal.worker.GradleWorkerMain.main(GradleWorkerMain.java:74) Disconnected from the target VM, address: 'localhost:51661', transport: 'socket' TreatmentOrderServiceTest &gt; interruptedExceptionThrownByCompletableFutures() FAILED org.mockito.exceptions.misusing.WrongTypeOfReturnValue at TreatmentOrderServiceTest.java:84 </code></pre> <p>-&gt; This test is not executing and when i run this individually this is running continuously until i stop. i'm thinking there is some thing wrong with this test especially the completable future with spy.</p> <p>using java 17 springboot 2.6.6 junit 5 gradle 7.4.2</p>
[ { "answer_id": 74380507, "author": "Dmitry Bychenko", "author_id": 2319407, "author_profile": "https://Stackoverflow.com/users/2319407", "pm_score": 2, "selected": false, "text": "IEnumerable<T>" }, { "answer_id": 74381019, "author": "Pete Kirkham", "author_id": 1527, "author_profile": "https://Stackoverflow.com/users/1527", "pm_score": 0, "selected": false, "text": "is_kept(index=2, percent=50)" }, { "answer_id": 74381526, "author": "TJ Rockefeller", "author_id": 4708150, "author_profile": "https://Stackoverflow.com/users/4708150", "pm_score": 2, "selected": true, "text": "using System.Security.Cryptography;\n\npublic static class ToKeepOrNotToKeep\n{\n private static readonly MD5 _md5 = MD5.Create();\n\n public static bool AtIndex(int index, double percentToKeep)\n {\n var byteArray = BitConverter.GetBytes(index);\n var hash = _md5.ComputeHash(byteArray);\n //I know that the hash is 16 bytes, and here we are converting\n //only the first 8 bytes to a ulong, but it's still random and\n //should work just as well as if we used all 16 bytes for our\n //threshold test\n var number = BitConverter.ToUInt64(hash, 0);\n var threshold = ulong.MaxValue * percentToKeep;\n\n if (number <= threshold)\n return true;\n else\n return false;\n }\n}\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74380270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20462184/" ]
74,380,286
<p>I am currently working on a login form in C# where I am using WPF, and I have made a check to see if the data in the form is valid but for some reason it always returns false.</p> <p>For context here is my check:</p> <pre><code>private bool CanExecuteLoginCommand(object obj) { bool validData; if (string.IsNullOrWhiteSpace(Username) || Username.Length &lt; 3 || Password == null || Password.Length &lt; 3) validData = false; else validData = true; return validData; } </code></pre> <p>Does anyone know what is causing it to always return false even though username and password is more than three characters?</p> <p>I have tried setting the username and password so they are both more than three characters and where expecting it to return true.</p>
[ { "answer_id": 74380365, "author": "Stephen", "author_id": 20462236, "author_profile": "https://Stackoverflow.com/users/20462236", "pm_score": -1, "selected": false, "text": "obj" }, { "answer_id": 74381214, "author": "kapz424", "author_id": 14226632, "author_profile": "https://Stackoverflow.com/users/14226632", "pm_score": 0, "selected": false, "text": " public string Username \n { \n get { return _username; }\n set\n {\n _username = value;\n OnPropertyChanged(nameof(Username));\n }\n }\n public string Password \n {\n get { return _password; }\n set\n {\n _password = value;\n OnPropertyChanged(nameof(Password));\n }\n }\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74380286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14226632/" ]
74,380,287
<p>I have converted a strategy to an indicator, basically share the same code, only the header and footer code is different.</p> <p>The strategy works as I expect.</p> <p>Say for example running on a 5min chart on the 10:30 bar the triggering conditions may occur several times but I am only concerned with the close of the bar and then trigger a strategy entry only if the conditions exist at the close of the bar.</p> <p>TV shows in its trade list that the trade was executed correctly at exactly 10:35</p> <p>With the indicator, I am using AlertCondition to trigger an alert that will eventually trigger a trade elsewhere.</p> <p>In the same conditions as above the alert is triggering at the start of the 10:30 bar not 10:35.</p> <pre><code>alertcondition(buySignal and barstate.isconfirmed, title=&quot;Alert Buy&quot;, message=&quot;Buy!&quot;) alertcondition(sellSignal and barstate.isconfirmed, title=&quot;Alert: Sell&quot;, message=&quot;Sell!&quot;) </code></pre> <p>So I am using barstate.isconfirmed to ensure the alert only triggers at the end of the 10:30 bar... and yet it is triggered at the start of the bar...</p> <p>How to resolve this issue</p> <p>TIA</p>
[ { "answer_id": 74380365, "author": "Stephen", "author_id": 20462236, "author_profile": "https://Stackoverflow.com/users/20462236", "pm_score": -1, "selected": false, "text": "obj" }, { "answer_id": 74381214, "author": "kapz424", "author_id": 14226632, "author_profile": "https://Stackoverflow.com/users/14226632", "pm_score": 0, "selected": false, "text": " public string Username \n { \n get { return _username; }\n set\n {\n _username = value;\n OnPropertyChanged(nameof(Username));\n }\n }\n public string Password \n {\n get { return _password; }\n set\n {\n _password = value;\n OnPropertyChanged(nameof(Password));\n }\n }\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74380287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1699015/" ]
74,380,303
<p>My project has many Enums that follow a certain Naming convention.</p> <p>I have a general method that converts a string into an Enum value.</p> <p>I want to convert Enum Attribute Names to Enums ( I got this handled ).</p> <p>Also I want to convert an <code>int</code> value passed in a string to an Enum if the enum inherits from <code>IntEnum</code> or <code>IntFlag</code>.</p> <p>My question is as follows: Is there a better way to discover if <code>ec</code> is of type <code>IntEnum</code> or <code>IntFlag</code>?</p> <pre class="lang-py prettyprint-override"><code>def enum_from_string(s: str, ec: Type[Enum]) -&gt; Enum: if not s: raise ValueError(&quot;from_str arg s cannot be an empty value&quot;) try: return getattr(ec, s.upper()) except AttributeError: pass for t in ec.mro(): if t is IntEnum or t is IntFlag: try: return ec(int(s)) except ValueError: pass try: return ec(int(s, 16)) except ValueError: pass break # finish processing and return value ... </code></pre> <p>Example usage:</p> <pre class="lang-py prettyprint-override"><code>class LayoutKind(IntEnum): TITLE_SUB = 0 TITLE_BULLETS = 1 TITLE_CHART = 2 TITLE_2CONTENT = 3 TITLE_CONTENT_CHART = 4 @staticmethod def from_str(s: str) -&gt; &quot;LayoutKind&quot;: return kind_helper.enum_from_string(s, LayoutKind) print(LayoutKind.from_str(&quot;3&quot;)) </code></pre>
[ { "answer_id": 74380358, "author": "juanpa.arrivillaga", "author_id": 5014455, "author_profile": "https://Stackoverflow.com/users/5014455", "pm_score": 2, "selected": false, "text": "if issubclass(ec, (enum.IntEnum, enum.IntFlag)):\n # handle IntEnum or IntFlag case\n" }, { "answer_id": 74381208, "author": "Ethan Furman", "author_id": 208880, "author_profile": "https://Stackoverflow.com/users/208880", "pm_score": 0, "selected": false, "text": "from enum import IntEnum\n\nclass LayoutKind(IntEnum):\n TITLE_SUB = 0\n TITLE_BULLETS = 1\n TITLE_CHART = 2\n TITLE_2CONTENT = 3\n TITLE_CONTENT_CHART = 4\n #\n @classmethod\n def _missing_(cls, value):\n # called when no value match\n if not isinstance(value, str):\n return\n return cls(int(value))\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74380303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1171746/" ]
74,380,335
<p>I just recently discovered gtsummary and I'm impressed by the ease of use and the amount of work that our team won't have to do creating summary tables of our results. Thanks!</p> <p>My question: With more than two groups, the p-value included with add_p() refers to the global test. How can I obtain the information about the post hoc comparaisons between groups? In some journals, we see the use of superscripted letters.</p> <p>I looked for the add_difference() option but it prints the difference between two groups. I also thought that add_q() would help me.</p> <p>Thanks in advance!</p>
[ { "answer_id": 74380358, "author": "juanpa.arrivillaga", "author_id": 5014455, "author_profile": "https://Stackoverflow.com/users/5014455", "pm_score": 2, "selected": false, "text": "if issubclass(ec, (enum.IntEnum, enum.IntFlag)):\n # handle IntEnum or IntFlag case\n" }, { "answer_id": 74381208, "author": "Ethan Furman", "author_id": 208880, "author_profile": "https://Stackoverflow.com/users/208880", "pm_score": 0, "selected": false, "text": "from enum import IntEnum\n\nclass LayoutKind(IntEnum):\n TITLE_SUB = 0\n TITLE_BULLETS = 1\n TITLE_CHART = 2\n TITLE_2CONTENT = 3\n TITLE_CONTENT_CHART = 4\n #\n @classmethod\n def _missing_(cls, value):\n # called when no value match\n if not isinstance(value, str):\n return\n return cls(int(value))\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74380335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14107245/" ]
74,380,377
<p>Im trying to dynamically change the link of a button based on which div a user has currently selected.</p> <p>I tried to run a quick test with a JS variable in the HTML script tag, but Django isn't reading the variable like a num.</p> <pre><code>&lt;script type=&quot;text/javascript&quot;&gt; const testing = 10 &lt;/script&gt; &lt;a href=&quot;{% url 'battlefield:onevsone_trainer_selection' num_trainers=testing %}&quot; class='description__button btn btn__large'&gt;Next &gt;&lt;/a&gt; </code></pre> <p>URL looks like:</p> <pre><code>path('one-vs-one/trainers/&lt;int:num_trainers&gt;', views.oneVsOne, name='onevsone_trainer_selection') </code></pre> <p>Not sure exactly why it's not working. When I passed it a string of '10' it worked</p>
[ { "answer_id": 74381020, "author": "SamSparx", "author_id": 18799377, "author_profile": "https://Stackoverflow.com/users/18799377", "pm_score": 3, "selected": true, "text": "{% url 'battlefield:onevsone_trainer_selection' num_trainers=testing %}" }, { "answer_id": 74381167, "author": "imperosol", "author_id": 15270926, "author_profile": "https://Stackoverflow.com/users/15270926", "pm_score": 0, "selected": false, "text": "<script type=\"text/javascript\">\n const testing = 10\n</script>\n\n<a href=\"one-vs-one/trainers/testing\" class='description__button btn btn__large'>Next ></a>\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74380377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16167140/" ]
74,380,391
<p>My program is like the command prompt (cmd) but much simpler. I am creating a command called, <code>'bd'</code> which stands for back (one) directory. There is a path string: <code>path = &quot;C:/Program Files/node.js&quot;</code> and I want to remove the last directory <code>'/node.js'</code> but I don't want to use indexing or slicing, because the path string will change on the file's name length.</p> <p>I have tried <code>path.rstrip(&quot;/&quot;)</code> but I couldn't figure how to remove the last <code>'/'</code> with the directory name, <code>'node.js'</code>.</p> <p>Thanks in advance.</p>
[ { "answer_id": 74381020, "author": "SamSparx", "author_id": 18799377, "author_profile": "https://Stackoverflow.com/users/18799377", "pm_score": 3, "selected": true, "text": "{% url 'battlefield:onevsone_trainer_selection' num_trainers=testing %}" }, { "answer_id": 74381167, "author": "imperosol", "author_id": 15270926, "author_profile": "https://Stackoverflow.com/users/15270926", "pm_score": 0, "selected": false, "text": "<script type=\"text/javascript\">\n const testing = 10\n</script>\n\n<a href=\"one-vs-one/trainers/testing\" class='description__button btn btn__large'>Next ></a>\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74380391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20442433/" ]
74,380,400
<p>Here I am trying to empty an array using recursion by calling shift function, but anyhow I am getting an error please help.</p> <pre><code>let arr = [1,2,3,4]; function del(arr){ if(arr.length === 0){ return [] }else { let result = arr.shift(); return del(result) } } console.log(del(arr)) </code></pre> <blockquote> <pre><code> TypeError: arr.shift is not a function </code></pre> </blockquote>
[ { "answer_id": 74380451, "author": "Nina Scholz", "author_id": 1447675, "author_profile": "https://Stackoverflow.com/users/1447675", "pm_score": 2, "selected": false, "text": "Array#shift" }, { "answer_id": 74380478, "author": "Andrew Parks", "author_id": 5898421, "author_profile": "https://Stackoverflow.com/users/5898421", "pm_score": 0, "selected": false, "text": "let arr = [1, 2, 3, 4];\narr.splice(0, arr.length);\nconsole.log(arr);" }, { "answer_id": 74380493, "author": "Tushar Shahi", "author_id": 10140124, "author_profile": "https://Stackoverflow.com/users/10140124", "pm_score": 0, "selected": false, "text": "del(result)" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74380400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16708103/" ]
74,380,413
<p>I'm trying to create a simple line plot in ggplot2 with a dataframe, but the results aren't appearing as expected.</p> <p>Here is the code to reproduce the data:</p> <pre><code>tograph&lt;-data.frame(PANEL=13:22,total=c(10,20,30,40,50,60,70,80,90,100)) </code></pre> <p>And when I graph the results in ggplot2, it just creates a straight vertical line at PANEL=1 (SO won't let me post images at this time)</p> <pre><code>ggplot(data=tograph,aes(x=PANEL,y=total))+geom_line() </code></pre> <p>As a sanity check, I ran some example data I found on a different post to make sure it wasn't something unique to my installation of R and it worked fine</p> <pre><code>xValue &lt;- 1:10 yValue &lt;- cumsum(rnorm(10)) data &lt;- data.frame(xValue,yValue) # Plot ggplot(data, aes(x=xValue, y=yValue)) + geom_line() </code></pre> <p>Similarly, graphing my intended data in base R also works fine, but I'd prefer to set it up in ggplot2 for aesthetic reasons:</p> <pre><code>plot(tograph$PANEL,tograph$total,type=&quot;l&quot;) </code></pre> <p>Any help with fixing this is much appreciated.</p>
[ { "answer_id": 74380451, "author": "Nina Scholz", "author_id": 1447675, "author_profile": "https://Stackoverflow.com/users/1447675", "pm_score": 2, "selected": false, "text": "Array#shift" }, { "answer_id": 74380478, "author": "Andrew Parks", "author_id": 5898421, "author_profile": "https://Stackoverflow.com/users/5898421", "pm_score": 0, "selected": false, "text": "let arr = [1, 2, 3, 4];\narr.splice(0, arr.length);\nconsole.log(arr);" }, { "answer_id": 74380493, "author": "Tushar Shahi", "author_id": 10140124, "author_profile": "https://Stackoverflow.com/users/10140124", "pm_score": 0, "selected": false, "text": "del(result)" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74380413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20462134/" ]
74,380,415
<p>I want to implement this layout:</p> <p><img src="https://i.stack.imgur.com/ro304.png" alt="layout" /></p> <ul> <li>where the body takes full view height,</li> <li>it has a fixed height app-bar</li> <li>and a main section that takes the rest available space using flex-grow: 1.</li> </ul> <p>Inside the main section,</p> <ul> <li>there is a card that I want to have 80% of the height of the main section</li> <li>and the card to be scrollable (to have content that exceeds its height)</li> </ul> <p>The problem appears to be when I set the <em>card height</em> to <em>80%</em>. There is no problem when i set it to fixed <em>800px</em></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { background: #f1f1f1; margin: 0; width: 100vw; height: 100vh; display: flex; flex-direction: column; align-items: center; } body main { flex-grow: 1; display: flex; flex-direction: column; justify-content: center; align-items: center; } /* HERE IS THE ISSUE */ /* (uncomment height: 80%) */ body main #main-card { height: 400px; /* height: 80%; */ overflow-y: auto; background: green; padding: 20px; width: 400px; } body main #main-card #main-card-content { background: #bf8040; height: 150vh; } body header { width: 100%; height: 50px; background: red; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;body&gt; &lt;header&gt;&lt;/header&gt; &lt;main&gt; &lt;div id="main-card"&gt; &lt;div id="main-card-content"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/main&gt; &lt;/body&gt;</code></pre> </div> </div> </p> <p>I can fix it by setting main height to be 100vh minus the height of the header, but I would like to keep the flex-grow property</p> <p>Here is the <a href="https://codepen.io/alexkougianos/pen/poKRqzw?editors=0100" rel="nofollow noreferrer">codepen</a> that replicates the problem</p> <p>Any suggestions?</p>
[ { "answer_id": 74380509, "author": "dangarfield", "author_id": 3265253, "author_profile": "https://Stackoverflow.com/users/3265253", "pm_score": 0, "selected": false, "text": "height: calc(80vh - 50px);\n" }, { "answer_id": 74380516, "author": "Michael Benjamin", "author_id": 3597276, "author_profile": "https://Stackoverflow.com/users/3597276", "pm_score": 3, "selected": true, "text": "flex-grow: 1" }, { "answer_id": 74380528, "author": "kumorin", "author_id": 16501128, "author_profile": "https://Stackoverflow.com/users/16501128", "pm_score": 0, "selected": false, "text": "height: calc(100% - 50px);" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74380415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14632244/" ]
74,380,418
<p>I have the following code where I want to add the string 'NSQscores' to the list of strings 'newlist'.</p> <p>However, the following code gives me a 'none'.</p> <pre><code>columnlist = list(newdf.columns) newlist = columnlist[0:87] newlist2 = newlist.extend(['NSQscores']) print(newlist2) none </code></pre> <p>Would be so grateful if anybody could give me a helping hand!</p> <p>As an example:</p> <pre><code>newlist[5:10] ['military-quantised', 'mental_imagery-quantised', 'navigate_growup-quantised', 'independent_nav-quantised', 'response-1 -quantised'] </code></pre>
[ { "answer_id": 74380509, "author": "dangarfield", "author_id": 3265253, "author_profile": "https://Stackoverflow.com/users/3265253", "pm_score": 0, "selected": false, "text": "height: calc(80vh - 50px);\n" }, { "answer_id": 74380516, "author": "Michael Benjamin", "author_id": 3597276, "author_profile": "https://Stackoverflow.com/users/3597276", "pm_score": 3, "selected": true, "text": "flex-grow: 1" }, { "answer_id": 74380528, "author": "kumorin", "author_id": 16501128, "author_profile": "https://Stackoverflow.com/users/16501128", "pm_score": 0, "selected": false, "text": "height: calc(100% - 50px);" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74380418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12985497/" ]
74,380,420
<p>the issue is very easy, but seems quite complicate;I've search on internet and try a lot but there is not way to find a solution for me!! All I need is not having space between an icon and a text: <a href="https://i.stack.imgur.com/S42rJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/S42rJ.png" alt="enter image description here" /></a></p> <p>this is the code:</p> <pre><code>Label subTitle = new Label(&quot;nel cammin di nostra vita mi trovai in selva oscura&quot;); Label stpIMG = null; stpIMG = new Label(); stpIMG.setContentMode(ContentMode.HTML); stpIMG.setValue(&quot;&lt;img src=\&quot;VAADIN/themes/valo/images/sprite_svg_all.svg#ristampa\&quot;&gt;&quot;); stpIMG.setWidth(&quot;30px&quot;); stpIMG.setHeight(&quot;20px&quot;); HorizontalLayout subTitleLayout=null; subTitleLayout = new HorizontalLayout(stpIMG,subTitle); subTitleLayout.setExpandRatio(stpIMG, 1); subTitleLayout.setExpandRatio(subTitle, 2); subTitleLayout.setWidth(&quot;650px&quot;); subTitleLayout.setSpacing(false); mainLayout.addComponents(subTitleLayout); </code></pre> <p>And is not easy to accomplish even if is so easy; What I'm wrong? thanks so much</p>
[ { "answer_id": 74381248, "author": "Rolf", "author_id": 298103, "author_profile": "https://Stackoverflow.com/users/298103", "pm_score": 1, "selected": false, "text": "subTitleLayout.setExpandRatio(stpIMG, 1);" }, { "answer_id": 74617331, "author": "fraaanz", "author_id": 3691373, "author_profile": "https://Stackoverflow.com/users/3691373", "pm_score": 0, "selected": false, "text": "Label warnIMG = new Label();\nwarnIMG.setContentMode(ContentMode.HTML);\n\n\nwarnIMG.setValue(\"<img src=\\\"VAADIN/themes/valo/images/sprite_all2.svg#ristampa\\\">\");\nwarnIMG.setWidth(\"30px\");\nwarnIMG.setHeight(\"30px\");\n\n\nLabel[] labels = new Label[text.length];\nfor (int i = 0; i < text.length; i++) {\n Label body = new Label(text[i]);\n body.setSizeFull();\n body.setStyleName(\"bsr-gray\");\n labels[i] = body;\n}\n\nVerticalLayout vl = new VerticalLayout(labels);\nHorizontalLayout result = new HorizontalLayout(warnIMG, vl);\nresult.setSpacing(true);\nresult.setExpandRatio(vl, 1);\nreturn result;\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74380420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3691373/" ]
74,380,421
<p>I have a flat JSON where keys represent different levels.</p> <p>For example:</p> <pre><code>data = { &quot;name&quot;: &quot;John&quot;, &quot;age&quot;: 30, &quot;address:city&quot;: &quot;New-York&quot;, &quot;address:street&quot;: &quot;5th avenue&quot;, &quot;address:number&quot;: 10, } </code></pre> <p>As you can see keys contains <code>:</code> which is the separator for the level.</p> <p>I would like to convert it to have something like this:</p> <pre><code>wanted = { &quot;name&quot;: &quot;John&quot;, &quot;age&quot;: 30, &quot;address&quot;: { &quot;city&quot;: &quot;New-York&quot;, &quot;street&quot;: &quot;5th avenue&quot;, &quot;number&quot;: 10 } } </code></pre> <p>I'm working with Python but here I'm more looking just for logic advice, what would be the best approach to solve this problem in a generic way (not for this specific example only)</p> <p>Thanks for your help</p>
[ { "answer_id": 74380680, "author": "jpseng", "author_id": 16332641, "author_profile": "https://Stackoverflow.com/users/16332641", "pm_score": 0, "selected": false, "text": "jq 'reduce to_entries[] as {$key, $value} ({}; setpath($key / \":\"; $value))'\n" }, { "answer_id": 74381157, "author": "VPfB", "author_id": 5378816, "author_profile": "https://Stackoverflow.com/users/5378816", "pm_score": 0, "selected": false, "text": "def convert(inp, sep=':'):\n output = {}\n for key, value in inp.items():\n *path, skey = key.split(sep)\n dest = output\n for p in path:\n if p not in dest:\n dest[p] = dict()\n dest = dest[p]\n dest[skey] = value\n return output\n" }, { "answer_id": 74381416, "author": "0x0fba", "author_id": 20339407, "author_profile": "https://Stackoverflow.com/users/20339407", "pm_score": 2, "selected": true, "text": "from typing import Any\n\ndef build(key: list[str], value: Any, res: dict):\n k, *r = key\n if r:\n if not res.get(k):\n res[k] = {}\n build(r, value, res[k])\n else:\n res[k] = value\n\nres = {}\nfor k, v in data.items():\n build(k.split(\":\"), v, res)\n" }, { "answer_id": 74382049, "author": "Vincent Casey", "author_id": 13171500, "author_profile": "https://Stackoverflow.com/users/13171500", "pm_score": 0, "selected": false, "text": "\n# Data input\ndata = {\n \"name\": \"John\",\n \"age\": 30,\n \"address:city\": \"New-York\",\n \"address:street\": \"5th avenue\",\n \"address:number\": 10,\n}\n\n# Initiate output\noutput = {\n\n}\n\n# Get keys in data\nkeys = data.keys()\n\n# Iterate through keys\nfor i in keys:\n \n # If there is a seperator, make sub-dcitionary. If not then proceed to add data normally.\n if \":\" in i:\n\n # Extract subdictionary title and element name\n split = i.split(\":\")\n\n # If the subdictionary doesn't already exist, create it\n if not (split[0] in output.keys()):\n output[split[0]] = {}\n\n # Add element to subdictionary\n output[split[0]][split[1]]=data[i]\n else:\n output[i]=data[i]\n\n# Print out results\nprint(output)\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74380421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6240756/" ]
74,380,428
<p>I want to achieve similar effect to the google play books app where searchbar expands and takes the whole screen. Currently I have simple Textfield that sits in Card widget and elevates it and the whole thing is in Appbar. How should I approach it? (I'm using material you 3)</p> <pre><code> appBar: AppBar( title: Card( elevation: 2, child: TextField( autocorrect: false, controller: _textEditingController, onChanged: (value) { setState(() {}); }, decoration: InputDecoration( hintText: &quot;Search&quot;, border: InputBorder.none, prefixIcon: const Icon( Icons.search, ), suffixIcon: _textEditingController.text.isEmpty ? null : IconButton( icon: const Icon(Icons.clear), onPressed: _clearTextField, ), ), ), ), ) </code></pre> <p><a href="https://i.stack.imgur.com/Os6rx.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Os6rx.gif" alt="example" /></a></p>
[ { "answer_id": 74380680, "author": "jpseng", "author_id": 16332641, "author_profile": "https://Stackoverflow.com/users/16332641", "pm_score": 0, "selected": false, "text": "jq 'reduce to_entries[] as {$key, $value} ({}; setpath($key / \":\"; $value))'\n" }, { "answer_id": 74381157, "author": "VPfB", "author_id": 5378816, "author_profile": "https://Stackoverflow.com/users/5378816", "pm_score": 0, "selected": false, "text": "def convert(inp, sep=':'):\n output = {}\n for key, value in inp.items():\n *path, skey = key.split(sep)\n dest = output\n for p in path:\n if p not in dest:\n dest[p] = dict()\n dest = dest[p]\n dest[skey] = value\n return output\n" }, { "answer_id": 74381416, "author": "0x0fba", "author_id": 20339407, "author_profile": "https://Stackoverflow.com/users/20339407", "pm_score": 2, "selected": true, "text": "from typing import Any\n\ndef build(key: list[str], value: Any, res: dict):\n k, *r = key\n if r:\n if not res.get(k):\n res[k] = {}\n build(r, value, res[k])\n else:\n res[k] = value\n\nres = {}\nfor k, v in data.items():\n build(k.split(\":\"), v, res)\n" }, { "answer_id": 74382049, "author": "Vincent Casey", "author_id": 13171500, "author_profile": "https://Stackoverflow.com/users/13171500", "pm_score": 0, "selected": false, "text": "\n# Data input\ndata = {\n \"name\": \"John\",\n \"age\": 30,\n \"address:city\": \"New-York\",\n \"address:street\": \"5th avenue\",\n \"address:number\": 10,\n}\n\n# Initiate output\noutput = {\n\n}\n\n# Get keys in data\nkeys = data.keys()\n\n# Iterate through keys\nfor i in keys:\n \n # If there is a seperator, make sub-dcitionary. If not then proceed to add data normally.\n if \":\" in i:\n\n # Extract subdictionary title and element name\n split = i.split(\":\")\n\n # If the subdictionary doesn't already exist, create it\n if not (split[0] in output.keys()):\n output[split[0]] = {}\n\n # Add element to subdictionary\n output[split[0]][split[1]]=data[i]\n else:\n output[i]=data[i]\n\n# Print out results\nprint(output)\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74380428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12191215/" ]
74,380,430
<p>I'm attempting to initialize a table called, &quot;character&quot;, in a MySQL server database, and I am getting the SQL syntax error provided below:</p> <pre><code>You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'character ( character_id INT PRIMARY KEY, first_name VARCHAR(20) NOT NUL' at line 1 </code></pre> <p>My SQL code is as follows:</p> <pre><code>CREATE TABLE character ( character_id INT PRIMARY KEY, first_name VARCHAR(20) NOT NULL, last_name VARCHAR(20) NOT NULL, branch VARCHAR(40) NOT NULL, game_wins INT(5) DEFAULT 'N/A', game_losses INT(5) DEFAULT 'N/A', match_wins INT(6) DEFAULT 'N/A', match_ties INT(6) DEFAULT 'N/A', match_losses INT(6) DEFAULT 'N/A', match_no INT(6) DEFAULT 'N/A' ); </code></pre> <p>I must be missing a syntax error that is straightforward but I've looked over this code block several times and I cannot seem to pinpoint the issue.</p>
[ { "answer_id": 74380680, "author": "jpseng", "author_id": 16332641, "author_profile": "https://Stackoverflow.com/users/16332641", "pm_score": 0, "selected": false, "text": "jq 'reduce to_entries[] as {$key, $value} ({}; setpath($key / \":\"; $value))'\n" }, { "answer_id": 74381157, "author": "VPfB", "author_id": 5378816, "author_profile": "https://Stackoverflow.com/users/5378816", "pm_score": 0, "selected": false, "text": "def convert(inp, sep=':'):\n output = {}\n for key, value in inp.items():\n *path, skey = key.split(sep)\n dest = output\n for p in path:\n if p not in dest:\n dest[p] = dict()\n dest = dest[p]\n dest[skey] = value\n return output\n" }, { "answer_id": 74381416, "author": "0x0fba", "author_id": 20339407, "author_profile": "https://Stackoverflow.com/users/20339407", "pm_score": 2, "selected": true, "text": "from typing import Any\n\ndef build(key: list[str], value: Any, res: dict):\n k, *r = key\n if r:\n if not res.get(k):\n res[k] = {}\n build(r, value, res[k])\n else:\n res[k] = value\n\nres = {}\nfor k, v in data.items():\n build(k.split(\":\"), v, res)\n" }, { "answer_id": 74382049, "author": "Vincent Casey", "author_id": 13171500, "author_profile": "https://Stackoverflow.com/users/13171500", "pm_score": 0, "selected": false, "text": "\n# Data input\ndata = {\n \"name\": \"John\",\n \"age\": 30,\n \"address:city\": \"New-York\",\n \"address:street\": \"5th avenue\",\n \"address:number\": 10,\n}\n\n# Initiate output\noutput = {\n\n}\n\n# Get keys in data\nkeys = data.keys()\n\n# Iterate through keys\nfor i in keys:\n \n # If there is a seperator, make sub-dcitionary. If not then proceed to add data normally.\n if \":\" in i:\n\n # Extract subdictionary title and element name\n split = i.split(\":\")\n\n # If the subdictionary doesn't already exist, create it\n if not (split[0] in output.keys()):\n output[split[0]] = {}\n\n # Add element to subdictionary\n output[split[0]][split[1]]=data[i]\n else:\n output[i]=data[i]\n\n# Print out results\nprint(output)\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74380430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20073587/" ]
74,380,466
<p>I've been looking during 2 days for <strong>a sotfware which allows me to limit the time I play</strong>(or use any program) and I found nothing usefull so I decided to put my coding cape back since 6 years ago and program it myself.</p> <p>A friend recommended me powershell as the easiest and faster way to do it. I have no idea of powershell but I've come to this: With</p> <pre><code>gps | ? { $_.MainWindowTitle } </code></pre> <p>I check the running processes . Then with an if clause I would define if the game is being runned, if it is being runned I use</p> <pre><code>$StartTime = Get-Process processOfTheGame | select starttime </code></pre> <p>to know when the game started. And then I should use another if clause to compare it with actual date</p> <pre><code>Get-Date </code></pre> <p>but im finding problems to compare it as Get-Process processOfTheGame | select starttime data type is PSCustomObject so it is throwing me errors when I try to change the format to datetype.</p> <p><strong>So i need help to</strong> convert the $StartTime variable to datetype and then to compare it with the actual date. and if the actual date is 2 houres more than $StartTime close the program with</p> <pre><code>Stop-process -name GAME </code></pre> <p>Things i've tried</p> <pre><code>$testConversion = [datetime]::ParseExact($StartTime, 'dd/MM/yyyy' ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodException + FullyQualifiedErrorId : MethodCountCouldNotFindBest </code></pre> <pre><code>[datetime]::parseexact($StartTime, 'dd-MMM-yy', $null) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodException + FullyQualifiedErrorId : MethodCountCouldNotFindBest </code></pre> <pre><code>$Date = get-date $StartTime -Format &quot;dd-MM-yyyy&quot; + ~~~~~~~~~~ + CategoryInfo : InvalidArgument: (:) [Get-Date], ParameterBindingException + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.GetDateCommand </code></pre> <pre><code>PS&gt; $Obj = ((get-date &quot;10/22/2020 12:51:1&quot;) - (get-date &quot;10/22/2020 12:20:1 &quot;)) </code></pre> <p>I tried it with a &quot;flat&quot; date cause it is supposed to work that way but it does not. It neither works with the variable StartTime</p> <pre><code>PS&gt; $Obj = ((get-date &quot;10/22/2020 12:51:1&quot;) - (get-date &quot;10/2 ... + ~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (:) [Get-Date], ParameterBindingException + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.GetDateCommand </code></pre>
[ { "answer_id": 74380680, "author": "jpseng", "author_id": 16332641, "author_profile": "https://Stackoverflow.com/users/16332641", "pm_score": 0, "selected": false, "text": "jq 'reduce to_entries[] as {$key, $value} ({}; setpath($key / \":\"; $value))'\n" }, { "answer_id": 74381157, "author": "VPfB", "author_id": 5378816, "author_profile": "https://Stackoverflow.com/users/5378816", "pm_score": 0, "selected": false, "text": "def convert(inp, sep=':'):\n output = {}\n for key, value in inp.items():\n *path, skey = key.split(sep)\n dest = output\n for p in path:\n if p not in dest:\n dest[p] = dict()\n dest = dest[p]\n dest[skey] = value\n return output\n" }, { "answer_id": 74381416, "author": "0x0fba", "author_id": 20339407, "author_profile": "https://Stackoverflow.com/users/20339407", "pm_score": 2, "selected": true, "text": "from typing import Any\n\ndef build(key: list[str], value: Any, res: dict):\n k, *r = key\n if r:\n if not res.get(k):\n res[k] = {}\n build(r, value, res[k])\n else:\n res[k] = value\n\nres = {}\nfor k, v in data.items():\n build(k.split(\":\"), v, res)\n" }, { "answer_id": 74382049, "author": "Vincent Casey", "author_id": 13171500, "author_profile": "https://Stackoverflow.com/users/13171500", "pm_score": 0, "selected": false, "text": "\n# Data input\ndata = {\n \"name\": \"John\",\n \"age\": 30,\n \"address:city\": \"New-York\",\n \"address:street\": \"5th avenue\",\n \"address:number\": 10,\n}\n\n# Initiate output\noutput = {\n\n}\n\n# Get keys in data\nkeys = data.keys()\n\n# Iterate through keys\nfor i in keys:\n \n # If there is a seperator, make sub-dcitionary. If not then proceed to add data normally.\n if \":\" in i:\n\n # Extract subdictionary title and element name\n split = i.split(\":\")\n\n # If the subdictionary doesn't already exist, create it\n if not (split[0] in output.keys()):\n output[split[0]] = {}\n\n # Add element to subdictionary\n output[split[0]][split[1]]=data[i]\n else:\n output[i]=data[i]\n\n# Print out results\nprint(output)\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74380466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14677704/" ]
74,380,489
<p>I'm a newbie and I'm looking to get my basic HTML calculator working.</p> <p>I have the JavaScript working to the point it's logging the button presses from my HTML buttons in a string variable. So for example if I click 9 * 9 on the calculator I can see I have a string &quot;9*9&quot; in the console which is what I was after.</p> <p>I have been trying to get JavaScript to treat the string as a mathematical statement and I understand I need an anonymous function to get JS to calculate the string so &quot;10*10&quot; becomes 100 for example.</p> <p>However, when my function is called from the event listener on my equals button, I am not getting a result in the console. I added a console log to at least let me know the equals button press was registered and it is. I only get a numerical result if I call the function in the code with a console log separately, or I set the userInput variable at the point of declaration to a string suitable for calculating e.e. &quot;10*10&quot;. So It's kind of working but I can't get it to calculate userInput in normal use, only when it's been hard coded. I have double checked userInput is a string user typeof and it is.</p> <pre><code>// My event listener statement is here: eqs.addEventListener(&quot;click&quot;, calcs); </code></pre> <p>When I click = I hoped calcs is called and the return statement is returned with whatever the value of userInput is, and it gets calculated.</p> <pre><code>// The function: function calcs() { return new Function(&quot;return &quot; + userInput)(); } </code></pre> <p>First ever post so this is likely missing key bits of info but any help gratefully received.</p>
[ { "answer_id": 74380680, "author": "jpseng", "author_id": 16332641, "author_profile": "https://Stackoverflow.com/users/16332641", "pm_score": 0, "selected": false, "text": "jq 'reduce to_entries[] as {$key, $value} ({}; setpath($key / \":\"; $value))'\n" }, { "answer_id": 74381157, "author": "VPfB", "author_id": 5378816, "author_profile": "https://Stackoverflow.com/users/5378816", "pm_score": 0, "selected": false, "text": "def convert(inp, sep=':'):\n output = {}\n for key, value in inp.items():\n *path, skey = key.split(sep)\n dest = output\n for p in path:\n if p not in dest:\n dest[p] = dict()\n dest = dest[p]\n dest[skey] = value\n return output\n" }, { "answer_id": 74381416, "author": "0x0fba", "author_id": 20339407, "author_profile": "https://Stackoverflow.com/users/20339407", "pm_score": 2, "selected": true, "text": "from typing import Any\n\ndef build(key: list[str], value: Any, res: dict):\n k, *r = key\n if r:\n if not res.get(k):\n res[k] = {}\n build(r, value, res[k])\n else:\n res[k] = value\n\nres = {}\nfor k, v in data.items():\n build(k.split(\":\"), v, res)\n" }, { "answer_id": 74382049, "author": "Vincent Casey", "author_id": 13171500, "author_profile": "https://Stackoverflow.com/users/13171500", "pm_score": 0, "selected": false, "text": "\n# Data input\ndata = {\n \"name\": \"John\",\n \"age\": 30,\n \"address:city\": \"New-York\",\n \"address:street\": \"5th avenue\",\n \"address:number\": 10,\n}\n\n# Initiate output\noutput = {\n\n}\n\n# Get keys in data\nkeys = data.keys()\n\n# Iterate through keys\nfor i in keys:\n \n # If there is a seperator, make sub-dcitionary. If not then proceed to add data normally.\n if \":\" in i:\n\n # Extract subdictionary title and element name\n split = i.split(\":\")\n\n # If the subdictionary doesn't already exist, create it\n if not (split[0] in output.keys()):\n output[split[0]] = {}\n\n # Add element to subdictionary\n output[split[0]][split[1]]=data[i]\n else:\n output[i]=data[i]\n\n# Print out results\nprint(output)\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74380489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20462058/" ]
74,380,521
<p>I'm getting my JSON data as such:</p> <pre><code>{ &quot;cars&quot;: [ { &quot;make&quot;:&quot;BMW&quot;, &quot;model&quot;:&quot;X3&quot;, &quot;Lot&quot;:&quot;Used&quot; }, { &quot;make&quot;:&quot;BMW&quot;, &quot;model&quot;:&quot;520&quot;, &quot;Lot&quot;:&quot;Used&quot; }, { &quot;make&quot;:&quot;Mercedes&quot;, &quot;model&quot;:&quot;550&quot;, &quot;Lot&quot;:&quot;New&quot; }, { &quot;make&quot;:&quot;Mercedes&quot;, &quot;model&quot;:&quot;C400&quot;, &quot;Lot&quot;:&quot;Used&quot; } ] } </code></pre> <p>I want to group them by the make to show in my dropdown list like so:</p> <pre><code> BMW Used X3 520 Mercedes New 550 Used C400 </code></pre> <p>I'm currently using this on a React page and I have the dropdown populated, I'd like to group them as such instead of showing everything on one line for each record</p>
[ { "answer_id": 74380650, "author": "JustWantsToCode", "author_id": 8382717, "author_profile": "https://Stackoverflow.com/users/8382717", "pm_score": 0, "selected": false, "text": "const getAllCars = () => {\n allCars.GetAllCars()\n .then((response) => {\n setallCars(response.data)\n })\n .catch((e) => { console.log(e)}\n\n}\n\nreturn (\n <select> \n <option value ='0'>\n { carTypes.map(data => (\n <option\n value={data.make}\n >\n { data.make }\n </option>\n )\n )\n" }, { "answer_id": 74380665, "author": "kind user", "author_id": 6695924, "author_profile": "https://Stackoverflow.com/users/6695924", "pm_score": 1, "selected": false, "text": "Array#reduce" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74380521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8382717/" ]
74,380,545
<p>I am struggling to extract the text between two works. Specifically, I would like to extract the text between Example and Constraints. Here is a sample</p> <pre><code>&quot;Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.\nYou can return the answer in any order.\n Example 1:\nInput: nums = [2,7,11,15], target = 9\nOutput: [0,1]\nExplanation: Because nums[0] + nums[1] == 9, we return [0, 1].\nExample 2:\nInput: nums = [3,2,4], target = 6\nOutput: [1,2]\nExample 3:\nInput: nums = [3,3], target = 6\nOutput: [0,1]\n Constraints:\n2 &lt;= nums.length &lt;= 104\n-109 &lt;= nums[i] &lt;= 109\n-109 &lt;= target &lt;= 109\nOnly one valid answer exists.\n Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?&quot; </code></pre> <p>This is a row in a pandas dataframe</p> <p>This is what I have tried:</p> <pre><code>def extract(example): return example.str.extract('(Example.*(?=.Constraints))') </code></pre> <p>this returns null.</p>
[ { "answer_id": 74380650, "author": "JustWantsToCode", "author_id": 8382717, "author_profile": "https://Stackoverflow.com/users/8382717", "pm_score": 0, "selected": false, "text": "const getAllCars = () => {\n allCars.GetAllCars()\n .then((response) => {\n setallCars(response.data)\n })\n .catch((e) => { console.log(e)}\n\n}\n\nreturn (\n <select> \n <option value ='0'>\n { carTypes.map(data => (\n <option\n value={data.make}\n >\n { data.make }\n </option>\n )\n )\n" }, { "answer_id": 74380665, "author": "kind user", "author_id": 6695924, "author_profile": "https://Stackoverflow.com/users/6695924", "pm_score": 1, "selected": false, "text": "Array#reduce" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74380545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7158458/" ]
74,380,583
<p>I need to create a new array as you can see it has a key value that specifies the latitude and longitude.</p> <p>I want the key values ​​that are equal to be set as 1 only but according to who has the highest count</p> <pre><code>[ { &quot;color&quot;:&quot;green&quot;, &quot;coment_calification&quot;:&quot;Califica&quot;, &quot;count&quot;:7, &quot;key&quot;:&quot;-13.0711552&amp;-76.3723776&amp;Califica&quot;, &quot;latitud&quot;:&quot;-13.0711552&quot;, &quot;longitud&quot;:&quot;-76.3723776&quot; }, { &quot;color&quot;:&quot;yellow&quot;, &quot;coment_calification&quot;:&quot;Reporte&quot;, &quot;count&quot;:6, &quot;key&quot;:&quot;-13.0711552&amp;-76.3723776&amp;Reporte&quot;, &quot;latitud&quot;:&quot;-13.0711552&quot;, &quot;longitud&quot;:&quot;-76.3723776&quot; }, { &quot;color&quot;:&quot;green&quot;, &quot;coment_calification&quot;:&quot;Califica&quot;, &quot;count&quot;:1, &quot;key&quot;:&quot;-13.1711552&amp;-76.3423776&amp;Califica&quot;, &quot;latitud&quot;:&quot;-13.1711552&quot;, &quot;longitud&quot;:&quot;-76.3423776&quot; }, { &quot;color&quot;:&quot;yellow&quot;, &quot;coment_calification&quot;:&quot;Reporte&quot;, &quot;count&quot;:2, &quot;key&quot;:&quot;-13.1711552&amp;-76.3423776&amp;Reporte&quot;, &quot;latitud&quot;:&quot;-13.1711552&quot;, &quot;longitud&quot;:&quot;-76.3423776&quot; } ] </code></pre> <pre><code> let result = count.filter((e) =&gt; e &amp;&amp; e.count &amp;&amp; e.key == e.key); let datas = result; </code></pre>
[ { "answer_id": 74380650, "author": "JustWantsToCode", "author_id": 8382717, "author_profile": "https://Stackoverflow.com/users/8382717", "pm_score": 0, "selected": false, "text": "const getAllCars = () => {\n allCars.GetAllCars()\n .then((response) => {\n setallCars(response.data)\n })\n .catch((e) => { console.log(e)}\n\n}\n\nreturn (\n <select> \n <option value ='0'>\n { carTypes.map(data => (\n <option\n value={data.make}\n >\n { data.make }\n </option>\n )\n )\n" }, { "answer_id": 74380665, "author": "kind user", "author_id": 6695924, "author_profile": "https://Stackoverflow.com/users/6695924", "pm_score": 1, "selected": false, "text": "Array#reduce" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74380583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20462347/" ]
74,380,607
<p>I'm having a problem trying to pass data into the &quot;amount&quot; param.</p> <p>I am sending the &quot;price&quot; from the client to the server.</p> <p>When I output the data into the console, I get the correct information.</p> <p>When I check the &quot;typeOf&quot;, i get &quot;number&quot; which is the expected output.</p> <p>However, when I run the application, I am getting the error</p> <p>&quot;UnhandledPromiseRejectionWarning: Error: Invalid integer: NaN&quot;</p> <p>It seems like the &quot;paymentIntents.create&quot; method isnt reading the data. <code>your text</code></p> <p>What am I doing wrong here?</p> <p>How can I pass by price field into the amount param.</p> <p>Here is my code:</p> <p>`</p> <pre><code>const express = require(&quot;express&quot;); const app = express(); const { resolve } = require(&quot;path&quot;); const stripe = require(&quot;stripe&quot;)(process.env.secret_key); // https://stripe.com/docs/keys#obtain-api-keys app.use(express.static(&quot;.&quot;)); app.use(express.json()); const calculateOrderAmount = price =&gt;{ const total = price * 100 return total } // An endpoint for your checkout app.post(&quot;/payment-sheet&quot;, async (req, res) =&gt; { const price = req.body.price console.log(typeof calculateOrderAmount(price)) const paymentIntent = await stripe.paymentIntents.create({ amount: calculateOrderAmount(price), currency: &quot;usd&quot;, //customer: customer.id, automatic_payment_methods: { enabled: true, }, }); // Send the object keys to the client res.json({ publishableKey: process.env.publishable_key, // https://stripe.com/docs/keys#obtain-api-keys paymentIntent: paymentIntent.client_secret, //customer: customer.id, //ephemeralKey: ephemeralKey.secret }); }); app.listen(process.env.PORT, () =&gt; console.log(`Node server listening on port ${process.env.PORT}!`) ); </code></pre> <p>`</p> <p>Ive tried to send the &quot;price&quot; field directly without doing the calculation and the error returned is:</p> <pre><code>Error: Missing required param: amount. </code></pre>
[ { "answer_id": 74380743, "author": "bismarck", "author_id": 18506404, "author_profile": "https://Stackoverflow.com/users/18506404", "pm_score": -1, "selected": true, "text": "amount" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74380607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19367048/" ]
74,380,618
<p>I have this vector of names:</p> <pre><code>vector &lt;string&gt; names; names.push_back(&quot;William&quot;); names.push_back(&quot;Maria&quot;); names.push_back(&quot;Petterson&quot;); names.push_back(&quot;McCarthy&quot;); names.push_back(&quot;Jose&quot;); names.push_back(&quot;Pedro&quot;); names.push_back(&quot;Hang&quot;); </code></pre> <p>I need to display this vector IN ORDER using a reverse iterator.</p> <p>This is my attempt:</p> <pre><code>//Define a reverse iterator for the vector object vector&lt;string&gt;::reverse_iterator itR = names.rend(); itR = itR - 1; //Use the reverse iterator to display each element in the vector cout &lt;&lt; &quot;\tNames:\n&quot;; while (itR != names.rbegin()) { cout &lt;&lt; *itR &lt;&lt; endl; itR--; } </code></pre> <p>This will display all names in correct order BUT it cuts off &quot;Hang&quot; at the end, any tips?</p>
[ { "answer_id": 74380736, "author": "Vlad from Moscow", "author_id": 2877241, "author_profile": "https://Stackoverflow.com/users/2877241", "pm_score": -1, "selected": false, "text": "while (itR != names.rbegin())\n" }, { "answer_id": 74380781, "author": "fabian", "author_id": 2991525, "author_profile": "https://Stackoverflow.com/users/2991525", "pm_score": 2, "selected": true, "text": "// print elements in original (= non-reversed) order\nfor (auto pos = names.rend(); pos != names.rbegin();)\n{\n --pos;\n std::cout << *pos << std::endl;\n}\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74380618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18992797/" ]
74,380,623
<p>We have these tables in PostgreSQL 12:</p> <pre> User -> id, name, email items -> id, user_id, description </pre> <p>We want to run a query to find users that have 1 item or less.</p> <p>I tried using a join statement and in the WHERE clause tried to put the count of users &lt; 1 with this query</p> <pre><code>select * from &quot;user&quot; inner join item on &quot;user&quot;.id = item.user_id where count(item.user_id) &lt; 1; </code></pre> <p>but it failed and gave me this error.</p> <blockquote> <p>ERROR: aggregate functions are not allowed in WHERE LINE 1: ...inner join item on &quot;user&quot;.id = item.user_id where count(item...</p> </blockquote> <p>so im thinking the query needs to be more techincal. Can anyone please help me with this? thanks</p>
[ { "answer_id": 74380736, "author": "Vlad from Moscow", "author_id": 2877241, "author_profile": "https://Stackoverflow.com/users/2877241", "pm_score": -1, "selected": false, "text": "while (itR != names.rbegin())\n" }, { "answer_id": 74380781, "author": "fabian", "author_id": 2991525, "author_profile": "https://Stackoverflow.com/users/2991525", "pm_score": 2, "selected": true, "text": "// print elements in original (= non-reversed) order\nfor (auto pos = names.rend(); pos != names.rbegin();)\n{\n --pos;\n std::cout << *pos << std::endl;\n}\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74380623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18907309/" ]
74,380,630
<p>The database for an application I manage use UUIDs. These UUIDs are stored as <code>char(36)</code> with a <code>utf8</code> character set. From a strict performance point of view, I know this is not optimal. The general recommendation seem to be to use a <code>binary(16)</code> column for UUIDs. I cannot change the data type, but I can change the character set.</p> <p>The characters in a UUID can be a digit 0 through 9, or letter a through f.</p> <p>By changing the character set from <code>utf8</code> to <code>ascii</code>, the total size of all indexes for the database will probably be reduced by several gigabytes.</p> <p>The application connects to the database and explicitly sets character encoding and connection collation in the connection string : <code>characterEncoding=utf8&amp;connectionCollation=utf8</code>.</p> <p>What will I have to do (if anything at all) to ensure a safe &quot;conversion&quot; from utf8 to ascii for the UUIDs?</p>
[ { "answer_id": 74383301, "author": "Rick James", "author_id": 1766831, "author_profile": "https://Stackoverflow.com/users/1766831", "pm_score": 1, "selected": false, "text": "JOINing" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74380630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/355232/" ]
74,380,634
<p>I've got a list of customers which I'm binding to a CollectionView in .Net Maui. If a value of a boolean in the bound objects is set to false, I want to set the background color of the frame to red. Otherwise, I just want to keep it &quot;normal&quot; / default.</p> <pre><code> &lt;CollectionView Grid.Row=&quot;5&quot; Grid.ColumnSpan=&quot;2&quot; ItemsSource=&quot;{Binding Items}&quot; SelectionMode=&quot;None&quot;&gt; &lt;CollectionView.ItemTemplate&gt; &lt;DataTemplate x:DataType=&quot;dm:CustomerReturn&quot;&gt; &lt;SwipeView&gt; &lt;SwipeView.RightItems&gt; &lt;SwipeItem Text=&quot;Delete&quot; BackgroundColor=&quot;Red&quot;/&gt; &lt;/SwipeView.RightItems&gt; &lt;Frame BackgroundColor=&quot;{Binding ???}&quot;&gt; ... </code></pre> <p>The ObservableConnection (items) of objects:</p> <pre><code> public class CustomerReturn { public int Id { get; set; } public DateTime Created { get; } public DateTime Updated { get; } public string? CustomerName { get; set; } public string? CustomerPhone { get; set; } public string? CustomerEmail { get; set; } public string? CustomerGuid { get; set; } public bool isValid { get; set; } } </code></pre> <p>Items is populated with the customerReturn collection.</p>
[ { "answer_id": 74380923, "author": "Siegfried.V", "author_id": 7310000, "author_profile": "https://Stackoverflow.com/users/7310000", "pm_score": 3, "selected": true, "text": "<DataTrigger Binding=\"{Binding IsValid}\" Value=\"true\">\n <Setter Property=\"Background\" Value=\"#FFFFFF\"/>\n</DataTrigger>\n" }, { "answer_id": 74381121, "author": "Zonus", "author_id": 1623023, "author_profile": "https://Stackoverflow.com/users/1623023", "pm_score": 1, "selected": false, "text": " <Frame>\n <Frame.Triggers>\n <DataTrigger TargetType=\"Frame\"\n Binding=\"{Binding Source={x:Reference isValid},Path=IsChecked}\"\n Value=\"false\">\n <Setter Property=\"BackgroundColor\" Value=\"Red\"/>\n </DataTrigger>\n </Frame.Triggers>\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74380634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1623023/" ]
74,380,644
<p>I'm trying to join 2 tables and count the number of entries for unique variables in one of the columns. In this case I'm trying to join 2 tables - <code>patients</code> and <code>trials</code> (patients has a FK to trials) and count the number of patients that show up in each trial. This is the code i have so far:</p> <pre><code>SELECT patients.trial_id, trials.title FROM trials JOIN(SELECT patients, COUNT(id) AS Num_Enrolled FROM patients GROUP BY trials) AS Trial_Name; </code></pre> <p>The Outcome I'm trying to acheive is:</p> <pre><code>Trial_Name Num_Patients Bushtucker 5 Tribulations 7 </code></pre> <p>I'm completely new to sql and have been struggling with the syntax compared to scripting languages.</p>
[ { "answer_id": 74380753, "author": "Stu", "author_id": 15332650, "author_profile": "https://Stackoverflow.com/users/15332650", "pm_score": 2, "selected": true, "text": "select t.title Trial_Name, Count(*) Num_Patients\nfrom Trials t\njoin Patients p on p.Trial_Id = t.Id\ngroup by t.title;\n" }, { "answer_id": 74380883, "author": "anar1501", "author_id": 14558434, "author_profile": "https://Stackoverflow.com/users/14558434", "pm_score": 0, "selected": false, "text": "SELECT trial.title AS Trial_Name, COUNT(p.id) AS Num_Patients\nFROM trial\nINNER JOIN patients AS p\nON trial.patient_fk_id = p.id\nGROUP BY trial.title,p.id;\n" } ]
2022/11/09
[ "https://Stackoverflow.com/questions/74380644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11370582/" ]