qid
int64
4
22.2M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,394,965
<p>I have a function that returns an interpolated string for example.</p> <pre><code>`This is my string $t(some.value)` </code></pre> <p>The issue I am facing is that <code>t</code> is returned after I get the interpolated string. For example</p> <pre><code>const mainFunction = (targetString) =&gt; { const { t } = getTranslationService(); return targetString; } </code></pre> <p>I want to resolve the value and return the processed string in the mainFunction. I tried with <code>eval</code> but it didn't work</p>
[ { "answer_id": 74396252, "author": "Yukulélé", "author_id": 806169, "author_profile": "https://Stackoverflow.com/users/806169", "pm_score": -1, "selected": false, "text": "`This is my string ${t(some.value)}`\n" }, { "answer_id": 74445952, "author": "agusgambina", "author_id": 2853555, "author_profile": "https://Stackoverflow.com/users/2853555", "pm_score": 1, "selected": true, "text": "t" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74394965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2853555/" ]
74,394,976
<p>I have a data set like this</p> <pre><code>df1&lt;-data.frame(ID=c(1,2,3,4),colA=c(101,102,103,104),colB=c(201,202,203,204)) df2&lt;-data.frame(var_id=c(101,102,103,104,201,202,203,204),var_value=c(&quot;A&quot;,&quot;B&quot;,&quot;C&quot;,&quot;D&quot;,&quot;E&quot;,&quot;F&quot;,&quot;G&quot;,&quot;H&quot;)) </code></pre> <p>I want to map any value in df1 that is in df2$var_id with the corresponding string in df2$var_value.</p> <p>Desired output</p> <pre><code>df1&lt;-data.frame(ID=c(1,2,3,4),colA=c(&quot;A&quot;,&quot;B&quot;,&quot;C&quot;,&quot;D&quot;),colB=c(&quot;E&quot;,&quot;F&quot;,&quot;G&quot;,&quot;H&quot;)) </code></pre> <p>I have tried write a function, and then do lapply, but it only display one var_value</p>
[ { "answer_id": 74396252, "author": "Yukulélé", "author_id": 806169, "author_profile": "https://Stackoverflow.com/users/806169", "pm_score": -1, "selected": false, "text": "`This is my string ${t(some.value)}`\n" }, { "answer_id": 74445952, "author": "agusgambina", "author_id": 2853555, "author_profile": "https://Stackoverflow.com/users/2853555", "pm_score": 1, "selected": true, "text": "t" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74394976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20472213/" ]
74,394,999
<p>When trying to use EarlyStopping for Seq2SeqTrainer, e.g. patience was set to 1 and threshold 1.0:</p> <pre><code>training_args = Seq2SeqTrainingArguments( output_dir='./', num_train_epochs=3, per_device_train_batch_size=4, per_device_eval_batch_size=4, logging_steps=1, save_steps=5, eval_steps=1, max_steps=10, evaluation_strategy=&quot;steps&quot;, predict_with_generate=True, report_to=None, metric_for_best_model=&quot;chr_f_score&quot;, load_best_model_at_end=True ) early_stop = EarlyStoppingCallback(2, 1.0) trainer = Seq2SeqTrainer( model=model, args=training_args, train_dataset=valid_data.with_format(&quot;torch&quot;), eval_dataset=test_data.with_format(&quot;torch&quot;), compute_metrics=compute_metrics, callbacks=[early_stop] ) trainer.train() </code></pre> <p>The model continues training until <code>max_steps</code> instead of stopping after the stopping criteria is met.</p> <p>I'm not sure if this is a bug or maybe some argument is missing in when I use Seq2SeqTrainer, a working code to replicate the issue can be found on <a href="https://www.kaggle.com/code/alvations/huggingface-earlystopping-callbacks?scriptVersionId=110637297" rel="nofollow noreferrer">https://www.kaggle.com/code/alvations/huggingface-earlystopping-callbacks?scriptVersionId=110637297</a></p> <h2>Q: Why did the Seq2SeqTrainer not stop when the EarlyStoppingCallback criteria is met?</h2> <hr /> <p>After the <code>max_steps</code>, if we do some probing, somehow the <code>early_stopping_patience_counter</code> has been reached but the training didn't stop</p> <pre><code>&gt;&gt;&gt; early_stop.early_stopping_patience_counter 2 </code></pre>
[ { "answer_id": 74396252, "author": "Yukulélé", "author_id": 806169, "author_profile": "https://Stackoverflow.com/users/806169", "pm_score": -1, "selected": false, "text": "`This is my string ${t(some.value)}`\n" }, { "answer_id": 74445952, "author": "agusgambina", "author_id": 2853555, "author_profile": "https://Stackoverflow.com/users/2853555", "pm_score": 1, "selected": true, "text": "t" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74394999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/610569/" ]
74,395,003
<p>I have a data which comes from GitHub Api <code>https://docs.github.com/en/rest/repos/repos#list-repository-languages</code>. It is a Array of objects of every repository of specified user, the first problem is that the value shown for each language is the number of bytes of code written in that language. So it looks like this:</p> <pre><code>data = [ { repoName: &quot;Docker_Kubernetes_Labs&quot;, languages: { JavaScript: 64677, HTML: 17832, CSS: 8154, Dockerfile: 2859, }, }, { repoName: &quot;Frontend-HTTP-MQTT-Project&quot;, languages: { JavaScript: 59038, SCSS: 4732, CSS: 4281, HTML: 1925, }, }, { repoName: &quot;frontend-prj&quot;, languages: { JavaScript: 16730, SCSS: 5388, HTML: 1721, }, }, { repoName: &quot;JavaProjects&quot;, languages: { Java: 42040, }, }, ]; </code></pre> <p>What I would like to change, is to sum all of the languages used, and display percentages so for all repositorys it would look like this:</p> <pre><code>{ JavaScript: 0.55, SCSS: 0.1, CSS: 0.1, HTML: 0.1, Java: 0.1, Dockerfile: 0.05 } </code></pre> <p>I just want it to be summing up to 100% or 1 or 100, because I want to create a Pie-chart with these data, But also I want to be able to have a list of all repositories, so the final data would look like this:</p> <pre><code>expected_output = [ { languages: { JavaScript: 0.55, SCSS: 0.1, CSS: 0.1, HTML: 0.1, Java: 0.1, Dockerfile: 0.05, }, repositories: [ &quot;Docker_Kubernetes_Labs&quot;, &quot;Frontend-HTTP-MQTT-Project&quot;, &quot;frontend-prj&quot;, &quot;JavaProjects&quot;, ], }, ]; </code></pre> <p>And for me it's to much, firstly I do not know how to conver those bytes into percentages so they sum up to 100, and secondly I do not know how to display this data in a simpler way.</p>
[ { "answer_id": 74395093, "author": "Konrad", "author_id": 5089567, "author_profile": "https://Stackoverflow.com/users/5089567", "pm_score": 0, "selected": false, "text": "JavaScript: 64677,\nHTML: 17832,\nCSS: 8154,\nDockerfile: 2859,\n" }, { "answer_id": 74395314, "author": "GrafiCode", "author_id": 5334486, "author_profile": "https://Stackoverflow.com/users/5334486", "pm_score": 1, "selected": false, "text": "Array.reduce()" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17885211/" ]
74,395,019
<p>In a ViewModel i load data from a FirebaseDatabase and showing it in a CollectionView.</p> <pre><code> public MainViewModel() { var collection = firebase .Child(&quot;Foto/&quot;) .AsObservable&lt;Fotos&gt;() .Subscribe((dbevent) =&gt; { if (dbevent.Object != null) { Foto.Add(dbevent.Object); } }); } </code></pre> <p>But i want to change it ToList so i make it Descending based on BalId in the Database.</p> <p>Want to use <code>GetAllFotosDesending()</code> but i cannot make it work in the MainViewModel.</p> <pre><code> public async Task&lt;List&lt;Fotos&gt;&gt; GetAllFotosDesending() { return (await firebase .Child(&quot;Foto/&quot;) .OnceAsync&lt;Fotos&gt;()).Select(item =&gt; new Fotos { BalId = item.Object.BalId, RollNo = item.Object.RollNo, Foto = item.Object.Foto, Titel = item.Object.Titel, Fototekst = item.Object.Fototekst }).OrderByDescending(x =&gt; x.BalId).ToList(); } </code></pre> <p>2 options , or make it <code>ToList</code> in the MainViewModel or add <code>GetAllFotosDesending()</code> work in the MainViewModel. The last option is maybe better ? but i cannot make this working when adding to the MainViewModel</p> <p>This is the CollectionView with <code>ItemsSource=&quot;{Binding Foto}&quot;</code></p> <pre><code> &lt;CollectionView x:Name=&quot;Dood&quot; ItemsSource=&quot;{Binding Foto}&quot;&gt; &lt;CollectionView.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;Grid ColumnDefinitions=&quot;Auto, *&quot; RowDefinitions=&quot;Auto, Auto, Auto, 1&quot; ColumnSpacing=&quot;10&quot; RowSpacing=&quot;5&quot; Padding=&quot;0,10&quot;&gt; &lt;Image Source=&quot;{Binding Pic}&quot; Margin=&quot;20,0,0,10&quot; HeightRequest=&quot;70&quot; WidthRequest=&quot;70&quot; HorizontalOptions=&quot;Center&quot; VerticalOptions=&quot;Center&quot; Grid.RowSpan=&quot;3&quot; Grid.Row=&quot;0&quot; Grid.Column=&quot;0&quot;&gt; &lt;Image.Clip&gt; &lt;EllipseGeometry Center=&quot;35,35&quot; RadiusX=&quot;35&quot; RadiusY=&quot;35&quot;/&gt; &lt;/Image.Clip&gt; &lt;/Image&gt; &lt;Label Text=&quot;{Binding Titel}&quot; FontAttributes=&quot;Bold&quot; Grid.Column=&quot;1&quot; Grid.Row=&quot;0&quot;/&gt; &lt;Label Text=&quot;{Binding Email}&quot; Grid.Column=&quot;1&quot; Grid.Row=&quot;1&quot;/&gt; &lt;Label Text=&quot;{Binding RollNo}&quot; Grid.Column=&quot;1&quot; Grid.Row=&quot;2&quot;/&gt; &lt;BoxView Style=&quot;{StaticResource SeparatorLine}&quot; Grid.Column=&quot;0&quot; Grid.Row=&quot;3&quot; Grid.ColumnSpan=&quot;2&quot;/&gt; &lt;/Grid&gt; &lt;/DataTemplate&gt; &lt;/CollectionView.ItemTemplate&gt; &lt;/CollectionView&gt; </code></pre> <p>Binding like this</p> <pre><code> public MainPage() { InitializeComponent(); BindingContext = new MainViewModel(); } </code></pre>
[ { "answer_id": 74395414, "author": "FreakyAli", "author_id": 7462031, "author_profile": "https://Stackoverflow.com/users/7462031", "pm_score": 1, "selected": false, "text": "public class AlphanumComparator : IComparer<object>\n{\n private enum ChunkType { Alphanumeric, Numeric };\n\n private bool InChunk(char ch, char otherCh)\n {\n ChunkType type = ChunkType.Alphanumeric;\n\n if (char.IsDigit(otherCh))\n {\n type = ChunkType.Numeric;\n }\n\n return (type != ChunkType.Alphanumeric || !char.IsDigit(ch))\n && (type != ChunkType.Numeric || char.IsDigit(ch));\n }\n\n public int Compare(object x, object y)\n {\n string firstString = x as string;\n string secondString = y as string;\n if (string.IsNullOrWhiteSpace(firstString) || string.IsNullOrWhiteSpace(secondString))\n {\n return 0;\n }\n\n int firstMarker = 0, secondMarker = 0;\n\n while ((firstMarker < firstString.Length) || (secondMarker < secondString.Length))\n {\n if (firstMarker >= firstString.Length)\n {\n return -1;\n }\n else if (secondMarker >= secondString.Length)\n {\n return 1;\n }\n char firstCh = firstString[firstMarker];\n char secondCh = secondString[secondMarker];\n\n StringBuilder thisChunk = new StringBuilder();\n StringBuilder thatChunk = new StringBuilder();\n\n while ((firstMarker < firstString.Length) && (thisChunk.Length == 0 || InChunk(firstCh, thisChunk[0])))\n {\n thisChunk.Append(firstCh);\n firstMarker++;\n\n if (firstMarker < firstString.Length)\n {\n firstCh = firstString[firstMarker];\n }\n }\n\n while ((secondMarker < secondString.Length) && (thatChunk.Length == 0 || InChunk(secondCh, thatChunk[0])))\n {\n thatChunk.Append(secondCh);\n secondMarker++;\n\n if (secondMarker < secondString.Length)\n {\n secondCh = secondString[secondMarker];\n }\n }\n\n int result = 0;\n // If both chunks contain numeric characters, sort them numerically\n if (char.IsDigit(thisChunk[0]) && char.IsDigit(thatChunk[0]))\n {\n int thisNumericChunk = Convert.ToInt32(thisChunk.ToString());\n int thatNumericChunk = Convert.ToInt32(thatChunk.ToString());\n if (thisNumericChunk < thatNumericChunk)\n {\n result = -1;\n }\n\n if (thisNumericChunk > thatNumericChunk)\n {\n result = 1;\n }\n }\n else\n {\n result = thisChunk.ToString().CompareTo(thatChunk.ToString());\n }\n\n if (result != 0)\n {\n return result;\n }\n }\n\n return 0;\n }\n}\n" }, { "answer_id": 74411073, "author": "Bas H", "author_id": 10867491, "author_profile": "https://Stackoverflow.com/users/10867491", "pm_score": 0, "selected": false, "text": " public async Task<List<Fotos>> GetAllFotosDesending()\n {\n return (await firebase\n .Child(\"Foto/\")\n .OnceAsync<Fotos>()).Select(item => new Fotos\n {\n BalId = item.Object.BalId,\n RollNo = item.Object.RollNo,\n Foto = item.Object.Foto,\n Titel = item.Object.Titel,\n Fototekst = item.Object.Fototekst\n }).OrderByDescending(x => x.BalId).ToList();\n }\n public async void InitializeAsync()\n { \n Fotos = await GetAllFotosDesending(); \n }\n \n\n public MainViewModel()\n {\n InitializeAsync();\n }\n \n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10867491/" ]
74,395,078
<p>I use Sambroadcaster</p> <p>change color of a text in php with echo</p> <p>this is the code:</p> <pre><code>&lt;span id=&quot;currently-playing-title&quot;&gt;&lt;?php echo $currentSong-&gt;artist_title;; ?&gt;&lt;/span&gt;&lt;?php if ($currentSong-&gt;isRequested) echo &quot;[Request]&quot;; ?&gt; </code></pre> <p>This is the text that i want to change the color <strong>[Request]</strong></p> <p>The next code is:</p> <pre><code>&lt;?php if($comingSong-&gt;isRequested): ?&gt;[Request] </code></pre> <p>In this line i want also change the color of the text <strong>[Request]</strong></p> <p>In the css there is no rule al the text colors are white</p> <p>Any idea?</p> <p>I try to find a solution in the css file but there is no rule herfore</p>
[ { "answer_id": 74395414, "author": "FreakyAli", "author_id": 7462031, "author_profile": "https://Stackoverflow.com/users/7462031", "pm_score": 1, "selected": false, "text": "public class AlphanumComparator : IComparer<object>\n{\n private enum ChunkType { Alphanumeric, Numeric };\n\n private bool InChunk(char ch, char otherCh)\n {\n ChunkType type = ChunkType.Alphanumeric;\n\n if (char.IsDigit(otherCh))\n {\n type = ChunkType.Numeric;\n }\n\n return (type != ChunkType.Alphanumeric || !char.IsDigit(ch))\n && (type != ChunkType.Numeric || char.IsDigit(ch));\n }\n\n public int Compare(object x, object y)\n {\n string firstString = x as string;\n string secondString = y as string;\n if (string.IsNullOrWhiteSpace(firstString) || string.IsNullOrWhiteSpace(secondString))\n {\n return 0;\n }\n\n int firstMarker = 0, secondMarker = 0;\n\n while ((firstMarker < firstString.Length) || (secondMarker < secondString.Length))\n {\n if (firstMarker >= firstString.Length)\n {\n return -1;\n }\n else if (secondMarker >= secondString.Length)\n {\n return 1;\n }\n char firstCh = firstString[firstMarker];\n char secondCh = secondString[secondMarker];\n\n StringBuilder thisChunk = new StringBuilder();\n StringBuilder thatChunk = new StringBuilder();\n\n while ((firstMarker < firstString.Length) && (thisChunk.Length == 0 || InChunk(firstCh, thisChunk[0])))\n {\n thisChunk.Append(firstCh);\n firstMarker++;\n\n if (firstMarker < firstString.Length)\n {\n firstCh = firstString[firstMarker];\n }\n }\n\n while ((secondMarker < secondString.Length) && (thatChunk.Length == 0 || InChunk(secondCh, thatChunk[0])))\n {\n thatChunk.Append(secondCh);\n secondMarker++;\n\n if (secondMarker < secondString.Length)\n {\n secondCh = secondString[secondMarker];\n }\n }\n\n int result = 0;\n // If both chunks contain numeric characters, sort them numerically\n if (char.IsDigit(thisChunk[0]) && char.IsDigit(thatChunk[0]))\n {\n int thisNumericChunk = Convert.ToInt32(thisChunk.ToString());\n int thatNumericChunk = Convert.ToInt32(thatChunk.ToString());\n if (thisNumericChunk < thatNumericChunk)\n {\n result = -1;\n }\n\n if (thisNumericChunk > thatNumericChunk)\n {\n result = 1;\n }\n }\n else\n {\n result = thisChunk.ToString().CompareTo(thatChunk.ToString());\n }\n\n if (result != 0)\n {\n return result;\n }\n }\n\n return 0;\n }\n}\n" }, { "answer_id": 74411073, "author": "Bas H", "author_id": 10867491, "author_profile": "https://Stackoverflow.com/users/10867491", "pm_score": 0, "selected": false, "text": " public async Task<List<Fotos>> GetAllFotosDesending()\n {\n return (await firebase\n .Child(\"Foto/\")\n .OnceAsync<Fotos>()).Select(item => new Fotos\n {\n BalId = item.Object.BalId,\n RollNo = item.Object.RollNo,\n Foto = item.Object.Foto,\n Titel = item.Object.Titel,\n Fototekst = item.Object.Fototekst\n }).OrderByDescending(x => x.BalId).ToList();\n }\n public async void InitializeAsync()\n { \n Fotos = await GetAllFotosDesending(); \n }\n \n\n public MainViewModel()\n {\n InitializeAsync();\n }\n \n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20472286/" ]
74,395,103
<p>I have a array of objects with the property status, where I want to return false IF</p> <p>I have (zero slots with &quot;return&quot; or zero &quot;ordered&quot; status or 1 slot with &quot;verification&quot; or 1 &quot;active&quot; status)</p> <pre><code>const slots = [ { status: 'void' }, { status: 'closed' }, { status: 'ordered' }, { status: 'verification' }, { status: 'active' } ] </code></pre> <p>I don't want to make like</p> <pre><code>x = slots.filter((val) =&gt; val.status === 'verification' || val.status === 'active' if (x.length &gt; 1) return false y = slots.filter((val) =&gt; val.status === 'return' &amp;&amp; val.status === 'ordered') if (y.length &gt; 0) return false </code></pre> <p>Is there a way to do this more efficiently and in just one &quot;function&quot;?</p>
[ { "answer_id": 74395414, "author": "FreakyAli", "author_id": 7462031, "author_profile": "https://Stackoverflow.com/users/7462031", "pm_score": 1, "selected": false, "text": "public class AlphanumComparator : IComparer<object>\n{\n private enum ChunkType { Alphanumeric, Numeric };\n\n private bool InChunk(char ch, char otherCh)\n {\n ChunkType type = ChunkType.Alphanumeric;\n\n if (char.IsDigit(otherCh))\n {\n type = ChunkType.Numeric;\n }\n\n return (type != ChunkType.Alphanumeric || !char.IsDigit(ch))\n && (type != ChunkType.Numeric || char.IsDigit(ch));\n }\n\n public int Compare(object x, object y)\n {\n string firstString = x as string;\n string secondString = y as string;\n if (string.IsNullOrWhiteSpace(firstString) || string.IsNullOrWhiteSpace(secondString))\n {\n return 0;\n }\n\n int firstMarker = 0, secondMarker = 0;\n\n while ((firstMarker < firstString.Length) || (secondMarker < secondString.Length))\n {\n if (firstMarker >= firstString.Length)\n {\n return -1;\n }\n else if (secondMarker >= secondString.Length)\n {\n return 1;\n }\n char firstCh = firstString[firstMarker];\n char secondCh = secondString[secondMarker];\n\n StringBuilder thisChunk = new StringBuilder();\n StringBuilder thatChunk = new StringBuilder();\n\n while ((firstMarker < firstString.Length) && (thisChunk.Length == 0 || InChunk(firstCh, thisChunk[0])))\n {\n thisChunk.Append(firstCh);\n firstMarker++;\n\n if (firstMarker < firstString.Length)\n {\n firstCh = firstString[firstMarker];\n }\n }\n\n while ((secondMarker < secondString.Length) && (thatChunk.Length == 0 || InChunk(secondCh, thatChunk[0])))\n {\n thatChunk.Append(secondCh);\n secondMarker++;\n\n if (secondMarker < secondString.Length)\n {\n secondCh = secondString[secondMarker];\n }\n }\n\n int result = 0;\n // If both chunks contain numeric characters, sort them numerically\n if (char.IsDigit(thisChunk[0]) && char.IsDigit(thatChunk[0]))\n {\n int thisNumericChunk = Convert.ToInt32(thisChunk.ToString());\n int thatNumericChunk = Convert.ToInt32(thatChunk.ToString());\n if (thisNumericChunk < thatNumericChunk)\n {\n result = -1;\n }\n\n if (thisNumericChunk > thatNumericChunk)\n {\n result = 1;\n }\n }\n else\n {\n result = thisChunk.ToString().CompareTo(thatChunk.ToString());\n }\n\n if (result != 0)\n {\n return result;\n }\n }\n\n return 0;\n }\n}\n" }, { "answer_id": 74411073, "author": "Bas H", "author_id": 10867491, "author_profile": "https://Stackoverflow.com/users/10867491", "pm_score": 0, "selected": false, "text": " public async Task<List<Fotos>> GetAllFotosDesending()\n {\n return (await firebase\n .Child(\"Foto/\")\n .OnceAsync<Fotos>()).Select(item => new Fotos\n {\n BalId = item.Object.BalId,\n RollNo = item.Object.RollNo,\n Foto = item.Object.Foto,\n Titel = item.Object.Titel,\n Fototekst = item.Object.Fototekst\n }).OrderByDescending(x => x.BalId).ToList();\n }\n public async void InitializeAsync()\n { \n Fotos = await GetAllFotosDesending(); \n }\n \n\n public MainViewModel()\n {\n InitializeAsync();\n }\n \n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20176092/" ]
74,395,110
<p>I a column which has dates in <code>yyyymdd</code> and <code>yyyymmdd</code> format. I want to convert the yyyymdd to yyyymmdd.</p> <p>for example I have dates <code>2022520</code> and <code>20220520</code>. how can I convert 202250 to 20220520 using SSIS?</p> <p>I tired the following</p> <ol> <li>using len I counted the number of characters</li> <li>then used if condition to add 0 before 5 in &quot;2022520&quot;. <code>[Character count]==7 ? &quot;0&quot;+ Substring([Extract Date],5,2) : [Extract Date]</code></li> <li>result of this expression <code>052</code></li> </ol>
[ { "answer_id": 74395414, "author": "FreakyAli", "author_id": 7462031, "author_profile": "https://Stackoverflow.com/users/7462031", "pm_score": 1, "selected": false, "text": "public class AlphanumComparator : IComparer<object>\n{\n private enum ChunkType { Alphanumeric, Numeric };\n\n private bool InChunk(char ch, char otherCh)\n {\n ChunkType type = ChunkType.Alphanumeric;\n\n if (char.IsDigit(otherCh))\n {\n type = ChunkType.Numeric;\n }\n\n return (type != ChunkType.Alphanumeric || !char.IsDigit(ch))\n && (type != ChunkType.Numeric || char.IsDigit(ch));\n }\n\n public int Compare(object x, object y)\n {\n string firstString = x as string;\n string secondString = y as string;\n if (string.IsNullOrWhiteSpace(firstString) || string.IsNullOrWhiteSpace(secondString))\n {\n return 0;\n }\n\n int firstMarker = 0, secondMarker = 0;\n\n while ((firstMarker < firstString.Length) || (secondMarker < secondString.Length))\n {\n if (firstMarker >= firstString.Length)\n {\n return -1;\n }\n else if (secondMarker >= secondString.Length)\n {\n return 1;\n }\n char firstCh = firstString[firstMarker];\n char secondCh = secondString[secondMarker];\n\n StringBuilder thisChunk = new StringBuilder();\n StringBuilder thatChunk = new StringBuilder();\n\n while ((firstMarker < firstString.Length) && (thisChunk.Length == 0 || InChunk(firstCh, thisChunk[0])))\n {\n thisChunk.Append(firstCh);\n firstMarker++;\n\n if (firstMarker < firstString.Length)\n {\n firstCh = firstString[firstMarker];\n }\n }\n\n while ((secondMarker < secondString.Length) && (thatChunk.Length == 0 || InChunk(secondCh, thatChunk[0])))\n {\n thatChunk.Append(secondCh);\n secondMarker++;\n\n if (secondMarker < secondString.Length)\n {\n secondCh = secondString[secondMarker];\n }\n }\n\n int result = 0;\n // If both chunks contain numeric characters, sort them numerically\n if (char.IsDigit(thisChunk[0]) && char.IsDigit(thatChunk[0]))\n {\n int thisNumericChunk = Convert.ToInt32(thisChunk.ToString());\n int thatNumericChunk = Convert.ToInt32(thatChunk.ToString());\n if (thisNumericChunk < thatNumericChunk)\n {\n result = -1;\n }\n\n if (thisNumericChunk > thatNumericChunk)\n {\n result = 1;\n }\n }\n else\n {\n result = thisChunk.ToString().CompareTo(thatChunk.ToString());\n }\n\n if (result != 0)\n {\n return result;\n }\n }\n\n return 0;\n }\n}\n" }, { "answer_id": 74411073, "author": "Bas H", "author_id": 10867491, "author_profile": "https://Stackoverflow.com/users/10867491", "pm_score": 0, "selected": false, "text": " public async Task<List<Fotos>> GetAllFotosDesending()\n {\n return (await firebase\n .Child(\"Foto/\")\n .OnceAsync<Fotos>()).Select(item => new Fotos\n {\n BalId = item.Object.BalId,\n RollNo = item.Object.RollNo,\n Foto = item.Object.Foto,\n Titel = item.Object.Titel,\n Fototekst = item.Object.Fototekst\n }).OrderByDescending(x => x.BalId).ToList();\n }\n public async void InitializeAsync()\n { \n Fotos = await GetAllFotosDesending(); \n }\n \n\n public MainViewModel()\n {\n InitializeAsync();\n }\n \n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20472322/" ]
74,395,119
<p>So I'm working on this code for practice and its supposed to take all the numbers between 2 &quot;-&quot;s and add them together. I'm supposed to convert the strings to ints as part of the problem. (This is my first time using this website so apologies if anything is formatted oddly)</p> <p>This is my first time using the Integer.parseInt() so maybe it has to do with that but I think it has to do with how I set up my index I'm not quite sure. this is everything I have so far. Ive tried to chnage around the order of the index as well as remove the +1 and even create a variable with just parts of the string but nothing seems to work. the error im getting reads as follows:</p> <pre><code>Exception in thread &quot;main&quot; java.lang.StringIndexOutOfBoundsException: begin 4, end 3, length 8 at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3751) at java.base/java.lang.String.substring(String.java:1907) at Social.chopAndAdd(Social.java:23) at Social.toString(Social.java:28) at Social.main(Social.java:33) </code></pre> <p>Below is what I currently have coded</p> <pre><code></code></pre> <pre><code>public class Social{ private String socialNum; private int sum; public Social(){ socialNum = null; sum = 0; } public Social(String soc){ socialNum = soc; } public void setSocial(String w){ socialNum = w; } public int chopAndAdd(){ sum = ((Integer.parseInt(socialNum.substring(0, socialNum.indexOf(&quot;-&quot;))))); sum = sum + (Integer.parseInt(socialNum.substring((socialNum.indexOf(&quot;-&quot;) + 1), socialNum.indexOf(&quot;&quot;)))); sum = sum + (Integer.parseInt(socialNum.substring((socialNum.lastIndexOf(&quot;-&quot;)), socialNum.length() - 1))); return sum; } public String toString(){ return &quot;SS# &quot; + socialNum + &quot; has a total of &quot; + chopAndAdd(); } public static void main( String args[] ){ Social test = new Social(); test.setSocial(&quot;102-2-12&quot;); System.out.print(test.toString()); //add test cases for each given input } } </code></pre> <pre><code></code></pre>
[ { "answer_id": 74395414, "author": "FreakyAli", "author_id": 7462031, "author_profile": "https://Stackoverflow.com/users/7462031", "pm_score": 1, "selected": false, "text": "public class AlphanumComparator : IComparer<object>\n{\n private enum ChunkType { Alphanumeric, Numeric };\n\n private bool InChunk(char ch, char otherCh)\n {\n ChunkType type = ChunkType.Alphanumeric;\n\n if (char.IsDigit(otherCh))\n {\n type = ChunkType.Numeric;\n }\n\n return (type != ChunkType.Alphanumeric || !char.IsDigit(ch))\n && (type != ChunkType.Numeric || char.IsDigit(ch));\n }\n\n public int Compare(object x, object y)\n {\n string firstString = x as string;\n string secondString = y as string;\n if (string.IsNullOrWhiteSpace(firstString) || string.IsNullOrWhiteSpace(secondString))\n {\n return 0;\n }\n\n int firstMarker = 0, secondMarker = 0;\n\n while ((firstMarker < firstString.Length) || (secondMarker < secondString.Length))\n {\n if (firstMarker >= firstString.Length)\n {\n return -1;\n }\n else if (secondMarker >= secondString.Length)\n {\n return 1;\n }\n char firstCh = firstString[firstMarker];\n char secondCh = secondString[secondMarker];\n\n StringBuilder thisChunk = new StringBuilder();\n StringBuilder thatChunk = new StringBuilder();\n\n while ((firstMarker < firstString.Length) && (thisChunk.Length == 0 || InChunk(firstCh, thisChunk[0])))\n {\n thisChunk.Append(firstCh);\n firstMarker++;\n\n if (firstMarker < firstString.Length)\n {\n firstCh = firstString[firstMarker];\n }\n }\n\n while ((secondMarker < secondString.Length) && (thatChunk.Length == 0 || InChunk(secondCh, thatChunk[0])))\n {\n thatChunk.Append(secondCh);\n secondMarker++;\n\n if (secondMarker < secondString.Length)\n {\n secondCh = secondString[secondMarker];\n }\n }\n\n int result = 0;\n // If both chunks contain numeric characters, sort them numerically\n if (char.IsDigit(thisChunk[0]) && char.IsDigit(thatChunk[0]))\n {\n int thisNumericChunk = Convert.ToInt32(thisChunk.ToString());\n int thatNumericChunk = Convert.ToInt32(thatChunk.ToString());\n if (thisNumericChunk < thatNumericChunk)\n {\n result = -1;\n }\n\n if (thisNumericChunk > thatNumericChunk)\n {\n result = 1;\n }\n }\n else\n {\n result = thisChunk.ToString().CompareTo(thatChunk.ToString());\n }\n\n if (result != 0)\n {\n return result;\n }\n }\n\n return 0;\n }\n}\n" }, { "answer_id": 74411073, "author": "Bas H", "author_id": 10867491, "author_profile": "https://Stackoverflow.com/users/10867491", "pm_score": 0, "selected": false, "text": " public async Task<List<Fotos>> GetAllFotosDesending()\n {\n return (await firebase\n .Child(\"Foto/\")\n .OnceAsync<Fotos>()).Select(item => new Fotos\n {\n BalId = item.Object.BalId,\n RollNo = item.Object.RollNo,\n Foto = item.Object.Foto,\n Titel = item.Object.Titel,\n Fototekst = item.Object.Fototekst\n }).OrderByDescending(x => x.BalId).ToList();\n }\n public async void InitializeAsync()\n { \n Fotos = await GetAllFotosDesending(); \n }\n \n\n public MainViewModel()\n {\n InitializeAsync();\n }\n \n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20472273/" ]
74,395,149
<p>I am working on the way to transform or parse elements of a plain-text file that contains multiple records that look like the following:</p> <p>US/CIV/JOHN SMITH/-/-/Z/-/2018-03-25/BLUE/ 159/AZ/AUDI/2015// US/CTR/BILL STONE/5/TEXT/G/AU24/2021-06-18/ GREEN/174/CO/BENZ/2019//</p> <p>These records separate elements using a forward-slash '/' and end each record using a double-slash '//'. Dashes '-' indicate a null value for that particular element.</p> <p>I think it might be best to transform these records into JSON but not sure of the best way to proceed.</p> <p>I haven't attempted this yet, nor have I been able to find any specific articles on it either.</p>
[ { "answer_id": 74395414, "author": "FreakyAli", "author_id": 7462031, "author_profile": "https://Stackoverflow.com/users/7462031", "pm_score": 1, "selected": false, "text": "public class AlphanumComparator : IComparer<object>\n{\n private enum ChunkType { Alphanumeric, Numeric };\n\n private bool InChunk(char ch, char otherCh)\n {\n ChunkType type = ChunkType.Alphanumeric;\n\n if (char.IsDigit(otherCh))\n {\n type = ChunkType.Numeric;\n }\n\n return (type != ChunkType.Alphanumeric || !char.IsDigit(ch))\n && (type != ChunkType.Numeric || char.IsDigit(ch));\n }\n\n public int Compare(object x, object y)\n {\n string firstString = x as string;\n string secondString = y as string;\n if (string.IsNullOrWhiteSpace(firstString) || string.IsNullOrWhiteSpace(secondString))\n {\n return 0;\n }\n\n int firstMarker = 0, secondMarker = 0;\n\n while ((firstMarker < firstString.Length) || (secondMarker < secondString.Length))\n {\n if (firstMarker >= firstString.Length)\n {\n return -1;\n }\n else if (secondMarker >= secondString.Length)\n {\n return 1;\n }\n char firstCh = firstString[firstMarker];\n char secondCh = secondString[secondMarker];\n\n StringBuilder thisChunk = new StringBuilder();\n StringBuilder thatChunk = new StringBuilder();\n\n while ((firstMarker < firstString.Length) && (thisChunk.Length == 0 || InChunk(firstCh, thisChunk[0])))\n {\n thisChunk.Append(firstCh);\n firstMarker++;\n\n if (firstMarker < firstString.Length)\n {\n firstCh = firstString[firstMarker];\n }\n }\n\n while ((secondMarker < secondString.Length) && (thatChunk.Length == 0 || InChunk(secondCh, thatChunk[0])))\n {\n thatChunk.Append(secondCh);\n secondMarker++;\n\n if (secondMarker < secondString.Length)\n {\n secondCh = secondString[secondMarker];\n }\n }\n\n int result = 0;\n // If both chunks contain numeric characters, sort them numerically\n if (char.IsDigit(thisChunk[0]) && char.IsDigit(thatChunk[0]))\n {\n int thisNumericChunk = Convert.ToInt32(thisChunk.ToString());\n int thatNumericChunk = Convert.ToInt32(thatChunk.ToString());\n if (thisNumericChunk < thatNumericChunk)\n {\n result = -1;\n }\n\n if (thisNumericChunk > thatNumericChunk)\n {\n result = 1;\n }\n }\n else\n {\n result = thisChunk.ToString().CompareTo(thatChunk.ToString());\n }\n\n if (result != 0)\n {\n return result;\n }\n }\n\n return 0;\n }\n}\n" }, { "answer_id": 74411073, "author": "Bas H", "author_id": 10867491, "author_profile": "https://Stackoverflow.com/users/10867491", "pm_score": 0, "selected": false, "text": " public async Task<List<Fotos>> GetAllFotosDesending()\n {\n return (await firebase\n .Child(\"Foto/\")\n .OnceAsync<Fotos>()).Select(item => new Fotos\n {\n BalId = item.Object.BalId,\n RollNo = item.Object.RollNo,\n Foto = item.Object.Foto,\n Titel = item.Object.Titel,\n Fototekst = item.Object.Fototekst\n }).OrderByDescending(x => x.BalId).ToList();\n }\n public async void InitializeAsync()\n { \n Fotos = await GetAllFotosDesending(); \n }\n \n\n public MainViewModel()\n {\n InitializeAsync();\n }\n \n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20471867/" ]
74,395,175
<p>We found this code online and we are trying to make it work with our project but need help with one small part...</p> <pre><code> function ajsearch () { var data = new FormData(); data.append(&quot;search&quot;, document.getElementById(&quot;search&quot;).value); data.append(&quot;ajax&quot;, 1); fetch(&quot;2-search.php&quot;, { method:&quot;POST&quot;, body:data }) .then(res =&gt; res.json()).then((results) =&gt; { var wrapper = document.getElementById(&quot;results&quot;); if (results.length &gt; 0) { wrapper.innerHTML = &quot;&quot;; for (let res of results) { let line = document.createElement(&quot;div&quot;); line.innerHTML = `&lt;a href='&lt;?= $baseurl ?&gt;/listings/${res[&quot;state&quot;]}/${res[&quot;slug&quot;]}'&gt;${res[&quot;city_name&quot;]}, ${res[&quot;state_name&quot;]}&lt;/a&gt;`; wrapper.appendChild(line); } } else { wrapper.innerHTML = &quot;No city or town found request it be added by using our &lt;a href='&lt;?= $baseurl ?&gt;/contact'&gt;&lt;strong&gt;contact form&lt;/strong&gt;&lt;/a&gt;&quot;; } }); return false; } </code></pre> <p>Now the problem is we need this</p> <pre><code>${res[&quot;state&quot;]} </code></pre> <p>To be all lower case and add a hyphon - where there is a space so it looks like this new-york...</p> <p>Any help would be appreciated.</p>
[ { "answer_id": 74395235, "author": "Nijat Mursali", "author_id": 10489887, "author_profile": "https://Stackoverflow.com/users/10489887", "pm_score": 2, "selected": true, "text": "-" }, { "answer_id": 74404078, "author": "MrX", "author_id": 9041793, "author_profile": "https://Stackoverflow.com/users/9041793", "pm_score": 0, "selected": false, "text": "${res[\"state\"].split(' ').join('-').toLowerCase()}\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9041793/" ]
74,395,195
<p>I have a list of the lists that contain strings, like so :</p> <pre><code>[['1 0'], ['2 0'], ['3 1 2']] </code></pre> <p>How can I convert it to an adjacency list in Python please like this: (all ints)</p> <pre><code>{ 1: 0, 2:0, 3: 1,2 } </code></pre> <p>My attempts so far have gotten me to this:</p> <pre><code>newlist = [] for word in linelist: word = word.split(&quot;,&quot;) newlist.append(word) print(newlist) </code></pre> <p>which produces this:</p> <pre><code>[['1 0'], ['2 0'], ['3 1 2']] </code></pre> <p>Thanks very much!</p>
[ { "answer_id": 74395241, "author": "jprebys", "author_id": 3268228, "author_profile": "https://Stackoverflow.com/users/3268228", "pm_score": 2, "selected": true, "text": "adj_dict = {}\nfor inner_list in outer_list:\n values = [int(x) for x in inner_list[0].split()]\n adj_dict[values[0]] = values[1:]\n" }, { "answer_id": 74395248, "author": "CumminUp07", "author_id": 8297962, "author_profile": "https://Stackoverflow.com/users/8297962", "pm_score": 0, "selected": false, "text": "res = {}\nfor e in a:\n res[e[0][0]] = ','.join(e[0][1::].strip().split(' '))\n" }, { "answer_id": 74395299, "author": "accdias", "author_id": 6789321, "author_profile": "https://Stackoverflow.com/users/6789321", "pm_score": 0, "selected": false, "text": ">>> s = [['1 0'], \n... ['2 0'], \n... ['3 1 2']]\n>>> \n>>> [{_[0]: _[1:]} for _ in [list(map(int, _[0].split())) for _ in s]]\n[{1: [0]}, {2: [0]}, {3: [1, 2]}]\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18354441/" ]
74,395,230
<p>I am trying to drop some columns that have less than 5 valid values. Here is an example dataset.</p> <pre><code>df &lt;- data.frame(id = c(1,2,3,4,5,6,7,8,9,10), i1 = c(0,1,1,1,1,0,0,1,NA,1), i2 = c(1,0,0,1,0,1,1,0,0,NA), i3 = c(NA,NA,NA,NA,NA,NA,NA,NA,NA,0), i4 = c(NA,1,NA,NA,NA,NA,NA,NA,1,NA)) &gt; df id i1 i2 i3 i4 1 1 0 1 NA NA 2 2 1 0 NA 1 3 3 1 0 NA NA 4 4 1 1 NA NA 5 5 1 0 NA NA 6 6 0 1 NA NA 7 7 0 1 NA NA 8 8 1 0 NA NA 9 9 NA 0 NA 1 10 10 1 NA 0 NA </code></pre> <p>in this case, columns <code>i3</code> and <code>i4</code> needs to be dropped from the data frame.</p> <p>How can I get the desired dataset below:</p> <pre><code>&gt; df id i1 i2 1 1 0 1 2 2 1 0 3 3 1 0 4 4 1 1 5 5 1 0 6 6 0 1 7 7 0 1 8 8 1 0 9 9 NA 0 10 10 1 NA </code></pre>
[ { "answer_id": 74395272, "author": "Santiago", "author_id": 13507658, "author_profile": "https://Stackoverflow.com/users/13507658", "pm_score": 4, "selected": true, "text": "df[colSums(!is.na(df)) >= 5]\n" }, { "answer_id": 74395274, "author": "Baraliuh", "author_id": 11157753, "author_profile": "https://Stackoverflow.com/users/11157753", "pm_score": 2, "selected": false, "text": "discard" }, { "answer_id": 74395277, "author": "Jilber Urbina", "author_id": 1315767, "author_profile": "https://Stackoverflow.com/users/1315767", "pm_score": 2, "selected": false, "text": "> df[, sapply(df, function(x) sum(is.na(x))) < 5]\n id i1 i2\n1 1 0 1\n2 2 1 0\n3 3 1 0\n4 4 1 1\n5 5 1 0\n6 6 0 1\n7 7 0 1\n8 8 1 0\n9 9 NA 0\n10 10 1 NA\n" }, { "answer_id": 74395883, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 1, "selected": false, "text": "select" }, { "answer_id": 74396048, "author": "Ricardo Semião e Castro", "author_id": 13048728, "author_profile": "https://Stackoverflow.com/users/13048728", "pm_score": 2, "selected": false, "text": "funs = list(\n colSums = function(df){df[colSums(!is.na(df)) >= nrow/10]},\n sapply = function(df){df[, sapply(df, function(x) sum(!is.na(x))) >= nrow/10]},\n discard = function(df){df %>% discard(~ sum(!is.na(.)) < nrow/10)},\n mutate = function(df){df %>% mutate(across(where(~ sum(!is.na(.)) < nrow/10), ~ NULL))},\n select = function(df){df %>% select(where(~ sum(!is.na(.)) >= nrow/10))})\n\nncol = 10000\nnrow = 100\ndf = replicate(ncol, sample(c(1:9, NA), nrow, TRUE)) %>% as_tibble()\n\navrtime = map_dbl(funs, function(f){\n duration = c()\n for(i in 1:10){\n t1 = Sys.time()\n f(df)\n t2 = Sys.time()\n duration[i] = as.numeric(t2 - t1)}\n \n return(mean(duration))})\n\navrtime[order(avrtime)]\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5933306/" ]
74,395,257
<p>I'm working on a Springboot app that includes a task that's executed on a schedule. It typically takes about two to three minutes to run.</p> <pre class="lang-java prettyprint-override"><code>@Scheduled(cron = &quot;* */30 * * * *&quot;) public void stageOfferUpdates() throws SQLException { ... } </code></pre> <p>We have a requirement to be able to kick off the execution of that task at any time by calling a rest endpoint. Is there a way my <code>@GET</code> method can programmatically kick this off and immediately return an <code>http 200 OK</code>?</p>
[ { "answer_id": 74395272, "author": "Santiago", "author_id": 13507658, "author_profile": "https://Stackoverflow.com/users/13507658", "pm_score": 4, "selected": true, "text": "df[colSums(!is.na(df)) >= 5]\n" }, { "answer_id": 74395274, "author": "Baraliuh", "author_id": 11157753, "author_profile": "https://Stackoverflow.com/users/11157753", "pm_score": 2, "selected": false, "text": "discard" }, { "answer_id": 74395277, "author": "Jilber Urbina", "author_id": 1315767, "author_profile": "https://Stackoverflow.com/users/1315767", "pm_score": 2, "selected": false, "text": "> df[, sapply(df, function(x) sum(is.na(x))) < 5]\n id i1 i2\n1 1 0 1\n2 2 1 0\n3 3 1 0\n4 4 1 1\n5 5 1 0\n6 6 0 1\n7 7 0 1\n8 8 1 0\n9 9 NA 0\n10 10 1 NA\n" }, { "answer_id": 74395883, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 1, "selected": false, "text": "select" }, { "answer_id": 74396048, "author": "Ricardo Semião e Castro", "author_id": 13048728, "author_profile": "https://Stackoverflow.com/users/13048728", "pm_score": 2, "selected": false, "text": "funs = list(\n colSums = function(df){df[colSums(!is.na(df)) >= nrow/10]},\n sapply = function(df){df[, sapply(df, function(x) sum(!is.na(x))) >= nrow/10]},\n discard = function(df){df %>% discard(~ sum(!is.na(.)) < nrow/10)},\n mutate = function(df){df %>% mutate(across(where(~ sum(!is.na(.)) < nrow/10), ~ NULL))},\n select = function(df){df %>% select(where(~ sum(!is.na(.)) >= nrow/10))})\n\nncol = 10000\nnrow = 100\ndf = replicate(ncol, sample(c(1:9, NA), nrow, TRUE)) %>% as_tibble()\n\navrtime = map_dbl(funs, function(f){\n duration = c()\n for(i in 1:10){\n t1 = Sys.time()\n f(df)\n t2 = Sys.time()\n duration[i] = as.numeric(t2 - t1)}\n \n return(mean(duration))})\n\navrtime[order(avrtime)]\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9671608/" ]
74,395,260
<p>I have tried looking for a way to create a dataframe of columns and their unique values. I know this has less use cases but would be a great way to get an initial idea of unique values. It would look something like this....</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>State</th> <th>County</th> <th>City</th> </tr> </thead> <tbody> <tr> <td>Colorado</td> <td>Denver</td> <td>Denver</td> </tr> <tr> <td>Colorado</td> <td>El Paso</td> <td>Colorado Springs</td> </tr> <tr> <td>Colorado</td> <td>Larimar</td> <td>Fort Collins</td> </tr> <tr> <td>Colorado</td> <td>Larimar</td> <td>Loveland</td> </tr> </tbody> </table> </div> <p>Turns into this...</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>State</th> <th>County</th> <th>City</th> </tr> </thead> <tbody> <tr> <td>Colorado</td> <td>Denver</td> <td>Denver</td> </tr> <tr> <td></td> <td>El Paso</td> <td>Colorado Springs</td> </tr> <tr> <td></td> <td>Larimar</td> <td>Fort Collins</td> </tr> <tr> <td></td> <td></td> <td>Loveland</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74395261, "author": "trey hannam", "author_id": 13972322, "author_profile": "https://Stackoverflow.com/users/13972322", "pm_score": 0, "selected": false, "text": "def create_unique_df(df) -> pd.DataFrame:\n \"\"\" take a dataframe and creates a new one containing unique values for each column\n note, it only works for two columns or more\n\n :param df: dataframe you want see unique values for\n :param type: pandas.DataFrame\n return: dataframe of columns with unique values\n \"\"\"\n # using list() allows us to combine lists down the line\n data_series = df.apply(lambda x: list( x.unique() ) )\n\n list_df = data_series.to_frame()\n\n # to create a df from lists they all neet to be the same leng. so we can append null \n # values\n # to lists and make them the same length. First find differenc in length of longest list and\n # the rest\n list_df['needed_nulls'] = list_df[0].str.len().max() - list_df[0].str.len()\n\n # Second create a column of lists with one None value\n list_df['null_list_placeholder'] = [[None] for _ in range(list_df.shape[0])]\n\n # Third multiply the null list times the difference to get a list we can add to the list of\n # unique values making all the lists the same length. Example: [None] * 3 == [None, None, \n # None]\n list_df['null_list_needed'] = list_df.null_list_placeholder * list_df.needed_nulls\n list_df['full_list'] = list_df[0] + list_df.null_list_needed\n\n unique_df = pd.DataFrame(\n list_df['full_list'].to_dict()\n )\n\n return unique_df\n" }, { "answer_id": 74395306, "author": "Umar.H", "author_id": 9375102, "author_profile": "https://Stackoverflow.com/users/9375102", "pm_score": 2, "selected": false, "text": "mask" }, { "answer_id": 74395520, "author": "Python16367225", "author_id": 16367225, "author_profile": "https://Stackoverflow.com/users/16367225", "pm_score": 1, "selected": false, "text": "import pandas as pd\n\ndf = pd.DataFrame({\n 'State': ['Colorado', 'Colorado', 'Colorado', 'Colorado'], \n 'County': ['Denver', 'El Paso', 'Larimar', 'Larimar'],\n 'City': ['Denver', 'Colorado Springs', 'Fort Collins', 'Loveland']\n})\n\ndf\n\n State County City\n0 Colorado Denver Denver\n1 Colorado El Paso Colorado Springs\n2 Colorado Larimar Fort Collins\n3 Colorado Larimar Loveland\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13972322/" ]
74,395,265
<p>I'm not an expert at all on this but I'm trying to create an option list so they can choose either 1/4, 1/2 or 3/4 from the ComboBox for the userform I have created. The Data comes from Sheet1 that perfectly shows the correct format for each value but when you run the form the ComboBox shows instead 0.25, 0.5 or 0.75.</p> <p>Example</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Column A</th> </tr> </thead> <tbody> <tr> <td>1/4</td> </tr> <tr> <td>1/2</td> </tr> <tr> <td>3/4</td> </tr> </tbody> </table> </div> <pre><code>Private Sub UserForm_Initialize() ComboBox1.List = Worksheets(&quot;Sheet1&quot;).Range(&quot;A1:A3&quot;).Value End Sub </code></pre> <p>I don't know what to do. I need them to show in fraction format in the simplest way possible. Any ideas how to fix this problem? Thanks</p>
[ { "answer_id": 74395375, "author": "Cyril", "author_id": 3233363, "author_profile": "https://Stackoverflow.com/users/3233363", "pm_score": 2, "selected": false, "text": ".text" }, { "answer_id": 74396347, "author": "Tim Williams", "author_id": 478884, "author_profile": "https://Stackoverflow.com/users/478884", "pm_score": 2, "selected": false, "text": "Private Sub UserForm_Initialize()\n With Worksheets(\"Sheet1\")\n ComboBox1.List = .Evaluate(\"TEXT(A1:A3,\"\"# ?/?\"\")\")\n End With\nEnd Sub\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20472344/" ]
74,395,283
<p>I am able to view my site (html)in the browser but none of my mark-up is working. I have checked my stylesheet links for types, settings.py, but I am at a lost.<br /> When I run my site I am getting the below responses in my terminal.</p> <pre><code>[10/Nov/2022 20:46:23] &quot;GET / HTTP/1.1&quot; 200 168 [10/Nov/2022 20:46:23] &quot;GET /static/css/main.css HTTP/1.1&quot; 404 1795 [10/Nov/2022 20:46:23] &quot;GET /static/images/6%2Bcart.png HTTP/1.1&quot; 404 1810` </code></pre> <p>Here is code from my settings.py file:</p> <pre><code>STATIC_URL = 'static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] </code></pre> <p>Example of my css link in my html page</p> <pre><code>{% load static %} &lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;{% static 'css/main.css' %}&quot;&gt; </code></pre> <p>I have tried going over everything possible but cannot locate the issue, any and all feedback would be greatly appreciated. I am not allowed to post images yet so unfortunately, I could not include.</p> <p>I have re-coded, deleted and remade static folder, scoured the internet with no luck yet.</p>
[ { "answer_id": 74395718, "author": "ckabah", "author_id": 20472435, "author_profile": "https://Stackoverflow.com/users/20472435", "pm_score": 3, "selected": true, "text": "STATIC_URL = 'static/'\nSTATICFILES_DIRS = [os.path.join(BASE_DIR, 'static/')]\nSTATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # for deployment\n" }, { "answer_id": 74398394, "author": "Manoj Tolagekar", "author_id": 17808039, "author_profile": "https://Stackoverflow.com/users/17808039", "pm_score": 1, "selected": false, "text": "<link rel=\"stylesheet\" type=\"text/css\" href=\"{% static 'css/main.css' %}\">\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20472397/" ]
74,395,284
<p>I recently benchmarked my framework and noticed that it allocates tons of garbage.</p> <p>I'm using a <code>Channel&lt;T&gt;</code> and the <code>TryRead</code> or <code>ReadAsync</code> operation allocates memory every single call. So I exchanged that with a <code>BlockingCollection&lt;T&gt;</code> which also allocates memory during <code>TryTake</code>.</p> <p>I used a unbounded channel with a single writer/reader. And a normal <code>BlockingCollection&lt;T&gt;</code>.</p> <pre><code>// Each thread runs this, jobmeta is justa struct while (!token.IsCancellationRequested) { var jobMeta = await Reader.ReadAsync(token); // &lt;- allocs here jobMeta.Job.Execute(); jobMeta.JobHandle.Notify(); } </code></pre> <p>The profiler told me that all allocations are caused by the <code>ChannelReader.ReadAsync</code> method. Unfortunately I can't show the full code, however since I use them in a hot path, I need to avoid allocations at all cost.</p> <p>Are there any alternatives which do not allocate memory during read/write/get and behave the same (Concurrent classes for producer/consumer multithreading) ? How could I implement one by myself?</p>
[ { "answer_id": 74395718, "author": "ckabah", "author_id": 20472435, "author_profile": "https://Stackoverflow.com/users/20472435", "pm_score": 3, "selected": true, "text": "STATIC_URL = 'static/'\nSTATICFILES_DIRS = [os.path.join(BASE_DIR, 'static/')]\nSTATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # for deployment\n" }, { "answer_id": 74398394, "author": "Manoj Tolagekar", "author_id": 17808039, "author_profile": "https://Stackoverflow.com/users/17808039", "pm_score": 1, "selected": false, "text": "<link rel=\"stylesheet\" type=\"text/css\" href=\"{% static 'css/main.css' %}\">\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5801049/" ]
74,395,293
<p>My main function</p> <pre><code> for record in event[&quot;Records&quot;]: payload = json.loads(record[&quot;body&quot;]) if payload[&quot;action&quot;] != &quot;Create&quot;: continue issue_id = payload[&quot;documentId&quot;][&quot;id&quot;] issue = client.get_issue(issue_id) data_id, main_id = parse_issue(client, issue) </code></pre> <p>Error: <code>local variable 'issue' referenced before assignment</code> <code>data_id, main_id = parse_issue(client, issue)</code></p> <p>[Edited] I need to be able to pass issue as I am also using it to one of my function above. Should I place the <code>issue = client.get_issue(issue_id)</code> outside for loop? How to fix?</p> <pre><code>def parse_issue(client, issue): data_id = issue.data[&quot;id&quot;] main_id = issue.main_id ## More Code return data_id, main_id </code></pre>
[ { "answer_id": 74395358, "author": "Neposis", "author_id": 11717865, "author_profile": "https://Stackoverflow.com/users/11717865", "pm_score": 2, "selected": false, "text": "issue = 0\nfor record in event[\"Records\"]:\n payload = json.loads(record[\"body\"])\n if payload[\"action\"] != \"Create\":\n continue\n issue_id = payload[\"documentId\"][\"id\"]\n if issue_id is None:\n issue_id = payload[\"documentId\"][\"id\"]\n issue = sim_client.get_issue(issue_id)\n\ndata_id, main_id = parse_issue(client, issue)\n" }, { "answer_id": 74395396, "author": "kenntnisse", "author_id": 18318238, "author_profile": "https://Stackoverflow.com/users/18318238", "pm_score": 0, "selected": false, "text": "issue" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19396056/" ]
74,395,297
<p>I'm making a 2D game and I want my player when he is moving left and right based on the <strong>Input Key</strong> to switch the side of my player's sprite.</p> <p>The way I'm handling it so far which it works for now is by changing the local scale on the X-Axis like this:</p> <pre><code>void Update() { if (Input.GetKeyDown(KeyCode.A)) { transform.localScale = new Vector3(-1, 1, 1); } else if(Input.GetKeyDown(KeyCode.D)) { transform.localScale = new Vector3(1, 1, 1); } } </code></pre> <p>The default is for the player to face the right side but when he press the A button the player will look to the left side and when he press D it will look back to the right side.</p> <p>So far everything is good, but when I try to increase my player's size when he collects a power up everything is messed up.</p> <p>To increase the size I'm using the DOTween package which provides an easy way for scaling up an object like this:</p> <pre><code>transform.DOScale(new Vector3(2, 2, 2),1.5f); </code></pre> <p>After that I realise that messing with the scale it can become really messed up. My question is there any better way to handle the sprite side switch?</p>
[ { "answer_id": 74395469, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": true, "text": "Flip" }, { "answer_id": 74395532, "author": "Schuhbacca", "author_id": 4036213, "author_profile": "https://Stackoverflow.com/users/4036213", "pm_score": 0, "selected": false, "text": "Vector3 localScale;\nprivate boolIsFacingRight = true;\nvoid Update()\n{\n localScale = transform.localScale;\n if (Input.GetKeyDown(KeyCode.A))\n {\n localScale.x *= isFacingRight ? 1 : -1;\n isFacingRight = true;\n transform.localScale = localScale;\n }\n else if(Input.GetKeyDown(KeyCode.D))\n {\n localScale.x *= isFacingRight ? -1 : 1;\n isFacingRight = false;\n transform.localScale = localScale;\n }\n}\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16523060/" ]
74,395,303
<p>I have some python that needs to send a pickled numpy array to stdout. If I try to</p> <pre><code>numpy.save(sys.stdout.buffer, data, allow_pickle=False) </code></pre> <p>I get the following error</p> <pre><code>Traceback (most recent call last): File &quot;/home/thoth/work/TandbergLabs/2022/iot-rendezvous/picture-server/src/main/resources/com/ericsson/duluthMadScience/pictureServer/histogram.py&quot;, line 29, in &lt;module&gt; numpy.save(sys.stdout.buffer, data, allow_pickle=False) File &quot;&lt;__array_function__ internals&gt;&quot;, line 180, in save File &quot;/usr/lib/python3.10/site-packages/numpy/lib/npyio.py&quot;, line 502, in save format.write_array(fid, arr, allow_pickle=allow_pickle, File &quot;/usr/lib/python3.10/site-packages/numpy/lib/format.py&quot;, line 689, in write_array array.tofile(fp) OSError: obtaining file position failed </code></pre> <p>What writable file-like object can I pass to <code>numpy.save</code> that I can later fetch bytes from?</p>
[ { "answer_id": 74395502, "author": "Ahmed AEK", "author_id": 15649230, "author_profile": "https://Stackoverflow.com/users/15649230", "pm_score": 3, "selected": true, "text": "io.BytesIO" }, { "answer_id": 74395578, "author": "MysteRys337", "author_id": 18011181, "author_profile": "https://Stackoverflow.com/users/18011181", "pm_score": 1, "selected": false, "text": "binary mode" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/995935/" ]
74,395,324
<p>I have a collection where I want to find one data based on another object data:</p> <pre class="lang-js prettyprint-override"><code>const data = [ { _id :0, name:&quot;jane&quot;, joined : ISODate(&quot;2011-03-02&quot;), likes : 30, dislikes: 9}, { _id :1, name: &quot;joe&quot;, joined : ISODate(&quot;2012-07-02&quot;), likes : 40, dislikes: 07}, { _id : 2, name:&quot;Ant&quot;, joined : ISODate(&quot;2012-07-02&quot;), likes : 60, dislikes: 02} ] </code></pre> <p>From here I want to get the name who got most likes and I want to get the name who got maximum dislikes.</p> <p>My code is like this:</p> <pre class="lang-js prettyprint-override"><code>const parcel = await regionModel.aggregate([ { $match: { &quot;likes&quot;: { $gt: 0 }, } }, { $group: { likes: { $max: &quot;$likes&quot; }, dislikes: { $max: &quot;$dislikes&quot; } } } ]) </code></pre> <p>In this code, I can get the maximum <code>likes</code> value and maximum <code>likes</code>, but how can I get the <code>name</code> or whole object based on the max <code>likes</code> and max <code>dislikes</code>?</p> <p><strong>Required Output:</strong></p> <pre><code>likes: 60 MostLikedName: &quot;Ant&quot; ---OR--- { _id : 2, name:&quot;Ant&quot;, joined : ISODate(&quot;2012-07-02&quot;), likes : 60, dislikes: 02} dislikes. 09 mostDislikedName: &quot;Jane&quot; ---OR--- { _id :0, name:&quot;jane&quot;, joined : ISODate(&quot;2011-03-02&quot;), likes : 30, dislikes: 9} </code></pre> <p>I tried to sort the the document but I can sort the document based on dislike or like. Also I was wondering if I can use <code>$cond</code> here.</p>
[ { "answer_id": 74395502, "author": "Ahmed AEK", "author_id": 15649230, "author_profile": "https://Stackoverflow.com/users/15649230", "pm_score": 3, "selected": true, "text": "io.BytesIO" }, { "answer_id": 74395578, "author": "MysteRys337", "author_id": 18011181, "author_profile": "https://Stackoverflow.com/users/18011181", "pm_score": 1, "selected": false, "text": "binary mode" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16665539/" ]
74,395,361
<p>If the discrimated union is defined as follows:</p> <pre><code>enum KEYS { A= 'a', B= 'b' ... } type TUnion = | { keyType: KEYS.A; items: AType[] | { keyType: KEYS.B; items: BType[] ... </code></pre> <p>How can I define the type for an object where the key is a <code>keyType</code> and the value is the matching ìtems`, without doing it all manually?</p> <p>The manual approach seems to work but repeats the key-to-possible values relation:</p> <pre><code>type TObj = { [KEYS.A]?: AType[] [KEYS.B]?: BType[] ... } </code></pre>
[ { "answer_id": 74395499, "author": "caTS", "author_id": 18244921, "author_profile": "https://Stackoverflow.com/users/18244921", "pm_score": 3, "selected": true, "text": "type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? { [K in keyof I]: I[K] } : never;\n\ntype FromDiscriminatedUnion<U, K extends keyof U, V extends keyof U> = UnionToIntersection<U extends U ? {\n [_ in U[K] & PropertyKey]: U[V];\n} : never>;\n" }, { "answer_id": 74395504, "author": "Slava Knyazev", "author_id": 4088472, "author_profile": "https://Stackoverflow.com/users/4088472", "pm_score": 2, "selected": false, "text": "enum KEYS {\n A = \"a\",\n B = \"b\",\n}\n\ntype AType = number;\ntype BType = string;\n\ntype TUnion = { keyType: KEYS.A; items: AType[] } | { keyType: KEYS.B; items: BType[] };\n\ntype UnionToIntersection<U> = \n (U extends any ? (k: U)=>void : never) extends ((k: infer I)=>void) ? I : never\n\ntype ToKeyValue<U extends TUnion> = U extends TUnion ? { [key in U['keyType']]: U['items']} : never;\n\ntype mapped = UnionToIntersection<ToKeyValue<TUnion>>\n\n\ntype optionalMapped = Partial<UnionToIntersection<ToKeyValue<TUnion>>>\n" }, { "answer_id": 74395576, "author": "kaya3", "author_id": 12299000, "author_profile": "https://Stackoverflow.com/users/12299000", "pm_score": 2, "selected": false, "text": "TObj" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1827442/" ]
74,395,366
<p>Writing a function to check an input string for numbers, and if there are any, to randomize every digit, letter, and punctuation mark in the string. (i.e. &quot;hello3.14&quot; might become &quot;jdbme6?21&quot;)</p> <p>This code works (and the goal makes sense in context, I promise) but it sure seems redundant. Not sure how to tighten it up. The ELSE is just there to make me feel better about loose ends, but it's probably disposable.</p> <p>My primary question is, Can this method be condensed? Secondary question, Is there a completely different, better way I should do this? Thanks for any guidance.</p> <pre><code>import random import string def new_thing(old_thing): output_str = '' if any(char.isdigit() for char in old_thing): for char in old_thing: get_new = char if char in string.digits: while get_new == char: get_new = random.choice(string.digits) output_str += get_new elif char in string.ascii_lowercase: while get_new == char: get_new = random.choice(string.ascii_lowercase) output_str += get_new elif char in string.punctuation: while get_new == char: get_new = random.choice(string.punctuation) output_str += get_new else: output_str += char print(output_str) else: print(&quot;lol no numbers gg&quot;) new_thing(input(&quot;Type a thing: &quot;).lower()) </code></pre>
[ { "answer_id": 74395499, "author": "caTS", "author_id": 18244921, "author_profile": "https://Stackoverflow.com/users/18244921", "pm_score": 3, "selected": true, "text": "type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? { [K in keyof I]: I[K] } : never;\n\ntype FromDiscriminatedUnion<U, K extends keyof U, V extends keyof U> = UnionToIntersection<U extends U ? {\n [_ in U[K] & PropertyKey]: U[V];\n} : never>;\n" }, { "answer_id": 74395504, "author": "Slava Knyazev", "author_id": 4088472, "author_profile": "https://Stackoverflow.com/users/4088472", "pm_score": 2, "selected": false, "text": "enum KEYS {\n A = \"a\",\n B = \"b\",\n}\n\ntype AType = number;\ntype BType = string;\n\ntype TUnion = { keyType: KEYS.A; items: AType[] } | { keyType: KEYS.B; items: BType[] };\n\ntype UnionToIntersection<U> = \n (U extends any ? (k: U)=>void : never) extends ((k: infer I)=>void) ? I : never\n\ntype ToKeyValue<U extends TUnion> = U extends TUnion ? { [key in U['keyType']]: U['items']} : never;\n\ntype mapped = UnionToIntersection<ToKeyValue<TUnion>>\n\n\ntype optionalMapped = Partial<UnionToIntersection<ToKeyValue<TUnion>>>\n" }, { "answer_id": 74395576, "author": "kaya3", "author_id": 12299000, "author_profile": "https://Stackoverflow.com/users/12299000", "pm_score": 2, "selected": false, "text": "TObj" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19602996/" ]
74,395,422
<p>I am making a sidebar for my site and I want the side bar to fill the rest of the screen but also scroll separate to the right of the screen when it overflows with other elements inside. When I use 100% for the height the element only goes to the height of the last element inside of it.</p> <p>I am trying to get it to fill the rest of the screen as I stated previously but it only goes to not all the way.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { margin: 0; font-family: Arial, Helvetica, sans-serif; } .main { margin-left: 345px; border: 0px solid #ffffff; padding: 0px 0px; flex-direction: column; align-content: center; text-align: center; width: 450px; } .card { display: inline-block; width: 400px; height: 160px; background-color: #404040; border: 1px solid #404040; border-radius: 4px; margin: 0px; margin-top: 20px; text-decoration: none; } .toptext { display: inline-block; width: 400px; height: 45px; color: #ffffff; background-color: #ffffff; border: 1px solid #ffffff; border-radius: 4px; margin: 0px; margin-top: 5px; text-decoration: none; text-align: left; } .toptext h1 { font-size: 20px; margin-left: 0px; margin-top: 1px; color: #404040; } .toptext p { font-size: 12px; margin-left: 0px; margin-top: -10px; color: #404040; } .flexcolumn { flex-direction: column; } .leftmain { height: 100%; width: 325px; padding: 0px 10px; flex-direction: column; align-content: center; background-color: #333333; overflow: scroll; } .leftmain p { float: left; color: #ffffff; text-align: left; padding: 0px 10px; text-decoration: none; font-size: 12px; line-height: 25px; border-radius: 4px; background-color: #333333; width: 300px; } .leftmain p:hover { background-color: #404040; color: #ffffff; } .header { overflow: hidden; background-color: #404040; padding: 10px 10px; height: 36px; text-align: center; } .header-right { float: right; padding: 0px 0px; } .header a { float: left; color: #ffffff; text-align: center; padding: 5px 10px; text-decoration: none; font-size: 18px; line-height: 25px; border-radius: 4px; align-content: center; } .header a:hover { background-color: #333333; color: #ffffff; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="header"&gt; &lt;a href="#test" id="nameOfCompany"&gt; My Paper Company&lt;/a&gt; &lt;div class="header-right"&gt; &lt;a href="#settings"&gt;Settings&lt;/a&gt; &lt;a href="#contact"&gt;Contact&lt;/a&gt; &lt;a href="#donate"&gt;Donate&lt;/a&gt; &lt;div class="flexcolumn"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="leftmain" class="leftmain"&gt; &lt;p id="button" div="leftmain" onclick='show("htpmain")'&gt; How To Play&lt;/p&gt; &lt;/div&gt; &lt;center&gt; &lt;div id=htpmain class="main"&gt; &lt;div class="toptext"&gt; &lt;h1&gt; How To Play &lt;/h1&gt; &lt;p&gt;This guide will get you start the game and will be helpful to grasp everything you need to do. &lt;/p&gt; &lt;/div&gt; &lt;div class="card" /&gt; &lt;/div&gt; &lt;/center&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74395499, "author": "caTS", "author_id": 18244921, "author_profile": "https://Stackoverflow.com/users/18244921", "pm_score": 3, "selected": true, "text": "type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? { [K in keyof I]: I[K] } : never;\n\ntype FromDiscriminatedUnion<U, K extends keyof U, V extends keyof U> = UnionToIntersection<U extends U ? {\n [_ in U[K] & PropertyKey]: U[V];\n} : never>;\n" }, { "answer_id": 74395504, "author": "Slava Knyazev", "author_id": 4088472, "author_profile": "https://Stackoverflow.com/users/4088472", "pm_score": 2, "selected": false, "text": "enum KEYS {\n A = \"a\",\n B = \"b\",\n}\n\ntype AType = number;\ntype BType = string;\n\ntype TUnion = { keyType: KEYS.A; items: AType[] } | { keyType: KEYS.B; items: BType[] };\n\ntype UnionToIntersection<U> = \n (U extends any ? (k: U)=>void : never) extends ((k: infer I)=>void) ? I : never\n\ntype ToKeyValue<U extends TUnion> = U extends TUnion ? { [key in U['keyType']]: U['items']} : never;\n\ntype mapped = UnionToIntersection<ToKeyValue<TUnion>>\n\n\ntype optionalMapped = Partial<UnionToIntersection<ToKeyValue<TUnion>>>\n" }, { "answer_id": 74395576, "author": "kaya3", "author_id": 12299000, "author_profile": "https://Stackoverflow.com/users/12299000", "pm_score": 2, "selected": false, "text": "TObj" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20471402/" ]
74,395,439
<p>I have my react frontend which is very basic right now as i just want to retrieve some data from my backend api written in node js which calls and external api the data is fetched properly to the backend as I have tested it by printing the data. The issue is that my promise on the frontend is never resolved meaning the data is never fetched</p> <p>frontend code so far:</p> <pre><code>import &quot;./App.css&quot;; import axios from &quot;axios&quot;; function App() { const getDataPromise = async () =&gt; { const response = await axios.get( &quot;http://localhost:8800/api/auth/data&quot; ); console.log(&quot;ACTIVITY RESPONSE = &quot;, response); //return data; }; const getActivities = async () =&gt; { const promiseData = await getDataPromise() // NEVER RESOLVES console.log(&quot;Promise data = &quot;, promiseData); //getDataPromise().then((res) =&gt; console.log(&quot;RES = &quot;, res)); //} }; return ( &lt;div className=&quot;App&quot;&gt; &lt;button onClick={getActivities}&gt;Get All Data&lt;/button&gt; &lt;/div&gt; ); } export default App; </code></pre> <p>backend section of code with api link replaced with text:</p> <pre><code> async function getDataPromise() { const link = `externalAPI`; const response = await axios.get(link); console.log(&quot;Response = &quot;, response.data[0]); return response.data[0]; } router.get(&quot;/data&quot;, async (req, res) =&gt; { const data = await getDataPromise(); console.log(&quot;data = &quot;, data); return data; }); </code></pre> <p>Does anyone see my issue why my frontend promise when the getData button is clicked never resolves so the promiseData value is eventually printed</p>
[ { "answer_id": 74395546, "author": "JigolKa", "author_id": 16651308, "author_profile": "https://Stackoverflow.com/users/16651308", "pm_score": -1, "selected": false, "text": "<button onClick={async () => { await getActivities() }}>Get All Data</button>\n" }, { "answer_id": 74439660, "author": "Alexey Ushakov", "author_id": 20467532, "author_profile": "https://Stackoverflow.com/users/20467532", "pm_score": -1, "selected": false, "text": "router.get(\"/data\", async (req, res) => {\n\n const data = await getDataPromise();\n console.log(\"data = \", data);\n return data;\n});\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14712903/" ]
74,395,451
<p>I am using the following terraform to create windows EC2 instance. The instance is launched successfully, but in AWS console I see hyphenated name for EC2 instance.<br /> For brevity purpose I have removed some TF code</p> <p><a href="https://i.stack.imgur.com/8EvzS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8EvzS.png" alt="enter image description here" /></a></p> <pre><code>resource &quot;aws_launch_template&quot; &quot;server_launch_template&quot; { name = &quot;my-launch-template&quot; image_id = &quot;my-windows-ami-id&quot; instance_type = &quot;t3.medium&quot; key_name = &quot;my-keypair&quot; vpc_security_group_ids = [var.security_group_id] iam_instance_profile { arn = aws_iam_instance_profile.my_instance.arn } tag_specifications { resource_type = &quot;instance&quot; tags = module.tags.mytags } lifecycle { create_before_destroy = true } } resource &quot;aws_autoscaling_group&quot; &quot;server_autoscaling_group&quot; { name = &quot;my autoscaling group&quot; max_size = 1 min_size = 1 desired_capacity = 1 vpc_zone_identifier = [var.subnet_id] wait_for_capacity_timeout = var.wait_for_capacity health_check_type = &quot;EC2&quot; dynamic &quot;tag&quot; { #some code here } launch_template { id = aws_launch_template.server_launch_template.id version = &quot;$Latest&quot; } lifecycle { create_before_destroy = true } } </code></pre> <p>How and where do I specify instance name in the launch template?</p>
[ { "answer_id": 74395546, "author": "JigolKa", "author_id": 16651308, "author_profile": "https://Stackoverflow.com/users/16651308", "pm_score": -1, "selected": false, "text": "<button onClick={async () => { await getActivities() }}>Get All Data</button>\n" }, { "answer_id": 74439660, "author": "Alexey Ushakov", "author_id": 20467532, "author_profile": "https://Stackoverflow.com/users/20467532", "pm_score": -1, "selected": false, "text": "router.get(\"/data\", async (req, res) => {\n\n const data = await getDataPromise();\n console.log(\"data = \", data);\n return data;\n});\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3862378/" ]
74,395,467
<p>I have made a Intellij project and tried to commit it to Github and got this error:</p> <blockquote> <p>Another git process seems to be running in this repository, e.g. an editor opened by 'git commit'. Please make sure all processes are terminated then try again. If it still fails, a git process may have crashed in this repository earlier: remove the file manually to continue.</p> </blockquote> <p>I have no idea what to do. There aren't any other git processes, and I don't know what &quot;git commit&quot; is.</p> <p>I tried some things and nothing changed.</p>
[ { "answer_id": 74395546, "author": "JigolKa", "author_id": 16651308, "author_profile": "https://Stackoverflow.com/users/16651308", "pm_score": -1, "selected": false, "text": "<button onClick={async () => { await getActivities() }}>Get All Data</button>\n" }, { "answer_id": 74439660, "author": "Alexey Ushakov", "author_id": 20467532, "author_profile": "https://Stackoverflow.com/users/20467532", "pm_score": -1, "selected": false, "text": "router.get(\"/data\", async (req, res) => {\n\n const data = await getDataPromise();\n console.log(\"data = \", data);\n return data;\n});\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20472533/" ]
74,395,496
<p>I`m trying to create a profile screen for my website with an uploaded profile picture. I want the user's uploaded image to fill the container. As this would ensure that all of the profile pictures are the same size and in the same place</p> <pre><code>&lt;div class=&quot;row d-flex justify-content-center&quot;&gt; &lt;div class=&quot;col-4 align-self-center border border-danger&quot; style=&quot;width: 190px ;height: 190px; border-radius:70%;&quot;&gt; @if ($profile_picture != null) &lt;img src=&quot;{{ $profile_picture }}&quot; style=&quot;border-radius:70% ;width:auto; height:auto; object-fit: fill;&quot;&gt; @else &lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot; width=&quot;auto&quot; height=&quot;auto&quot; fill=&quot;currentColor&quot; class=&quot;bi bi-person-circle&quot; viewBox=&quot;0 0 16 16&quot;&gt; &lt;path d=&quot;M11 6a3 3 0 1 1-6 0 3 3 0 0 1 6 0z&quot;/&gt; &lt;path fill-rule=&quot;evenodd&quot; d=&quot;M0 8a8 8 0 1 1 16 0A8 8 0 0 1 0 8zm8-7a7 7 0 0 0-5.468 11.37C3.242 11.226 4.805 10 8 10s4.757 1.225 5.468 2.37A7 7 0 0 0 8 1z&quot;/&gt; &lt;/svg&gt; &lt;i class=&quot;bi bi-person-circle&quot;&gt;&lt;/i&gt; @endif &lt;/div&gt; &lt;/div&gt; </code></pre> <p>The current code makes it look like this(I put a border on the container to make it easier to see)</p> <p><a href="https://i.stack.imgur.com/j1ADZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/j1ADZ.png" alt="Current look" /></a></p>
[ { "answer_id": 74395876, "author": "Timothy Louwet", "author_id": 8722338, "author_profile": "https://Stackoverflow.com/users/8722338", "pm_score": 0, "selected": false, "text": "<div class=\"d-flex justify-content-center\">\n <div class=\"border border-danger\" style=\"width: 190px;height: 190px;border-radius:70%;\">\n @if ($profile_picture != null)\n <img src=\"{{ $profile_picture }}\" style=\"border-radius:70%;width: 100%;height:auto;\">\n @else\n <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"auto\" height=\"auto\" fill=\"currentColor\" class=\"bi bi-person-circle\" viewBox=\"0 0 16 16\">\n <path d=\"M11 6a3 3 0 1 1-6 0 3 3 0 0 1 6 0z\"/>\n <path fill-rule=\"evenodd\" d=\"M0 8a8 8 0 1 1 16 0A8 8 0 0 1 0 8zm8-7a7 7 0 0 0-5.468 11.37C3.242 11.226 4.805 10 8 10s4.757 1.225 5.468 2.37A7 7 0 0 0 8 1z\"/>\n </svg>\n <i class=\"bi bi-person-circle\"></i>\n @endif\n </div>\n</div>\n" }, { "answer_id": 74397267, "author": "Boatti", "author_id": 19192614, "author_profile": "https://Stackoverflow.com/users/19192614", "pm_score": 2, "selected": true, "text": "#pic {\n background: no-repeat url(\"https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/dog-puppy-on-garden-royalty-free-image-1586966191.jpg?crop=1.00xw:0.669xh;0,0.190xh&resize=640:*\");\n width: 200px;\n background-size: cover;\n background-position: 60% 10%;\n height: 200px;\n border: 2px solid red;\n border-radius: 200px;\n}" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17732797/" ]
74,395,559
<p>I have a list like <code>[&quot;A&quot;, &quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;, &quot;D&quot;, &quot;E&quot;]</code> and I want to delete completely elements which occur more then once.</p> <p>In this case the output would be <code>[&quot;B&quot;, &quot;C&quot;, &quot;E&quot;]</code></p> <p>I've been looking at using <code>Enum.dedup</code>. So far the best I've come up with is N^2 algorithms which find the duplicates and then filter again.</p> <p>What is the best idiomatic Elixir way to accomplish this?</p>
[ { "answer_id": 74396509, "author": "Adam Millerchip", "author_id": 1225617, "author_profile": "https://Stackoverflow.com/users/1225617", "pm_score": 1, "selected": false, "text": "--" }, { "answer_id": 74396683, "author": "sabiwara", "author_id": 13979518, "author_profile": "https://Stackoverflow.com/users/13979518", "pm_score": 2, "selected": false, "text": "Enum.frequencies/1" }, { "answer_id": 74397932, "author": "Dogbert", "author_id": 320615, "author_profile": "https://Stackoverflow.com/users/320615", "pm_score": 2, "selected": false, "text": "O(n log n)" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5240483/" ]
74,395,572
<p>I need to copy all data from one column <code>customerId</code> to another new column (<code>customerIds</code> - which is in different format) in the same table. There is a column called <code>customerId</code> whose type is <code>bigint</code> and I need to copy data from this column to <code>customerIds</code> whose data type is <code>bigint[]</code>.</p> <p>Is there any way to do this in postgres sql? I know how to copy data from one column to other column which is in same format but not sure how to do this when new column is array.</p> <p>Same table and column is in same format.</p> <pre><code>UPDATE table_name SET customerId = customerIds </code></pre>
[ { "answer_id": 74395648, "author": "nbk", "author_id": 5193536, "author_profile": "https://Stackoverflow.com/users/5193536", "pm_score": 2, "selected": true, "text": "CREATE TABLE table_name (customerId BIGINT, customerIds BIGINT[]);\n\n\nINSERT INTO table_name VALUES(1);\nINSERT INTO table_name VALUES(2);\nINSERT INTO table_name VALUES(3);\nINSERT INTO table_name VALUES(4);\nINSERT INTO table_name VALUES(5);\n\nUPDATE table_name SET customerIds[1] = customerId ;\n\n\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18393248/" ]
74,395,574
<p>I'm writing a script to print out some info scraped from a certain website, I'm using the <code>.includes()</code> to find and print a number if that number falls inside a certain range from 1,000 to 100,000 but I can't figure out how to do that at all. The solution I'm trying right now is long and redundant and not even working.</p> <p><strong>Code</strong></p> <pre><code>const numShare = await page.$$eval(&quot;.FormData&quot;, els =&gt; els.find(e =&gt; e.textContent.includes(',000' || ',9' || ',8' || ',7' || ',6' || ',5' || ',4' || ',3' || ',2' || ',1')) .parentNode .textContent .trim() ); return numShare; </code></pre> <p>One other thing I tried before is just using <code>.includes(',000')</code>, which worked but it only gave me stricly numbers with a comma and 3 zeros after it. What I want is for it to find any number from 1,000 to 100,000 or with the format &quot;x,xxx to xxx,xxx&quot;. Would this be possible?</p> <p><strong>Edit, what I'm trying</strong></p> <pre><code> const shares = document.querySelector(&quot;.FormData&quot;); return { shares: shares.parentNode.nextElementSibling.nextElementSibling.textContent, }; }); return numShare.shares;``` </code></pre>
[ { "answer_id": 74395660, "author": "Sanusi hassan", "author_id": 10944954, "author_profile": "https://Stackoverflow.com/users/10944954", "pm_score": 0, "selected": false, "text": "// helper\nfunction range(start, end) {\n return Array(end - start + 1).fill().map((_, idx) => start + idx)\n}\nlet values = range(1000, 10000);\n" }, { "answer_id": 74395785, "author": "ggorlen", "author_id": 6243352, "author_profile": "https://Stackoverflow.com/users/6243352", "pm_score": 3, "selected": true, "text": "const numShare = await page.$$eval(\".FormData\", els =>\n els.find(e => {\n const n = +e.textContent.trim().replace(/,/g, \"\");\n return n >= 1000 && n <= 100000;\n })\n .parentNode\n .textContent\n .trim()\n);\n" }, { "answer_id": 74395859, "author": "Nico", "author_id": 8760866, "author_profile": "https://Stackoverflow.com/users/8760866", "pm_score": 1, "selected": false, "text": "function isInRange(stringNum) {\n const unformattedNum = stringNum.trim().split(\", \").join(\"\").split(\",\").join(\"\");\n // Or if you're ok with only supporting browsers from 2020 onwards...\n // const unformattedNum = stringNumber.trim().replaceAll(\", \", \"\").replaceAll(\",\" , \"\");\n\n const parsed = parseInt(unformattedNum); // Assuming these are always whole numbers, otherwise use parseFloat instead\n return parsed >= 1000 && parsed <= 100000;\n}\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17164833/" ]
74,395,581
<p>Im tryng to repeat react element for certain amount of times. I have used for loop before and it was working with simple HTML elements. Now it wont work, constantly getting error that 'fields' array is undefined. Here is my code:</p> <pre><code>import { useRef, useState } from 'react'; import SecondForm from './SecondForm'; function App() { const inputRef = useRef(null); [fields, setFields] = useState([]); const setFields = () =&gt; { let numberOfAngles = inputRef.current.value; for (let i = 1; i &lt;= numberOfAngles; i++) { fields.push(&lt;SecondForm id={i} key={i}&gt;&lt;/SecondForm&gt;); } }; return ( &lt;div className=&quot;app&quot;&gt; &lt;h1&gt;Check is point inide of polygon or not&lt;/h1&gt; &lt;div className=&quot;start-form&quot;&gt; &lt;p&gt;Select number from 3 to 10 for number of Polygon angles&lt;/p&gt; &lt;input type=&quot;number&quot; id=&quot;nr-of-angles&quot; name=&quot;nr-ofangles&quot; min=&quot;3&quot; max=&quot;10&quot; ref={inputRef} &gt;&lt;/input&gt; &lt;button className=&quot;btn&quot; onClick={setFields}&gt; Sumbit &lt;/button&gt; &lt;/div&gt; {fields ? fields : null} &lt;/div&gt; ); } </code></pre> <p>I also have tried with .map but still getting same error... Any help is welcome.</p>
[ { "answer_id": 74395660, "author": "Sanusi hassan", "author_id": 10944954, "author_profile": "https://Stackoverflow.com/users/10944954", "pm_score": 0, "selected": false, "text": "// helper\nfunction range(start, end) {\n return Array(end - start + 1).fill().map((_, idx) => start + idx)\n}\nlet values = range(1000, 10000);\n" }, { "answer_id": 74395785, "author": "ggorlen", "author_id": 6243352, "author_profile": "https://Stackoverflow.com/users/6243352", "pm_score": 3, "selected": true, "text": "const numShare = await page.$$eval(\".FormData\", els =>\n els.find(e => {\n const n = +e.textContent.trim().replace(/,/g, \"\");\n return n >= 1000 && n <= 100000;\n })\n .parentNode\n .textContent\n .trim()\n);\n" }, { "answer_id": 74395859, "author": "Nico", "author_id": 8760866, "author_profile": "https://Stackoverflow.com/users/8760866", "pm_score": 1, "selected": false, "text": "function isInRange(stringNum) {\n const unformattedNum = stringNum.trim().split(\", \").join(\"\").split(\",\").join(\"\");\n // Or if you're ok with only supporting browsers from 2020 onwards...\n // const unformattedNum = stringNumber.trim().replaceAll(\", \", \"\").replaceAll(\",\" , \"\");\n\n const parsed = parseInt(unformattedNum); // Assuming these are always whole numbers, otherwise use parseFloat instead\n return parsed >= 1000 && parsed <= 100000;\n}\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18621629/" ]
74,395,592
<p>I'm trying to work with data sent from postman, array of objects. I need to write all data into database, so I use mapping of array, and get undefined</p> <pre><code>const providers = await req.body.providers.map((provider) =&gt; { ProviderService.createProvider(provider.name, container._id); }); Promise.all(providers).then((value) =&gt; { console.log(value); }); </code></pre> <p>I get from console log array of undefined, but items are creating in Data Base, I know I have mistake in asynchronous functions, but I don't really understand - where</p> <p>Thank you for answer</p>
[ { "answer_id": 74395660, "author": "Sanusi hassan", "author_id": 10944954, "author_profile": "https://Stackoverflow.com/users/10944954", "pm_score": 0, "selected": false, "text": "// helper\nfunction range(start, end) {\n return Array(end - start + 1).fill().map((_, idx) => start + idx)\n}\nlet values = range(1000, 10000);\n" }, { "answer_id": 74395785, "author": "ggorlen", "author_id": 6243352, "author_profile": "https://Stackoverflow.com/users/6243352", "pm_score": 3, "selected": true, "text": "const numShare = await page.$$eval(\".FormData\", els =>\n els.find(e => {\n const n = +e.textContent.trim().replace(/,/g, \"\");\n return n >= 1000 && n <= 100000;\n })\n .parentNode\n .textContent\n .trim()\n);\n" }, { "answer_id": 74395859, "author": "Nico", "author_id": 8760866, "author_profile": "https://Stackoverflow.com/users/8760866", "pm_score": 1, "selected": false, "text": "function isInRange(stringNum) {\n const unformattedNum = stringNum.trim().split(\", \").join(\"\").split(\",\").join(\"\");\n // Or if you're ok with only supporting browsers from 2020 onwards...\n // const unformattedNum = stringNumber.trim().replaceAll(\", \", \"\").replaceAll(\",\" , \"\");\n\n const parsed = parseInt(unformattedNum); // Assuming these are always whole numbers, otherwise use parseFloat instead\n return parsed >= 1000 && parsed <= 100000;\n}\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17676671/" ]
74,395,599
<p>I have following regex:</p> <pre><code>/^(.*[^0-9])(.[a-z]+[0-9]+[a-z0-9]*|[0-9]+[a-z]+[a-z0-9]*{3,})(.*)$/gm </code></pre> <p>I want to match alphanumeric groups in an URL which are greater than two characters in length. So basically:</p> <p>In the URL: <code>/version/a1/type/eg1234/abc</code>, <code>eg1234</code> should match since it's alphanumeric and greater than two in length.</p> <p>However, while my alphanumeric match logic seems to be working fine, the length condition i.e. <code>{3,}</code> isn't being satisfied, as in e.g. <code>/version/a1/type/</code>, the regex also matches <code>a1</code> which it shouldn't as its less than two characters in length.</p> <p>How can I correct my regex?</p>
[ { "answer_id": 74395669, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 3, "selected": true, "text": "(?=\\d+[a-z][a-z\\d]*|[a-z\\d]*[a-z]\\d)[a-z\\d]{3,}\n" }, { "answer_id": 74395687, "author": "dawg", "author_id": 298607, "author_profile": "https://Stackoverflow.com/users/298607", "pm_score": 1, "selected": false, "text": "/\\b(?=[a-zA-Z0-9]{4,})(?=(?:[^\\/\\d]*\\d){4,})([^\\/]{3,})/\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/971741/" ]
74,395,602
<pre><code>procedure Summera(Int1: in Integer; Int2: in Integer; Summa: out Integer) is begin Put(&quot;Mata in ett heltal: &quot;); 48 Get(Int1); Put(&quot;Mata in ett heltal: &quot;); 50 Get(Int2); Summa:= Int1 + Int2; Put(&quot;Du matade in heltalet: &quot;); Put(Int1, Width=&gt;0); Put(&quot; och heltalet: &quot;); Put(Int2, Width=&gt;0); Put(&quot; och summan blev &quot;); end Summera; </code></pre> <p>I know there is something wrong but not really what. on the lines 48 and 50 which are I get the error message &quot;actual for item must be a variable.&quot; I am not allowed to put the string/text outside of the &quot;subprogram&quot; bit I have no idea how to make this work. Why do I get this error messeage?</p> <p>after begin I have this</p> <pre><code>Int1, Int2: Integer; Summa: Integer; begin Summera(Int1, Int2, Summa); Put(Summa); end program; </code></pre>
[ { "answer_id": 74395669, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 3, "selected": true, "text": "(?=\\d+[a-z][a-z\\d]*|[a-z\\d]*[a-z]\\d)[a-z\\d]{3,}\n" }, { "answer_id": 74395687, "author": "dawg", "author_id": 298607, "author_profile": "https://Stackoverflow.com/users/298607", "pm_score": 1, "selected": false, "text": "/\\b(?=[a-zA-Z0-9]{4,})(?=(?:[^\\/\\d]*\\d){4,})([^\\/]{3,})/\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20153118/" ]
74,395,610
<p>My first post here.</p> <p>So here is how it goes,</p> <p>The end goal is to place the New User in the specific OU, under its distinguished name as path. I can resolve this with one subsequent OU selections, but once there are multiple, I would like to avoid the subsequent scripting, because the number of subsequent OUs can change.</p> <p>Does anyone have an idea how to create a loop or any other solution that will continue to ask me through each layer of OU's until desired OU is chosen.</p> <p>For example, User will be employed as Safety in US, under state IL, in city Chicago My OU configuration would be as follows: US IL Chicago Safety Users</p> <p>I would like the script to loop through each layer until I've chosen Users, or a parameter to my liking. Note that each of subsequent OU's would have multiple choices, which I would like to sort and choose within a Grid. I already know this part, but what's tricky for me is creating that loop.</p> <p>Not very familiar with While Do Until on powershell.</p> <p>I will do my research but would appreciate any suggestions. It doesn't have to be a loop, but I'm looking for a solution with $ instead of a definite parameter.</p> <p>Cheers,</p> <pre><code>if ($Location -eq $null ) { [System.Windows.MessageBox]::Show(&quot;'You didn't enter the required parameter, script ending'&quot;,&quot;System Notification&quot;,&quot;Ok&quot;) exit } if ($Location -ne $null ) { while ($Location -ne $null) { $DomainOU1=Get-ADOrganizationalUnit -Filter &quot;Name -like '$Location'&quot; -SearchBase $DistinguishedGroupName -SearchScope OneLevel | select Name -ExpandProperty Name } do { $Location1=@($DomainOU1) | sort $Location1=$Location1 | Out-GridView -Title &quot;Choose Employee Location of Deployment&quot; $Location1=$Location } Until ($Location -eq &quot;Users&quot;) } Write-output &quot;You chose $Location&quot; </code></pre>
[ { "answer_id": 74395669, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 3, "selected": true, "text": "(?=\\d+[a-z][a-z\\d]*|[a-z\\d]*[a-z]\\d)[a-z\\d]{3,}\n" }, { "answer_id": 74395687, "author": "dawg", "author_id": 298607, "author_profile": "https://Stackoverflow.com/users/298607", "pm_score": 1, "selected": false, "text": "/\\b(?=[a-zA-Z0-9]{4,})(?=(?:[^\\/\\d]*\\d){4,})([^\\/]{3,})/\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20471715/" ]
74,395,626
<p>I have df1 that looks like this:</p> <pre><code>STATE YEAR EVENT_TYPE DAMAGE ALABAMA 1962 Tornado 27 ALABAMA 1962 Flood 7 ALABAMA 1963 Thunderstorm 12 ... </code></pre> <p>and df2 that looks like this:</p> <pre><code>STATE YEAR TORNADO THUNDERSTORM FLOOD ALABAMA 1962 NaN NaN NaN ALABAMA 1963 NaN NaN NaN ... </code></pre> <p>And I want to merge these two dataframes together, so the final output looks like this:</p> <pre><code>STATE YEAR TORNADO THUNDERSTORM FLOOD ALABAMA 1962 27 NaN 7 ... </code></pre> <p>Having hard time figuring out how to do this.</p>
[ { "answer_id": 74395706, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 1, "selected": true, "text": "merge" }, { "answer_id": 74395722, "author": "C-3PO", "author_id": 4667669, "author_profile": "https://Stackoverflow.com/users/4667669", "pm_score": 0, "selected": false, "text": "df1.update(df2)" }, { "answer_id": 74395732, "author": "Captain Caveman", "author_id": 2325014, "author_profile": "https://Stackoverflow.com/users/2325014", "pm_score": 1, "selected": false, "text": "pd.concat([df1, df2], axis=0)\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16451496/" ]
74,395,655
<p>I am trying to place the text at the bottom of the <code>div</code> but even when I set it to <code>position: relative; bottom: 0</code> it doesn't work. I also tried vertical alignment but it doesn't work:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>* { box-sizing: border-box; } body { padding: 0; margin: 0; } .mainContainer { display: grid; width: 100vw; height: 100vh; place-items: center; } .subContainer { display: grid; grid-template-columns: 20% 80%; width: 60%; } .anotherDiv { background-color: rgb(195, 171, 171); } img { width: 100%; height: auto; } .textForBottom { position: relative; bottom: 0; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="mainContainer"&gt; &lt;div class="subContainer"&gt; &lt;img src="https://static01.nyt.com/images/2021/09/14/science/07CAT-STRIPES/07CAT-STRIPES-mediumSquareAt3X-v2.jpg" alt="cat" /&gt; &lt;div class="anotherDiv"&gt; &lt;span class="textForBottom"&gt; This text should be at the bottom in the div that contains it &lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p><a href="https://codepen.io/metaxenology/pen/bGKqpzQ" rel="nofollow noreferrer">CodePen</a></p>
[ { "answer_id": 74395706, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 1, "selected": true, "text": "merge" }, { "answer_id": 74395722, "author": "C-3PO", "author_id": 4667669, "author_profile": "https://Stackoverflow.com/users/4667669", "pm_score": 0, "selected": false, "text": "df1.update(df2)" }, { "answer_id": 74395732, "author": "Captain Caveman", "author_id": 2325014, "author_profile": "https://Stackoverflow.com/users/2325014", "pm_score": 1, "selected": false, "text": "pd.concat([df1, df2], axis=0)\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14459522/" ]
74,395,656
<p>See the Chevrons in the attached images. The first one is from a desktop Chrome browser. It renders this way in the standard desktop browsers including Safari. It also renders this way in Chrome dev tools device simulations including iPhone 12, and on real Android devices.</p> <p>The second image shows how it renders on a real iPhone 12 and device simulations (such as lambdatest or browserstack). The Chevron is at least 100% larger.</p> <p>I've tried adding a position: relative style to both the chevron and its parent div with no luck. Reference the answer by Aaron Krauss at <a href="https://stackoverflow.com/questions/4504942/mobile-safari-svg-problem">Mobile Safari SVG Problem</a> .</p> <p>I don't know of a way to check the css from a simulation, let alone an iPhone. Any advice on how to do that or what to try for a fix?</p> <p><a href="https://i.stack.imgur.com/b2Zfj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/b2Zfj.png" alt="Correctly rendering in most browsers" /></a></p> <p><a href="https://i.stack.imgur.com/lyu84.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lyu84.png" alt="Enlarged on iPhone" /></a></p> <p>Markup:</p> <pre><code>&lt;div id=&quot;alert-message&quot; class=&quot;warning&quot; aria-live=&quot;assertive&quot;&gt; &lt;div id=&quot;alert-message-header&quot; data-bind=&quot;click: toggleAlertMessageBody()&quot;&gt; &lt;span id=&quot;alert-icon&quot;&gt;&lt;/span&gt; &lt;span id=&quot;alert-header-text&quot;&gt;Other shops may have earlier availability.&lt;/span&gt; &lt;button id=&quot;alert-chevron&quot; name=&quot;alert-chevron-btn&quot; type=&quot;button&quot;&gt;&lt;/button&gt; &lt;/div&gt; &lt;div id=&quot;alert-message-body&quot; &gt;Body&lt;/div&gt; </code></pre> <p>css:</p> <pre><code>#alert-message { margin-bottom: 32px; border: 1px solid; border-radius: 5px; font-family: 'Roboto'; font-style: normal; } #alert-message #alert-message-header { display: -webkit-box; display: -ms-flexbox; display: flex; padding: 12px 16px 12px 16px; min-height: 41px; font-weight: 500; cursor: pointer; line-height: 26px; position: relative; } #alert-message #alert-message-body { margin: 0 15px; padding: 8px 16px 12px 16px; border-top: 1px solid; color: #525656; line-height: 26px; font-weight: 400; } #alert-message.warning, #alert-message.warning-info { background-color: #fef6e8; border-color: #e86421; } #alert-message.warning #alert-message-body, #alert-message.warning-info #alert-message-body { border-color: #e86421; } #alert-message.warning #alert-icon { background: url(&quot;/Shared/images/alert-circle-yellow.svg&quot;) no-repeat; min-width: 15px; max-height: 25px; background-position: center; background-size: 100% auto; } #alert-message #alert-header-text { padding: 0 10px; color: #000000; -webkit-box-flex: 1; -ms-flex-positive: 1; flex-grow: 1; } #alert-message.warning #alert-chevron { background: url(&quot;/Shared/images/chevron-up-yellow.svg&quot;) no-repeat; min-width: 15px; max-height: 25px; background-position: center; background-size: 100% auto; } #alert-message #alert-chevron { position: relative; border: none; transition: -webkit-transform 0.3s; transition: transform 0.3s; } #alert-message #alert-chevron.collapsed { -webkit-transform: rotate(180deg); -ms-transform: rotate(180deg); transform: rotate(180deg); } #alert-message b { color: #000000; } </code></pre> <p>Tried replacing the min-height on #alert-message-header div that contains the chevron with height: 48px;. No change.</p> <p>SVG:</p> <pre><code>&lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot; width=&quot;15&quot; height=&quot;9&quot; viewBox=&quot;0 0 15 9&quot;&gt; &lt;path fill=&quot;#E86421&quot; fill-rule=&quot;nonzero&quot; d=&quot;M7.5 0a.806.806 0 0 0-.593.265L.246 7.455a.957.957 0 0 0 0 1.28.796.796 0 0 0 1.185 0l6.07-6.55 6.068 6.55a.796.796 0 0 0 1.186 0 .957.957 0 0 0 0-1.28L8.093.265A.806.806 0 0 0 7.5 0&quot;/&gt; &lt;/svg&gt; </code></pre>
[ { "answer_id": 74395921, "author": "user2817078", "author_id": 2817078, "author_profile": "https://Stackoverflow.com/users/2817078", "pm_score": 1, "selected": false, "text": "preferences/advanced" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/641361/" ]
74,395,667
<p>i'm trying to develope an app with Flutter. I'm new at this :(</p> <p>I can't add a button under the gridView.</p> <p>This is my code:</p> <pre><code> body: Container( height: 300, width: 300, margin: const EdgeInsets.only(left: 47.0, top: 100), child: Padding( padding: const EdgeInsets.all(8.0), child: GridView(children: [ Container(decoration: BoxDecoration(borderRadius: BorderRadius.circular(20), color: Colors.grey), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon(Icons.router, size: 40, color: Colors.white), Text(&quot;DFGW&quot;, style: TextStyle(color: Colors.white, fontSize: 20)) ],),), Container(decoration: BoxDecoration(borderRadius: BorderRadius.circular(20), color: Colors.grey), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon(Icons.route_rounded, size: 40, color: Colors.white), Text(&quot;WAN&quot;, style: TextStyle(color: Colors.white, fontSize: 20)) ],),), Container(decoration: BoxDecoration(borderRadius: BorderRadius.circular(20), color: Colors.grey), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon(Icons.vpn_lock, size: 40, color: Colors.white), Text(&quot;VPN&quot;, style: TextStyle(color: Colors.white, fontSize: 20)) ],),), Container(decoration: BoxDecoration(borderRadius: BorderRadius.circular(20), color: Colors.grey), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon(Icons.language, size: 40, color: Colors.white), Text(&quot;INTERNET&quot;, style: TextStyle(color: Colors.white, fontSize: 20)) ],),), ], gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2, mainAxisSpacing: 10, crossAxisSpacing: 10),), )), bottomNavigationBar: Container( child: OutlinedButton( style: OutlinedButton.styleFrom( backgroundColor: Colors.white, fixedSize: const Size(100, 100) ), child: Text(&quot;Start Checking&quot;, style: TextStyle(fontSize: 20.0, color: Colors.black,),), onPressed: () {}, ), ), </code></pre> <p><a href="https://i.stack.imgur.com/rsSNi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rsSNi.png" alt="enter image description here" /></a></p> <p>This is my output right now.</p> <p>I would like the button to be exactly under the grid, what can I do?</p> <p>Thanks in advance for your help!</p>
[ { "answer_id": 74395766, "author": "Braden Bagby", "author_id": 7817786, "author_profile": "https://Stackoverflow.com/users/7817786", "pm_score": 1, "selected": true, "text": "import 'package:flutter/material.dart';\nimport 'package:provider/provider.dart';\n\nvoid main() => runApp(const SwitchApp());\n\nclass ColorModel extends ChangeNotifier {\n Color color = Colors.green;\n void setColor(Color color) {\n this.color = color;\n notifyListeners();\n }\n}\n\nclass SwitchApp extends StatelessWidget {\n const SwitchApp({super.key});\n\n @override\n Widget build(BuildContext context) {\n return ChangeNotifierProvider<ColorModel>(\n create: (context) => ColorModel(),\n child: MaterialApp(\n home: Scaffold(\n appBar: AppBar(title: const Text('Switch Sample')),\n body: Column(\n crossAxisAlignment: CrossAxisAlignment.start,\n children: [\n Container(\n height: 300,\n width: 300,\n margin: const EdgeInsets.only(left: 47.0, top: 100),\n child: Padding(\n padding: const EdgeInsets.all(8.0),\n child: GridView(\n children: [\n Container(\n decoration: BoxDecoration(\n borderRadius: BorderRadius.circular(20),\n color: Colors.grey),\n child: Column(\n mainAxisAlignment: MainAxisAlignment.center,\n children: [\n Icon(Icons.router, size: 40, color: Colors.white),\n Text(\"DFGW\",\n style: TextStyle(\n color: Colors.white, fontSize: 20))\n ],\n ),\n ),\n Container(\n decoration: BoxDecoration(\n borderRadius: BorderRadius.circular(20),\n color: Colors.grey),\n child: Column(\n mainAxisAlignment: MainAxisAlignment.center,\n children: [\n Icon(Icons.route_rounded,\n size: 40, color: Colors.white),\n Text(\"WAN\",\n style: TextStyle(\n color: Colors.white, fontSize: 20))\n ],\n ),\n ),\n Container(\n decoration: BoxDecoration(\n borderRadius: BorderRadius.circular(20),\n color: Colors.grey),\n child: Column(\n mainAxisAlignment: MainAxisAlignment.center,\n children: [\n Icon(Icons.vpn_lock,\n size: 40, color: Colors.white),\n Text(\"VPN\",\n style: TextStyle(\n color: Colors.white, fontSize: 20))\n ],\n ),\n ),\n Container(\n decoration: BoxDecoration(\n borderRadius: BorderRadius.circular(20),\n color: Colors.grey),\n child: Column(\n mainAxisAlignment: MainAxisAlignment.center,\n children: [\n Icon(Icons.language,\n size: 40, color: Colors.white),\n Text(\"INTERNET\",\n style: TextStyle(\n color: Colors.white, fontSize: 20))\n ],\n ),\n ),\n ],\n gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(\n crossAxisCount: 2,\n mainAxisSpacing: 10,\n crossAxisSpacing: 10),\n ),\n )),\n Center(child: ElevatedButton(onPressed: () {}, child: Text('button')))\n ],\n ),\n bottomNavigationBar: Container(\n child: OutlinedButton(\n style: OutlinedButton.styleFrom(\n backgroundColor: Colors.white,\n fixedSize: const Size(100, 100)),\n child: Text(\n \"Start Checking\",\n style: TextStyle(\n fontSize: 20.0,\n color: Colors.black,\n ),\n ),\n onPressed: () {},\n ),\n ),\n ),\n ),\n );\n }\n}\n\nclass SwitchExample extends StatefulWidget {\n const SwitchExample({super.key});\n\n @override\n State<SwitchExample> createState() => _SwitchExampleState();\n}\n\nclass _SwitchExampleState extends State<SwitchExample> {\n bool light = false;\n\n @override\n Widget build(BuildContext context) {\n return Column(\n children: [\n Switch(\n // This bool value toggles the switch.\n value: light,\n activeColor: Colors.red,\n onChanged: (bool value) {\n // This is called when the user toggles the switch.\n setState(() {\n light = value;\n });\n Provider.of<ColorModel>(context, listen: false)\n .setColor(value ? Colors.green : Colors.blue);\n },\n ),\n MyText()\n ],\n );\n }\n}\n\nclass MyText extends StatelessWidget {\n const MyText({super.key});\n\n @override\n Widget build(BuildContext context) {\n return Consumer<ColorModel>(builder: (context, state, _) {\n return Text('Change my color', style: TextStyle(color: state.color));\n });\n }\n}\n\n" }, { "answer_id": 74395816, "author": "samedhrmn", "author_id": 13077944, "author_profile": "https://Stackoverflow.com/users/13077944", "pm_score": 2, "selected": false, "text": "body: Column(\n children:[\n Container(\n height: 300,\n width: 300,\n margin: const EdgeInsets.only(left: 47.0, top: 100),\n child: // your grid view..\n ),\n YourButtonWidget(), // and your button \n ],\n),\n \n \n \n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19717897/" ]
74,395,678
<p>I'm not sure why I'm receiving this error. I'm trying to get data from two separate tables in this query.</p> <pre><code>@Query(&quot;SELECT * FROM ConnectionRequest c &quot; + &quot;INNER JOIN (SELECT firstName as name FROM USER u WHERE c.userId = u.id) &quot; + &quot;WHERE c.dateTimeCompleted IS NULL&quot;, nativeQuery = true) List&lt;ConnectionRequest&gt; findAllByDateTimeCompletedIsNull(); </code></pre>
[ { "answer_id": 74395764, "author": "chrylis -cautiouslyoptimistic-", "author_id": 1189885, "author_profile": "https://Stackoverflow.com/users/1189885", "pm_score": 3, "selected": true, "text": "value" }, { "answer_id": 74395818, "author": "nbk", "author_id": 5193536, "author_profile": "https://Stackoverflow.com/users/5193536", "pm_score": 0, "selected": false, "text": "SELECT c.*,u.firstName as name FROM ConnectionRequest c \n INNER JOIN USER u ON c.userId = u.id\n WHERE c.dateTimeCompleted IS NULL\n \n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16200097/" ]
74,395,775
<p>In the previous YouTube version there was an option to get the first YouTube video as follows:</p> <p><a href="https://www.youtube.com/channel/MrBeast6000/videos?view=0&amp;sort=da&amp;flow=grid" rel="nofollow noreferrer">https://www.youtube.com/channel/MrBeast6000/videos?view=0&amp;sort=da&amp;flow=grid</a> // MrBeast6000 channel Name</p> <p>But the new version does not support this method. Is there any other way to get the first video of any YouTube channel?</p>
[ { "answer_id": 74590069, "author": "jlo", "author_id": 1202124, "author_profile": "https://Stackoverflow.com/users/1202124", "pm_score": -1, "selected": false, "text": "yt-dlp https://www.youtube.com/<CHANNEL-ID> --playlist-reverse --max-downloads 1\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6282064/" ]
74,395,792
<p>Im trying to submit the user data to the firebase firestore database, but the function to create a new collection is not working for me, I have checked some diferent ways to do it, but none of theme are working, I already update my firebase config file using the firebase comands on my terminal.</p> <p>This is the code to call the service that use firestore:</p> <pre><code> this.authSvc.register(email, password).then((result) =&gt; { this.authSvc.logout(); this.verifyEmail(); this.res = result?.user; this.registerDB(); }) .catch((error) =&gt; { this.toastr.error(this.firebaseError.codeError(error.code), 'Error'); this.loading = false; }); } verifyEmail() { this.afAuth.currentUser.then(user =&gt; user?.sendEmailVerification()) .then(() =&gt; { this.toastr.info('Se envio un correo con el link de verificación', 'Verificar Email') this.router.navigate(['/verify-email']) }); } async registerDB() { const path = 'Users'; const id = this.res.uid; this.userData.uid = id; this.userData.password = null; await this.frservice.createDoc(this.userData, path, id); } </code></pre> <p>And this is the code of the firestore service:</p> <pre><code>import { Injectable } from '@angular/core'; import { AngularFirestore } from '@angular/fire/compat/firestore'; @Injectable({ providedIn: 'root' }) export class FirestoreService { constructor(private firestore: AngularFirestore) { } createDoc(userData: any, path: string, id: string) { const collection = this.firestore.collection(path); return collection.doc(id).set(userData); } getId() { return this.firestore.createId(); } getCollection&lt;tipo&gt;(path: string) { const collection = this.firestore.collection&lt;tipo&gt;(path); return collection.valueChanges(); } getDoc&lt;tipo&gt;(path: string, id: string) { return this.firestore.collection(path).doc&lt;tipo&gt;(id).valueChanges() } } </code></pre> <p>I just want to create a new collection were the user's data are going to be registered.</p>
[ { "answer_id": 74590069, "author": "jlo", "author_id": 1202124, "author_profile": "https://Stackoverflow.com/users/1202124", "pm_score": -1, "selected": false, "text": "yt-dlp https://www.youtube.com/<CHANNEL-ID> --playlist-reverse --max-downloads 1\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20472544/" ]
74,395,814
<p>How do I return only Members from the delta API for group (<a href="https://learn.microsoft.com/en-us/graph/delta-query-overview?tabs=http" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/graph/delta-query-overview?tabs=http</a>)</p> <p>Adding .Members &amp; .Select() are not supported</p> <p><a href="https://i.stack.imgur.com/1mdod.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1mdod.png" alt="enter image description here" /></a></p> <pre><code>await _graphServiceClient .Groups .Members .Delta() .Request() .Filter($&quot;id eq '{groupId}'&quot;) .GetAsync(); </code></pre> <p>On trying this:</p> <pre><code> var queryOptions = new List&lt;QueryOption&gt;() { new QueryOption(&quot;select&quot;, &quot;members&quot;) }; await _graphServiceClient .Groups .Delta() .Request(queryOptions) .Filter($&quot;id eq '{groupId}'&quot;) .GetAsync(); </code></pre> <p>I see this error:</p> <p>Message: Unrecognized query argument specified: 'select'. What am I missing?</p>
[ { "answer_id": 74398587, "author": "user2250152", "author_id": 2250152, "author_profile": "https://Stackoverflow.com/users/2250152", "pm_score": 2, "selected": true, "text": "Select" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3693060/" ]
74,395,864
<p>Is it possible to change an if-else statement to include OR in an R-Script? Like 70% of the time would turn into this, while the remaining 30% would turn into something else. Similar to increasing the probability to change?</p> <pre><code>if (w0[i, j] == 1) { w1[i, j] &lt;- rL[nNeigh + 1] } else { w1[i, j] &lt;- rD[nNeigh + 1] } </code></pre> <p>This is the statement where the result is deterministic, but I want to change it into a probabilistic function.</p> <pre><code>if (w0[i, j] == 1) { w1[i, j] &lt;- rL[nNeigh + 1] || w1[i, j] &lt;- rL[nNeigh] } else { w1[i, j] &lt;- rD[nNeigh + 1] || w1[i, j] &lt;- rL[nNeigh] } </code></pre> <p>I know this is not the right way to even do it, but I'm at a loss</p>
[ { "answer_id": 74398587, "author": "user2250152", "author_id": 2250152, "author_profile": "https://Stackoverflow.com/users/2250152", "pm_score": 2, "selected": true, "text": "Select" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13811851/" ]
74,395,920
<p>I am validating using jQuery:</p> <pre><code>$el.rules(&quot;add&quot;, { remote: { url: `/api/distributors/KeywordExists`, type: &quot;post&quot;, data: { id: @Model.Distributor.DistributorId } } }); </code></pre> <p>The <code>$el</code> is an input element generated by Razor Pages from a <code>string[]</code>, so it is rendered like this:<br /> <code>&lt;input class=&quot;form-control keyword&quot; type=&quot;text&quot; id=&quot;Distributor_Keywords_0_&quot; name=&quot;Distributor.Keywords[0]&quot; &gt;</code></p> <p>After that there is the next element in the <code>string[]</code>:<br /> <code>&lt;input class=&quot;form-control keyword&quot; type=&quot;text&quot; id=&quot;Distributor_Keywords_1_&quot; name=&quot;Distributor.Keywords[1]&quot; &gt;</code> etc.</p> <p>In order to validate, the <code>rules</code> say to check <code>/api/distributors/KeywordExists</code> . This method looks like this:</p> <pre><code>[AcceptVerbs(&quot;GET&quot;,&quot;POST&quot;), Route(&quot;KeywordExists&quot;)] public JsonResult KeywordExists(long id, string keyword) { if (!string.IsNullOrEmpty(keyword)) { var match = CheckDbIfKeywordIsMatch(); if (match is not null) { return new JsonResult(!match.Exists) ; } } return new JsonResult(true); } </code></pre> <p>The actual API works perfectly, the problem is that it only works when the parameters are <code>id</code> and <code>keyword</code> However the jQuery validation sends the following Form Data in its payload:</p> <ol> <li><p><strong>Distributor.Keywords[0]:</strong></p> <p>Amazon</p> </li> <li><p><strong>id:</strong></p> <p>1</p> </li> </ol> <p>Therefore, the URL is <code>Distributor.Keywords%5B0%5D=Amazon&amp;id=1</code></p> <p>which the Controller does not recognize.</p> <p>If I could write <code>KeywordExists(long id, string Distributor.Keyword*)</code> that would catch the params being sent but obviously I can't.</p> <p>I have tried adding [Bind] attributes to no avail</p>
[ { "answer_id": 74398587, "author": "user2250152", "author_id": 2250152, "author_profile": "https://Stackoverflow.com/users/2250152", "pm_score": 2, "selected": true, "text": "Select" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19488719/" ]
74,395,936
<p>Hello I am trying to design a very simple web application with <code>Express.js</code> that just sends your email address that you submitted to the server side. But when I try to combine normal JavaScript (like <code>querySelector</code>) with code that has <code>Express.js</code> contents, it does not work and crashes saying that <code>document</code> in <code>document.getElementById(&quot;email&quot;)</code> is not defined. May I ask if there is a way to do this? Or how should I send data from the client side to the server side and vice versa properly?</p> <p>This is my first very simple project in web development so the code is not the best.</p> <p><strong>JavaScript Code</strong></p> <pre><code>const express = require(&quot;express&quot;) const app = express(); const path = require(&quot;path&quot;) app.use(express.static(&quot;./&quot;)) app.listen(5000, () =&gt; { console.log(&quot;Server listening on port 5000...&quot;) }) app.get(&quot;/&quot;, (req, res) =&gt; { res.sendFile(&quot;index.html&quot;, (err) =&gt; { console.log(err) }) }) let enterEmail = document.getElementById(&quot;email&quot;) let submit = document.getElementById(&quot;submit&quot;) let status = document.getElementById(&quot;status&quot;) let email; submit.addEventListener(&quot;click&quot;, (e) =&gt; { email = enterEmail.value enterEmail.value = &quot;&quot; status.innerHTML = &quot;Submitted email: &quot; + email; }) </code></pre> <p><strong>HTML Code</strong></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;./styles.css&quot;&gt; &lt;/head&gt; &lt;body&gt; &lt;input id =&quot;email&quot; placeholder=&quot;enter email&quot; type=&quot;text&quot;&gt;&lt;/input&gt; &lt;input id=&quot;submit&quot; type=&quot;submit&quot;&gt; &lt;h1 id=&quot;status&quot;&gt;Submitted email: &lt;/h1&gt; &lt;script src=&quot;./index.js&quot;&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>The error message:</strong></p> <pre><code>let enterEmail = document.getElementById(&quot;email&quot;) ^ ReferenceError: document is not defined at Object.&lt;anonymous&gt; (C:\Users\Lenovo\Desktop\personal-projects\app.js:23:18) at Module._compile (node:internal/modules/cjs/loader:1103:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1155:10) at Module.load (node:internal/modules/cjs/loader:981:32) at Function.Module._load (node:internal/modules/cjs/loader:822:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12) at node:internal/main/run_main_module:17:47 [nodemon] app crashed - waiting for file changes before starting... </code></pre>
[ { "answer_id": 74396226, "author": "Pekar Kids", "author_id": 20012002, "author_profile": "https://Stackoverflow.com/users/20012002", "pm_score": 0, "selected": false, "text": "script.js" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18558349/" ]
74,395,944
<p>I have a python 2.7 codebase that I'm trying to containerize. Much as I'd like to, our devs cannot move to Python 3.</p> <p>When running natively in their dev environments, datetimes respect timezones. I can confirm that the output is as expected on a Mac running <code>Python 3.9.6</code>. But when we containerize this on Ubuntu base images, this no longer works correctly.</p> <p>Using <code>python:2.7.18-buster</code> works correctly, but that is a 3 year old image that doesn't get updates. Both <code>ubuntu:18.04</code> and <code>ubuntu:16.04</code> fail.</p> <p>The incorrect output when run at this time is</p> <pre><code>UTC Hour: 22 NY Hour: 22 1609459200.0 London Hour: 22 1609459200.0 </code></pre> <p>The code to repro the issue is</p> <pre><code>import os import datetime import time from dateutil.parser import parse date_string=&quot;2021-01-01&quot; os.environ.get(&quot;TZ&quot;) # should be none, use system TZ, which is UTC print (&quot;UTC Hour: &quot;, datetime.datetime.now().hour) # should be whatever hour it is in UTC os.environ[&quot;TZ&quot;] = &quot;America/New_York&quot; print (&quot;NY Hour:&quot;, datetime.datetime.now().hour) # should be whatever hour it is in EST print (time.mktime(parse(date_string).timetuple())) # should be 1609477200.0 os.environ[&quot;TZ&quot;] = &quot;Europe/London&quot; print (&quot;London Hour: &quot;, datetime.datetime.now().hour) # should be whatever hour it is in GMT print (time.mktime(parse(date_string).timetuple())) # should be 1609459200.0 </code></pre>
[ { "answer_id": 74396226, "author": "Pekar Kids", "author_id": 20012002, "author_profile": "https://Stackoverflow.com/users/20012002", "pm_score": 0, "selected": false, "text": "script.js" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/246754/" ]
74,395,948
<p>I want to create an event system that uses lambda functions as its subscribers/listeners, and an event type to assign them to the specific event that they should subscribe to. The lambdas should have variable arguments, as different kinds of events use different kinds of arguments/provide the subscribers with different kinds of data.</p> <p>For my dispatcher, I have the following:</p> <pre><code>class EventDispatcher { public: static void subscribe(EventType event_type, std::function&lt;void(...)&gt; callback); void queue_event(Event event); void dispatch_queue(); private: std::queue&lt;Event*&gt; event_queue; std::map&lt;EventType, std::function&lt;void(...)&gt;&gt; event_subscribers; }; </code></pre> <p>No issues here, but when I go to implement the <code>subscribe()</code> function in my <code>.cpp</code> file, like this:</p> <pre><code>void EventDispatcher::subscribe(EventType event_type, std::function&lt;void(...)&gt; callback) { ... (nothing here yet) } </code></pre> <p>The IDE shows me this:</p> <blockquote> <p>Implicit instantiation of undefined template 'std::function&lt;void (...)&gt;'</p> </blockquote>
[ { "answer_id": 74405789, "author": "Jeff Garrett", "author_id": 3242146, "author_profile": "https://Stackoverflow.com/users/3242146", "pm_score": 0, "selected": false, "text": "std::function" }, { "answer_id": 74408574, "author": "HolyBlackCat", "author_id": 2752075, "author_profile": "https://Stackoverflow.com/users/2752075", "pm_score": 2, "selected": false, "text": "#include <functional>\n#include <iostream>\n#include <map>\n#include <memory>\n#include <queue>\n#include <tuple>\n#include <typeindex>\n#include <typeinfo>\n#include <type_traits>\n#include <utility>\n\nstruct Event\n{\n virtual ~Event() = default;\n};\n\nstruct Observer\n{\n virtual ~Observer() = default;\n virtual void Observe(const Event &e) const = 0;\n};\n\ntemplate <typename ...P>\nstruct BasicEvent : Event\n{\n std::tuple<P...> params;\n\n BasicEvent(P ...params) : params(std::move(params)...) {}\n\n struct EventObserver : Observer\n {\n std::function<void(P...)> func;\n\n template <typename T>\n EventObserver(T &&func) : func(std::forward<T>(func)) {}\n\n void Observe(const Event &e) const override\n {\n std::apply(func, dynamic_cast<const BasicEvent &>(e).params);\n }\n };\n\n // We need a protected destructor, but adding one silently removes the move operations.\n // And adding the move operations removes the copy operations, so we add those too.\n BasicEvent(const BasicEvent &) = default;\n BasicEvent(BasicEvent &&) = default;\n BasicEvent &operator=(const BasicEvent &) = default;\n BasicEvent &operator=(BasicEvent &&) = default;\n\n protected:\n ~BasicEvent() {}\n};\n\nclass EventDispatcher\n{\n public:\n template <typename E>\n void Subscribe(typename E::EventObserver observer)\n {\n event_subscribers.insert_or_assign(typeid(E), std::make_unique<typename E::EventObserver>(std::move(observer)));\n }\n\n template <typename E>\n void QueueEvent(E &&event)\n {\n event_queue.push(std::make_unique<std::remove_cvref_t<E>>(std::forward<E>(event)));\n }\n\n void DispatchQueue()\n {\n while (!event_queue.empty())\n {\n Event &event = *event_queue.front();\n event_subscribers.at(typeid(event))->Observe(event);\n event_queue.pop();\n }\n }\n\n private:\n std::queue<std::unique_ptr<Event>> event_queue;\n std::map<std::type_index, std::unique_ptr<Observer>> event_subscribers;\n};\n\n\nstruct EventA : BasicEvent<> {using BasicEvent::BasicEvent;};\nstruct EventB : BasicEvent<> {using BasicEvent::BasicEvent;};\nstruct EventC : BasicEvent<int, int> {using BasicEvent::BasicEvent;};\n\nint main()\n{\n EventDispatcher dis;\n dis.Subscribe<EventA>([]{std::cout << \"Observing A!\\n\";});\n dis.Subscribe<EventB>([]{std::cout << \"Observing B!\\n\";});\n dis.Subscribe<EventC>([](int x, int y){std::cout << \"Observing C: \" << x << \", \" << y << \"!\\n\";});\n dis.QueueEvent(EventA());\n dis.QueueEvent(EventB());\n dis.QueueEvent(EventC(1, 2));\n dis.DispatchQueue();\n}\n" }, { "answer_id": 74409037, "author": "joergbrech", "author_id": 12173376, "author_profile": "https://Stackoverflow.com/users/12173376", "pm_score": 2, "selected": false, "text": "std::function" }, { "answer_id": 74414040, "author": "F4LS3", "author_id": 12277653, "author_profile": "https://Stackoverflow.com/users/12277653", "pm_score": 2, "selected": true, "text": "enum class EventType {\n WindowClosed, WindowResized, WindowFocused, WindowLostFocus, WindowMoved,\n AppTick, AppUpdate, AppRender,\n KeyPressed, KeyRelease,\n MouseButtonPressed, MouseButtonRelease, MouseMoved, MouseScrolled,\n ControllerAxisChange, ControllerButtonPressed, ControllerConnected, ControllerDisconnected\n};\n\nclass IEvent {\npublic:\n IEvent(EventType event_type) {\n this->event_type = event_type;\n }\n\n EventType get_event_type() {\n return event_type;\n }\n\nprivate:\n EventType event_type;\n};\n\nclass IEventSubscriber {\npublic:\n /**\n * @param event The event that is passed to the subscriber by the publisher; should be cast to specific event\n * */\n virtual void on_event(IEvent *event) = 0;\n\n EventType get_event_type() {\n return event_type;\n }\n\nprotected:\n explicit IEventSubscriber(EventType event_type) {\n this->event_type = event_type;\n }\n\nprivate:\n EventType event_type;\n};\n\nclass FORGE_API EventPublisher {\npublic:\n static void subscribe(IEventSubscriber *subscriber);\n static void queue_event(IEvent *event);\n static void dispatch_queue();\n\nprivate:\n static std::queue<IEvent*> event_queue;\n static std::set<IEventSubscriber*> event_subscribers;\n};\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12277653/" ]
74,395,992
<p>I built a login page using firebase. When the user clicks the login button, a CircularProgressIndicator is started and if the user gave the correct credentials everything works perfectly but if there is an error (e.g user not found OR wrong password) the user will be not forwarded to the next page but the CircularProgressIndicator will not stop showing.</p> <p>The aim is, that if there is an error, I want to stop the CircularProgressIndicator and want to show an error message but I don't know how to stop the CircularProgressIndicator.</p> <p>My code looks the following:</p> <pre><code>import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; final navigatorKey = GlobalKey&lt;NavigatorState&gt;(); class LoginUser { Future loginUser(userEmail, userPassword, context) async { navigatorKey: navigatorKey; showDialog( barrierDismissible: false, context: context, builder: (context) =&gt; Center(child: CircularProgressIndicator()) ); try { await FirebaseAuth.instance.signInWithEmailAndPassword( email: userEmail, password: userPassword ); // Close Dialog when route changes } on FirebaseAuthException catch (e) { if (e.code == 'user-not-found') { return &quot;ec-unf&quot;; } else if (e.code == 'wrong-password') { return &quot;ec-wp&quot;; } navigatorKey.currentState!.popUntil((route) =&gt; route.isFirst); } } } Does anybody know how to do this? Thanks! Chris </code></pre>
[ { "answer_id": 74396093, "author": "ariga", "author_id": 20384182, "author_profile": "https://Stackoverflow.com/users/20384182", "pm_score": 3, "selected": true, "text": "isLoading = true\ntry {\n //your code\n print(\"done !\"); \n isLoading\n} catch (err) {\n print(\"error\");\n isLoading = false\n} finally {\n print(\"Finish \"); //error and success\n isLoading = false\n}\n\n \n" }, { "answer_id": 74408357, "author": "Chris", "author_id": 14143776, "author_profile": "https://Stackoverflow.com/users/14143776", "pm_score": 0, "selected": false, "text": "Future login() async{\n isSignInLoading = true; // START LOADING CYCLE\n\n // --- LOADING CYCLE - START ---\n if (isSignInLoading == true) {\n showDialog(\n barrierDismissible: false,\n context: context,\n builder: (context) => Center(child: CircularProgressIndicator())\n );\n }\n // --- LOADING CYCLE - END ---\n\n try {\n await FirebaseAuth.instance.signInWithEmailAndPassword(\n email: _controllerEmail.text,\n password: _controllerPassword.text\n );\n\n } catch (e) {\n isSignInLoading = false; // START LOADING CYCLE\n isErrorLogin = true; // START LOADING CYCLE\n }\n Navigator.of(context).pop();\n\n // --- ERROR MESSAGE - START ---\n if (isErrorLogin == true) {\n showDialog(\n barrierDismissible: false,\n context: context,\n builder: (context) => Center(child:\n AlertDialog(\n title: const Text('Something went wrong!'),\n content: const Text('Please check your entries, either the user does not exist or the password is incorrect.'),\n actions: [\n TextButton(\n child: const Text(\n 'Close',\n style: TextStyle(\n color: Color(0xff004494),\n fontWeight: FontWeight.w500\n ),\n ),\n onPressed: () {\n Navigator.of(context).pop();\n },\n ),\n ],\n )\n )\n );\n }\n // --- ERROR MESSAGE - END ---\n\n //var loginInfo = await LoginUser().loginUser(_controllerEmail.text,_controllerPassword.text, context);\n if (FirebaseAuth.instance.currentUser != null) {\n SharedPreferences prefs = await SharedPreferences.getInstance();\n prefs.setBool(\"userLoginStatus\", true);\n Navigator.popAndPushNamed(context, '/overview');\n }\n }\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74395992", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14143776/" ]
74,396,029
<p>I'm quite new to clojure and have been struggling to understand how things work exactly. I have a vector of hashmaps as such, titled authors:</p> <pre><code>------ Authors ----------- [{:id 100, :name &quot;Albert Einstein&quot;, :interest &quot;Physics&quot;} {:id 200, :name &quot;Alan Turing&quot;, :interest &quot;Computer Science&quot;} {:id 300, :name &quot;Jeff Dean&quot;, :interest &quot;Programming&quot;}] </code></pre> <p>I want to write a function that takes the id, and returns a list of the corresponding author names. I have two options for doing so: using filter or using for loop.</p> <p>When using filter, I have a predicate function already that returns true if the author has matching id:</p> <pre><code>(defn check-by-id [author id] (if (= id (:id author)) true false)) </code></pre> <p>But I'm not sure how to use this in order to get the list of author names when passing the id.</p>
[ { "answer_id": 74402519, "author": "TheChetan", "author_id": 4110233, "author_profile": "https://Stackoverflow.com/users/4110233", "pm_score": 0, "selected": false, "text": "Filter" }, { "answer_id": 74408268, "author": "rrudakov", "author_id": 7751381, "author_profile": "https://Stackoverflow.com/users/7751381", "pm_score": 0, "selected": false, "text": "group-by" }, { "answer_id": 74416113, "author": "user2609980", "author_id": 2609980, "author_profile": "https://Stackoverflow.com/users/2609980", "pm_score": 1, "selected": false, "text": "keep" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74396029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18648904/" ]
74,396,051
<p>I have a python string that looks like as shown below. This string is from the SEC filing of one public company in the US. I am trying to remove some annoying characters from the string using <code>unicodedata.normalise</code> function, but this is not removing all characters. What could be the reason behind such behavior?</p> <pre class="lang-py prettyprint-override"><code>from unicodedata import normalize s = 'GTS.Client.Services@JPMChase.com\nFacsimile\nNo.:\xa0 312-233-2266\n\xa0\nJPMorgan Chase Bank,\nN.A., as Administrative Agent\n10 South Dearborn, Floor 7th\nIL1-0010\nChicago, IL 60603-2003\nAttention:\xa0 Hiral Patel\nFacsimile No.:\xa0 312-385-7096\n\xa0\nLadies and Gentlemen:\n\xa0\nReference is made to the\nCredit Agreement, dated as of May\xa07, 2010 (as the same may be amended,\nrestated, supplemented or otherwise modified from time to time, the \x93Credit Agreement\x94), by and among\nHawaiian Electric Industries,\xa0Inc., a Hawaii corporation (the \x93Borrower\x94), the Lenders from time to\ntime party thereto and JPMorgan Chase Bank, N.A., as issuing bank and\nadministrative agent (the \x93Administrative Agent\x94).' normalize('NFKC', s) 'GTS.Client.Services@JPMChase.com\nFacsimile\nNo.: 312-233-2266\n \nJPMorgan Chase Bank,\nN.A., as Administrative Agent\n10 South Dearborn, Floor 7th\nIL1-0010\nChicago, IL 60603-2003\nAttention: Hiral Patel\nFacsimile No.: 312-385-7096\n \nLadies and Gentlemen:\n \nReference is made to the\nCredit Agreement, dated as of May 7, 2010 (as the same may be amended,\nrestated, supplemented or otherwise modified from time to time, the \x93Credit Agreement\x94), by and among\nHawaiian Electric Industries, Inc., a Hawaii corporation (the \x93Borrower\x94), the Lenders from time to\ntime party thereto and JPMorgan Chase Bank, N.A., as issuing bank and\nadministrative agent (the \x93Administrative Agent\x94).' </code></pre> <p>As one can see from the outputs, the characters <code>\xa0</code> is handled properly, but the characters like <code>\x92</code>, <code>\x93</code> and <code>\x94</code> are not normalized and are as it is in the result string.</p>
[ { "answer_id": 74396195, "author": "Mark Tolonen", "author_id": 235698, "author_profile": "https://Stackoverflow.com/users/235698", "pm_score": 4, "selected": true, "text": "latin1" }, { "answer_id": 74396223, "author": "jsbueno", "author_id": 108205, "author_profile": "https://Stackoverflow.com/users/108205", "pm_score": 2, "selected": false, "text": "unicodedata.normalize" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74396051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13952588/" ]
74,396,081
<p>I am working through a training class for ASP.NET Core 6 and in it, in a class declaration, it has:</p> <pre><code>public class Pie { public Category Category { get; set; } = default!; } </code></pre> <p>If I understand the <code>default!</code> correctly (I'm experienced with C# 3 so this is new to me) it is assigning a default value to this property when the object is created. And as this property is a class, it is assigning null. And the <code>!</code> is telling the compiler that it's ok to assign a null to this non nullable property.</p> <p>Is that correct? If so, this does not appear to be necessary as the code will compile without this assignment and with no assignment, that property is null. So why is this done?</p> <p>Also, in my programming to date it was assumed that a property in an object, if nothing is assigned to it, is null. And that any class member that is not a simple type is by definition nullable. Is that no longer true?</p>
[ { "answer_id": 74396164, "author": "Sweeper", "author_id": 5133585, "author_profile": "https://Stackoverflow.com/users/5133585", "pm_score": 2, "selected": false, "text": "Category" }, { "answer_id": 74396175, "author": "gunr2171", "author_id": 1043380, "author_profile": "https://Stackoverflow.com/users/1043380", "pm_score": 2, "selected": true, "text": "Category" }, { "answer_id": 74633319, "author": "JdB", "author_id": 7174557, "author_profile": "https://Stackoverflow.com/users/7174557", "pm_score": 0, "selected": false, "text": "public string A { get; set; } = string.Empty;\n\npublic List<string> A { get; set; } = new List<string>(); \n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74396081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/509627/" ]
74,396,107
<p>I am doing integration testing, and have 2 databases to test my project against. Rather than creating 2 profiles, is there a quick and easy way where I create 2 integration test classes, and one to test against the database originally written on my main profile, and another where I add some sort of annotation that changes the database url programatically, but otherwise keeps everything else the same, and run my tests through there?</p> <p>Thanks!</p>
[ { "answer_id": 74396143, "author": "Bartosz Szymański", "author_id": 7100461, "author_profile": "https://Stackoverflow.com/users/7100461", "pm_score": 2, "selected": true, "text": "@PropertySource" }, { "answer_id": 74396216, "author": "birca123", "author_id": 10231374, "author_profile": "https://Stackoverflow.com/users/10231374", "pm_score": 0, "selected": false, "text": "properties" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74396107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11712575/" ]
74,396,111
<p>Clicking on each <code>exit</code> button should remove each video, but only one video is being removed. To reproduce, click on the 1st blue play button, next, click on the exit button. <code>console.log(&quot;removePlayer&quot;);</code> says it is removed.</p> <p>Do the same thing for the next video player. Click on the play button, then click on the exit, but nothing occurs unless the first video is playing.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function addPlayerHandler(evt) { const play = evt.target; play.closest(".wrap").player = {}; play.disabled = true; } function removePlayerHandler(evt) { const el = evt.target; const container = el.closest(".container"); const wrapper = container.querySelector(".wrap"); if (wrapper.player) { return removePlayer(wrapper); } } function removePlayer(wrapper) { wrapper.querySelector(".play").disabled = false; delete wrapper.player; console.log("removePlayer"); } for (let curtain of document.querySelectorAll(".curtain")) { curtain.querySelector(".play").addEventListener( 'click', addPlayerHandler, ); curtain.querySelector(".exit").addEventListener( 'click', removePlayerHandler, ); }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.curtain { border: solid; } .play[disabled]::after { content: " - Now Playing"; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="container"&gt; &lt;div class="curtain"&gt; &lt;div class="wrap"&gt; &lt;div class="video"&gt;&lt;/div&gt; &lt;button class="play"&gt;Play&lt;/button&gt; &lt;/div&gt; &lt;button class="exit" type="button"&gt;Exit&lt;/button&gt; &lt;/div&gt; &lt;div class="curtain"&gt; &lt;div class="wrap"&gt; &lt;div class="video"&gt;&lt;/div&gt; &lt;button class="play"&gt;Play&lt;/button&gt; &lt;/div&gt; &lt;button class="exit" type="button"&gt;Exit&lt;/button&gt; &lt;/div&gt; &lt;div class="curtain"&gt; &lt;div class="wrap"&gt; &lt;div class="video"&gt;&lt;/div&gt; &lt;button class="play"&gt;Play&lt;/button&gt; &lt;/div&gt; &lt;button class="exit" type="button"&gt;Exit&lt;/button&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>This part of the code would need to be changed to something else. I think this part of the code needs to be changed to work properly.</p> <pre><code> function removePlayerHandler(evt) { const el = evt.target; const container = el.closest(&quot;.container&quot;); const wrapper = container.querySelector(&quot;.wrap&quot;); if (wrapper.player) { return removePlayer(wrapper); } } </code></pre>
[ { "answer_id": 74396143, "author": "Bartosz Szymański", "author_id": 7100461, "author_profile": "https://Stackoverflow.com/users/7100461", "pm_score": 2, "selected": true, "text": "@PropertySource" }, { "answer_id": 74396216, "author": "birca123", "author_id": 10231374, "author_profile": "https://Stackoverflow.com/users/10231374", "pm_score": 0, "selected": false, "text": "properties" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74396111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17631451/" ]
74,396,134
<p>The function takes the root node of a binary tree and a target value and returns the node that comes before the target value in an in-order traversal.</p> <p>Constraint is: If the target is the first value in an in-order traversal, return null.</p> <pre><code>function inOrderPredecessor(rootNode, target) { if (rootNode === null || rootNode.val === target) { return null } if (rootNode.left) { current = rootNode.left; while(current.right != null) { current = current.right; } return current.val; } } </code></pre> <p>I've been working on this for hours and I keep hitting my head against a wall. An embarassingly long amount of time.. Over 4 hours watching videos etc.</p> <p>The function can ONLY take in the rootNode and the target value.</p> <p>Psuedo Code I have been thinking -</p> <ol> <li>Start at left of rootNode since predecessor is always smaller.</li> <li>From first left go right, until you can't go right anymore.</li> <li>Return right most item when there are no more rights to take.</li> </ol>
[ { "answer_id": 74396358, "author": "caTS", "author_id": 18244921, "author_profile": "https://Stackoverflow.com/users/18244921", "pm_score": 0, "selected": false, "text": "// simple inorder traversal implementation\nfunction inorder(node, a = []) {\n if (node) {\n inorder(node.left, a);\n a.push(node);\n inorder(node.right, a);\n }\n \n return a;\n}\n\nconst tree = {\n value: 4,\n left: { value: 2, left: { value: 1 }, right: { value: 3 } },\n right: { value: 5 },\n};\n\n// show that the tree values are already in order\nconsole.log(inorder(tree).map((node) => node.value));\n\n// return node that was before the target\nfunction predecessor(node, target) {\n const traversed = inorder(node);\n \n return traversed[traversed.indexOf(target) - 1];\n}\n\n// should be 3, since tree.value is 4, and 3 is before 4\nconsole.log(predecessor(tree, tree));" }, { "answer_id": 74397394, "author": "Bergi", "author_id": 1048572, "author_profile": "https://Stackoverflow.com/users/1048572", "pm_score": 3, "selected": true, "text": "function inOrderPredecessor(node, target) {\n if (node === null) {\n return null\n }\n if (target <= node.val) {\n // the node lies to the right of, or at the target value\n // so we need to find a node that precedes the target from the left child tree\n return inOrderPredecessor(node.left, target);\n } else { // target > node.val\n // the node lies to the left of the target value (and would qualify)\n // but there might be a node in its right child tree that is closer\n // (but not larger than or equal to the target)\n const res = inOrderPredecessor(node.right, target);\n if (res) {\n // if there is, return it\n return res;\n } else {\n // otherwise return the node itself\n return node;\n }\n }\n}\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74396134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19677744/" ]
74,396,147
<p>Table <code>T1</code>:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Id</th> <th>R1</th> <th>R2</th> <th>R3</th> </tr> </thead> <tbody> <tr> <td>Id1</td> <td>r1_d1</td> <td>r2_d1</td> <td>r3_d1</td> </tr> <tr> <td>Id2</td> <td>r1_d2</td> <td>r2_d2</td> <td>r3_d2</td> </tr> <tr> <td>Id3</td> <td>r1_d3</td> <td>r2_d2</td> <td>r3_d3</td> </tr> <tr> <td>Id4</td> <td>r1_d4</td> <td>r2_d4</td> <td>r3_d4</td> </tr> </tbody> </table> </div> <p>Table <code>T2</code>:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Id</th> <th>K_R1</th> <th>K2</th> </tr> </thead> <tbody> <tr> <td>Id1</td> <td>r1_d1</td> <td>k2_d1</td> </tr> <tr> <td>Id2</td> <td>r1_d3</td> <td>k2_d2</td> </tr> <tr> <td>Id3</td> <td>r1_d4</td> <td>k2_d4</td> </tr> </tbody> </table> </div> <p>I need some properties of first table and an additional result indicating if <code>T1.R1 == T2.K_R1</code>:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Id</th> <th>R1</th> <th>R2</th> <th>P1</th> </tr> </thead> <tbody> <tr> <td>Id1</td> <td>r1_d1</td> <td>r2_d1</td> <td>true</td> </tr> <tr> <td>Id2</td> <td>r1_d2</td> <td>r2_d2</td> <td>false</td> </tr> <tr> <td>Id3</td> <td>r1_d3</td> <td>r2_d2</td> <td>true</td> </tr> <tr> <td>Id4</td> <td>r1_d4</td> <td>r2_d4</td> <td>true</td> </tr> </tbody> </table> </div> <p><code>LEFT JOIN</code> will return all entries of <code>T1</code> and matching entries of <code>T2</code>, but will have all properties of <code>T2</code> too, which is not needed. How (considering performance too) to exclude unnecessary properties and produce a boolean- instead of actual value?</p>
[ { "answer_id": 74396358, "author": "caTS", "author_id": 18244921, "author_profile": "https://Stackoverflow.com/users/18244921", "pm_score": 0, "selected": false, "text": "// simple inorder traversal implementation\nfunction inorder(node, a = []) {\n if (node) {\n inorder(node.left, a);\n a.push(node);\n inorder(node.right, a);\n }\n \n return a;\n}\n\nconst tree = {\n value: 4,\n left: { value: 2, left: { value: 1 }, right: { value: 3 } },\n right: { value: 5 },\n};\n\n// show that the tree values are already in order\nconsole.log(inorder(tree).map((node) => node.value));\n\n// return node that was before the target\nfunction predecessor(node, target) {\n const traversed = inorder(node);\n \n return traversed[traversed.indexOf(target) - 1];\n}\n\n// should be 3, since tree.value is 4, and 3 is before 4\nconsole.log(predecessor(tree, tree));" }, { "answer_id": 74397394, "author": "Bergi", "author_id": 1048572, "author_profile": "https://Stackoverflow.com/users/1048572", "pm_score": 3, "selected": true, "text": "function inOrderPredecessor(node, target) {\n if (node === null) {\n return null\n }\n if (target <= node.val) {\n // the node lies to the right of, or at the target value\n // so we need to find a node that precedes the target from the left child tree\n return inOrderPredecessor(node.left, target);\n } else { // target > node.val\n // the node lies to the left of the target value (and would qualify)\n // but there might be a node in its right child tree that is closer\n // (but not larger than or equal to the target)\n const res = inOrderPredecessor(node.right, target);\n if (res) {\n // if there is, return it\n return res;\n } else {\n // otherwise return the node itself\n return node;\n }\n }\n}\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74396147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11062204/" ]
74,396,165
<p>Using rust with glfw and gl bindings.</p> <p>I have created an array of vertices for usage in vbo:</p> <pre><code>let x = 2.0 / ((HORIZONTAL_BOOK_AMOUNT * 2) + HORIZONTAL_BOOK_AMOUNT + 1) as f32; // x is the desired distance based on width of NDC divided by amount of horizontal objects to draw // in the case of attached picture the HORIZONTAL_BOOK_AMOUNT would be 4 let mut vbo = 0; let side = x * IMAGE_HEIGHT_MULTIPLIER; // here x is multiplied by constant, equaling to desired height of object let vertices: Vec&lt;f32&gt; = vec![ -1.0 + x, 1.0 - x, 0.0, 1.0, //top left -1.0 + 3.0 * x, 1.0 - x, 1.0, 1.0, // top right -1.0 + 3.0 * x, 1.0 - x - (2.0 * side), 1.0, 0.0, //bottom right -1.0 + 3.0 * x, 1.0 - x - (2.0 * side), 1.0, 0.0, //bottom right -1.0 + x, 1.0 - x - (2.0 * side), 0.0, 0.0, //bottom left -1.0 + x, 1.0 - x, 0.0, 1.0]; //top left gl::GenBuffers(1, &amp;mut vbo); gl::BindBuffer(gl::ARRAY_BUFFER, vbo); gl::BufferData(gl::ARRAY_BUFFER, (vertices.len() * std::mem::size_of::&lt;GLfloat&gt;()) as GLsizeiptr, &amp;vertices[0] as *const f32 as *const std::ffi::c_void, gl::STATIC_DRAW); </code></pre> <p>The problem is that after drawing the distance between top left vertex and top border should be equal to distance between top left vertex and left border.</p> <p>The achieved effect, distances are not equal and are forming a rectangle:</p> <p><a href="https://i.imgur.com/0VAOzZq.png" rel="nofollow noreferrer"><img src="https://i.imgur.com/0VAOzZq.png" alt="Achieved effect" /></a></p> <p>I tried recreating the issue with shorter example but it yielded similar results. Possibly it could be window size issue, but it is just my guess</p> <p>The desired effect, which forms a square:</p> <p><a href="https://i.imgur.com/A4EnFcf.png" rel="nofollow noreferrer"><img src="https://i.imgur.com/A4EnFcf.png" alt="Desired effect" /></a></p> <p>VAO code:</p> <pre><code>let mut VAO = 0; gl::GenVertexArrays(1, &amp;mut VAO); gl::BindVertexArray(VAO); let stride = 4 * std::mem::size_of::&lt;GLfloat&gt;() as GLsizei; gl::VertexAttribPointer(0, 2, gl::FLOAT, gl::FALSE, stride, std::ptr::null()); gl::EnableVertexAttribArray(0); gl::VertexAttribPointer(1, 2, gl::FLOAT, gl::FALSE, stride, (2 * std::mem::size_of::&lt;GLfloat&gt;()) as *const std::ffi::c_void); gl::EnableVertexAttribArray(1); </code></pre> <p>Vertex shader:</p> <pre><code>#version 430 core layout (location = 0) in vec2 aPos; layout (location = 1) in vec2 aTexCoord; out vec2 TexCoord; uniform mat4 translatematrix; // this matrix is used for drawing objects by iterating through array // of (in this case:) books based on amount of them and horizontal // // amount void main() { gl_Position = translatematrix * vec4(aPos, 0.0, 1.0); TexCoord = aTexCoord; } </code></pre> <p>Frag shader:</p> <pre><code>#version 430 core out vec4 FragColor; in vec2 TexCoord; uniform sampler2D tex1; void main() { FragColor = texture(tex1, TexCoord); } </code></pre> <p>glViewport is set using glfw window event:</p> <pre><code>for (_, event) in glfw::flush_messages(&amp;events) { ... match event { glfw::WindowEvent::FramebufferSize(width, height) =&gt; { gl::Viewport(0, 0, width, height); }, </code></pre>
[ { "answer_id": 74397090, "author": "Yakov Galka", "author_id": 277176, "author_profile": "https://Stackoverflow.com/users/277176", "pm_score": 2, "selected": true, "text": "x" }, { "answer_id": 74398310, "author": "Rabbid76", "author_id": 5577765, "author_profile": "https://Stackoverflow.com/users/5577765", "pm_score": 0, "selected": false, "text": "y = x * width / height\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74396165", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20274040/" ]
74,396,182
<p>I have a list of tuples of [(city name, country name), ...].</p> <p>I'm trying to sort the list alphabetically so that the country names are ordered A-Z, and then if there is more than one city in that country, the cities in that country are then also ordered alphabetically.</p> <p>So far I've tried using sorted() with a lambda function (below), but it doesn't seem to work. I'm pretty new to Python, so any help would be massively appreciated!!</p> <pre><code>sorted(list, key=lambda element: (element[0], element[1])) </code></pre>
[ { "answer_id": 74396220, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 2, "selected": false, "text": "lst = [\n (\"Prague\", \"Czech Republic\"),\n (\"Bratislava\", \"Slovakia\"),\n (\"Brno\", \"Czech Republic\"),\n]\n\nprint(sorted(lst, key=lambda t: (t[1], t[0])))\n" }, { "answer_id": 74396327, "author": "Rodrigo Rodrigues", "author_id": 2938526, "author_profile": "https://Stackoverflow.com/users/2938526", "pm_score": 1, "selected": false, "text": "austria" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74396182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20473020/" ]
74,396,257
<p>I have a POST API to create a register on the database. My goal is to be able to log every 4XX request (with the response) for another team to view that list/search the data, with the option to download the request JSON sent in that call.</p> <p>What's the best way to archive that? Its just to create a logs table in the database?</p>
[ { "answer_id": 74396798, "author": "Kevin Bui", "author_id": 2994920, "author_profile": "https://Stackoverflow.com/users/2994920", "pm_score": 1, "selected": false, "text": "LogResponseReceived" }, { "answer_id": 74396854, "author": "Stevy", "author_id": 13326231, "author_profile": "https://Stackoverflow.com/users/13326231", "pm_score": -1, "selected": false, "text": "Log::warning('User is accessing something', ['user' => Auth::user()]);\nLog::info('User is accessing ', ['user' => Auth::user()]);\nLog::emergency($message); \nLog::alert($message);\nLog::critical($message); \nLog::error($message); \nLog::notice($message); \nLog::debug($message);\n" }, { "answer_id": 74397045, "author": "bariskau", "author_id": 11199696, "author_profile": "https://Stackoverflow.com/users/11199696", "pm_score": 0, "selected": false, "text": "<?php\n\nnamespace App\\Http\\Middleware;\n\nuse Closure;\nuse Illuminate\\Support\\Facades\\Log;\n\nclass RequestLogger\n{\n /**\n * Handle an incoming request.\n *\n * @param \\Illuminate\\Http\\Request $request\n * @param \\Closure $next\n * @return mixed\n */\n public function handle($request, Closure $next)\n {\n $response = $next($request);\n\n //here you can check the request to be logged\n $log = [\n 'URI' => $request->getUri(),\n 'METHOD' => $request->getMethod(),\n 'REQUEST_BODY' => $request->all(),\n 'RESPONSE' => $response->getContent()\n ];\n\n return $response;\n }\n}\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74396257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3455453/" ]
74,396,269
<p>I'm trying to export a variable in this manner:</p> <pre><code>P=&quot;A=&quot;X&quot;&quot; echo $P P=X export $$P &lt;- can't get this to work, tried a bunch of permutations </code></pre> <p>Desired out put is then to be effectively 'export A=X' In the example I want to 'export P=X' to be the command I run, however I cannot get it to work correctly</p>
[ { "answer_id": 74396798, "author": "Kevin Bui", "author_id": 2994920, "author_profile": "https://Stackoverflow.com/users/2994920", "pm_score": 1, "selected": false, "text": "LogResponseReceived" }, { "answer_id": 74396854, "author": "Stevy", "author_id": 13326231, "author_profile": "https://Stackoverflow.com/users/13326231", "pm_score": -1, "selected": false, "text": "Log::warning('User is accessing something', ['user' => Auth::user()]);\nLog::info('User is accessing ', ['user' => Auth::user()]);\nLog::emergency($message); \nLog::alert($message);\nLog::critical($message); \nLog::error($message); \nLog::notice($message); \nLog::debug($message);\n" }, { "answer_id": 74397045, "author": "bariskau", "author_id": 11199696, "author_profile": "https://Stackoverflow.com/users/11199696", "pm_score": 0, "selected": false, "text": "<?php\n\nnamespace App\\Http\\Middleware;\n\nuse Closure;\nuse Illuminate\\Support\\Facades\\Log;\n\nclass RequestLogger\n{\n /**\n * Handle an incoming request.\n *\n * @param \\Illuminate\\Http\\Request $request\n * @param \\Closure $next\n * @return mixed\n */\n public function handle($request, Closure $next)\n {\n $response = $next($request);\n\n //here you can check the request to be logged\n $log = [\n 'URI' => $request->getUri(),\n 'METHOD' => $request->getMethod(),\n 'REQUEST_BODY' => $request->all(),\n 'RESPONSE' => $response->getContent()\n ];\n\n return $response;\n }\n}\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74396269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14322433/" ]
74,396,285
<p>I am using basiclightbox to show text from an external txt file.</p> <p>It works, but I can't apply styles and size to the result.</p> <p>I've done this:</p> <pre><code> document.querySelector('button.html1001').onclick = () =&gt; { basicLightbox.create(` &lt;/div&gt; &lt;h1&gt;&lt;p&gt; &lt;object data=&quot;test.txt&quot;&gt;&lt;/object&gt; &lt;/p&gt;&lt;/h1&gt; &lt;/div&gt; `).show() } </code></pre> <p>and</p> <pre><code> &lt;h1&gt;&lt;p&gt; &lt;object data=&quot;test.txt&quot;&gt;&lt;/object&gt; &lt;/p&gt;&lt;/h1&gt; </code></pre> <p>and tried including styles in the text file, but this is the result of the popup:</p> <pre><code> &lt;h1&gt;&lt;p&gt; &lt;br&gt;&lt;br&gt;&lt;br&gt; &lt;br&gt; Testing text for testing &lt;br&gt; &lt;/p&gt;&lt;h1&gt; </code></pre> <p>It pops up with a black background and no style applies to the text.</p> <p>Anyone have any ideas how to apply styles and background color to this?</p> <p>Thanks in advance.</p>
[ { "answer_id": 74396798, "author": "Kevin Bui", "author_id": 2994920, "author_profile": "https://Stackoverflow.com/users/2994920", "pm_score": 1, "selected": false, "text": "LogResponseReceived" }, { "answer_id": 74396854, "author": "Stevy", "author_id": 13326231, "author_profile": "https://Stackoverflow.com/users/13326231", "pm_score": -1, "selected": false, "text": "Log::warning('User is accessing something', ['user' => Auth::user()]);\nLog::info('User is accessing ', ['user' => Auth::user()]);\nLog::emergency($message); \nLog::alert($message);\nLog::critical($message); \nLog::error($message); \nLog::notice($message); \nLog::debug($message);\n" }, { "answer_id": 74397045, "author": "bariskau", "author_id": 11199696, "author_profile": "https://Stackoverflow.com/users/11199696", "pm_score": 0, "selected": false, "text": "<?php\n\nnamespace App\\Http\\Middleware;\n\nuse Closure;\nuse Illuminate\\Support\\Facades\\Log;\n\nclass RequestLogger\n{\n /**\n * Handle an incoming request.\n *\n * @param \\Illuminate\\Http\\Request $request\n * @param \\Closure $next\n * @return mixed\n */\n public function handle($request, Closure $next)\n {\n $response = $next($request);\n\n //here you can check the request to be logged\n $log = [\n 'URI' => $request->getUri(),\n 'METHOD' => $request->getMethod(),\n 'REQUEST_BODY' => $request->all(),\n 'RESPONSE' => $response->getContent()\n ];\n\n return $response;\n }\n}\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74396285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14257245/" ]
74,396,289
<p>I use strings to represent my data and pass it around. Before using it I have to parse it and get the data out of string. I don't want to check for parse errors on runtime.</p> <p>How can I give a special type to strings only produced by factory functions and make sure they fail on any other string types.</p> <pre><code>type MyData = string let i = 0 function gen_id(): MyData { return `hello__${i}` } function hello(_: MyData) { console.log(_.split('__')[1]) } hello(gen_id()) hello('world') // I want this to give compile error </code></pre> <p>Currently this doesn't produce an compile error.</p>
[ { "answer_id": 74396798, "author": "Kevin Bui", "author_id": 2994920, "author_profile": "https://Stackoverflow.com/users/2994920", "pm_score": 1, "selected": false, "text": "LogResponseReceived" }, { "answer_id": 74396854, "author": "Stevy", "author_id": 13326231, "author_profile": "https://Stackoverflow.com/users/13326231", "pm_score": -1, "selected": false, "text": "Log::warning('User is accessing something', ['user' => Auth::user()]);\nLog::info('User is accessing ', ['user' => Auth::user()]);\nLog::emergency($message); \nLog::alert($message);\nLog::critical($message); \nLog::error($message); \nLog::notice($message); \nLog::debug($message);\n" }, { "answer_id": 74397045, "author": "bariskau", "author_id": 11199696, "author_profile": "https://Stackoverflow.com/users/11199696", "pm_score": 0, "selected": false, "text": "<?php\n\nnamespace App\\Http\\Middleware;\n\nuse Closure;\nuse Illuminate\\Support\\Facades\\Log;\n\nclass RequestLogger\n{\n /**\n * Handle an incoming request.\n *\n * @param \\Illuminate\\Http\\Request $request\n * @param \\Closure $next\n * @return mixed\n */\n public function handle($request, Closure $next)\n {\n $response = $next($request);\n\n //here you can check the request to be logged\n $log = [\n 'URI' => $request->getUri(),\n 'METHOD' => $request->getMethod(),\n 'REQUEST_BODY' => $request->all(),\n 'RESPONSE' => $response->getContent()\n ];\n\n return $response;\n }\n}\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74396289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3994249/" ]
74,396,305
<p>Suppose I have:</p> <p><code>arr1 = np.array([[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15], [16,17,18,19,20], [21,22,23,24,25]])</code></p> <p>And the empty matrix:</p> <pre><code>matrix = np.zeros((10, 10)) matrix[:] = np.NaN </code></pre> <p>I want to populate <code>matrix</code> with each element within <code>arr1</code>, but diagonally. This is the expected output:</p> <pre><code>array([[ nan, nan, nan, nan, nan, nan, nan, nan, nan, nan], [ 1, nan, nan, nan, nan, nan, nan, nan, nan, nan], [ 6, 2, nan, nan, nan, nan, nan, nan, nan, nan], [ 11, 7, 3, nan, nan, nan, nan, nan, nan, nan], [ 16, 12, 8, 4, nan, nan, nan, nan, nan, nan], [ 21, 17, 13, 9, 5, nan, nan, nan, nan, nan], [ nan, 22, 18, 14, 10, nan, nan, nan, nan, nan], [ nan, nan, 23, 19, 15, nan, nan, nan, nan, nan], [ nan, nan, nan, 24, 20, nan, nan, nan, nan, nan], [ nan, nan, nan, nan, 25, nan, nan, nan, nan, nan]]) </code></pre> <p>This is what I have tried so far without succeeding:</p> <pre><code>arr1 = np.array([[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15], [16,17,18,19,20], [21,22,23,24,25]]) matrix = np.zeros((10, 10)) matrix[:] = np.NaN for i, array in enumerate(arr1): for row_matrix in matrix: row_matrix = np.diag(array, -i-1) break </code></pre> <p>This is the output I have from the above code:</p> <pre><code>array([[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 21, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 22, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 23, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 24, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 25, 0, 0, 0, 0, 0]]) </code></pre>
[ { "answer_id": 74396798, "author": "Kevin Bui", "author_id": 2994920, "author_profile": "https://Stackoverflow.com/users/2994920", "pm_score": 1, "selected": false, "text": "LogResponseReceived" }, { "answer_id": 74396854, "author": "Stevy", "author_id": 13326231, "author_profile": "https://Stackoverflow.com/users/13326231", "pm_score": -1, "selected": false, "text": "Log::warning('User is accessing something', ['user' => Auth::user()]);\nLog::info('User is accessing ', ['user' => Auth::user()]);\nLog::emergency($message); \nLog::alert($message);\nLog::critical($message); \nLog::error($message); \nLog::notice($message); \nLog::debug($message);\n" }, { "answer_id": 74397045, "author": "bariskau", "author_id": 11199696, "author_profile": "https://Stackoverflow.com/users/11199696", "pm_score": 0, "selected": false, "text": "<?php\n\nnamespace App\\Http\\Middleware;\n\nuse Closure;\nuse Illuminate\\Support\\Facades\\Log;\n\nclass RequestLogger\n{\n /**\n * Handle an incoming request.\n *\n * @param \\Illuminate\\Http\\Request $request\n * @param \\Closure $next\n * @return mixed\n */\n public function handle($request, Closure $next)\n {\n $response = $next($request);\n\n //here you can check the request to be logged\n $log = [\n 'URI' => $request->getUri(),\n 'METHOD' => $request->getMethod(),\n 'REQUEST_BODY' => $request->all(),\n 'RESPONSE' => $response->getContent()\n ];\n\n return $response;\n }\n}\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74396305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10623448/" ]
74,396,332
<p>I am having a few issues. I have a sheet called (RF) in which I have information divided by places (Passenger seat, driver seat, etc), each one is identified with a number (1, 2, 3, 4. Four is the amount of categories but it could change so that is why I am trying a loop). Something like this: <a href="https://i.stack.imgur.com/uhFz2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uhFz2.png" alt="info" /></a></p> <p>So what I am trying to do is to iterate through each of the rows and filter them by the number on column A (as I said I would need to do it someway through a loop or something because those &quot;numbers&quot; I use as identifiers may vary). Once it's filtered, I am trying to copy the filtered data to a new sheet called just like the number. But it's just not working. I solve an error and then another one occurs and it's driving me crazy.</p> <p>I've seen a few posts on StackOverFlow trying to get close to my problem but I have not found any solution.</p> <pre><code>function bucleInicialPrueba(){ var spreadsheet = SpreadsheetApp.getActive(); var hojaRF = spreadsheet.getSheetByName('RF'); var ultFila = spreadsheet.getSheetByName('RF').getLastRow(); var data = hojaRF.getDataRange().getValues(); spreadsheet.getRange('1:156').activate(); hojaRF.getRange('1:156').createFilter(); for(j=0;j&lt;=data.length;j++){ if(data[j][0]!=j){ hojaRF.hideRows(j+1); hojaRF.getRange('A1').activate(); for(i=1;i&lt;=4;i++){ var filter = hojaRF.getFilter(); if (filter!=null) { var criterio = SpreadsheetApp.newFilterCriteria(); criterio.whenNumberEqualTo(i).build(); hojaRF.getFilter().setColumnFilterCriteria(i, criterio); spreadsheet.insertSheet(1); spreadsheet.getActiveSheet().setName(i); hojaRF.getRange('A'+ j + ':AK' + j).copyTo(spreadsheet.getSheetByName(i).getActiveRange(),SpreadsheetApp.CopyPasteType.PASTE_VALUES, false) hojaRF.getFilter().remove(); } else { var criterio = SpreadsheetApp.newFilterCriteria(); criterio.whenNumberEqualTo(i).build(); hojaRF.getRange(1, 1, hojaRF.getLastRow()).createFilter().setColumnFilterCriteria(i, criterio); spreadsheet.insertSheet(1); spreadsheet.getActiveSheet().setName(i); hojaRF.getRange('A'+ j + ':AK' + j).copyTo(spreadsheet.getSheetByName(i).getActiveRange(),SpreadsheetApp.CopyPasteType.PASTE_VALUES, false) } } } } }; </code></pre>
[ { "answer_id": 74396798, "author": "Kevin Bui", "author_id": 2994920, "author_profile": "https://Stackoverflow.com/users/2994920", "pm_score": 1, "selected": false, "text": "LogResponseReceived" }, { "answer_id": 74396854, "author": "Stevy", "author_id": 13326231, "author_profile": "https://Stackoverflow.com/users/13326231", "pm_score": -1, "selected": false, "text": "Log::warning('User is accessing something', ['user' => Auth::user()]);\nLog::info('User is accessing ', ['user' => Auth::user()]);\nLog::emergency($message); \nLog::alert($message);\nLog::critical($message); \nLog::error($message); \nLog::notice($message); \nLog::debug($message);\n" }, { "answer_id": 74397045, "author": "bariskau", "author_id": 11199696, "author_profile": "https://Stackoverflow.com/users/11199696", "pm_score": 0, "selected": false, "text": "<?php\n\nnamespace App\\Http\\Middleware;\n\nuse Closure;\nuse Illuminate\\Support\\Facades\\Log;\n\nclass RequestLogger\n{\n /**\n * Handle an incoming request.\n *\n * @param \\Illuminate\\Http\\Request $request\n * @param \\Closure $next\n * @return mixed\n */\n public function handle($request, Closure $next)\n {\n $response = $next($request);\n\n //here you can check the request to be logged\n $log = [\n 'URI' => $request->getUri(),\n 'METHOD' => $request->getMethod(),\n 'REQUEST_BODY' => $request->all(),\n 'RESPONSE' => $response->getContent()\n ];\n\n return $response;\n }\n}\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74396332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20472752/" ]
74,396,356
<p>There are multiple ways to fill missing values in R. However, I can't find a solution for filling just the last n NAs.</p> <p>Available options:</p> <pre><code>na_vector &lt;- c(1, NA, NA, NA, 2, 3, NA, NA) library(zoo) na.locf(na_vector) # Outputs: [1] 1 1 1 1 2 3 3 3 na.locf0(na_vector, maxgap = 2) # Outputs: [1] 1 NA NA NA 2 3 3 3 </code></pre> <p>How I would like it to be:</p> <pre><code>na_vector &lt;- c(1, NA, NA, NA, 2, 3, NA, NA) fill_na &lt;- function(vector, n){ ... } fill_na(na_vector, n = 1) # Outputs: [1] 1 1 NA NA 2 3 3 NA fill_na(na_vector, n = 2) # Outputs: [1] 1 1 1 NA 2 3 3 3 </code></pre>
[ { "answer_id": 74396508, "author": "Santiago", "author_id": 13507658, "author_profile": "https://Stackoverflow.com/users/13507658", "pm_score": 2, "selected": true, "text": "dplyr" }, { "answer_id": 74402957, "author": "G. Grothendieck", "author_id": 516548, "author_profile": "https://Stackoverflow.com/users/516548", "pm_score": 0, "selected": false, "text": "a" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74396356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15881999/" ]
74,396,357
<p>I was trying to get the substring from a string I am using in my program as follows:</p> <pre><code>mystring.Substring(mystring.Length - 4) </code></pre> <p>The Visual Studio IntelliSense recommended I use index and range operators as follows:</p> <pre><code>mystring[^4..] </code></pre> <p>I glanced through the documentation <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/ranges" rel="nofollow noreferrer">here</a> and it seems like using just <code>mystring[^4]</code> would work just fine. Why does the IntelliSense recommend to use the extra <code>..</code> in there, are there any benefits from adding it?</p>
[ { "answer_id": 74396462, "author": "gunr2171", "author_id": 1043380, "author_profile": "https://Stackoverflow.com/users/1043380", "pm_score": 4, "selected": true, "text": "^4" }, { "answer_id": 74396465, "author": "Slava Knyazev", "author_id": 4088472, "author_profile": "https://Stackoverflow.com/users/4088472", "pm_score": 2, "selected": false, "text": ".." } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74396357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13949270/" ]
74,396,361
<p>I am using the pynput and winsound modules to make a program that makes the pc play the sound of the keys and mouse. The problem is that when I press a key and hold it down the key is triggered repeatedly, which causes the sound to play repeatedly in a loop until I release the key.</p> <p>I followed this solution to create the program: <a href="https://stackoverflow.com/a/62172376/4779475">Play Sound whenever key is pressed in Python</a></p> <p>Then as I wanted to play the mouse sound as well, I found this article: <a href="https://nitratine.net/blog/post/how-to-use-pynputs-mouse-and-keyboard-listener-at-the-same-time/#:%7E:text=The%20first%20solution%20I%20recommend%20is%20to%20use,KeyboardListener%20This%20is%20very%20similar%20to%20the%20following%3A" rel="nofollow noreferrer">How to Use pynput's Mouse and Keyboard Listener at the Same Time</a></p> <p>So, I ended up with this code:</p> <pre class="lang-py prettyprint-override"><code>from pynput.mouse import Listener as MouseListener from pynput.keyboard import Listener as KeyboardListener import winsound def on_press(key): winsound.PlaySound(&quot;sound.wav&quot;, winsound.SND_ASYNC) print(&quot;Key pressed: {0}&quot;.format(key)) def on_release(key): print(&quot;Key released: {0}&quot;.format(key)) def on_click(x, y, button, pressed): if pressed: winsound.PlaySound(&quot;mouse_click.wav&quot;, winsound.SND_ASYNC) print('Mouse clicked at ({0}, {1}) with {2}'.format(x, y, button)) else: print('Mouse released at ({0}, {1}) with {2}'.format(x, y, button)) keyboard_listener = KeyboardListener(on_press=on_press, on_release=on_release) mouse_listener = MouseListener(on_click=on_click) keyboard_listener.start() mouse_listener.start() keyboard_listener.join() mouse_listener.join() </code></pre> <p>Now, the mouse click does exactly what I want the keyboard to do! It plays the sound once while it is being held until I release it!</p> <p>I just don't know how to make the keyboard play the sound only once until the key is released, like the mouse!!!</p>
[ { "answer_id": 74396462, "author": "gunr2171", "author_id": 1043380, "author_profile": "https://Stackoverflow.com/users/1043380", "pm_score": 4, "selected": true, "text": "^4" }, { "answer_id": 74396465, "author": "Slava Knyazev", "author_id": 4088472, "author_profile": "https://Stackoverflow.com/users/4088472", "pm_score": 2, "selected": false, "text": ".." } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74396361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4779475/" ]
74,396,374
<p>I have a Postgres table that looks like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">Name</th> <th style="text-align: center;">Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td style="text-align: center;">business_id (PK)</td> <td style="text-align: center;">int4</td> <td>Business ID</td> </tr> <tr> <td style="text-align: center;">day (PK)</td> <td style="text-align: center;">int4</td> <td>Day of week (0-6, monday is zero)</td> </tr> <tr> <td style="text-align: center;">open</td> <td style="text-align: center;">time</td> <td>Open time</td> </tr> <tr> <td style="text-align: center;">close</td> <td style="text-align: center;">time</td> <td>Close time</td> </tr> </tbody> </table> </div> <p>Every row stores open and closing times for a business on a specific day of week. Example data for a business looks like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>business_id</th> <th>day</th> <th>open</th> <th>close</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>0</td> <td>18:00</td> <td>23:00</td> </tr> <tr> <td>1</td> <td>1</td> <td>18:00</td> <td>23:00</td> </tr> <tr> <td>1</td> <td>2</td> <td>18:00</td> <td>23:00</td> </tr> <tr> <td>1</td> <td>3</td> <td>18:00</td> <td>23:00</td> </tr> <tr> <td>1</td> <td>4</td> <td>18:00</td> <td>01:00</td> </tr> <tr> <td>1</td> <td>5</td> <td>18:00</td> <td>02:00</td> </tr> </tbody> </table> </div> <p>You can see that the business is opened from 18:00 to 23:00 from Mo.-Fr. Note that on the weekend the opening hours extend over to the next day.</p> <p>I'm trying to write a single statement query that determines if a business is opened now or at a specific time.</p> <p>I tried writing the query below but the results are wrong and I can't think of another way to solve this problem.</p> <pre><code>select count(*) from ( select * from business_hours bh where bh.business_id = 1 and bh.day = extract(dow from now()) - 1 union all select * from business_hours bh where bh.business_id = 1 and bh.day = extract(dow from now()) - 1 ) a where (&quot;from&quot; &lt; &quot;to&quot; and now()::time between &quot;from&quot; and &quot;to&quot;) or (&quot;from&quot; &gt; &quot;to&quot; and now()::time not between &quot;to&quot; and &quot;from&quot;) </code></pre> <p>Thank you for helping me out with this query</p>
[ { "answer_id": 74396462, "author": "gunr2171", "author_id": 1043380, "author_profile": "https://Stackoverflow.com/users/1043380", "pm_score": 4, "selected": true, "text": "^4" }, { "answer_id": 74396465, "author": "Slava Knyazev", "author_id": 4088472, "author_profile": "https://Stackoverflow.com/users/4088472", "pm_score": 2, "selected": false, "text": ".." } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74396374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6090547/" ]
74,396,379
<p>As mentioned in the title, I want to use multiple-dispatch to assign different behaviors of the same struct, distinguished by Symbol. The struct can be constructed as follows:</p> <pre><code>struct AbstractAlgorithm algorithmName::String algorithmSymbol::Symbol function AbstractAlgorithm(algorithmName::String) if algorithmName ∉ (&quot;Value Iteration&quot;, &quot;Policy Iteration&quot;) error(&quot;Given algorithm $algorithmName not defined yet.&quot;) elseif algorithmName==&quot;Value Iteration&quot; new(algorithmName, Symbol(&quot;vIter&quot;)) elseif algorithmName==&quot;Policy Iteration&quot; new(algorithmName, Symbol(&quot;pIter&quot;)) end end end </code></pre> <p>And I wanted to distinguish the same struct using different symbols in a function, such as:</p> <pre><code>function A(a::AbstractAlgorithm with Symbol vIter) = do A1 function A(a::AbstractAlgorithm with Symbol pIter) = do A2 </code></pre> <p>How should I design function A using multiple-dispatch?</p>
[ { "answer_id": 74397582, "author": "Giovanni", "author_id": 16204281, "author_profile": "https://Stackoverflow.com/users/16204281", "pm_score": 2, "selected": false, "text": "struct AbstractAlgorithm{T}\n algorithmName::String\n\n function AbstractAlgorithm(algorithmName::String)\n if algorithmName ∉ (\"Value Iteration\", \"Policy Iteration\")\n error(\"Given algorithm $algorithmName not defined yet.\")\n elseif algorithmName==\"Value Iteration\"\n new{Val{:vIter}}(algorithmName)\n elseif algorithmName==\"Policy Iteration\"\n new{Val{:pIter}}(algorithmName)\n end\n end\nend\n\nfunction A(a::AbstractAlgorithm{Val{:pIter}})\n A1\nend\n\nfunction A(a::AbstractAlgorithm{Val{:vIter}})\n A2\nend\n" }, { "answer_id": 74398611, "author": "DNF", "author_id": 2749865, "author_profile": "https://Stackoverflow.com/users/2749865", "pm_score": 3, "selected": false, "text": "AbstractNN" }, { "answer_id": 74398771, "author": "Bogumił Kamiński", "author_id": 1269567, "author_profile": "https://Stackoverflow.com/users/1269567", "pm_score": 4, "selected": true, "text": "struct Algorithm{T}\n algorithmName::String\n\n function Algorithm(algorithmName::AbstractString)\n algorithmName == \"Value Iteration\" && return new{:vIter}(algorithmName)\n algorithmName == \"Policy Iteration\" && return new{:pIter}(algorithmName)\n error(\"Given algorithm $algorithmName not defined yet.\")\n end\nend\n\nfunction A(a::Algorithm{:pIter})\n # ...\nend\n\nfunction A(a::Algorithm{:vIter})\n # ...\nend\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74396379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13241995/" ]
74,396,387
<p>I am attempting to determine if a folder is empty.</p> <p>My current method involves using a GetMeta shape and running the following to set a Boolean.</p> <p><strong>@greater(length(activity('Is Staging Folder Empty').output.childItems), 0)</strong></p> <p>This works great when files are present.</p> <p>When the folder is empty (a state I want to test for) I get</p> <p>&quot;The required Blob is missing&quot;.</p> <p>Can I trap this condition?</p> <p>What alternatives are there to determine if a folder is empty?</p>
[ { "answer_id": 74397582, "author": "Giovanni", "author_id": 16204281, "author_profile": "https://Stackoverflow.com/users/16204281", "pm_score": 2, "selected": false, "text": "struct AbstractAlgorithm{T}\n algorithmName::String\n\n function AbstractAlgorithm(algorithmName::String)\n if algorithmName ∉ (\"Value Iteration\", \"Policy Iteration\")\n error(\"Given algorithm $algorithmName not defined yet.\")\n elseif algorithmName==\"Value Iteration\"\n new{Val{:vIter}}(algorithmName)\n elseif algorithmName==\"Policy Iteration\"\n new{Val{:pIter}}(algorithmName)\n end\n end\nend\n\nfunction A(a::AbstractAlgorithm{Val{:pIter}})\n A1\nend\n\nfunction A(a::AbstractAlgorithm{Val{:vIter}})\n A2\nend\n" }, { "answer_id": 74398611, "author": "DNF", "author_id": 2749865, "author_profile": "https://Stackoverflow.com/users/2749865", "pm_score": 3, "selected": false, "text": "AbstractNN" }, { "answer_id": 74398771, "author": "Bogumił Kamiński", "author_id": 1269567, "author_profile": "https://Stackoverflow.com/users/1269567", "pm_score": 4, "selected": true, "text": "struct Algorithm{T}\n algorithmName::String\n\n function Algorithm(algorithmName::AbstractString)\n algorithmName == \"Value Iteration\" && return new{:vIter}(algorithmName)\n algorithmName == \"Policy Iteration\" && return new{:pIter}(algorithmName)\n error(\"Given algorithm $algorithmName not defined yet.\")\n end\nend\n\nfunction A(a::Algorithm{:pIter})\n # ...\nend\n\nfunction A(a::Algorithm{:vIter})\n # ...\nend\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74396387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3609480/" ]
74,396,391
<p>Is the following program valid? (In the sense of being well-defined by the ISO C standard, not just happening to work on a particular compiler.)</p> <pre><code>struct foo { int a, b, c; }; int f(struct foo *p) { // should return p-&gt;c char *q = ((char *)p) + 2 * sizeof(int); return *((int *)q); } </code></pre> <p>It follows at least some of the rules for well-defined use of pointers:</p> <ul> <li><p>The value being loaded, is of the same type that was stored at the address.</p> </li> <li><p>The provenance of the calculated pointer is valid, being derived from a valid pointer by adding an offset, that gives a pointer still within the original storage instance.</p> </li> <li><p>There is no mixing of element types within the struct, that would generate padding to make an element offset unpredictable.</p> </li> </ul> <p>But I'm still not sure it's valid to explicitly calculate and use element pointers that way.</p>
[ { "answer_id": 74396591, "author": "Davislor", "author_id": 4474419, "author_profile": "https://Stackoverflow.com/users/4474419", "pm_score": 2, "selected": true, "text": "struct" }, { "answer_id": 74438159, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 1, "selected": false, "text": "struct foo { unsigned char a[4], b[4]; } x;\nint test(int i)\n{\n x.b[0] = 1;\n x.a[i] = 2;\n return x.b[0];\n}\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74396391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45843/" ]
74,396,407
<p>I have very little to no knowledge when it comes to using JavaScript. I have 24 of the same image given an id from q1 - q24. my code allows for the 24 images to be changed to image2 one at a time, but I need for it to stop and display a text/alert when image2 is clicked.</p> <pre><code>&lt;script&gt; { let num = 1; function sequence() { let back = 1; while (back &lt; 25) { if(back == 1) { document.getElementById(&quot;q24&quot;).src = &quot;question.jpg&quot;; } else { document.getElementById(&quot;q&quot; + (back-1)).src = &quot;question.jpg&quot;; } back++ } document.getElementById(&quot;q&quot; + num).src = &quot;question2.png&quot;; num = num + 1; if(num &gt; 24){num = 1;} } setInterval(sequence, 500); } &lt;/script&gt; </code></pre>
[ { "answer_id": 74396591, "author": "Davislor", "author_id": 4474419, "author_profile": "https://Stackoverflow.com/users/4474419", "pm_score": 2, "selected": true, "text": "struct" }, { "answer_id": 74438159, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 1, "selected": false, "text": "struct foo { unsigned char a[4], b[4]; } x;\nint test(int i)\n{\n x.b[0] = 1;\n x.a[i] = 2;\n return x.b[0];\n}\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74396407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20473078/" ]
74,396,419
<p>I have a data frame that has a quantity column and I need to check if the data was inputted correctly. If there's a number that was inputted with decimals I receive de data frame with de quantity column as a float and not as an integer, but I need to print out the index of the rows that were inputted with decimals.</p> <p>For example</p> <pre><code>data = {'quantity': [2.00, 1.00, 3.00, 4.55, 5.00, 6.22]       } testdf = pd.DataFrame(data) </code></pre> <p>I need to print out the index of the rows that contain the decimal values that are not .00</p>
[ { "answer_id": 74396591, "author": "Davislor", "author_id": 4474419, "author_profile": "https://Stackoverflow.com/users/4474419", "pm_score": 2, "selected": true, "text": "struct" }, { "answer_id": 74438159, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 1, "selected": false, "text": "struct foo { unsigned char a[4], b[4]; } x;\nint test(int i)\n{\n x.b[0] = 1;\n x.a[i] = 2;\n return x.b[0];\n}\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74396419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19742465/" ]
74,396,440
<p>My goal is to take lists that contain strings such as ['1 0', '2 0', '3 1 2'] or [['1 0'], ['2 0'], ['3 1 2']]</p> <p>and turn that into an adjacency list like so: [[1, 0], [2,0], [3,1], [3,2]]</p> <p>The issue I have is that the last string in the list has more than two digits ['3 1 2']. This causes unpacking the sublist to generate the error shown below:</p> <pre><code>Traceback (most recent call last): File &quot;/tmp/source.py&quot;, line 79, in &lt;module&gt; for dest, src in nlist: ValueError: too many values to unpack (expected 2) </code></pre> <p>Code so far:</p> <p>linelist: ['1 0', '2 0', '3 1 2']</p> <pre><code>newlist = [] print(&quot;linelist1&quot;, linelist) for word in linelist: word = word.split(&quot;,&quot;) newlist.append(word) </code></pre> <p>newlist: [['1 0'], ['2 0'], ['3 1 2']]</p> <pre><code>adj_list = {} nlist = [] for inner_list in newlist: values = [int(x) for x in inner_list[0].split()] # splits each sublist nlist.append(values) adj_list [values[1]] = values[0:] adj_list = defaultdict(list) for dest, src in nlist: adj_list[src].append(dest) </code></pre> <p>Should output: [[1, 0], [2,0], [3,1], [3,2]]</p>
[ { "answer_id": 74396510, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 2, "selected": true, "text": "lst = [\"1 0\", \"2 0\", \"3 1 2\"]\n\nout = []\nfor s in lst:\n n, *rest = map(int, s.split())\n out.extend([n, v] for v in rest)\n\nprint(out)\n" }, { "answer_id": 74396512, "author": "Adam Ali", "author_id": 20473187, "author_profile": "https://Stackoverflow.com/users/20473187", "pm_score": 0, "selected": false, "text": "['1 0', '2 0', '3 1 2']\n" }, { "answer_id": 74396568, "author": "Madison Courto", "author_id": 2926779, "author_profile": "https://Stackoverflow.com/users/2926779", "pm_score": 0, "selected": false, "text": "def convertList(argi):\n # convert list of strings to list of lists\n resultArr = []\n for item in argi:\n resultArr.append(item.split(\" \"))\n if len(resultArr[-1]) > 2:\n firstItem = resultArr[-1][0]\n resultArr[-1] = resultArr[-1][1:]\n for item in resultArr[-1]:\n resultArr.append([firstItem, item])\n resultArr = [item for item in resultArr if len(item) == 2]\n\n return resultArr\n\n\nprint(convertList(['1 0', '2 0', '3 1 2 4 5 6', '3 7 8 9 10 11']))\n" }, { "answer_id": 74396651, "author": "Yuri Ginsburg", "author_id": 2397684, "author_profile": "https://Stackoverflow.com/users/2397684", "pm_score": 0, "selected": false, "text": "lst = ['1 0', '2 0', '3 1 2']\n\nnlist = [z.split() for z in lst]\n\nres = []\nfor i in range(len(nlist)):\n if len(nlist[i]) > 2:\n for k in range(1, len(nlist[i])):\n res.append([nlist[i][0], nlist[i][k]])\n else:\n res.append(nlist[i])\n\nprint(res)\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74396440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18354441/" ]
74,396,447
<p>I have this spreadsheet below, and I'm looking to lock the entire column in sheets except for the column that matches today's date (11/10/2022). And then the next day it will lock the column E and 11/11/2022 column(F) will be unlocked and so on. And I'd like to specify users who can edit those locked columns.</p> <p>Here's my sheet.</p> <p><a href="https://i.stack.imgur.com/fzb7G.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fzb7G.png" alt="" /></a></p>
[ { "answer_id": 74396510, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 2, "selected": true, "text": "lst = [\"1 0\", \"2 0\", \"3 1 2\"]\n\nout = []\nfor s in lst:\n n, *rest = map(int, s.split())\n out.extend([n, v] for v in rest)\n\nprint(out)\n" }, { "answer_id": 74396512, "author": "Adam Ali", "author_id": 20473187, "author_profile": "https://Stackoverflow.com/users/20473187", "pm_score": 0, "selected": false, "text": "['1 0', '2 0', '3 1 2']\n" }, { "answer_id": 74396568, "author": "Madison Courto", "author_id": 2926779, "author_profile": "https://Stackoverflow.com/users/2926779", "pm_score": 0, "selected": false, "text": "def convertList(argi):\n # convert list of strings to list of lists\n resultArr = []\n for item in argi:\n resultArr.append(item.split(\" \"))\n if len(resultArr[-1]) > 2:\n firstItem = resultArr[-1][0]\n resultArr[-1] = resultArr[-1][1:]\n for item in resultArr[-1]:\n resultArr.append([firstItem, item])\n resultArr = [item for item in resultArr if len(item) == 2]\n\n return resultArr\n\n\nprint(convertList(['1 0', '2 0', '3 1 2 4 5 6', '3 7 8 9 10 11']))\n" }, { "answer_id": 74396651, "author": "Yuri Ginsburg", "author_id": 2397684, "author_profile": "https://Stackoverflow.com/users/2397684", "pm_score": 0, "selected": false, "text": "lst = ['1 0', '2 0', '3 1 2']\n\nnlist = [z.split() for z in lst]\n\nres = []\nfor i in range(len(nlist)):\n if len(nlist[i]) > 2:\n for k in range(1, len(nlist[i])):\n res.append([nlist[i][0], nlist[i][k]])\n else:\n res.append(nlist[i])\n\nprint(res)\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74396447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19621475/" ]
74,396,473
<p>I have following data:</p> <p>#1. dates of 15 day frequency: dates = seq(as.Date(&quot;2017-01-01&quot;), as.Date(&quot;2020-12-30&quot;), by=15)</p> <p>#2. I have a dataframe containing dates where certain observation is recoded per variable as: <a href="https://i.stack.imgur.com/tKYEN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tKYEN.png" alt="enter image description here" /></a></p> <p>#3. Values corresponding to dates in #2 as: <a href="https://i.stack.imgur.com/OO19u.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OO19u.png" alt="enter image description here" /></a></p> <p>What I am trying to do is assign values to respective dates, and keep other as NaN for the dates which has no observation, and save as a text file. The output look something like below. Appreciate your help. Can be in R or in python.</p> <p><a href="https://i.stack.imgur.com/sWxQT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sWxQT.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74396510, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 2, "selected": true, "text": "lst = [\"1 0\", \"2 0\", \"3 1 2\"]\n\nout = []\nfor s in lst:\n n, *rest = map(int, s.split())\n out.extend([n, v] for v in rest)\n\nprint(out)\n" }, { "answer_id": 74396512, "author": "Adam Ali", "author_id": 20473187, "author_profile": "https://Stackoverflow.com/users/20473187", "pm_score": 0, "selected": false, "text": "['1 0', '2 0', '3 1 2']\n" }, { "answer_id": 74396568, "author": "Madison Courto", "author_id": 2926779, "author_profile": "https://Stackoverflow.com/users/2926779", "pm_score": 0, "selected": false, "text": "def convertList(argi):\n # convert list of strings to list of lists\n resultArr = []\n for item in argi:\n resultArr.append(item.split(\" \"))\n if len(resultArr[-1]) > 2:\n firstItem = resultArr[-1][0]\n resultArr[-1] = resultArr[-1][1:]\n for item in resultArr[-1]:\n resultArr.append([firstItem, item])\n resultArr = [item for item in resultArr if len(item) == 2]\n\n return resultArr\n\n\nprint(convertList(['1 0', '2 0', '3 1 2 4 5 6', '3 7 8 9 10 11']))\n" }, { "answer_id": 74396651, "author": "Yuri Ginsburg", "author_id": 2397684, "author_profile": "https://Stackoverflow.com/users/2397684", "pm_score": 0, "selected": false, "text": "lst = ['1 0', '2 0', '3 1 2']\n\nnlist = [z.split() for z in lst]\n\nres = []\nfor i in range(len(nlist)):\n if len(nlist[i]) > 2:\n for k in range(1, len(nlist[i])):\n res.append([nlist[i][0], nlist[i][k]])\n else:\n res.append(nlist[i])\n\nprint(res)\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74396473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20473161/" ]
74,396,514
<p>I have a problem with cors origin in my laravel project, I created cors.php in middwares folder and I declare it in Kernel.php and app/Providers/RouteServiceProvider.php as well... I did everything to solve it in my Laravel project, even in folder config I added a file Cors.php</p> <p>I'm now wondering if I have to add something in Nginx configuration or Apache configuration ?</p> <p>I'm hosting my project in hostinger VPS, The version of linux is ubuntu 22.04.5 LTS</p> <p>Thank you in advance. Regards</p> <pre><code></code></pre> <p>Middlewares/Cors.php</p> <pre><code>&lt;?php namespace App\Http\Middleware; use Closure; class Cors { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { return $next($request) -&gt;header('Access-Control-Allow-Origin', '*') } } </code></pre> <pre><code> config/cors.php </code></pre> <pre><code>&lt;?php return [ /* |-------------------------------------------------------------------------- | Cross-Origin Resource Sharing (CORS) Configuration |-------------------------------------------------------------------------- | | Here you may configure your settings for cross-origin resource sharing | or &quot;CORS&quot;. This determines what cross-origin operations may execute | in web browsers. You are free to adjust these settings as needed. | | To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS | */ 'paths' =&gt; ['api/*','web/*', 'sanctum/*'], 'allowed_methods' =&gt; ['*'], 'allowed_origins' =&gt; ['*'], 'allowed_origins_patterns' =&gt; ['*'], 'allowed_headers' =&gt; ['*'], 'exposed_headers' =&gt; ['*'], 'max_age' =&gt; 0, 'supports_credentials' =&gt; true ]; </code></pre> <pre><code>I added also this lines to Http/kernel.php </code></pre> <pre><code> protected $routeMiddleware = [ 'auth' =&gt; \App\Http\Middleware\Authenticate::class, 'auth.basic' =&gt; \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'auth.session' =&gt; \Illuminate\Session\Middleware\AuthenticateSession::class, 'cache.headers' =&gt; \Illuminate\Http\Middleware\SetCacheHeaders::class, 'can' =&gt; \Illuminate\Auth\Middleware\Authorize::class, 'guest' =&gt; \App\Http\Middleware\RedirectIfAuthenticated::class, 'password.confirm' =&gt; \Illuminate\Auth\Middleware\RequirePassword::class, 'signed' =&gt; \Illuminate\Routing\Middleware\ValidateSignature::class, 'throttle' =&gt; \Illuminate\Routing\Middleware\ThrottleRequests::class, 'verified' =&gt; \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class, 'cors' =&gt; \App\Http\Middleware\Cors::class, // added ]; </code></pre> <pre><code> </code></pre> <pre><code> I in console I have this message ( see pictures ): and I have this message in console : Download the Vue Devtools extension for a better development experience: https://github.com/vuejs/vue-devtools post.js:42559 You are running Vue in development mode. Make sure to turn on production mode when deploying for production. See more tips at https://vuejs.org/guide/deployment.html scrollspy.js:224 Uncaught TypeError: Cannot read properties of null (reading 'classList') at An._activate (scrollspy.js:224:10) at An._process (scrollspy.js:191:14) at new An (scrollspy.js:80:10) at bg_scripts.js:35:9 sb-forms-latest.js:5 Uncaught Error: GET_ELEMENTS: -&gt; form[data-sb-form-api-token] at e (sb-forms-latest.js:5:415) at sb-forms-latest.js:5:3777 profile.js:32882 Error: Network Error at createError (profile.js:872:15) at XMLHttpRequest.handleError (profile.js:754:14) 127.0.0.1:8000/getMessages:1 Failed to load resource: net::ERR_CONNECTION_REFUSED boxicons.min.css:1 Failed to load resource: the server responded with a status of 404 () [enter image description here][1] [enter image description here][2] [1]: https://i.stack.imgur.com/T9DhM.png [2]: https://i.stack.imgur.com/7zXtW.png </code></pre>
[ { "answer_id": 74396510, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 2, "selected": true, "text": "lst = [\"1 0\", \"2 0\", \"3 1 2\"]\n\nout = []\nfor s in lst:\n n, *rest = map(int, s.split())\n out.extend([n, v] for v in rest)\n\nprint(out)\n" }, { "answer_id": 74396512, "author": "Adam Ali", "author_id": 20473187, "author_profile": "https://Stackoverflow.com/users/20473187", "pm_score": 0, "selected": false, "text": "['1 0', '2 0', '3 1 2']\n" }, { "answer_id": 74396568, "author": "Madison Courto", "author_id": 2926779, "author_profile": "https://Stackoverflow.com/users/2926779", "pm_score": 0, "selected": false, "text": "def convertList(argi):\n # convert list of strings to list of lists\n resultArr = []\n for item in argi:\n resultArr.append(item.split(\" \"))\n if len(resultArr[-1]) > 2:\n firstItem = resultArr[-1][0]\n resultArr[-1] = resultArr[-1][1:]\n for item in resultArr[-1]:\n resultArr.append([firstItem, item])\n resultArr = [item for item in resultArr if len(item) == 2]\n\n return resultArr\n\n\nprint(convertList(['1 0', '2 0', '3 1 2 4 5 6', '3 7 8 9 10 11']))\n" }, { "answer_id": 74396651, "author": "Yuri Ginsburg", "author_id": 2397684, "author_profile": "https://Stackoverflow.com/users/2397684", "pm_score": 0, "selected": false, "text": "lst = ['1 0', '2 0', '3 1 2']\n\nnlist = [z.split() for z in lst]\n\nres = []\nfor i in range(len(nlist)):\n if len(nlist[i]) > 2:\n for k in range(1, len(nlist[i])):\n res.append([nlist[i][0], nlist[i][k]])\n else:\n res.append(nlist[i])\n\nprint(res)\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74396514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12103127/" ]
74,396,517
<p>With the given type signature below, is there a way to do something similar to below?</p> <pre><code>func Transform[T, U any](item T) U { return item } </code></pre> <p>The code above gives the following error:</p> <pre><code>cannot use item (variable of type T constrained by any) as U value in return statement </code></pre> <p>I am unable to use the type signature above, as I am essentially trying to make an optional transform method that sometimes will need to convert from T to U, but sometimes just return itself. A more detailed example of the use case is shown below.</p> <pre><code>type SomeStruct[T, U any] struct { Transform func(T) U } func (s SomeStruct[T, U]) Transform(elem T) (U) { if s.Transform != nil { return s.Transform(elem) } return elem } </code></pre> <p>Is there a way to create a Transform function that sometimes conditionally just returns itself?</p>
[ { "answer_id": 74397517, "author": "Erwin Bolwidt", "author_id": 981744, "author_profile": "https://Stackoverflow.com/users/981744", "pm_score": 3, "selected": true, "text": "func Transform[T, U any](item T) U {\n return any(item).(U)\n}\n" }, { "answer_id": 74473173, "author": "blackgreen", "author_id": 4108803, "author_profile": "https://Stackoverflow.com/users/4108803", "pm_score": 1, "selected": false, "text": "T" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74396517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1093160/" ]
74,396,544
<p>I use portable hotspot for internet access.</p> <p>Devices:<br /> Phone (hotspot) - site isn't accessible (err_connection_timed_out)<br /> Laptop (development server) - site accessible<br /> Another phone - site isn't site accessible(err_connection_timed_out)<br /> Another laptop - site isn't site accessible(err_connection_refused)</p> <p><code>nuxt.config.js</code></p> <pre class="lang-js prettyprint-override"><code>ssr: true, target: 'server', server: { port: 8080, // default: 3000 host: '0.0.0.0', // default: localhost, }, </code></pre> <p>I can't get the source of problem, because static one worked nicely.</p>
[ { "answer_id": 74397517, "author": "Erwin Bolwidt", "author_id": 981744, "author_profile": "https://Stackoverflow.com/users/981744", "pm_score": 3, "selected": true, "text": "func Transform[T, U any](item T) U {\n return any(item).(U)\n}\n" }, { "answer_id": 74473173, "author": "blackgreen", "author_id": 4108803, "author_profile": "https://Stackoverflow.com/users/4108803", "pm_score": 1, "selected": false, "text": "T" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74396544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12859981/" ]
74,396,546
<p>I am trying to understand the preferred approach for a class to handle the validity of (reference to) the object of <em>another</em> class.</p> <p>In here, <code>C</code> has a vector that stores references of <code>D</code> objects. If <code>D</code> and <code>C</code> are a part of the library, how should <code>C</code> handle the case where a <code>D</code> object goes out of scope in the caller?</p> <p>A couple approaches that I have in mind though not sure of the feasibility:</p> <ul> <li><code>D</code> knows about what <code>_list</code> stores and as soon as the said <code>D</code> goes out of scope, <code>~D()</code> runs which removes itself from <code>_list</code>.</li> <li><code>_list</code> stores <code>weak_ptr</code> instead of a raw and upon any access to <code>D</code>, you invoke <code>weak_ptr::lock()</code> prior to accessing, though this will require the instantiation of a <code>shared_ptr</code> which seems to be not so common in production?</li> </ul> <pre><code>struct D { ~D() { printf (&quot;~D()\n&quot;); } }; class C { vector&lt;D*&gt; _list; public: void add(D* dObject) { _list.push_back(dObject); printf (&quot;Adding D =&gt; size = %ld\n&quot;, _list.size()); } ~C() { printf (&quot;~C()\n&quot;); } }; int main() { C c1; { D d1; c1.add(&amp;d1); } /** _list[0] is garbage now. How to avoid accessing it i.e C being aware to not access it? */ printf (&quot;----out of scope---\n&quot;); D d2; c1.add(&amp;d2); } </code></pre>
[ { "answer_id": 74410184, "author": "dirck", "author_id": 11134583, "author_profile": "https://Stackoverflow.com/users/11134583", "pm_score": -1, "selected": false, "text": "~D()" }, { "answer_id": 74439212, "author": "shy45", "author_id": 20313707, "author_profile": "https://Stackoverflow.com/users/20313707", "pm_score": 1, "selected": false, "text": "#include <vector>\n#include <string>\n#include <memory>\nusing namespace std;\n\nstruct D{\npublic:\n string _name;\n D(const string& name) : _name(name){}\n ~D(){\n printf(\"~D()\\n\");\n }\n};\n\nclass C{\n vector<shared_ptr<D>> _list;\npublic:\n void add(shared_ptr<D> dObject){\n _list.push_back(dObject);\n printf(\"Adding D => size = %ld\\n\", _list.size());\n }\n void print() {\n for (const auto& d : _list) {\n printf(\"%s\\n\", d->_name.c_str());\n }\n }\n ~C(){\n printf(\"~C()\\n\");\n }\n};\n\nint main(){\n C c1;\n {\n c1.add(make_shared<D>(\"first D\"));\n }\n c1.add(make_shared<D>(\"second D\"));\n c1.print();\n}\n" }, { "answer_id": 74440614, "author": "Sebastian", "author_id": 13130048, "author_profile": "https://Stackoverflow.com/users/13130048", "pm_score": 1, "selected": false, "text": "int main() {\n C c1;\n {\n D d1;\n c1.add(&d1);\n scope_exit d1_erase([&] {\n c1.erase(&d1);\n });\n // ... insert here other code within the inner scope\n }\n // ... insert here other code within the outer scope\n return 0;\n}\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74396546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12497236/" ]
74,396,553
<p>I am trying to compare values on 2 different columns values to ensure that they exist(on Sheet 1) Once the script is aware that they exist I need to access sheet1's column for quantity and add that value to sheet 2's quantity column. The problem is I am unsure of how to just get the location/index of the foreach loop and offset a setValue to another column without setting the value to the entire column(I dont want to do that if the product name of column A does not exist in Sheet1)</p> <p>Here is the code example of how i am trying to do it</p> <p>I have included it in a pastebin because I could not figure out how to format the code to paste ( sorry i'm super new at this!)</p> <pre><code>&lt;https://pastebin.com/EKB2n9kA&gt; </code></pre> <p>Sheet1 incoming data <a href="https://drive.google.com/file/d/1eLNeOZZbdeCDfMMImksVRnBXwKxpHIO_/view?usp=sharing" rel="nofollow noreferrer">https://drive.google.com/file/d/1eLNeOZZbdeCDfMMImksVRnBXwKxpHIO_/view?usp=sharing</a></p> <p>Sheet2 'base' data to add quantity values to <a href="https://drive.google.com/file/d/1h26H9eQgZapd2Y0LVamhRPYme-8LmVF0/view?usp=sharing" rel="nofollow noreferrer">https://drive.google.com/file/d/1h26H9eQgZapd2Y0LVamhRPYme-8LmVF0/view?usp=sharing</a></p> <p>example of expected/wanted results <a href="https://drive.google.com/file/d/1-0ozD5PrbIq-otG4j7kAyLufQFjDR5Hi/view?usp=sharing" rel="nofollow noreferrer">https://drive.google.com/file/d/1-0ozD5PrbIq-otG4j7kAyLufQFjDR5Hi/view?usp=sharing</a></p> <p>I have also attached 3 different reference photos</p> <p>Sheet 1 is 'incoming' data to read Sheet 2 is our 'base' data and where Sheet1's quantity column needs to be added to the third screenshot is the expected result(having the script skip over rows that do not contain matching data but still being able to get the quantity value based on the index/location the value was found)</p> <p>Any insight on how to achieve this would be sincerely appreciated</p> <p>I have tried pushing the results into an empty array but it does not seem to give much useful info the way I am doing it.</p> <p>I have also tried just getting an offset range (getRange(&quot;G2:G&quot;).offset(0,3).setValues() to set the results but it sets the value of the entire column instead of only where the values match for each column being compared.</p>
[ { "answer_id": 74410184, "author": "dirck", "author_id": 11134583, "author_profile": "https://Stackoverflow.com/users/11134583", "pm_score": -1, "selected": false, "text": "~D()" }, { "answer_id": 74439212, "author": "shy45", "author_id": 20313707, "author_profile": "https://Stackoverflow.com/users/20313707", "pm_score": 1, "selected": false, "text": "#include <vector>\n#include <string>\n#include <memory>\nusing namespace std;\n\nstruct D{\npublic:\n string _name;\n D(const string& name) : _name(name){}\n ~D(){\n printf(\"~D()\\n\");\n }\n};\n\nclass C{\n vector<shared_ptr<D>> _list;\npublic:\n void add(shared_ptr<D> dObject){\n _list.push_back(dObject);\n printf(\"Adding D => size = %ld\\n\", _list.size());\n }\n void print() {\n for (const auto& d : _list) {\n printf(\"%s\\n\", d->_name.c_str());\n }\n }\n ~C(){\n printf(\"~C()\\n\");\n }\n};\n\nint main(){\n C c1;\n {\n c1.add(make_shared<D>(\"first D\"));\n }\n c1.add(make_shared<D>(\"second D\"));\n c1.print();\n}\n" }, { "answer_id": 74440614, "author": "Sebastian", "author_id": 13130048, "author_profile": "https://Stackoverflow.com/users/13130048", "pm_score": 1, "selected": false, "text": "int main() {\n C c1;\n {\n D d1;\n c1.add(&d1);\n scope_exit d1_erase([&] {\n c1.erase(&d1);\n });\n // ... insert here other code within the inner scope\n }\n // ... insert here other code within the outer scope\n return 0;\n}\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74396553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20473200/" ]
74,396,584
<p>Let's say we have a nested list in Python. AKA a matrix, and we have a list consisting of elements, lets say li = [1, 2, 3, 4, 5, 6]. I want to insert two elements in matrix rows, resulting matrix = [ [1,2] [3,4], [5,6] ]. How can this be done ? Thanks!</p> <pre><code>b = [[]] c = [1, 2, 3, 4, 5, 6] for i in range(len(c)): for j in range(2): b[i].append(c[i]) print(b) </code></pre>
[ { "answer_id": 74410184, "author": "dirck", "author_id": 11134583, "author_profile": "https://Stackoverflow.com/users/11134583", "pm_score": -1, "selected": false, "text": "~D()" }, { "answer_id": 74439212, "author": "shy45", "author_id": 20313707, "author_profile": "https://Stackoverflow.com/users/20313707", "pm_score": 1, "selected": false, "text": "#include <vector>\n#include <string>\n#include <memory>\nusing namespace std;\n\nstruct D{\npublic:\n string _name;\n D(const string& name) : _name(name){}\n ~D(){\n printf(\"~D()\\n\");\n }\n};\n\nclass C{\n vector<shared_ptr<D>> _list;\npublic:\n void add(shared_ptr<D> dObject){\n _list.push_back(dObject);\n printf(\"Adding D => size = %ld\\n\", _list.size());\n }\n void print() {\n for (const auto& d : _list) {\n printf(\"%s\\n\", d->_name.c_str());\n }\n }\n ~C(){\n printf(\"~C()\\n\");\n }\n};\n\nint main(){\n C c1;\n {\n c1.add(make_shared<D>(\"first D\"));\n }\n c1.add(make_shared<D>(\"second D\"));\n c1.print();\n}\n" }, { "answer_id": 74440614, "author": "Sebastian", "author_id": 13130048, "author_profile": "https://Stackoverflow.com/users/13130048", "pm_score": 1, "selected": false, "text": "int main() {\n C c1;\n {\n D d1;\n c1.add(&d1);\n scope_exit d1_erase([&] {\n c1.erase(&d1);\n });\n // ... insert here other code within the inner scope\n }\n // ... insert here other code within the outer scope\n return 0;\n}\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74396584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12896325/" ]
74,396,602
<p>I want to test an app that only has Google Oauth Login via AWS Cognito. Lots of guides on how to use cypress to programatically login to Cognito using AWS Amplify with a username and password, but cannot find anything on how to do it with Google Oauth.</p> <p>Im trying to use cypress to click the buttons to authenticate but I think there is a click forgery protection on Google.</p> <p>I have also been able to use <a href="https://docs.cypress.io/guides/end-to-end-testing/google-authentication" rel="nofollow noreferrer">this</a> cypress documentation to login to Google directly and get a jwt into session storage but not sure if there is a way to pass this to Cognito.</p>
[ { "answer_id": 74435696, "author": "lindsaymacvean", "author_id": 2827300, "author_profile": "https://Stackoverflow.com/users/2827300", "pm_score": 1, "selected": true, "text": "// /support/login.js\nCypress.Commands.add('loginByGoogle', () => {\n \n cy.visit('http://localhost:3030')\n\n cy.origin('https://somecognitouserpool.auth.eu-west-1.amazoncognito.com', () => {\n cy.contains('button', 'Continue with Google')\n .click({force: true}) \n })\n \n cy.origin('https://accounts.google.com', () => {\n const resizeObserverLoopError = /^[^(ResizeObserver loop limit exceeded)]/;\n Cypress.on('uncaught:exception', (err) => {\n /* returning false here prevents Cypress from failing the test */\n if (resizeObserverLoopError.test(err.message)) {\n return false;\n }\n });\n cy.get('input#identifierId[type=\"email\"]')\n .type(Cypress.env('googleSocialLoginUsername'))\n .get('button[type=\"button\"]').contains('Next')\n .click()\n .get('div#password input[type=\"password\"]')\n .type(Cypress.env('googleSocialLoginPassword'))\n .get('button[type=\"button\"]').contains('Next')\n .click();\n });\n \n});\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74396602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2827300/" ]
74,396,608
<p>I have the following df:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">Name</th> <th style="text-align: center;">Time Elapsed</th> <th style="text-align: right;">Amount</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">A</td> <td style="text-align: center;">2</td> <td style="text-align: right;">$2</td> </tr> <tr> <td style="text-align: left;">A</td> <td style="text-align: center;">5</td> <td style="text-align: right;">$1</td> </tr> <tr> <td style="text-align: left;">A</td> <td style="text-align: center;">7</td> <td style="text-align: right;">$6</td> </tr> <tr> <td style="text-align: left;">B</td> <td style="text-align: center;">3</td> <td style="text-align: right;">$3</td> </tr> <tr> <td style="text-align: left;">B</td> <td style="text-align: center;">5</td> <td style="text-align: right;">$5</td> </tr> </tbody> </table> </div> <p>I would like to expand this per group so that I get all the times in between the min and max, and then fill downwards (assuming it's sorted by name then by time elapsed) to produce the following output</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">Name</th> <th style="text-align: center;">Time Elapsed</th> <th style="text-align: right;">Amount</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">A</td> <td style="text-align: center;">2</td> <td style="text-align: right;">$2</td> </tr> <tr> <td style="text-align: left;">A</td> <td style="text-align: center;">3</td> <td style="text-align: right;">$2</td> </tr> <tr> <td style="text-align: left;">A</td> <td style="text-align: center;">4</td> <td style="text-align: right;">$2</td> </tr> <tr> <td style="text-align: left;">A</td> <td style="text-align: center;">5</td> <td style="text-align: right;">$1</td> </tr> <tr> <td style="text-align: left;">A</td> <td style="text-align: center;">6</td> <td style="text-align: right;">$1</td> </tr> <tr> <td style="text-align: left;">A</td> <td style="text-align: center;">7</td> <td style="text-align: right;">$6</td> </tr> <tr> <td style="text-align: left;">B</td> <td style="text-align: center;">3</td> <td style="text-align: right;">$3</td> </tr> <tr> <td style="text-align: left;">B</td> <td style="text-align: center;">4</td> <td style="text-align: right;">$3</td> </tr> <tr> <td style="text-align: left;">B</td> <td style="text-align: center;">5</td> <td style="text-align: right;">$5</td> </tr> </tbody> </table> </div> <p>I tried the following:</p> <pre><code>df = df(df.set_index('Time Elapsed') .groupby('Name')['Amount'] .apply(lambda x: x.reindex(range(x.index.min(), x.index.max()+1)) .ffill().fillna(0)).reset_index) </code></pre> <p>Feel free to offer a solution that does not use any of my code.</p>
[ { "answer_id": 74397151, "author": "ziying35", "author_id": 16755671, "author_profile": "https://Stackoverflow.com/users/16755671", "pm_score": 3, "selected": true, "text": "def func(g: pd.DataFrame):\n tmp = g.set_index('Time Elapsed')\n res = tmp.reindex(\n np.arange(tmp.index.min(), tmp.index.max()+1),\n method='ffill')\n return res\n\ngrouped = df.groupby('Name', as_index=False)\nresult = grouped.apply(func).reset_index().reindex(columns=df.columns)\nprint(result)\n>>>\nName Time Elapsed Amount\n0 A 2 $2\n1 A 3 $2\n2 A 4 $2\n3 A 5 $1\n4 A 6 $1\n5 A 7 $6\n6 B 3 $3\n7 B 4 $3\n8 B 5 $5\n" }, { "answer_id": 74397163, "author": "sammywemmy", "author_id": 7175713, "author_profile": "https://Stackoverflow.com/users/7175713", "pm_score": 1, "selected": false, "text": "# pip install pyjanitor\nimport pandas as pd\nimport janitor\n\n# build a dictionary of all the possible times\n# the key of the dictionary should be the column to be expanded\ntimes = {\"Time Elapsed\" : lambda df: range(df.min(), df.max() + 1)}\ndf.complete(times, by = 'Name').ffill()\n Name Time Elapsed Amount\n0 A 2 $2\n1 A 3 $2\n2 A 4 $2\n3 A 5 $1\n4 A 6 $1\n5 A 7 $6\n6 B 3 $3\n7 B 4 $3\n8 B 5 $5\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74396608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12875502/" ]
74,396,618
<p>I have the following <a href="https://jsfiddle.net/btcof8wz/" rel="nofollow noreferrer">JSFiddle</a> where I have an image icon on the left of text like this:</p> <pre><code> &lt;img&gt; &lt;text goes here&gt; </code></pre> <p>However, when the text overflows I want it to look like this:</p> <pre><code> &lt;img&gt; &lt;text goes here............ .........&gt; </code></pre> <p>Instead of like this:</p> <pre><code> &lt;img&gt; &lt;text goes here............ .........&gt; </code></pre> <p>How would I do this? Here is the current html I have:</p> <pre><code>&lt;div class=&quot;para&quot;&gt; &lt;p style=&quot;margin:0 0 5px;line-height: 1.2;font-family: sans-serif;font-size: 14px; color: #666666;&quot;&gt; &lt;img src=&quot;https://i.postimg.cc/0ybqQCBY/hand.png&quot; style=&quot;width: 20px;height: 20px;display: inline-block;vertical-align: middle;margin-right: 5px;&quot;&gt; Join the waitlist &lt;a href=&quot;https://www.example.com/&quot; target=&quot;_blank&quot; style=&quot;color:#29abe2&quot;&gt;here is some long text here is some long text here is some long text here is some long text here is some long text &lt;/a&gt; &lt;/p&gt; &lt;/div&gt; </code></pre> <p>It current looks like this: <a href="https://i.stack.imgur.com/RCjVX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RCjVX.png" alt="enter image description here" /></a></p> <p>I want it to look like this:</p> <p><a href="https://i.stack.imgur.com/pNLNO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pNLNO.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74396660, "author": "Madison Courto", "author_id": 2926779, "author_profile": "https://Stackoverflow.com/users/2926779", "pm_score": 0, "selected": false, "text": "<div class=\"para\">\n <p style=\"margin:0 0 5px;line-height: 1.2;font-family: sans-serif;font-size: 14px; color: #666666;\"> \n \n <img src=\"https://i.postimg.cc/0ybqQCBY/hand.png\" style=\"width: 20px;height: 20px;display: inline-block;vertical-align: middle;margin-right: 5px;\">\n Join the waitlist \n \n <a href=\"https://www.google.com\" style=\"display: inline-block;vertical-align: middle;margin-left: 20px;overflow: hidden;text-overflow: clip;white-space: nowrap;\">S IS TEXTTHIS IS TEXTTHIS IS TEXTTHIS IS TEXTTHIS IS TEXTTHIS IS TEXTTHIS IS TEXTTHIS IS TEXTTHIS IS TEXTTHIS IS TEXT</a>\n \n </p>\n</div>\n" }, { "answer_id": 74396717, "author": "Davide Coppola", "author_id": 19044435, "author_profile": "https://Stackoverflow.com/users/19044435", "pm_score": 2, "selected": true, "text": " <div class=\"para\">\n <div style=\"display:flex\">\n <img src=\"https://i.postimg.cc/0ybqQCBY/hand.png\" style=\"width: 20px;height: 20px;display: inline-block;vertical-align: middle;margin-right: 5px;\">\n <span>\n Join the waitlist <a href=\"https://www.example.com/\" target=\"_blank\" style=\"color:#29abe2\">here is some long text here is some long text here is some long text here is some long text here is some long text </a>\n </span>\n </div>\n </div>\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74396618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/651174/" ]
74,396,635
<p>I want to put a condition in the where clause according to the null condition of the parameter in the procedure. But the procedure I made has some problem. There's problem is in IF clause.</p> <p>How I can put a condition in the where clause in the procedure?</p> <pre><code>CREATE OR REPLACE PROCEDURE SP_PROCEDURE(START_DATE, END_DATE) IS START_DATE DATE; END_DATE DATE; BEGIN START_DATE := TO_DATE(START_DATE, 'YYYYMMDD'); END_DATE := TO_DATE(END_DATE, 'YYYYMMDD'); INSERT INTO USER ( USR_KEY, USR_NAME ) SELECT USR_KEY, USR_NAME FROM USER WHERE 1 = 1 IF START_DATE THEN --I think there's problem here.. AND USR_CRT_DATE &gt;= START_DATE END IF; COMMIT; EXCEPTION WHEN OTHERS THEN ROLLBACK; END; </code></pre>
[ { "answer_id": 74396660, "author": "Madison Courto", "author_id": 2926779, "author_profile": "https://Stackoverflow.com/users/2926779", "pm_score": 0, "selected": false, "text": "<div class=\"para\">\n <p style=\"margin:0 0 5px;line-height: 1.2;font-family: sans-serif;font-size: 14px; color: #666666;\"> \n \n <img src=\"https://i.postimg.cc/0ybqQCBY/hand.png\" style=\"width: 20px;height: 20px;display: inline-block;vertical-align: middle;margin-right: 5px;\">\n Join the waitlist \n \n <a href=\"https://www.google.com\" style=\"display: inline-block;vertical-align: middle;margin-left: 20px;overflow: hidden;text-overflow: clip;white-space: nowrap;\">S IS TEXTTHIS IS TEXTTHIS IS TEXTTHIS IS TEXTTHIS IS TEXTTHIS IS TEXTTHIS IS TEXTTHIS IS TEXTTHIS IS TEXTTHIS IS TEXT</a>\n \n </p>\n</div>\n" }, { "answer_id": 74396717, "author": "Davide Coppola", "author_id": 19044435, "author_profile": "https://Stackoverflow.com/users/19044435", "pm_score": 2, "selected": true, "text": " <div class=\"para\">\n <div style=\"display:flex\">\n <img src=\"https://i.postimg.cc/0ybqQCBY/hand.png\" style=\"width: 20px;height: 20px;display: inline-block;vertical-align: middle;margin-right: 5px;\">\n <span>\n Join the waitlist <a href=\"https://www.example.com/\" target=\"_blank\" style=\"color:#29abe2\">here is some long text here is some long text here is some long text here is some long text here is some long text </a>\n </span>\n </div>\n </div>\n" } ]
2022/11/10
[ "https://Stackoverflow.com/questions/74396635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10314668/" ]
74,396,695
<p>I currently run two commands:</p> <ul> <li>sleep 180</li> <li>wget <a href="https://somedomain.com/api/up" rel="nofollow noreferrer">https://somedomain.com/api/up</a></li> </ul> <p>So it waits for 3 minutes and then calls api up</p> <p>I would like to change that so it continuously checks every minute for up to ten minutes until wget returns 200.</p> <p>so it should be the equivalent of this php function, but in bash. It is important to be a one liner (can be multiple statements separated by ;)</p> <pre><code>foreach(range(1,10) as $i) { sleep(60); try { Http::get('https://somedomain.com/api/up'); break; } catch(Exception $e) { if($i&gt;=10) throw $e; } } </code></pre> <p>the two things where my bash knowledge fails me:</p> <ul> <li>how to do the try catch or check for a 200 response code.</li> <li>how to get that all into one line/statement</li> </ul>
[ { "answer_id": 74396710, "author": "Barmar", "author_id": 1491895, "author_profile": "https://Stackoverflow.com/users/1491895", "pm_score": 2, "selected": true, "text": "for" }, { "answer_id": 74403406, "author": "ANISH SAJI KUMAR", "author_id": 12309235, "author_profile": "https://Stackoverflow.com/users/12309235", "pm_score": 0, "selected": false, "text": "for i in {1..5}; do wget -- \"$1\" && break || sleep 15; done\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74396695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5661749/" ]
74,396,709
<p>I'm facing an element like:</p> <pre><code>&lt;li _ngcontent-bcp-c271=&quot;&quot;&gt; &lt;a _ngcontent-bcp-c271=&quot;&quot;&gt;2018&lt;/a&gt; &lt;!----&gt; &lt;!----&gt; &lt;/li&gt; </code></pre> <p>This element is clickable but since it does not have a <code>href</code> attribute, and I think it should use some script for the click event, I don't have a solution to get the URL from this element.</p> <p>The code that I use most of the time is as follows:</p> <pre><code>driver.find_element(By.TAG_NAME, 'li').find_element(By.TAG_NAME, 'a').get_attribute('href') </code></pre> <p>Update:<br /> I need to know the URL before I click on the bottom.</p>
[ { "answer_id": 74396710, "author": "Barmar", "author_id": 1491895, "author_profile": "https://Stackoverflow.com/users/1491895", "pm_score": 2, "selected": true, "text": "for" }, { "answer_id": 74403406, "author": "ANISH SAJI KUMAR", "author_id": 12309235, "author_profile": "https://Stackoverflow.com/users/12309235", "pm_score": 0, "selected": false, "text": "for i in {1..5}; do wget -- \"$1\" && break || sleep 15; done\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74396709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1188943/" ]
74,396,733
<p>So from what I understand, a static compiled <code>mylib.a</code> file should just be usable as plug-and-play. But I can't use it without the source code, I'm trying to avoid that.</p> <p>I adapted <a href="https://domiyanyue.medium.com/c-development-tutorial-4-static-and-dynamic-libraries-7b537656163e" rel="nofollow noreferrer">this tutorial</a> to compile using CMake with the following directory structure:</p> <pre><code>/ lib libmy_math.a main.cpp my_math.h my_math.cpp CMakeLists.txt </code></pre> <p>The contents of the files are exactly as in the tutorial. The only added file is <code>CMakeLists.txt</code> which basically just runs the library compiling part before building:</p> <h2><code>CMakeLists.txt</code></h2> <pre><code>cmake_minimum_required(VERSION 3.21) project(Test) ### Uncomment this ONCE to compile a libmy_math.a file # add_library(my_math STATIC my_math.cpp) add_executable(Test main.cpp) find_library(MY_MATH_LIB my_math HINTS ./lib) target_link_libraries(Test PUBLIC ${MY_MATH_LIB}) </code></pre> <hr /> <p>As the <code>CMake</code> file says, uncommenting Line 5 compiles the library, which is then linked to my code when compiling.</p> <p>I'm trying to package my code so that I don't show my client the source code for the compiled library (<code>my_math</code>), but if I delete the <code>my_math.h</code> and <code>my_math.cpp</code> files, I get a &quot;<code>file not found</code>&quot; error on import:</p> <pre><code>/Users/Joe/Desktop/Test/main.cpp:1:10: fatal error: 'my_math.h' file not found #include &quot;my_math.h&quot; ^~~~~~~~~~~ </code></pre> <hr /> <p>I thought you could compile libraries without needing the source code. What am I missing here?</p>
[ { "answer_id": 74396710, "author": "Barmar", "author_id": 1491895, "author_profile": "https://Stackoverflow.com/users/1491895", "pm_score": 2, "selected": true, "text": "for" }, { "answer_id": 74403406, "author": "ANISH SAJI KUMAR", "author_id": 12309235, "author_profile": "https://Stackoverflow.com/users/12309235", "pm_score": 0, "selected": false, "text": "for i in {1..5}; do wget -- \"$1\" && break || sleep 15; done\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74396733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5420846/" ]
74,396,736
<p>New programmer here. I am trying to replicate a youtube video for a program that creates a CSV table viewer on html and am getting this error SyntaxError: The requested module './TableCsv.js' does not provide an export named 'default'</p> <p>I have tried adding curly braces around TableCsv in main.js but no luck. When I try adding my own export in TableCsv.js it says A module cannot have multiple default exports.ts(2528).</p> <p>Here is my code</p> <p>main.js</p> <pre><code>import TableCsv from &quot;./TableCsv.js&quot;; const tableRoot = document.querySelector(&quot;#csvRoot&quot;); const csvFileInput = document.querySelector(&quot;#csvFileInput&quot;); const tableCsv = new TableCsv(tableRoot); csvFileInput.addEventListener(&quot;change&quot;, e =&gt; { Papa.parse(csvFileInput.files[0], { delimiter: &quot;,&quot;, skipEmptyLines: true, complete: results =&gt; { tableCsv.update(results.data.slice(1), results.data[0]); } }); }); </code></pre> <p>TableCsv.js</p> <pre><code>class TableCsv { /** * @param {HTMLTableElement} root The table element which will display the CSV data. */ constructor(root) { this.root = root; } /** * Clears existing data in the table and replaces it with new data. * * @param {string[][]} data A 2D array of data to be used as the table body * @param {string[]} headerColumns List of headings to be used */ update(data, headerColumns = []) { this.clear(); this.setHeader(headerColumns); this.setBody(data); } /** * Clears all contents of the table (incl. the header). */ clear() { this.root.innerHTML = &quot;&quot;; } /** * Sets the table header. * * @param {string[]} headerColumns List of headings to be used */ setHeader(headerColumns) { this.root.insertAdjacentHTML( &quot;afterbegin&quot;, ` &lt;thead&gt; &lt;tr&gt; ${headerColumns.map((text) =&gt; `&lt;th&gt;${text}&lt;/th&gt;`).join(&quot;&quot;)} &lt;/tr&gt; &lt;/thead&gt; ` ); } /** * Sets the table body. * * @param {string[][]} data A 2D array of data to be used as the table body */ setBody(data) { const rowsHtml = data.map((row) =&gt; { return ` &lt;tr&gt; ${row.map((text) =&gt; `&lt;td&gt;${text}&lt;/td&gt;`).join(&quot;&quot;)} &lt;/tr&gt; `; }); this.root.insertAdjacentHTML( &quot;beforeend&quot;, ` &lt;tbody&gt; ${rowsHtml.join(&quot;&quot;)} &lt;/tbody&gt; ` ); } } const tableRoot = document.querySelector(&quot;#csvRoot&quot;); const csvFileInput = document.querySelector(&quot;#csvFileInput&quot;); const tableCsv = new TableCsv(tableRoot); csvFileInput.addEventListener(&quot;change&quot;, (e) =&gt; { Papa.parse(csvFileInput.files[0], { delimiter: &quot;,&quot;, skipEmptyLines: true, complete: (results) =&gt; { tableCsv.update(results.data.slice(1), results.data[0]); } }); }); </code></pre>
[ { "answer_id": 74396710, "author": "Barmar", "author_id": 1491895, "author_profile": "https://Stackoverflow.com/users/1491895", "pm_score": 2, "selected": true, "text": "for" }, { "answer_id": 74403406, "author": "ANISH SAJI KUMAR", "author_id": 12309235, "author_profile": "https://Stackoverflow.com/users/12309235", "pm_score": 0, "selected": false, "text": "for i in {1..5}; do wget -- \"$1\" && break || sleep 15; done\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74396736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20473014/" ]
74,396,759
<p>By default in Android, when using the <code>BottomNavigationView</code>, navigation by pressing on item looks like this:</p> <p>A -&gt; B -&gt; C</p> <p>Back button: C -&gt; A</p> <p>But when using <code>setOnItemSelectedListener</code>, the navigation breaks and when you click on the back button it looks completely different:</p> <p>A -&gt; B -&gt; C</p> <p>Back button: C -&gt; B -&gt; A</p> <p>How can I fix this and make it so that when the back button is clicked, the navigation always leads to the first (startDestination) item?</p> <p>My code:</p> <pre><code>bottomNavigationView.setOnItemSelectedListener { when(it.itemId) { R.id.homeFragment -&gt; { navController.navigate(R.id.homeFragment) } R.id.favoriteFragment -&gt; { navController.navigate(R.id.favoriteFragment) } R.id.profileFragment -&gt; { navController.navigate(R.id.profileFragment) } } true } </code></pre>
[ { "answer_id": 74397699, "author": "局外人", "author_id": 18188786, "author_profile": "https://Stackoverflow.com/users/18188786", "pm_score": 3, "selected": true, "text": "menu.setOnNavigationItemSelectedListener {\n when(it.itemId){\n R.id.homeFragment -> {\n val graph = navController.graph\n graph.startDestination = R.id.homeFragment\n navController.graph = graph\n }\n }\n}\n" }, { "answer_id": 74400121, "author": "Mert", "author_id": 4058604, "author_profile": "https://Stackoverflow.com/users/4058604", "pm_score": 0, "selected": false, "text": " bottomNavigationView.setOnItemSelectedListener { item ->\n NavigationUI.onNavDestinationSelected(item, navController)\n navController.popBackStack(item.itemId, inclusive = false)\n true\n }\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74396759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15317497/" ]
74,396,772
<p>I am new to Power BI, I am facing issue where I want to create a new column based on the latest date and the id column</p> <pre><code>ID LogCreationDate Points What I want 1001 12-Oct-2022 5 null 1001 17-Oct-2022 2 2 1001 13-Oct-2022 7 null 1001 07-Aug-2022 2 null 1002 03-Sept-2022 2.1 null 1002 22-Sept-2022 5 null 1002 04-Oct-2022 1 1 1002 01-Aug-2022 1.2 null 1003 05-Nov-2022 3.5 3.5 1003 01-Nov-2022 6.6 null </code></pre> <p>In Above table, I want to calculate &quot;What I want&quot; column using DAX, not using power query</p>
[ { "answer_id": 74397699, "author": "局外人", "author_id": 18188786, "author_profile": "https://Stackoverflow.com/users/18188786", "pm_score": 3, "selected": true, "text": "menu.setOnNavigationItemSelectedListener {\n when(it.itemId){\n R.id.homeFragment -> {\n val graph = navController.graph\n graph.startDestination = R.id.homeFragment\n navController.graph = graph\n }\n }\n}\n" }, { "answer_id": 74400121, "author": "Mert", "author_id": 4058604, "author_profile": "https://Stackoverflow.com/users/4058604", "pm_score": 0, "selected": false, "text": " bottomNavigationView.setOnItemSelectedListener { item ->\n NavigationUI.onNavDestinationSelected(item, navController)\n navController.popBackStack(item.itemId, inclusive = false)\n true\n }\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74396772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4273118/" ]
74,396,790
<p>I have a stream of data comming in which I want to use while it's comming in. Besides that I want to run another function every 30 seconds. Thus, while I am using the data stream to compute things I would like to run another function every 30 seconds. The code I have now:</p> <pre><code>import asyncio import websockets async def other_function(): while True: print(&quot;Do stuff&quot;) await asyncio.sleep(30) async def main(): async with websockets.connect(&quot;url&quot;) as websocket: while True: await other_function() message = websocket.recv() print(message) if __name__ == &quot;__main__&quot;: asyncio.run(main()) </code></pre> <p>I know what is going wrong, but I have no idea how to fix it. I also understand that the computations I do with the data stream will stop while the other function is running. I just want the 30 seconds of wait time to be on the 'background'.</p>
[ { "answer_id": 74397699, "author": "局外人", "author_id": 18188786, "author_profile": "https://Stackoverflow.com/users/18188786", "pm_score": 3, "selected": true, "text": "menu.setOnNavigationItemSelectedListener {\n when(it.itemId){\n R.id.homeFragment -> {\n val graph = navController.graph\n graph.startDestination = R.id.homeFragment\n navController.graph = graph\n }\n }\n}\n" }, { "answer_id": 74400121, "author": "Mert", "author_id": 4058604, "author_profile": "https://Stackoverflow.com/users/4058604", "pm_score": 0, "selected": false, "text": " bottomNavigationView.setOnItemSelectedListener { item ->\n NavigationUI.onNavDestinationSelected(item, navController)\n navController.popBackStack(item.itemId, inclusive = false)\n true\n }\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74396790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12457813/" ]
74,396,794
<p>I have an object with the timestamp and I want to build another object with number of occurrences based on the minutes from the timestamp</p> <p><strong>Existing Object:</strong></p> <pre><code>{ &quot;data&quot;: { &quot;dataArr&quot;: [ { &quot;fields&quot;: { &quot;@timestamp&quot;: [ &quot;2022-10-04T22:45:17.482Z&quot; ] }, { &quot;fields&quot;: { &quot;@timestamp&quot;: [ &quot;2022-10-04T22:45:17.482Z&quot; ] }, { &quot;fields&quot;: { &quot;@timestamp&quot;: [ &quot;2022-10-04T22:46:17.482Z&quot; ] } ] } } </code></pre> <p><strong>My Code:</strong></p> <pre><code>let arr = []; const occData = data?. dataArr.map(function (val) { timestamp = val.fields[&quot;@timestamp&quot;]; var myDate = new Date(timestamp); var minutes = myDate.getMinutes(); // converted date to the minutes arr.push(minutes); // Now I need to find the occurrences and build the new object }); </code></pre> <p><strong>Expected Result:</strong></p> <pre><code>{ &quot;45&quot;: 2, &quot;46&quot;: 1 } </code></pre>
[ { "answer_id": 74397699, "author": "局外人", "author_id": 18188786, "author_profile": "https://Stackoverflow.com/users/18188786", "pm_score": 3, "selected": true, "text": "menu.setOnNavigationItemSelectedListener {\n when(it.itemId){\n R.id.homeFragment -> {\n val graph = navController.graph\n graph.startDestination = R.id.homeFragment\n navController.graph = graph\n }\n }\n}\n" }, { "answer_id": 74400121, "author": "Mert", "author_id": 4058604, "author_profile": "https://Stackoverflow.com/users/4058604", "pm_score": 0, "selected": false, "text": " bottomNavigationView.setOnItemSelectedListener { item ->\n NavigationUI.onNavDestinationSelected(item, navController)\n navController.popBackStack(item.itemId, inclusive = false)\n true\n }\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74396794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3361650/" ]
74,396,799
<p>I have been working on code that will extract four rows from every .CSV in a folder, compile the rows into a new table, and pivot wider so there is only one entry per each original .csv.</p> <p>Everything works great until I try to write the resulting table to a .csv,</p> <p>The table looks great in viewer and as a tibble. If I could just get this format to export to .csv I'd be thrilled.</p> <p><a href="https://i.stack.imgur.com/VJHB8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VJHB8.png" alt="enter image description here" /></a></p> <p>However, when I export it using write.csv I get this:</p> <p><a href="https://i.stack.imgur.com/C3cPN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/C3cPN.png" alt="enter image description here" /></a></p> <p>It looks like each column is being exported as a cell and then copied for each row. I figure the problem is something to do with exporting after completing the pivot_wider function.</p> <h2>Here is my code. Everything works and I am not getting any errors, it just doesn't export the way I need it to.</h2> <pre><code>library(dplyr) library(tidyverse) library(tidyr) #Create a list of files files &lt;-list.files(pattern = &quot;*Correlations.csv&quot;) # Create an empty object to store all combined rows combined_df= data.frame(material=character(), code=double(), measurement=double(), name=character(), spectra=character()) #Create empty object to temporarily collect data produced every run in the loop data_it= data.frame(matrix(ncol = 5, nrow = 4)) colnames(data_it) =c(&quot;material&quot;, &quot;code&quot;, &quot;measurement&quot;, &quot;name&quot;, &quot;spectra&quot;) #Run a loop for (j in 1:length(files)){ data &lt;- read_csv(files[j], skip = 2, col_names =c(&quot;material&quot;, &quot;code&quot;, &quot;measurement&quot;, &quot;name&quot;, &quot;spectra&quot;)) data_it$material &lt;- data[3:6, 1] data_it$code &lt;- data[3:6, 2] data_it$measurement&lt;- data[3:6, 3] data_it$name &lt;- paste(files[j]) data_it$spectra &lt;- c(&quot;spectra 1&quot;, &quot;spectra 2&quot;, &quot;spectra 3&quot;, &quot;spectra 4&quot;) combined_df &lt;- rbind(combined_df, data_it) } #pivot table so that there is one row per file combined_pivot&lt;-pivot_wider(combined_df, names_from = spectra, values_from = c(material, code, measurement), names_vary = &quot;slowest&quot;) #export to .csv write.csv(combined_pivot, file =&quot;combined_results.csv&quot;) </code></pre> <h2>Here is a sample of one of the .csv files I am trying to extract from. I have hundreds of these with 100 rows each and I just need the top three rows from each one</h2> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>material</th> <th>code</th> <th>measurement</th> </tr> </thead> <tbody> <tr> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> </tr> <tr> <td>animal furs/natural polyamides</td> <td>13</td> <td>0.6777</td> </tr> <tr> <td>animal furs/natural polyamides</td> <td>13</td> <td>0.6065</td> </tr> <tr> <td>cellulose/plant fibres</td> <td>14</td> <td>0.5725</td> </tr> <tr> <td>animal furs/natural polyamides</td> <td>13</td> <td>0.5698</td> </tr> <tr> <td>animal furs/natural polyamides</td> <td>13</td> <td>0.5171</td> </tr> <tr> <td>animal furs/natural polyamides</td> <td>13</td> <td>0.5128</td> </tr> <tr> <td>animal furs/natural polyamides</td> <td>13</td> <td>0.4932</td> </tr> <tr> <td>animal furs/natural polyamides</td> <td>13</td> <td>0.4904</td> </tr> </tbody> </table> </div> <p>Thanks for reading and for any suggestions. I am new to R and out of ideas.</p>
[ { "answer_id": 74397699, "author": "局外人", "author_id": 18188786, "author_profile": "https://Stackoverflow.com/users/18188786", "pm_score": 3, "selected": true, "text": "menu.setOnNavigationItemSelectedListener {\n when(it.itemId){\n R.id.homeFragment -> {\n val graph = navController.graph\n graph.startDestination = R.id.homeFragment\n navController.graph = graph\n }\n }\n}\n" }, { "answer_id": 74400121, "author": "Mert", "author_id": 4058604, "author_profile": "https://Stackoverflow.com/users/4058604", "pm_score": 0, "selected": false, "text": " bottomNavigationView.setOnItemSelectedListener { item ->\n NavigationUI.onNavDestinationSelected(item, navController)\n navController.popBackStack(item.itemId, inclusive = false)\n true\n }\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74396799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20472784/" ]
74,396,829
<p>I'm making a Balloon Fight style game and I'm having trouble with object collision. Each character has two balloons on top of his head and each balloon has an on trigger Box Collider. I want to make it so only one balloon can be hit at a time so you can't destroy both balloons at the same time. In order to do this I added a boolean called isAttacking to prevent it from destroying more than one balloon at the same time.</p> <p>Hello, I'm making a Balloon Fight style game and I'm having trouble with object collision. Each character has two balloons on top of his head and each balloon has an on trigger Box Collider. I want to make it so only one balloon can be hit at a time so you can't destroy both balloons at the same time. In order to do this I added a boolean called isAttacking to prevent it from destroying more than one balloon at the same time.</p> <pre><code> public bool isAttacking = false; private void OnTriggerEnter(Collider collision) { if (collision.GetComponent&lt;Collider&gt;().gameObject.layer == 7 &amp;&amp; collision.GetComponent&lt;Collider&gt;().gameObject.tag != this.gameObject.tag) { if (!isAttacking) { Destroy(collision.GetComponent&lt;Collider&gt;().transform.parent.gameObject); transform.parent.gameObject.GetComponent&lt;Jump&gt;().jump = true; isAttacking = true; } } } void LateUpdate() { if (isAttacking) { isAttacking = false; } } </code></pre> <p>While it does prevent two collisions from registering I still found this solution to be insufficient, since the balloon that is destroyed is not necessarily the one closest to the character destroying it. How could I improve the collision code in order for it to only register the collision happening closer to the character?</p>
[ { "answer_id": 74397699, "author": "局外人", "author_id": 18188786, "author_profile": "https://Stackoverflow.com/users/18188786", "pm_score": 3, "selected": true, "text": "menu.setOnNavigationItemSelectedListener {\n when(it.itemId){\n R.id.homeFragment -> {\n val graph = navController.graph\n graph.startDestination = R.id.homeFragment\n navController.graph = graph\n }\n }\n}\n" }, { "answer_id": 74400121, "author": "Mert", "author_id": 4058604, "author_profile": "https://Stackoverflow.com/users/4058604", "pm_score": 0, "selected": false, "text": " bottomNavigationView.setOnItemSelectedListener { item ->\n NavigationUI.onNavDestinationSelected(item, navController)\n navController.popBackStack(item.itemId, inclusive = false)\n true\n }\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74396829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20473276/" ]
74,396,883
<p>I was trying to make a chat UI with some actions that show in an overlay, but the buttons got chopped off. Here's what I tried to do:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.parent { position: relative; overflow: hidden; background: #111; color: white; } .overlay { background: purple; position: absolute; right: 0; top: 0; bottom: 0; display: flex; flex-direction: column; flex-wrap: wrap; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="parent"&gt; Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque sit odio temporibus quidem, tempora libero nobis fuga impedit alias illum. &lt;div class="overlay"&gt; &lt;button&gt; A &lt;/button&gt; &lt;button&gt; B &lt;/button&gt; &lt;button&gt; C &lt;/button&gt; &lt;button&gt; D &lt;/button&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>I'm looking for something that looks like a grid, and would get longer if more buttons were added.<br /> If I set <code>flex-direction</code> to row instead, it works fine, but that makes the buttons not be stacked. If I remove <code>overflow: hidden</code> I can see the buttons outside of the overlay, instead of it staying inside of the box. If I set a width for the overlay, things work fine, but I want the width to be dynamic.</p>
[ { "answer_id": 74396959, "author": "DeusDev", "author_id": 10312417, "author_profile": "https://Stackoverflow.com/users/10312417", "pm_score": 0, "selected": false, "text": "parent" }, { "answer_id": 74396963, "author": "John", "author_id": 11111119, "author_profile": "https://Stackoverflow.com/users/11111119", "pm_score": 1, "selected": false, "text": "display: flex;" }, { "answer_id": 74397007, "author": "DCR", "author_id": 4398966, "author_profile": "https://Stackoverflow.com/users/4398966", "pm_score": 0, "selected": false, "text": "#container{\ndisplay:flex;}\n\n#x, #y{\ndisplay:flex;}" }, { "answer_id": 74397166, "author": "KTibow", "author_id": 12243248, "author_profile": "https://Stackoverflow.com/users/12243248", "pm_score": 0, "selected": false, "text": ".parent {\n position: relative;\n overflow: hidden;\n background: #111;\n color: white;\n}\n.overlay {\n background: purple;\n position: absolute;\n right: 0;\n top: 0;\n bottom: 0;\n display: grid;\n grid-template-columns: repeat(2, minmax(0, 1fr));\n}" }, { "answer_id": 74397918, "author": "Michael Benjamin", "author_id": 3597276, "author_profile": "https://Stackoverflow.com/users/3597276", "pm_score": 0, "selected": false, "text": ".parent {\n position: relative;\n /* overflow: hidden; */ /* 1 */\n background: #111;\n color: white;\n}\n\n.overlay {\n background: purple;\n position: absolute;\n right: 0;\n top: 0;\n bottom: 0;\n display: flex;\n /* flex-direction: column; */ /* 2 */\n flex-wrap: wrap;\n}\n\nbutton {\n flex-basis: 50%; /* 3 */\n}" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74396883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12243248/" ]
74,396,935
<p>I am working on a problem where I am using a dictionary to replace certain words in a string.</p> <p>This is my code for a minimal example:</p> <pre><code>dictionary = {&quot;happy&quot;: 'YAY!', &quot;happybday&quot;: &quot;PARTY!&quot;} string = &quot;There were so many happy people exclaiming happybday!&quot; for old_word, new_word in dictionary.items(): string = string.replace(old_word, new_word) print(string) </code></pre> <p>The problem here is I am getting the output:</p> <pre><code>There were so many YAY! people exclaiming YAY!bday! </code></pre> <p>Desired output:</p> <pre><code>There were so many YAY! people exclaiming PARTY!! </code></pre> <p>Clearly what is happening is that while iterating through each element in the dictionary, it is first seeing &quot;happy&quot; and then seeing that as a substring and replacing each instance of the substring. Where this is a problem is that in the second case, I the substring forms a larger string which should be replaced. However, when I iterate through each element in the dictionary it is only looking at the substring level.</p> <p>Does anyone have any ideas on how I might be able to fix this? I thought perhaps either reordering the items in the dictionary (so that the larger stings come first), but this does not seem like the best solution. I could also just simply split the string into a list of words and try to compare and replace based on this, but since this might take more time, I though that might not be the best solution either.</p> <p>I think part of the problem might be occurring because of using the &quot;in&quot; keyword here, but I am not entirety sure.</p> <p>Any advice? Any links to explanations, tutorials, or examples would be greatly appreciated. I am really trying to understand not only what to fix but what is wrong in the first place. Thanks.</p>
[ { "answer_id": 74396979, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 1, "selected": false, "text": "dictionary = {\"happy\": 'YAY!', \"happybday\": \"PARTY!\"}\nstring = \"There were so many happy people exclaiming happybday!\"\n\nregex = r'\\b(?:' + r'|'.join(sorted(dictionary.keys(), key=len, reverse=True)) + r')\\b'\noutput = re.sub(regex, lambda m: dictionary[m.group()], string)\nprint(output)\n\n# There were so many YAY! people exclaiming PARTY!!\n" }, { "answer_id": 74397022, "author": "monkut", "author_id": 24718, "author_profile": "https://Stackoverflow.com/users/24718", "pm_score": 0, "selected": false, "text": "dictionary = {\"happy\": 'YAY!', \"happybday\": \"PARTY!\"}\n\nstring = \"There were so many happy people exclaiming happybday!\"\n\ndef by_length(item): \n key, value = item\n return len(key)\n\nfor old_word, new_word in sorted(dictionary.items(), key=by_length, reverse=True):\n string = string.replace(old_word, new_word)\n" } ]
2022/11/11
[ "https://Stackoverflow.com/questions/74396935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12035742/" ]