qid
int64
4
22.2M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,361,666
<p>I'm working on developing a Python library related to financial modelling.</p> <p>The thing is, a lot of the functions I am creating depend on inputs that are being fed as tables (which I'm treating as Pandas DataFrames) to the functions I am creating. For example, what I do a lot is functions that take a Pandas DataFrame as an argument and manipulate those DataFrame columns and give a result as an output, here is what I mean:</p> <pre><code>def example_function(input:pd.DataFrame) -&gt; float: input['created_column'] = input['col_1'] + input['col_2'] return input['created_column'].sum() </code></pre> <p>The functions I have are a lot more complex than this but you get the idea.</p> <p>The thing that rubs me the wrong way about this is that the function will only work if the DataFrame being fed has the same exact structure every time, so, if the user feeds a slightly different DataFrame, everything will break.</p> <p>I'm having a hard time figuring out a solution to this problem, without adding a ton of complexity to the functions, since the functions that I'm actually developing are much more complex than this. Depending on several different information contained on those tables.</p> <p>Is this way of developing actually a bad practice? If so, how should I actually go about as developing these functions?</p> <p>What I have developed is functions that look like the example I've shown above. And I'm having a hard time figuring out if this is actually the best approach I could take.</p>
[ { "answer_id": 74361817, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 2, "selected": true, "text": "IllegalStateException" }, { "answer_id": 74361832, "author": "Moe Singh", "author_id": 3817061, "author_profile": "https://Stackoverflow.com/users/3817061", "pm_score": 0, "selected": false, "text": " private static String findBestValue(List<String> list) {\n return list.stream().filter(str -> str.equals(\"a\"))\n .findFirst()\n .orElse(list.stream().filter(str -> str.equals(\"b\"))\n .findFirst()\n .orElse(list.stream().filter(str -> str.equals(\"c\"))\n .findFirst()\n .orElse(null)));\n }\n" }, { "answer_id": 74362648, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "private static <T> T findBestValue(Stream<T> stream, T... keys) {\n Set<T> set = stream.collect(Collectors.toSet());\n return Stream.of(keys)\n .filter(set::contains)\n .findFirst()\n .orElse(null);\n}\n\npublic static void main(String[] args) {\n Stream<String> stream0 = Stream.of(\"a\", \"b\", \"c\", \"d\");\n Stream<String> stream1 = Stream.of(\"b\", \"c\", \"d\", \"a\");\n Stream<String> stream2 = Stream.of(\"b\", \"c\", \"d\", \"e\");\n Stream<String> stream3 = Stream.of(\"d\", \"e\", \"f\", \"g\");\n\n System.out.println(findBestValue(stream0, \"a\", \"b\", \"c\")); //should return \"a\"\n System.out.println(findBestValue(stream1, \"a\", \"b\", \"c\")); //should return \"a\"\n System.out.println(findBestValue(stream2, \"a\", \"b\", \"c\")); //should return \"b\"\n System.out.println(findBestValue(stream3, \"a\", \"b\", \"c\")); //should return null\n}\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74361666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16261029/" ]
74,361,667
<p><strong>I have a Model with Clients:</strong></p> <pre><code>public class Client { [Key] public int id { get; set; } [Required] public string? Hostname { get; set; } public ICollection&lt;Software&gt;? Softwares { get; set; } } </code></pre> <p><strong>And a Model with Software:</strong></p> <pre><code>public class Software { [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int id { get; set; } public string Name { get; set; } public ICollection&lt;Client&gt;? Clients { get; set; } } </code></pre> <p><strong>This is supposed to be an n to n connection. How can I add software to my clients?</strong></p> <p><strong>What I've tried:</strong></p> <pre><code>public async void add(Software software) { using (var repo = new ClientRepository(contextFactory.CreateDbContext())) { client.Softwares.Add(software); await repo.Save(client); } </code></pre> <p><strong>Repository:</strong></p> <pre><code>public async Task Save(Client client) { _context.Clients.Update(client); _context.SaveChanges(); } } </code></pre> <p>This works for the first software I add, but gives me the following error if I try to add a second one:</p> <blockquote> <p>SqlException: Violation of PRIMARY KEY constraint 'PK_ClientSoftware'. Cannot insert duplicate key in object 'dbo.ClientSoftware'. The duplicate key value is (7003, 5002).</p> </blockquote>
[ { "answer_id": 74361817, "author": "Alexander Ivanchenko", "author_id": 17949945, "author_profile": "https://Stackoverflow.com/users/17949945", "pm_score": 2, "selected": true, "text": "IllegalStateException" }, { "answer_id": 74361832, "author": "Moe Singh", "author_id": 3817061, "author_profile": "https://Stackoverflow.com/users/3817061", "pm_score": 0, "selected": false, "text": " private static String findBestValue(List<String> list) {\n return list.stream().filter(str -> str.equals(\"a\"))\n .findFirst()\n .orElse(list.stream().filter(str -> str.equals(\"b\"))\n .findFirst()\n .orElse(list.stream().filter(str -> str.equals(\"c\"))\n .findFirst()\n .orElse(null)));\n }\n" }, { "answer_id": 74362648, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "private static <T> T findBestValue(Stream<T> stream, T... keys) {\n Set<T> set = stream.collect(Collectors.toSet());\n return Stream.of(keys)\n .filter(set::contains)\n .findFirst()\n .orElse(null);\n}\n\npublic static void main(String[] args) {\n Stream<String> stream0 = Stream.of(\"a\", \"b\", \"c\", \"d\");\n Stream<String> stream1 = Stream.of(\"b\", \"c\", \"d\", \"a\");\n Stream<String> stream2 = Stream.of(\"b\", \"c\", \"d\", \"e\");\n Stream<String> stream3 = Stream.of(\"d\", \"e\", \"f\", \"g\");\n\n System.out.println(findBestValue(stream0, \"a\", \"b\", \"c\")); //should return \"a\"\n System.out.println(findBestValue(stream1, \"a\", \"b\", \"c\")); //should return \"a\"\n System.out.println(findBestValue(stream2, \"a\", \"b\", \"c\")); //should return \"b\"\n System.out.println(findBestValue(stream3, \"a\", \"b\", \"c\")); //should return null\n}\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74361667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20128442/" ]
74,361,679
<p>Is it possible to style the first 2 characters of a message another styling?</p> <pre><code>::first-letter </code></pre> <p>Does not do the trick, also looked <a href="https://stackoverflow.com/questions/35328019/css-display-only-the-first-two-letters-of-a-string">at this question</a>, but this only hides the other ones.</p> <p>Is it perhaps possible with the new pseudo elements? Or use the <code>ch</code> in combination with <code>::first-letter</code>?</p> <p>This is what I want to achieve but I have no clue how to do it with pure CSS. <a href="https://i.stack.imgur.com/GoFN4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GoFN4.png" alt="enter image description here" /></a></p> <p><strong>NOTE</strong>, I <em><strong>can not</strong></em> change the HTML.</p> <pre><code>&lt;h4 class=&quot;date&quot;&gt;10 Mar. 2022&lt;/h4&gt; </code></pre>
[ { "answer_id": 74361812, "author": "0stone0", "author_id": 5625547, "author_profile": "https://Stackoverflow.com/users/5625547", "pm_score": 1, "selected": false, "text": "<em></em>" }, { "answer_id": 74361846, "author": "joohong89", "author_id": 9166143, "author_profile": "https://Stackoverflow.com/users/9166143", "pm_score": 0, "selected": false, "text": "var text = $('.date').text();\nvar textArr = text.split(/\\s+/);\n\n$('.date').html(`<span class=\"day\">${textArr[0]}</span>&nbsp;\n <span class=\"month\">${textArr[1]}</span>&nbsp;\n <span class=\"year\">${textArr[2]}</span>`);" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74361679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4561301/" ]
74,361,684
<p>df:</p> <pre><code> first last email 0 Corey Schafer CoreMSchafer@gmail.com 1 Jane Doe JaneDoe@gmail.com 2 John Doe JohnDoe@gmail.com </code></pre> <p>From a big CSV file, how can I find a specific word like John, without knowing on what column or row he is? If there are several names with John, can I get all the info in the row or column where the names are?</p>
[ { "answer_id": 74361716, "author": "Faisal Nazik", "author_id": 13959139, "author_profile": "https://Stackoverflow.com/users/13959139", "pm_score": 1, "selected": false, "text": "import pandas as pd\n\ndf = pd.read_csv('data.csv')\ndf[df['first'].str.contains('John')] # returns all rows where John in the column 'first'\ndf[df['first'].str.contains('John')].index.tolist() # get the index of the rows\n" }, { "answer_id": 74369286, "author": "johnnybarrels", "author_id": 11511200, "author_profile": "https://Stackoverflow.com/users/11511200", "pm_score": 1, "selected": true, "text": ".applymap()" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74361684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20331697/" ]
74,361,692
<p>Sorry if this is a similar question, I tried to find one that could answer my specific use-case but I only found ones that give exact matches between dataframes.</p> <p>I have 2 pandas data frames of descriptions:</p> <p>df1:</p> <pre><code>Description i had lunch going to the airport buying a suitcase </code></pre> <p>df2:</p> <pre><code>Description buying lunch airport travel owning a car </code></pre> <p>I'd like to filter and/or count how many times <code>df2</code> has a matching word that appears in any row of <code>df1</code></p> <p>so for example <code>df2</code> has the words 'lunch' and 'airport' and those single words appear in <code>df1</code>, so I would like to pull out and count the rows in <code>df2</code> that have that match.</p> <p>So my output is just a filtered <code>df2</code> based on single word matches in <code>df1</code>.</p> <p>Example output filtered would be:</p> <p>df2:</p> <pre><code>Description buying lunch airport travel </code></pre> <p>Is there a way I can do this with pandas dataframes?</p> <p>Example input data:</p> <pre><code>d = {'Description': ['i had lunch', 'going to the airport', 'buying a suitcase']} df1 = pd.DataFrame(data=d) d = {'Description': ['buying lunch', 'airport travel', 'owning a car']} df2 = pd.DataFrame(data=d) </code></pre>
[ { "answer_id": 74361917, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": true, "text": "import re\nregex = '|'.join(map(re.escape, df1['Description'].str.split().explode().unique()))\n\nout = df2[df2['Description'].str.contains(fr'\\b({regex})\\b')]\n" }, { "answer_id": 74361996, "author": "maxxel_", "author_id": 17575465, "author_profile": "https://Stackoverflow.com/users/17575465", "pm_score": 0, "selected": false, "text": "result = df2.loc[df2['Description'].isin(df1['Description'].apply(pd.Series).stack().reset_index(drop=True).tolist())\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74361692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8831033/" ]
74,361,698
<p>I am making integration test for my app. I would like to see how cartItems payload my db can write. For that, I have generated cartItems array. Inside that array I have one item called ean. I would like to generate 12 digits random number to ean. But it always return me same number from the array.</p> <p>I have facing two issue</p> <ol> <li>Could not able generate 12 digits ean number</li> <li>When I generate the arrays and the 6 digits ean number always same. But I want random numbers</li> </ol> <p><strong>Here is my code</strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code> const requestParameters = { id: "530d275e-5de1-466d-86fe-3993a2563fb6", cartItems: new Array(500).fill({ additionalInfo: '', brand: '', replace: false, basicQuantityUnit: 'KPL', collectingPriority: 1000, ean: Math.floor(100000 + Math.random() * 900000) + 10000, // I want to render random 12 digits id: '0200097823340', itemCount: '1' }) } console.log(requestParameters)</code></pre> </div> </div> </p>
[ { "answer_id": 74361746, "author": "Konrad", "author_id": 5089567, "author_profile": "https://Stackoverflow.com/users/5089567", "pm_score": 3, "selected": true, "text": "500" }, { "answer_id": 74361881, "author": "xodeeq", "author_id": 13824776, "author_profile": "https://Stackoverflow.com/users/13824776", "pm_score": 1, "selected": false, "text": "Math.floor(100000000000 + Math.random() * 900000000000)\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74361698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12494839/" ]
74,361,725
<p>I have the following df</p> <pre><code>df &lt;- data.frame(name.name1 = c(1, 1, 1), name.name2 = c(2, 2, 2), name.name3 = c(3, 3, 3)) </code></pre> <p>I'm trying to substitute <code>.</code> by space. When I do</p> <pre><code>colnames(df) &lt;- gsub(&quot;^.$&quot;, &quot; &quot;, colnames(df)) </code></pre> <p>What's happening here and how can I proceed?</p>
[ { "answer_id": 74361784, "author": "cgvoller", "author_id": 17144974, "author_profile": "https://Stackoverflow.com/users/17144974", "pm_score": 2, "selected": true, "text": "colnames(df) <- gsub(\"\\\\.\", \" \", colnames(df))\n" }, { "answer_id": 74362171, "author": "zx8754", "author_id": 680068, "author_profile": "https://Stackoverflow.com/users/680068", "pm_score": 2, "selected": false, "text": "#when creating a dataframe\ndata.frame(\"name name1\" = c(1, 1, 1),\n \"name name2\" = c(2, 2, 2),\n \"name name3\"= c(3, 3, 3), check.names = FALSE)\n# name name1 name name2 name name3\n# 1 1 2 3\n# 2 1 2 3\n# 3 1 2 3\n\n#when importing data from file\nread.table(\"myFile.txt\", header = TRUE, check.names = FALSE)\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74361725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15108186/" ]
74,361,756
<p>I coded a small Golang program, that takes N arguments (files with resourceQuota requests for K8s) from a GitHub PR, and writes a file with the total amount of CPU and Memory requested that is then exported as GHA output in the next step.</p> <p>can't do <code>go run main.go /path/to/file1 /path/to/file2</code> because Apparently i hit a bug in <code>actions/setup-go</code> with our self-hosted runner, so i had to containerise that.</p> <p>I'm new to all of these, so my colleagues told me to import the docker program from a self-made GitHub action, all works like a charm when only 1 file is changed in the PR (only 1 arg to handle).</p> <p>Problem is when 2 or more args are passed, because the action im using: <a href="https://github.com/marketplace/actions/changed-files" rel="nofollow noreferrer">tj-actions/changed-files</a> outputs a single string with all the files names and i'm really clueless on how to work around it.</p> <p>this is how i call the self-made action:</p> <pre><code> - name: Capture request values actions uses: ./goCapacityCheck with: files: ${{ steps.changed-files.outputs.all_changed_files }} </code></pre> <p>goCapacityCheck action.yml</p> <pre><code>name: 'goCapacityCheck' description: 'Capture requests CPU and Memory values from all files in the PR' inputs: files: description: 'files changed in the PR.' required: false runs: using: 'docker' image: './Dockerfile' args: - ${{ inputs.files }} </code></pre> <p>is there a way to split that string when passing to the action? or to Docker or something?</p> <p>I haven't tried much when i hit this issue, but i'd expect that the sting that looks like <code>&quot;/path/to/file1 /path/to/file2&quot;</code> to be split at some point in order to be able to do <code>docker run --name mygocap gocap /path/to/file1 /path/to/file2</code></p>
[ { "answer_id": 74363377, "author": "Matteo", "author_id": 2270041, "author_profile": "https://Stackoverflow.com/users/2270041", "pm_score": 0, "selected": false, "text": "\nstring=\"/path/to/file1 /path/to/file2\"\necho \\\"$(echo $string | cut -d' ' -f1)\\\" \\\"$(echo $string | cut -d' ' -f2)\\\"\n" }, { "answer_id": 74373527, "author": "Dichtrich", "author_id": 7045379, "author_profile": "https://Stackoverflow.com/users/7045379", "pm_score": 1, "selected": false, "text": "os.Args[]" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74361756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7045379/" ]
74,361,781
<p>I must've skipped school that day because I cannot remember how to calculate the middle of a square.</p>
[ { "answer_id": 74361923, "author": "Ali Muhammad", "author_id": 11351501, "author_profile": "https://Stackoverflow.com/users/11351501", "pm_score": 3, "selected": true, "text": "# method-1\ndef square_middle(square):\n x1, y1, x2, y2 = square\n return ((x1 + x2) / 2, (y1 + y2) / 2)\n\n# method-2 \ndef square_middle(square):\n x1, y1, x2, y2 = square\n cx = (x1 + x2) / 2\n cy = (y1 + y2) / 2\n return (cx, cy)\n" }, { "answer_id": 74362093, "author": "Remzinho", "author_id": 2484591, "author_profile": "https://Stackoverflow.com/users/2484591", "pm_score": 1, "selected": false, "text": "pyautogui" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74361781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20374112/" ]
74,361,797
<p>I have a table like this:</p> <pre class="lang-none prettyprint-override"><code>a | a_vector | 1 | 710.83;-776.98;-10.86;2013.02;-896.28; | 2 | 3 ; 2 ; 1 | </code></pre> <p>Using PySpark/pandas, how do I dynamically create columns so that first values in vector go to &quot;col1&quot; and second values go to &quot;col2&quot; etc. + calculate the sum?</p> <pre class="lang-none prettyprint-override"><code>a | a_vector | col1 | col2 | col3 1 | 300;-200;2022; | 300 | -200 | 2022 2 | 3 ; 2 ; 1 | 3 | 2 | 1 </code></pre> <p>The final requirement is to have the sums of new columns sorted in one column.</p>
[ { "answer_id": 74361923, "author": "Ali Muhammad", "author_id": 11351501, "author_profile": "https://Stackoverflow.com/users/11351501", "pm_score": 3, "selected": true, "text": "# method-1\ndef square_middle(square):\n x1, y1, x2, y2 = square\n return ((x1 + x2) / 2, (y1 + y2) / 2)\n\n# method-2 \ndef square_middle(square):\n x1, y1, x2, y2 = square\n cx = (x1 + x2) / 2\n cy = (y1 + y2) / 2\n return (cx, cy)\n" }, { "answer_id": 74362093, "author": "Remzinho", "author_id": 2484591, "author_profile": "https://Stackoverflow.com/users/2484591", "pm_score": 1, "selected": false, "text": "pyautogui" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74361797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9390633/" ]
74,361,802
<p>I opened VSCode a few days ago to continue work on a Flutter project, unfortunately, the Flutter and Dart usually take a while to start(2-3 minutes), but this time,the extensions failed to initialize, and I'm left with white colourless code and no access to the tools that come with the extensions(i.e F5 for debug).<a href="https://i.stack.imgur.com/rofeJ.png" rel="nofollow noreferrer">screenshot of the current state of things</a></p> <h3>Over the past few days, I have,</h3> <ul> <li><p>Deleted and re-installed the Flutter SDK(forgive me, I cant remember what version it was at before, but now its 3.3.7, Dart 2.18.4)</p> </li> <li><p>Deleted and re-installed VSCode(used to be a snap, now a .deb)</p> </li> <li><p>Uninstalled and re-installed the Flutter and Dart extensions(multiple times, restarted VSCode each time)</p> </li> </ul> <p>- Ran said project directly from the terminal to be sure I had the flutter tool correctly installed(<em>flutter run</em> and <em>flutter build apk</em> ran fine, with no errors)</p> <p>Please find the results of 'flutter doctor -v' below</p> <pre><code> Flutter (Channel stable, 3.3.7, on Ubuntu 20.04.5 LTS 5.15.0-52-generic, locale en_NG) • Flutter version 3.3.7 on channel stable at /home/alabi/snap/flutter/common/flutter • Upstream repository https://github.com/flutter/flutter.git • Framework revision e99c9c7cd9 (7 days ago), 2022-11-01 16:59:00 -0700 • Engine revision 857bd6b74c • Dart version 2.18.4 • DevTools version 2.15.0 [!] Android toolchain - develop for Android devices (Android SDK version 32.1.0-rc1) • Android SDK at /home/alabi/Android/Sdk • Platform android-33, build-tools 32.1.0-rc1 • ANDROID_SDK_ROOT = /home/alabi/Android/Sdk • Java binary at: /home/alabi/.jdks/openjdk-18.0.1.1/bin/java • Java version OpenJDK Runtime Environment (build 18.0.1.1+2-6) ✗ Android license status unknown. Run `flutter doctor --android-licenses` to accept the SDK licenses. See https://flutter.dev/docs/get-started/install/linux#android-setup for more details. [✗] Chrome - develop for the web (Cannot find Chrome executable at google-chrome) ! Cannot find Chrome. Try setting CHROME_EXECUTABLE to a Chrome executable. [✓] Linux toolchain - develop for Linux desktop • clang version 10.0.0-4ubuntu1 • cmake version 3.16.3 • ninja version 1.10.0 • pkg-config version 0.29.1 [!] Android Studio (not installed) • Android Studio not found; download from https://developer.android.com/studio/index.html (or visit https://flutter.dev/docs/get-started/install/linux#android-setup for detailed instructions). [✓] VS Code (version 1.73.0) • VS Code at /usr/share/code • Flutter extension version 3.52.0 [✓] Connected device (1 available) • Linux (desktop) • linux • linux-x64 • Ubuntu 20.04.5 LTS 5.15.0-52-generic </code></pre> <p>The CLI command, 'flutter --version' returns</p> <pre><code>Flutter 3.3.7 • channel stable • https://github.com/flutter/flutter.git Framework • revision e99c9c7cd9 (7 days ago) • 2022-11-01 16:59:00 -0700 Engine • revision 857bd6b74c Tools • Dart 2.18.4 • DevTools 2.15.0 </code></pre> <p>All of this leads me to believe the Flutter SDK is installed correctly and the problem is with VSCode and the extensions</p> <p>Any help is appreciated, thank you!</p>
[ { "answer_id": 74361923, "author": "Ali Muhammad", "author_id": 11351501, "author_profile": "https://Stackoverflow.com/users/11351501", "pm_score": 3, "selected": true, "text": "# method-1\ndef square_middle(square):\n x1, y1, x2, y2 = square\n return ((x1 + x2) / 2, (y1 + y2) / 2)\n\n# method-2 \ndef square_middle(square):\n x1, y1, x2, y2 = square\n cx = (x1 + x2) / 2\n cy = (y1 + y2) / 2\n return (cx, cy)\n" }, { "answer_id": 74362093, "author": "Remzinho", "author_id": 2484591, "author_profile": "https://Stackoverflow.com/users/2484591", "pm_score": 1, "selected": false, "text": "pyautogui" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74361802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9671879/" ]
74,361,809
<p>I'm trying to build a React Native application using Expo and <a href="https://github.com/rnmapbox/maps" rel="nofollow noreferrer">rnmapbox/maps</a> module, which includes some custom native code.</p> <p>Up until now, I could build the application without any problems, for Android at least, which is my target platform. But suddenly, it stopped working and the following error log is displayed:</p> <pre><code>* What went wrong: A problem occurred evaluating project ':app'. &gt; Failed to apply plugin class 'org.gradle.api.plugins.BasePlugin'. &gt; Could not find method maven() for arguments [build_1quotit9ccucu377qnhf7kv5h$_run_closure1$_closure3$_closure5@4a87f9f7] on configuration ':app:archives' of type org.gradle.api.in ternal.artifacts.configurations.DefaultConfiguration. </code></pre> <p>What is the problem and how can I possibly fix it?</p>
[ { "answer_id": 74364481, "author": "relasine", "author_id": 10096794, "author_profile": "https://Stackoverflow.com/users/10096794", "pm_score": 1, "selected": false, "text": "eas build" }, { "answer_id": 74390674, "author": "Educorreia", "author_id": 9422823, "author_profile": "https://Stackoverflow.com/users/9422823", "pm_score": 1, "selected": true, "text": "\"image\": \"latest\"" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74361809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9422823/" ]
74,361,822
<p>I've got an old script from someone that I want to remodel but unfortunately I am not that experienced in PHP. What it does is, it reads article information from a CSV file into an array and then basically posts the output into a HTML table, which can then be saved into a PDF file.</p> <p>One thing I couldn't quite wrap my head around is, the file provides duplicate lines for an article while only some values changed (size, color etc). The article does have the same name but is not repeated twice in the output, the &quot;new&quot; values are just added to the already existing record and I am quite unsure how to do that. Let me give you a simplified example:</p> <p><strong>CSV Example:</strong></p> <p><strong>ArtNo,Name,Color,Size</strong></p> <p>DEF270, Fingal, Stellar, 3XL</p> <p>DEF270, Fingal, White, 4XL;</p> <p>So, in a regular loop, the output would be like this</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ArtNo</th> <th>Name</th> <th>Color</th> <th>Size</th> </tr> </thead> <tbody> <tr> <td>DEF270</td> <td>Fingal</td> <td>Stellar</td> <td>3XL</td> </tr> <tr> <td>DEF270</td> <td>Fingal</td> <td>White</td> <td>4XL</td> </tr> </tbody> </table> </div> <p>What I would need is this</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ArtNo</th> <th>Name</th> <th>Color</th> <th>Size</th> </tr> </thead> <tbody> <tr> <td>DEF270</td> <td>Fingal</td> <td>Stellar, White</td> <td>3XL, 4XL</td> </tr> </tbody> </table> </div> <p>Can you guys give me a hint on how to achieve this?</p>
[ { "answer_id": 74362192, "author": "Slava Rozhnev", "author_id": 3399356, "author_profile": "https://Stackoverflow.com/users/3399356", "pm_score": 3, "selected": true, "text": "array_reduce" }, { "answer_id": 74362436, "author": "Markus Zeller", "author_id": 2645713, "author_profile": "https://Stackoverflow.com/users/2645713", "pm_score": 0, "selected": false, "text": "$csv = <<<'_CSV'\nArtNo,Name,Color,Size\nDEF270, Fingal, Stellar, 3XL\nDEF270, Fingal, White, 4XL;\n_CSV;\n\n$csv_handle = fopen('php://memory', 'rw');\n$fwrite = fwrite($csv_handle, $csv);\nfseek($csv_handle, 0);\n\n$articles = [];\nwhile (($data = fgetcsv($csv_handle)) !== false) {\n [$articleNumber, $name, $color, $size] = array_map('trim', $data);\n if (!isset($articles[$articleNumber])) {\n $articles[$articleNumber] = [\n 'names' => [$name],\n 'colors' => [$color],\n 'sizes' => [$size],\n ];\n continue;\n }\n $article = &$articles[$articleNumber];\n if (!in_array($name, $article['names'])) {\n $article['names'][] = $name;\n }\n if (!in_array($color, $article['colors'])) {\n $article['colors'][] = $color;\n }\n if (!in_array($size, $article['sizes'])) {\n $article['sizes'][] = $size;\n }\n unset ($article);\n}\nfclose($csv_handle);\n\necho \"<table>\\n\";\nforeach ($articles as $articleNumber => $article) {\n $names = implode(', ', $article['names']);\n $colors = implode(', ', $article['colors']);\n $sizes = implode(', ', $article['sizes']);\n echo \"<tr><td>$articleNumber</td><td>$names</td><td>$colors</td><td>$sizes</tr>\\n\";\n}\necho \"</table>\\n\";\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74361822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4350734/" ]
74,361,843
<p>In GLP 10.0.3.</p> <p>On the plan, I have this error:</p> <p><code> Warning: strlen() expects parameter 1 to be string, array given in C:\wamp64\www\glpi\src\PlanningExternalEvent.php on line 160</code></p> <p>My PlanningExternalEvent on line 160 :</p> <pre><code> $is_rrule = strlen($this-&gt;fields['rrule']) &gt; 0; </code></pre> <p>Can you help me ? Thx</p> <pre><code> $is_rrule = strlen($this-&gt;fields['rrule']) &gt; 1; </code></pre>
[ { "answer_id": 74362192, "author": "Slava Rozhnev", "author_id": 3399356, "author_profile": "https://Stackoverflow.com/users/3399356", "pm_score": 3, "selected": true, "text": "array_reduce" }, { "answer_id": 74362436, "author": "Markus Zeller", "author_id": 2645713, "author_profile": "https://Stackoverflow.com/users/2645713", "pm_score": 0, "selected": false, "text": "$csv = <<<'_CSV'\nArtNo,Name,Color,Size\nDEF270, Fingal, Stellar, 3XL\nDEF270, Fingal, White, 4XL;\n_CSV;\n\n$csv_handle = fopen('php://memory', 'rw');\n$fwrite = fwrite($csv_handle, $csv);\nfseek($csv_handle, 0);\n\n$articles = [];\nwhile (($data = fgetcsv($csv_handle)) !== false) {\n [$articleNumber, $name, $color, $size] = array_map('trim', $data);\n if (!isset($articles[$articleNumber])) {\n $articles[$articleNumber] = [\n 'names' => [$name],\n 'colors' => [$color],\n 'sizes' => [$size],\n ];\n continue;\n }\n $article = &$articles[$articleNumber];\n if (!in_array($name, $article['names'])) {\n $article['names'][] = $name;\n }\n if (!in_array($color, $article['colors'])) {\n $article['colors'][] = $color;\n }\n if (!in_array($size, $article['sizes'])) {\n $article['sizes'][] = $size;\n }\n unset ($article);\n}\nfclose($csv_handle);\n\necho \"<table>\\n\";\nforeach ($articles as $articleNumber => $article) {\n $names = implode(', ', $article['names']);\n $colors = implode(', ', $article['colors']);\n $sizes = implode(', ', $article['sizes']);\n echo \"<tr><td>$articleNumber</td><td>$names</td><td>$colors</td><td>$sizes</tr>\\n\";\n}\necho \"</table>\\n\";\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74361843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20450284/" ]
74,361,903
<p><strong>Context</strong></p> <p>I like to use <code>pixi.js</code> for a game I have in mind. Over the years I always used React and <code>next.js</code>.</p> <p>So what I want to do it use pixi.js inside React / Next.</p> <p>There are 2 packages out there that integrate into react fiber to render component like but they are outdated and give so many errors to me (for example doesn't work with react 18 and also have poor documentations). (<code>@inlet/react-pixi</code> and <code>react-pixi-fiber</code>)</p> <p>So I decided to go the <code>useRef</code> route.</p> <p>Here is some code that works fine:</p> <pre><code>import { useRef, useEffect } from &quot;react&quot;; import { Application, Sprite, Texture } from &quot;pixi.js&quot;; import bunnyImg from &quot;../public/negx.jpg&quot;; const app = new Application({ width: 800, height: 600, backgroundColor: 0x5bba6f, }); const Pixi = () =&gt; { const ref = useRef(); useEffect(() =&gt; { // On first render add app to DOM ref.current.appendChild(app.view); // Start the PixiJS app app.start(); const texture = Texture.from(bunnyImg.src); const bunny = new Sprite(texture); bunny.anchor.set(0.5); bunny.x = 0; bunny.y = 0; bunny.width = 100; bunny.height = 100; app.stage.addChild(bunny); return () =&gt; { // On unload stop the application app.stop(); }; }, []); return &lt;div ref={ref} /&gt;; }; export default Pixi; </code></pre> <p><strong>The Problem</strong></p> <p>The only problem I have with this is, that hot reload doesn't work. So if I change something in the <code>useEffect</code> hook, I have to go into the browser and manually refresh the page. So basically hot reloading doesn't work.</p> <p>I think since it uses a ref that basically never changes.</p> <p><strong>The question</strong></p> <p>Is there a better way of coding <code>pixi.js</code> inside react / next?</p>
[ { "answer_id": 74362192, "author": "Slava Rozhnev", "author_id": 3399356, "author_profile": "https://Stackoverflow.com/users/3399356", "pm_score": 3, "selected": true, "text": "array_reduce" }, { "answer_id": 74362436, "author": "Markus Zeller", "author_id": 2645713, "author_profile": "https://Stackoverflow.com/users/2645713", "pm_score": 0, "selected": false, "text": "$csv = <<<'_CSV'\nArtNo,Name,Color,Size\nDEF270, Fingal, Stellar, 3XL\nDEF270, Fingal, White, 4XL;\n_CSV;\n\n$csv_handle = fopen('php://memory', 'rw');\n$fwrite = fwrite($csv_handle, $csv);\nfseek($csv_handle, 0);\n\n$articles = [];\nwhile (($data = fgetcsv($csv_handle)) !== false) {\n [$articleNumber, $name, $color, $size] = array_map('trim', $data);\n if (!isset($articles[$articleNumber])) {\n $articles[$articleNumber] = [\n 'names' => [$name],\n 'colors' => [$color],\n 'sizes' => [$size],\n ];\n continue;\n }\n $article = &$articles[$articleNumber];\n if (!in_array($name, $article['names'])) {\n $article['names'][] = $name;\n }\n if (!in_array($color, $article['colors'])) {\n $article['colors'][] = $color;\n }\n if (!in_array($size, $article['sizes'])) {\n $article['sizes'][] = $size;\n }\n unset ($article);\n}\nfclose($csv_handle);\n\necho \"<table>\\n\";\nforeach ($articles as $articleNumber => $article) {\n $names = implode(', ', $article['names']);\n $colors = implode(', ', $article['colors']);\n $sizes = implode(', ', $article['sizes']);\n echo \"<tr><td>$articleNumber</td><td>$names</td><td>$colors</td><td>$sizes</tr>\\n\";\n}\necho \"</table>\\n\";\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74361903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8502436/" ]
74,361,927
<p>I have two .csv files in the same directory with the same number of columns and I want to combine them into one file, but keep just one header from the first file. The file name is always different, only the prefix remains the same:</p> <pre><code>orderline_123456.csv Order_number,Quantity,Price 100,10,25.3 101,15,30.2 </code></pre> <pre><code>orderline_896524.csv Order_number,Quantity,Price 102,20,12.33 103,3,3.4 </code></pre> <p>The output file should be like:</p> <pre><code>file_load.csv Order_number,Quantity,Price 100,10,25.3 101,15,30.2 102,20,12.33 103,3,3.4 </code></pre> <p>This was already in the shell script file, because since now I needed to take only one file, but now I have to merge two files:</p> <pre><code>awk '(NR-1)%2{$1=$1}1' RS=\&quot; ORS=\&quot; orderline_*.csv &gt;&gt; file_to_load.csv </code></pre> <p>I tried changing it into</p> <pre><code>awk 'FNR == 1 &amp;&amp; NR != 1 {next} (NR-1)%2{$1=$1}1' RS=\&quot; ORS=\&quot; orderline_*.csv &gt;&gt; file_to_load.csv </code></pre> <p>but I get the header twice in the output.</p> <p>Could you please help me? How exactly should the command look like? I need to keep how it was defined before.</p> <p>Thank you!</p>
[ { "answer_id": 74362080, "author": "glenn jackman", "author_id": 7552, "author_profile": "https://Stackoverflow.com/users/7552", "pm_score": 2, "selected": false, "text": "awk 'NR == 1 || FNR > 1' file ...\n" }, { "answer_id": 74362761, "author": "JRichardsz", "author_id": 3957754, "author_profile": "https://Stackoverflow.com/users/3957754", "pm_score": 0, "selected": false, "text": "header=$(head -n 1 file1.csv)\n" }, { "answer_id": 74363102, "author": "Shawn", "author_id": 9952196, "author_profile": "https://Stackoverflow.com/users/9952196", "pm_score": 0, "selected": false, "text": "csvstack" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74361927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14320670/" ]
74,361,936
<p><a href="https://i.stack.imgur.com/DqHpG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DqHpG.png" alt="enter image description here" /></a></p> <p>I am trying to calculate if a member shops in January, what proportion shop again in February and what proportion shop again within 3 months. Ultimately to create a table similar to the image attached.</p> <p>I have tried the below code. The first left join works, but when I add the second one to calculate within_3months the error: &quot;FROM keyword not found where expected&quot; is shown (for the separate line). Can I left join twice or must I do separate scripts for columns?</p> <pre><code>, count(distinct B.members)/count(distinct A.members) *100 as 1month_retention_rate </code></pre> <pre><code>select year_month_january21 , count(distinct A.members) as num_of_mems_shopped_january21 , count(distinct B.members)as retained_february21 , count(distinct B.members)/count(distinct A.members) *100 as 1month_retention_rate , count(distinct C.members)/count(distinct A.members) *100 as within_3months from (select members , year_month as year_month_january21 from table.members t join table.date tm on t.dt_key = tm.date_key and year_month = 202101 group by members , year_month) A left join (select members , year_month as year_month_february21 from table.members t join table.date tm on t.dt_key = tm.date_key and year_month = 202102 group by members , year_month) B on A.members = B.members left join (select members , year_month as year_month_3months from table.members t join table.date tm on t.dt_key = tm.date_key and year_month between 202102 and 202104 group by members , year_month) C on A.members = C.members group by year_month_january21; </code></pre> <p>I have tried left creating a separate time table and joining to this. It does not work. Doing calculations separately works but I must do this for multiple time frames so will take a long time.</p>
[ { "answer_id": 74362314, "author": "MT0", "author_id": 1509264, "author_profile": "https://Stackoverflow.com/users/1509264", "pm_score": 0, "selected": false, "text": "SELECT 202101 AS year_month,\n COUNT(CASE WHEN cnt_202101 > 0 THEN 1 END)\n AS members_shopped_202101,\n COUNT(CASE WHEN cnt_202101 > 0 AND cnt_202102 > 0 THEN 1 END)\n AS members_retained_202102,\n COUNT(CASE WHEN cnt_202101 > 0 AND cnt_202102 > 0 THEN 1 END)\n / COUNT(CASE WHEN cnt_202101 > 0 THEN 1 END) * 100\n AS one_month_retention_rate,\n COUNT(CASE WHEN cnt_202101 > 0 AND (cnt_202102 > 0 OR cnt_202103 > 0 OR cnt_202104 > 0) THEN 1 END)\n / COUNT(CASE WHEN cnt_202101 > 0 THEN 1 END) * 100\n AS within_3months\nFROM (\n SELECT members,\n year_month\n FROM members m\n INNER JOIN date d\n ON m.dt_key = d.date_key\n)\nPIVOT (\n COUNT(*)\n FOR year_month IN (\n 202101 AS cnt_202101,\n 202102 AS cnt_202102,\n 202103 AS cnt_202103,\n 202104 AS cnt_202104\n )\n);\n" }, { "answer_id": 74362680, "author": "Alex Poole", "author_id": 266304, "author_profile": "https://Stackoverflow.com/users/266304", "pm_score": 2, "selected": false, "text": "as 1month_retention_rate" }, { "answer_id": 74362958, "author": "Ehab", "author_id": 20342736, "author_profile": "https://Stackoverflow.com/users/20342736", "pm_score": 0, "selected": false, "text": "\nSELECT\n mem_jan AS num_of_mems_shopped_january21,\n mem_feb AS retained_february21,\n mem_feb / mem_jan * 100 as 1month_retention_rate\n mem_3m / mem_jan * 100 as within_3months\nFROM(\n SELECT\n SUM(IF(mm_jan>0,1,0) AS mem_jan,\n SUM(IF(mm_jan>0 AND mm_feb>0,1,0) AS mem_feb,\n SUM(IF(mm_jan>0 AND mm_count_3m>0,1,0) AS mem_3m\n FROM\n (\n SELECT\n t.Id,\n SUM(IF(year_month = 202101, 1,0)) AS mm_jan, /*visit for a member in Jan*/\n SUM(IF(year_month = 202102, 1,0)) AS mm_feb, /*visit for a member in Feb*/\n SUM(IF(year_month between 202102 and 202104,1,0)) AS mem_3m/*visit for a member in 3 months*/\n FROM \n table.members t\n join table.date tm on t.dt_key = tm.date_key\n WHERE\n year_month between 202101 and 202104\n GROUP BY\n t.Id\n ) AS t1\n) AS t2\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74361936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20450265/" ]
74,361,947
<p>I'm trying to perform a simple addition based on user inputs ( for dimensions of a box in cubic meters.. i want to sum up all the boxes they want to add ).</p> <pre><code> const totalW = [] const cubitMeters = (parseInt(height) * parseInt(width) * parseInt(length) * parseInt(count)) / 1000000 totalW.push(cubitMeters) </code></pre> <p>then in JSX I'm reducing it</p> <pre><code> &lt;Text&gt; {totalW?.reduce((a, b) =&gt; a + b, 0).toFixed(2)} &lt;/Text&gt; </code></pre> <p>Everything is fine, however as you can see the calculation for <code>cubitMeters</code> is a multiplication.. and unless all numbers are provided, it returns NaN. And it only works properly when the user finally enters all numbers, which isn't ideal.</p> <p>How can I make sure that the function only is triggered when all numbers are entered?</p>
[ { "answer_id": 74362314, "author": "MT0", "author_id": 1509264, "author_profile": "https://Stackoverflow.com/users/1509264", "pm_score": 0, "selected": false, "text": "SELECT 202101 AS year_month,\n COUNT(CASE WHEN cnt_202101 > 0 THEN 1 END)\n AS members_shopped_202101,\n COUNT(CASE WHEN cnt_202101 > 0 AND cnt_202102 > 0 THEN 1 END)\n AS members_retained_202102,\n COUNT(CASE WHEN cnt_202101 > 0 AND cnt_202102 > 0 THEN 1 END)\n / COUNT(CASE WHEN cnt_202101 > 0 THEN 1 END) * 100\n AS one_month_retention_rate,\n COUNT(CASE WHEN cnt_202101 > 0 AND (cnt_202102 > 0 OR cnt_202103 > 0 OR cnt_202104 > 0) THEN 1 END)\n / COUNT(CASE WHEN cnt_202101 > 0 THEN 1 END) * 100\n AS within_3months\nFROM (\n SELECT members,\n year_month\n FROM members m\n INNER JOIN date d\n ON m.dt_key = d.date_key\n)\nPIVOT (\n COUNT(*)\n FOR year_month IN (\n 202101 AS cnt_202101,\n 202102 AS cnt_202102,\n 202103 AS cnt_202103,\n 202104 AS cnt_202104\n )\n);\n" }, { "answer_id": 74362680, "author": "Alex Poole", "author_id": 266304, "author_profile": "https://Stackoverflow.com/users/266304", "pm_score": 2, "selected": false, "text": "as 1month_retention_rate" }, { "answer_id": 74362958, "author": "Ehab", "author_id": 20342736, "author_profile": "https://Stackoverflow.com/users/20342736", "pm_score": 0, "selected": false, "text": "\nSELECT\n mem_jan AS num_of_mems_shopped_january21,\n mem_feb AS retained_february21,\n mem_feb / mem_jan * 100 as 1month_retention_rate\n mem_3m / mem_jan * 100 as within_3months\nFROM(\n SELECT\n SUM(IF(mm_jan>0,1,0) AS mem_jan,\n SUM(IF(mm_jan>0 AND mm_feb>0,1,0) AS mem_feb,\n SUM(IF(mm_jan>0 AND mm_count_3m>0,1,0) AS mem_3m\n FROM\n (\n SELECT\n t.Id,\n SUM(IF(year_month = 202101, 1,0)) AS mm_jan, /*visit for a member in Jan*/\n SUM(IF(year_month = 202102, 1,0)) AS mm_feb, /*visit for a member in Feb*/\n SUM(IF(year_month between 202102 and 202104,1,0)) AS mem_3m/*visit for a member in 3 months*/\n FROM \n table.members t\n join table.date tm on t.dt_key = tm.date_key\n WHERE\n year_month between 202101 and 202104\n GROUP BY\n t.Id\n ) AS t1\n) AS t2\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74361947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18984558/" ]
74,361,951
<p>I need help with python program. I don't know how to make python change at least 1 lowercase letter to uppercase.</p> <pre><code>from random import * import random pin=&quot;&quot; lenght=random.randrange(8,15) for i in range(lenght): pin=pin+chr(randint(97,122)) print(pin) </code></pre>
[ { "answer_id": 74362030, "author": "André", "author_id": 11657650, "author_profile": "https://Stackoverflow.com/users/11657650", "pm_score": -1, "selected": false, "text": "pin=\"asd\"\n\nprint(pin.upper())\n>>>ASD\n" }, { "answer_id": 74362116, "author": "ChamRun", "author_id": 14761615, "author_profile": "https://Stackoverflow.com/users/14761615", "pm_score": 0, "selected": false, "text": "import random\n\npin = []\nlength = random.randrange(8, 15)\n\nfor i in range(length):\n pin.append(chr(random.randint(97, 122)))\n\nnumber_of_uppercase_chars = random.randint(1, length)\n\nfor i in range(number_of_uppercase_chars):\n char_index = random.randint(0, length - 1)\n while pin[char_index].isupper():\n char_index = random.randint(0, length - 1)\n\n pin[char_index] = pin[char_index].upper()\n\n\npin = \"\".join(pin)\nprint(pin)\n" }, { "answer_id": 74362209, "author": "Matthias", "author_id": 1209921, "author_profile": "https://Stackoverflow.com/users/1209921", "pm_score": 3, "selected": true, "text": "length" }, { "answer_id": 74362228, "author": "Aymen", "author_id": 5165980, "author_profile": "https://Stackoverflow.com/users/5165980", "pm_score": 0, "selected": false, "text": "from random import *\nimport random\n\n\npin=\"\"\nlenght=random.randrange(8,15)\n\nfor i in range(lenght):\n pin=pin+chr(randint(97,122))\n\nprint(pin)\n\npin = pin.upper()\n\nwhile not any(c for c in pin if c.islower()):\n pin = pin.lower()\n pin = \"\".join(random.choice([k.upper(), k ]) for k in pin )\n\nprint(pin)\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74361951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20247401/" ]
74,362,000
<p>I have a text input that is changed by Javascript based on values of other inputs.</p> <p>How do I get Selenium to wait for it to change?</p> <p>I currently have tried both</p> <pre><code>var wait3 = new WebDriverWait(_driver, TimeSpan.FromSeconds(5)).Until(driver =&gt; !driver.FindElement(By.Id(&quot;gbpAmount&quot;)).Equals(&quot;&quot;)); </code></pre> <p>and</p> <pre><code>bool pop= wait.Until&lt;bool&gt;((d) =&gt; { var populated1 = d.FindElement(By.Id(&quot;gbpAmount&quot;)).Text != &quot;&quot;; var populated2 = d.FindElement(By.Id(&quot;gbpAmount&quot;)).Text != &quot;0&quot;; if (populated1 &amp;&amp; populated2) { return true; } else { return false; } }); </code></pre> <p>However neither of these methods work. Either they just pass through and when I fetch and check the element afterwards it is &quot;&quot; or they just exceed the wait time.</p> <p>Yet clearly on the screen the value is changed...</p>
[ { "answer_id": 74362030, "author": "André", "author_id": 11657650, "author_profile": "https://Stackoverflow.com/users/11657650", "pm_score": -1, "selected": false, "text": "pin=\"asd\"\n\nprint(pin.upper())\n>>>ASD\n" }, { "answer_id": 74362116, "author": "ChamRun", "author_id": 14761615, "author_profile": "https://Stackoverflow.com/users/14761615", "pm_score": 0, "selected": false, "text": "import random\n\npin = []\nlength = random.randrange(8, 15)\n\nfor i in range(length):\n pin.append(chr(random.randint(97, 122)))\n\nnumber_of_uppercase_chars = random.randint(1, length)\n\nfor i in range(number_of_uppercase_chars):\n char_index = random.randint(0, length - 1)\n while pin[char_index].isupper():\n char_index = random.randint(0, length - 1)\n\n pin[char_index] = pin[char_index].upper()\n\n\npin = \"\".join(pin)\nprint(pin)\n" }, { "answer_id": 74362209, "author": "Matthias", "author_id": 1209921, "author_profile": "https://Stackoverflow.com/users/1209921", "pm_score": 3, "selected": true, "text": "length" }, { "answer_id": 74362228, "author": "Aymen", "author_id": 5165980, "author_profile": "https://Stackoverflow.com/users/5165980", "pm_score": 0, "selected": false, "text": "from random import *\nimport random\n\n\npin=\"\"\nlenght=random.randrange(8,15)\n\nfor i in range(lenght):\n pin=pin+chr(randint(97,122))\n\nprint(pin)\n\npin = pin.upper()\n\nwhile not any(c for c in pin if c.islower()):\n pin = pin.lower()\n pin = \"\".join(random.choice([k.upper(), k ]) for k in pin )\n\nprint(pin)\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/965302/" ]
74,362,010
<p>when I try to install any dependence in command prompt get this error message and tried to google but nothing any one to help me please</p> <p><a href="https://i.stack.imgur.com/QgGAH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QgGAH.png" alt="enter image description here" /></a></p> <p>please I need help someone to help me</p>
[ { "answer_id": 74362030, "author": "André", "author_id": 11657650, "author_profile": "https://Stackoverflow.com/users/11657650", "pm_score": -1, "selected": false, "text": "pin=\"asd\"\n\nprint(pin.upper())\n>>>ASD\n" }, { "answer_id": 74362116, "author": "ChamRun", "author_id": 14761615, "author_profile": "https://Stackoverflow.com/users/14761615", "pm_score": 0, "selected": false, "text": "import random\n\npin = []\nlength = random.randrange(8, 15)\n\nfor i in range(length):\n pin.append(chr(random.randint(97, 122)))\n\nnumber_of_uppercase_chars = random.randint(1, length)\n\nfor i in range(number_of_uppercase_chars):\n char_index = random.randint(0, length - 1)\n while pin[char_index].isupper():\n char_index = random.randint(0, length - 1)\n\n pin[char_index] = pin[char_index].upper()\n\n\npin = \"\".join(pin)\nprint(pin)\n" }, { "answer_id": 74362209, "author": "Matthias", "author_id": 1209921, "author_profile": "https://Stackoverflow.com/users/1209921", "pm_score": 3, "selected": true, "text": "length" }, { "answer_id": 74362228, "author": "Aymen", "author_id": 5165980, "author_profile": "https://Stackoverflow.com/users/5165980", "pm_score": 0, "selected": false, "text": "from random import *\nimport random\n\n\npin=\"\"\nlenght=random.randrange(8,15)\n\nfor i in range(lenght):\n pin=pin+chr(randint(97,122))\n\nprint(pin)\n\npin = pin.upper()\n\nwhile not any(c for c in pin if c.islower()):\n pin = pin.lower()\n pin = \"\".join(random.choice([k.upper(), k ]) for k in pin )\n\nprint(pin)\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20450337/" ]
74,362,011
<p>Here's the code in question:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame( [ list(range(200)), list(range(200, 400)) ], index=['col_1', 'col_2'] ).transpose() col_1_index = df.columns.get_loc('col_1') col_2_index = df.columns.get_loc('col_2') target_1 = 2 for i in range(2, len(df)): if ( df.iloc[i - 2, col_1_index] - df.iloc[i - 1, col_2_index] ) &gt; target_1: col_2_value = ( df.iloc[i - 1, col_2_index] + target_1 ) elif ( df.iloc[i - 1, col_2_index] - df.iloc[i - 2, col_1_index] ) &gt; target_1: col_2_value = ( df.iloc[i - 1, col_2_index] - target_1 ) else: col_2_value = df.iloc[i - 2, col_1_index] df.iloc[i, col_2_index] = col_2_value df ''' # expected output col_1 col_2 0 0 200 1 1 201 2 2 199 3 3 197 4 4 195 ... ... ... 195 195 193 196 196 194 197 197 195 198 198 196 199 199 197 ''' </code></pre> <p>My issue is I can't use the common methods of speeding up the iteration such as <code>df.itertuples()</code> or <code>df.apply()</code> because I am referencing the previous row's calculated value.</p> <hr /> <p>The logic is iterating over the <code>DataFrame</code> comparing the <code>t-2</code> col_1 value with the <code>t-1</code> col_2 value to decide what to assign to the <code>t</code> col_2 value. So col_1 is static, while the col_2 time <code>t</code> value is updated each iteration.</p>
[ { "answer_id": 74363054, "author": "Ben.T", "author_id": 9274732, "author_profile": "https://Stackoverflow.com/users/9274732", "pm_score": 3, "selected": true, "text": "itertuples" }, { "answer_id": 74365120, "author": "Alex F", "author_id": 3453901, "author_profile": "https://Stackoverflow.com/users/3453901", "pm_score": 1, "selected": false, "text": "CPU times: total: 46.9 ms" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3453901/" ]
74,362,047
<p>Coming from c++ this implementation looks similar to accessing pointers, in python is there more elegant way to do this?</p> <pre><code> if something is not None: return something.x else: return None </code></pre> <p>if the instance itself is not null, then allow accessing its members.</p> <p>any ideas? thanks</p>
[ { "answer_id": 74362177, "author": "Jasmijn", "author_id": 573255, "author_profile": "https://Stackoverflow.com/users/573255", "pm_score": 0, "selected": false, "text": "something" }, { "answer_id": 74362196, "author": "rv.kvetch", "author_id": 10237506, "author_profile": "https://Stackoverflow.com/users/10237506", "pm_score": 2, "selected": false, "text": "if-else" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3930599/" ]
74,362,063
<p>I tried to make a basic calculator by myself. I am complately new and that is why ı don't really know where did ı made the mistake. I can make an addition but still when ı try to make subtraction ıt makes addition again. It ıs my first project and ı need help. I am waiting for your responds :)</p> <pre><code>mathematical_operation=input(&quot;Choose your mathematical operation &quot;) print(mathematical_operation) def addition(str): &quot;addition&quot; print(str) return if mathematical_operation:= 'addition': first=input(&quot;first: &quot;) print(&quot;first&quot;) second=input(&quot;second: &quot;) print(&quot;second&quot;) sum=float(first) + float(second) print(&quot;sum&quot; +str(sum)) def subtraction(str): &quot;subtraction&quot; print(str) return if mathematical_operation:='subtraction': first=input(&quot;first: &quot;) print(&quot;first&quot;) second=input(&quot;second: &quot;) print(&quot;second&quot;) dif=float(first) -float(second) print(&quot;Sum&quot; +str(dif)) </code></pre>
[ { "answer_id": 74362143, "author": "Paul-Marie", "author_id": 9603417, "author_profile": "https://Stackoverflow.com/users/9603417", "pm_score": 1, "selected": false, "text": ":=" }, { "answer_id": 74362752, "author": "Muhammad Ayaz", "author_id": 11222265, "author_profile": "https://Stackoverflow.com/users/11222265", "pm_score": -1, "selected": false, "text": "first=int(input(\"first: \")) # converting str to int\nprint(\"first\")\nsecond=int(input(\"second: \")) # converting str to int\nprint(\"second\")\nsum=float(first) + float(second)\nprint(\"sum\" +str(sum))\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20450297/" ]
74,362,072
<p>I am writing a program where the user enters certain substrings, and the code will concatenate them based on overlapping characters. The program works perfectly fine for two strings, however, when I enter three strings, it overlaps two substrings in the string. Here is my code: `</p> <pre><code>y = int(input(&quot;How many strings do you want to enter?: &quot;)) String_List = [] final_str = &quot;&quot; for i in range(y): x = input(&quot;Enter a string: &quot;) String_List.append(x) for o in String_List: for p in String_List: if o != p: if o in p: if p not in final_str: final_str += str(p) elif p in o: if o not in final_str: final_str += str(o) for n in range(2,len(p)): if o[-n:] == p[:n]: if o and p not in final_str: p = p[n:] final_str += str(o+p) for j in range(2,len(p)): if o[:j] == p[-j:]: if o and p not in final_str: o = o[j:] final_str += str(p+o) else: continue else: continue print(final_str) </code></pre> <p>`</p> <p>To better explain this problem, I entered three substrings, A1B2, 1B2C3, C3D4E5. Here is the output I got: A1B2C3<strong>1B2C3</strong>D4E5 The bold area is the repeat that I don't want.</p>
[ { "answer_id": 74362143, "author": "Paul-Marie", "author_id": 9603417, "author_profile": "https://Stackoverflow.com/users/9603417", "pm_score": 1, "selected": false, "text": ":=" }, { "answer_id": 74362752, "author": "Muhammad Ayaz", "author_id": 11222265, "author_profile": "https://Stackoverflow.com/users/11222265", "pm_score": -1, "selected": false, "text": "first=int(input(\"first: \")) # converting str to int\nprint(\"first\")\nsecond=int(input(\"second: \")) # converting str to int\nprint(\"second\")\nsum=float(first) + float(second)\nprint(\"sum\" +str(sum))\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18628562/" ]
74,362,106
<p>I just noticed that <code>libclang_rt.asan_osx_dynamic.dylib</code> is in the release build of my macOS app's <code>Contents/Frameworks/</code> directory. I was under the impression that the address sanitizer is a debug feature, so I was surprised to see this. I'm using xcodebuild in a custom build script to generate the release build of the app.</p> <p>2 questions:</p> <ol> <li>Is it wrong for that dylib to be in release builds?</li> <li>How do I prevent Xcode from including it?</li> </ol>
[ { "answer_id": 74362143, "author": "Paul-Marie", "author_id": 9603417, "author_profile": "https://Stackoverflow.com/users/9603417", "pm_score": 1, "selected": false, "text": ":=" }, { "answer_id": 74362752, "author": "Muhammad Ayaz", "author_id": 11222265, "author_profile": "https://Stackoverflow.com/users/11222265", "pm_score": -1, "selected": false, "text": "first=int(input(\"first: \")) # converting str to int\nprint(\"first\")\nsecond=int(input(\"second: \")) # converting str to int\nprint(\"second\")\nsum=float(first) + float(second)\nprint(\"sum\" +str(sum))\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1228525/" ]
74,362,110
<ol> <li>I declare a variable and assign it an integer value, its type is &lt;class 'int&gt;. Shouldn't that be an object?</li> <li>If I define a class and instantiate its object, the type of the object is again class.</li> <li>If I assign a variable to object, the variable is &lt;class 'object&gt; and its type is &lt;class 'type'&gt; (refer the corresponding shell entries)</li> </ol> <p>To be precise, I want to understand what it means when (in tutorials) it is said that everything in Python is an object, when I can see the that type always says it's a class? Can anyone please explain this discrepancy?</p> <p>In Python shell: 1.</p> <pre><code>&gt;&gt;&gt; a = 1 &gt;&gt;&gt; type(a) &gt;&gt;&gt; &lt;class 'int'&gt; </code></pre> <ol start="2"> <li></li> </ol> <pre><code>&gt;&gt;&gt; class Something: ... pass ... &gt; &gt;&gt;&gt; s = Something() &gt;&gt;&gt; type(s) &gt;&gt;&gt; &lt;class '__main__.Something'&gt; </code></pre> <ol start="3"> <li></li> </ol> <pre><code>&gt;&gt;&gt; t = object &gt;&gt;&gt; t &gt;&gt;&gt; &lt;class 'object'&gt; &gt; &gt;&gt;&gt; type(t) &gt;&gt;&gt; &lt;class 'type'&gt; </code></pre>
[ { "answer_id": 74362521, "author": "chepner", "author_id": 1126841, "author_profile": "https://Stackoverflow.com/users/1126841", "pm_score": 2, "selected": false, "text": "type(a)" }, { "answer_id": 74362559, "author": "Serge Ballesta", "author_id": 3545273, "author_profile": "https://Stackoverflow.com/users/3545273", "pm_score": 0, "selected": false, "text": "object" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15188807/" ]
74,362,124
<p>i'm trying to get user data from AAD using Microsoft Graph API Python SDK. App registration that i have in company tenant has the followiing API permissions: <a href="https://i.stack.imgur.com/Ve2Eh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ve2Eh.png" alt="enter image description here" /></a></p> <p>I'm using the following piece of code to get user's details from AAD:</p> <pre><code>from azure.common.credentials import ServicePrincipalCredentials from azure.graphrbac import GraphRbacManagementClient credentials = ServicePrincipalCredentials( client_id=&quot;appClientId&quot;, secret=&quot;appClientSecret&quot;, resource=&quot;https://graph.windows.net&quot;, tenant = 'companyTenant' ) tenant_id = 'companyTenantId' graphrbac_client = GraphRbacManagementClient( credentials, tenant_id ) user = graphrbac_client.users.get(&quot;myUserObjectId&quot;) </code></pre> <p>And get &quot;azure.graphrbac.models.graph_error_py3.GraphErrorException: Insufficient privileges to complete the operation.&quot;</p> <p>I'm using Python 3.10.5 and my app service should be able to get data of any user from AAD.</p> <p>What am i doing wrong here?</p>
[ { "answer_id": 74387930, "author": "Sridevi", "author_id": 18043665, "author_profile": "https://Stackoverflow.com/users/18043665", "pm_score": 1, "selected": false, "text": "API permissions" }, { "answer_id": 74388054, "author": "1gentlemann", "author_id": 8483809, "author_profile": "https://Stackoverflow.com/users/8483809", "pm_score": 1, "selected": true, "text": "from azure.identity import ClientSecretCredential\nfrom msgraph.core import GraphClient\n\ncredential = ClientSecretCredential(tenant_id='tenantId',client_secret='appRegClientId',client_id='appRegClientSecret')\nclient = GraphClient(credential=credential)\n\nresult = client.get('/users') # gets all users\n# result = client.get('/users/userObjectId') # gets a certain user by it's objectId\n# result = client.get('/users/email') # gets a certain user by it's email address\n\nprint(result.json())\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8483809/" ]
74,362,135
<p>I have main navigation stack with few child stacks. In <code>OnboardingStack</code> child stack, I set up custom header per screen, but it renders double header (adds one more header with child stack name above custom header intended for that screen). How can I get rid of it? Tried passing <code>screenOptions={{headerShown: false}}</code> on parent stack and then both headers hide (i.e. missing custom header on screen too). How can I get rid of that additional header above custom one?</p> <pre><code>const MainNavigation = () =&gt; { return ( &lt;NavigationContainer&gt; &lt;Stack.Navigator id={'MainStack'}&gt; &lt;Stack.Screen name=&quot;SplashScreen&quot; component={Splash} options={{ headerShown: false }} /&gt; &lt;Stack.Screen name=&quot;Onboarding&quot; component={OnboardingStack} /&gt; &lt;Stack.Screen name=&quot;Auth&quot; component={AuthStack} /&gt; &lt;Stack.Screen name=&quot;Home&quot; options={{ headerShown: false }} component={Tabs} /&gt; &lt;/Stack.Navigator&gt; &lt;/NavigationContainer&gt; ); </code></pre> <p>};</p> <p>This is <code>OnboardingStack</code> :</p> <pre><code>const OnboardingStack = () =&gt; { return ( &lt;Stack.Navigator initialRouteName=&quot;Onboarding&quot;&gt; &lt;Stack.Screen name=&quot;OnboardingStep1&quot; component={OnboardingStep1} options={{ header: () =&gt; &lt;Header title={'header'} /&gt;, }} /&gt; &lt;Stack.Screen name=&quot;OnboardingStep2&quot; component={OnboardingStep2} options={{ header: () =&gt; &lt;Header title={'header'} /&gt;, }} /&gt; &lt;Stack.Screen name=&quot;OnboardingStep3&quot; component={OnboardingStep3} options={{ headerShown: false, }} /&gt; &lt;/Stack.Navigator&gt; ); </code></pre> <p>};</p> <p>I want get rid of light gray header above my custom one.</p> <p><a href="https://i.stack.imgur.com/ETPbR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ETPbR.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74387930, "author": "Sridevi", "author_id": 18043665, "author_profile": "https://Stackoverflow.com/users/18043665", "pm_score": 1, "selected": false, "text": "API permissions" }, { "answer_id": 74388054, "author": "1gentlemann", "author_id": 8483809, "author_profile": "https://Stackoverflow.com/users/8483809", "pm_score": 1, "selected": true, "text": "from azure.identity import ClientSecretCredential\nfrom msgraph.core import GraphClient\n\ncredential = ClientSecretCredential(tenant_id='tenantId',client_secret='appRegClientId',client_id='appRegClientSecret')\nclient = GraphClient(credential=credential)\n\nresult = client.get('/users') # gets all users\n# result = client.get('/users/userObjectId') # gets a certain user by it's objectId\n# result = client.get('/users/email') # gets a certain user by it's email address\n\nprint(result.json())\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13451224/" ]
74,362,155
<p>I am deploying a simple function on Google Cloud Functions but I am getting a <code>Function cannot be initialized. Error: function terminated. Recommended action: inspect logs for termination reason.</code> error.</p> <p>This is my code:</p> <p>index.js</p> <pre><code>require('dotenv').config(); const crypto = require('crypto'); const { Octokit } = require(&quot;@octokit/core&quot;); const moment = require('moment'); const myFunc = (req, res) =&gt; { // My Code } </code></pre> <p>package.json</p> <pre><code>{ &quot;name&quot;: &quot;Test&quot;, &quot;version&quot;: &quot;1.0.0&quot;, &quot;description&quot;: &quot;Test&quot;, &quot;main&quot;: &quot;index.js&quot;, &quot;scripts&quot;: { &quot;start&quot;: &quot;node index.js&quot; }, &quot;author&quot;: &quot;jane doe&quot;, &quot;license&quot;: &quot;MIT&quot;, &quot;dependencies&quot;: { &quot;@octokit/core&quot;: &quot;^4.1.0&quot;, &quot;dotenv&quot;: &quot;^16.0.3&quot;, &quot;moment&quot;: &quot;^2.29.4&quot; } } </code></pre> <p>Other files are:</p> <ul> <li>.env file to set environment variables</li> <li>package-lock.json</li> <li>node_modules folder</li> </ul> <p>I am deploying using the UI, and have set the entry point to <code>myFunc</code>. <a href="https://i.stack.imgur.com/7HFO1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7HFO1.png" alt="deployment" /></a></p> <p>My deployment is unsuccessful when doing it this way and this is what my error logs say:</p> <ul> <li><code>Function 'myFunc' is not defined in the provided module.</code></li> <li><code>Did you specify the correct target function to execute?</code></li> <li><code>Could not load the function, shutting down.</code></li> <li><code>Function cannot be initialized. Error: function terminated. Recommended action: inspect logs for termination reason.</code></li> </ul> <p>What am I missing here?</p>
[ { "answer_id": 74387930, "author": "Sridevi", "author_id": 18043665, "author_profile": "https://Stackoverflow.com/users/18043665", "pm_score": 1, "selected": false, "text": "API permissions" }, { "answer_id": 74388054, "author": "1gentlemann", "author_id": 8483809, "author_profile": "https://Stackoverflow.com/users/8483809", "pm_score": 1, "selected": true, "text": "from azure.identity import ClientSecretCredential\nfrom msgraph.core import GraphClient\n\ncredential = ClientSecretCredential(tenant_id='tenantId',client_secret='appRegClientId',client_id='appRegClientSecret')\nclient = GraphClient(credential=credential)\n\nresult = client.get('/users') # gets all users\n# result = client.get('/users/userObjectId') # gets a certain user by it's objectId\n# result = client.get('/users/email') # gets a certain user by it's email address\n\nprint(result.json())\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10034685/" ]
74,362,186
<p>So, importing an implicit member from a created instance works as expected,</p> <pre class="lang-scala prettyprint-override"><code>object Test extends App { class Bag { implicit val ssss: String = &quot;omg&quot; } def call(): Unit = { val bag = new Bag import bag._ val s = implicitly[String] println(s) } call() } </code></pre> <p>But, if I try doing the same with <code>spark.implicits._</code></p> <pre class="lang-scala prettyprint-override"><code>object Test extends App { val spark: SparkSession = ... def call(): Unit = { import spark.implicits._ case class Person(id: Long, name: String) // I can summon an existing encoder // val enc = implicitly[Encoder[Long]] // but encoder derivation is failing for some reason // val encP = implicitly[Encoder[Person]] val df: Dataset[Person] = spark.range(10).map(i =&gt; Person(i, i.toString)) df.show() } } </code></pre> <p>It fails to derive the <code>Encoder[Person]</code>,</p> <pre><code>Unable to find encoder for type Person. An implicit Encoder[Person] is needed to store Person instances in a Dataset. Primitive types (Int, String, etc) and Product types (case classes) are supported by importing spark.implicits._ Support for serializing other types will be added in future releases. .map(i =&gt; Person(i, i.toString) </code></pre> <p>But, it works if I create the dataframe outside the method,</p> <pre class="lang-scala prettyprint-override"><code>object Test extends App { val spark: SparkSession = ... import spark.implicits._ case class Person(id: Long, name: String) val df: Dataset[Person] = spark.range(10).map(i =&gt; Person(i, i.toString)) df.show() } </code></pre> <p>Tested with Scala version <code>2.13.10</code> and <code>2.12.17</code> with Spark version <code>3.3.1</code>.</p>
[ { "answer_id": 74363386, "author": "partlov", "author_id": 759126, "author_profile": "https://Stackoverflow.com/users/759126", "pm_score": 2, "selected": false, "text": "case class" }, { "answer_id": 74377253, "author": "Dmytro Mitin", "author_id": 5249621, "author_profile": "https://Stackoverflow.com/users/5249621", "pm_score": 2, "selected": true, "text": "Person" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1151929/" ]
74,362,202
<p>I have table:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>user_id</th> <th>days_since_install</th> </tr> </thead> <tbody> <tr> <td>001</td> <td>0</td> </tr> <tr> <td>001</td> <td>1</td> </tr> <tr> <td>001</td> <td>1</td> </tr> </tbody> </table> </div> <p>It is necessary to check if there is 1 in the column &quot;days_since_install&quot; in grouping by &quot;user_id&quot; and fill in True in the column &quot;retention_1d&quot; otherwise False.</p> <p>The resulting table should look like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>user_id</th> <th>retention_1d</th> </tr> </thead> <tbody> <tr> <td>001</td> <td>True</td> </tr> <tr> <td></td> <td></td> </tr> </tbody> </table> </div>
[ { "answer_id": 74362238, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 0, "selected": false, "text": "groupby.any" }, { "answer_id": 74362257, "author": "BENY", "author_id": 7964527, "author_profile": "https://Stackoverflow.com/users/7964527", "pm_score": 3, "selected": true, "text": "any" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14085367/" ]
74,362,212
<p>I have a data set like this</p> <pre><code>at_ID journey_id flight is_origin is_destination is_outbound 1 1 1 NA NA TRUE 2 1 2 NA NA TRUE 3 1 3 NA NA FALSE 4 1 4 NA NA FALSE 5 2 1 NA NA FALSE 6 3 1 NA NA TRUE 7 3 2 NA NA FALSE </code></pre> <p>The columns is_origin and is_destination must be filled with TRUE/FALSE with the following conditions:</p> <pre><code>#first condition is_origin = TRUE if min(flight) AND is_outbound = TRUE is_destination = TRUE if max(flight) AND is_outbound =TRUE #second condition is_origin = TRUE if min(flight) AND if is_outbound = FALSE is_destination = TRUE if max(flight) AND if is_outbound = FALSE </code></pre> <p>The output should look like this:</p> <pre><code>at_ID journey_id flight is_origin is_destination is_outbound 1 1 1 TRUE FALSE TRUE 2 1 2 FALSE TRUE TRUE 3 1 3 TRUE FALSE FALSE 4 1 4 FALSE TRUE FALSE 5 2 1 TRUE TRUE FALSE 6 3 1 TRUE FALSE TRUE 7 3 2 FALSE TRUE FALSE </code></pre> <p>Is there an efficient way to do this?</p>
[ { "answer_id": 74362287, "author": "Jilber Urbina", "author_id": 1315767, "author_profile": "https://Stackoverflow.com/users/1315767", "pm_score": 1, "selected": false, "text": "is_origin" }, { "answer_id": 74362404, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 0, "selected": false, "text": "library(dplyr)\n\ndf %>% \n group_by(journey_id) %>% \n mutate(is_origin = flight == min(flight) & (is_outbound == T | is_outbound == F), \n is_destination = flight == max(flight) & (is_outbound == T | is_outbound == F)) %>% \n ungroup()\n# A tibble: 7 × 6\n at_ID journey_id flight is_origin is_destination is_outbound\n <int> <int> <int> <lgl> <lgl> <lgl>\n1 1 1 1 TRUE FALSE TRUE\n2 2 1 2 FALSE FALSE TRUE\n3 3 1 3 FALSE FALSE FALSE\n4 4 1 4 FALSE TRUE FALSE\n5 5 2 1 TRUE TRUE FALSE\n6 6 3 1 TRUE FALSE TRUE\n7 7 3 2 FALSE TRUE FALSE\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18679050/" ]
74,362,247
<p>I am trying to build an elevator simulator program and I am getting started with the passenger function. I need to create a thread for each passenger and ask them to input their floor number. I have been able to create the no of passengers (threads) needed and I just need to ask them for their input. But I haven't been able to figure that out</p> <p>code</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;time.h&gt; #include &lt;pthread.h&gt; #include &lt;unistd.h&gt; #define MAX_PASSENGERS 5 #define floor 5 #define NUM_THREAD 6 pthread_mutex_t mymutex = PTHREAD_MUTEX_INITIALIZER; /*Mutex Initializer*/ int dest_floor; int elevator[floor]; int current_floor; int no_passengers; int t, user_input; void *passengers(void *threadid) { // Getting thread ID long tid; tid = (long)threadid; printf(&quot;Passenger %d Kindly select your floor number :\n&quot;, tid); scanf(&quot;%d\n&quot;, &amp;user_input); // Where I ask them for input // End of Getting ID pthread_exit(NULL); } int main() { pthread_t thread[NUM_THREAD]; int th; for (t = 1; t &lt; NUM_THREAD; t++) { th = pthread_create(&amp;thread[t], NULL, passengers, (void *)t); if (th) { printf(&quot;ERROR Creating Thread\n&quot;); exit(-1); } } pthread_exit(NULL); } </code></pre> <p>What I tried:</p> <pre><code>void *passengers(void *threadid) { // Getting thread ID long tid; tid = (long)threadid; printf(&quot;Passenger %d Kindly select your floor number :\n&quot;, tid); scanf(&quot;%d\n&quot;, &amp;user_input); // Where I ask them for input // End of Getting ID pthread_exit(NULL); } </code></pre> <p>What I was expecting :</p> <pre><code>Passenger 2 Kindly select your floor number:2 Passenger 3 KIndly select your floor number:4 ... and so on </code></pre> <p>What I got :</p> <pre><code>Passenger 1 Kindly select your floor number: Passenger 2 KIndly select your floor number : Passenger 3 Kindly select your floor number: Passenger 4 KIndly select your floor number : Passenger 5 Kindly select your floor number: 2 3 4 5 6 </code></pre> <p>It doesn't allow the user to input a floor number on the prompt, but prints out all the threads and then collects the input.</p>
[ { "answer_id": 74362556, "author": "Lundin", "author_id": 584518, "author_profile": "https://Stackoverflow.com/users/584518", "pm_score": 2, "selected": false, "text": "stdin" }, { "answer_id": 74362654, "author": "Ingo Leonhardt", "author_id": 2470782, "author_profile": "https://Stackoverflow.com/users/2470782", "pm_score": 3, "selected": true, "text": "stdin" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362247", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16668751/" ]
74,362,266
<p>Given the following algorithm that returns a value from a predefined enumeration if a random input value <code>u</code> is less than some predefined probability in a (cumulative) <code>prob</code> vector</p> <pre class="lang-r prettyprint-override"><code>val &lt;- 1:5 prob &lt;- c(1/3,1/30,2/15,7/30,4/15) u &lt;- runif(1) if (u&lt;prob[1]) { x=val[1] } else if(u&lt;prob[1]+prob[2]) { x=val[2] } else if(u&lt;prob[1]+prob[2]+prob[3]) { x=val[3] } else if (u&lt;prob[1]+prob[2]+prob[3]+prob[4]) { x=val[4] } else x=val[5] } </code></pre> <p>Is there a way to make all this more efficient? I can't figure it out how to do it differently.</p>
[ { "answer_id": 74362298, "author": "Maël", "author_id": 13460602, "author_profile": "https://Stackoverflow.com/users/13460602", "pm_score": 2, "selected": false, "text": "cumsum" }, { "answer_id": 74362303, "author": "Ben Bolker", "author_id": 190277, "author_profile": "https://Stackoverflow.com/users/190277", "pm_score": 3, "selected": false, "text": "sample(val, size = 1, prob = prob)" }, { "answer_id": 74362309, "author": "MrFlick", "author_id": 2372064, "author_profile": "https://Stackoverflow.com/users/2372064", "pm_score": 3, "selected": false, "text": "findInterval" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19101562/" ]
74,362,276
<div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>HOUR</th> <th>Account_id</th> <th>media_id</th> <th>impressions</th> </tr> </thead> <tbody> <tr> <td>2022-11-04 04:00:00 UTC</td> <td>256789</td> <td>35</td> <td>null</td> </tr> <tr> <td>2022-11-04 05:00:00 UTC</td> <td>256789</td> <td>35</td> <td>null</td> </tr> <tr> <td>2022-11-04 06:00:00 UTC</td> <td>256789</td> <td>35</td> <td>null</td> </tr> <tr> <td>2022-11-04 07:00:00 UTC</td> <td>256789</td> <td>35</td> <td>null</td> </tr> <tr> <td>2022-11-04 08:00:00 UTC</td> <td>256789</td> <td>35</td> <td>40</td> </tr> <tr> <td>2022-11-04 09:00:00 UTC</td> <td>256789</td> <td>35</td> <td>7</td> </tr> <tr> <td>2022-11-04 10:00:00 UTC</td> <td>256789</td> <td>35</td> <td>null</td> </tr> <tr> <td>2022-11-04 11:00:00 UTC</td> <td>256789</td> <td>35</td> <td>10</td> </tr> <tr> <td>2022-11-04 12:00:00 UTC</td> <td>256789</td> <td>35</td> <td>12</td> </tr> </tbody> </table> </div> <p>What we are trying to do is that when the impressions is count is null for an hour, then we take the value from the impressions where it is not null and then split the number evenly across the previously consecutive null rows and the first non null row.</p> <p>If we take the row where the impressions count is <code>40</code> in the above 4 rows the impressions is null so including the row where the impressions is <code>40</code> makes the count as <code>5</code>, then we divide <code>40</code> by <code>5</code> hence each hour gets <code>8</code> impressions.</p> <p>The same above logic can be applied to the row where the impressions count is <code>10</code>. It is distributed between <code>2</code> rows evenly hence in the output it is <code>5</code> impressions for each hour.</p> <p>Here <code>HOUR</code> column is an increment of one hour with no gaps in between.</p> <p>The query looks like this:</p> <pre><code>select *, case when impressions is null then row_number() over(partition by media_id,ACCOUNT_ID ORDER BY HOUR) else 0 end as rn1, from table_name order by 1 ; </code></pre> <p>How I take it from there?</p> <p>Expected Output:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>HOUR</th> <th>Account_id</th> <th>media_id</th> <th>impressions</th> <th>distributed_impressions</th> </tr> </thead> <tbody> <tr> <td>2022-11-04 04:00:00 UTC</td> <td>256789</td> <td>35</td> <td>null</td> <td>8</td> </tr> <tr> <td>2022-11-04 05:00:00 UTC</td> <td>256789</td> <td>35</td> <td>null</td> <td>8</td> </tr> <tr> <td>2022-11-04 06:00:00 UTC</td> <td>256789</td> <td>35</td> <td>null</td> <td>8</td> </tr> <tr> <td>2022-11-04 07:00:00 UTC</td> <td>256789</td> <td>35</td> <td>null</td> <td>8</td> </tr> <tr> <td>2022-11-04 08:00:00 UTC</td> <td>256789</td> <td>35</td> <td>40</td> <td>8</td> </tr> <tr> <td>2022-11-04 09:00:00 UTC</td> <td>256789</td> <td>35</td> <td>7</td> <td>7</td> </tr> <tr> <td>2022-11-04 10:00:00 UTC</td> <td>256789</td> <td>35</td> <td>null</td> <td>5</td> </tr> <tr> <td>2022-11-04 11:00:00 UTC</td> <td>256789</td> <td>35</td> <td>10</td> <td>5</td> </tr> <tr> <td>2022-11-04 12:00:00 UTC</td> <td>256789</td> <td>35</td> <td>12</td> <td>12</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74362515, "author": "Jaytiger", "author_id": 19039920, "author_profile": "https://Stackoverflow.com/users/19039920", "pm_score": 3, "selected": true, "text": "SELECT * EXCEPT(part),\n MAX(impressions) OVER w1 / COUNT(*) OVER W1 AS distributed_impressions \n FROM (\n SELECT *, COUNT(*) OVER w0 - COUNTIF(impressions IS NULL) OVER w0 AS part\n FROM sample_table\n WINDOW w0 AS (PARTITION BY Account_id, media_id ORDER BY HOUR ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)\n ) WINDOW w1 AS (PARTITION BY Account_id, media_id, part);\n" }, { "answer_id": 74362760, "author": "KeithL", "author_id": 3325290, "author_profile": "https://Stackoverflow.com/users/3325290", "pm_score": 0, "selected": false, "text": "declare @T table (hr datetime, Account_id int, media_id int, impressions decimal(5,2))\n\ninsert into @t\nvalues\n('2022-11-04 04:00:00' ,256789 ,35 ,null)\n,('2022-11-04 05:00:00' ,256789 ,35 ,null)\n,('2022-11-04 06:00:00' ,256789 ,35 ,null)\n,('2022-11-04 07:00:00' ,256789 ,35 ,null)\n,('2022-11-04 08:00:00' ,256789 ,35 ,40)\n,('2022-11-04 09:00:00' ,256789 ,35 ,7)\n,('2022-11-04 10:00:00' ,256789 ,35 ,null)\n,('2022-11-04 11:00:00' ,256789 ,35 ,10)\n,('2022-11-04 12:00:00' ,256789 ,35 ,12)\n\ndeclare @prevHr datetime\n ,@currHr datetime\n ,@imp int\n ,@AvgImp decimal(5,2)\n ,@GapCt int\n\ndeclare csr cursor \nfor\nselect hr,impressions\nfrom @t\nwhere impressions is not null\norder by hr\n\nopen csr\n\nfetch next from csr into @currHr,@imp\n\n--Handle the starting point\nselect @GapCt = count(*)\nfrom @t\nwhere hr <= @currHr\n\nset @AvgImp = @imp/@GapCt\n\nupdate @t\nset impressions = @AvgImp\nwhere hr <= @currHr\n\nset @prevHr = @currHr\n\nfetch next from csr into @currHr,@imp\n\nwhile @@FETCH_STATUS=0\nBEGIN\n select @GapCt = count(*)\n from @t\n where hr <= @currHr\n and hr > @prevHr\n\n set @AvgImp = @imp/@GapCt\n\n update @t\n set impressions = @AvgImp\n where hr <= @currHr\n and hr > @prevHr\n\n set @prevHr = @currHr\n\n fetch next from csr into @currHr,@imp\nEND\n\nclose csr\ndeallocate csr\n\nselect * from @t\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9087250/" ]
74,362,301
<p>I have a webpage with some images on it:</p> <pre><code>&lt;head&gt; &lt;style type=&quot;text/css&quot;&gt; #pictureframe { width: 100% background-color: #00000066; } #pictureframe &gt; img { max-height: 90%; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); border: solid 2em #000000; border-radius: 1em; cursor: pointer; overflow-x: scroll; } .isHidden { display: none; visibility: hidden; z-index: -1; } .isHidden &gt; img { z-index: -1; } .isVisible { display: block; visibility: visible; z-index: 99; } .isVisible &gt; img { z-index: 100; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div id=&quot;pictureframe&quot;&gt;&lt;img src=&quot;&quot; /&gt;&lt;/div&gt; &lt;div id=&quot;pictures&quot;&gt; &lt;!-- pictures here ... --&gt; &lt;div class=&quot;cell&quot;&gt;&lt;img src=&quot;./images/image01.jpg&quot; width=&quot;100px&quot; loading=&quot;lazy&quot; /&gt;&lt;/div&gt; &lt;!-- pictures here ... --&gt; &lt;/div&gt; &lt;script type=&quot;text/javascript&quot;&gt; const pictureframe = document.getElementById('pictureframe'); var pictureframe_img = pictureframe.children[0]; var imgarray = document.getElementById('pictures').querySelectorAll('img'); for(let i=0; i&lt;imgarray.length; i++){ imgarray[i].addEventListener('click', function(){ pictureframe.classList.replace('isHidden','isVisible'); pictureframe_img.src = imgarray[i].src; }); } pictureframe_img.addEventListener('click', function(){ pictureframe.classList.replace('isVisible','isHidden'); }); &lt;/script&gt; &lt;/body&gt; </code></pre> <p>This works fairly well, in that when I click the image, the <code>pictureframe</code> is &quot;front and center&quot;, and when I click the pictureframe, it does disappear nicely.</p> <p>However, when I go back and forth between mobile, things start to look bad.</p> <p>I have the <code>max-height</code> set, which works well on desktop, but on mobile, the edgs are clipped off. If I reverse it, set the <code>max-width</code> then it will also work fine on desktop, but the top and bottom will be clipped off on mobile.</p> <p>I cannot seem to find the right balance so that it looks good on desktop and mobile. It seems that I may need to dynamically set either the <code>max-height</code> or <code>max-width</code> depending, but I am not sure if this is the correct way to go.</p> <hr /> <p><strong>EDIT:</strong></p> <p>Here is a jsfiddle with a working example:</p> <p><a href="https://jsfiddle.net/1uqgoc8w/" rel="nofollow noreferrer">https://jsfiddle.net/1uqgoc8w/</a></p>
[ { "answer_id": 74362515, "author": "Jaytiger", "author_id": 19039920, "author_profile": "https://Stackoverflow.com/users/19039920", "pm_score": 3, "selected": true, "text": "SELECT * EXCEPT(part),\n MAX(impressions) OVER w1 / COUNT(*) OVER W1 AS distributed_impressions \n FROM (\n SELECT *, COUNT(*) OVER w0 - COUNTIF(impressions IS NULL) OVER w0 AS part\n FROM sample_table\n WINDOW w0 AS (PARTITION BY Account_id, media_id ORDER BY HOUR ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)\n ) WINDOW w1 AS (PARTITION BY Account_id, media_id, part);\n" }, { "answer_id": 74362760, "author": "KeithL", "author_id": 3325290, "author_profile": "https://Stackoverflow.com/users/3325290", "pm_score": 0, "selected": false, "text": "declare @T table (hr datetime, Account_id int, media_id int, impressions decimal(5,2))\n\ninsert into @t\nvalues\n('2022-11-04 04:00:00' ,256789 ,35 ,null)\n,('2022-11-04 05:00:00' ,256789 ,35 ,null)\n,('2022-11-04 06:00:00' ,256789 ,35 ,null)\n,('2022-11-04 07:00:00' ,256789 ,35 ,null)\n,('2022-11-04 08:00:00' ,256789 ,35 ,40)\n,('2022-11-04 09:00:00' ,256789 ,35 ,7)\n,('2022-11-04 10:00:00' ,256789 ,35 ,null)\n,('2022-11-04 11:00:00' ,256789 ,35 ,10)\n,('2022-11-04 12:00:00' ,256789 ,35 ,12)\n\ndeclare @prevHr datetime\n ,@currHr datetime\n ,@imp int\n ,@AvgImp decimal(5,2)\n ,@GapCt int\n\ndeclare csr cursor \nfor\nselect hr,impressions\nfrom @t\nwhere impressions is not null\norder by hr\n\nopen csr\n\nfetch next from csr into @currHr,@imp\n\n--Handle the starting point\nselect @GapCt = count(*)\nfrom @t\nwhere hr <= @currHr\n\nset @AvgImp = @imp/@GapCt\n\nupdate @t\nset impressions = @AvgImp\nwhere hr <= @currHr\n\nset @prevHr = @currHr\n\nfetch next from csr into @currHr,@imp\n\nwhile @@FETCH_STATUS=0\nBEGIN\n select @GapCt = count(*)\n from @t\n where hr <= @currHr\n and hr > @prevHr\n\n set @AvgImp = @imp/@GapCt\n\n update @t\n set impressions = @AvgImp\n where hr <= @currHr\n and hr > @prevHr\n\n set @prevHr = @currHr\n\n fetch next from csr into @currHr,@imp\nEND\n\nclose csr\ndeallocate csr\n\nselect * from @t\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/319020/" ]
74,362,351
<p>When I click on the <code>Portfolio</code> rubric, the page is not running...</p> <p><a href="https://i.stack.imgur.com/eNzhO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eNzhO.png" alt="enter image description here" /></a></p> <p>I have an error message in the console which is the following.</p> <pre><code>ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'administration/portfolio' Error: Cannot match any routes. URL Segment: 'administration/portfolio' </code></pre> <p><a href="https://i.stack.imgur.com/Qf5Qs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Qf5Qs.png" alt="enter image description here" /></a></p> <p>Here is the structure of the project</p> <p><a href="https://i.stack.imgur.com/3Uo7J.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3Uo7J.png" alt="enter image description here" /></a></p> <p>I suspect it's a problem with the route configuration, but I haven't found the problem for several hours.</p> <p><em><strong>app-routing.module.ts</strong></em></p> <pre><code>const routes: Routes = [ { path: '', component: OnlineComponent, canActivate: [AuthGuard] }, { path: 'signin', component: SigninComponent }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } </code></pre> <p><em><strong>app.module.ts</strong></em></p> <pre><code>@NgModule({ imports: [ BrowserModule, ReactiveFormsModule, HttpClientModule, AppRoutingModule ], declarations: [ AppComponent, OnlineComponent, SigninComponent ], providers: [ { provide: HTTP_INTERCEPTORS, useClass: BasicAuthInterceptor, multi: true }, { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }, // provider used to create fake backend fakeBackendProvider ], bootstrap: [AppComponent] }) export class AppModule { } </code></pre> <p><em><strong>online-routing.module.ts</strong></em></p> <pre><code>const ONLINE_ROUTES: Routes = [ { path: '', component: OnlineComponent, children: [ { path: 'administration', loadChildren: () =&gt; import('./views/administration/administration.module').then((m) =&gt; m.AdministrationModule), }, ] }, ]; @NgModule({ imports: [RouterModule.forChild(ONLINE_ROUTES)], exports: [RouterModule], }) export class OnlineRoutingModule {} </code></pre> <p><em><strong>online.module.ts</strong></em></p> <pre><code>@NgModule({ imports: [CommonModule, OnlineRoutingModule], declarations: [OnlineComponent], }) export class OnlineModule {} </code></pre> <p><em><strong>administration-routing.module.ts</strong></em></p> <pre><code>export const ADMINISTRATION_ROUTES: Routes = [ { path: '', component: OnlineComponent, }, { path: 'portfolio', component: PortfolioComponent, }, ]; @NgModule({ imports: [RouterModule.forChild(ADMINISTRATION_ROUTES)], exports: [RouterModule], }) export class AdministrationRoutingModule {} </code></pre> <p><em><strong>administration.module.ts</strong></em></p> <pre><code>@NgModule({ imports: [CommonModule, AdministrationRoutingModule], declarations: [AdministrationComponent], }) export class AdministrationModule {} </code></pre> <p><em><strong>portfolio.module.ts</strong></em></p> <pre><code>@NgModule({ imports: [CommonModule, RouterModule], declarations: [PortfolioComponent], }) export class PortfolioModule {} </code></pre> <p>Here is the project <a href="https://stackblitz.com/github/kora1348/nini?file=src/app/views/online/views/administration/administration.module.ts" rel="nofollow noreferrer">here</a>.</p> <p>Thank you for your help.</p>
[ { "answer_id": 74362515, "author": "Jaytiger", "author_id": 19039920, "author_profile": "https://Stackoverflow.com/users/19039920", "pm_score": 3, "selected": true, "text": "SELECT * EXCEPT(part),\n MAX(impressions) OVER w1 / COUNT(*) OVER W1 AS distributed_impressions \n FROM (\n SELECT *, COUNT(*) OVER w0 - COUNTIF(impressions IS NULL) OVER w0 AS part\n FROM sample_table\n WINDOW w0 AS (PARTITION BY Account_id, media_id ORDER BY HOUR ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)\n ) WINDOW w1 AS (PARTITION BY Account_id, media_id, part);\n" }, { "answer_id": 74362760, "author": "KeithL", "author_id": 3325290, "author_profile": "https://Stackoverflow.com/users/3325290", "pm_score": 0, "selected": false, "text": "declare @T table (hr datetime, Account_id int, media_id int, impressions decimal(5,2))\n\ninsert into @t\nvalues\n('2022-11-04 04:00:00' ,256789 ,35 ,null)\n,('2022-11-04 05:00:00' ,256789 ,35 ,null)\n,('2022-11-04 06:00:00' ,256789 ,35 ,null)\n,('2022-11-04 07:00:00' ,256789 ,35 ,null)\n,('2022-11-04 08:00:00' ,256789 ,35 ,40)\n,('2022-11-04 09:00:00' ,256789 ,35 ,7)\n,('2022-11-04 10:00:00' ,256789 ,35 ,null)\n,('2022-11-04 11:00:00' ,256789 ,35 ,10)\n,('2022-11-04 12:00:00' ,256789 ,35 ,12)\n\ndeclare @prevHr datetime\n ,@currHr datetime\n ,@imp int\n ,@AvgImp decimal(5,2)\n ,@GapCt int\n\ndeclare csr cursor \nfor\nselect hr,impressions\nfrom @t\nwhere impressions is not null\norder by hr\n\nopen csr\n\nfetch next from csr into @currHr,@imp\n\n--Handle the starting point\nselect @GapCt = count(*)\nfrom @t\nwhere hr <= @currHr\n\nset @AvgImp = @imp/@GapCt\n\nupdate @t\nset impressions = @AvgImp\nwhere hr <= @currHr\n\nset @prevHr = @currHr\n\nfetch next from csr into @currHr,@imp\n\nwhile @@FETCH_STATUS=0\nBEGIN\n select @GapCt = count(*)\n from @t\n where hr <= @currHr\n and hr > @prevHr\n\n set @AvgImp = @imp/@GapCt\n\n update @t\n set impressions = @AvgImp\n where hr <= @currHr\n and hr > @prevHr\n\n set @prevHr = @currHr\n\n fetch next from csr into @currHr,@imp\nEND\n\nclose csr\ndeallocate csr\n\nselect * from @t\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18216840/" ]
74,362,383
<p>I've added a Lambda Step as the first step in my Sagemaker Pipeline. It processes some data and creates 2 files as part of the output like so:</p> <pre><code>from sagemaker.workflow.lambda_step import LambdaStep, Lambda, LambdaOutput, LambdaOutputTypeEnum # lamb_preprocess = LambdaStep(func_arn=&quot;&quot;) output_param_1 = LambdaOutput(output_name=&quot;status&quot;, output_type=LambdaOutputTypeEnum.Integer) output_param_2 = LambdaOutput(output_name=&quot;file_name_a_c_drop&quot;, output_type=LambdaOutputTypeEnum.String) output_param_3 = LambdaOutput(output_name=&quot;file_name_q_c_drop&quot;, output_type=LambdaOutputTypeEnum.String) step_lambda = LambdaStep( name=&quot;ProcessingLambda&quot;, lambda_func=Lambda( function_arn=&quot;arn:aws:lambda:us-east-1:xxxxxxxx:function:xxxxx&quot; ), inputs={ &quot;input_data&quot;: input_data, &quot;input_file&quot;: trigger_file, &quot;input_bucket&quot;: trigger_bucket }, outputs = [ output_param_1, output_param_2, output_param_3 ] ) </code></pre> <p>In my next step, I want to trigger a Processing Job for which I need to pass in the above Lambda function's outputs as it's inputs. I'm trying to do it like so:</p> <pre><code>inputs = [ ProcessingInput(source=step_lambda.properties.Outputs[&quot;file_name_q_c_drop&quot;], destination=&quot;/opt/ml/processing/input&quot;), ProcessingInput(source=step_lambda.properties.Outputs[&quot;file_name_a_c_drop&quot;], destination=&quot;/opt/ml/processing/input&quot;), ] </code></pre> <p>However, when the processing step is trying to get created, I get a validation message saying</p> <p><code>Object of type Properties is not JSON serializable</code></p> <p>I followed the data dependency docs here: <a href="https://sagemaker.readthedocs.io/en/stable/amazon_sagemaker_model_building_pipeline.html#lambdastep" rel="nofollow noreferrer">https://sagemaker.readthedocs.io/en/stable/amazon_sagemaker_model_building_pipeline.html#lambdastep</a> and tried accessing <code>step_lambda.OutputParameters[&quot;file_name_a_c_drop&quot;]</code> too but it errored out saying <code>'LambdaStep' object has no attribute 'OutputParameters'</code></p> <p>How do I properly access the return value of a LambdaStep in a Sagemaker pipeline ?</p>
[ { "answer_id": 74362515, "author": "Jaytiger", "author_id": 19039920, "author_profile": "https://Stackoverflow.com/users/19039920", "pm_score": 3, "selected": true, "text": "SELECT * EXCEPT(part),\n MAX(impressions) OVER w1 / COUNT(*) OVER W1 AS distributed_impressions \n FROM (\n SELECT *, COUNT(*) OVER w0 - COUNTIF(impressions IS NULL) OVER w0 AS part\n FROM sample_table\n WINDOW w0 AS (PARTITION BY Account_id, media_id ORDER BY HOUR ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)\n ) WINDOW w1 AS (PARTITION BY Account_id, media_id, part);\n" }, { "answer_id": 74362760, "author": "KeithL", "author_id": 3325290, "author_profile": "https://Stackoverflow.com/users/3325290", "pm_score": 0, "selected": false, "text": "declare @T table (hr datetime, Account_id int, media_id int, impressions decimal(5,2))\n\ninsert into @t\nvalues\n('2022-11-04 04:00:00' ,256789 ,35 ,null)\n,('2022-11-04 05:00:00' ,256789 ,35 ,null)\n,('2022-11-04 06:00:00' ,256789 ,35 ,null)\n,('2022-11-04 07:00:00' ,256789 ,35 ,null)\n,('2022-11-04 08:00:00' ,256789 ,35 ,40)\n,('2022-11-04 09:00:00' ,256789 ,35 ,7)\n,('2022-11-04 10:00:00' ,256789 ,35 ,null)\n,('2022-11-04 11:00:00' ,256789 ,35 ,10)\n,('2022-11-04 12:00:00' ,256789 ,35 ,12)\n\ndeclare @prevHr datetime\n ,@currHr datetime\n ,@imp int\n ,@AvgImp decimal(5,2)\n ,@GapCt int\n\ndeclare csr cursor \nfor\nselect hr,impressions\nfrom @t\nwhere impressions is not null\norder by hr\n\nopen csr\n\nfetch next from csr into @currHr,@imp\n\n--Handle the starting point\nselect @GapCt = count(*)\nfrom @t\nwhere hr <= @currHr\n\nset @AvgImp = @imp/@GapCt\n\nupdate @t\nset impressions = @AvgImp\nwhere hr <= @currHr\n\nset @prevHr = @currHr\n\nfetch next from csr into @currHr,@imp\n\nwhile @@FETCH_STATUS=0\nBEGIN\n select @GapCt = count(*)\n from @t\n where hr <= @currHr\n and hr > @prevHr\n\n set @AvgImp = @imp/@GapCt\n\n update @t\n set impressions = @AvgImp\n where hr <= @currHr\n and hr > @prevHr\n\n set @prevHr = @currHr\n\n fetch next from csr into @currHr,@imp\nEND\n\nclose csr\ndeallocate csr\n\nselect * from @t\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5446891/" ]
74,362,386
<p>how are you?</p> <p>I have a distance matrix and need to perform a filter based on another list before applying some functions.</p> <p>The matrix has 10 elements that represent machines and the distances between them, I need to filter this list by getting only the distances between some chosen machines.</p> <pre><code>matrix = [[0, 1, 3, 17, 24, 12, 18, 16, 17, 15], [1, 0, 2, 2, 5, 6, 13, 11, 12, 10], [3, 2, 0, 1, 6, 12, 18, 12, 17, 15], [17, 2, 1, 0, 3, 12, 17, 15, 16, 14], [24, 5, 6, 3, 0, 1, 24, 22, 23, 21], [12, 6, 12, 12, 1, 0, 12, 10, 11, 9], [18, 13, 18, 17, 24, 12, 0, 3, 4, 5], [16, 11, 12, 15, 22, 10, 3, 0, 1, 2], [17, 12, 17, 16, 23, 11, 4, 1, 0, 1], [15, 10, 15, 14, 21, 9, 5, 2, 1, 0]] </code></pre> <p>The list used for filtering, for example, is:</p> <pre><code>filter_list = [1, 2, 7, 10] </code></pre> <p>The idea is to use this list to filter the rows and the indices of the sublists to get the final matrix:</p> <pre><code>final_matrix = [[0, 1, 18, 15], [1, 0, 13, 10], [18, 13, 0, 5], [15, 10, 5, 0]] </code></pre> <p>It is worth noting that the filter list elements vary. Can someone please help me?</p> <p>That's what I tried:</p> <pre><code>final_matrix = [] for i in range(0, len(filter_list)): for j in range(0,len(filter_list[i])): a = filter_list[i][j] final_matrix .append(matrix[a-1]) print(final_matrix) </code></pre> <p>This is because the filter_list can have sublists. I get it:</p> <pre><code>final_matrix = [[0, 1, 3, 17, 24, 12, 18, 16, 17, 15], [1, 0, 2, 2, 5, 6, 13, 11, 12, 10], [18, 13, 18, 17, 24, 12, 0, 3, 4, 5], [15, 10, 15, 14, 21, 9, 5, 2, 1, 0]] </code></pre> <p>I could not remove the spare elements.</p>
[ { "answer_id": 74362442, "author": "chc", "author_id": 12932447, "author_profile": "https://Stackoverflow.com/users/12932447", "pm_score": 1, "selected": false, "text": "final_matrix = []\n\nfor i in filter_list:\n to_append = []\n for j in filter_list:\n to_append.append(matrix[i-1][j-1])\n final_matrix.append(to_append)\n" }, { "answer_id": 74362448, "author": "ILS", "author_id": 10017662, "author_profile": "https://Stackoverflow.com/users/10017662", "pm_score": 3, "selected": true, "text": "final_matrix = [[matrix[row-1][col-1] for col in filter_list] for row in filter_list]\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19023621/" ]
74,362,396
<p>After upgrading my Windows OS, I got an error while installing the node-sass package.</p> <p>As shown in the output that I provided, the rest of the packages are installed successfully.</p> <p>To fix this error, I added the path of python and node to environment variable names, installed visual build tools, tried different versions of Python, installed node in other folders and did all the methods that could be found in stack overflow, but I still get the errors.</p> <p>Please help me solve this issue.</p> <pre><code>E:\Programming\ME\Dibaji_Agency\MainSite&gt;npm i node-sass npm WARN deprecated @npmcli/move-file@1.1.2: This functionality has been moved to @npmcli/fs npm WARN deprecated har-validator@5.1.5: this library is no longer supported npm WARN deprecated uuid@3.4.0: Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details. npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142 npm ERR! code 1 npm ERR! path E:\Programming\ME\Dibaji_Agency\MainSite\node_modules\node-sass npm ERR! command failed npm ERR! command C:\Windows\system32\cmd.exe /d /s /c node scripts/build.js npm ERR! Building: C:\Program Files\nodejs\node.exe E:\Programming\ME\Dibaji_Agency\MainSite\node_modules\node-gyp\bin\node-gyp.js rebuild --verbose --libsass_ext= --libsass_cflags= --libsass_ldflags= --libsass_library= npm ERR! gyp info it worked if it ends with ok npm ERR! gyp verb cli [ npm ERR! gyp verb cli 'C:\\Program Files\\nodejs\\node.exe', npm ERR! gyp verb cli 'E:\\Programming\\ME\\Dibaji_Agency\\MainSite\\node_modules\\node-gyp\\bin\\node-gyp.js', npm ERR! gyp verb cli 'rebuild', npm ERR! gyp verb cli '--verbose', npm ERR! gyp verb cli '--libsass_ext=', npm ERR! gyp verb cli '--libsass_cflags=', npm ERR! gyp verb cli '--libsass_ldflags=', npm ERR! gyp verb cli '--libsass_library=' npm ERR! gyp verb cli ] npm ERR! gyp info using node-gyp@8.4.1 npm ERR! gyp info using node@18.12.1 | win32 | x64 npm ERR! gyp verb command rebuild [] npm ERR! gyp verb command clean [] npm ERR! gyp verb clean removing &quot;build&quot; directory npm ERR! gyp verb command configure [] npm ERR! gyp verb download using dist-url https://npm.taobao.org/dist npm ERR! gyp verb find Python checking Python explicitly set from command line or npm configuration npm ERR! gyp verb find Python - &quot;--python=&quot; or &quot;npm config get python&quot; is &quot;/path/to/executable/python&quot; npm ERR! gyp verb find Python - executing &quot;/path/to/executable/python&quot; to get executable path npm ERR! gyp verb find Python - &quot;/path/to/executable/python&quot; is not in PATH or produced an error npm ERR! gyp verb find Python Python is not set from environment variable PYTHON npm ERR! gyp verb find Python checking if &quot;python3&quot; can be used npm ERR! gyp verb find Python - executing &quot;python3&quot; to get executable path npm ERR! gyp verb find Python - &quot;python3&quot; is not in PATH or produced an error npm ERR! gyp verb find Python checking if &quot;python&quot; can be used npm ERR! gyp verb find Python - executing &quot;python&quot; to get executable path npm ERR! gyp verb find Python - &quot;python&quot; is not in PATH or produced an error npm ERR! gyp verb find Python checking if Python is C:\Users\Parham\AppData\Local\Programs\Python\Python39\python.exe npm ERR! gyp verb find Python - executing &quot;C:\Users\Parham\AppData\Local\Programs\Python\Python39\python.exe&quot; to get version npm ERR! gyp verb find Python - version is &quot;3.9.12&quot; npm ERR! gyp info find Python using Python version 3.9.12 found at &quot;C:\Users\Parham\AppData\Local\Programs\Python\Python39\python.exe&quot; npm ERR! gyp verb get node dir no --target version specified, falling back to host node version: 18.12.1 npm ERR! gyp verb command install [ '18.12.1' ] npm ERR! gyp verb download using dist-url https://npm.taobao.org/dist npm ERR! gyp verb install input version string &quot;18.12.1&quot; npm ERR! gyp verb install installing version: 18.12.1 npm ERR! gyp verb install --ensure was passed, so won't reinstall if already installed npm ERR! gyp verb install version is already installed, need to check &quot;installVersion&quot; npm ERR! gyp verb got &quot;installVersion&quot; 9 npm ERR! gyp verb needs &quot;installVersion&quot; 9 npm ERR! gyp verb install version is good npm ERR! gyp verb get node dir target node version installed: 18.12.1 npm ERR! gyp verb build dir attempting to create &quot;build&quot; dir: E:\Programming\ME\Dibaji_Agency\MainSite\node_modules\node-sass\build npm ERR! gyp verb build dir &quot;build&quot; dir needed to be created? Yes npm ERR! gyp verb find VS msvs_version was set from command line or npm config npm ERR! gyp verb find VS - looking for Visual Studio version 2022 npm ERR! gyp verb find VS VCINSTALLDIR not set, not running in VS Command Prompt npm ERR! gyp verb find VS could not use PowerShell to find Visual Studio 2017 or newer, try re-running with '--loglevel silly' for more details npm ERR! gyp verb find VS looking for Visual Studio 2015 npm ERR! gyp verb find VS - not found npm ERR! gyp verb find VS not looking for VS2013 as it is only supported up to Node.js 8 npm ERR! gyp ERR! find VS npm ERR! gyp ERR! find VS msvs_version was set from command line or npm config npm ERR! gyp ERR! find VS - looking for Visual Studio version 2022 npm ERR! gyp ERR! find VS VCINSTALLDIR not set, not running in VS Command Prompt npm ERR! gyp ERR! find VS could not use PowerShell to find Visual Studio 2017 or newer, try re-running with '--loglevel silly' for more details npm ERR! gyp ERR! find VS looking for Visual Studio 2015 npm ERR! gyp ERR! find VS - not found npm ERR! gyp ERR! find VS not looking for VS2013 as it is only supported up to Node.js 8 npm ERR! gyp ERR! find VS npm ERR! gyp ERR! find VS valid versions for msvs_version: npm ERR! gyp ERR! find VS npm ERR! gyp ERR! find VS ************************************************************** npm ERR! gyp ERR! find VS You need to install the latest version of Visual Studio npm ERR! gyp ERR! find VS including the &quot;Desktop development with C++&quot; workload. npm ERR! gyp ERR! find VS For more information consult the documentation at: npm ERR! gyp ERR! find VS https://github.com/nodejs/node-gyp#on-windows npm ERR! gyp ERR! find VS ************************************************************** npm ERR! gyp ERR! find VS npm ERR! gyp ERR! configure error npm ERR! gyp ERR! stack Error: Could not find any Visual Studio installation to use npm ERR! gyp ERR! stack at VisualStudioFinder.fail (E:\Programming\ME\Dibaji_Agency\MainSite\node_modules\node-gyp\lib\find-visualstudio.js:122:47) npm ERR! gyp ERR! stack at E:\Programming\ME\Dibaji_Agency\MainSite\node_modules\node-gyp\lib\find-visualstudio.js:75:16 npm ERR! gyp ERR! stack at VisualStudioFinder.findVisualStudio2013 (E:\Programming\ME\Dibaji_Agency\MainSite\node_modules\node-gyp\lib\find-visualstudio.js:363:14) npm ERR! gyp ERR! stack at E:\Programming\ME\Dibaji_Agency\MainSite\node_modules\node-gyp\lib\find-visualstudio.js:71:14 npm ERR! gyp ERR! stack at E:\Programming\ME\Dibaji_Agency\MainSite\node_modules\node-gyp\lib\find-visualstudio.js:384:16 npm ERR! gyp ERR! stack at E:\Programming\ME\Dibaji_Agency\MainSite\node_modules\node-gyp\lib\util.js:54:7 npm ERR! gyp ERR! stack at E:\Programming\ME\Dibaji_Agency\MainSite\node_modules\node-gyp\lib\util.js:33:16 npm ERR! gyp ERR! stack at ChildProcess.exithandler (node:child_process:420:5) npm ERR! gyp ERR! stack at ChildProcess.emit (node:events:513:28) npm ERR! gyp ERR! stack at maybeClose (node:internal/child_process:1091:16) npm ERR! gyp ERR! System Windows_NT 10.0.19045 npm ERR! gyp ERR! command &quot;C:\\Program Files\\nodejs\\node.exe&quot; &quot;E:\\Programming\\ME\\Dibaji_Agency\\MainSite\\node_modules\\node-gyp\\bin\\node-gyp.js&quot; &quot;rebuild&quot; &quot;--verbose&quot; &quot;--libsass_ext=&quot; &quot;--libsass_cflags=&quot; &quot;--libsass_ldflags=&quot; &quot;--libsass_library=&quot; npm ERR! gyp ERR! cwd E:\Programming\ME\Dibaji_Agency\MainSite\node_modules\node-sass npm ERR! gyp ERR! node -v v18.12.1 npm ERR! gyp ERR! node-gyp -v v8.4.1 npm ERR! gyp ERR! not ok npm ERR! Build failed with error code: 1 npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\Parham\AppData\Local\npm-cache\_logs\2022-11-09T01_13_37_687Z-debug-0.log </code></pre>
[ { "answer_id": 74362442, "author": "chc", "author_id": 12932447, "author_profile": "https://Stackoverflow.com/users/12932447", "pm_score": 1, "selected": false, "text": "final_matrix = []\n\nfor i in filter_list:\n to_append = []\n for j in filter_list:\n to_append.append(matrix[i-1][j-1])\n final_matrix.append(to_append)\n" }, { "answer_id": 74362448, "author": "ILS", "author_id": 10017662, "author_profile": "https://Stackoverflow.com/users/10017662", "pm_score": 3, "selected": true, "text": "final_matrix = [[matrix[row-1][col-1] for col in filter_list] for row in filter_list]\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16431648/" ]
74,362,408
<p>I want to form a new list of dictionaries by random choosing dictionary from existing list of dictionary based on same key name.</p> <pre><code>existing_list = [{'topic1': 'question1'}, {'topic2': 'question2'}, {'topic3': 'question3'}, {'topic2': 'question4'}, {'topic2': 'question5'}, {'topic1': 'question2'}, {'topic1': 'question3'}, {'topic3': 'question5'}, {'topic3': 'question6'}] </code></pre> <p>The new list should choose two random dictionary having same key name:</p> <pre><code> new_list = [{'topic1': 'question1'}, {'topic1': 'question3'}, {'topic2': 'question2'}, {'topic2': 'question5'}, {'topic3': 'question5'}, {'topic3': 'question3'}] </code></pre> <p>Taking suggestions below i change the data structures:</p> <pre><code>arrange = {} for item in questions: arrange.setdefault(item['parent'], []).append(item['question_link']) question_lists_of_lists = [random.sample(arrange[topic], 2) for topic in arrange] question_lists= sum(question_lists_of_lists,[]) </code></pre> <p>Now i am looking for better alternative to achieve the new list using:</p> <pre><code>new_list = [] for k, v in arrange.items(): for i in range(2): random_value = random.choice(v) new_list.append({k: random_value}) arrange[k].remove(random_value) </code></pre>
[ { "answer_id": 74362442, "author": "chc", "author_id": 12932447, "author_profile": "https://Stackoverflow.com/users/12932447", "pm_score": 1, "selected": false, "text": "final_matrix = []\n\nfor i in filter_list:\n to_append = []\n for j in filter_list:\n to_append.append(matrix[i-1][j-1])\n final_matrix.append(to_append)\n" }, { "answer_id": 74362448, "author": "ILS", "author_id": 10017662, "author_profile": "https://Stackoverflow.com/users/10017662", "pm_score": 3, "selected": true, "text": "final_matrix = [[matrix[row-1][col-1] for col in filter_list] for row in filter_list]\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1980208/" ]
74,362,409
<p>I have a long list of JSON data, with repeats of contents similar to followings.</p> <p>Due to the original JSON file is too long, I will just shared the hyperlinks here. This is a result generated from a database called RegulomeDB.</p> <p><a href="https://regulomedb.org/regulome-search/?regions=chr16:28539847-28539848&amp;genome=GRCh37&amp;format=json" rel="nofollow noreferrer">Direct link to the JSON file</a></p> <p>I would like to extract specific data (eQTLs) from <code>&quot;method&quot;: &quot;eQTLs&quot;</code> and <code>&quot;value&quot;: &quot;xxxx&quot;</code>, and put them into 2 columns (tab delimited) exactly like below. Note: <code>&quot;value&quot;:&quot;xxxx&quot;</code> is extracted right after <code>&quot;method&quot;: &quot;eQTLs&quot;</code>is detected.</p> <pre><code>eQTLs firstResult, secondResult, thirdResult, ... </code></pre> <p>In this example, the desired output is:</p> <pre><code>eQTLs EIF3S8, EIF3CL </code></pre> <p>I've tried using a python script but was unsuccessful.</p> <pre><code>import json with open('file.json') as f: f_json = json.load(f) print 'f_json[0]['&quot;method&quot;: &quot;eQTLs&quot;'] + &quot;\t&quot; + f_json[0][&quot;value&quot;] </code></pre> <p>Thank you for your kind help.</p>
[ { "answer_id": 74373547, "author": "SaSkY", "author_id": 18104248, "author_profile": "https://Stackoverflow.com/users/18104248", "pm_score": 1, "selected": true, "text": "cat file.json | grep -iE '\"method\":\\s*\"eQTLs\"[^}]*' -o | cut -d ',' -f 1,5 | sed -r 's/\"|:|method|value//gi' | sed 's/\\s*eqtls,\\s*//gi' | tr '\\n' ',' | sed 's/,$/\\n/g' | sed 's/,/, /g' | xargs echo -e 'eQTLs\\x09'\n" }, { "answer_id": 74379712, "author": "Reino", "author_id": 2703456, "author_profile": "https://Stackoverflow.com/users/2703456", "pm_score": 1, "selected": false, "text": "$ xidel -s \"https://regulomedb.org/regulome-search/?regions=chr16:28539847-28539848&genome=GRCh37&format=json\" \\\n -e '\"eQTLs&#9;\"||join($json(\"@graph\")()[method=\"eQTLs\"]/value,\", \")'\neQTLs EIF3S8, EIF3CL\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13838020/" ]
74,362,411
<p>I want to take city name as input and on button click it should call specific url <a href="https://www.google.com/maps/search/tourist+places+in+" rel="nofollow noreferrer">https://www.google.com/maps/search/tourist+places+in+</a> <strong>mumbai</strong> with ending url with input value in react. It should open the url in new tab</p> <p>Destination.jsx (file name)</p> <pre><code>import React from 'react' const Destination = () =&gt; { return ( &lt;div&gt; &lt;h1&gt;Destination&lt;/h1&gt; &lt;input type=&quot;text&quot; name=&quot;place&quot; class=&quot;form-control&quot; id=&quot;place&quot; placeholder=&quot;Enter place&quot; /&gt; &lt;button type=&quot;Submit&quot; id=&quot;submit&quot;&gt; Search &lt;/button&gt; &lt;/div&gt; ) } export default Destination </code></pre>
[ { "answer_id": 74373547, "author": "SaSkY", "author_id": 18104248, "author_profile": "https://Stackoverflow.com/users/18104248", "pm_score": 1, "selected": true, "text": "cat file.json | grep -iE '\"method\":\\s*\"eQTLs\"[^}]*' -o | cut -d ',' -f 1,5 | sed -r 's/\"|:|method|value//gi' | sed 's/\\s*eqtls,\\s*//gi' | tr '\\n' ',' | sed 's/,$/\\n/g' | sed 's/,/, /g' | xargs echo -e 'eQTLs\\x09'\n" }, { "answer_id": 74379712, "author": "Reino", "author_id": 2703456, "author_profile": "https://Stackoverflow.com/users/2703456", "pm_score": 1, "selected": false, "text": "$ xidel -s \"https://regulomedb.org/regulome-search/?regions=chr16:28539847-28539848&genome=GRCh37&format=json\" \\\n -e '\"eQTLs&#9;\"||join($json(\"@graph\")()[method=\"eQTLs\"]/value,\", \")'\neQTLs EIF3S8, EIF3CL\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16966403/" ]
74,362,455
<p>I am trying to integrate <code>NavigationStack</code> in my <code>SwiftUI</code> app, I have four views <code>CealUIApp</code>, <code>OnBoardingView</code>, <code>UserTypeView</code> and <code>RegisterView</code>. I want to navigate from <code>OnBoardingView</code> to <code>UserTypeView</code> when user presses a button in <code>OnBoardingView</code> and from <code>UserTypeView</code> to <code>RegisterView</code> when user presses a button in <code>UserTypeView </code></p> <p>Below is my code for CealUIApp</p> <pre><code>@main struct CealUIApp: App { @State private var path = [String]() var body: some Scene { WindowGroup { NavigationStack(path: $path){ OnBoardingView(path: $path) } } } } </code></pre> <p>In <code>OnBoardingView</code></p> <pre><code>Button { path.append(&quot;UserTypeView&quot;) } label: { Text(&quot;Hello&quot;) }.navigationDestination(for: String.self) { string in UserTypeView(path: $path) } </code></pre> <p>In <code>UserTypeView</code></p> <pre><code>Button { path.append(&quot;RegisterView&quot;) } label: { Text(&quot;Hello&quot;) }.navigationDestination(for: String.self) { string in RegisterView() } </code></pre> <p>When button in <code>UserTypeView</code> is pressed I keep getting navigated to <code>UserTypeView</code> instead of <code>RegisterView</code> with msg in <code>Xcode</code> logs saying <code>Only root-level navigation destinations are effective for a navigation stack with a homogeneous path.</code></p>
[ { "answer_id": 74362840, "author": "lorem ipsum", "author_id": 12738750, "author_profile": "https://Stackoverflow.com/users/12738750", "pm_score": 2, "selected": true, "text": "Only root-level navigation destinations are effective for a navigation stack with a homogeneous path" }, { "answer_id": 74674417, "author": "grenos", "author_id": 7977491, "author_profile": "https://Stackoverflow.com/users/7977491", "pm_score": 0, "selected": false, "text": " @State private var path: NavigationPath = .init()" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9552485/" ]
74,362,492
<p>I have a numpy array that has a shape of <code>(500, 151296)</code>. Below is the array format</p> <p>array:</p> <pre><code>array([[-0.18510018, 0.13180602, 0.32903048, ..., 0.39744213, -0.01461623, 0.06420607], [-0.14988784, 0.12030973, 0.34801325, ..., 0.36962894, 0.04133283, 0.04434045], [-0.3080041 , 0.18728344, 0.36068922, ..., 0.09335024, -0.11459247, 0.10187756], ..., [-0.17399777, -0.02492459, -0.07236133, ..., 0.08901921, -0.17250113, 0.22222663], [-0.17399777, -0.02492459, -0.07236133, ..., 0.08901921, -0.17250113, 0.22222663], [-0.17399777, -0.02492459, -0.07236133, ..., 0.08901921, -0.17250113, 0.22222663]], dtype=float32) </code></pre> <p>array[0]:</p> <pre><code>array([-0.18510018, 0.13180602, 0.32903048, ..., 0.39744213, -0.01461623, 0.06420607], dtype=float32) </code></pre> <p>I have another list that has stopwords which are same size of the numpy array shape</p> <p>stopwords = ['no', 'not', 'in' .........]</p> <p>I want to add each stopword to the numpy array which has 500 elements. Below is the code that I am using to add</p> <pre><code>for i in range(len(stopwords)): array = np.append(array[i], str(stopwords[i])) </code></pre> <p>I am getting the below error</p> <pre><code>IndexError Traceback (most recent call last) &lt;ipython-input-45-361e2cf6519b&gt; in &lt;module&gt; 1 for i in range(len(stopwords)): ----&gt; 2 array = np.append(array[i], str(stopwords[i])) IndexError: index 2 is out of bounds for axis 0 with size 2 </code></pre> <p>Desired output:</p> <p>array[0]:</p> <pre><code>array([-0.18510018, 0.13180602, 0.32903048, ..., 0.39744213, -0.01461623, 0.06420607, 'no'], dtype=float32) </code></pre> <p>Can anyone tell me where am I doing wrong?</p>
[ { "answer_id": 74362793, "author": "paime", "author_id": 13636407, "author_profile": "https://Stackoverflow.com/users/13636407", "pm_score": 2, "selected": true, "text": "array" }, { "answer_id": 74363860, "author": "hpaulj", "author_id": 901925, "author_profile": "https://Stackoverflow.com/users/901925", "pm_score": 0, "selected": false, "text": "In [76]: arr = np.arange(12).reshape(3,4).astype(float) \nIn [77]: arr\nOut[77]: \narray([[ 0., 1., 2., 3.],\n [ 4., 5., 6., 7.],\n [ 8., 9., 10., 11.]])\n\nIn [78]: words = ['no','not','in']\n\nIn [79]: for i in range(3):\n ...: arr = np.append(arr[i], str(words[i]))\n ...: \n---------------------------------------------------------------------------\nIndexError Traceback (most recent call last)\nInput In [79], in <cell line: 1>()\n 1 for i in range(3):\n----> 2 arr = np.append(arr[i], str(words[i]))\n\nIndexError: index 2 is out of bounds for axis 0 with size 2\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9798210/" ]
74,362,498
<p>The UI to send emails from Salesforce (including Subject, Body, etc.) is not displaying: <a href="https://i.stack.imgur.com/o67r5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/o67r5.png" alt="Tab to send email from the Activity" /></a></p> <p>This Activity section is visible on the right of a Contact Record. On the Related List &quot;Activity History&quot;, the button &quot;Email&quot; is showing the same empty UI.</p> <p>I am logged as a System Admin, I have all the permissions to access the object EmailMessage;</p> <p>The UI displays as expected when using Saleforce Classic: <a href="https://i.stack.imgur.com/peHaP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/peHaP.png" alt="enter image description here" /></a></p> <p>Any idea of why the send Email UI is not displaying the normal set of fields (Subject, Body, To, etc.) with Lightning Experience?</p>
[ { "answer_id": 74362793, "author": "paime", "author_id": 13636407, "author_profile": "https://Stackoverflow.com/users/13636407", "pm_score": 2, "selected": true, "text": "array" }, { "answer_id": 74363860, "author": "hpaulj", "author_id": 901925, "author_profile": "https://Stackoverflow.com/users/901925", "pm_score": 0, "selected": false, "text": "In [76]: arr = np.arange(12).reshape(3,4).astype(float) \nIn [77]: arr\nOut[77]: \narray([[ 0., 1., 2., 3.],\n [ 4., 5., 6., 7.],\n [ 8., 9., 10., 11.]])\n\nIn [78]: words = ['no','not','in']\n\nIn [79]: for i in range(3):\n ...: arr = np.append(arr[i], str(words[i]))\n ...: \n---------------------------------------------------------------------------\nIndexError Traceback (most recent call last)\nInput In [79], in <cell line: 1>()\n 1 for i in range(3):\n----> 2 arr = np.append(arr[i], str(words[i]))\n\nIndexError: index 2 is out of bounds for axis 0 with size 2\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12031499/" ]
74,362,513
<p>i have a function to append a list, something like this:</p> <pre><code>def append_func(element): if xxxx: new_list.append(element) else: [] </code></pre> <p>I have another function that uses <code>append_func()</code>:</p> <pre><code>def second_func(item): for i in item: append_func(i) </code></pre> <p>if i run :</p> <pre><code>new_list = [] second _func(item) new_list </code></pre> <p>This will return the list i want, but i can't do <code>new_list = second _func(item)</code> because in this case <code>new_list</code> will be a <code>None</code>.</p> <p>I understand that <code>append()</code> will return a <code>None</code> type, but i'd like to return the appended list so I can use in other places <code>result = second _func(xxx)</code>, what i have missed? Thanks.</p>
[ { "answer_id": 74362557, "author": "George Rey", "author_id": 1701405, "author_profile": "https://Stackoverflow.com/users/1701405", "pm_score": 1, "selected": false, "text": "def append_func(element):\n if xxxx:\n new_list.append(element)\n else:\n []\n return new_list # here, return whatever you want to return\n" }, { "answer_id": 74362659, "author": "berkelem", "author_id": 4844311, "author_profile": "https://Stackoverflow.com/users/4844311", "pm_score": 0, "selected": false, "text": "new_list" }, { "answer_id": 74363026, "author": "Matthias", "author_id": 1209921, "author_profile": "https://Stackoverflow.com/users/1209921", "pm_score": 3, "selected": true, "text": "second_func" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10581944/" ]
74,362,547
<p>When searching a directory for files of a specific name driven by the <code>_fileToSearch</code> parameter, I then create a custom list of <code>DrawingFound</code> and store the files path in a string called <code>FileDirectory</code>.</p> <p>I then require on a button click <code>OpenDrawing()</code> for the file stored within <code>FileDirectory</code> to open to the user. This works in most cases, however, if the path has a <code>,</code> for example then the explorer defaults to opening the users documents directory. How can I handle commas within a file path to achieve the desired outcome?</p> <pre><code>public partial class DrawingFound { public string DrawingName; public string FileType; public string FileDirectory; public string Revision; public void OpenDrawing() { Process.Start(&quot;Explorer.exe&quot;, FileDirectory); } } public void GetDrawings() { string _searchFolder = @&quot;C:\Users\ThisUser\Documents&quot;; string _fileToSearch = &quot;Example of file, where a comma is used.txt&quot;; ObservableCollection&lt;DrawingFound&gt; _drawings = new(); DirectoryInfo dirInfo = new(_searchFolder); FileInfo[] files = dirInfo.GetFiles($&quot;*{_fileToSearch}*&quot;, SearchOption.AllDirectories); foreach (FileInfo file in files) { if (!_drawings.Any(item =&gt; $&quot;{item.DrawingName}{item.FileType}&quot; == file.Name)) { _drawings.Add(new DrawingFound { DrawingName = Path.GetFileNameWithoutExtension(file.Name), FileType = file.Extension, FileDirectory = file.FullName, Revision = &quot;- Ignore -&quot; }); } } } </code></pre>
[ { "answer_id": 74362618, "author": "George Rey", "author_id": 1701405, "author_profile": "https://Stackoverflow.com/users/1701405", "pm_score": 0, "selected": false, "text": "one \"two\" three" }, { "answer_id": 74364619, "author": "Shadyjunior", "author_id": 9098538, "author_profile": "https://Stackoverflow.com/users/9098538", "pm_score": 0, "selected": false, "text": "Process.Start(\"explorer.exe\", $\"\\\"{FileDirectory}\\\"\");\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9098538/" ]
74,362,563
<p>I am using bootstrap for creating a tab list like below one: <a href="https://i.stack.imgur.com/KEy7F.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KEy7F.png" alt="enter image description here" /></a></p> <p>The problem is that when I click on &quot;Profile&quot; or Contact, it changes nothing. I included the bootstrap library. I mean it doesn't remove the 'active', 'show' classes. Does someone know why?</p> <pre><code>&lt;script src=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js&quot;&gt;&lt;/script&gt; &lt;link href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css&quot; rel=&quot;stylesheet&quot; crossorigin=&quot;anonymous&quot;&gt; &lt;script src=&quot;https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js&quot;&gt;&lt;/script&gt; </code></pre> <pre><code>&lt;ul class=&quot;nav nav-tabs&quot; id=&quot;myTab&quot; role=&quot;tablist&quot;&gt; &lt;li class=&quot;nav-item&quot;&gt; &lt;a class=&quot;nav-link active&quot; id=&quot;home-tab&quot; data-toggle=&quot;tab&quot; href=&quot;#home&quot; role=&quot;tab&quot; aria-controls=&quot;home&quot; aria-selected=&quot;true&quot;&gt;Home&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;nav-item&quot;&gt; &lt;a class=&quot;nav-link&quot; id=&quot;profile-tab&quot; data-toggle=&quot;tab&quot; href=&quot;#profile&quot; role=&quot;tab&quot; aria-controls=&quot;profile&quot; aria-selected=&quot;false&quot;&gt;Profile&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;nav-item&quot;&gt; &lt;a class=&quot;nav-link&quot; id=&quot;contact-tab&quot; data-toggle=&quot;tab&quot; href=&quot;#contact&quot; role=&quot;tab&quot; aria-controls=&quot;contact&quot; aria-selected=&quot;false&quot;&gt;Contact&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;div class=&quot;tab-content&quot; id=&quot;myTabContent&quot;&gt; &lt;div class=&quot;tab-pane fade show active&quot; id=&quot;home&quot; role=&quot;tabpanel&quot; aria-labelledby=&quot;home-tab&quot;&gt;...&lt;/div&gt; &lt;div class=&quot;tab-pane fade&quot; id=&quot;profile&quot; role=&quot;tabpanel&quot; aria-labelledby=&quot;profile-tab&quot;&gt;...&lt;/div&gt; &lt;div class=&quot;tab-pane fade&quot; id=&quot;contact&quot; role=&quot;tabpanel&quot; aria-labelledby=&quot;contact-tab&quot;&gt;...&lt;/div&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 74362796, "author": "Paul Viorel", "author_id": 16815116, "author_profile": "https://Stackoverflow.com/users/16815116", "pm_score": 0, "selected": false, "text": "$('#myTab a').on('click', function (e) {\n e.preventDefault()\n $(this).tab('show')\n})\n" }, { "answer_id": 74362901, "author": "DᴀʀᴛʜVᴀᴅᴇʀ", "author_id": 1952287, "author_profile": "https://Stackoverflow.com/users/1952287", "pm_score": 1, "selected": false, "text": "data-toggle\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16815116/" ]
74,362,576
<p>I'm trying to make dropdownbutton using Getx in flutter However, it doesn't work. Even if I choose a value, the value does not been selected.</p> <pre><code> class BecomePlayerPage2 extends GetView&lt;BecomePlayerController&gt; { const BecomePlayerPage2 ({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Obx( () =&gt; Scaffold( body: Padding( padding: EdgeInsets.all(20), child: DropdownButton&lt;RxString&gt;( onChanged: (newValue){ controller.selected=newValue!; }, value: controller.selected, items: [ for(var value in controller.tierList) DropdownMenuItem( child: new Text( value, ), value: value.obs, ), ] ), ), ), } </code></pre> <pre><code>class BecomePlayerController extends GetxController { final tierList=['first', 'second', 'third'].obs; var selected = &quot;first&quot;.obs; } </code></pre> <p>This is my first day of studying Getx so it is so hard to match with basic widget. What should I do?</p>
[ { "answer_id": 74362796, "author": "Paul Viorel", "author_id": 16815116, "author_profile": "https://Stackoverflow.com/users/16815116", "pm_score": 0, "selected": false, "text": "$('#myTab a').on('click', function (e) {\n e.preventDefault()\n $(this).tab('show')\n})\n" }, { "answer_id": 74362901, "author": "DᴀʀᴛʜVᴀᴅᴇʀ", "author_id": 1952287, "author_profile": "https://Stackoverflow.com/users/1952287", "pm_score": 1, "selected": false, "text": "data-toggle\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19358943/" ]
74,362,600
<p>Trying to get the number <code>811.00</code> when its placed under the word <code>Size</code>.</p> <p>I know how to get the number when its NEAR some word, like &quot;Jerusalem&quot; in this case.<br /> But here I'm trying to get the number when it's <em>under</em> the word <code>Size</code>.</p> <pre><code>Property Size Jerusalem 811.00 A new property agreement </code></pre> <p>Thanks, Couldn't Find any solution for this.</p>
[ { "answer_id": 74552045, "author": "njk18", "author_id": 17160016, "author_profile": "https://Stackoverflow.com/users/17160016", "pm_score": 2, "selected": false, "text": "(?<=(\\w\\s){1}?)(\\d+.\\d+)\n" }, { "answer_id": 74555313, "author": "bobble bubble", "author_id": 5527985, "author_profile": "https://Stackoverflow.com/users/5527985", "pm_score": 2, "selected": false, "text": "^(?:.(?=.*\\n(\\1?+.)))*?(?=Size)(?:\\w\\B(?=.*\\n\\1?+(\\2?+\\D)))*+.*\\n\\1?+\\2?+(?<![\\d.])([\\d.]+)\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14877266/" ]
74,362,606
<p>I have a number of pages in my app wrapped in <code>Offstage</code> widgets. Each page makes use of the provider package to render based on state updates (e.g. the user does something, we make a network call and display the result).</p> <p>As the pages are wrapped in <code>Offstage</code> widgets, the <code>build()</code> methods (and subsequent network calls) are called even if it's not the current page.</p> <p>Is there a way inside the <code>build()</code> method to know if the widget is currently off stage (and if so, skip any expensive logic)?</p> <p>I'm assuming I can work something with global state etc, but I was wondering if there was anything built-in in relation to the <code>Offstage</code> widget itself, similar to <code>mounted</code></p>
[ { "answer_id": 74362876, "author": "Ivo", "author_id": 1514861, "author_profile": "https://Stackoverflow.com/users/1514861", "pm_score": 0, "selected": false, "text": "Offstage" }, { "answer_id": 74439115, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 1, "selected": false, "text": "Map<String, bool>" }, { "answer_id": 74442373, "author": "Rahul", "author_id": 16569443, "author_profile": "https://Stackoverflow.com/users/16569443", "pm_score": 3, "selected": true, "text": " @override\n Widget build(BuildContext context) {\n final offstageParent = context.findAncestorWidgetOfExactType<Offstage>();\n if (offstageParent != null && offstageParent.offstage == false) {\n // widget is currently offstage.\n print('offstaged child');\n } else {\n // widget is not offstage\n print('non-offstaged child');\n }\n return const Text('Example Widget');\n }\n\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/639441/" ]
74,362,629
<p>I'm running API tests using GitHub Actions and I want to upload to the report generated by Mochawesome to Google Cloud so I can see failures clearly without digging through CI logs. I have the upload part working but when I view the html file on Google Cloud it doesn't load, I just get a blank white page. I'm uploading the css files too so why isn't the html file loading?</p> <p><a href="https://i.stack.imgur.com/ne6R3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ne6R3.png" alt="enter image description here" /></a> <a href="https://i.stack.imgur.com/DHbBn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DHbBn.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74362876, "author": "Ivo", "author_id": 1514861, "author_profile": "https://Stackoverflow.com/users/1514861", "pm_score": 0, "selected": false, "text": "Offstage" }, { "answer_id": 74439115, "author": "Gwhyyy", "author_id": 18670641, "author_profile": "https://Stackoverflow.com/users/18670641", "pm_score": 1, "selected": false, "text": "Map<String, bool>" }, { "answer_id": 74442373, "author": "Rahul", "author_id": 16569443, "author_profile": "https://Stackoverflow.com/users/16569443", "pm_score": 3, "selected": true, "text": " @override\n Widget build(BuildContext context) {\n final offstageParent = context.findAncestorWidgetOfExactType<Offstage>();\n if (offstageParent != null && offstageParent.offstage == false) {\n // widget is currently offstage.\n print('offstaged child');\n } else {\n // widget is not offstage\n print('non-offstaged child');\n }\n return const Text('Example Widget');\n }\n\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4405472/" ]
74,362,630
<p>Method not found: 'Void CoreTypeMappingParameters..ctor(System.Type, Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter, Microsoft.EntityFrameworkCore.ChangeTracking.ValueComparer, Microsoft.EntityFrameworkCore.ChangeTracking.ValueComparer, System.Func`3&lt;Microsoft.EntityFrameworkCore.Metadata.IProperty,Microsoft.EntityFrameworkCore.Metadata.IEntityType,Microsoft.EntityFrameworkCore.ValueGeneration.ValueGenerator&gt;)'.</p> <p>I am getting this error. Please help me to solve this.</p> <p>How to solve my problem?</p>
[ { "answer_id": 74410590, "author": "Samisa", "author_id": 918001, "author_profile": "https://Stackoverflow.com/users/918001", "pm_score": 0, "selected": false, "text": "Install-Package Microsoft.EntityFrameworkCore.Design -Version 6.0.10" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20450754/" ]
74,362,637
<p>The objective was to append a node within the node <code>testcases</code> using the <code>lxml</code> append function.</p> <p>However, the compiler return the following error</p> <blockquote> <p>AttributeError: 'NoneType' object has no attribute 'append'</p> </blockquote> <p>But, append the new node into the super node such as <code>question</code> does not produce any error. But as expected, this does not produce the intended output.</p> <p>May I know how to address this issue?</p> <p>The code to reproduce the above issue is</p> <pre><code>from lxml import etree tree = etree.parse(&quot;d_xml.xml&quot;) d='&lt;testcase testtype=&quot;0&quot; useasexample=&quot;0&quot; hiderestiffail=&quot;0&quot; mark=&quot;1.0000000&quot; &gt; &lt;testcode&gt; &lt;text&gt;print(solve(' \ 'read_file(&quot;file_2.txt&quot;)))&lt;/text&gt; &lt;/testcode&gt;&lt;stdin&gt;&lt;text&gt;&lt;/text&gt;&lt;/stdin&gt;&lt;expected&gt;&lt;text&gt;status_2&lt;/text&gt;&lt;/expected' \ '&gt;&lt;extra&gt;&lt;text&gt;&lt;/text&gt;&lt;/extra&gt;&lt;display&gt;&lt;text&gt;SHOW&lt;/text&gt; &lt;/display&gt;&lt;/testcase&gt;' # contentnav = tree.find(&quot;question&quot;) contentnav = tree.find(&quot;testcases&quot;) contentnav.append(etree.XML(d)) print(etree.tostring(tree)) tree.write('output.xml', pretty_print=True, xml_declaration=True, encoding=&quot;utf-8&quot;) </code></pre> <p>The <code>d_xml.xml</code> content is a below or downloadable via the <a href="https://drive.google.com/file/d/1k1_y7dH5P66gIxrUnSwEUgsmjFJEXwvz/view?usp=sharing" rel="nofollow noreferrer">link</a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;quiz&gt; &lt;!-- question: 0 --&gt; &lt;!-- question: 6675757 --&gt; &lt;question type="coderunner"&gt; &lt;name&gt; &lt;text&gt;test_code_runner&lt;/text&gt; &lt;/name&gt; &lt;questiontext format="html"&gt; &lt;text&gt;&lt;![CDATA[&lt;p dir="ltr" style="text-align: left;"&gt;ex_test&lt;br&gt;&lt;/p&gt;]]&gt;&lt;/text&gt; &lt;/questiontext&gt; &lt;generalfeedback format="html"&gt; &lt;text&gt;&lt;/text&gt; &lt;/generalfeedback&gt; &lt;giveupallowed&gt;0&lt;/giveupallowed&gt; &lt;prototypeextra&gt;&lt;/prototypeextra&gt; &lt;testcases&gt; &lt;testcase testtype="0" useasexample="0" hiderestiffail="0" mark="1.0000000"&gt; &lt;testcode&gt; &lt;text&gt;print(solve(read_file('file_1.txt')))&lt;/text&gt; &lt;/testcode&gt; &lt;stdin&gt; &lt;text&gt;&lt;/text&gt; &lt;/stdin&gt; &lt;expected&gt; &lt;text&gt;status_1&lt;/text&gt; &lt;/expected&gt; &lt;extra&gt; &lt;text&gt;&lt;/text&gt; &lt;/extra&gt; &lt;display&gt; &lt;text&gt;SHOW&lt;/text&gt; &lt;/display&gt; &lt;/testcase&gt; &lt;file name="fmlie.cpp" path="/" encoding="base64"&gt;aW1wb3J0IHJhbmRvbH&lt;/file&gt; &lt;file name="idfile.txt" path="/" encoding="base64"&gt;TnVA2DQoyICg==&lt;/file&gt; &lt;/testcases&gt; &lt;/question&gt; &lt;/quiz&gt;</code></pre> </div> </div> </p> <p>The expected output is as below</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-html lang-html prettyprint-override"><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;quiz&gt; &lt;!-- question: 0 --&gt; &lt;!-- question: 6675757 --&gt; &lt;question type="coderunner"&gt; &lt;name&gt; &lt;text&gt;test_code_runner&lt;/text&gt; &lt;/name&gt; &lt;questiontext format="html"&gt; &lt;text&gt;&lt;![CDATA[&lt;p dir="ltr" style="text-align: left;"&gt;ex_test&lt;br&gt;&lt;/p&gt;]]&gt;&lt;/text&gt; &lt;/questiontext&gt; &lt;generalfeedback format="html"&gt; &lt;text&gt;&lt;/text&gt; &lt;/generalfeedback&gt; &lt;giveupallowed&gt;0&lt;/giveupallowed&gt; &lt;prototypeextra&gt;&lt;/prototypeextra&gt; &lt;testcases&gt; &lt;testcase testtype="0" useasexample="0" hiderestiffail="0" mark="1.0000000"&gt; &lt;testcode&gt; &lt;text&gt;print(solve(read_file('file_1.txt')))&lt;/text&gt; &lt;/testcode&gt; &lt;stdin&gt; &lt;text&gt;&lt;/text&gt; &lt;/stdin&gt; &lt;expected&gt; &lt;text&gt;status_1&lt;/text&gt; &lt;/expected&gt; &lt;extra&gt; &lt;text&gt;&lt;/text&gt; &lt;/extra&gt; &lt;display&gt; &lt;text&gt;SHOW&lt;/text&gt; &lt;/display&gt; &lt;/testcase&gt; &lt;testcases&gt; &lt;testcase testtype="0" useasexample="0" hiderestiffail="0" mark="1.0000000"&gt; &lt;testcode&gt; &lt;text&gt;print(solve(read_file('file_2.txt')))&lt;/text&gt; &lt;/testcode&gt; &lt;stdin&gt; &lt;text&gt;&lt;/text&gt; &lt;/stdin&gt; &lt;expected&gt; &lt;text&gt;status_2&lt;/text&gt; &lt;/expected&gt; &lt;extra&gt; &lt;text&gt;&lt;/text&gt; &lt;/extra&gt; &lt;display&gt; &lt;text&gt;SHOW&lt;/text&gt; &lt;/display&gt; &lt;/testcase&gt; &lt;file name="fmlie.cpp" path="/" encoding="base64"&gt;aW1wb3J0IHJhbmRvbH&lt;/file&gt; &lt;file name="idfile.txt" path="/" encoding="base64"&gt;TnVA2DQoyICg==&lt;/file&gt; &lt;/testcases&gt; &lt;/question&gt; &lt;/quiz&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74363096, "author": "LMC", "author_id": 2834978, "author_profile": "https://Stackoverflow.com/users/2834978", "pm_score": 1, "selected": false, "text": "find()" }, { "answer_id": 74363165, "author": "Jack Fleeting", "author_id": 9448090, "author_profile": "https://Stackoverflow.com/users/9448090", "pm_score": 1, "selected": true, "text": "d=etree.fromstring('<testcase testtype=\"0\" useasexample=\"0\" hiderestiffail=\"0\" mark=\"1.0000000\" > <testcode> <text>print(solve(' \\\n 'read_file(\"file_2.txt\")))</text> </testcode><stdin><text></text></stdin><expected><text>status_2</text></expected' \\\n '><extra><text></text></extra><display><text>SHOW</text> </display></testcase>')\n\ndest = tree.xpath('//question//testcases//testcase')[-1]\n#this makes sure d is inserted as the last testcase\n\ndest.addnext(d)\nprint(etree.tostring(tree).decode()) \n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6446053/" ]
74,362,647
<p>I am building a react app and I want to know what is the best way to fill a div with dots, to be more specific how to fill a div entirely with small rounded divs, but no matter the width of the screen the div is always full with small rounded divs.</p> <p>The end result should look like this :</p> <p><a href="https://i.stack.imgur.com/PmgP5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PmgP5.png" alt="How it should look like" /></a></p> <p>I tried to use <code>Array.fill().map()</code> but when the width of my screen changes the dots became unorganized.</p> <p>My code :</p> <pre><code>function About() { const service = [ { icon: &lt;PhoneCallbackIcon style={{ fontSize: 32 }} /&gt;, text: &quot;Inbound Call Center Service&quot;, subText: &quot;Read more&quot; }, { icon: &lt;QuestionAnswerIcon style={{ fontSize: 32 }} /&gt;, text: &quot;Schriftbeschreibung&quot;, subText: &quot;Read more&quot; }, { icon: &lt;GTranslateIcon style={{ fontSize: 32 }} /&gt;, text: &quot;Übersetzung&quot;, subText: &quot;Read more&quot; } ] const dots = 266 return ( &lt;Container&gt; &lt;OurJob&gt; &lt;Title&gt;Was machen wir?&lt;/Title&gt; &lt;Line /&gt; &lt;p&gt;Wir sind Experten in diesen Bereichen&lt;/p&gt; &lt;/OurJob&gt; &lt;OurServices&gt; {service.map((item, index) =&gt; ( &lt;Service key={index} &gt; {item.icon} &lt;div&gt; {item.text} &lt;/div&gt; &lt;p&gt; {item.subText} &lt;/p&gt; &lt;/Service&gt; ))} &lt;/OurServices&gt; &lt;Dots &gt; {Array(dots).fill().map((_, i) =&gt; ( &lt;Dot /&gt; ))} &lt;/Dots&gt; &lt;/Container&gt; ) } </code></pre> <p>My styled components :</p> <pre><code>const Container = styled.div` display: flex; width: 100%; border-radius: 16px; position: relative; margin: 5% 0; box-shadow: 9px 11px 17px -6px rgba(0,0,0,0.3); -webkit-box-shadow: 9px 11px 17px -6px rgba(0,0,0,0.3); -moz-box-shadow: 9px 11px 17px -6px rgba(0,0,0,0.3); ` const Dots = styled.div` position: absolute; width: 33%; display: flex; flex-wrap: wrap; left: -4%; bottom: -25%; ` const Dot = styled.div` width: 4px; content: &quot;&quot;; height: 4px; margin: 5px 5.5px; border-radius: 50%; /* background: rgba(217, 217, 217, 0.5); */ background: black; ` const OurJob = styled.div` width: 25%; padding: 40px; background: rgba(122, 223, 210, 1); overflow: hidden; border-radius: 16px 0 0 16px; p { font-size: 20px; font-weight: 400; color: white; } ` const Line = styled.div` height: 8px; background: white; width: 60%; margin: 10px 0; ` const Title = styled.div` font-size: 50px; font-weight: 600; color: white; ` const OurServices = styled.div` display: flex; width: 70%; ` const Service = styled.div` display: flex; flex-direction: column; justify-content: center; align-items: center; padding: 40px; width: 25%; text-align: center; div { font-size: 22px; font-weight: 600; height: 20%; } p { color: rgba(92, 92, 92, 1); font-size: 20px; } ` </code></pre>
[ { "answer_id": 74363009, "author": "Adam", "author_id": 12571484, "author_profile": "https://Stackoverflow.com/users/12571484", "pm_score": 3, "selected": true, "text": ".dots {\n width: 100%;\n height: 50vh;\n background-image: url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' height='20' width='20'%3E%3Ccircle cx='10' cy='10' r='5' fill='%23e0e0e0' /%3E%3C/svg%3E \");\n}" }, { "answer_id": 74363114, "author": "maxencedhx", "author_id": 20241610, "author_profile": "https://Stackoverflow.com/users/20241610", "pm_score": 0, "selected": false, "text": "background-size" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13886184/" ]
74,362,662
<p>i use a script to take all my files from drive to a google spreadsheet with name, url...</p> <p>My problem is there are a lot of files and the script run during ~30 min and exceed during time permission for apps script.</p> <p>How can i speed this script please ?</p> <pre><code>function listFilesAndFolders() { var folderid = &quot; &quot;; // change FolderID var sh = SpreadsheetApp.getActiveSheet(); sh.clear(); sh.appendRow([&quot;parent&quot;,&quot;folder&quot;, &quot;name&quot;, &quot;update&quot;, &quot;Size&quot;, &quot;URL&quot;, &quot;ID&quot;, &quot;description&quot;, &quot;type&quot;]); try { var parentFolder =DriveApp.getFolderById(folderid); listFiles(parentFolder,parentFolder.getName()) listSubFolders(parentFolder,parentFolder.getName()); } catch (e) { Logger.log(e.toString()); } } function listSubFolders(parentFolder,parent) { var childFolders = parentFolder.getFolders(); while (childFolders.hasNext()) { var childFolder = childFolders.next(); Logger.log(&quot;Fold : &quot; + childFolder.getName()); listFiles(childFolder,parent) listSubFolders(childFolder,parent + &quot;|&quot; + childFolder.getName()); } } function listFiles(fold,parent){ var sh = SpreadsheetApp.getActiveSheet(); var data = []; var files = fold.getFiles(); while (files.hasNext()) { var file = files.next(); data = [ parent, fold.getName(), file.getName(), file.getLastUpdated(), file.getSize(), file.getUrl(), file.getId(), file.getDescription(), file.getMimeType() ]; sh.appendRow(data); } } </code></pre>
[ { "answer_id": 74363009, "author": "Adam", "author_id": 12571484, "author_profile": "https://Stackoverflow.com/users/12571484", "pm_score": 3, "selected": true, "text": ".dots {\n width: 100%;\n height: 50vh;\n background-image: url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' height='20' width='20'%3E%3Ccircle cx='10' cy='10' r='5' fill='%23e0e0e0' /%3E%3C/svg%3E \");\n}" }, { "answer_id": 74363114, "author": "maxencedhx", "author_id": 20241610, "author_profile": "https://Stackoverflow.com/users/20241610", "pm_score": 0, "selected": false, "text": "background-size" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20214066/" ]
74,362,673
<p>Here is a simple example of what I'm trying to achieve: Assume we are given a <code>std::vector&lt;std::byte&gt; rgb_data</code> containing RGB color values and a <code>struct rgb{ double r, g, b; };</code>. I would to create a <code>std::vector&lt;rgb&gt; transformed_rgb_data</code> containing these RGB color values using <code>std::transform</code>. Without <code>std::transform</code>, this could be done as follows:</p> <pre><code>std::size_t j = 0; for (std::size_t i = 0; i &lt; rgb_data.size(); i += 3) { transformed_rgb_data = { static_cast&lt;double&gt;(rgb_data[i], static_cast&lt;double&gt;(rgb_data[i + 1], static_cast&lt;double&gt;(rgb_data[i + 2] }; } </code></pre> <p>Is there a mechanism in the standard library which allows me to construct an iterator for <code>rgb_data</code> which increments by <code>3</code> and references a <code>std::tuple</code> (I think that would be the best idea) which then is passed to the unary function passed to <code>std::transform</code>?</p>
[ { "answer_id": 74363046, "author": "Jack", "author_id": 121747, "author_profile": "https://Stackoverflow.com/users/121747", "pm_score": 2, "selected": false, "text": "std::views::adjacent_view" }, { "answer_id": 74363166, "author": "Ayxan Haqverdili", "author_id": 10147399, "author_profile": "https://Stackoverflow.com/users/10147399", "pm_score": 2, "selected": false, "text": "uint8_t* p" }, { "answer_id": 74365359, "author": "Jarod42", "author_id": 2684539, "author_profile": "https://Stackoverflow.com/users/2684539", "pm_score": 2, "selected": false, "text": "chunk" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/547231/" ]
74,362,692
<p>I'm trying to check if a parameter that was received is 0, but as I'm doing this alot I would like to have a faster way to check if it is 0 and not to have to do an entire if check every time.</p> <p>Exactly like the Guard method allow me to do that with string. This Guard method: using CommunityToolkit.Diagnostics;</p> <p>Here's an example code:</p> <pre><code> Guard.IsNotNullOrEmpty(myname); Guard.IsNotNullOrEmpty(yourname); //this works for strings and if that string is null or empty it will generate an Execption for me if(myage == 0 ) { throw new Exception(&quot;Your age cannot be 0&quot;); } //this does check if myage is 0, but it took 3 lines of code` There is something like Guard for integers? </code></pre>
[ { "answer_id": 74362953, "author": "Tim Schmelter", "author_id": 284240, "author_profile": "https://Stackoverflow.com/users/284240", "pm_score": 0, "selected": false, "text": "Guard.IsNotDefault" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20204855/" ]
74,362,694
<p>I have this table:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">group</th> <th style="text-align: center;">May 1990</th> <th style="text-align: center;">Jun 1990</th> <th style="text-align: center;">Jul 1990</th> </tr> </thead> <tbody> <tr> <td style="text-align: center;">1</td> <td style="text-align: center;">581</td> <td style="text-align: center;">552</td> <td style="text-align: center;">465</td> </tr> <tr> <td style="text-align: center;">2</td> <td style="text-align: center;">193</td> <td style="text-align: center;">184</td> <td style="text-align: center;">176</td> </tr> <tr> <td style="text-align: center;">3</td> <td style="text-align: center;">207</td> <td style="text-align: center;">177</td> <td style="text-align: center;">165</td> </tr> <tr> <td style="text-align: center;">Total</td> <td style="text-align: center;">981</td> <td style="text-align: center;">913</td> <td style="text-align: center;">806</td> </tr> </tbody> </table> </div> <p>I want to calculate percent on row level from the row total.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">group</th> <th style="text-align: center;">May 1990</th> <th style="text-align: center;">Jun 1990</th> <th style="text-align: center;">Jul 1990</th> </tr> </thead> <tbody> <tr> <td style="text-align: center;">1</td> <td style="text-align: center;">0.59</td> <td style="text-align: center;">0.60</td> <td style="text-align: center;">0.58</td> </tr> <tr> <td style="text-align: center;">2</td> <td style="text-align: center;">0.19</td> <td style="text-align: center;">0.21</td> <td style="text-align: center;">0.22</td> </tr> <tr> <td style="text-align: center;">3</td> <td style="text-align: center;">0.21</td> <td style="text-align: center;">0.19</td> <td style="text-align: center;">0.20</td> </tr> <tr> <td style="text-align: center;">Total</td> <td style="text-align: center;">1</td> <td style="text-align: center;">1</td> <td style="text-align: center;">1</td> </tr> </tbody> </table> </div> <p>I got this far for now, but is not what I want.</p> <pre><code>df &lt;- data.frame(group=c('1','2','3','Total'),may_1990=c(581,193,207,981),jun_1990=c(552,184,177,913),jul_1990=c(465,176,165,806)) total &lt;- df %&gt;% slice_tail(n = 1) z &lt;- df %&gt;% rowwise() %&gt;% mutate(across(where(is.numeric), ~ .x/total[-1])) </code></pre>
[ { "answer_id": 74362844, "author": "Maël", "author_id": 13460602, "author_profile": "https://Stackoverflow.com/users/13460602", "pm_score": 2, "selected": true, "text": "across" }, { "answer_id": 74363205, "author": "Laura", "author_id": 19109145, "author_profile": "https://Stackoverflow.com/users/19109145", "pm_score": 0, "selected": false, "text": "df <- data.frame(group=c('1','2','3','Total'),may_1990=c(581,193,207,981),jun_1990=c(552,184,177,913),jul_1990=c(465,176,165,806))\n\n# Compute proportions for the central data\nprop = proportions(as.matrix(df[-4,-1]), 2)\n\n# Add total at the column level (margin = 1)\nprop = addmargins(prop, 1)\n\n# Create the final table\ndf_end = data.frame(\n group=c('1','2','3','Total'),\n prop\n \n)\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9076548/" ]
74,362,709
<p>I'm using PDFLib (this library <a href="https://www.pdflib.com/" rel="nofollow noreferrer">https://www.pdflib.com/</a>). I'm on PHP but this library exists also for other languages, so the question is not specific for PHP.</p> <p>I would like to print on the PDF name value pairs. Something like this: <a href="https://i.stack.imgur.com/myeYd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/myeYd.png" alt="expected output" /></a></p> <p>I know the easiest solution would be to use a table, but I can't because the PDF has to be <strong>accessible</strong> and they told me that, on PDF, a table to show name-value paris would not be accessible, so <strong>I have to find another solution instead of table</strong>.</p> <p>Currently I tried with Textflow:</p> <pre><code>&lt;?php $upperX = 525; $upperY = 780; $lowerX = 70; $lowerY = 50; $y = $upperY; $x = 70; $pdf = new \PDFlib(); $pdf-&gt;begin_document('', ''); $pdf-&gt;begin_page_ext(0, 0, 'width=a4.width height=a4.height'); // Write &quot;Name-Value paris:&quot; $optlist = &quot;fontname={Helvetica} fontsize=8 encoding=utf8 alignment=center fakebold=true&quot;; $tf = 0; $tf = $pdf-&gt;add_textflow($tf, &quot;Name-Value paris:&quot;, $optlist); $pdf-&gt;fit_textflow($tf, $x, $lowerY, $upperX, $y, ''); $pdf-&gt;delete_textflow($tf); $y -= 10; // Write the pairs $label_optlist = &quot;fontname={Helvetica} fontsize=7 encoding=utf8 fakebold=true leftindent=0%&quot;; $value_optlist = &quot;fontname={Helvetica} fontsize=7 encoding=utf8 fakebold=false leftindent=22%&quot;; $tf = 0; $tf = $pdf-&gt;add_textflow($tf, &quot;Name:&quot;, $label_optlist); $tf = $pdf-&gt;add_textflow($tf, &quot;John&quot;, $value_optlist); $pdf-&gt;fit_textflow($tf, $x, $lowerY, $upperX, $y, ''); $pdf-&gt;delete_textflow($tf); $y = $pdf-&gt;get_option('texty', ''); // Get Y where the above textflow ends $tf = 0; $tf = $pdf-&gt;add_textflow($tf, &quot;Surname:&quot;, $label_optlist); $tf = $pdf-&gt;add_textflow($tf, &quot;Doe&quot;, $value_optlist); $pdf-&gt;fit_textflow($tf, $x, $lowerY, $upperX, $y, ''); $pdf-&gt;delete_textflow($tf); $y = $pdf-&gt;get_option('texty', ''); $tf = 0; $tf = $pdf-&gt;add_textflow($tf, &quot;Date of birth:&quot;, $label_optlist); $tf = $pdf-&gt;add_textflow($tf, &quot;2022/11/08&quot;, $value_optlist); $pdf-&gt;fit_textflow($tf, $x, $lowerY, $upperX, $y, ''); $pdf-&gt;delete_textflow($tf); $y = $pdf-&gt;get_option('texty', ''); $tf = 0; $tf = $pdf-&gt;add_textflow($tf, &quot;A key that has a long value:&quot;, $label_optlist); $tf = $pdf-&gt;add_textflow($tf, &quot;A very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very long value&quot;, $value_optlist); $pdf-&gt;fit_textflow($tf, $x, $lowerY, $upperX, $y, ''); $pdf-&gt;delete_textflow($tf); $pdf-&gt;end_page_ext(''); $pdf-&gt;end_document(''); return $pdf-&gt;get_buffer(); </code></pre> <p>It is working, but as you can see, in optlist, I put <code>leftindent=0%</code> and <code>leftindent=22%</code></p> <p>The problem is that if a key would be longer, I will have to increase the &quot;leftindent&quot; manually, otherwise it will not align with other pairs. Furthermore, what if the keys would be dynamic so I don't know their length? I wouldn't know how much &quot;leftindent&quot;.</p> <p>Is there a cleaner and better way to print name value paris using PDFLib?</p>
[ { "answer_id": 74363739, "author": "Rainer", "author_id": 2862406, "author_profile": "https://Stackoverflow.com/users/2862406", "pm_score": 2, "selected": false, "text": "info_textline()" }, { "answer_id": 74375967, "author": "Rainer", "author_id": 2862406, "author_profile": "https://Stackoverflow.com/users/2862406", "pm_score": 1, "selected": true, "text": "leftindent" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20442826/" ]
74,362,777
<p>I am writing a Modelica code for an electrolyser cell and I want to build a Polarization curve as shown in the picture bellow</p> <p><a href="https://i.stack.imgur.com/jWWZw.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jWWZw.jpg" alt="Polariszation curve of electrolysis" /></a></p> <p>So the independent variable is the current density, but I don't know how to run the simulation for that variable instead of time. At the moment, I can simulate for a fixed current, which is not very usefull. I am writing all the code, so I am not using components in the Modelica library.</p> <p>I was thinking of making the current density as a range from, say 0 to 6 (as in the picture), but I am not sure it will work as simulation. Also, I am not sure how I could make that.</p> <p>Could someone help me with that? Thanks in advance. Kind regards. Vicente.</p>
[ { "answer_id": 74363739, "author": "Rainer", "author_id": 2862406, "author_profile": "https://Stackoverflow.com/users/2862406", "pm_score": 2, "selected": false, "text": "info_textline()" }, { "answer_id": 74375967, "author": "Rainer", "author_id": 2862406, "author_profile": "https://Stackoverflow.com/users/2862406", "pm_score": 1, "selected": true, "text": "leftindent" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20450832/" ]
74,362,778
<p>I thought I know the shell, but I got bitten with unexpected behavior.</p> <p>Consider this code:</p> <pre class="lang-bash prettyprint-override"><code>#!/bin/bash foo() { if false then echo success else return fi } foo || echo failure </code></pre> <p>Now at first glance one would think the <code>else return</code> part is superfluous, but it is not. The code as it is outputs <code>failure</code>, but when the cited part is removed, then <em>nothing</em> is output.</p> <p>The bash manual explains (for <code>if</code>):</p> <blockquote> <p>The exit status is the exit status of the last command executed, or zero if no condition tested true.</p> </blockquote> <p>Somehow I'd expect the <code>if</code> to fail when the command had failed. Imagine where <code>echo success</code> stands there are actually dependent commands that make only sense to execute when the main command (<code>false</code> here) succeeded.</p> <p>What is the logic behind that unexpected behavior?</p> <p>Seen for bash-4.4. Related: <a href="https://stackoverflow.com/a/63884458/6607497">https://stackoverflow.com/a/63884458/6607497</a></p>
[ { "answer_id": 74363003, "author": "chepner", "author_id": 1126841, "author_profile": "https://Stackoverflow.com/users/1126841", "pm_score": 2, "selected": false, "text": "if" }, { "answer_id": 74363342, "author": "KamilCuk", "author_id": 9072753, "author_profile": "https://Stackoverflow.com/users/9072753", "pm_score": 1, "selected": false, "text": "return" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6607497/" ]
74,362,810
<p>I am trying to create an excel formula if comma-separated values in the cell doesn't present in the allowed values list then I need to highlight it.</p> <p>Something like this</p> <p><a href="https://i.stack.imgur.com/9981Q.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9981Q.png" alt="enter image description here" /></a></p> <p>Is there any excel formula to achieve something like this.</p>
[ { "answer_id": 74363106, "author": "JvdV", "author_id": 9758194, "author_profile": "https://Stackoverflow.com/users/9758194", "pm_score": 3, "selected": true, "text": "=$B$3:$C$7" }, { "answer_id": 74363109, "author": "Ike", "author_id": 16578424, "author_profile": "https://Stackoverflow.com/users/16578424", "pm_score": 2, "selected": false, "text": "=BYROW(A2:A3,LAMBDA(d,\nSUM(--ISERROR(FIND(TEXTSPLIT(d,,\",\"),E2:E3)))=0\n))\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14118943/" ]
74,362,823
<p>I have three tables: <code>Customer</code>, <code>CustomerOrder</code>, and <code>OrderStatus</code>.</p> <p>My database is filled with the following info:</p> <p><strong>Customer</strong></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>name</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Bob</td> </tr> <tr> <td>2</td> <td>James</td> </tr> </tbody> </table> </div> <p><strong>CustomerOrder</strong></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>customer</th> <th>amount</th> <th>status</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>1</td> <td>100</td> <td>1</td> </tr> <tr> <td>2</td> <td>1</td> <td>83</td> <td>1</td> </tr> <tr> <td>3</td> <td>1</td> <td>432</td> <td>2</td> </tr> <tr> <td>4</td> <td>2</td> <td>58</td> <td>3</td> </tr> <tr> <td>5</td> <td>2</td> <td>33</td> <td>2</td> </tr> <tr> <td>6</td> <td>3</td> <td>10</td> <td>1</td> </tr> </tbody> </table> </div> <p><strong>OrderStatus</strong></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>description</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>pending</td> </tr> <tr> <td>2</td> <td>completed</td> </tr> <tr> <td>3</td> <td>cancelled</td> </tr> </tbody> </table> </div> <p>I need help writing a SQL query which shows the status of the latest order (highest order id), per customer. Running the query on the data would produce the following result:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>customer</th> <th>latest_order_status</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>2</td> </tr> <tr> <td>2</td> <td>2</td> </tr> <tr> <td>3</td> <td>1</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74363005, "author": "Netzer", "author_id": 5500118, "author_profile": "https://Stackoverflow.com/users/5500118", "pm_score": 2, "selected": true, "text": "max(CustomerOrder.Id)" }, { "answer_id": 74363359, "author": "tomasz", "author_id": 20450939, "author_profile": "https://Stackoverflow.com/users/20450939", "pm_score": 0, "selected": false, "text": "SELECT *, ROW_NUMBER() over ( partition by customer_id order by id desc) as row_no FROM\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20450598/" ]
74,362,837
<p>I've been trying to get a response from a REST API through Axios, I've tried setting the headers up, specifically the Access-Control-Allow-Origin header as stated in the error message, which seems to be the main problem, because even as I insert the required header, it still doesn't acknowledge the header.</p> <pre><code>axios .get(url, { headers: { &quot;Access-Control-Allow-Origin&quot;: &quot;*&quot;, crossDomain: true, &quot;Content-Type&quot;: &quot;text/plain;charset=utf-8&quot;, }, params: { access_key: API_KEY, adults: adults, origin: origin, destination: destination, departure: departure, }, }) .then((res) =&gt; { console.log(res.data); }); </code></pre>
[ { "answer_id": 74363005, "author": "Netzer", "author_id": 5500118, "author_profile": "https://Stackoverflow.com/users/5500118", "pm_score": 2, "selected": true, "text": "max(CustomerOrder.Id)" }, { "answer_id": 74363359, "author": "tomasz", "author_id": 20450939, "author_profile": "https://Stackoverflow.com/users/20450939", "pm_score": 0, "selected": false, "text": "SELECT *, ROW_NUMBER() over ( partition by customer_id order by id desc) as row_no FROM\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14096802/" ]
74,362,872
<p>How do you combine two objects like this?</p> <pre><code>const target = { year1 : {}, year2: {somevalue2...}}; const source = { year1 : {somevalue1...}, year2: {} }; </code></pre> <p>expected Input:</p> <pre><code>{ year1 : {somevalue1}, year2 : {somevalue2} } </code></pre> <p>Thank you!</p>
[ { "answer_id": 74362995, "author": "ncpa0cpl", "author_id": 8907391, "author_profile": "https://Stackoverflow.com/users/8907391", "pm_score": -1, "selected": false, "text": "target" }, { "answer_id": 74363044, "author": "dangarfield", "author_id": 3265253, "author_profile": "https://Stackoverflow.com/users/3265253", "pm_score": 3, "selected": true, "text": "const target = { year1 : {}, year2: {s:1}}\nconst source = { year1 : {s:2}, year2: {} }\nconst result = _.merge(target, source);\nconsole.log('result', result)\n// => { year1 : {s:2}, year2: {s:1}}" }, { "answer_id": 74363253, "author": "PeterKA", "author_id": 3558931, "author_profile": "https://Stackoverflow.com/users/3558931", "pm_score": 1, "selected": false, "text": "Array#reduce" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6749183/" ]
74,362,938
<p>Is there a way to toggle the class &quot;.first-active&quot; on the parent div &quot;.ProductItem-gallery-slides&quot; when the first &quot;.ProductItem-gallery-slides-item&quot; child has its active &quot;.selected&quot; class?</p> <p>Also, toggle the class &quot;.last-active&quot; on the parent div &quot;.ProductItem-gallery-slides&quot; when the last &quot;.ProductItem-gallery-slides-item&quot; child has its active &quot;.selected&quot; class.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const slides_items = $('.ProductItem-gallery-slides-item'); slides_items.on('click', function() { const slide_index = $(this).data('slide-index'); slides_items.removeClass('selected'); $(this).addClass('selected'); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.ProductItem-gallery, .ProductItem-gallery-scroll, .ProductItem-gallery-thumbnails, .ProductItem-gallery-thumbnails-item, .ProductItem-gallery-slides, .ProductItem-gallery-slides-item { border: 2px solid #000000; margin: 10px; padding: 10px; } .ProductItem-gallery { border-color: yellow; } .ProductItem-gallery-scroll { border-color: green; } .ProductItem-gallery-thumbnails { border-color: orange; } .ProductItem-gallery-slides { border-color: blue; } .selected { color: red; } .ProductItem-gallery-next { float: right; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; &lt;section class="ProductItem-gallery"&gt; &lt;div class="ProductItem-gallery-slides"&gt; &lt;div class="ProductItem-gallery-carousel-controls"&gt; &lt;button class="product-item-gallery-carousel-control ProductItem-gallery-prev" data-product-gallery="prev" aria-label="Previous"&gt;Previous&lt;/button&gt; &lt;button class="product-item-gallery-carousel-control ProductItem-gallery-next" data-product-gallery="next" aria-label="Next"&gt;Next&lt;/button&gt; &lt;/div&gt; &lt;div class="ProductItem-gallery-slides-item selected" data-slide-index="1"&gt; Item one &lt;/div&gt; &lt;div class="ProductItem-gallery-slides-item" data-slide-index="2"&gt; Item two &lt;/div&gt; &lt;div class="ProductItem-gallery-slides-item" data-slide-index="3"&gt; Item three &lt;/div&gt; &lt;div class="ProductItem-gallery-slides-item" data-slide-index="4"&gt; Item four &lt;/div&gt; &lt;div class="ProductItem-gallery-slides-item" data-slide-index="5"&gt; Item five &lt;/div&gt; &lt;div class="ProductItem-gallery-slides-item" data-slide-index="6"&gt; Item six &lt;/div&gt; &lt;div class="ProductItem-gallery-slides-item" data-slide-index="7"&gt; Item seven &lt;/div&gt; &lt;/div&gt; &lt;/section&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74362995, "author": "ncpa0cpl", "author_id": 8907391, "author_profile": "https://Stackoverflow.com/users/8907391", "pm_score": -1, "selected": false, "text": "target" }, { "answer_id": 74363044, "author": "dangarfield", "author_id": 3265253, "author_profile": "https://Stackoverflow.com/users/3265253", "pm_score": 3, "selected": true, "text": "const target = { year1 : {}, year2: {s:1}}\nconst source = { year1 : {s:2}, year2: {} }\nconst result = _.merge(target, source);\nconsole.log('result', result)\n// => { year1 : {s:2}, year2: {s:1}}" }, { "answer_id": 74363253, "author": "PeterKA", "author_id": 3558931, "author_profile": "https://Stackoverflow.com/users/3558931", "pm_score": 1, "selected": false, "text": "Array#reduce" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14926793/" ]
74,362,959
<p>I want to get the button printed out and whenever it is clicked to change the property searching game to the opposite (if its false - true) and print out the other button. Right now not even a button appears (if its in the jsx code after the return it prints the button but doesn't change it on click). Any ideas how can I write it down?</p> <pre><code>let searchingGame = false; const isSearchingForGame = () =&gt; { searchingGame = !searchingGame; if (isSearchingForGame == true) { return (&lt;button onClick={isSearchingForGame} className=&quot;find-match&quot;&gt;Find Match&lt;/button&gt;) } else { return (&lt;button onClick={isSearchingForGame} className=&quot;find-match&quot;&gt;Searching for a Match&lt;/button&gt;) } } return ( &lt;div className=&quot;look-ranked-container&quot;&gt; &lt;div className=&quot;time-searching&quot;&gt;Searching: 00:23 min&lt;/div&gt; {isSearchingForGame} &lt;/div&gt; ) } </code></pre>
[ { "answer_id": 74363217, "author": "0stone0", "author_id": 5625547, "author_profile": "https://Stackoverflow.com/users/5625547", "pm_score": 2, "selected": true, "text": "{isSearchingForGame()}" }, { "answer_id": 74363248, "author": "Beatriz Infante", "author_id": 7773975, "author_profile": "https://Stackoverflow.com/users/7773975", "pm_score": 0, "selected": false, "text": "return (\n <div className=\"look-ranked-container\">\n <div className=\"time-searching\">Searching: 00:23 min</div>\n <button onClick={isSearchingForGame} className=\"find-match\">. \n { searchingGame ? 'Find Match' : 'Searching for a Match' }</button>\n </div>\n)\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20045530/" ]
74,362,961
<p><strong>Use case :</strong></p> <p>This is a Cypress E2E test coded with JS and I'm trying to apply a regex filter to this array (more than 100 values) to be able to ignore everything before <code>/flux/sitemaps/</code> and catches only the .xml file names. my aim is to be able to compare pre-production and production sitemap URL contents.</p> <p>One example of what I would like to achieve :</p> <p><strong>Before regex :</strong></p> <pre class="lang-js prettyprint-override"><code>[ &quot;https://xxxxxxxxx.com/flux/sitemaps/sitemap_cms_1.xml&quot;, &quot;https://xxxxxx.com/flux/sitemaps/sitemap_category_1.xml&quot; ] </code></pre> <p><strong>After regex (test goal) :</strong></p> <pre class="lang-js prettyprint-override"><code>[&quot;/flux/sitemaps/sitemap_cms_1.xml&quot;, &quot;/flux/sitemaps/sitemap_category_1.xml&quot;] </code></pre> <p><strong>Or</strong></p> <pre class="lang-js prettyprint-override"><code>[&quot;sitemap_cms_1.xml&quot;,&quot;sitemap_category_1.xml&quot;] </code></pre> <p>I've tried different regex rules but no success so far, any help is greatly appreciated.</p>
[ { "answer_id": 74363217, "author": "0stone0", "author_id": 5625547, "author_profile": "https://Stackoverflow.com/users/5625547", "pm_score": 2, "selected": true, "text": "{isSearchingForGame()}" }, { "answer_id": 74363248, "author": "Beatriz Infante", "author_id": 7773975, "author_profile": "https://Stackoverflow.com/users/7773975", "pm_score": 0, "selected": false, "text": "return (\n <div className=\"look-ranked-container\">\n <div className=\"time-searching\">Searching: 00:23 min</div>\n <button onClick={isSearchingForGame} className=\"find-match\">. \n { searchingGame ? 'Find Match' : 'Searching for a Match' }</button>\n </div>\n)\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3095223/" ]
74,362,983
<p>we know the standard <code>Exception Handling</code> in python:</p> <pre><code>def fun(): a = 1 x = 5 ...... ...... try: print(x) except: print(&quot;An exception occurred %d&quot;, a) ...... ...... return x+a </code></pre> <p>I want to achieve that</p> <ol> <li>if <code>try</code> fails, we will retry again immediately; if <code>try</code> fails second time, we will go to <code>except</code>.</li> <li>if <code>try</code> fails, we will retry after 1 min; if <code>try</code> fails second time, we will go to <code>except</code>.</li> </ol> <p>Could you offer me some reference of retry function in python?</p>
[ { "answer_id": 74363029, "author": "George Rey", "author_id": 1701405, "author_profile": "https://Stackoverflow.com/users/1701405", "pm_score": 2, "selected": false, "text": "retry" }, { "answer_id": 74363053, "author": "Dee almond man", "author_id": 17721141, "author_profile": "https://Stackoverflow.com/users/17721141", "pm_score": 0, "selected": false, "text": "while true:\n try:\n print(x)\n break\n except:\n pass\n" }, { "answer_id": 74363184, "author": "BokiX", "author_id": 16843389, "author_profile": "https://Stackoverflow.com/users/16843389", "pm_score": 0, "selected": false, "text": "def fun(repeated=False):\n a = 1\n x = 5\n try:\n print(x)\n return x+a\n except:\n if times_repeated:\n print(\"An exception occurred\")\n else:\n print(\"Trying again\")\n fun(repeated=True)\n\nfun()\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6703592/" ]
74,362,996
<p>I have a &quot;main&quot; powershell script that executes multiple scripts that install apps on a VM. I'm trying to implement the error control on the main script, meaning:</p> <p><strong>If one of the scripts that installs the apps fails, the rest of the scripts aren't executed.</strong></p> <p>Here is my main script:</p> <pre><code>try{ powershell.exe -ExecutionPolicy Unrestricted -File 'C:\\TEST\\Scripts\\App1.ps1' powershell.exe -ExecutionPolicy Unrestricted -File 'C:\\TEST\\Scripts\\App2.ps1' powershell.exe -ExecutionPolicy Unrestricted -File 'C:\\TEST\\Scripts\\App3.ps1' }catch { Write-Host &quot;Error&quot; } </code></pre> <p>Here is an example of one of the scripts (App2.ps1) that installs the apps (all the scripts follow the same logic as this one)</p> <pre><code>#Set logging $logFile = &quot;C:\TEST\Logs\&quot; + (get-date -format 'yyyyMMdd') + '_softwareinstall.log' function Write-Log { Param($message) Write-Output &quot;$(get-date -format 'yyyyMMdd HH:mm:ss') $message&quot; | Out-File -Encoding utf8 $logFile -Append } #Install APP2 $file = Test-Path &quot;C:\TEST\Apps\APP2\APP2 x64 7.2.1.msi&quot; if($file) { try{ Write-Log &quot;Installing App2&quot; Start-Process msiexec.exe -Wait -ArgumentList '/i &quot;C:\TEST\Apps\APP2\App2 x64 7.2.1.msi&quot; ALLUSERS=1 AddLocal=MiniDriver,PKCS,UserConsole,Troubleshooting,Help /qn /norestart' if(Test-Path -Path &quot;C:\Program Files\HID Global\APP2\ac.app2.exe&quot;) { Write-Log &quot;App2 installed&quot; } else { Write-Log &quot;There was a problem while installing App2&quot; throw &quot;There was a problem while installing App2&quot; } }catch { Write-Log &quot;[ERROR] There was a problem while starting the installation for App2&quot; throw &quot;[ERROR] There was a problem while starting the installation for App2&quot; } } else { Write-Log &quot;Installation file for App2 not found&quot; throw &quot;Installation file for App2 not found&quot; } </code></pre> <p>Here is the output: <a href="https://i.stack.imgur.com/J2gIq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/J2gIq.png" alt="enter image description here" /></a></p> <p><strong>(I blured the names of the apps for confidential purposes)</strong></p> <p>Why did the main script continue to execute when the script to install the APP2 through an exception? Shouldn't have stopped and shown the message written on the catch section in the main script?</p> <p>Thank you in advance</p>
[ { "answer_id": 74363190, "author": "Sam", "author_id": 15266912, "author_profile": "https://Stackoverflow.com/users/15266912", "pm_score": 1, "selected": false, "text": "$ErrorActionPreference = 'Stop'" }, { "answer_id": 74382502, "author": "mklement0", "author_id": 45375, "author_profile": "https://Stackoverflow.com/users/45375", "pm_score": 0, "selected": false, "text": ".ps1" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74362996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15266912/" ]
74,363,016
<p>I need to convert a yyyy/dd varchar type data( ex: 2021/03) to a monthly sort of date. (Ex: 2021/01, 2021/02, 2021/03). So, i need to convert the quarterly format to a monthly format in snowflake. Can we do this?</p> <p>I tried many things but didn't get the expected results</p>
[ { "answer_id": 74363190, "author": "Sam", "author_id": 15266912, "author_profile": "https://Stackoverflow.com/users/15266912", "pm_score": 1, "selected": false, "text": "$ErrorActionPreference = 'Stop'" }, { "answer_id": 74382502, "author": "mklement0", "author_id": 45375, "author_profile": "https://Stackoverflow.com/users/45375", "pm_score": 0, "selected": false, "text": ".ps1" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74363016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20451054/" ]
74,363,040
<p><strong>Update 01/12/2022</strong></p> <p>With triplee's helpful suggestions, I resolved it to take both files &amp; directories by adding a comma in between f and d, the final code now looks like this:</p> <pre><code>while read -r old new; do echo &quot;replacing ${old} by ${new}&quot; &gt;&amp;2 find '/path/to/dir' -depth -type d,f -name &quot;$old&quot; -exec rename &quot;s/${old}/${new}/&quot; {} ';' done &lt;input.txt </code></pre> <p>Thank you!</p> <hr /> <p><strong>Original request:</strong></p> <p>I am trying to rename a list of files (from <code>$old</code> to <code>$new</code>), all present in <code>$homedir</code> or in subdirectories in <code>$homedir</code>.</p> <p>In the command line this line works to rename files in the subfolders: <code>find ${homedir}/ -name ${old} -exec rename &quot;s/${old}/${new}/&quot; */${old} ';'</code></p> <p>However, when I want to implement this line in a simple bash script getting the <code>$old</code> and <code>$new</code> filenames from <code>input.txt</code>, it doesn't work anymore...</p> <p><code>input.txt</code> looks like this:</p> <pre><code>name_old name_new name_old2 name_new2 etc... </code></pre> <p>the script looks like this:</p> <pre><code>#!/bin/bash homedir='/path/to/dir' cat input.txt | while read old new; do echo 'replacing' ${old} 'by' ${new} find ${homedir}/ -name ${old} -exec rename &quot;s/${old}/${new}/&quot; */${old} ';' done </code></pre> <p>After running the script, the text line from echo with <code>$old</code> and <code>$new</code> filenames being replaced is printed for the entire loop, but no files are renamed. No error is printed either. What am I missing? Your help would be greatly appreaciated!</p> <p>I checked whether the <code>$old</code> and <code>$new</code> variables were correctly passed to the <code>find -exec rename</code> command, but because they are printed by <code>echo</code> that doesn't seem to be the issue.</p>
[ { "answer_id": 74363190, "author": "Sam", "author_id": 15266912, "author_profile": "https://Stackoverflow.com/users/15266912", "pm_score": 1, "selected": false, "text": "$ErrorActionPreference = 'Stop'" }, { "answer_id": 74382502, "author": "mklement0", "author_id": 45375, "author_profile": "https://Stackoverflow.com/users/45375", "pm_score": 0, "selected": false, "text": ".ps1" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74363040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20450802/" ]
74,363,057
<p>I have a dataset that includes a binary variable (0 vs 1) across time. I want to plot the occurrence of 1 across time. The idea is to see during which period the 1 occurs more often. Here is an example dataset:</p> <pre><code>set.seed(123) dd &lt;- data.frame(id = c(rep(1,100), rep(2,80), rep(3,90)), time = c(seq(from=1,to=100), seq(from=1,to=80), seq(from=1,to=90)), outcome = c(sample(c(0, 1), 100, replace = TRUE), sample(c(0, 1), 80, replace = TRUE), sample(c(0, 1), 90, replace = TRUE))) </code></pre> <p>I am thinking maybe a <a href="https://r-graph-gallery.com/283-the-hourly-heatmap.html" rel="nofollow noreferrer">heatmap</a> like this will give the best presentation <a href="https://i.stack.imgur.com/Ry2D5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ry2D5.png" alt="enter image description here" /></a></p> <p>My heatmap will have my <code>time</code> variable instead of <code>Day</code> for the x axis and the heat scale will reflect the frequency of 1. For my example dataset, because 1 occurs most often in the second period of time it will be highlighted as the most heated place in the plot.</p>
[ { "answer_id": 74363190, "author": "Sam", "author_id": 15266912, "author_profile": "https://Stackoverflow.com/users/15266912", "pm_score": 1, "selected": false, "text": "$ErrorActionPreference = 'Stop'" }, { "answer_id": 74382502, "author": "mklement0", "author_id": 45375, "author_profile": "https://Stackoverflow.com/users/45375", "pm_score": 0, "selected": false, "text": ".ps1" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74363057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7989204/" ]
74,363,061
<p>I am working on pagination which works with the following logic:</p> <pre><code> if (currentPage &gt; 5 &amp;&amp; currentPage &lt; 11) pages = [6, 7, 8, 9, 10]; if (currentPage &gt; 10 &amp;&amp; currentPage &lt; 16) pages = [11, 12, 13, 14, 15]; if (currentPage &gt; 15 &amp;&amp; currentPage &lt; 21) pages = [16, 17, 18, 19, 20]; if (currentPage &gt; 20 &amp;&amp; currentPage &lt; 26) pages = [21, 22, 23, 24, 25]; </code></pre> <p>However, rather than hardcoding these values, I'd like to write a dynamic version of this, as much as is possible. If you notice, there are always five clickable page numbers on each page, represented by the values in the pages array. But I'm unclear on how to accomplish this.</p>
[ { "answer_id": 74363255, "author": "romellem", "author_id": 864233, "author_profile": "https://Stackoverflow.com/users/864233", "pm_score": 3, "selected": true, "text": "currentPage" }, { "answer_id": 74363288, "author": "Dave Pritlove", "author_id": 2005666, "author_profile": "https://Stackoverflow.com/users/2005666", "pm_score": 0, "selected": false, "text": "currentPage = 5;\npages = [];\n\npages = setPages(currentPage);\n\nfunction setPages(num) {\nbegin = (currentPage%5)*5+6;\npages.length=0;\nfor (let i=0; i<5; i++) {\n pages.push(begin++);\n}\nreturn pages;\n}\n\nconsole.log(pages);\ncurrentPage = 11;\npages = setPages(currentPage);\nconsole.log(pages)" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74363061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2584924/" ]
74,363,077
<p>I have a database in which records look like this:</p> <pre><code>{ id: someId initialValue: 100 currentValue: 150 creationDate: someDate } </code></pre> <p>And I have to get values that are the biggest in terms of difference between <code>currentValue</code> and <code>initialValue</code>. Is it possible in MongoDB to write a sorting function that will substract one value from another and then compare (sort) them?</p>
[ { "answer_id": 74363199, "author": "user20042973", "author_id": 20042973, "author_profile": "https://Stackoverflow.com/users/20042973", "pm_score": 2, "selected": true, "text": "$addFields" }, { "answer_id": 74363265, "author": "ray", "author_id": 14732669, "author_profile": "https://Stackoverflow.com/users/14732669", "pm_score": 2, "selected": false, "text": "$setWindowFields" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74363077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13534726/" ]
74,363,079
<p>So my legend here is village which has (Chirodzo, God, Ruaca). How to remove the legend and display it inside the bars; for instance inside the bar for chirodzo, I want chirodzo written inside?</p> <pre><code>ggplot(data = interviews_plotting, aes(x = respondent_wall_type, fill = village)) + geom_bar(position = &quot;fill&quot;) </code></pre> <p>Source is here <a href="https://mq-software-carpentry.github.io/r-ggplot-extension/02-categorical-data/index.html" rel="nofollow noreferrer">https://mq-software-carpentry.github.io/r-ggplot-extension/02-categorical-data/index.html</a></p> <pre><code>ggplot(data = interviews_plotting, aes(x = respondent_wall_type, fill = village)) + geom_bar(position = &quot;fill&quot;) </code></pre>
[ { "answer_id": 74363199, "author": "user20042973", "author_id": 20042973, "author_profile": "https://Stackoverflow.com/users/20042973", "pm_score": 2, "selected": true, "text": "$addFields" }, { "answer_id": 74363265, "author": "ray", "author_id": 14732669, "author_profile": "https://Stackoverflow.com/users/14732669", "pm_score": 2, "selected": false, "text": "$setWindowFields" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74363079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20398455/" ]
74,363,085
<p>I want to update the below table where name is null to repeat the pattern from first 10 rows. <a href="https://i.stack.imgur.com/m54X7.png" rel="nofollow noreferrer">enter image description here</a></p> <p>sql:</p> <p>declare @name varchar(255) set @name = select distinct name from #temp update #temp set name = @name where name is not null</p> <hr /> <p>Obviously the above the query will not work due to multiple values. I want to update the table where it's null to fill with the pattern from above.</p>
[ { "answer_id": 74363199, "author": "user20042973", "author_id": 20042973, "author_profile": "https://Stackoverflow.com/users/20042973", "pm_score": 2, "selected": true, "text": "$addFields" }, { "answer_id": 74363265, "author": "ray", "author_id": 14732669, "author_profile": "https://Stackoverflow.com/users/14732669", "pm_score": 2, "selected": false, "text": "$setWindowFields" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74363085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13190639/" ]
74,363,097
<p>We're supposed to do this exercise for webdev class and I can't figure out how to solve it.</p> <p>We have to create a 'person' object and fill it with random information using a method called <code>randomPerson()</code>. That part works fine so far.</p> <pre><code>let person = { fname: &quot;&quot;, lname: &quot;&quot;, city: &quot;&quot;, street: &quot;&quot;, hobbies: new Array(), } </code></pre> <p>After this, we're supposed to create another function that creates 10 of these random person objects and stores them in an array.</p> <p>This is what I have so far:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>let person = { fname: "", lname: "", city: "", street: "", hobbies: new Array(), }; personsArr = new Array(); function persons10() { for (let i = 0; i &lt; 10; i++) { // randomPerson() // makes it crash personsArr.fill(person) } } persons10() console.log(personsArr)</code></pre> </div> </div> </p> <p>When I try to run that, the page gets stuck loading and freezes.</p>
[ { "answer_id": 74363197, "author": "ncpa0cpl", "author_id": 8907391, "author_profile": "https://Stackoverflow.com/users/8907391", "pm_score": 0, "selected": false, "text": "personsArr" }, { "answer_id": 74363268, "author": "depperm", "author_id": 3462319, "author_profile": "https://Stackoverflow.com/users/3462319", "pm_score": 1, "selected": false, "text": "randomPerson()" }, { "answer_id": 74363284, "author": "Raffael", "author_id": 10653015, "author_profile": "https://Stackoverflow.com/users/10653015", "pm_score": 2, "selected": false, "text": "// since you didnt share the randomPerson() function, I created a dummy function\nfunction randomPerson() {\n let person = {\n fname: \"\",\n lname: \"\",\n city: \"\",\n street: \"\",\n hobbies: new Array(),\n }\n\n\n return person;\n}\n\n\nlet personsArr = new Array();\n\nfunction persons10() {\n for(let i = 0; i < 10; i++) {\n personsArr.push(randomPerson());\n }\n \n console.log(personsArr);\n \n}\n\npersons10();" }, { "answer_id": 74363521, "author": "Ben Aston", "author_id": 38522, "author_profile": "https://Stackoverflow.com/users/38522", "pm_score": 0, "selected": false, "text": "Array#map" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74363097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19283908/" ]
74,363,107
<p>Is it possible to round the numbers in a data frame to the nearest integer 10?</p> <pre><code>df &lt;- data.frame(a = c(17,1,15,5,1,1,11,0,24,0), b = c(0,10,19,1,1,32,0,5,7,8), c = c(1,1,12,18,7,3,12,1,1,20)) round_df &lt;- function(x, digits) { numeric_columns &lt;- sapply(x, mode) == 'numeric' x[numeric_columns] &lt;- round_any(x[numeric_columns], digits) x } df_10 &lt;- round_df(df, 10) </code></pre> <p>I tried this way but it doesn't work for data.frame</p>
[ { "answer_id": 74363163, "author": "Maël", "author_id": 13460602, "author_profile": "https://Stackoverflow.com/users/13460602", "pm_score": 2, "selected": false, "text": "round" }, { "answer_id": 74364081, "author": "AndrewGB", "author_id": 15293191, "author_profile": "https://Stackoverflow.com/users/15293191", "pm_score": 1, "selected": false, "text": "DescTools::RoundTo" }, { "answer_id": 74364522, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 1, "selected": false, "text": "df[] <- lapply(df, plyr::round_any, accuracy = 10)\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74363107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20176942/" ]
74,363,122
<p>Can we say that Django models are considered dataclasses? I don't see @dataclass annotation on them or on their base class model.Models. However, we do treat them like dataclasses because they don't have constructors and we can create new objects by naming their arguments, for example MyDjangoModel(arg1= ..., arg2=...). On the other hand, Django models also don't have <strong>init</strong> methods (constructors) or inherit from NamedTuple class.</p> <p>What happens under the hood that I create new Django model objects?</p>
[ { "answer_id": 74363163, "author": "Maël", "author_id": 13460602, "author_profile": "https://Stackoverflow.com/users/13460602", "pm_score": 2, "selected": false, "text": "round" }, { "answer_id": 74364081, "author": "AndrewGB", "author_id": 15293191, "author_profile": "https://Stackoverflow.com/users/15293191", "pm_score": 1, "selected": false, "text": "DescTools::RoundTo" }, { "answer_id": 74364522, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 1, "selected": false, "text": "df[] <- lapply(df, plyr::round_any, accuracy = 10)\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74363122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5402618/" ]
74,363,133
<p>I have two tables containing data on names with a pass/fail variable. I am trying to count how many people originally failed but then passed later on.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Name</th> <th>Passed</th> </tr> </thead> <tbody> <tr> <td>Mike</td> <td>Passed</td> </tr> <tr> <td>John</td> <td>Failed</td> </tr> <tr> <td>Billy</td> <td>Failed</td> </tr> </tbody> </table> </div><div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Name</th> <th>Passed</th> </tr> </thead> <tbody> <tr> <td>Mike</td> <td>Passed</td> </tr> <tr> <td>John</td> <td>Passed</td> </tr> <tr> <td>Billy</td> <td>Failed</td> </tr> </tbody> </table> </div> <p>I originally did this by creating a third table with an IF array that put out the names of the people who failed. I then counted the amount of &quot;TRUE&quot;s.</p> <p>For Name:</p> <pre><code>=IFERROR(IFS(Table13[Passed]=&quot;FAILED&quot;, Table13[Name]), &quot;&quot;) </code></pre> <p>For Passed Later:</p> <pre><code>=IF(XLOOKUP(VALUETOTEXT(A2),Table1[Name],Table1[Passed])=&quot;Passed&quot;,TRUE,FALSE) </code></pre> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Name</th> <th>Passed Originally</th> <th>Passed Later</th> </tr> </thead> <tbody> <tr> <td>#N/A</td> <td>#N/A</td> <td>#N/A</td> </tr> <tr> <td>John</td> <td>Failed</td> <td>TRUE</td> </tr> <tr> <td>Billy</td> <td>Failed</td> <td>FALSE</td> </tr> </tbody> </table> </div> <p>And finally got the count by</p> <pre><code>=COUNTIF(Table3[Passed Later], &quot;=TRUE&quot;) </code></pre> <p>I was able to skip the name column and got the Passed Later column directly by combining the first two formulas into</p> <pre><code>=IF(XLOOKUP(IFS(Table13[Passed]=&quot;Failed&quot;, Table13[Name]),Table1[Name],Table1[Passed])=&quot;Passed&quot;,TRUE,FALSE) </code></pre> <p>Now I am stuck at combining the COUNTIF Function. I do not know how I can implement this all into one function, if that is possible. Any advise? I think my main problem is the output of the Passed Later column is not numbers, but strings.</p>
[ { "answer_id": 74363180, "author": "Micah Ayers", "author_id": 12021976, "author_profile": "https://Stackoverflow.com/users/12021976", "pm_score": 1, "selected": false, "text": "=COUNT(IF(XLOOKUP(IFS(Table13[Passed]<>1, Table13[Name]),Table1[Name],Table1[Passed])=1,1,\"\"))\n" }, { "answer_id": 74363231, "author": "JvdV", "author_id": 9758194, "author_profile": "https://Stackoverflow.com/users/9758194", "pm_score": 2, "selected": false, "text": "G1" }, { "answer_id": 74363237, "author": "Scott Craner", "author_id": 4851590, "author_profile": "https://Stackoverflow.com/users/4851590", "pm_score": 3, "selected": true, "text": "=LET(\n fst,FILTER(Table13[Name],Table13[Passed]=\"Failed\"),\n scd,FILTER(Table1[Name],Table1[Passed]= \"Passed\"), \n SUM(--ISNUMBER(MATCH(fst,scd,0))))\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74363133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12021976/" ]
74,363,137
<p>I've a time series (typically energy usage) recorded over a range of days. Since usage tends to be different over the weekend I want to highlight the weekends.</p> <p>I've done what seems sensible:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt import datetime import random #Create dummy data. start=datetime.datetime(2022,10,22,0,0) finish=datetime.datetime(2022,11,7,0,0) def randomWalk(): i=0 while True: i=i+random.random()-0.5 yield i s = pd.Series({i: next(randomWalk()) for i in pd.date_range(start, finish,freq='h')}) # Plot it. plt.figure(figsize=[12, 8]); s.plot(); # Color the labels according to the day of week. for label, day in zip(plt.gca().xaxis.get_ticklabels(which='minor'), pd.date_range(start,finish,freq='d')): label.set_color('red' if day.weekday() &gt; 4 else 'black') </code></pre> <p>But what I get is wrong. Two weekends appear one off, and the third doesn't show at all.</p> <p><a href="https://i.stack.imgur.com/znK6W.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/znK6W.png" alt="The X axis" /></a></p> <p>I've explored the 'label' objects, but their X coordinate is just an integer, and doesn't seem meaningful. Using DateFormatter just gives nonsense.</p> <p>How would be best to fix this, please?</p>
[ { "answer_id": 74363180, "author": "Micah Ayers", "author_id": 12021976, "author_profile": "https://Stackoverflow.com/users/12021976", "pm_score": 1, "selected": false, "text": "=COUNT(IF(XLOOKUP(IFS(Table13[Passed]<>1, Table13[Name]),Table1[Name],Table1[Passed])=1,1,\"\"))\n" }, { "answer_id": 74363231, "author": "JvdV", "author_id": 9758194, "author_profile": "https://Stackoverflow.com/users/9758194", "pm_score": 2, "selected": false, "text": "G1" }, { "answer_id": 74363237, "author": "Scott Craner", "author_id": 4851590, "author_profile": "https://Stackoverflow.com/users/4851590", "pm_score": 3, "selected": true, "text": "=LET(\n fst,FILTER(Table13[Name],Table13[Passed]=\"Failed\"),\n scd,FILTER(Table1[Name],Table1[Passed]= \"Passed\"), \n SUM(--ISNUMBER(MATCH(fst,scd,0))))\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74363137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2806617/" ]
74,363,164
<p>I have data in an array like so:</p> <pre><code>array([[ 5, 5, 5, 6, 9, 6, 6], [10, 4, 10, 3, 5, 3, 3], [10, 3, 10, 4, 5, 3, 4], [ 9, 6, 8, 8, 10, 6, 9], [10, 10, 10, 7, 10, 4, 4], [10, 6, 10, 5, 9, 7, 5], [ 9, 7, 10, 7, 10, 8, 10], [ 8, 5, 10, 7, 10, 7, 10], [ 7, 10, 10, 9, 10, 7, 8]]) </code></pre> <p>I want to sort it by the amount of non-10 values, and I also want to sort it in ascending order for rows, and in descending order of number of 10s:</p> <pre><code>arr = np.sort(arr, axis=1) arr = arr[(arr==10).sum(axis=1).argsort()][::-1] </code></pre> <p>Output:</p> <pre><code>array([[ 4, 4, 7, 10, 10, 10, 10], [ 7, 7, 8, 9, 10, 10, 10], [ 5, 7, 7, 8, 10, 10, 10], [ 7, 7, 8, 9, 10, 10, 10], [ 5, 5, 6, 7, 9, 10, 10], [ 3, 3, 4, 4, 5, 10, 10], [ 3, 3, 3, 4, 5, 10, 10], [ 6, 6, 8, 8, 9, 9, 10], [ 5, 5, 5, 6, 6, 6, 9]]) </code></pre> <p>I want to implement a tie breaker system so that if the amount of 10s the same, it now orders by amount of 9s, then 8s, and so on. Expected output:</p> <pre><code>array([[ 4, 4, 7, 10, 10, 10, 10], [ 7, 7, 8, 9, 10, 10, 10], [ 7, 7, 8, 9, 10, 10, 10], [ 5, 7, 7, 8, 10, 10, 10], [ 5, 5, 6, 7, 9, 10, 10], [ 3, 3, 4, 4, 5, 10, 10], [ 3, 3, 3, 4, 5, 10, 10], [ 6, 6, 8, 8, 9, 9, 10], [ 5, 5, 5, 6, 6, 6, 9]]) </code></pre>
[ { "answer_id": 74363601, "author": "Nick ODell", "author_id": 530160, "author_profile": "https://Stackoverflow.com/users/530160", "pm_score": 0, "selected": false, "text": "arr = np.sort(arr, axis=1)\narr = arr[(arr==8).sum(axis=1).argsort(kind='stable')]\narr = arr[(arr==9).sum(axis=1).argsort(kind='stable')]\narr = arr[(arr==10).sum(axis=1).argsort(kind='stable')]\narr = arr[::-1]\n" }, { "answer_id": 74364390, "author": "ILS", "author_id": 10017662, "author_profile": "https://Stackoverflow.com/users/10017662", "pm_score": 3, "selected": true, "text": "numpy.frompyfunc" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74363164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13800787/" ]
74,363,167
<p>I would like to know how to leave a loop from the terminal, otherwise when closing it...<a href="https://i.stack.imgur.com/6BhF4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6BhF4.png" alt="enter image description here" /></a></p> <p>Thanks!</p> <p>I tried 'exit', 'leave' and others keywords like that</p>
[ { "answer_id": 74363601, "author": "Nick ODell", "author_id": 530160, "author_profile": "https://Stackoverflow.com/users/530160", "pm_score": 0, "selected": false, "text": "arr = np.sort(arr, axis=1)\narr = arr[(arr==8).sum(axis=1).argsort(kind='stable')]\narr = arr[(arr==9).sum(axis=1).argsort(kind='stable')]\narr = arr[(arr==10).sum(axis=1).argsort(kind='stable')]\narr = arr[::-1]\n" }, { "answer_id": 74364390, "author": "ILS", "author_id": 10017662, "author_profile": "https://Stackoverflow.com/users/10017662", "pm_score": 3, "selected": true, "text": "numpy.frompyfunc" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74363167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17518439/" ]
74,363,200
<p>I need to load a file .xlsx who have multiple worksheet.</p> <p>It look like this :</p> <p>First Worksheet : Zoo</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Name</th> <th>Location</th> </tr> </thead> <tbody> <tr> <td>Zoo</td> <td>Paris</td> </tr> <tr> <td>END</td> <td></td> </tr> </tbody> </table> </div> <p>Second Worksheet : Animals</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Name</th> <th>Species</th> <th>Family</th> <th>Sex</th> <th>Date Of Birth</th> </tr> </thead> <tbody> <tr> <td>Zoe</td> <td>Elephant</td> <td>Elephantidae</td> <td>F</td> <td>03/19/2004</td> </tr> <tr> <td>Victor</td> <td>Deer</td> <td>Cervidae</td> <td>M</td> <td></td> </tr> <tr> <td>Camille</td> <td>Eagle</td> <td>Accipitridae</td> <td>F</td> <td>09/03/2108</td> </tr> <tr> <td>END</td> <td></td> <td></td> <td></td> <td></td> </tr> </tbody> </table> </div> <p>Afterwards I have worksheet for each Animal :</p> <p>Zoe</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Name</th> <th>Unit</th> <th>Value</th> </tr> </thead> <tbody> <tr> <td>Height</td> <td>cm</td> <td>280</td> </tr> <tr> <td>Weight</td> <td>kg</td> <td>4 000</td> </tr> <tr> <td>END</td> <td></td> <td></td> </tr> </tbody> </table> </div> <p>Victor</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Name</th> <th>Unit</th> <th>Value</th> </tr> </thead> <tbody> <tr> <td>Height</td> <td>cm</td> <td>150</td> </tr> <tr> <td>Weight</td> <td>kg</td> <td>75</td> </tr> <tr> <td>END</td> <td></td> <td></td> </tr> </tbody> </table> </div> <p>ETC</p> <p>I have a function Load() who call all the function to load the information I need.</p> <pre><code>public bool Load(string fileName) { bool returnValue = false; if (File.Exists(fileName)) { SpreadsheetDocument spreadsheetDocument = spreadsheetDocument.Open(fileName, false); if (LoadZoo(spreadsheetDocument)) { returnValue = true; } if (LoadAnimals(spreadsheetDocument)) { returnValue = true; } spreadsheetDocument.Close(); } return returnValue; } </code></pre> <p>In LoadAnimals I retrieve Information from the second worksheet and I call my function to retrieve information from all Animal Worksheet :</p> <pre><code>public Dictionary&lt;string, IXlsxAnimals&gt; Animals { get; private set; } = new Dictionary&lt;string, IXlsxAnimals&gt;(); private bool LoadAnimals(SpreadsheetDocument spreadsheetDocuement) { bool returnValue = false; WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart; WorksheetPart worksheetPart = ExcelHelper.GetWorksheetFromSheetname(workbookPart, &quot;Animals&quot;); if (worksheetPart != null) { SheetData sheetData = worksheetPart.Worksheet.GetFirstChild&lt;SheetData&gt;(); Sheet sheet = workbookPart.workbook.Descendants&lt;Sheet&gt;().FirstOrDefault(s =&gt; s.Name == &quot;Animals&quot;); if (sheet.Name == &quot;Animals&quot;) { Cell cell = worksheetPart.Descendants&lt;Cell&gt;().FirstOrDefault(); string endingCell = &quot;&quot;; while (endingCell != &quot;END&quot;) { foreach (Row row in sheetData.Descendants&lt;Row&gt;()) { endingCell = ExcelHelper.GetCellValue(worbookPart, sheetData, $&quot;A{row.RowIndex}&quot;); if (endingCell == null) { break; } XlsxAnimals xlsxAnimals = new XlsxAnimals() { Name = ExcelHelper.GetCellValue(workbookPart, sheetData, $&quot;A{row.RowIndex}&quot;), Species = ExcelHelper.GetCellValue(workbookPart, sheetData, $&quot;B{row.RowIndex}&quot;), Family = ExcelHelper.GetCellValue(workbookPart, sheetData, $&quot;C{row.RowIndex}&quot;), Sex = ExcelHelper.GetCellValue(workbookPart, sheetData, $&quot;D{row.RowIndex}&quot;), DateOfBirth = ExcelHelper.GetCellValue(workbookPart, sheetData, $&quot;E{row.RowIndex}&quot;), Animal = new Dictionary&lt;string, IXlsxAnimal&gt;(); }; if (!Animals.ContainsKey(xlsxAnimals.Name)) { if(xlsxAnimals.Name != &quot;Name&quot;) { Animals.Add(xlsxAnimals.Name, xlsxAnimals); LoadAnimal(spreadsheetDocument, xlsxAnimals.Animal, xlsxAnimals); } } returnValue = true; } } } } return returnValue; } </code></pre> <p>And LoadAnimal look like this :</p> <pre><code>private bool LoadAnimal (SpreadsheetDocument spreadsheetDocument, Dictionary&lt;string, IXlsxAnimal&gt; Animal, XlsxAnimals xlsxAnimals) { bool returnValue = false; WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart; WorksheetPart worksheetPart = ExcelHelper.GetworksheetFromSheetName(workbookPart, xlsxAnimals.Name); if (worksheetPart != null) { SheetData sheetData = worksheetPart.Worksheet.GetFirstChild&lt;SheetData&gt;(); Sheet sheet = workbookPart.Workbook.Descendants&lt;Sheet&gt;().FirstOrdefault(s =&gt; s.Name == xlsxAnimals.Name); if (sheet.Name == xlsxAnimals.Name) { Cell cell = worksheetPart.Wroksheet.Descendants&lt;Cell&gt;().FirstOrDefault(); string endingCell = &quot;&quot;; while (endingCell != &quot;End&quot;) { foreach (Row row in sheetData.Descendants&lt;Row&gt;()) { endingCell = ExcelHelper.GetCellValue(workbookPart, sheetData, $&quot;A{row.RowIndex}&quot;); if (endingCell == null) { break; } XlsxAnimal xlsxAnimal = new XlsxAnimal() { Name = ExcelHelper.GetCellValue(workbookPart, sheetData, $&quot;A{row.RowIndex}&quot;), Unit = ExcelHelper.GetCellValue(workbookPart, sheetData, $&quot;B{row.RowIndex}&quot;), Value = ExcelHelper.GetCellValue(workbookPart, sheetData, $&quot;C{row.RowIndex}&quot;) }; if (!Animal.ContainKey(XlsxAnimal.Name)) { if (XlsxAnimal.Name != &quot;Name&quot;) { Animal.Add(xlsxAnimal.Name, xlsxAnimal); } } returnValue = true; } } } } return returnValue; } </code></pre> <p>All of my code run, I can retrieve all the information I want.</p> <p>I want to have my LoadAnimal() function in my function Load() not in LoadAnimals()</p> <pre><code>public bool Load(string fileName) { bool returnValue = false; if (File.Exists(fileName)) { SpreadsheetDocument spreadsheetDocument = spreadsheetDocument.Open(fileName, false); if (LoadZoo(spreadsheetDocument)) { returnValue = true; } if (LoadAnimals(spreadsheetDocument)) { returnValue = true; } if (LoadAnimal(spreadsheetDocument)) { returnValue = true; } spreadsheetDocument.Close(); } return returnValue; } </code></pre> <p>Something like that, but I dont know what to use as parameters or how to move the function for it to works.</p>
[ { "answer_id": 74363601, "author": "Nick ODell", "author_id": 530160, "author_profile": "https://Stackoverflow.com/users/530160", "pm_score": 0, "selected": false, "text": "arr = np.sort(arr, axis=1)\narr = arr[(arr==8).sum(axis=1).argsort(kind='stable')]\narr = arr[(arr==9).sum(axis=1).argsort(kind='stable')]\narr = arr[(arr==10).sum(axis=1).argsort(kind='stable')]\narr = arr[::-1]\n" }, { "answer_id": 74364390, "author": "ILS", "author_id": 10017662, "author_profile": "https://Stackoverflow.com/users/10017662", "pm_score": 3, "selected": true, "text": "numpy.frompyfunc" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74363200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20067336/" ]
74,363,204
<p>I have a very simple consumer from which I create a materialized view. I have enabled validation on my value object (throwing Constraintviolationexception for invalid json data). When I receive a value on which the validation fails, <em><strong>I exepct the value to logged &amp; consumer should read the next offset as I have LogAndContinueExceptionHandler enabled</strong></em>.</p> <p>However LogAndContinueExceptionHandler is never invoked and consumePojo State transition from PENDING_ERROR to ERROR</p> <p>Code</p> <pre><code>@Bean public Consumer&lt;KTable&lt;String, Pojo&gt;&gt; consume() { return values-&gt; values .filter((key, value) -&gt; Objects.nonNull(key)) .mapValues(value-&gt; value, Materialized.&lt;String, Pojo&gt;as(Stores.inMemoryKeyValueStore(&quot;POJO_STORE_NAME&quot;)) .withKeySerde(Serdes.String()) .withValueSerde(SerdeUtil.pojoSerde()) .withLoggingDisabled()) .toStream() .peek((key, value) -&gt; log.debug(&quot;Receiving Pojo from topic with key: {}, and UUID: {}&quot;, key, value == null ? 0 : value.getUuid())); } </code></pre> <p><strong>Why is it that LogAndContinueExceptionHandler is not invoked in case of KTable?</strong></p> <p>Note: If code is changed to KStreams then I see logging and records being skipped but with KTable not !!</p>
[ { "answer_id": 74363601, "author": "Nick ODell", "author_id": 530160, "author_profile": "https://Stackoverflow.com/users/530160", "pm_score": 0, "selected": false, "text": "arr = np.sort(arr, axis=1)\narr = arr[(arr==8).sum(axis=1).argsort(kind='stable')]\narr = arr[(arr==9).sum(axis=1).argsort(kind='stable')]\narr = arr[(arr==10).sum(axis=1).argsort(kind='stable')]\narr = arr[::-1]\n" }, { "answer_id": 74364390, "author": "ILS", "author_id": 10017662, "author_profile": "https://Stackoverflow.com/users/10017662", "pm_score": 3, "selected": true, "text": "numpy.frompyfunc" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74363204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14741163/" ]
74,363,227
<p>I would like to fill the missing values of the dates of a Pandas dataframe, but instead of filling the missing date based only on the date column, I would like to do it based on more than 1 column. In this case, the column <code>source</code>.</p> <p>The example is the following</p> <h3>Original</h3> <pre><code>date_found source count_unique_uuids count_unique_uuids_raw 2021-05-13 source_1 20 20 2021-05-14 source_2 1829 1829 2021-05-14 source_3 2245 2245 2021-05-14 source_1 40 40 2021-05-15 source_1 903 903 2021-05-16 source_2 20 20 2021-05-18 source_3 89 89 </code></pre> <h3>Desired dataset</h3> <pre><code> date_found source count_unique_uuids count_unique_uuids_raw 2021-05-13 source_1 20 20 2021-05-13 source_2 0 0 2021-05-13 source_3 0 0 2021-05-14 source_1 40 40 2021-05-14 source_2 1829 1829 2021-05-14 source_3 2245 2245 2021-05-15 source_1 903 903 2021-05-15 source_2 0 0 2021-05-15 source_3 0 0 2021-05-16 source_1 0 0 2021-05-16 source_2 20 20 2021-05-16 source_3 0 0 2021-05-17 source_1 0 0 2021-05-17 source_2 0 0 2021-05-17 source_3 0 0 2021-05-18 source_1 0 0 2021-05-18 source_2 0 0 2021-05-18 source_3 89 89 </code></pre> <p>I was using reindex and resample as a reference to build the dataset</p> <p><code>Reindex</code>: <a href="https://stackoverflow.com/questions/19324453/add-missing-dates-to-pandas-dataframe">Add missing dates to pandas dataframe</a></p> <p><code>Resample</code>: <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.resample.html" rel="nofollow noreferrer">https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.resample.html</a></p> <h4>I'm trying the following code</h4> <p>But getting an <code>error</code> ValueError: StringArray requires a sequence of strings or pandas.NA</p> <pre><code>def add_missing_dates(df: pd.DataFrame) -&gt; pd.DataFrame: df['date_found'] = pd.to_datetime(df['date_found'], format='%Y-%m-%d') min_date = df['date_found'].min() max_date = df['date_found'].max() (df.set_index(['date_found']) .groupby(['source'], as_index=False, group_keys=False) .apply(lambda x: x.reindex(pd.date_range(min_date, max_date))) .reset_index().rename(columns={'index': 'date_found'}) .fillna(0) ) return df def add_dates_to_source(df: pd.DataFrame, source: str = 'source') -&gt; pd.DataFrame: sources = df[source].tolist() dfs_to_concat = [] for source_value in sources: filtered_df = df.loc[df[source] == source_value] df_ = add_missing_dates(filtered_df) df_[source] = source_value dfs_to_concat.append(df_) return pd.concat(dfs_to_concat) </code></pre> <h3>To run</h3> <pre><code> df = add_dates_to_source(df) </code></pre>
[ { "answer_id": 74363428, "author": "Naveed", "author_id": 3494754, "author_profile": "https://Stackoverflow.com/users/3494754", "pm_score": 1, "selected": false, "text": "# make the date as of type datetime\ndf['date_found']=pd.to_datetime(df['date_found'])\n\n#find the min_date\nmin_date = df['date_found'].min()\n\n#find the max date\nmax_date = df['date_found'].max()\n\n\ndf2=(df.set_index(['date_found']) # set index to date, to allow for reindex\n .groupby(['source'],as_index=False, group_keys=False) # group on source\n .apply(lambda x: x.reindex(pd.date_range(min_date, max_date))) # reindex on the date range\n .reset_index() # reset index\n .rename(columns={'index': 'date_found'}) # rename the column\n)\ndf2['source'].ffill(inplace=True)\ndf2.fillna(0, inplace=True)\ndf2\n\n" }, { "answer_id": 74366417, "author": "SergFSM", "author_id": 18344512, "author_profile": "https://Stackoverflow.com/users/18344512", "pm_score": 1, "selected": false, "text": "min_date = df['date_found'].min()\nmax_date = df['date_found'].max()\n\ndates = (pd.date_range(min_date,max_date).to_frame()\n .reset_index(drop=True)\n .set_axis(['date_found'],axis=1))\n\nres = (dates.merge(df['source'].drop_duplicates(),how='cross')\n .merge(df,how='left').fillna(0))\n\nprint(res)\n'''\n date_found source count_unique_uuids count_unique_uuids_raw\n0 2021-05-13 source_1 20.0 20.0\n1 2021-05-13 source_2 0.0 0.0\n2 2021-05-13 source_3 0.0 0.0\n3 2021-05-14 source_1 40.0 40.0\n4 2021-05-14 source_2 1829.0 1829.0\n5 2021-05-14 source_3 2245.0 2245.0\n6 2021-05-15 source_1 903.0 903.0\n7 2021-05-15 source_2 0.0 0.0\n8 2021-05-15 source_3 0.0 0.0\n9 2021-05-16 source_1 0.0 0.0\n10 2021-05-16 source_2 20.0 20.0\n11 2021-05-16 source_3 0.0 0.0\n12 2021-05-17 source_1 0.0 0.0\n13 2021-05-17 source_2 0.0 0.0\n14 2021-05-17 source_3 0.0 0.0\n15 2021-05-18 source_1 0.0 0.0\n16 2021-05-18 source_2 0.0 0.0\n17 2021-05-18 source_3 89.0 89.0\n​\n" }, { "answer_id": 74366650, "author": "sammywemmy", "author_id": 7175713, "author_profile": "https://Stackoverflow.com/users/7175713", "pm_score": 0, "selected": false, "text": "# pip install pyjanitor\nimport pandas as pd\nimport janitor\ndf['date_found'] = pd.to_datetime(df['date_found'])\n\n# build a dictionary to contain the new dates\n# the key of the dictionary must exist in the dataframe\nnew_dates = {\"date_found\":pd.date_range(df.date_found.min(), \n df.date_found.max(), \n freq='D')}\n\ndf.complete(new_dates, 'source', fill_value=0)\n date_found source count_unique_uuids count_unique_uuids_raw\n0 2021-05-13 source_1 20 20\n1 2021-05-13 source_2 0 0\n2 2021-05-13 source_3 0 0\n3 2021-05-14 source_1 40 40\n4 2021-05-14 source_2 1829 1829\n5 2021-05-14 source_3 2245 2245\n6 2021-05-15 source_1 903 903\n7 2021-05-15 source_2 0 0\n8 2021-05-15 source_3 0 0\n9 2021-05-16 source_1 0 0\n10 2021-05-16 source_2 20 20\n11 2021-05-16 source_3 0 0\n12 2021-05-17 source_1 0 0\n13 2021-05-17 source_2 0 0\n14 2021-05-17 source_3 0 0\n15 2021-05-18 source_1 0 0\n16 2021-05-18 source_2 0 0\n17 2021-05-18 source_3 89 89\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74363227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12474157/" ]
74,363,238
<p>suppose i have</p> <pre><code>list1 = [3, 4, 6, 8, 13] </code></pre> <p>in a for loop I want to subtract the value i from the value that comes right after. In the above example: 4-3, 6-4, 8-6, 13-8. (and i want to skip the first value) desired result</p> <pre><code>list2 = [3, 1, 2, 2, 5] </code></pre> <p>can i do this in a for loop / list comprehension?</p> <p>more specifically do I want to do this in a dataframe</p> <pre><code> list1 0 3 1 4 2 6 3 8 4 13 </code></pre> <p>and after the operation</p> <pre><code> list1 list2 0 3 3 1 4 1 2 6 2 3 8 2 4 13 5 </code></pre> <p>I have tried for loops, lambda functions and list comprehensions and trying to access the positional index with enumerate() but I can't figure out how to access the value just before the value from which I want to subtract from</p> <p>edit: answers below worked. thank you very much!</p>
[ { "answer_id": 74363275, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 1, "selected": true, "text": "shift" }, { "answer_id": 74363317, "author": "Jamie.Sgro", "author_id": 11550733, "author_profile": "https://Stackoverflow.com/users/11550733", "pm_score": 1, "selected": false, "text": "list1 = [3, 4, 6, 8, 13]\n\nlist2 = []\nfor i, v in enumerate(list1):\n list2.append(list1[i] - list1[i-1])\nlist2[0] = list1[0]\n\nprint(list2) # [3, 1, 2, 2, 5]\n" }, { "answer_id": 74363341, "author": "Portal", "author_id": 20160920, "author_profile": "https://Stackoverflow.com/users/20160920", "pm_score": 0, "selected": false, "text": "for x in range(len(list) - 1, 0, -1):" }, { "answer_id": 74363420, "author": "hassan oubrahim", "author_id": 17010345, "author_profile": "https://Stackoverflow.com/users/17010345", "pm_score": 0, "selected": false, "text": "import pandas as pd\n\nlist1 = [3, 4, 6, 8, 13]\nlist2 = [list1[i+1]-list1[i] for i in range(len(list1)-1)]\nlist2.insert(0, list1[0])\n\ndata = {\n \"list1\":list1, \n \"list2\":list2\n}\n\ndf = pd.DataFrame(data)\nprint(df)\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74363238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20339178/" ]
74,363,242
<p>I want to store books, with title, year and already existing Author. An author is saved in a table authors that have a one to many relationship with books table. To create a book i have a from with two text inputs and one select. Select is filled from database. Now i want to store them and attach the author immediately.</p> <p>I can't pass the author in the route because it's dynamically due the select-input. Is there a possibility to do it like the call below?</p> <p><strong>Route:</strong></p> <pre><code>Route::post('/store', [BookController::class, 'store'])-&gt;name('book.store'); </code></pre> <p><strong>Controller:</strong></p> <pre><code>public function store(Request $request,Author $author_id) { $validated = $request-&gt;validate([ 'title' =&gt; 'required', 'year' =&gt; 'required', 'book_id' =&gt; 'required' ]); Book::create($request-&gt;all()); return redirect()-&gt;route('book.index'); } </code></pre>
[ { "answer_id": 74363275, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 1, "selected": true, "text": "shift" }, { "answer_id": 74363317, "author": "Jamie.Sgro", "author_id": 11550733, "author_profile": "https://Stackoverflow.com/users/11550733", "pm_score": 1, "selected": false, "text": "list1 = [3, 4, 6, 8, 13]\n\nlist2 = []\nfor i, v in enumerate(list1):\n list2.append(list1[i] - list1[i-1])\nlist2[0] = list1[0]\n\nprint(list2) # [3, 1, 2, 2, 5]\n" }, { "answer_id": 74363341, "author": "Portal", "author_id": 20160920, "author_profile": "https://Stackoverflow.com/users/20160920", "pm_score": 0, "selected": false, "text": "for x in range(len(list) - 1, 0, -1):" }, { "answer_id": 74363420, "author": "hassan oubrahim", "author_id": 17010345, "author_profile": "https://Stackoverflow.com/users/17010345", "pm_score": 0, "selected": false, "text": "import pandas as pd\n\nlist1 = [3, 4, 6, 8, 13]\nlist2 = [list1[i+1]-list1[i] for i in range(len(list1)-1)]\nlist2.insert(0, list1[0])\n\ndata = {\n \"list1\":list1, \n \"list2\":list2\n}\n\ndf = pd.DataFrame(data)\nprint(df)\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74363242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5751628/" ]
74,363,277
<p>I have an array with two items, which are also arrays themselves: <code>product</code> and <code>countries</code>.</p> <p>There are cases in which the <code>countries</code> array is the same for more than one product, like <code>basic</code> and <code>pro</code> in the example below.</p> <hr /> <h3>Given this array:</h3> <pre><code>$array = [ [ 'product' =&gt; [ 'value' =&gt; 'basic', 'label' =&gt; 'Basic' ], 'countries' =&gt; [ 'Japan', // these 'Korea' // two... ], ], [ 'product' =&gt; [ 'value' =&gt; 'pro', 'label' =&gt; 'Pro' ], 'countries' =&gt; [ 'Japan', // ...and these two 'Korea' // are identical... ], ], [ 'product' =&gt; [ 'value' =&gt; 'expert', 'label' =&gt; 'Expert' ], 'countries' =&gt; [ 'Japan', 'France' ], ] ]; </code></pre> <p>I would like to create new arrays grouped by <code>countries</code>, more precisely,</p> <h3>this is the result I'm after:</h3> <pre><code>$array = [ [ 'product' =&gt; [ [ 'value' =&gt; 'basic', 'label' =&gt; 'Basic' ], [ 'value' =&gt; 'pro', 'label' =&gt; 'Pro' ] ], 'countries' =&gt; [ 'Japan', // ...so they are now one single array 'Korea' // as the two products 'basic' and 'pro' have been grouped ], ], [ 'product' =&gt; [ 'value' =&gt; 'expert', 'label' =&gt; 'Expert' ], 'countries' =&gt; [ 'Japan', 'France' ], ] ]; </code></pre> <p>As you can see in the second snippet, what I'm trying to do is to group <code>basic</code> and <code>pro</code> together in the same array, since they both share the exact same <code>countries</code> (<code>Korea</code> and <code>Japan</code>).</p> <p>I've been trying for days to play around with this code, but it only seems to work if <code>product</code> and <code>countries</code> are strings rather than arrays:</p> <pre><code>$grouped = array(); foreach ($array as $element) { $grouped[$element['countries']][] = $element; } var_dump($grouped); </code></pre>
[ { "answer_id": 74367333, "author": "Rob Eyre", "author_id": 20418616, "author_profile": "https://Stackoverflow.com/users/20418616", "pm_score": 3, "selected": true, "text": "$productsByCountrySet = [];\nforeach ($array as $product) {\n $countries = $product['countries'];\n sort($countries);\n $countrySet = implode('/', $countries);\n if (isset($productsByCountrySet[$countrySet])) {\n $productsByCountrySet[$countrySet]['product'][] = $product['product'];\n } else {\n $productsByCountrySet[$countrySet] = [\n 'product' => [$product['product']],\n 'countries' => $countries,\n ];\n }\n}\n$products = [];\nforeach ($productsByCountrySet as $p) {\n if (count($p['product']) == 1) {\n $p['product'] = $p['product'][0];\n }\n $products[] = $p;\n}\nprint_r($products);\n" }, { "answer_id": 74367953, "author": "mickmackusa", "author_id": 2943403, "author_profile": "https://Stackoverflow.com/users/2943403", "pm_score": 2, "selected": false, "text": "elseif()" }, { "answer_id": 74368001, "author": "Sibidharan", "author_id": 3073612, "author_profile": "https://Stackoverflow.com/users/3073612", "pm_score": 1, "selected": false, "text": "<?php\n\n$array = [\n\n [\n 'product' => [\n 'value' => 'basic',\n 'label' => 'Basic'\n ],\n 'countries' => [\n 'Japan', // these\n 'Korea' // two...\n ],\n ],\n\n [\n 'product' => [\n 'value' => 'pro',\n 'label' => 'Pro'\n ],\n 'countries' => [\n 'Japan', // ...and these two\n 'Korea' // are identical...\n ],\n ],\n\n [\n 'product' => [\n 'value' => 'expert',\n 'label' => 'Expert'\n ],\n 'countries' => [\n 'Japan',\n 'France'\n ],\n ]\n\n];\n\n// print(serialize($array));\n\n$newarr = [];\n\n//Here I am sorting the countries so that it can be compared and making a new array\nforeach ($array as $key) {\n $new = $key['countries'];\n sort($key['countries']);\n sort($key['product']);\n $newarr[] = $key;\n}\n\n$result = [];\nforeach($newarr as $key => $value) {\n\n //Genetraing a unique key for each array type so that it can be compared\n $ckey = md5(serialize($value['countries']));\n $pkey = md5(serialize($value['product']));\n\n //In the new array, the unique Countries key is used to generate a new array which will contain the product & countries\n $result[$ckey]['product'][$pkey] = $value['product'];\n\n //Product key is used to reduce redunant entires in product array \n $result[$ckey]['countries'] = $value['countries'];\n\n //This new loop is used to compare other arrays and group them together\n foreach($newarr as $key2 => $value2) {\n if($key != $key2 && $value['countries'] == $value2['countries']) {\n $result[$ckey]['product'][$pkey] = $value2['product'];\n }\n }\n}\n\n\nprint_r($result);\n" }, { "answer_id": 74368046, "author": "user3425506", "author_id": 3425506, "author_profile": "https://Stackoverflow.com/users/3425506", "pm_score": 0, "selected": false, "text": "$newArray" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74363277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5122803/" ]
74,363,313
<p>I am very new to python and programming in generall. I am following a tutorial and tried to install python-docx using pip in the cmd, but it doesn't work. Those are the errors i see:</p> <pre><code>DEPRECATION: lxml is being installed using the legacy 'setup.py install' method, because it does not have a 'pyproject.toml' and the 'wheel' package is not installed. pip 23.1 will enforce this behaviour change. A possible replacement is to enable the '--use-pep517' option. Discussion can be found at https://github.com/pypa/pip/issues/8559 Running setup.py install for lxml ... error error: subprocess-exited-with-error </code></pre> <p>and</p> <pre><code>note: This error originates from a subprocess, and is likely not a problem with pip. error: legacy-install-failure × Encountered error while trying to install package. ╰─&gt; lxml note: This is an issue with the package mentioned above, not pip. hint: See above for output from the failure. </code></pre> <p>Can somebody help me with that problems in a way that even a newcomer like me understands it ?</p> <p>I tried it with &gt;pip install python-docx and &gt;pip install python-docx==0.8.11 in the cmd.</p>
[ { "answer_id": 74367333, "author": "Rob Eyre", "author_id": 20418616, "author_profile": "https://Stackoverflow.com/users/20418616", "pm_score": 3, "selected": true, "text": "$productsByCountrySet = [];\nforeach ($array as $product) {\n $countries = $product['countries'];\n sort($countries);\n $countrySet = implode('/', $countries);\n if (isset($productsByCountrySet[$countrySet])) {\n $productsByCountrySet[$countrySet]['product'][] = $product['product'];\n } else {\n $productsByCountrySet[$countrySet] = [\n 'product' => [$product['product']],\n 'countries' => $countries,\n ];\n }\n}\n$products = [];\nforeach ($productsByCountrySet as $p) {\n if (count($p['product']) == 1) {\n $p['product'] = $p['product'][0];\n }\n $products[] = $p;\n}\nprint_r($products);\n" }, { "answer_id": 74367953, "author": "mickmackusa", "author_id": 2943403, "author_profile": "https://Stackoverflow.com/users/2943403", "pm_score": 2, "selected": false, "text": "elseif()" }, { "answer_id": 74368001, "author": "Sibidharan", "author_id": 3073612, "author_profile": "https://Stackoverflow.com/users/3073612", "pm_score": 1, "selected": false, "text": "<?php\n\n$array = [\n\n [\n 'product' => [\n 'value' => 'basic',\n 'label' => 'Basic'\n ],\n 'countries' => [\n 'Japan', // these\n 'Korea' // two...\n ],\n ],\n\n [\n 'product' => [\n 'value' => 'pro',\n 'label' => 'Pro'\n ],\n 'countries' => [\n 'Japan', // ...and these two\n 'Korea' // are identical...\n ],\n ],\n\n [\n 'product' => [\n 'value' => 'expert',\n 'label' => 'Expert'\n ],\n 'countries' => [\n 'Japan',\n 'France'\n ],\n ]\n\n];\n\n// print(serialize($array));\n\n$newarr = [];\n\n//Here I am sorting the countries so that it can be compared and making a new array\nforeach ($array as $key) {\n $new = $key['countries'];\n sort($key['countries']);\n sort($key['product']);\n $newarr[] = $key;\n}\n\n$result = [];\nforeach($newarr as $key => $value) {\n\n //Genetraing a unique key for each array type so that it can be compared\n $ckey = md5(serialize($value['countries']));\n $pkey = md5(serialize($value['product']));\n\n //In the new array, the unique Countries key is used to generate a new array which will contain the product & countries\n $result[$ckey]['product'][$pkey] = $value['product'];\n\n //Product key is used to reduce redunant entires in product array \n $result[$ckey]['countries'] = $value['countries'];\n\n //This new loop is used to compare other arrays and group them together\n foreach($newarr as $key2 => $value2) {\n if($key != $key2 && $value['countries'] == $value2['countries']) {\n $result[$ckey]['product'][$pkey] = $value2['product'];\n }\n }\n}\n\n\nprint_r($result);\n" }, { "answer_id": 74368046, "author": "user3425506", "author_id": 3425506, "author_profile": "https://Stackoverflow.com/users/3425506", "pm_score": 0, "selected": false, "text": "$newArray" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74363313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20451134/" ]
74,363,314
<p><strong>EDIT: Now after 16 hours break I realized I have been misreading the results for hours - I didn't notice that there is <code>null</code> in all cases, so the behavior is consistent unlike I claim in this question (facepalm). However I decided not to delete this question but only close it as there is already useful answers.</strong></p> <p>Consider the following input JSON:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;widgets&quot;: [ { &quot;type&quot;: &quot;FOO&quot;, &quot;id&quot;: &quot;F1&quot; }, { &quot;type&quot;: &quot;ZAP&quot;, &quot;id&quot;: &quot;Z1&quot; }, { &quot;type&quot;: &quot;BAR&quot;, &quot;id&quot;: &quot;B1&quot; } ] } </code></pre> <p>The following transformation:</p> <pre class="lang-json prettyprint-override"><code>[ { &quot;operation&quot;: &quot;shift&quot;, &quot;spec&quot;: { &quot;widgets&quot;: { &quot;*&quot;: { &quot;type&quot;: { &quot;FOO&quot;: { &quot;@(2,id)&quot;: &quot;widgets[&amp;3].fooId&quot; }, &quot;BAR&quot;: { &quot;@(2,id)&quot;: &quot;widgets[&amp;3].barId&quot; } } } } } } ] </code></pre> <p>creates the expected (correct) output. <strong>EDIT I misread this output - I didn't realize there is 3 elements where one element is null but I though there is only 2 non-null elements</strong>:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;widgets&quot;: [ { &quot;fooId&quot;: &quot;F1&quot; }, null, { &quot;barId&quot;: &quot;B1&quot; } ] } </code></pre> <p>However the following transformation creates the unexpected output:</p> <pre class="lang-json prettyprint-override"><code>[ { &quot;operation&quot;: &quot;shift&quot;, &quot;spec&quot;: { &quot;widgets&quot;: { &quot;*&quot;: { &quot;type&quot;: { &quot;BAR&quot;: { &quot;@(2,id)&quot;: &quot;widgets[&amp;3].barId&quot; } } } } } } ] </code></pre> <p>This is the actual (wrong) output:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;widgets&quot;: [ null, null, { &quot;barId&quot;: &quot;B1&quot; } ] } </code></pre> <p>This is the expected (correct) output:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;widgets&quot;: [ { &quot;barId&quot;: &quot;B1&quot; } ] } </code></pre> <p>Why sometimes there is <code>null</code> elements in the <code>widgets</code> array and sometimes there is not? How I can avoid them?</p> <p>Based on the many other SO questions the following operation:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;operation&quot;: &quot;modify-overwrite-beta&quot;, &quot;spec&quot;: { &quot;*&quot;: &quot;=recursivelySquashNulls&quot; } } </code></pre> <p>should remove the <code>null</code> values, but why those are not removed in the following transformation?</p> <pre class="lang-json prettyprint-override"><code>[ { &quot;operation&quot;: &quot;shift&quot;, &quot;spec&quot;: { &quot;widgets&quot;: { &quot;*&quot;: { &quot;type&quot;: { &quot;BAR&quot;: { &quot;@(2,id)&quot;: &quot;widgets[&amp;3].barId&quot; } } } } } }, { &quot;operation&quot;: &quot;modify-overwrite-beta&quot;, &quot;spec&quot;: { &quot;*&quot;: &quot;=recursivelySquashNulls&quot; } } ] </code></pre> <p>I'm observing this behavior in <a href="http://jolt-demo.appspot.com/" rel="nofollow noreferrer">http://jolt-demo.appspot.com/</a></p>
[ { "answer_id": 74367333, "author": "Rob Eyre", "author_id": 20418616, "author_profile": "https://Stackoverflow.com/users/20418616", "pm_score": 3, "selected": true, "text": "$productsByCountrySet = [];\nforeach ($array as $product) {\n $countries = $product['countries'];\n sort($countries);\n $countrySet = implode('/', $countries);\n if (isset($productsByCountrySet[$countrySet])) {\n $productsByCountrySet[$countrySet]['product'][] = $product['product'];\n } else {\n $productsByCountrySet[$countrySet] = [\n 'product' => [$product['product']],\n 'countries' => $countries,\n ];\n }\n}\n$products = [];\nforeach ($productsByCountrySet as $p) {\n if (count($p['product']) == 1) {\n $p['product'] = $p['product'][0];\n }\n $products[] = $p;\n}\nprint_r($products);\n" }, { "answer_id": 74367953, "author": "mickmackusa", "author_id": 2943403, "author_profile": "https://Stackoverflow.com/users/2943403", "pm_score": 2, "selected": false, "text": "elseif()" }, { "answer_id": 74368001, "author": "Sibidharan", "author_id": 3073612, "author_profile": "https://Stackoverflow.com/users/3073612", "pm_score": 1, "selected": false, "text": "<?php\n\n$array = [\n\n [\n 'product' => [\n 'value' => 'basic',\n 'label' => 'Basic'\n ],\n 'countries' => [\n 'Japan', // these\n 'Korea' // two...\n ],\n ],\n\n [\n 'product' => [\n 'value' => 'pro',\n 'label' => 'Pro'\n ],\n 'countries' => [\n 'Japan', // ...and these two\n 'Korea' // are identical...\n ],\n ],\n\n [\n 'product' => [\n 'value' => 'expert',\n 'label' => 'Expert'\n ],\n 'countries' => [\n 'Japan',\n 'France'\n ],\n ]\n\n];\n\n// print(serialize($array));\n\n$newarr = [];\n\n//Here I am sorting the countries so that it can be compared and making a new array\nforeach ($array as $key) {\n $new = $key['countries'];\n sort($key['countries']);\n sort($key['product']);\n $newarr[] = $key;\n}\n\n$result = [];\nforeach($newarr as $key => $value) {\n\n //Genetraing a unique key for each array type so that it can be compared\n $ckey = md5(serialize($value['countries']));\n $pkey = md5(serialize($value['product']));\n\n //In the new array, the unique Countries key is used to generate a new array which will contain the product & countries\n $result[$ckey]['product'][$pkey] = $value['product'];\n\n //Product key is used to reduce redunant entires in product array \n $result[$ckey]['countries'] = $value['countries'];\n\n //This new loop is used to compare other arrays and group them together\n foreach($newarr as $key2 => $value2) {\n if($key != $key2 && $value['countries'] == $value2['countries']) {\n $result[$ckey]['product'][$pkey] = $value2['product'];\n }\n }\n}\n\n\nprint_r($result);\n" }, { "answer_id": 74368046, "author": "user3425506", "author_id": 3425506, "author_profile": "https://Stackoverflow.com/users/3425506", "pm_score": 0, "selected": false, "text": "$newArray" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74363314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/272735/" ]
74,363,316
<p>i need actual_new column from actual in pandas dataframe.</p> <pre><code>start time end time actual actual_new 4/1/2022 20:00 4/1/2022 21:00 0.749123 0.749123 4/1/2022 21:00 4/1/2022 22:00 0.749123 0.770175 4/1/2022 22:00 4/1/2022 23:00 0.749123 0.725439 4/1/2022 23:00 4/2/2022 0:00 0.749123 0.659649 4/2/2022 0:00 4/2/2022 1:00 0.749123 0.245614 4/2/2022 1:00 4/2/2022 2:00 0.749123 0.078947 4/1/2022 21:00 4/1/2022 22:00 0.770175 0.749123 4/1/2022 22:00 4/1/2022 23:00 0.770175 0.770175 4/1/2022 23:00 4/2/2022 0:00 0.770175 0.725439 4/2/2022 0:00 4/2/2022 1:00 0.770175 0.659649 4/2/2022 1:00 4/2/2022 2:00 0.770175 0.245614 4/2/2022 2:00 4/2/2022 3:00 0.770175 0.078947 4/1/2022 22:00 4/1/2022 23:00 0.725439 0.749123 4/1/2022 23:00 4/2/2022 0:00 0.725439 0.770175 4/2/2022 0:00 4/2/2022 1:00 0.725439 0.725439 4/2/2022 1:00 4/2/2022 2:00 0.725439 0.659649 4/2/2022 2:00 4/2/2022 3:00 0.725439 0.245614 4/2/2022 3:00 4/2/2022 4:00 0.725439 0.078947 4/1/2022 23:00 4/2/2022 0:00 0.659649 0.749123 4/2/2022 0:00 4/2/2022 1:00 0.659649 0.770175 4/2/2022 1:00 4/2/2022 2:00 0.659649 0.725439 4/2/2022 2:00 4/2/2022 3:00 0.659649 0.659649 4/2/2022 3:00 4/2/2022 4:00 0.659649 0.245614 4/2/2022 4:00 4/2/2022 5:00 0.659649 0.078947 4/2/2022 0:00 4/2/2022 1:00 0.245614 0.749123 4/2/2022 1:00 4/2/2022 2:00 0.245614 0.770175 4/2/2022 2:00 4/2/2022 3:00 0.245614 0.725439 4/2/2022 3:00 4/2/2022 4:00 0.245614 0.659649 4/2/2022 4:00 4/2/2022 5:00 0.245614 0.245614 4/2/2022 5:00 4/2/2022 6:00 0.245614 0.078947 4/2/2022 1:00 4/2/2022 2:00 0.078947 0.749123 4/2/2022 2:00 4/2/2022 3:00 0.078947 0.770175 4/2/2022 3:00 4/2/2022 4:00 0.078947 0.725439 4/2/2022 4:00 4/2/2022 5:00 0.078947 0.659649 4/2/2022 5:00 4/2/2022 6:00 0.078947 0.245614 4/2/2022 6:00 4/2/2022 7:00 0.078947 0.078947 </code></pre>
[ { "answer_id": 74363560, "author": "fnqwejflqo", "author_id": 17060744, "author_profile": "https://Stackoverflow.com/users/17060744", "pm_score": 1, "selected": false, "text": "df['actual_new'] = list(df['actual'].unique())*int(df.shape[0]/len(uniques))\n" }, { "answer_id": 74363969, "author": "Jahirul islam", "author_id": 7386944, "author_profile": "https://Stackoverflow.com/users/7386944", "pm_score": 0, "selected": false, "text": "df['actual_new'] = df['actual']\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74363316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5506647/" ]
74,363,320
<p>there is an example with content dropdown: <a href="https://codesandbox.io/s/expand-content-4pc09c?fil.." rel="nofollow noreferrer">https://codesandbox.io/s/expand-content-4pc09c?fil..</a>. But the appearance of content on the button is quite fast. I need to set smoothness using the transition property, but it didn't work. As far as I understand, you need to add some kind of appearance effect with the help of <code>visability</code>, but here there is a link to useState also tried to set a property for the content: <code>transition: all 0.5s ease-out;</code> but the animation is not happening I also tried change styles like that:</p> <pre><code> const styles = { height: expand ? &quot;auto&quot; : &quot;0px&quot;, maxHeight: expand ? &quot;auto&quot; : &quot;0px&quot;, overflow: expand ? &quot;visible&quot; : &quot;hidden&quot; }; </code></pre> <p>but it turns out that i have the same result</p>
[ { "answer_id": 74376229, "author": "Franco Gabriel", "author_id": 19499461, "author_profile": "https://Stackoverflow.com/users/19499461", "pm_score": 3, "selected": true, "text": "visibility" }, { "answer_id": 74430644, "author": "fiorentina.gf", "author_id": 10073607, "author_profile": "https://Stackoverflow.com/users/10073607", "pm_score": 0, "selected": false, "text": "transition: max-height .5s ease-in-out; \n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74363320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10073607/" ]
74,363,345
<p>So I'm trying to make an app where you fill out a survey and then go to another page. I've tried using React Router for this. I followed a tutorial but when I try to render components with Route in them it doesn't seem to render. components without Route seem to work fine.</p> <p>main app:</p> <pre><code>import Intro from &quot;./pages/intro.js&quot; function App() { return ( &lt;div className=&quot;App&quot;&gt; &lt;Intro/&gt; &lt;/div&gt; ); } export default App; </code></pre> <p>component with Route:</p> <pre><code>import { Routes, useNavigate, Route, Router } from 'react-router-dom'; import B1 from &quot;./B1.js&quot; function Intro() { const navigate = useNavigate(); const navigateToB1 = () =&gt; { navigate('./B1.js'); }; return ( &lt;form&gt; &lt;h1&gt;Walcome!&lt;/h1&gt; &lt;p&gt;&lt;b&gt;plase enter your name:&lt;/b&gt;&lt;/p&gt; &lt;label&gt; Name: &lt;input type=&quot;text&quot; name=&quot;name&quot; /&gt; &lt;/label&gt; &lt;input type=&quot;submit&quot; id=&quot;sumbit&quot; value=&quot;Submit&quot; onClick={navigateToB1} /&gt; &lt;Router&gt; &lt;Routes&gt; &lt;Route path=&quot;./B1.js&quot; element={&lt;B1 /&gt;} /&gt; &lt;/Routes&gt; &lt;/Router&gt; &lt;/form&gt; ); } export default Intro; </code></pre>
[ { "answer_id": 74363892, "author": "Letincel", "author_id": 4735563, "author_profile": "https://Stackoverflow.com/users/4735563", "pm_score": 0, "selected": false, "text": "function Intro() {\n const navigate = useNavigate();\n\n const navigateToB1= () => \n {\n navigate('./B1.js');\n };\n\n return ( \n <> \n <form>\n <h1>Walcome!</h1>\n <p><b>plase enter your name:</b></p>\n <label>\n Name:\n <input type=\"text\" name=\"name\" />\n </label>\n <input type=\"submit\" id=\"sumbit\" value=\"Submit\" onClick={navigateToB1} />\n \n </form>\n <BrowserRouter>\n <Routes>\n <Route path=\"./B1.js\" element={<B1/>} />\n </Routes>\n </BrowserRouter\n\n </>\n );\n }\n\n export default Intro;\n" }, { "answer_id": 74364483, "author": "Drew Reese", "author_id": 8690857, "author_profile": "https://Stackoverflow.com/users/8690857", "pm_score": 2, "selected": true, "text": "Intro" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74363345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10528301/" ]
74,363,374
<p>Using openpyxl we can properly check if a cell is fully bold/not bold, but we cannot work with richtext so having two words, one bolded and one not, will make the check fail.</p> <p>This can be done correctly with xlrd, but it doesn't support xlsx files. Converting from xlsx to xls is risky, especially in my use case, since I have a big file with many languages and I think i could lose information.</p> <p>How can I check if cells substrings are bold inside a xlsx file?</p>
[ { "answer_id": 74363946, "author": "ojdo", "author_id": 2375855, "author_profile": "https://Stackoverflow.com/users/2375855", "pm_score": 1, "selected": false, "text": ".xls" }, { "answer_id": 74364103, "author": "Remzinho", "author_id": 2484591, "author_profile": "https://Stackoverflow.com/users/2484591", "pm_score": 0, "selected": false, "text": "openpyxl 3.0.10" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74363374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11377787/" ]
74,363,404
<p>I am trying to filter a vector of structs by a struct attribute and then return another attribute. However I'm not quite sure how to elegantly extract the value.</p> <p>My function will take in the name of a budget and then I want to return the id of that budget by searching through a list of <code>Budget</code>s.</p> <p>Is there a cleaner way to do this in one pass without allocating a new struct?</p> <pre><code>// Budget structs #[derive(Serialize, Deserialize, Debug)] pub struct Budgets { pub budgets: Vec&lt;Budget&gt; } #[derive(Serialize, Deserialize, Debug)] pub struct Budget { pub id: String, name: String, last_modified_on: String, first_month: String, last_month: String, date_format: DateFormat, currency_format: Option&lt;CurrencyFormat&gt;, accounts: Option&lt;Accounts&gt;, } impl Adapter { fn get_budget_id(&amp;self, budget_name: &amp;str) -&gt; anyhow::Result&lt;String&gt; { let budget_data = self.get_budgets()?; let budget = budget_data.data.budgets.into_iter() .filter(|b| b.name == budget_name); //.collect::&lt;Budgets&gt;() &lt;-- FromIterator not implemented //.remove(0); let b = Budgets { budgets: Vec::from_iter(budget) }; if b.budgets.is_empty() { Err(anyhow::anyhow!(&quot;Error, no budget with {} name found&quot;, budget_name)) } else { Ok(b.budgets[0].id.clone()) } } } </code></pre>
[ { "answer_id": 74363613, "author": "Seve Martinez", "author_id": 8055704, "author_profile": "https://Stackoverflow.com/users/8055704", "pm_score": 1, "selected": false, "text": "fn get_budget_id(&self, budget_name: &str) -> anyhow::Result<String> {\n let budget_data = self.get_budgets()?;\n if let Some(budget) = budget_data.data.budgets.into_iter()\n .find(|b| b.name == budget_name) {\n Ok(budget.id)\n } else {\n Err(anyhow::anyhow!(\"Error, no budget with name {} found\", budget_name))\n }\n }\n" }, { "answer_id": 74363621, "author": "Oussama Gammoudi", "author_id": 3978243, "author_profile": "https://Stackoverflow.com/users/3978243", "pm_score": -1, "selected": false, "text": "let budget:Budget = budget_data.data.budgets.into_iter()\n .find(|b| b.name == budget_name)\n .ok_or(anyhow::anyhow!(\"Error, no budget with {} name found\", budget_name))?;\n" } ]
2022/11/08
[ "https://Stackoverflow.com/questions/74363404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8055704/" ]