qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,536,100
<p>I'm looking to transition this code to use Streams.</p> <pre class="lang-java prettyprint-override"><code>public ResultObject getBestObjectWithParameters() { int maxParameterValue = 10; double bestValue = 0.0; ResultObject bestObject = null; for (int a = 0; a &lt; maxParameterValue; a++) { for (int b = 0; b &lt; maxParameterValue; b++) { for (int c = 0; c &lt; maxParameterValue; c++) { ResultObject o = runCalculation(a, b, c); if (o.getValue() &gt; bestValue) { bestValue = getValue; bestObject = o; } } } } return bestObject; } </code></pre> <p>In short, I'd like to <code>runCalculation</code> on every combination of parameters. <code>runCalculation</code> returns a <code>ResultObject</code>. I'd like to return <em>the</em> <code>ResultObject</code> that returns the maximum <code>ResultObject.getValue()</code>.</p> <p>Ideally, I would like to use <code>parallel()</code> to run this as quickly as possible.</p> <p>What is the best way to do this?</p>
[ { "answer_id": 74536328, "author": "Rob Spoor", "author_id": 1180351, "author_profile": "https://Stackoverflow.com/users/1180351", "pm_score": 1, "selected": false, "text": "flatMap public ResultObject getBestObjectWithParameters() {\n int maxParameterValue = 10;\n return IntStream.range(0, maxParameterValue)\n .mapToObj(a -> a) // Stream<Integer>\n .flatMap(a -> IntStream.range(0, maxParameterValue)\n .mapToObj(b -> b) // Stream<Integer>\n .flatMap(b -> IntStream.range(0, maxParameterValue)\n .mapToObj(c -> c) // Stream<Integer>\n .map(c -> runCalculation(a, b, c)) // Stream<ResultObject>\n ) // Stream<resultObject>\n ) // Stream<ResultObject>\n .max(Comparator.comparingDouble(ResultObject::getValue))\n .orElse(null);\n}\n mapToObj IntStream flatMap IntStream Stream<ResultObject>" }, { "answer_id": 74536464, "author": "Edward Peters", "author_id": 6016064, "author_profile": "https://Stackoverflow.com/users/6016064", "pm_score": 1, "selected": false, "text": "IntStream flatMap int maxParameterValue = 10;\n IntStream.range(0, maxParameterValue).boxed()\n .flatMap(i -> IntStream.range(0, maxParameterValue).boxed()\n .flatMap(j -> IntStream.range(0, maxParameterValue).boxed()\n .map(k -> i + \"-\" + j + \"-\" + k)))\n .forEach(s -> System.out.println(s));\n .boxed()" }, { "answer_id": 74536540, "author": "James Mudd", "author_id": 4653517, "author_profile": "https://Stackoverflow.com/users/4653517", "pm_score": 3, "selected": true, "text": "import com.google.common.collect.Sets;\n\nimport java.util.Comparator;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.stream.Collectors;\nimport java.util.stream.IntStream;\n\nclass Scratch {\n public static void main(String[] args) {\n int maxParameterValue = 10;\n\n Set<Integer> params = IntStream.range(0, maxParameterValue).boxed().collect(Collectors.toSet());\n Result bestResult = Sets.cartesianProduct(params, params, params).stream()\n .parallel()\n .map(Result::new)\n .max(Comparator.comparingDouble(Result::getResult)).get();\n\n System.out.println(bestResult);\n }\n\n private static double runCalculation(int a, int b, int c) {\n // This just sums the 3 inputs replace with your function\n return a + b + c;\n }\n\n private static class Result {\n int a,b, c;\n double result;\n\n public Result(List<Integer> params) {\n this.a = params.get(0);\n this.b = params.get(1);\n this.c = params.get(2);\n this.result = runCalculation(a, b, c);\n }\n\n public double getResult() {\n return result;\n }\n\n @Override\n public String toString() {\n return String.format(\"Result{a=%d, b=%d, c=%d, result=%s}\", a, b, c, result);\n }\n }\n}\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/795221/" ]
74,536,110
<p>I am asking a question concerning the additive predictive benefit of the inclusion of a variable to a logistic and an ordinal model. I am using mice to impute missing covariates and am having difficulty finding ways to calculate the AUC and R squared of the pooled imputed models. Does anyone have any advice?</p> <p>The summary readout only provides the term, estimate, std.error, statistic, df , p.value</p> <p>Example code:</p> <pre><code>imputed_Data &lt;- mice(Cross_sectional, m=10, predictorMatrix=predM, seed=500, method = meth) Imputedreferecemodel &lt;- with(imputed_Data, glm(Poor ~ age + sex + education + illness + injurycause, family = &quot;binomial&quot;, na.action=na.omit) ) summary(pool(Imputedreferecemodel)) </code></pre> <p>Many thanks.</p>
[ { "answer_id": 74536829, "author": "jrcalabrese", "author_id": 14992857, "author_profile": "https://Stackoverflow.com/users/14992857", "pm_score": 1, "selected": false, "text": "mice::pool.r.squared lm glm() mfc() glmice mfc() # install.packages(\"remotes\")\n# remotes::install_github(\"noahlorinczcomi/glmice\")\nlibrary(glmice)\nlibrary(mice)\ndata(nhanes)\nnhanes$hyp <- ifelse(nhanes$hyp == 2, 1, 0)\nimp <- mice(nhanes, m = 10, seed = 500, printFlag = FALSE)\nmod <- with(imp, glm(hyp ~ age + bmi, family = \"binomial\"))\n# summary(pool(mod))\nmcf(mod)\n#> [1] \"34.9656%\"\n glm() finalfit library(finalfit)\nmod %>% \n getfit() %>% \n purrr::map(~ pROC::roc(.x$y, .x$fitted)$auc)\n# not pasting the output because it's a lot\n" }, { "answer_id": 74655635, "author": "Quinten", "author_id": 14282714, "author_profile": "https://Stackoverflow.com/users/14282714", "pm_score": 0, "selected": false, "text": "psfmi mice pool_performance nhanes mice # install.packages(\"devtools\")\n# devtools::install_github(\"mwheymans/psfmi\") # for installing package\nlibrary(psfmi)\nlibrary(mice)\n\n# Make reproducible data with 0 and 1 outcome variable\nset.seed(123)\nnhanes$hyp <- ifelse(nhanes$hyp==1,0,1)\nnhanes$hyp <- as.factor(nhanes$hyp)\n\n# Mice\nimp <- mice(nhanes, m=5, maxit=5) \n\nnhanes_comp <- complete(imp, action = \"long\", include = FALSE)\n\npool_lr <- psfmi_lr(data=nhanes_comp, nimp=5, impvar=\".imp\", \n formula=hyp ~ bmi, method=\"D1\")\npool_lr$RR_model\n#> $`Step 1 - no variables removed -`\n#> term estimate std.error statistic df p.value OR\n#> 1 (Intercept) -0.76441322 3.4753113 -0.21995532 16.06120 0.8286773 0.4656071\n#> 2 bmi -0.01262911 0.1302484 -0.09696177 15.79361 0.9239765 0.9874503\n#> lower.EXP upper.EXP\n#> 1 0.0002947263 735.56349\n#> 2 0.7489846190 1.30184\n\n# Check performance\npool_performance(pool_lr, data = nhanes_comp, formula = hyp ~ bmi, \n nimp=5, impvar=\".imp\", \n cal.plot=TRUE, plot.indiv=\"mean\", \n groups_cal=4, model_type=\"binomial\")\n#> Warning: argument plot.indiv is deprecated; please use plot.method instead.\n #> $ROC_pooled\n#> 95% Low C-statistic 95% Up\n#> C-statistic (logit) 0.2731 0.5207 0.7586\n#> \n#> $coef_pooled\n#> (Intercept) bmi \n#> -0.76441322 -0.01262911 \n#> \n#> $R2_pooled\n#> [1] 0.009631891\n#> \n#> $Brier_Scaled_pooled\n#> [1] 0.004627443\n#> \n#> $nimp\n#> [1] 5\n#> \n#> $HLtest_pooled\n#> F_value P(>F) df1 df2\n#> [1,] 0.9405937 0.400953 2 31.90878\n#> \n#> $model_type\n#> [1] \"binomial\"\n" }, { "answer_id": 74677209, "author": "kppro", "author_id": 10955397, "author_profile": "https://Stackoverflow.com/users/10955397", "pm_score": 0, "selected": false, "text": "# load the required packages\nlibrary(mice)\nlibrary(ROCR)\nlibrary(MuMIn)\n\n# create the imputed data using mice\nimputed_data <- mice(Cross_sectional, m=10, predictorMatrix=predM, seed=500, method = meth)\n\n# fit the reference model to the imputed data\nImputedreferecemodel <- with(imputed_data, glm(Poor ~ age + sex + education + illness + injurycause, family = \"binomial\", na.action=na.omit) )\n\n# pool the estimates of the imputed models\npooled_model <- pool(Imputedreferecemodel)\n\n# get the predicted probabilities of the pooled model\npredicted_probabilities <- predict(pooled_model, type=\"response\")\n\n# calculate the AUC of the pooled model\nroc_obj <- roc(Cross_sectional$Poor, predicted_probabilities)\nauc <- roc_obj$auc\n\n# calculate the R squared of the pooled model\nrsquared <- r.squaredGLM(pooled_model)\n\n# print the AUC and R squared values\nprint(auc)\nprint(rsquared)\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14322196/" ]
74,536,116
<p>I'm an R/Tidyverse guy getting my feet wet in python/pandas and having trouble discerning if there is a way to do the following as elegantly in pandas as tidyverse:</p> <pre class="lang-r prettyprint-override"><code>( dat %&gt;% group_by(grp) %&gt;% mutate( value = value/max(value) ) ) </code></pre> <p>So, there's a grouped mutate that involves a non-reducing operation (division) that in turn involves the result of a reducing operation (max). I know the following is possible:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np df = pd.DataFrame({'grp': np.random.randint(0,5, 10), 'value': np.random.randn(10)}).sort_values('grp') tmp = ( df .groupby('grp') .agg('max') ) ( df .merge(tmp,on='grp') .assign( value = lambda x: x.value_x / x.value_y ) ) </code></pre> <p>But I feel like there must be a way to avoid the creation of the temporary variable <code>tmp</code> to achieve this in one expression like I can achieve in tidyverse. Am I wrong?</p> <p>Update: I'm marking @PaulS's answer as correct as it indeed addresses the question as posed. On using it something other than my minimal example, I realized there was further implicit behaviour in tidyverse I hadn't accounted for; specifically, that columns not involved in the series of specified operations are kept in the tidyverse case and dropped in @PaulS's answer. So here instead is an example &amp; solution that more closely emulates tidyverse:</p> <pre class="lang-py prettyprint-override"><code>df = ( pd.DataFrame({ 'grp': np.random.randint(0,5, 10) #to be used for grouping , 'time': np.random.normal(0,1,10) #extra column not involved in computation , 'value': np.random.randn(10) #to be used for calculations }) .sort_values(['grp','time']) .reset_index() ) #computing a grouped non-reduced-divided-by-reduced: ( df .groupby('grp', group_keys=False) .apply( lambda x: ( x.assign( value = ( x.value / x.value.max() ) ) ) ) .reset_index() .drop(['index','level_0'],axis=1) ) </code></pre> <p>I also discovered that if I want to index into one column during the assignment, I have to tweak things a bit, for example:</p> <pre class="lang-py prettyprint-override"><code>#this time the reduced compute involves getting the value at the time closest to zero: ( df .groupby('grp', group_keys=False) .apply( lambda x: ( x.assign( value = ( x.value / x.value.values[np.argmin(np.abs(x.time))] #note use of .values[] ) ) ) ) .reset_index() .drop(['index','level_0'],axis=1) ) </code></pre>
[ { "answer_id": 74536166, "author": "PaulS", "author_id": 11564487, "author_profile": "https://Stackoverflow.com/users/11564487", "pm_score": 1, "selected": false, "text": "(df.groupby('grp')\n .apply(lambda g: g['value'].div(g['value'].max()))\n .droplevel(1)\n .reset_index())\n grp value\n0 0 1.000000\n1 1 1.000000\n2 1 1.052922\n3 2 1.000000\n4 2 5.873499\n5 3 10.009542\n6 3 1.000000\n7 4 1.000000\n8 4 -0.842420\n9 4 0.410153\n" }, { "answer_id": 74538597, "author": "sammywemmy", "author_id": 7175713, "author_profile": "https://Stackoverflow.com/users/7175713", "pm_score": 3, "selected": true, "text": "df.assign(value = df.value/df.groupby('grp').value.transform('max'))\n grp value\n1 0 1.000000\n2 1 -0.290494\n3 1 1.000000\n4 1 0.214848\n6 2 8.242604\n7 2 1.000000\n8 2 1.156246\n0 3 0.655760\n9 3 1.000000\n5 4 1.000000\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/174902/" ]
74,536,117
<p>I have created a CMS. When installing the CMS, I must install its database. I use PHP <code>multi_query()</code> to istall the database without opening phpMyAdmin. When the SQL file is as small as 624KB, the database is installed successfully. However, when the SQL file is as large as 6.32MB or more, the database does not install. Here is the code I use to install the database via PHP</p> <pre><code> $sParamSqlFile = 'database.sql'; if(file_exists($sParamSqlFile)){ $fSql = file_get_contents($sParamSqlFile); /* execute multi query */ if ($oDbConn-&gt;multi_query($fSql)){ do { /* store first result set */ if ($oResult = $oDbConn-&gt;store_result()) { while ($aRow = $oResult-&gt;fetch_row()) { // } $oResult-&gt;free(); }; /* print divider */ if ($oDbConn-&gt;more_results()){ // } } while ($oDbConn-&gt;next_result()); } else{ return 'false'; } /* close connection */ $oDbConn-&gt;close(); return 'true'; } return $sParamSqlFile . ' does not exist'; </code></pre> <p>Edit: I have encounted this error while trying to install the database <strong>&quot;Warning: mysqli::multi_query(): Error while reading SET_OPTION's response packet. PID=8660&quot;</strong></p> <p>Could you help with a solution so that I could install the database when the SQL file is large?</p>
[ { "answer_id": 74536166, "author": "PaulS", "author_id": 11564487, "author_profile": "https://Stackoverflow.com/users/11564487", "pm_score": 1, "selected": false, "text": "(df.groupby('grp')\n .apply(lambda g: g['value'].div(g['value'].max()))\n .droplevel(1)\n .reset_index())\n grp value\n0 0 1.000000\n1 1 1.000000\n2 1 1.052922\n3 2 1.000000\n4 2 5.873499\n5 3 10.009542\n6 3 1.000000\n7 4 1.000000\n8 4 -0.842420\n9 4 0.410153\n" }, { "answer_id": 74538597, "author": "sammywemmy", "author_id": 7175713, "author_profile": "https://Stackoverflow.com/users/7175713", "pm_score": 3, "selected": true, "text": "df.assign(value = df.value/df.groupby('grp').value.transform('max'))\n grp value\n1 0 1.000000\n2 1 -0.290494\n3 1 1.000000\n4 1 0.214848\n6 2 8.242604\n7 2 1.000000\n8 2 1.156246\n0 3 0.655760\n9 3 1.000000\n5 4 1.000000\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12963244/" ]
74,536,165
<p>I have a JSON column, <code>telework</code>, stored in Postgres which looks like</p> <pre><code>&quot;{ ..., &quot;biweeklyWeek1-locationMon&quot;: &quot;alternative&quot;, &quot;biweeklyWeek1-locationTues&quot;: &quot;agency&quot;, &quot;biweeklyWeek1-locationWeds&quot;: &quot;alternative&quot;, &quot;biweeklyWeek1-locationThurs&quot;: &quot;alternative&quot;, &quot;biweeklyWeek1-locationFri&quot;: &quot;alternative&quot;, ... , &quot;biweeklyWeek2-locationMon&quot;: &quot;alternative&quot;, &quot;biweeklyWeek2-locationTues&quot;: &quot;agency&quot;, &quot;biweeklyWeek2-locationWeds&quot;: &quot;alternative&quot;, &quot;biweeklyWeek2-locationThurs&quot;: &quot;alternative&quot;, &quot;biweeklyWeek2-locationFri&quot;: &quot;alternative&quot;, ... }&quot; </code></pre> <p>I need to <strong>count the number of occurrences of &quot;alternative&quot;</strong> in the <code>biweeklyWeek1-location*</code> fields and <code>biWeeklyWeek2-location*</code> fields separately and select these two as separate fields in the main query. It's possible that the values in these fields could be filled, blank (<code>&quot;&quot;</code>), or <code>null</code>. Also, it's possible that these fields are partially or completely missing in the JSON.</p> <pre><code>select a.id, a.name, a.telework-&gt;&gt;??? as alternativePerWeek1, a.telework-&gt;&gt;??? as alternativePerWeek2, ... </code></pre> <p>Strangely enough, even when I do the following single example with <code>-&gt;</code> a hard-coded ID, I get a NULL result even though I see that it shouldn't be NULL:</p> <p><code>select telework, telework-&gt;'biweeklyWeek1-locationMon' from ets.agreement_t where id = 24763;</code></p> <p><a href="https://i.stack.imgur.com/W0eFC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/W0eFC.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74536166, "author": "PaulS", "author_id": 11564487, "author_profile": "https://Stackoverflow.com/users/11564487", "pm_score": 1, "selected": false, "text": "(df.groupby('grp')\n .apply(lambda g: g['value'].div(g['value'].max()))\n .droplevel(1)\n .reset_index())\n grp value\n0 0 1.000000\n1 1 1.000000\n2 1 1.052922\n3 2 1.000000\n4 2 5.873499\n5 3 10.009542\n6 3 1.000000\n7 4 1.000000\n8 4 -0.842420\n9 4 0.410153\n" }, { "answer_id": 74538597, "author": "sammywemmy", "author_id": 7175713, "author_profile": "https://Stackoverflow.com/users/7175713", "pm_score": 3, "selected": true, "text": "df.assign(value = df.value/df.groupby('grp').value.transform('max'))\n grp value\n1 0 1.000000\n2 1 -0.290494\n3 1 1.000000\n4 1 0.214848\n6 2 8.242604\n7 2 1.000000\n8 2 1.156246\n0 3 0.655760\n9 3 1.000000\n5 4 1.000000\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536165", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1005607/" ]
74,536,170
<p>I am trying to do the secant method to find the root of the polynonium (-2<em>x**6)-(1.5</em>x**4)+(10*x)+(2) with inithial value 2,3 and I get this error</p> <pre><code>import numpy as np def f(x): return (-2*x**6)-(1.5*x**4)+(10*x)+(2) def secante(f,x,fp,N=100,emax=0.0001): for k in range(N): fp=(f(x1)-f(x0))/(x1-x0) x=x1-f(x1)/fp e=abs((x-x1)/x) if e&lt;emax: break x0=x1 x1=x print(k,x,f(x),e) secante(f,2,3) </code></pre> <pre><code>--------------------------------------------------------------------------- UnboundLocalError Traceback (most recent call last) Input In [10], in &lt;cell line: 17&gt;() 15 x1=x 16 print(k,x,f(x),e) ---&gt; 17 secante(f,2,3) Input In [10], in secante(f, x, fp, N, emax) 7 def secante(f,x,fp,N=100,emax=0.0001): 8 for k in range(N): ----&gt; 9 fp=(f(x1)-f(x0))/(x1-x0) 10 x=x1-f(x1)/fp 11 e=abs((x-x1)/x) UnboundLocalError: local variable 'x1' referenced before assignment </code></pre>
[ { "answer_id": 74536166, "author": "PaulS", "author_id": 11564487, "author_profile": "https://Stackoverflow.com/users/11564487", "pm_score": 1, "selected": false, "text": "(df.groupby('grp')\n .apply(lambda g: g['value'].div(g['value'].max()))\n .droplevel(1)\n .reset_index())\n grp value\n0 0 1.000000\n1 1 1.000000\n2 1 1.052922\n3 2 1.000000\n4 2 5.873499\n5 3 10.009542\n6 3 1.000000\n7 4 1.000000\n8 4 -0.842420\n9 4 0.410153\n" }, { "answer_id": 74538597, "author": "sammywemmy", "author_id": 7175713, "author_profile": "https://Stackoverflow.com/users/7175713", "pm_score": 3, "selected": true, "text": "df.assign(value = df.value/df.groupby('grp').value.transform('max'))\n grp value\n1 0 1.000000\n2 1 -0.290494\n3 1 1.000000\n4 1 0.214848\n6 2 8.242604\n7 2 1.000000\n8 2 1.156246\n0 3 0.655760\n9 3 1.000000\n5 4 1.000000\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20574324/" ]
74,536,171
<p>I'm a beginner in Deep Learning and NLP stream. I was trying to install Tensorflow but it is giving me an error. Can anyone please help me how to solve this? <a href="https://i.stack.imgur.com/Mm2rk.png" rel="nofollow noreferrer">This is the error I'm getting</a></p> <p>I was watchig an YouTube video for Toxic Comment Classification and thought should try that out for better practice. After creating an enviroment for the file I triedd to install Tensorflow but it threw this error. I updated my Anaconda, Updated python to 3.11 and pip to 22.3 but still it is not working.</p>
[ { "answer_id": 74536166, "author": "PaulS", "author_id": 11564487, "author_profile": "https://Stackoverflow.com/users/11564487", "pm_score": 1, "selected": false, "text": "(df.groupby('grp')\n .apply(lambda g: g['value'].div(g['value'].max()))\n .droplevel(1)\n .reset_index())\n grp value\n0 0 1.000000\n1 1 1.000000\n2 1 1.052922\n3 2 1.000000\n4 2 5.873499\n5 3 10.009542\n6 3 1.000000\n7 4 1.000000\n8 4 -0.842420\n9 4 0.410153\n" }, { "answer_id": 74538597, "author": "sammywemmy", "author_id": 7175713, "author_profile": "https://Stackoverflow.com/users/7175713", "pm_score": 3, "selected": true, "text": "df.assign(value = df.value/df.groupby('grp').value.transform('max'))\n grp value\n1 0 1.000000\n2 1 -0.290494\n3 1 1.000000\n4 1 0.214848\n6 2 8.242604\n7 2 1.000000\n8 2 1.156246\n0 3 0.655760\n9 3 1.000000\n5 4 1.000000\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19811627/" ]
74,536,221
<p>Can anyone please help me wrap the condition inside another condition in php.</p> <p>I have this code #1 that I want to be inside code #2.</p> <p>Here's code #1</p> <pre><code>&lt;?php if( get_field('highlights') ): ?&gt; &lt;div class=&quot;overview&quot;&gt; &lt;h3&gt;Quick Overview&lt;/h3&gt; &lt;?php the_field('highlights'); ?&gt; &lt;/div&gt; &lt;?php endif; ?&gt; </code></pre> <p>Here's code #2</p> <pre><code>&lt;?php if(strstr($_SERVER['HTTP_REFERER'],'www.example.com')) { echo '**CODE #1 should be placed here**'; } ?&gt; </code></pre> <p>Sorry, I don't haev any knowledge in PHP.</p> <p>Wrapping code 1 inside code 2</p>
[ { "answer_id": 74536166, "author": "PaulS", "author_id": 11564487, "author_profile": "https://Stackoverflow.com/users/11564487", "pm_score": 1, "selected": false, "text": "(df.groupby('grp')\n .apply(lambda g: g['value'].div(g['value'].max()))\n .droplevel(1)\n .reset_index())\n grp value\n0 0 1.000000\n1 1 1.000000\n2 1 1.052922\n3 2 1.000000\n4 2 5.873499\n5 3 10.009542\n6 3 1.000000\n7 4 1.000000\n8 4 -0.842420\n9 4 0.410153\n" }, { "answer_id": 74538597, "author": "sammywemmy", "author_id": 7175713, "author_profile": "https://Stackoverflow.com/users/7175713", "pm_score": 3, "selected": true, "text": "df.assign(value = df.value/df.groupby('grp').value.transform('max'))\n grp value\n1 0 1.000000\n2 1 -0.290494\n3 1 1.000000\n4 1 0.214848\n6 2 8.242604\n7 2 1.000000\n8 2 1.156246\n0 3 0.655760\n9 3 1.000000\n5 4 1.000000\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19612840/" ]
74,536,225
<p>I am a beginner writing a Python code, where the computer generates a random number between 1 and 10, 1 and 100, 1 and 1000, 1 and 10000, 1 and 100000 and so on. The computer itself will guess the random number a number of times (a user input number), and every time there is a count of how many times the computer took to guess the random number. A mean of the count over the number of times will be calculated and put in an array, where matplotlib will generate a graph of x=log10(the upper bounds of the random number range, i.e. 10, 100, 1000,...)</p> <p>At the moment, I print the log10 of each bound as it is processed, and that has been acting as my progress tracker. But I am thinking of adding my progress bar, and I don't know where to put it so that I can see how much of the overall program has run.</p> <p>I have added tqdm.tqdm in all sorts of different places to no avail. I am expecting a progress bar increasing as the program runs.</p> <p>My program is as shown.</p> <pre><code># Importing the modules needed import random import time import timeit import numpy as np import matplotlib.pyplot as plt import tqdm # Function for making the computer guess the number it itself has generated and seeing how many times it takes for it to guess the number def computer_guess(x): # Telling program that value &quot;low&quot; exists and it's 0 low = 0 # Telling program that value &quot;high&quot; exists and it's the arbitrary parameter x high = x # Storing random number with lower limit &quot;low&quot; and upper limit &quot;high&quot; as &quot;ranno&quot; for the while-loop later ranno = random.randint(low, high) # Setting initial value of &quot;guess&quot; for iteration guess = -1 # Setting initial value of &quot;count&quot; for iteration count = 1 # While-loop for all guessing conditions while guess != ranno: # Condition: As long as values of &quot;low&quot; and &quot;high&quot; aren't the same, keep guessing until the values are the same, in which case &quot;guess&quot; is same as &quot;low&quot; (or &quot;high&quot; becuase they are the same anyway) if low != high: guess = random.randint(low, high) else: guess = low # Condition: If the guess if bigger than the random number, lower the &quot;high&quot; value to one less than 1, and add 1 to the guess count if guess &gt; ranno: high = guess - 1 count += 1 # Condition: If the guess if smaller than the random number, increase the &quot;low&quot; value to one more than 1, and add 1 to the guess count elif guess &lt; ranno: low = guess + 1 count += 1 # Condition: If it's not either of the above, i.e. the computer has guessed the number, return the guess count for this function else: return count # Setting up a global array &quot;upper_bounds&quot; of the range of range of random numbers as a log array from 10^1 to 10^50 upper_bounds = np.logspace(1, 50, 50, 10) def guess_avg(no_of_guesses): # Empty array for all averages list_of_averages = [] # For every value in the &quot;upper_bounds&quot; array, for bound in upper_bounds: # choose random number, &quot;ranx&quot;, between 0 and the bound in the array ranx = random.randint(0, bound) # make an empty Numpy array, &quot;guess_array&quot;, to insert the guesses into guess_array = np.array([]) # For every value in whatever the no_of_guesses is when function called, for i in np.arange(no_of_guesses): # assign value, &quot;guess&quot;, as calling function with value &quot;ranx&quot; guess = computer_guess(ranx) # stuff each resultant guess into the &quot;guess_array&quot; array guess_array = np.append(guess_array, guess) # Print log10 of each value in &quot;upper_bound&quot; print(int(np.log10(bound))) # Finding the mean of each value of the array of all guesses for the order of magnitude average_of_guesses = np.mean(guess_array) # Stuff the averages of guesses into the array the empty array made before list_of_averages.append(average_of_guesses) # Save the average of all averages in the list of averages into a single variable average_of_averages = np.mean(list_of_averages) # Print the list of averages print(f&quot;Your list of averages: {list_of_averages}&quot;) # Print the average of averages print(f&quot;Average of averages: {average_of_averages}&quot;) return list_of_averages # Repeat the &quot;guess_avg&quot; function as long as the program is running while True: # Ask user to input a number for how many guesses they want the computer to make for each order of magnitude, and use that number for calling the function &quot;guess_avg()&quot; resultant_average_numbers = guess_avg( int(input(&quot;Input the number of guesses you want the computer to make: &quot;))) # Plot a graph with log10 of the order of magnitudes on the horizontal and the returned number of average of guesses plt.plot(np.log10(upper_bounds), resultant_average_numbers) # Show plot plt.show() </code></pre> <p>I apologise if this is badly explained, it's my first time using Stackoverflow.</p>
[ { "answer_id": 74536166, "author": "PaulS", "author_id": 11564487, "author_profile": "https://Stackoverflow.com/users/11564487", "pm_score": 1, "selected": false, "text": "(df.groupby('grp')\n .apply(lambda g: g['value'].div(g['value'].max()))\n .droplevel(1)\n .reset_index())\n grp value\n0 0 1.000000\n1 1 1.000000\n2 1 1.052922\n3 2 1.000000\n4 2 5.873499\n5 3 10.009542\n6 3 1.000000\n7 4 1.000000\n8 4 -0.842420\n9 4 0.410153\n" }, { "answer_id": 74538597, "author": "sammywemmy", "author_id": 7175713, "author_profile": "https://Stackoverflow.com/users/7175713", "pm_score": 3, "selected": true, "text": "df.assign(value = df.value/df.groupby('grp').value.transform('max'))\n grp value\n1 0 1.000000\n2 1 -0.290494\n3 1 1.000000\n4 1 0.214848\n6 2 8.242604\n7 2 1.000000\n8 2 1.156246\n0 3 0.655760\n9 3 1.000000\n5 4 1.000000\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20574309/" ]
74,536,245
<p>Here is my situation. Iam using Alteryx ETL tool where in basically we are appending new records to tableau by using option provided like 'Overwrite the file'.</p> <p>What it does is any data incoming is captured to the target and delete the old data--&gt; publish results in Tableau visualisation tool.</p> <p>So whatever data coming in source must overwrite the existing data in Sink table.</p> <p>How can we achieve this in Azure data Flow?</p>
[ { "answer_id": 74536166, "author": "PaulS", "author_id": 11564487, "author_profile": "https://Stackoverflow.com/users/11564487", "pm_score": 1, "selected": false, "text": "(df.groupby('grp')\n .apply(lambda g: g['value'].div(g['value'].max()))\n .droplevel(1)\n .reset_index())\n grp value\n0 0 1.000000\n1 1 1.000000\n2 1 1.052922\n3 2 1.000000\n4 2 5.873499\n5 3 10.009542\n6 3 1.000000\n7 4 1.000000\n8 4 -0.842420\n9 4 0.410153\n" }, { "answer_id": 74538597, "author": "sammywemmy", "author_id": 7175713, "author_profile": "https://Stackoverflow.com/users/7175713", "pm_score": 3, "selected": true, "text": "df.assign(value = df.value/df.groupby('grp').value.transform('max'))\n grp value\n1 0 1.000000\n2 1 -0.290494\n3 1 1.000000\n4 1 0.214848\n6 2 8.242604\n7 2 1.000000\n8 2 1.156246\n0 3 0.655760\n9 3 1.000000\n5 4 1.000000\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20490950/" ]
74,536,263
<p>I'm not able to align my text to the bottom of the divs in my flex content. I'm new to CSS and any help will be appreciated.</p> <p>Thank you for your time and kindness.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>body, html { background-color: #666666; box-sizing: border-box; font-family: "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", "DejaVu Sans", Verdana, "sans-serif"; color: #ffffff; } .flexTest { display: flex; flex-wrap: wrap; align-items: flex-end; border: 1px solid #D2D2D2; background-color: #000000; } .flexTest div { background-color: #EB710F; padding: 5px; margin: 5px; height: 50px; border: 1px solid #D2D2D2; cursor: pointer; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="div1" class="flexTest"&gt; &lt;div&gt; Tatactic - Nicolas 1 &lt;/div&gt; &lt;div&gt; Tatactic - Nicolas 2 &lt;/div&gt; &lt;div&gt; Tatactic - Nicolas 3 &lt;/div&gt; &lt;div&gt; Tatactic - Nicolas 4 &lt;/div&gt; &lt;div&gt; Tatactic - Nicolas 5 &lt;/div&gt; &lt;div&gt; Tatactic - Nicolas 6 &lt;/div&gt; &lt;div&gt; Tatactic - Nicolas 7 &lt;/div&gt; &lt;div&gt; Tatactic - Nicolas 8 &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74536290, "author": "Coopero", "author_id": 2421346, "author_profile": "https://Stackoverflow.com/users/2421346", "pm_score": 2, "selected": false, "text": ".flexTest div {\n background-color: #EB710F;\n padding: 5px;\n margin: 5px;\n height: 50px;\n border: 1px solid #D2D2D2;\n cursor: pointer;\n display: flex;\n flex-direction: column-reverse;\n}\n" }, { "answer_id": 74536316, "author": "isherwood", "author_id": 1264804, "author_profile": "https://Stackoverflow.com/users/1264804", "pm_score": 0, "selected": false, "text": ".flexTest body,\nhtml {\n background-color: #666666;\n box-sizing: border-box;\n font-family: \"Lucida Grande\", \"Lucida Sans Unicode\", \"Lucida Sans\", \"DejaVu Sans\", Verdana, \"sans-serif\";\n color: #ffffff;\n}\n\n.flexTest {\n display: flex;\n flex-wrap: wrap;\n align-items: flex-end;\n border: 1px solid #D2D2D2;\n background-color: #000000;\n}\n\n.flexTest > div {\n background-color: #EB710F;\n padding: 5px;\n margin: 5px;\n height: 50px;\n border: 1px solid #D2D2D2;\n cursor: pointer;\n display: flex;\n flex-direction: column;\n justify-content: end;\n} <div id=\"div1\" class=\"flexTest\">\n <div>\n Tatactic - Nicolas 1\n </div>\n <div>\n Tatactic - Nicolas 2\n </div>\n <div>\n Tatactic - Nicolas 3\n </div>\n <div>\n Tatactic - Nicolas 4\n </div>\n <div>\n Tatactic - Nicolas 5\n </div>\n <div>\n Tatactic - Nicolas 6\n </div>\n <div>\n Tatactic - Nicolas 7\n </div>\n <div>\n Tatactic - Nicolas 8\n </div>\n</div>" }, { "answer_id": 74536325, "author": "marcos.efrem", "author_id": 5417679, "author_profile": "https://Stackoverflow.com/users/5417679", "pm_score": 2, "selected": true, "text": ".flexTest div { \n display: flex;\n align-items: flex-end;\n}\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1247977/" ]
74,536,276
<p>I have something like:</p> <pre><code> const Tab = createBottomTabNavigator&lt;DefaultTabbedParamList&gt;(); const DefaultTabbedNavigation = () =&gt; { return ( &lt;&gt; &lt;Tab.Navigator initialRouteName='Home' screenOptions={{ unmountOnBlur: true, }}&gt; &lt;Tab.Screen name=&quot;Home&quot; component={HomeScreen} options={{ ...defaultOptions, tabBarIcon: ({ color, size, focused }) =&gt; ( &lt;Icon as={Ionicons} name={`home${focused ? `` : `-outline`}`} size={size} color={color} /&gt; ) }} /&gt; ... &lt;/Tab.Navigator&gt; &lt;/&gt; ); } </code></pre> <p>When a user clicks to a detail view from <code>Home</code> (or any other tab), I want to load a detail view with the currently selected tab remaining.</p> <p>What's the correct approach to handle this?</p> <p>One idea I had was to have a <code>StackNavigator</code> in <code>HomeScreen</code> that includes a <code>Detail</code> screen. But it seems repetitive to do for every screen, no?</p>
[ { "answer_id": 74626983, "author": "PaleRedDot", "author_id": 10607003, "author_profile": "https://Stackoverflow.com/users/10607003", "pm_score": 1, "selected": false, "text": "return (\n <NavigationContainer>\n <Stack.Navigator screenOptions={{ headerShown: false }}>\n <Stack.Screen name={\"Tabs\"} component={Tabs} />\n <Stack.Screen name={\"Detail\"} component={DetailScreen} />\n </Stack.Navigator>\n </NavigationContainer>\n );\n" }, { "answer_id": 74680584, "author": "elliot", "author_id": 14665527, "author_profile": "https://Stackoverflow.com/users/14665527", "pm_score": 0, "selected": false, "text": "StackNavigator const HomeStackNavigator = () => {\n return (\n <Stack.Navigator>\n <Stack.Screen name=\"Home\" component={HomeScreen} />\n <Stack.Screen name=\"Detail\" component={DetailScreen} />\n </Stack.Navigator>\n );\n};\n\nconst OtherStackNavigator = () => {\n return (\n <Stack.Navigator>\n <Stack.Screen name=\"Other\" component={OtherScreen} />\n <Stack.Screen name=\"Detail\" component={DetailScreen} />\n </Stack.Navigator>\n );\n};\n\nconst DefaultTabbedNavigation = () => {\n return (\n <Tab.Navigator>\n <Tab.Screen name=\"Home\" component={HomeStackNavigator} />\n <Tab.Screen name=\"Other\" component={OtherStackNavigator} />\n </Tab.Navigator>\n )\n}\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/239879/" ]
74,536,305
<p>I've faced the problem that JMeter doesn't clear the cache and extract variables in the next loop iteration, ruining the following request in the next loop.<br /> <a href="https://i.stack.imgur.com/Avo8s.png" rel="nofollow noreferrer">problem itself</a></p> <ol> <li><p>I tried check-box 'Clear cache each iteration.</p> </li> <li><p>Then I turned off the cache manager at all, but at the beginning of the next loop, I noticed that variables were left from the previous one.<br /> <a href="https://i.stack.imgur.com/tDDkt.png" rel="nofollow noreferrer">1-2</a></p> </li> <li><p>I even ad the pre-processor at the beginning of the scenario to remove all variables and clear the cache. Didn't help. <a href="https://i.stack.imgur.com/RrrQb.png" rel="nofollow noreferrer">3</a></p> </li> </ol>
[ { "answer_id": 74626983, "author": "PaleRedDot", "author_id": 10607003, "author_profile": "https://Stackoverflow.com/users/10607003", "pm_score": 1, "selected": false, "text": "return (\n <NavigationContainer>\n <Stack.Navigator screenOptions={{ headerShown: false }}>\n <Stack.Screen name={\"Tabs\"} component={Tabs} />\n <Stack.Screen name={\"Detail\"} component={DetailScreen} />\n </Stack.Navigator>\n </NavigationContainer>\n );\n" }, { "answer_id": 74680584, "author": "elliot", "author_id": 14665527, "author_profile": "https://Stackoverflow.com/users/14665527", "pm_score": 0, "selected": false, "text": "StackNavigator const HomeStackNavigator = () => {\n return (\n <Stack.Navigator>\n <Stack.Screen name=\"Home\" component={HomeScreen} />\n <Stack.Screen name=\"Detail\" component={DetailScreen} />\n </Stack.Navigator>\n );\n};\n\nconst OtherStackNavigator = () => {\n return (\n <Stack.Navigator>\n <Stack.Screen name=\"Other\" component={OtherScreen} />\n <Stack.Screen name=\"Detail\" component={DetailScreen} />\n </Stack.Navigator>\n );\n};\n\nconst DefaultTabbedNavigation = () => {\n return (\n <Tab.Navigator>\n <Tab.Screen name=\"Home\" component={HomeStackNavigator} />\n <Tab.Screen name=\"Other\" component={OtherStackNavigator} />\n </Tab.Navigator>\n )\n}\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17044125/" ]
74,536,310
<p>I'm trying to replicate a feature I like in twitter.</p> <p><a href="https://i.stack.imgur.com/GFsX0.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GFsX0.jpg" alt="example 1" /></a></p> <p><a href="https://i.stack.imgur.com/IzpDB.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IzpDB.jpg" alt="example 2" /></a></p> <p><a href="https://i.stack.imgur.com/LyV9C.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LyV9C.jpg" alt="example 3" /></a></p> <p>As you can see from the images above Twitter images are always the exact same width but the height are in respect to the image. I have been able to semi replicate this idea using BoxFit.contain but the Container doesn't fit the image.</p> <p>What I have implemented]</p> <p><a href="https://i.stack.imgur.com/GxdmZ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GxdmZ.jpg" alt="What I have implemented" /></a></p> <pre class="lang-dart prettyprint-override"><code>Container( width: 290.0, // height: 400, constraints: const BoxConstraints( maxHeight: 350, minHeight: 150, ), decoration: BoxDecoration( color: Colors.red, borderRadius: BorderRadius.circular(27.5), image: DecorationImage( image: AssetImage(image[itemIndex]), fit: BoxFit.fitWidth, ), boxShadow: const [ BoxShadow( color: Color(0x80000000), offset: Offset(0, 2.5), blurRadius: 5, ), ], ), ), </code></pre> <p>I tried a FittedBox with no luck. I attempted a FractionallySizedBox but kept on getting an error! If anybody could lead me in the right direction I would appreciate it!</p>
[ { "answer_id": 74536420, "author": "Yeasin Sheikh", "author_id": 10157127, "author_profile": "https://Stackoverflow.com/users/10157127", "pm_score": 1, "selected": false, "text": "fit: BoxFit.cover, Container(\n width: 290.0,\n // height: 400,\n constraints: const BoxConstraints(\n maxHeight: 350,\n minHeight: 150,\n ),\n decoration: BoxDecoration(\n color: Colors.red,\n borderRadius: BorderRadius.circular(27.5),\n image: DecorationImage(\n image: AssetImage(image[itemIndex]),\n fit: BoxFit.cover, //\n ),\n boxShadow: const [\n BoxShadow(\n color: Color(0x80000000),\n offset: Offset(0, 2.5),\n blurRadius: 5,\n ),\n ],\n ),\n),\n" }, { "answer_id": 74537074, "author": "Paulo", "author_id": 15649348, "author_profile": "https://Stackoverflow.com/users/15649348", "pm_score": 1, "selected": false, "text": "child Container(\n width: 290,\n constraints: const BoxConstraints(\n maxHeight: 350,\n minHeight: 150,\n ),\n child: Card(\n semanticContainer: true,\n clipBehavior: Clip.antiAliasWithSaveLayer,\n shape:\n RoundedRectangleBorder(borderRadius: BorderRadius.circular(12.0)),\n margin: const EdgeInsets.all(12),\n child: Image.asset(\n image[itemIndex],\n fit: BoxFit.cover,\n ),\n ),\n);\n" }, { "answer_id": 74537794, "author": "Isis Curiel", "author_id": 5771844, "author_profile": "https://Stackoverflow.com/users/5771844", "pm_score": 0, "selected": false, "text": "ClipRRect(\n borderRadius:\n BorderRadius.circular(27.5),\n child: Container(\n //width: 290.0,\n constraints: const BoxConstraints(\n maxHeight: 350,\n minHeight: 150,\n ),\n decoration: const BoxDecoration(\n color: Colors.red,\n\n /*image: DecorationImage(\n \n image: AssetImage(image[itemIndex]),\n \n fit: BoxFit.cover,\n ),*/\n boxShadow: [\n BoxShadow(\n color: Color(0x80000000),\n offset: Offset(0, 2.5),\n blurRadius: 5,\n ),\n ],\n ),\n child: Image.asset(\n image[itemIndex],\n width: 290,\n fit: BoxFit.cover,\n ),\n ),\n ),\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5771844/" ]
74,536,312
<p>I have created a pause screen Area2D for my game, in any case the player goes AFK. I wrote a code so whenever the key P is pressed it appears and everything pauses, and if it is clicked it disappears and everything goes back to normal. I wrote a code, but it didn't work</p> <p>I tried this:</p> <pre><code> public override void _PhysicsProcess(float delta) { // Makes the pause screen visible when P is pressed if (Input.IsActionPressed(&quot;Pause&quot;)) { Visible = true; } } public override void _Ready() { } public void _on_PauseScreen_mouse_entered() { if (Input.IsActionPressed(&quot;click&quot;)) { Visible = false; } } </code></pre> <p>But it only works when clicked on the edges, I know that's how collisions are but how do I make it so when anywhere the sprite is pressed, it disappears?</p>
[ { "answer_id": 74536420, "author": "Yeasin Sheikh", "author_id": 10157127, "author_profile": "https://Stackoverflow.com/users/10157127", "pm_score": 1, "selected": false, "text": "fit: BoxFit.cover, Container(\n width: 290.0,\n // height: 400,\n constraints: const BoxConstraints(\n maxHeight: 350,\n minHeight: 150,\n ),\n decoration: BoxDecoration(\n color: Colors.red,\n borderRadius: BorderRadius.circular(27.5),\n image: DecorationImage(\n image: AssetImage(image[itemIndex]),\n fit: BoxFit.cover, //\n ),\n boxShadow: const [\n BoxShadow(\n color: Color(0x80000000),\n offset: Offset(0, 2.5),\n blurRadius: 5,\n ),\n ],\n ),\n),\n" }, { "answer_id": 74537074, "author": "Paulo", "author_id": 15649348, "author_profile": "https://Stackoverflow.com/users/15649348", "pm_score": 1, "selected": false, "text": "child Container(\n width: 290,\n constraints: const BoxConstraints(\n maxHeight: 350,\n minHeight: 150,\n ),\n child: Card(\n semanticContainer: true,\n clipBehavior: Clip.antiAliasWithSaveLayer,\n shape:\n RoundedRectangleBorder(borderRadius: BorderRadius.circular(12.0)),\n margin: const EdgeInsets.all(12),\n child: Image.asset(\n image[itemIndex],\n fit: BoxFit.cover,\n ),\n ),\n);\n" }, { "answer_id": 74537794, "author": "Isis Curiel", "author_id": 5771844, "author_profile": "https://Stackoverflow.com/users/5771844", "pm_score": 0, "selected": false, "text": "ClipRRect(\n borderRadius:\n BorderRadius.circular(27.5),\n child: Container(\n //width: 290.0,\n constraints: const BoxConstraints(\n maxHeight: 350,\n minHeight: 150,\n ),\n decoration: const BoxDecoration(\n color: Colors.red,\n\n /*image: DecorationImage(\n \n image: AssetImage(image[itemIndex]),\n \n fit: BoxFit.cover,\n ),*/\n boxShadow: [\n BoxShadow(\n color: Color(0x80000000),\n offset: Offset(0, 2.5),\n blurRadius: 5,\n ),\n ],\n ),\n child: Image.asset(\n image[itemIndex],\n width: 290,\n fit: BoxFit.cover,\n ),\n ),\n ),\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20485985/" ]
74,536,346
<p>The below code looks to be error free to me at least. But I'm not getting the output I want, but if i dont use the function and add the two of them directly with the same syntax, I'm getting the correct answer. pls help</p> <pre class="lang-py prettyprint-override"><code> a = [[1,1],[2,2]] #first matrix b = [[4,4],[3,3]] #second matrix #creating a function to add to two matrices and return the sum def sum(m,n): o = [[0,0],[0,0]] for i in range(2): for j in range(2): o[i][j] = m[i][j] + n[i][j] return o ans = sum(a,b) print(ans) </code></pre> <p>this is giving the following answer output:</p> <p>[[5, 0], [0, 0]]</p> <p>where as the output should be : [[5, 5], [5, 5]]</p> <pre><code></code></pre>
[ { "answer_id": 74536419, "author": "Prime Price", "author_id": 19685980, "author_profile": "https://Stackoverflow.com/users/19685980", "pm_score": 0, "selected": false, "text": "import numpy\nnumpy.add(list1, list2)\n" }, { "answer_id": 74536485, "author": "SoulSeeke", "author_id": 20573886, "author_profile": "https://Stackoverflow.com/users/20573886", "pm_score": 1, "selected": false, "text": "def sum(m,n): \no = [[0,0],[0,0]] \nfor i in range(2): \n for j in range(2): \n o[i][j] = m[i][j] + n[i][j] \nreturn o\n" }, { "answer_id": 74536633, "author": "Riccardo Bucco", "author_id": 5296106, "author_profile": "https://Stackoverflow.com/users/5296106", "pm_score": 0, "selected": false, "text": "def sum_matrices(a, b):\n return [[a[i][j] + b[i][j] for j in range(len(a[i]))] for i in range(len(a))]\n import numpy as np\n\ndef sum_matrices(a, b):\n return np.add(a, b).tolist()\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20574441/" ]
74,536,410
<pre><code>function handler(){ const results = [].map((item) =&gt; { a(); b(); }) Promise.allSettled(results); } function a() { // returns promise } function b() { // returns promise } } </code></pre> <p>How to modify the above code so that I can pass array of promises to <code>promise.allSettled(results)</code></p> <p>I tried this but not sure if this is correct way?</p> <pre><code>function handler() { const results = [].map((item) =&gt; { const out1 = a(); const out2 = b(); return [...out1, ...out2]; }) Promise.allSettled(results); } </code></pre>
[ { "answer_id": 74536531, "author": "codinn.dev", "author_id": 15755662, "author_profile": "https://Stackoverflow.com/users/15755662", "pm_score": 0, "selected": false, "text": "function handler() {\n const results = [].map((item) => {\n const out1 = a();\n const out2 = b();\n return [...out1, ...out2];\n })\n Promise.allSettled(results.flat());\n}\n" }, { "answer_id": 74536543, "author": "epascarello", "author_id": 14104, "author_profile": "https://Stackoverflow.com/users/14104", "pm_score": 2, "selected": true, "text": "const a = [1,2,3,4,5,6];\n\nconst b = a.flatMap(v => [Promise.resolve(a), Promise.reject(a)])\n\nPromise.allSettled(b).then(x => console.log(x));" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1800583/" ]
74,536,412
<p>I am working with a compound database in sdf format. I would like to simple replace the head title of all molecules (with the pattern $$$$ before the title) by the line followed by &gt; &lt;GENERIC_NAME&gt;.</p> <p>The file looks like this:</p> <pre><code>$$$$ 91443 -OEChem-10051719083D 55 57 0 1 0 0 0 0 0999 V2000 -5.0661 -1.1129 2.4181 O 0 0 0 0 0 0 0 0 0 0 0 0 4.2383 1.9583 1.7563 O 0 0 0 0 0 0 0 0 0 0 0 0 7.3280 0.6119 -1.9919 O 0 0 0 0 0 0 0 0 0 0 0 0 5.1868 0.6987 -2.7387 O 0 0 0 0 0 0 0 0 0 0 0 0 </code></pre> <blockquote> <p>&lt;GENERIC_NAME&gt; Tetrahydrofolic acid</p> </blockquote> <p>The script should replace 91443 by Tetrahydrofolic acid and do the same task in all lines with the head $$$$ and replace by the &gt; &lt;GENERIC_NAME&gt; (there are about 9000 molecules, each one with different names and number codes).</p> <p>This SDF file can be downloaded in the next web page (after registration, sorry): <a href="https://go.drugbank.com/releases/latest#structures" rel="nofollow noreferrer">https://go.drugbank.com/releases/latest#structures</a></p> <p>Thanks in advance for the replies, but those only change the first molecule, not the rest. Best regards and thank you very much for your concern and help!!!</p> <p>I tried in a simple way GREP both patterns and replace by sed with no result:</p> <pre><code>a=$(grep -A 1 --no-group-separator &quot;$$$$&quot; test.sdf | grep -v &quot;$$$$&quot;) b=$(grep -A 1 --no-group-separator &quot;GENERIC_NAME&quot; test.sdf | grep -v &quot;GENERIC_NAME&quot;) while $a $b, do sed -i &quot;s/$a/$b/&quot; test.sdf done </code></pre>
[ { "answer_id": 74536531, "author": "codinn.dev", "author_id": 15755662, "author_profile": "https://Stackoverflow.com/users/15755662", "pm_score": 0, "selected": false, "text": "function handler() {\n const results = [].map((item) => {\n const out1 = a();\n const out2 = b();\n return [...out1, ...out2];\n })\n Promise.allSettled(results.flat());\n}\n" }, { "answer_id": 74536543, "author": "epascarello", "author_id": 14104, "author_profile": "https://Stackoverflow.com/users/14104", "pm_score": 2, "selected": true, "text": "const a = [1,2,3,4,5,6];\n\nconst b = a.flatMap(v => [Promise.resolve(a), Promise.reject(a)])\n\nPromise.allSettled(b).then(x => console.log(x));" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20574419/" ]
74,536,442
<p><strong>How do I create a custom type converter for a boolean parameter in a GET request?</strong></p> <p>For example, I want the allowed values in the GET request to be &quot;oui&quot; and &quot;non&quot; instead of &quot;true&quot; and &quot;false&quot;. I followed the <a href="https://docs.spring.io/spring-framework/docs/5.0.0.M4/spring-framework-reference/html/mvc.html#mvc-ann-typeconversion" rel="nofollow noreferrer">Spring documentation</a> on how to do this, and tried the following:</p> <pre><code>@RestController public class ExampleController { @InitBinder protected void initBinder(WebDataBinder binder) { binder.registerCustomEditor(Boolean.class, new CustomBooleanEditor(&quot;oui&quot;, &quot;non&quot;, true)); } @GetMapping(&quot;/e&quot;) ResponseEntity&lt;String&gt; showRequestParam(@RequestParam boolean flag) { return new ResponseEntity&lt;&gt;(String.valueOf(flag), HttpStatus.OK); } } </code></pre> <p>I also tried this:</p> <pre><code>@RestController public class DemoController { @InitBinder protected void initBinder(WebDataBinder binder) { binder.addCustomFormatter(new Formatter&lt;Boolean&gt;() { @Override public Boolean parse(String text, Locale locale) throws ParseException { if (&quot;oui&quot;.equalsIgnoreCase(text)) return true; if (&quot;non&quot;.equalsIgnoreCase(text)) return false; throw new ParseException(&quot;Invalid boolean parameter value '&quot; + text + &quot;'; please specify oui or non&quot;, 0); } @Override public String print(Boolean object, Locale locale) { return String.valueOf(object); } }, Boolean.class); } @GetMapping(&quot;/r&quot;) ResponseEntity&lt;String&gt; showRequestParam(@RequestParam(value = &quot;param&quot;) boolean param) { return new ResponseEntity&lt;&gt;(String.valueOf(param), HttpStatus.OK); } } </code></pre> <p>Neither of these worked. When supplying the value &quot;oui&quot;, I got an HTTP 400 response with the following message:</p> <blockquote> <p>Failed to convert value of type 'java.lang.String' to required type 'boolean'; nested exception is java.lang.IllegalArgumentException: Invalid boolean value [oui]&quot;</p> </blockquote> <p><strong>Update:</strong></p> <p>I've also now tried using a Converter:</p> <pre class="lang-java prettyprint-override"><code>@Component public class BooleanConverter implements Converter&lt;String, Boolean&gt; { @Override public Boolean convert(String text) { if (&quot;oui&quot;.equalsIgnoreCase(text)) return true; if (&quot;non&quot;.equalsIgnoreCase(text)) return false; throw new IllegalArgumentException(&quot;Invalid boolean parameter value '&quot; + text + &quot;'; please specify oui or non&quot;); } } </code></pre> <p>This &quot;kind of&quot; works, in that it now accepts &quot;oui&quot; and &quot;non&quot;, but it does so <em>in addition</em> to &quot;true&quot; and &quot;false&quot;. How can I get it to accept &quot;oui&quot; and &quot;non&quot; <em>instead of</em> &quot;true&quot; and &quot;false&quot;?</p>
[ { "answer_id": 74537088, "author": "sanurah", "author_id": 4079056, "author_profile": "https://Stackoverflow.com/users/4079056", "pm_score": 1, "selected": false, "text": "enum BooleanInput {\n oui(true),\n non(false);\n\n private boolean value;\n\n BooleanInput(boolean value) {\n this.value = value;\n }\n\n Boolean value() {\n return this.value;\n }\n}\n @GetMapping(\"/e\")\n ResponseEntity<String> showRequestParam(@RequestParam BooleanInput flag) {\n return new ResponseEntity<>(flag.value(), HttpStatus.OK);\n }\n" }, { "answer_id": 74537090, "author": "Noplopy", "author_id": 2347461, "author_profile": "https://Stackoverflow.com/users/2347461", "pm_score": 3, "selected": true, "text": "@InitBinder\nprotected void initBinder(WebDataBinder binder) {\n binder.registerCustomEditor(Boolean.class, new CustomBooleanEditor(\"oui\", \"non\", true));\n}\n\n@GetMapping(\"/e\")\nResponseEntity<String> showRequestParam(@RequestParam(value=\"flag\") Boolean flag) {\n return new ResponseEntity<>(String.valueOf(flag), HttpStatus.OK);\n}\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13963086/" ]
74,536,484
<p>So i have this method to read from a CSV File and it works.</p> <pre><code>//Alte Bestand private void PageLoad_Alt(object sender, RoutedEventArgs e) { try { //Index von selectedItem string filepath = directory + &quot;\\&quot; + &quot;ParkingTool_BESTAND.csv&quot;; //CSVHelper Config var config = new CsvConfiguration(CultureInfo.CurrentCulture) { Delimiter = &quot;;&quot; }; using (var csv = new CsvReader(new StreamReader(filepath), config)) { csv.Read(); csv.ReadHeader(); while (csv.Read()) { string barcodeField = csv.GetField&lt;string&gt;(&quot;Barcode&quot;); string boxField = csv.GetField&lt;string&gt;(&quot;BoxNr&quot;); string datumField = csv.GetField&lt;string&gt;(&quot;Datum&quot;); alte_parking_collection.Add(new ParkingClass() { parking_barcode = barcodeField, parking_box = boxField, parking_datum = datumField }); ; } } code_box.Focus(); } catch (Exception ex) { MessageBox.Show(&quot;Bitte Datei überprüfen! &quot; + ex.Message, &quot;Error&quot;, MessageBoxButton.OK, MessageBoxImage.Warning); code_box.Focus(); } } </code></pre> <p>Then i call it with <code>Loaded += PageLoad_Alt;</code> when the page starts.</p> <p>But i want something that calls the method again when a another collection is edited. Any ideas?</p> <p><code>parking_collection.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(PageLoad_Alt());</code></p> <p>This is not working.</p>
[ { "answer_id": 74537088, "author": "sanurah", "author_id": 4079056, "author_profile": "https://Stackoverflow.com/users/4079056", "pm_score": 1, "selected": false, "text": "enum BooleanInput {\n oui(true),\n non(false);\n\n private boolean value;\n\n BooleanInput(boolean value) {\n this.value = value;\n }\n\n Boolean value() {\n return this.value;\n }\n}\n @GetMapping(\"/e\")\n ResponseEntity<String> showRequestParam(@RequestParam BooleanInput flag) {\n return new ResponseEntity<>(flag.value(), HttpStatus.OK);\n }\n" }, { "answer_id": 74537090, "author": "Noplopy", "author_id": 2347461, "author_profile": "https://Stackoverflow.com/users/2347461", "pm_score": 3, "selected": true, "text": "@InitBinder\nprotected void initBinder(WebDataBinder binder) {\n binder.registerCustomEditor(Boolean.class, new CustomBooleanEditor(\"oui\", \"non\", true));\n}\n\n@GetMapping(\"/e\")\nResponseEntity<String> showRequestParam(@RequestParam(value=\"flag\") Boolean flag) {\n return new ResponseEntity<>(String.valueOf(flag), HttpStatus.OK);\n}\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11150675/" ]
74,536,496
<p>This is the prototype of <code>Row</code>:</p> <pre class="lang-kotlin prettyprint-override"><code>@Composable public inline fun Row( modifier: Modifier = Modifier, horizontalArrangement: Arrangement.Horizontal = Arrangement.Start, verticalAlignment: Alignment.Vertical = Alignment.Top, content: @Composable() (RowScope.() -&gt; Unit) ): Unit </code></pre> <p>And this is <code>BottomAppBar</code>:</p> <pre class="lang-kotlin prettyprint-override"><code>@Composable @ComposableInferredTarget public fun BottomAppBar( modifier: Modifier, containerColor: Color, contentColor: Color, tonalElevation: Dp, contentPadding: PaddingValues, windowInsets: WindowInsets, content: @Composable() (RowScope.() -&gt; Unit) ): Unit </code></pre> <p>The content of <code>BottomAppBar</code> is in a <code>RowScope</code>. And a <code>Row</code> knows about the <code>horizontalArrangement</code> and I would like to set it to <code>Arrangement.SpaceEvenly</code>. But <code>BottomAppBar</code> has no argument to do so. How can I set the arrangement in the bottom app bar to &quot;space evenly&quot;?</p>
[ { "answer_id": 74536522, "author": "Gabriele Mariotti", "author_id": 2016562, "author_profile": "https://Stackoverflow.com/users/2016562", "pm_score": 3, "selected": true, "text": "horizontalArrangement content BottomAppBar RowScope Row @Composable\nfun BottomAppBar(\n //...\n content: @Composable RowScope.() -> Unit\n) {\n Surface(\n //...\n modifier = modifier\n ) {\n Row(\n Modifier\n .fillMaxWidth()\n .windowInsetsPadding(windowInsets)\n .height(BottomAppBarTokens.ContainerHeight)\n .padding(contentPadding),\n horizontalArrangement = Arrangement.Start,\n verticalAlignment = Alignment.CenterVertically,\n content = content\n )\n }\n" }, { "answer_id": 74536822, "author": "ceving", "author_id": 402322, "author_profile": "https://Stackoverflow.com/users/402322", "pm_score": 0, "selected": false, "text": "@Composable\nfun MyBottomAppBar(\n modifier: Modifier = Modifier,\n containerColor: Color = BottomAppBarDefaults.containerColor,\n contentColor: Color = contentColorFor(containerColor),\n tonalElevation: Dp = BottomAppBarDefaults.ContainerElevation,\n contentPadding: PaddingValues = BottomAppBarDefaults.ContentPadding,\n windowInsets: WindowInsets = BottomAppBarDefaults.windowInsets,\n content: @Composable RowScope.() -> Unit\n) {\n Surface(\n color = containerColor,\n contentColor = contentColor,\n tonalElevation = tonalElevation,\n //shape = ShapeKeyTokens.CornerNone,\n modifier = modifier\n ) {\n Row(\n Modifier\n .fillMaxWidth()\n .windowInsetsPadding(windowInsets)\n .height(80.0.dp)\n .padding(contentPadding),\n horizontalArrangement = Arrangement.SpaceEvenly,\n verticalAlignment = Alignment.CenterVertically,\n content = content\n )\n }\n}\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/402322/" ]
74,536,503
<p>I am receiving a response from the API, but the data doesn't display on the card. I don't think it has much to do with the data I think it has much to do with the card appearing itself first. Here is how the search file is set up, pretty straight forward. As you see I did set up a container to hold the card as I map through it.</p> <pre><code>import '../styles/searchPage.css' import SearchCard from '../components/SearchCard'; const API_URL = 'https://api.openbrewerydb.org/breweries?by_city'; const brewery1 = { &quot;id&quot;: &quot;10-barrel-brewing-co-san-diego&quot;, &quot;name&quot;: &quot;Nirmanz Food Boutique&quot;, &quot;brewery_type&quot;: &quot;large&quot;, &quot;street&quot;: &quot;1501 E St&quot;, &quot;phone&quot;: &quot;7739888990 &quot;, &quot;address&quot;: null, &quot;city&quot;: &quot;San Diego&quot;, &quot;state&quot;: &quot;California&quot;, &quot;postal_code&quot;: &quot;92101-6618&quot;, &quot;country&quot;: &quot;United States&quot;, } function SearchPage() { const [cards, setCards] = useState([]); const [searchTerm, setSearchTerm] = useState(''); const searchRestaurants = async (name) =&gt; { const req = await fetch(`${API_URL}&amp;s=${name}`); const data = await req.json() console.log(data[0].name) setCards({data: data.name}) } useEffect(() =&gt; { searchRestaurants('') }, []) return ( &lt;div className='search'&gt; &lt;h1&gt;Enter a City or Town name&lt;/h1&gt; &lt;div className='search-container'&gt; &lt;input type=&quot;text&quot; name=&quot;search&quot; value={searchTerm} onChange={(e) =&gt; setSearchTerm(e.target.value)} onKeyPress={(e) =&gt; { if (e.key === 'Enter'){ setCards(searchTerm); } }} placeholder=&quot;Search...&quot; class=&quot;search-input&quot; /&gt; &lt;button className='next' onClick={()=&gt; searchRestaurants(searchTerm)} &gt;Go&lt;/button&gt; &lt;/div&gt; { cards?.length &gt; 0 ? ( &lt;div className=&quot;container&quot;&gt; {cards.map((card) =&gt;( &lt;SearchCard brewery1={brewery1}/&gt; ))} &lt;/div&gt; ) : ( &lt;div className=&quot;empty&quot;&gt; &lt;h2&gt;Found 0 Breweries&lt;/h2&gt; &lt;/div&gt; ) } &lt;/div&gt; ); } export default SearchPage </code></pre> <p>Here is the my JSX for my search card labeling out what I want to display inside that card.</p> <pre><code>import '../styles/searchPage.css' const SearchCard = ({brewery1}) =&gt; { return ( &lt;div className=&quot;card&quot;&gt; {/* &lt;img src={brewery1.Poster !== 'N/A' ? brewery1.Poster : 'https://via.placeholder.com/400'} alt={brewery1.name /&gt; */} &lt;div&gt; &lt;span&gt;{brewery1.id}&lt;/span&gt; &lt;h3&gt;{brewery1.brewery_type}&lt;/h3&gt; &lt;h2&gt;{brewery1.street}&lt;/h2&gt; &lt;h2&gt;{brewery1.adress}&lt;/h2&gt; &lt;h2&gt;{brewery1.phone}&lt;/h2&gt; &lt;h2&gt;{brewery1.city}&lt;/h2&gt; &lt;h2&gt;{brewery1.state}&lt;/h2&gt; &lt;h2&gt;{brewery1.postal_code}&lt;/h2&gt; &lt;h2&gt;{brewery1.country}&lt;/h2&gt; &lt;/div&gt; &lt;/div&gt; ) } export default SearchCard; </code></pre>
[ { "answer_id": 74536522, "author": "Gabriele Mariotti", "author_id": 2016562, "author_profile": "https://Stackoverflow.com/users/2016562", "pm_score": 3, "selected": true, "text": "horizontalArrangement content BottomAppBar RowScope Row @Composable\nfun BottomAppBar(\n //...\n content: @Composable RowScope.() -> Unit\n) {\n Surface(\n //...\n modifier = modifier\n ) {\n Row(\n Modifier\n .fillMaxWidth()\n .windowInsetsPadding(windowInsets)\n .height(BottomAppBarTokens.ContainerHeight)\n .padding(contentPadding),\n horizontalArrangement = Arrangement.Start,\n verticalAlignment = Alignment.CenterVertically,\n content = content\n )\n }\n" }, { "answer_id": 74536822, "author": "ceving", "author_id": 402322, "author_profile": "https://Stackoverflow.com/users/402322", "pm_score": 0, "selected": false, "text": "@Composable\nfun MyBottomAppBar(\n modifier: Modifier = Modifier,\n containerColor: Color = BottomAppBarDefaults.containerColor,\n contentColor: Color = contentColorFor(containerColor),\n tonalElevation: Dp = BottomAppBarDefaults.ContainerElevation,\n contentPadding: PaddingValues = BottomAppBarDefaults.ContentPadding,\n windowInsets: WindowInsets = BottomAppBarDefaults.windowInsets,\n content: @Composable RowScope.() -> Unit\n) {\n Surface(\n color = containerColor,\n contentColor = contentColor,\n tonalElevation = tonalElevation,\n //shape = ShapeKeyTokens.CornerNone,\n modifier = modifier\n ) {\n Row(\n Modifier\n .fillMaxWidth()\n .windowInsetsPadding(windowInsets)\n .height(80.0.dp)\n .padding(contentPadding),\n horizontalArrangement = Arrangement.SpaceEvenly,\n verticalAlignment = Alignment.CenterVertically,\n content = content\n )\n }\n}\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18137450/" ]
74,536,514
<p>In prometheus we have the option to add a label to every metric of a job with something like this,</p> <pre class="lang-yaml prettyprint-override"><code>- job_name: 'your_job' honor_labels: true static_configs: - targets: - '127.0.0.1' labels: cluster: 'stage' </code></pre> <p>I want to add labels to metrics but using servicemonitors. I am using blackbox prometheus operator to scan some websites. This is how my service monitor looks.</p> <pre class="lang-yaml prettyprint-override"><code>apiVersion: monitoring.coreos.com/v1 kind: ServiceMonitor metadata: labels: app.kubernetes.io/instance: prometheus-blackbox-exporter app.kubernetes.io/name: prometheus-blackbox-exporter app.kubernetes.io/version: 0.20.0 instance: primary name: prometheus-blackbox-exporter-example.com namespace: monitoring spec: endpoints: - interval: 30s metricRelabelings: - action: replace replacement: https://example.com sourceLabels: - instance targetLabel: instance - action: replace replacement: example.com sourceLabels: - target targetLabel: target params: module: - http_2xx target: - https://example.com path: /probe port: http scheme: http scrapeTimeout: 30s jobLabel: prometheus-blackbox-exporter namespaceSelector: matchNames: - monitoring selector: matchLabels: app.kubernetes.io/instance: prometheus-blackbox-exporter app.kubernetes.io/name: prometheus-blackbox-exporter </code></pre> <p>I want to add a label to the metrics coming from this job. The label is</p> <pre class="lang-bash prettyprint-override"><code>project: monitoring </code></pre> <p>How can I do it using servicemonitors?</p>
[ { "answer_id": 74536522, "author": "Gabriele Mariotti", "author_id": 2016562, "author_profile": "https://Stackoverflow.com/users/2016562", "pm_score": 3, "selected": true, "text": "horizontalArrangement content BottomAppBar RowScope Row @Composable\nfun BottomAppBar(\n //...\n content: @Composable RowScope.() -> Unit\n) {\n Surface(\n //...\n modifier = modifier\n ) {\n Row(\n Modifier\n .fillMaxWidth()\n .windowInsetsPadding(windowInsets)\n .height(BottomAppBarTokens.ContainerHeight)\n .padding(contentPadding),\n horizontalArrangement = Arrangement.Start,\n verticalAlignment = Alignment.CenterVertically,\n content = content\n )\n }\n" }, { "answer_id": 74536822, "author": "ceving", "author_id": 402322, "author_profile": "https://Stackoverflow.com/users/402322", "pm_score": 0, "selected": false, "text": "@Composable\nfun MyBottomAppBar(\n modifier: Modifier = Modifier,\n containerColor: Color = BottomAppBarDefaults.containerColor,\n contentColor: Color = contentColorFor(containerColor),\n tonalElevation: Dp = BottomAppBarDefaults.ContainerElevation,\n contentPadding: PaddingValues = BottomAppBarDefaults.ContentPadding,\n windowInsets: WindowInsets = BottomAppBarDefaults.windowInsets,\n content: @Composable RowScope.() -> Unit\n) {\n Surface(\n color = containerColor,\n contentColor = contentColor,\n tonalElevation = tonalElevation,\n //shape = ShapeKeyTokens.CornerNone,\n modifier = modifier\n ) {\n Row(\n Modifier\n .fillMaxWidth()\n .windowInsetsPadding(windowInsets)\n .height(80.0.dp)\n .padding(contentPadding),\n horizontalArrangement = Arrangement.SpaceEvenly,\n verticalAlignment = Alignment.CenterVertically,\n content = content\n )\n }\n}\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7461941/" ]
74,536,535
<p>I am building a Flutter app with a ChangeNotifier provider. When the app is started, I make a call to the Firebase api and save the results in a Provider variable:</p> <pre><code>Map&lt;DateTime,List&gt; datesMap; </code></pre> <p>How can I define another variable in the same Provider, based on the first variable? for example:</p> <pre><code>List newList = datesMap[DateTime.now()] </code></pre> <p>If I try to do it I get an error:</p> <blockquote> <p>The instance member 'params' can't be accessed in an initializer</p> </blockquote> <p>And if I place the second variable in a Constructor, I will get an error because the first variable <code>datesMap</code> is null until the Firebase api is completed.</p> <p>Example code:</p> <pre><code>class ShiftsProvider with ChangeNotifier { Map&lt;DateTime,List&gt; datesMap; List newList = datesMap[DateTime.now()]; Future&lt;void&gt; getDatesMapfromFirebase () { some code... datesMap = something; notifyListeners(); return; } </code></pre>
[ { "answer_id": 74536522, "author": "Gabriele Mariotti", "author_id": 2016562, "author_profile": "https://Stackoverflow.com/users/2016562", "pm_score": 3, "selected": true, "text": "horizontalArrangement content BottomAppBar RowScope Row @Composable\nfun BottomAppBar(\n //...\n content: @Composable RowScope.() -> Unit\n) {\n Surface(\n //...\n modifier = modifier\n ) {\n Row(\n Modifier\n .fillMaxWidth()\n .windowInsetsPadding(windowInsets)\n .height(BottomAppBarTokens.ContainerHeight)\n .padding(contentPadding),\n horizontalArrangement = Arrangement.Start,\n verticalAlignment = Alignment.CenterVertically,\n content = content\n )\n }\n" }, { "answer_id": 74536822, "author": "ceving", "author_id": 402322, "author_profile": "https://Stackoverflow.com/users/402322", "pm_score": 0, "selected": false, "text": "@Composable\nfun MyBottomAppBar(\n modifier: Modifier = Modifier,\n containerColor: Color = BottomAppBarDefaults.containerColor,\n contentColor: Color = contentColorFor(containerColor),\n tonalElevation: Dp = BottomAppBarDefaults.ContainerElevation,\n contentPadding: PaddingValues = BottomAppBarDefaults.ContentPadding,\n windowInsets: WindowInsets = BottomAppBarDefaults.windowInsets,\n content: @Composable RowScope.() -> Unit\n) {\n Surface(\n color = containerColor,\n contentColor = contentColor,\n tonalElevation = tonalElevation,\n //shape = ShapeKeyTokens.CornerNone,\n modifier = modifier\n ) {\n Row(\n Modifier\n .fillMaxWidth()\n .windowInsetsPadding(windowInsets)\n .height(80.0.dp)\n .padding(contentPadding),\n horizontalArrangement = Arrangement.SpaceEvenly,\n verticalAlignment = Alignment.CenterVertically,\n content = content\n )\n }\n}\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13653363/" ]
74,536,550
<p>When I run <code>DATE_FORMAT('test', '%W %M %Y')</code> I get <code>null</code> returned.</p> <p>I'm running an update to my table <code>extras</code> where the column is a nullable varchar, but when I run eg.</p> <pre><code>update extras set extras.`value` = DATE_FORMAT('test', '%W %M %Y'); </code></pre> <p>I get the following error:</p> <pre><code>[22001][1292] Data truncation: Incorrect datetime value: 'test' </code></pre> <p><code>extras.value</code> is a varchar column with datetime values some of which are not valid dates. I want to update the column to null when the datetime is invalid ie. just a string as in this case 'test'.</p>
[ { "answer_id": 74536522, "author": "Gabriele Mariotti", "author_id": 2016562, "author_profile": "https://Stackoverflow.com/users/2016562", "pm_score": 3, "selected": true, "text": "horizontalArrangement content BottomAppBar RowScope Row @Composable\nfun BottomAppBar(\n //...\n content: @Composable RowScope.() -> Unit\n) {\n Surface(\n //...\n modifier = modifier\n ) {\n Row(\n Modifier\n .fillMaxWidth()\n .windowInsetsPadding(windowInsets)\n .height(BottomAppBarTokens.ContainerHeight)\n .padding(contentPadding),\n horizontalArrangement = Arrangement.Start,\n verticalAlignment = Alignment.CenterVertically,\n content = content\n )\n }\n" }, { "answer_id": 74536822, "author": "ceving", "author_id": 402322, "author_profile": "https://Stackoverflow.com/users/402322", "pm_score": 0, "selected": false, "text": "@Composable\nfun MyBottomAppBar(\n modifier: Modifier = Modifier,\n containerColor: Color = BottomAppBarDefaults.containerColor,\n contentColor: Color = contentColorFor(containerColor),\n tonalElevation: Dp = BottomAppBarDefaults.ContainerElevation,\n contentPadding: PaddingValues = BottomAppBarDefaults.ContentPadding,\n windowInsets: WindowInsets = BottomAppBarDefaults.windowInsets,\n content: @Composable RowScope.() -> Unit\n) {\n Surface(\n color = containerColor,\n contentColor = contentColor,\n tonalElevation = tonalElevation,\n //shape = ShapeKeyTokens.CornerNone,\n modifier = modifier\n ) {\n Row(\n Modifier\n .fillMaxWidth()\n .windowInsetsPadding(windowInsets)\n .height(80.0.dp)\n .padding(contentPadding),\n horizontalArrangement = Arrangement.SpaceEvenly,\n verticalAlignment = Alignment.CenterVertically,\n content = content\n )\n }\n}\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10727630/" ]
74,536,579
<p>I'm stuck in VBA and I couldn't find a good answer in the other questions related to error 91. I want to create an object and store variables and arrays inside that object. I tried an approach like I would do in js:</p> <pre><code>Dim block As Object ... Set block = Nothing block.Name = &quot;Unbekannter Prüfblock&quot; block.Awf = &quot;Unbekannter Anwendungsfall&quot; block.Conditions = Array() block.Checks = Array() </code></pre> <p>I use the &quot;Set block = Nothing&quot; because I will use it multiple times in a loop.</p> <p>But all I get is error 91 - Object variable not set</p> <p>How can I set the object? Do I really have to declare everything in vba? Isn't there a &quot;stop annoying me with declaration notices&quot; toggle? ;-)</p> <h3>Update</h3> <p>Thank you all so much for the detailed answers!</p> <p>As suggested I created a class for &quot;block&quot; and also a class for &quot;condition&quot; and &quot;check&quot;. Block for example:</p> <pre><code>Option Explicit Public name As String Public awf As String Public conditions As Collection Public checks As Collection </code></pre> <p>Then I use it inside my code like this:</p> <pre><code>Dim bl As Block Dim co As Condition Dim ce As Check Set bl = New Block bl.name = ws.Range(&quot;B&quot; &amp; i).value bl.awf = ws.Range(&quot;B&quot; &amp; i).value Set co = New Condition co.attr = ws.Range(&quot;B&quot; &amp; i).value co.value = ws.Range(&quot;C&quot; &amp; i).value bl.conditions.Add co </code></pre>
[ { "answer_id": 74537087, "author": "Mathieu Guindon", "author_id": 1188513, "author_profile": "https://Stackoverflow.com/users/1188513", "pm_score": 4, "selected": true, "text": "Nothing Set New Dim Block As Object\nBlock.Something = 42 ' Error 91\n\nSet Block = New SomeClass ' set reference \nBlock.Something = 42 ' OK\n As Object Dim Block As SomeClass\n As Variant SomeClass Option Explicit\nPublic Name As String\nPublic Case As String \nPublic Condition As Variant\nPublic Check As Variant\n Type Option Explicit" }, { "answer_id": 74537277, "author": "FunThomas", "author_id": 7599798, "author_profile": "https://Stackoverflow.com/users/7599798", "pm_score": 3, "selected": false, "text": "Dim block As Object Nothing Object Set New Class1 Option Explicit\nPublic name as String\nPublic case as String\n Dim block As Class1\nSet block = New Class1\nblock.name = \"Unbekannter Prüfblock\"\n block.data = \"Hello world\" data New Set block = Nothing Collection Dictionary block.Condition = Array() Dim a(1 to 10) as String ' Static array with 10 members (at compile time)\nDim b() as String ' Dynamic array.\n ReDim Redim b(1 to maxNames) ' Dynamic array, now with maxNames members (whatever maxNames is)\n Redim Preserve Preserve Redim Preserve b(1 to maxNames+10) ' Now with 10 more members.\n Collection Dictionary" }, { "answer_id": 74538184, "author": "Ike", "author_id": 16578424, "author_profile": "https://Stackoverflow.com/users/16578424", "pm_score": 2, "selected": false, "text": "Private Sub Class_Initialize()\nSet conditions = New Collection\nset checks = new Collection\nEnd Sub\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443767/" ]
74,536,585
<p>In an existing node project written in JS we're trying to enable the use of Typescript so we can use it in our ongoing refactoring.</p> <p>I've added a tsConfig like so:</p> <pre><code>{ &quot;compilerOptions&quot;: { &quot;target&quot;: &quot;es6&quot;, &quot;module&quot;: &quot;commonjs&quot;, &quot;sourceMap&quot;: true, &quot;rootDir&quot;: &quot;./&quot;, &quot;outDir&quot;: &quot;./tsOutput&quot;, &quot;strict&quot;: true, &quot;moduleResolution&quot;: &quot;node&quot;, &quot;esModuleInterop&quot;: true, &quot;forceConsistentCasingInFileNames&quot;: true }, &quot;include&quot;: [&quot;./&quot;] } </code></pre> <p>I've also installed the following as dev dependencies:</p> <pre><code> &quot;@types/express&quot;: &quot;^4.17.14&quot;, &quot;@types/node&quot;: &quot;^18.11.9&quot;, &quot;@types/node-fetch&quot;: &quot;^2.6.2&quot;, &quot;ts-node&quot;: &quot;^10.9.1&quot;, &quot;ts-node-dev&quot;: &quot;^2.0.0&quot;, &quot;typescript&quot;: &quot;^4.9.3&quot; </code></pre> <p>And I run tsc on build, which runs and generates a js and mapping file. I've run tried this both outputting to a separate directory and removing the outDir in the tsConfig.</p> <p>To test it works, I added the following class in my test project:</p> <pre><code>class ExampleClass { logSomeStuff(stringToLog : string, numberToLog : number, booleanToLog : boolean) { console.log(stringToLog); console.log(numberToLog); console.log(booleanToLog); } } export default ExampleClass; </code></pre> <p>Consume it with this JS file:</p> <pre><code>const { Example } = require(&quot;./Example.ts&quot;); function TypescriptConsumerExample() { const blah = new Example(); blah.logSomeStuff(&quot;String&quot;, 2, false); } module.exports = TypescriptConsumerExample; </code></pre> <p>And attempt to run this JS test:</p> <pre><code>const TypescriptConsumerExample = require(&quot;../TSExample/TSConsumerExample&quot;); describe(&quot;TS test&quot;, () =&gt; { it(&quot;Should be able to call TS code&quot;, () =&gt; { TypescriptConsumerExample(); console.log(&quot;Built&quot;); }); }); </code></pre> <p>But I get this warning, which implies that it doesn't understand what TS is:</p> <pre><code>logSomeStuff(stringToLog : string, numberToLog : number, booleanToLog : boolean) ^ SyntaxError: Unexpected token ':' </code></pre> <p>Equally, if I run the main project and try and call this TS class from index.js:</p> <pre><code>function TSTest() { console.log(&quot;Success!&quot;); } export default TSTest; </code></pre> <p>I get this error:</p> <pre><code>TypeError: TSTest is not a function at Object.&lt;anonymous&gt; </code></pre>
[ { "answer_id": 74536934, "author": "Thomas Skubicki", "author_id": 4647867, "author_profile": "https://Stackoverflow.com/users/4647867", "pm_score": 0, "selected": false, "text": "\"scripts\": { \"start\": \"tsc && node dist/server.js\" }, \"dev\": \"npx nodemon ./src/server.ts\",\n" }, { "answer_id": 74537489, "author": "Dimava", "author_id": 5734961, "author_profile": "https://Stackoverflow.com/users/5734961", "pm_score": 1, "selected": false, "text": "tsconfig.json allowJs: true tsx watch --inspect src/server tsx src/server .ts" }, { "answer_id": 74615854, "author": "Joshua Mee", "author_id": 1497219, "author_profile": "https://Stackoverflow.com/users/1497219", "pm_score": 1, "selected": true, "text": " \"main\": \"./tsOutput/index.js\",\n \"scripts\": {\n \"start\": \"tsc && node --unhandled-rejections=warn ./tsOutput/index.js\",\n \"dev\": \"tsc && node --unhandled-rejections=warn ./tsOutput/index.js\",\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1497219/" ]
74,536,612
<p>I have an angular application that read from a config file the backend URL in order to process the queries. The advantage of this is that the back and front can be deployed on any servers.</p> <p>In my angular application I read a JSON containing the following information:</p> <pre><code>{ baseUrl: &quot;http://server-url:8080/backend } </code></pre> <p>In a service I implemented a method that open the json in the service layer:</p> <pre><code>getJsonConfig() { let jsonUrl = './assets/configuration/config.json'; return this.http.get&lt;any&gt;(jsonUrl) .pipe( map((response: any) =&gt; { this.baseUrl = response.baseUrl; }) ); } </code></pre> <p>I have to call 2 other HTTP entry points to display data on my component: the call of those 2 URL depend on the baseUrl retrieved. First I have to retrieve a database name with this call:</p> <pre><code>getDbName(): Observable&lt;getDbName&gt; { const url = this.baseUrl + &quot;/dbInfos&quot; return this.http.get&lt;getDbName&gt;(url); } getData(): Observable&lt;data[]&gt; { let url = this.baseUrl + &quot;/actions&quot; return this.http.get&lt;data[]&gt;(url); } </code></pre> <p>Here it comes more complex: I have 2 components: a parent component and a child component. the method getData must be updated every 10 seconds because it is used to display a graph...</p> <p>In the parent component, I used ngOnInit webhook to call the webservice</p> <pre><code>ngOnInit(): void { this.httpService.getJsonConfig().subscribe({ next: res =&gt; { console.log(res) this.jsonConfigObject = res; }, error: err =&gt; { this.loading = false; Utils.handleErrorMessage(err, this.messageService); }, complete: () =&gt; { this.getData(); this.getDbName(); } }); } </code></pre> <p>At this stage, I wait the configuration to be loaded to call the 2 other webservices. Here is the implementation of those 2 methods:</p> <pre><code>private getDbName() { this.httpService.getDbName().subscribe({ next: (res) =&gt; { if(res != undefined) { this.isPathLoaded = true } this.dbName = res.path; return res.path; }, error: err =&gt; { this.loading = false; Utils.handleErrorMessage(err, this.messageService); } }); } private getData() { this.subscribe = timer(0, 10000).pipe( tap((res) =&gt; { console.log(res); return res; }), takeUntil(this.unsub), switchMap(() =&gt; this.httpService.getData().pipe( tap({ next: (res) =&gt; { if(res.length &gt;= 1) { this.isDataLoaded = true } this.data = res; } }), )) ).subscribe(); } </code></pre> <p>I have some data to display in the parent component and for this I check i do have values before inserting the data. Here is how i handle this:</p> <pre><code>&lt;div class=&quot;card&quot; *ngIf=&quot;data&quot;&gt; &lt;p class=&quot;card-category&quot;&gt; Database : {{ dbName }} &lt;br /&gt; Id : {{ histData.id }} &lt;br /&gt; &lt;/p&gt; &lt;/div&gt; </code></pre> <p>After in my code I use primeng where I bind the data to the select and labels have the id as value.</p> <pre><code>&lt;p-dropdown [options]=&quot;data&quot; [(ngModel)]=&quot;histData&quot; optionLabel =&quot;id&quot;&gt; &lt;/p-dropdown&gt; </code></pre> <p>And finally I send data to the child component:</p> <pre><code>&lt;app-stacked-charts [data] = &quot;histData&quot; &gt;&lt;/app-stacked-charts&gt; </code></pre> <p>My issues are the following:</p> <ol> <li>I have an error message : ERROR Error: NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: ''. Current value: 'someCurrentValue'</li> <li>When i select a value in my dropdown select, In certain cases, after a few seconds, the select is returning to its default value instead of remaining on the selected value.</li> </ol>
[ { "answer_id": 74536838, "author": "Timothy", "author_id": 9590251, "author_profile": "https://Stackoverflow.com/users/9590251", "pm_score": 2, "selected": true, "text": "getData(): Data {\n return this.getDbName().pipe(\n switchMap(dbName => this.getData(dbName))\n )\n}\n <div class=\"card\" *ngIf=\"data$ | async as data\">\n <p class=\"card-category\">\n Database : {{ dbName }} <br />\n Id : {{ histData.id }} <br />\n </p>\n</div>\n" }, { "answer_id": 74537191, "author": "MoxxiManagarm", "author_id": 11011793, "author_profile": "https://Stackoverflow.com/users/11011793", "pm_score": 1, "selected": false, "text": "getDbName getData takeUntil switchMap getJsonConfig map tap getData tap tap" }, { "answer_id": 74544583, "author": "davidvera", "author_id": 8521515, "author_profile": "https://Stackoverflow.com/users/8521515", "pm_score": 0, "selected": false, "text": "@Injectable({\n providedIn: 'root'\n})\nexport class AppConfigService {\n private appConfig: any;\n\n constructor(private http: HttpClient) { }\n\n loadAppConfig(): Observable<any> {\n let jsonUrl = './assets/configuration/config.json';\n return this.http.get<any>(jsonUrl)\n .pipe(\n map((response: any) => {\n this.appConfig = response;\n })\n );\n }\n\n getConfig(): any {\n return this.appConfig;\n }\n}\n const appInitializer = (appConfig: AppConfigService) => {\n return () => {\n // console.log('App Initialization');\n return appConfig.loadAppConfig();\n };\n};\n providers: [\n HttpService,\n {\n provide: APP_INITIALIZER,\n useFactory: appInitializer,\n multi: true,\n deps: [AppConfigService]\n },\n],\n getData() {\n this.dataSubscription = this.httpService.getData().subscribe({\n next: (res) => {\n this.data = res;\n this.histData = res[0];\n console.log(this.histData);\n },\n error: (err) => {\n this.loading = false;\n Utils.handleErrorMessage(err, this.messageService);\n }\n });\n this.refreshData();\n}\n private refreshData() {\n this.subscribe = timer(0, 10000).pipe(\n tap((res) => {\n console.log(res);\n return res;\n }),\n takeUntil(this.unsub),\n switchMap(() => this.httpService.getData().pipe(\n tap({\n next: (res) => {\n this.data = res\n return res;\n }\n }),\n ))\n ).subscribe();\n}\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8521515/" ]
74,536,614
<p>So as you will be able to see in the code, my class constructor asks the user for an input of the &quot;initialValue&quot; of their object. I then have a method &quot;addToValue&quot; which adds to that value. When trying to use JUnit4 to learn TDD it does not use the &quot;initialValue&quot; parameter to set the value of &quot;value&quot;, therefore it is only returning the input of the &quot;valueChange&quot; parameter. Sorry if this is confusing.</p> <p>Here is my code</p> <pre><code>public class Sterling { int value; public Sterling(int initialValue) { int value= initialValue; } public int addToValue(int valueChange){; value = value+valueChange; return value; } } </code></pre> <p>This is the JUnit4 code</p> <pre><code>import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class SterlingTest { private Sterling o; @Before public void setUp() { o = new Sterling(100); } @Test public void testAddToValue(){ assertEquals(150,o.addToValue(50)); }} </code></pre> <p>in the &quot;assertEquals&quot; line, 150 is the expected return value (initalValue is 100 and valueChange is 50) however my &quot;Actual&quot; output value is 50. As mentioned before I am only just learning to use JUnit so I'm sure its a simple mistake but I have been stuck on this for nearly 2hours lol.</p> <p>Thank you for any help :)</p>
[ { "answer_id": 74536838, "author": "Timothy", "author_id": 9590251, "author_profile": "https://Stackoverflow.com/users/9590251", "pm_score": 2, "selected": true, "text": "getData(): Data {\n return this.getDbName().pipe(\n switchMap(dbName => this.getData(dbName))\n )\n}\n <div class=\"card\" *ngIf=\"data$ | async as data\">\n <p class=\"card-category\">\n Database : {{ dbName }} <br />\n Id : {{ histData.id }} <br />\n </p>\n</div>\n" }, { "answer_id": 74537191, "author": "MoxxiManagarm", "author_id": 11011793, "author_profile": "https://Stackoverflow.com/users/11011793", "pm_score": 1, "selected": false, "text": "getDbName getData takeUntil switchMap getJsonConfig map tap getData tap tap" }, { "answer_id": 74544583, "author": "davidvera", "author_id": 8521515, "author_profile": "https://Stackoverflow.com/users/8521515", "pm_score": 0, "selected": false, "text": "@Injectable({\n providedIn: 'root'\n})\nexport class AppConfigService {\n private appConfig: any;\n\n constructor(private http: HttpClient) { }\n\n loadAppConfig(): Observable<any> {\n let jsonUrl = './assets/configuration/config.json';\n return this.http.get<any>(jsonUrl)\n .pipe(\n map((response: any) => {\n this.appConfig = response;\n })\n );\n }\n\n getConfig(): any {\n return this.appConfig;\n }\n}\n const appInitializer = (appConfig: AppConfigService) => {\n return () => {\n // console.log('App Initialization');\n return appConfig.loadAppConfig();\n };\n};\n providers: [\n HttpService,\n {\n provide: APP_INITIALIZER,\n useFactory: appInitializer,\n multi: true,\n deps: [AppConfigService]\n },\n],\n getData() {\n this.dataSubscription = this.httpService.getData().subscribe({\n next: (res) => {\n this.data = res;\n this.histData = res[0];\n console.log(this.histData);\n },\n error: (err) => {\n this.loading = false;\n Utils.handleErrorMessage(err, this.messageService);\n }\n });\n this.refreshData();\n}\n private refreshData() {\n this.subscribe = timer(0, 10000).pipe(\n tap((res) => {\n console.log(res);\n return res;\n }),\n takeUntil(this.unsub),\n switchMap(() => this.httpService.getData().pipe(\n tap({\n next: (res) => {\n this.data = res\n return res;\n }\n }),\n ))\n ).subscribe();\n}\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20574453/" ]
74,536,627
<p>I have a really weird problem in my elasticsearch query. I made an autocomplete search in my website and I have a problem.</p> <p>For example, there is a neighborhood in my country called &quot;Recreio dos Bandeirantes&quot; When I search for &quot;bandeirant&quot; (while user are typing) the query find the neighborhood, but, when finish the type &quot;bandeirantes&quot; cannot find the same neighborhood.</p> <p>This is my query</p> <pre class="lang-js prettyprint-override"><code> { query: { bool: { must: [ { match: { 'city.name': city, }, }, { match: { 'city.state': state, }, }, { match: { keyword: { query, // The query is 'bandeirant' or 'bandeirantes' }, }, }, ], }, }, highlight: { fields: { keyword: { number_of_fragments: 9, }, }, }, size: 20, } </code></pre> <p>The final neighborhood value is 'Recreio dos Bandeirantes, Rio de Janeiro, RJ'</p> <p>The mapping for this field is this:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;search-neighborhood-01&quot;: { &quot;mappings&quot;: { &quot;properties&quot;: { &quot;city&quot;: { //..... }, &quot;keyword&quot;: { &quot;type&quot;: &quot;text&quot;, &quot;analyzer&quot;: &quot;autocomplete&quot;, &quot;search_analyzer&quot;: &quot;standard&quot; }, &quot;name&quot;: { &quot;type&quot;: &quot;text&quot;, &quot;analyzer&quot;: &quot;autocomplete&quot;, &quot;search_analyzer&quot;: &quot;standard&quot; } } } } } </code></pre> <p>My settings with analyzer</p> <pre class="lang-json prettyprint-override"><code>{ &quot;search-neighborhood-01&quot;: { &quot;settings&quot;: { &quot;index&quot;: { // ....... &quot;analysis&quot;: { &quot;filter&quot;: { &quot;autocomplete_filter&quot;: { &quot;token_chars&quot;: [ &quot;letter&quot; ], &quot;min_gram&quot;: &quot;1&quot;, &quot;type&quot;: &quot;edge_ngram&quot;, &quot;max_gram&quot;: &quot;10&quot; } }, &quot;analyzer&quot;: { &quot;autocomplete&quot;: { &quot;filter&quot;: [ &quot;lowercase&quot;, &quot;autocomplete_filter&quot;, &quot;asciifolding&quot; ], &quot;type&quot;: &quot;custom&quot;, &quot;tokenizer&quot;: &quot;standard&quot; } } }, // ..... } } } } </code></pre> <p>My response with <code>bandeirant</code></p> <pre class="lang-json prettyprint-override"><code>// ..... { //..... &quot;_source&quot;: { &quot;city&quot;: { &quot;name&quot;: &quot;Rio de Janeiro&quot;, &quot;state&quot;: &quot;RJ&quot;, &quot;keyword&quot;: &quot;Rio de Janeiro, RJ&quot; }, &quot;name&quot;: &quot;Recreio dos Bandeirantes&quot;, &quot;keyword&quot;: &quot;Recreio dos Bandeirantes, Rio de Janeiro, RJ&quot; }, &quot;highlight&quot;: { &quot;keyword&quot;: [ &quot;Recreio dos &lt;em&gt;Bandeirantes&lt;/em&gt;, Rio de Janeiro, RJ&quot; ] } } </code></pre> <p>My response with <code>bandeirantes</code> is empty :/</p> <p>How can I do to solve this?</p> <p>Thanks o/</p>
[ { "answer_id": 74537552, "author": "Kaveh", "author_id": 14018385, "author_profile": "https://Stackoverflow.com/users/14018385", "pm_score": 2, "selected": false, "text": "\"max_gram\": \"10\" “min_gram”" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4764104/" ]
74,536,741
<p>is there any function that converts things like : &quot;1,8&quot; to 1.8</p> <p>I try as.double but it seems to not work.</p> <p>I need to convert a column of a dataframe (whith only characters like this &quot;1,3&quot;). And I dont understand why, when I use as.double I've got only Nas</p>
[ { "answer_id": 74537552, "author": "Kaveh", "author_id": 14018385, "author_profile": "https://Stackoverflow.com/users/14018385", "pm_score": 2, "selected": false, "text": "\"max_gram\": \"10\" “min_gram”" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13682994/" ]
74,536,748
<p>hello i'm using a stack overflow and i want to implement the login modal in my POS method so my plan here is that whenever i click the VOID button there was a login modal that will pop up to validate if the user has the authority to void a product</p> <p>code under edit.php Void Products</p> <pre><code>&lt;div id=&quot;loginModal&quot; class=&quot;modal fade&quot; role=&quot;dialog&quot;&gt; &lt;div class=&quot;modal-dialog&quot;&gt; &lt;!-- Modal content--&gt; &lt;div class=&quot;modal-content&quot;&gt; &lt;div class=&quot;modal-header&quot;&gt; &lt;button type=&quot;button&quot; class=&quot;close&quot; data-dismiss=&quot;modal&quot;&gt;&amp;times;&lt;/button&gt; &lt;h4 class=&quot;modal-title&quot;&gt;Login&lt;/h4&gt; &lt;/div&gt; &lt;div class=&quot;modal-body&quot;&gt; &lt;label&gt;Username&lt;/label&gt; &lt;input type=&quot;text&quot; name=&quot;username&quot; id=&quot;username&quot; class=&quot;form-control&quot; /&gt; &lt;br /&gt; &lt;label&gt;Password&lt;/label&gt; &lt;input type=&quot;password&quot; name=&quot;password&quot; id=&quot;password&quot; class=&quot;form-control&quot; /&gt; &lt;br /&gt; &lt;button type=&quot;button&quot; name=&quot;login_button&quot; id=&quot;login_button&quot; class=&quot;btn btn-warning&quot;&gt;Login&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>and yeah it's working as i expected and here is my ajax under edit.php</p> <pre><code>$(document).ready(function() { $('#login_button').click(function(){ var username = $('#username').val(); var password = $('#password').val(); if(username != '' &amp;&amp; password != '') { $.ajax({ url:&quot;action.php&quot;, method:&quot;POST&quot;, data: {username:username, password:password}, success:function(data) { //alert(data); if(data == 'No') { alert(&quot;Wrong Data&quot;); } else { $('#loginModal').hide(); location.reload(); } } }); } else { alert(&quot;Both fields are required&quot;); } }); }); </code></pre> <p>and my problem is that i'm using a code igniter framework and i do not know how to implement this line of code into my program</p> <p>action.php</p> <pre><code> &lt;?php session_start(); $connect = mysqli_connect(&quot;localhost&quot;, &quot;root&quot;, &quot;&quot;, &quot;bubblebee&quot;); if(isset($_POST[&quot;username&quot;])) { $query = &quot; SELECT * FROM admin_login WHERE admin_name = '&quot;.$_POST[&quot;username&quot;].&quot;' AND admin_password = '&quot;.$_POST[&quot;password&quot;].&quot;' &quot;; $result = mysqli_query($connect, $query); if(mysqli_num_rows($result) &gt; 0) { $_SESSION['username'] = $_POST['username']; echo 'Yes'; } else { echo 'No'; } } if(isset($_POST[&quot;action&quot;])) { unset($_SESSION[&quot;username&quot;]); } ?&gt; </code></pre> <p>when press the both required filed is working but the username and password seems like have a problem and i can't identify what is my error here maybe i do not know how to implement it in the code igniter? can someone teach me.</p> <p>my folder structure right now with that action.php is something like this</p> <ul> <li>application <ul> <li>view <ul> <li>order <ul> <li>action.php</li> <li>create.php</li> <li>edit.php</li> <li>index.php</li> </ul> </li> </ul> </li> </ul> </li> </ul>
[ { "answer_id": 74567617, "author": "KUMAR", "author_id": 12030528, "author_profile": "https://Stackoverflow.com/users/12030528", "pm_score": 2, "selected": false, "text": "edit.php <!DOCTYPE html>\n <html>\n <head>\n <title>Login</title>\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0\">\n <link href=\"http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css\" rel=\"stylesheet\">\n <!--[if lt IE 9]>\n <script src=\"//oss.maxcdn.com/libs/html5shiv/r29/html5.min.js\"></script>\n <script src=\"//oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js\"></script>\n <![endif]-->\n </head>\n <body>\n\n <div class=\"container\">\n <button class=\"btn btn-primary\" data-toggle=\"modal\" data-target=\"#myModal\">Login</button>\n\n <div class=\"modal fade\" id=\"myModal\">\n <div class=\"modal-dialog\">\n <div class=\"modal-content\">\n <form id=\"form\" role=\"form\">\n <div class=\"modal-header\">\n <button type=\"button\" class=\"close\" data-dismiss=\"modal\"><span aria-hidden=\"true\">&times;</span><span class=\"sr-only\">Close</span></button>\n <h4 class=\"modal-title\">Login</h4>\n </div>\n <div class=\"modal-body\">\n <div id=\"messages\"></div>\n YOUR FORM ELEMENTS HERE\n Username: <input type=\"text\" name=\"username\">\n </div>\n <div class=\"modal-footer\">\n <button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Close</button>\n <button type=\"submit\" class=\"btn btn-primary\">Login</button>\n </div>\n </form>\n </div>\n </div>\n </div>\n\n </div>\n <script src=\"http://code.jquery.com/jquery.js\"></script>\n <script src=\"http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js\"></script>\n <script>\n $('#form').submit(function(e) {\n\n var form = $(this);\n var formdata = false;\n if(window.FormData){\n formdata = new FormData(form[0]);\n }\n\n var formAction = form.attr('action');\n\n $.ajax({\n type : 'POST',\n url : \"<?php echo base_url(); ?>/controllerName/FunctionName\",\n cache : false,\n data : formdata ? formdata : form.serialize(),\n contentType : false,\n processData : false,\n dataType: 'json',\n\n success: function(response) {\n //TARGET THE MESSAGES DIV IN THE MODAL\n if(response.type == 'success') {\n $('#messages').addClass('alert alert-success').text(response.message);\n } else {\n $('#messages').addClass('alert alert-danger').text(response.message);\n }\n }\n });\n e.preventDefault();\n });\n </script>\n </body>\n</html>\n \n function get_user($username,$password)\n{\n $this->db->select('*');\n $this->db->from('user');\n $this->db->where('username',$username);\n $this->db->where('password',$password);\n $q = $this->db->get();\n if ($q->num_rows() > 0) {\n return $q->row();\n } else\n return FALSE;\n}\n public function login()\n {\n $user_email = $this->input->post('user_email', true);\n $user_pass = md5($this->input->post('user_pswd', true));\n $user_result = $this->M_login->get_user($username,$password));\n if ($user_result >0) //active user record is present\n {\n $this->session->set_userdata('user_session',$user_result);\n\n $this->session->set_flashdata('login_message', '<div class=\"alert alert-success text-center\">You are Successfully Login to your account!</div>');\n \n $url = base_url('Login/billing');\n redirect($url);\n \n } else {\n $this->session->set_flashdata('err_message', '<div class=\"alert alert-danger text-center\">Invalid email and password!</div>');\n redirect(\"Login/login\");\n }\n }\n" }, { "answer_id": 74579612, "author": "Iyang Agung Supriatna", "author_id": 9701396, "author_profile": "https://Stackoverflow.com/users/9701396", "pm_score": 0, "selected": false, "text": "<div id=\"loginModal\" class=\"modal fade\" role=\"dialog\"> \n <div class=\"modal-dialog\"> \n <!-- Modal content--> \n <form method=\"post\" accept-charset=\"utf-8\" action=\"<?=url('controller/method')?>\" class=\"email\" id=\"myform\">\n <div class=\"modal-content\"> \n <div class=\"modal-header\"> \n <button type=\"button\" class=\"close\" data-dismiss=\"modal\">&times;</button> \n <h4 class=\"modal-title\">Login</h4> \n </div> \n <div class=\"modal-body\"> \n <label>Username</label> \n <input type=\"text\" name=\"username\" id=\"username\" class=\"form-control\" /> \n <br /> \n <label>Password</label> \n <input type=\"password\" name=\"password\" id=\"password\" class=\"form-control\" /> \n <br /> \n <button type=\"button\" name=\"login_button\" id=\"login_button\" class=\"btn btn-warning\">Login</button> \n </div> \n </div> \n </form>\n </div> \n </div>\n ##.../controller.php\n\nfunction method(){\n ## create method to \n var_dump($this->input->post());\n}\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14393948/" ]
74,536,749
<p>I am working on the following problem which requires to use case_when. However, I encounter the error message <code>Error: must be a logical vector, not a double vector</code> because the replaced columns are not the same type (some logical and some double due to <code>bind_rows</code>). I am looking for a clean solution to get the desired output.</p> <pre><code>#set empty dataframe with column names df &lt;- setNames(data.frame(matrix(ncol = 5, nrow = 0)), c(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;,&quot;d&quot;,&quot;e&quot;)) df_subset &lt;- data.frame(b=c(1,2)) df1 &lt;- bind_rows(df,df_subset)%&gt;%mutate(type=&quot;b&quot;) df1 a b c d e type 1 NA 1 NA NA NA b 2 NA 2 NA NA NA b df1%&gt;%mutate(result=case_when(type==&quot;a&quot;~a, type==&quot;b&quot;~b, type==&quot;c&quot;~c, type==&quot;d&quot;~d, type==&quot;e&quot;~e, T~NA_real_)) Error: must be a logical vector, not a double vector </code></pre> <p>Expected output: <strong>(Note: I do not always know if column b has values)</strong></p> <pre><code>df1%&gt;%mutate(a=NA_real_, c=NA_real_, d=NA_real_, e=NA_real_, result=case_when(type==&quot;a&quot;~a, type==&quot;b&quot;~b, type==&quot;c&quot;~c, type==&quot;d&quot;~d, type==&quot;e&quot;~e, T~NA_real_)) #desired output a b c d e type result 1 NA 1 NA NA NA b 1 2 NA 2 NA NA NA b 2 </code></pre>
[ { "answer_id": 74536791, "author": "tmfmnk", "author_id": 5964557, "author_profile": "https://Stackoverflow.com/users/5964557", "pm_score": 2, "selected": false, "text": "df1 %>%\n rowwise() %>%\n mutate(result = get(type))\n\n a b c d e type result\n <lgl> <dbl> <lgl> <lgl> <lgl> <chr> <dbl>\n1 NA 1 NA NA NA b 1\n2 NA 2 NA NA NA b 2\n" }, { "answer_id": 74536802, "author": "Ruam Pimentel", "author_id": 13015865, "author_profile": "https://Stackoverflow.com/users/13015865", "pm_score": 3, "selected": true, "text": "dplyr library(dplyr)\n\ndf1 %>% \n mutate(across(a:e, as.numeric)) %>% # this is the fix\n mutate(result=case_when(type==\"a\"~a,\n type==\"b\"~b,\n type==\"c\"~c,\n type==\"d\"~d,\n type==\"e\"~e,\n T~NA_real_))\n #> a b c d e type result\n#> 1 NA 1 NA NA NA b 1\n#> 2 NA 2 NA NA NA b 2\n" }, { "answer_id": 74536810, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 2, "selected": false, "text": "library(dplyr)\ndf1 %>%\n rowwise() %>%\n mutate(result = cur_data()[[type]]) %>%\n ungroup\n # A tibble: 2 × 7\n a b c d e type result\n <lgl> <dbl> <lgl> <lgl> <lgl> <chr> <dbl>\n1 NA 1 NA NA NA b 1\n2 NA 2 NA NA NA b 2\n" }, { "answer_id": 74537057, "author": "M.Viking", "author_id": 10276092, "author_profile": "https://Stackoverflow.com/users/10276092", "pm_score": 2, "selected": false, "text": "matrix b str(df1) case_when() a b ?matrix df <- as.data.frame(matrix(NA_integer_, nrow=2, ncol=5, dimnames=list(1:2, letters[1:5])))\ndf$b <- c(1,2)\ndf$type <- c(\"b\",\"b\")\ndf %>% mutate(result=case_when(type==\"a\"~a,\n type==\"b\"~b,\n type==\"c\"~c,\n type==\"d\"~d,\n type==\"e\"~e,\n T~NA_integer_))\n \n# a b c d e type result\n#1 NA 1 NA NA NA b 1\n#2 NA 2 NA NA NA b 2\n" }, { "answer_id": 74537179, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 2, "selected": false, "text": "library(dplyr)\nlibrary(tibble)\ndf1 %>%\n mutate(across(everything(), as.character)) %>% \n mutate(result=case_when(type==\"a\"~a,\n type==\"b\"~b,\n type==\"c\"~c,\n type==\"d\"~d,\n type==\"e\"~e,\n TRUE~NA_character_)) %>% \n type.convert(as.is = TRUE) %>% \n as_tibble()\n a b c d e type result\n <lgl> <int> <lgl> <lgl> <lgl> <chr> <int>\n1 NA 1 NA NA NA b 1\n2 NA 2 NA NA NA b 2\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17918739/" ]
74,536,768
<p>I was developing a different app titled &quot;Video Chat&quot; around 5-6 hours ago and after my work was done I switched over to a different app and ran it using the &quot;npm start&quot; command, however the command now only starts the &quot;Video Chat&quot; app in the localhost and I'm stuck here. Any suggestions? Both applications were created using ReactJS.</p> <p>The problem persists even after I've deleted the &quot;Video Chat&quot; application, reinstalled Node LTS version and even changed the partitions of the project I'm working on now. I want to run my current application on the localhost for development.</p>
[ { "answer_id": 74536791, "author": "tmfmnk", "author_id": 5964557, "author_profile": "https://Stackoverflow.com/users/5964557", "pm_score": 2, "selected": false, "text": "df1 %>%\n rowwise() %>%\n mutate(result = get(type))\n\n a b c d e type result\n <lgl> <dbl> <lgl> <lgl> <lgl> <chr> <dbl>\n1 NA 1 NA NA NA b 1\n2 NA 2 NA NA NA b 2\n" }, { "answer_id": 74536802, "author": "Ruam Pimentel", "author_id": 13015865, "author_profile": "https://Stackoverflow.com/users/13015865", "pm_score": 3, "selected": true, "text": "dplyr library(dplyr)\n\ndf1 %>% \n mutate(across(a:e, as.numeric)) %>% # this is the fix\n mutate(result=case_when(type==\"a\"~a,\n type==\"b\"~b,\n type==\"c\"~c,\n type==\"d\"~d,\n type==\"e\"~e,\n T~NA_real_))\n #> a b c d e type result\n#> 1 NA 1 NA NA NA b 1\n#> 2 NA 2 NA NA NA b 2\n" }, { "answer_id": 74536810, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 2, "selected": false, "text": "library(dplyr)\ndf1 %>%\n rowwise() %>%\n mutate(result = cur_data()[[type]]) %>%\n ungroup\n # A tibble: 2 × 7\n a b c d e type result\n <lgl> <dbl> <lgl> <lgl> <lgl> <chr> <dbl>\n1 NA 1 NA NA NA b 1\n2 NA 2 NA NA NA b 2\n" }, { "answer_id": 74537057, "author": "M.Viking", "author_id": 10276092, "author_profile": "https://Stackoverflow.com/users/10276092", "pm_score": 2, "selected": false, "text": "matrix b str(df1) case_when() a b ?matrix df <- as.data.frame(matrix(NA_integer_, nrow=2, ncol=5, dimnames=list(1:2, letters[1:5])))\ndf$b <- c(1,2)\ndf$type <- c(\"b\",\"b\")\ndf %>% mutate(result=case_when(type==\"a\"~a,\n type==\"b\"~b,\n type==\"c\"~c,\n type==\"d\"~d,\n type==\"e\"~e,\n T~NA_integer_))\n \n# a b c d e type result\n#1 NA 1 NA NA NA b 1\n#2 NA 2 NA NA NA b 2\n" }, { "answer_id": 74537179, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 2, "selected": false, "text": "library(dplyr)\nlibrary(tibble)\ndf1 %>%\n mutate(across(everything(), as.character)) %>% \n mutate(result=case_when(type==\"a\"~a,\n type==\"b\"~b,\n type==\"c\"~c,\n type==\"d\"~d,\n type==\"e\"~e,\n TRUE~NA_character_)) %>% \n type.convert(as.is = TRUE) %>% \n as_tibble()\n a b c d e type result\n <lgl> <int> <lgl> <lgl> <lgl> <chr> <int>\n1 NA 1 NA NA NA b 1\n2 NA 2 NA NA NA b 2\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20574687/" ]
74,536,830
<p>Trying to learn C. To that end, I'm coding a program that creates a TroubleTicket report. The user is prompted to enter, priority, name and problem. I'm using a struct to store the data and create a struck array. Using the array approach for now as I'm developing the code. Eventually, I'd to use a linked list.</p> <p>Anyhow, the get_input() function reads in the user input and returns a char pointer. Included the get_input() and create_ticket() functions.</p> <pre><code>#define NUM_TICKETS 10 char* get_input(int maxlen) { static char s[110]; char ch; int i = 0; int chars_remain = 1; while (chars_remain) { ch = getchar(); if ((ch == '\n') || (ch == EOF)) { chars_remain = 0; } else if (i &lt; maxlen - 1) { s[i] = ch; i++; } } s[i] = '\0'; return s; void create_ticket() { struct ticket { int priority; int number; char * name; char * problem ; char * assigned_to; char * status ; }; struct ticket tkt_array[NUM_TICKETS]; struct ticket new_ticket; printf(&quot;Enter your name: &quot;); new_ticket.name = get_input(20); printf(&quot;new_ticket.name: %s \n&quot;, new_ticket.name); printf(&quot;Enter problem description: &quot;); new_ticket.problem = get_input(100); printf(&quot;new_ticket.problem: %s \n&quot;, new_ticket.problem); printf(&quot;Assigned to: &quot;); new_ticket.assigned_to = get_input(20); printf(&quot;new_ticket.assigned_to %s\n &quot;, new_ticket.assigned_to); printf(&quot;Enter ticket status: &quot;); new_ticket.status = get_input(10); printf(&quot;new_ticket.status: %s \n&quot;, new_ticket.status); } </code></pre> <p>I noticed that initial input was read and displayed correctly but subsequent inputs overwrote prior input.</p> <p>For example, after name was entered, the entered value is displayed</p> <pre><code>printf(&quot;Enter your name: &quot;); new_ticket.name = get_input(20); printf(&quot;new_ticket.name: %s \n&quot;, new_ticket.name); </code></pre> <p>But after problem description is entered, new_ticket.name was changed to display the problem description text. Took me a while to figure out that the problem is the return s in get_char(). It returns a pointer. The address is the same but the value changes and struct ticket pointers point to the same address of return s from get_char(). How can I save the return value in a variable and not get it reset on subsequent call to get_input? s is a char *, how can I save the return value of a pointer in a variable?</p> <pre><code>printf(&quot;Enter problem description: &quot;); new_ticket.problem = get_input(100); printf(&quot;new_ticket.problem: %s \n&quot;, new_ticket.problem); printf(&quot;new_ticket.name: %s \n&quot;, new_ticket.name); </code></pre> <p>How can I save the return value in a variable and not get it reset on subsequent call to get_input? s is a char *, how can I save the return value of a pointer in a variable? I hope I clearly stated the issue.</p>
[ { "answer_id": 74537009, "author": "Carson", "author_id": 4930913, "author_profile": "https://Stackoverflow.com/users/4930913", "pm_score": 2, "selected": true, "text": "static malloc(size) free free struct ticket char name[MAX_NAME_LEN] get_input(int max_len, char * buffer) malloc free" }, { "answer_id": 74537011, "author": "Bodo", "author_id": 10622916, "author_profile": "https://Stackoverflow.com/users/10622916", "pm_score": 2, "selected": false, "text": "get_input static char s[110]; new_ticket.name = get_input(20); s get_input strcpy strdup malloc strcpy new_ticket.name = strdup(get_input(20));\n strdup free strdup const char *s1;\n char *s2;\n/* ... */\n\n s1 = get_input(20);\n s2 = malloc(strlen(s1) + 1);\n if(s2 == NULL)\n {\n /* handle error */\n }\n else\n {\n strcpy(s2, s1);\n }\n new_ticket.name = s2;\n malloc strcpy struct ticket\n {\n int priority;\n int number;\n char name[20];\n char problem[100];\n char assigned_to[20];\n char status[10];\n };\n\n/* ... */\n strcpy(new_ticket.name, get_input(sizeof(new_ticket.name));\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6669933/" ]
74,536,857
<p>I am trying splitting a json column into multiple column. I am using the below query and it worked well before but for some reason I am getting SyntaxError: invalid syntax</p> <pre><code> df[&quot;column_config&quot;] = df[&quot;column_config&quot;].apply(lambda x: dict(eval(x))) final = df('column_config').reset_index(drop=True) </code></pre> <p>here is the sample data frame</p> <pre><code> company_id column_config 1 [{&quot;username&quot;:&quot;Rob&quot;,&quot;type&quot;:&quot;Admin&quot;,&quot;Id&quot;:&quot;f3234ds&quot;,&quot;prefixType&quot;:&quot;&quot;},{&quot;username&quot;:&quot;Lew&quot;,&quot;type&quot;:&quot;Finance&quot;,&quot;Id&quot;:&quot;d32423d&quot;,&quot;prefix&quot;:&quot;Mr&quot;}] 2 [{&quot;username&quot;:&quot;Bob&quot;,&quot;type&quot;:&quot;Admin&quot;,&quot;Id&quot;:&quot;t43234s&quot;,&quot;prefixType&quot;:&quot;&quot;}] </code></pre> <p>expected output</p> <pre><code> company_id username type Id prefix 1 Rob Admin f3234ds 1 Lew Finance d32423d Mr 2 Bob Admin t43234s </code></pre> <p>Not sure why I am getting this error. Is there any we can achieve the above?</p>
[ { "answer_id": 74537009, "author": "Carson", "author_id": 4930913, "author_profile": "https://Stackoverflow.com/users/4930913", "pm_score": 2, "selected": true, "text": "static malloc(size) free free struct ticket char name[MAX_NAME_LEN] get_input(int max_len, char * buffer) malloc free" }, { "answer_id": 74537011, "author": "Bodo", "author_id": 10622916, "author_profile": "https://Stackoverflow.com/users/10622916", "pm_score": 2, "selected": false, "text": "get_input static char s[110]; new_ticket.name = get_input(20); s get_input strcpy strdup malloc strcpy new_ticket.name = strdup(get_input(20));\n strdup free strdup const char *s1;\n char *s2;\n/* ... */\n\n s1 = get_input(20);\n s2 = malloc(strlen(s1) + 1);\n if(s2 == NULL)\n {\n /* handle error */\n }\n else\n {\n strcpy(s2, s1);\n }\n new_ticket.name = s2;\n malloc strcpy struct ticket\n {\n int priority;\n int number;\n char name[20];\n char problem[100];\n char assigned_to[20];\n char status[10];\n };\n\n/* ... */\n strcpy(new_ticket.name, get_input(sizeof(new_ticket.name));\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13896398/" ]
74,536,875
<p>I have pretty much same question as here: <a href="https://stackoverflow.com/questions/57518852/swiftui-picker-onchange-or-equivalent">SwiftUI Picker onChange or equivalent?</a>, but .onChange won't solve it exactly I need.</p> <p>I have wrote a question in that link, but I was told to ask a new question (as I wasn't able to find answer anywhere :(</p> <p>I have this enum:</p> <pre><code>enum FruitTea: String, CustomStringConvertible, CaseIterable, Codable { case peach = &quot;Peach&quot; case passionFruit = &quot;Passion Fruit&quot; case mango = &quot;Mango&quot; case greenApple = &quot;Green Apple&quot; var description: String { rawValue } } enum TypeOfTea: String, CustomStringConvertible, CaseIterable, Codable { case specialTeaPresso = &quot;Special Tea Presso&quot; case teaLatte = &quot;Tea Latte&quot; case mousseSeries = &quot;Mousse Series&quot; case milkTea = &quot;Milk Tea&quot; case fruitTea = &quot;Fruit Tea&quot; var description: String { rawValue } } </code></pre> <p>And this picker:</p> <pre><code>@State private var type: TypeOfTea = .specialTeaPresso @State private var fruit: FruitTea = .passionFruit Picker(&quot;Fruit Tea&quot;, selection: $fruit) { ForEach(FruitTea.allCases, id: \.self) { Text($0.rawValue).tag($0) } } .onChange(of: fruit, perform: { _ in type = .fruitTea }) </code></pre> <p>When I choose another kind of fruit tea that is already chosen, it works. But If I choose what is default value, my TypeOfTea won't change. I know why - because there was no change. But for my app clicking on Picker means choosing type. Can you please help? Thanks.</p> <p>In case someone is interested in my all app:</p> <p><a href="https://github.com/Marcel-git666/Geicha/tree/new" rel="nofollow noreferrer">My app on github</a></p>
[ { "answer_id": 74537009, "author": "Carson", "author_id": 4930913, "author_profile": "https://Stackoverflow.com/users/4930913", "pm_score": 2, "selected": true, "text": "static malloc(size) free free struct ticket char name[MAX_NAME_LEN] get_input(int max_len, char * buffer) malloc free" }, { "answer_id": 74537011, "author": "Bodo", "author_id": 10622916, "author_profile": "https://Stackoverflow.com/users/10622916", "pm_score": 2, "selected": false, "text": "get_input static char s[110]; new_ticket.name = get_input(20); s get_input strcpy strdup malloc strcpy new_ticket.name = strdup(get_input(20));\n strdup free strdup const char *s1;\n char *s2;\n/* ... */\n\n s1 = get_input(20);\n s2 = malloc(strlen(s1) + 1);\n if(s2 == NULL)\n {\n /* handle error */\n }\n else\n {\n strcpy(s2, s1);\n }\n new_ticket.name = s2;\n malloc strcpy struct ticket\n {\n int priority;\n int number;\n char name[20];\n char problem[100];\n char assigned_to[20];\n char status[10];\n };\n\n/* ... */\n strcpy(new_ticket.name, get_input(sizeof(new_ticket.name));\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17142491/" ]
74,536,926
<p>I am making a cloudformation template to create a lambda with its permissions. I need to access a specific s3 bucket and I am placing its specific arn, however when I execute the lambda it tells me that it does not have permission to access that bucket (getObject), but if I put the almost full name of the s3 arn only that I put a * at the end, if it lets me access the files in that bucket.</p> <p>Bucket name: bucket-test-impl</p> <pre><code>LambdaSSMPermissions: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Principal: Service: - lambda.amazonaws.com Action: - sts:AssumeRole Policies: - PolicyName: allowSsmS3 PolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Action: - ssm:PutParameters - ssm:PutParameter - s3:GetObject Resource: - arn:aws:s3:::bucket-test-* //THIS WORKS - arn:aws:s3:::bucket-test-impl //IT DOESN'T WORK AND IT'S THE ONE I NEED, - !Sub 'arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:parameter/abcd/*/*' ManagedPolicyArns: - 'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole' </code></pre>
[ { "answer_id": 74537009, "author": "Carson", "author_id": 4930913, "author_profile": "https://Stackoverflow.com/users/4930913", "pm_score": 2, "selected": true, "text": "static malloc(size) free free struct ticket char name[MAX_NAME_LEN] get_input(int max_len, char * buffer) malloc free" }, { "answer_id": 74537011, "author": "Bodo", "author_id": 10622916, "author_profile": "https://Stackoverflow.com/users/10622916", "pm_score": 2, "selected": false, "text": "get_input static char s[110]; new_ticket.name = get_input(20); s get_input strcpy strdup malloc strcpy new_ticket.name = strdup(get_input(20));\n strdup free strdup const char *s1;\n char *s2;\n/* ... */\n\n s1 = get_input(20);\n s2 = malloc(strlen(s1) + 1);\n if(s2 == NULL)\n {\n /* handle error */\n }\n else\n {\n strcpy(s2, s1);\n }\n new_ticket.name = s2;\n malloc strcpy struct ticket\n {\n int priority;\n int number;\n char name[20];\n char problem[100];\n char assigned_to[20];\n char status[10];\n };\n\n/* ... */\n strcpy(new_ticket.name, get_input(sizeof(new_ticket.name));\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19882964/" ]
74,536,930
<p>I found this formula on this website that helps me out with one of my columns on a google sheet I'm working on.</p> <p>=transpose(split(REPT(concat(JOIN(&quot;,&quot;,SEQUENCE(1,6)),&quot;,&quot;),ROUNDDOWN(ROWS(E3:E)/6)),&quot;,&quot;,true))</p> <p>Another column I need to make does exactly this, but each number is repeated 6 times before moving on to the next number. ie. 111111222222333333444444555555111111222222333333444444555555 etc.</p> <p>How would I go about doing this? Any help is appreciated!</p>
[ { "answer_id": 74537009, "author": "Carson", "author_id": 4930913, "author_profile": "https://Stackoverflow.com/users/4930913", "pm_score": 2, "selected": true, "text": "static malloc(size) free free struct ticket char name[MAX_NAME_LEN] get_input(int max_len, char * buffer) malloc free" }, { "answer_id": 74537011, "author": "Bodo", "author_id": 10622916, "author_profile": "https://Stackoverflow.com/users/10622916", "pm_score": 2, "selected": false, "text": "get_input static char s[110]; new_ticket.name = get_input(20); s get_input strcpy strdup malloc strcpy new_ticket.name = strdup(get_input(20));\n strdup free strdup const char *s1;\n char *s2;\n/* ... */\n\n s1 = get_input(20);\n s2 = malloc(strlen(s1) + 1);\n if(s2 == NULL)\n {\n /* handle error */\n }\n else\n {\n strcpy(s2, s1);\n }\n new_ticket.name = s2;\n malloc strcpy struct ticket\n {\n int priority;\n int number;\n char name[20];\n char problem[100];\n char assigned_to[20];\n char status[10];\n };\n\n/* ... */\n strcpy(new_ticket.name, get_input(sizeof(new_ticket.name));\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20574691/" ]
74,536,936
<p>I am attempting to generate all combinations of special characters and numbers around a string. For example, suppose the string is 'notebook' and the special characters are @, #, $, %, &amp; and numbers 0-9. This could generate: $#notebook12, notebook8, @5notebook0&amp;. I am assuming no repeats of characters.</p> <p>Thanks in advance.</p> <p>So far I can only generate:</p> <pre><code>special = ['@','#','$','%','&amp;',' ',0,1,2,3,4,5,6,7,8,9,' '] choice = list(permutations(special, 2)) word = ['notebook'] pw_choice = word + choice test = list(permutations(pw_choice, 2)) print(test) </code></pre> <p>But this results in a list of list that I would have to manipulate further. Is there an easier work around to produce the set of _ _ notebook _ _ ?</p>
[ { "answer_id": 74537110, "author": "Bhargav", "author_id": 15358800, "author_profile": "https://Stackoverflow.com/users/15358800", "pm_score": 1, "selected": false, "text": "import itertools\nspecial = ['@','#','$','%','&',' ',0,1,2,3,4,5,6,7,8,9,' ']\nlis=[]\n\nword = ['notebook']\nword = ''.join(word)\n\n\nfor comb in itertools.combinations(special, 4):\n first = str(comb[0])+str(comb[1])\n last = str(comb[2])+str(comb[3])\n\n \n final =f'{first}{word}{last}'\n if final.startswith(\"@\"):\n pass\n else:\n \n lis.append(final)\n\n\nprint(lis)\n 2380 combination\n @ 1820 combination\n" }, { "answer_id": 74537305, "author": "Riccardo Bucco", "author_id": 5296106, "author_profile": "https://Stackoverflow.com/users/5296106", "pm_score": 3, "selected": true, "text": "from itertools import combinations, permutations\n\nresult = [\n ''.join(p)\n for n_chars in range(len(special) + 1)\n for chars in combinations(special, n_chars)\n for p in permutations(('notebook',) + chars)\n]\n special = ['@','#','$'] ['notebook', 'notebook@', '@notebook', 'notebook#', '#notebook',\n 'notebook$', '$notebook', 'notebook@#', 'notebook#@',\n '@notebook#', '@#notebook', '#notebook@', '#@notebook',\n 'notebook@$', 'notebook$@', '@notebook$', '@$notebook',\n '$notebook@', '$@notebook', 'notebook#$', 'notebook$#',\n '#notebook$', '#$notebook', '$notebook#', '$#notebook',\n 'notebook@#$', 'notebook@$#', 'notebook#@$', 'notebook#$@',\n 'notebook$@#', 'notebook$#@', '@notebook#$', '@notebook$#',\n '@#notebook$', '@#$notebook', '@$notebook#', '@$#notebook',\n '#notebook@$', '#notebook$@', '#@notebook$', '#@$notebook',\n '#$notebook@', '#$@notebook', '$notebook@#', '$notebook#@',\n '$@notebook#', '$@#notebook', '$#notebook@', '$#@notebook']\n from itertools import combinations\n\nresult = [\n f'{\"{}\"*b}notebook{\"{}\"*a}'.format(*c)\n for b in range(3)\n for a in range(3)\n for c in combinations(special, a + b)\n]\n special = ['@','#','$'] ['notebook', 'notebook@', 'notebook#', 'notebook$', 'notebook@#',\n 'notebook@$', 'notebook#$', '@notebook', '#notebook', '$notebook',\n '@notebook#', '@notebook$', '#notebook$', '@notebook#$',\n '@#notebook', '@$notebook', '#$notebook', '@#notebook$']\n" }, { "answer_id": 74537341, "author": "S.B", "author_id": 13944524, "author_profile": "https://Stackoverflow.com/users/13944524", "pm_score": 2, "selected": false, "text": "r permutations from itertools import permutations\nfrom time import sleep\n\n\ndef generate_word(word: str):\n numbers_and_symbols = list(\"0123456789\") + list(\"@#$%&\")\n\n templates = (\n (f\"{{}}{word}\", f\"{word}{{}}\"), # 1 item\n (f\"{{}}{word}{{}}\", f\"{word}{{}}{{}}\", f\"{{}}{{}}{word}\"), # 2 items\n (f\"{{}}{{}}{word}{{}}\", f\"{{}}{word}{{}}{{}}\"), # 3 items\n (f\"{{}}{{}}{word}{{}}{{}}\",), # 4 items\n )\n\n for i in range(1, 5):\n for t in permutations(numbers_and_symbols, r=i):\n for string in templates[i-1]:\n yield string.format(*t)\n sleep(0.05)\n\n\nfor i in generate_word(\"notebook\"):\n print(i)\n" }, { "answer_id": 74538593, "author": "wwii", "author_id": 2823755, "author_profile": "https://Stackoverflow.com/users/2823755", "pm_score": 2, "selected": false, "text": "import itertools\n\nq = ['@', '#', '$', '%', '&',0,1,2,3,4,5,6,7,8,9]\nword = 'notebook'\nresults = []\n# one at a time\nfor c in q:\n results.append(f'{c}{word}')\n results.append(f'{word}{c}')\n\nfor a,b in itertools.combinations(q,2):\n results.append(f'{a}{b}{word}')\n results.append(f'{word}{a}{b}')\n results.append(f'{a}{word}{b}')\n \nfor a,b,c in itertools.combinations(q,3):\n results.append(f'{a}{b}{word}{c}')\n results.append(f'{a}{word}{b}{c}')\n\nfor a,b,c,d in itertools.combinations(q,4):\n results.append(f'{a}{b}{word}{c}{d}')\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74536936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18216824/" ]
74,537,021
<p>I am wondering how I can make a function execute such as making a text box appear when &quot;Yes&quot; option is clicked. How can I do this as the Yes is part of a radio input type in JS? I prefer an answer in vanilla javascript. It would help a lot! Thank You!</p> <p><strong>JavaScript</strong></p> <pre><code> document.querySelector(&quot;label[for=ediet]&quot;).style.opacity = &quot;100%&quot;; //RIGHT document.getElementById(&quot;edietq&quot;).style.opacity = &quot;100%&quot;; } function init( ) { var f = document.getElementsByName(&quot;form1&quot;); f[0].addEventListener(&quot;submit&quot;, validateForm); var yes = document.querySelector(&quot;label[for=ediet]&quot;); yes.addEventListener(&quot;click&quot;, yesClicked); var showT = document.getElementById(&quot;edietq&quot;); showT.addEventListener(&quot;click&quot;, yesClicked); } window.onload = init; ``` **HTML** </code></pre> <pre><code>&lt;input type=&quot;radio&quot; id=&quot;yes&quot; name=&quot;option&quot;&gt; &lt;label for=&quot;yes&quot; id=&quot;yesq&quot; value = &quot;option&quot;&gt;Yes&lt;/label&gt;&lt;br&gt;&lt;br&gt; &lt;input type=&quot;radio&quot; id=&quot;no&quot; name=&quot;option&quot;&gt; &lt;label for=&quot;No&quot;&gt;No&lt;/label&gt;&lt;br&gt;&lt;br&gt; &lt;label for=&quot;ediet&quot;&gt;If yes, explain your dietary restrictions&lt;/label&gt;&lt;br&gt; &lt;input type=&quot;text&quot; id=&quot;edietq&quot; name=&quot;edietq&quot;&gt;&lt;br&gt;&lt;br&gt; &lt;!-- Explain Diet--&gt; </code></pre>
[ { "answer_id": 74537391, "author": "Bianca Emi", "author_id": 18670309, "author_profile": "https://Stackoverflow.com/users/18670309", "pm_score": 2, "selected": false, "text": ".hide{\n display: none\n}\n <input type=\"text\" id=\"edietText\" class=\"hide\" name=\"edietq\">\n const yesInput = document.getElementById(\"yes\")\n\nyesInput.addEventListener(\"click\", yesClicked);\n\nfunction yesClicked(){\n let textExp = document.getElementById(\"edietText\");\n textExp.classList.remove('hide');\n}\n const yesInput = document.getElementById(\"yes\");\nconst noInput = document.getElementById(\"no\");\nconst textExp = document.getElementById(\"edietText\");\n\nyesInput.addEventListener(\"click\", yesClicked);\n\nnoInput.addEventListener(\"click\", noClicked);\n\nfunction yesClicked(){\n textExp.classList.remove('hide');\n}\nfunction noClicked(){\n textExp.classList.add('hide');\n}\n const yesInput = document.getElementById(\"yes\");\nconst noInput = document.getElementById(\"no\");\nconst textExp = document.getElementById(\"edietText\");\n\nyesInput.addEventListener(\"click\", yesClicked);\n\nnoInput.addEventListener(\"click\", noClicked);\n\nfunction yesClicked(){\n textExp.classList.remove('hide');\n}\nfunction noClicked(){\n textExp.classList.add('hide');\n} .hide{\n display: none\n} <input type=\"radio\" id=\"yes\" name=\"option\">\n\n<label for=\"yes\" id=\"yesq\" value = \"option\">Yes</label>\n<br><br>\n<input type=\"radio\" id=\"no\" name=\"option\">\n<label for=\"no\">No</label><br><br>\n<label for=\"ediet\">If yes, explain your dietary restrictions</label><br> \n <input type=\"text\" id=\"edietText\" class=\"hide\" name=\"edietq\">\n<br><br> <!-- Explain Diet-->" }, { "answer_id": 74537458, "author": "Unclebigay", "author_id": 7953084, "author_profile": "https://Stackoverflow.com/users/7953084", "pm_score": 1, "selected": true, "text": "onclick document.getElementById(\"dark\").addEventListener(\"click\", (e) => {\n console.log(e.target.id)\n document.body.style.background = \"black\"\n document.body.style.color = \"white\"\n});\n\ndocument.getElementById(\"light\").addEventListener(\"click\", (e) => {\n console.log(e.target.id)\n document.body.style.background = \"white\"\n document.body.style.color = \"black\"\n}); <label>Toggle Dark Mode</label>\n<input type=\"radio\" name=\"theme\" id=\"dark\" />\n\n<label>Toggle Light Mode</label>\n<input type=\"radio\" name=\"theme\" id=\"light\" />" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10173306/" ]
74,537,045
<p>When I insert lines into <code>file.json</code>, git also counts the old line as deleted. For example, inserting <code>&quot;foo2&quot;: &quot;bar2&quot;</code> into line 2:</p> <pre><code>old 1 { 2 &quot;foo1&quot;: &quot;bar1&quot; 3 } new 1 { 2 &quot;foo2&quot;: &quot;bar2&quot; 3 &quot;foo1&quot;: &quot;bar1&quot; 4 } </code></pre> <p>When I run the following, filtering out only the lines starting with <code>-</code> and <code>+</code>:</p> <pre><code>git diff -U0 ..origin/main -- path/to/file.json | grep '^[+-][^+-]'' </code></pre> <p>This is the result:</p> <pre><code>- &quot;foo1&quot;: &quot;bar1&quot; + &quot;foo2&quot;: &quot;bar2&quot; + &quot;foo1&quot;: &quot;bar1&quot; </code></pre> <p>I get that this is how git is intended to work, but is there a way where I can filter out or avoid the old lines showing up as deleted ? I need to find only the lines that were deleted, and not replaced by insertion.</p>
[ { "answer_id": 74537707, "author": "Klox", "author_id": 850332, "author_profile": "https://Stackoverflow.com/users/850332", "pm_score": 1, "selected": false, "text": "git diff -w" }, { "answer_id": 74543554, "author": "quetzalcoatl", "author_id": 717732, "author_profile": "https://Stackoverflow.com/users/717732", "pm_score": 0, "selected": false, "text": ", -w -w diff" }, { "answer_id": 74550783, "author": "prshnth23", "author_id": 13586005, "author_profile": "https://Stackoverflow.com/users/13586005", "pm_score": 0, "selected": false, "text": ", bar1 foo1 foo2" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9030977/" ]
74,537,055
<p>My company implemented Privileged Identity Management and I'm trying to make my life a bit easier by requesting a role straight from a Powershell script. I'm logging in with <s>Connect-AzureAD</s> Connect-MGGraph but it doesn't ask for my MFA which is a requirement to request a role assignement (and that's good thing, too). Yes, I want this to run interactively!</p> <p>I've read through this guys post but it requires setting up an application registration which is completely stupid: <a href="http://www.anujchaudhary.com/2020/02/connect-to-azure-ad-powershell-with-mfa.html" rel="nofollow noreferrer">http://www.anujchaudhary.com/2020/02/connect-to-azure-ad-powershell-with-mfa.html</a></p> <p>There must be a way to request a login with MFA through Powershell/Microsoft Graph without having to create an app registration. Anybody have any idea?</p> <p><strong>edit</strong>: removed my script because I learned that the AzureAD Powershell Module's days are numbered. Trying the same thing through Microsoft Graph but I still need to force MFA on the session:</p> <blockquote> <p>To run this request, the calling user must have multi-factor authentication (MFA) enforced, and running the query in a session in which they were challenged for MFA - (<a href="https://learn.microsoft.com/en-us/graph/api/rbacapplication-post-roleassignmentschedulerequests?view=graph-rest-beta&amp;tabs=powershell#example-2-user-activating-their-eligible-role" rel="nofollow noreferrer">Source</a>)</p> </blockquote>
[ { "answer_id": 74537707, "author": "Klox", "author_id": 850332, "author_profile": "https://Stackoverflow.com/users/850332", "pm_score": 1, "selected": false, "text": "git diff -w" }, { "answer_id": 74543554, "author": "quetzalcoatl", "author_id": 717732, "author_profile": "https://Stackoverflow.com/users/717732", "pm_score": 0, "selected": false, "text": ", -w -w diff" }, { "answer_id": 74550783, "author": "prshnth23", "author_id": 13586005, "author_profile": "https://Stackoverflow.com/users/13586005", "pm_score": 0, "selected": false, "text": ", bar1 foo1 foo2" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15330939/" ]
74,537,078
<p>After <a href="https://storybook.js.org/docs/react/get-started/install" rel="noreferrer">installing and configuring Storybook</a> on my Next.js application and running <code>build-storybook</code> I am receiving the following error.</p> <p><em>Note</em>: I am using npm version <code>8.19.1</code>. The project is written in Typescript.</p> <pre><code>&gt; msun@0.1.0 storybook:build &gt; build-storybook info @storybook/react v6.5.13 info info =&gt; Cleaning outputDir: /Users/msun/Documents/msun/storybook-static info =&gt; Loading presets info =&gt; Compiling manager.. info =&gt; Compiling preview.. info Addon-docs: using MDX1 info =&gt; Using PostCSS preset with postcss@8.4.19 info =&gt; Using default Webpack5 setup ERR! =&gt; Failed to build the preview ERR! Module not found: Error: Can't resolve '/Users/msun/Documents/msun/generated-stories-entry.cjs' in '/Users/msun/Documents/msun' 65% building 14/14 entries 18/18 dependencies 2/6 modulesinfo =&gt; Manager built (7.26 s) ERR! ModuleNotFoundError: Module not found: Error: Can't resolve '/Users/msun/Documents/msun/generated-stories-entry.cjs' in '/Users/msun/Documents/msun' ERR! at /Users/msun/Documents/msun/node_modules/webpack/lib/Compilation.js:2016:28 ERR! at /Users/msun/Documents/msun/node_modules/webpack/lib/NormalModuleFactory.js:798:13 ERR! at eval (eval at create (/Users/msun/Documents/msun/node_modules/webpack/node_modules/tapable/lib/HookCodeFactory.js:33:10), &lt;anonymous&gt;:10:1) ERR! at /Users/msun/Documents/msun/node_modules/webpack/lib/NormalModuleFactory.js:270:22 ERR! at eval (eval at create (/Users/msun/Documents/msun/node_modules/webpack/node_modules/tapable/lib/HookCodeFactory.js:33:10), &lt;anonymous&gt;:9:1) ERR! at /Users/msun/Documents/msun/node_modules/webpack/lib/NormalModuleFactory.js:434:22 ERR! at /Users/msun/Documents/msun/node_modules/webpack/lib/NormalModuleFactory.js:116:11 ERR! at /Users/msun/Documents/msun/node_modules/webpack/lib/NormalModuleFactory.js:670:25 ERR! at /Users/msun/Documents/msun/node_modules/webpack/lib/NormalModuleFactory.js:855:8 ERR! at /Users/msun/Documents/msun/node_modules/webpack/lib/NormalModuleFactory.js:975:5 ERR! ModuleNotFoundError: Module not found: Error: Can't resolve '/Users/msun/Documents/msun/generated-stories-entry.cjs' in '/Users/msun/Documents/msun' ERR! at /Users/msun/Documents/msun/node_modules/webpack/lib/Compilation.js:2016:28 ERR! at /Users/msun/Documents/msun/node_modules/webpack/lib/NormalModuleFactory.js:798:13 ERR! at eval (eval at create (/Users/msun/Documents/msun/node_modules/webpack/node_modules/tapable/lib/HookCodeFactory.js:33:10), &lt;anonymous&gt;:10:1) ERR! at /Users/msun/Documents/msun/node_modules/webpack/lib/NormalModuleFactory.js:270:22 ERR! at eval (eval at create (/Users/msun/Documents/msun/node_modules/webpack/node_modules/tapable/lib/HookCodeFactory.js:33:10), &lt;anonymous&gt;:9:1) ERR! at /Users/msun/Documents/msun/node_modules/webpack/lib/NormalModuleFactory.js:434:22 ERR! at /Users/msun/Documents/msun/node_modules/webpack/lib/NormalModuleFactory.js:116:11 ERR! at /Users/msun/Documents/msun/node_modules/webpack/lib/NormalModuleFactory.js:670:25 ERR! at /Users/msun/Documents/msun/node_modules/webpack/lib/NormalModuleFactory.js:855:8 ERR! at /Users/msun/Documents/msun/node_modules/webpack/lib/NormalModuleFactory.js:975:5 ERR! resolve '/Users/msun/Documents/msun/generated-stories-entry.cjs' in '/Users/msun/Documents/msun' ERR! using description file: /Users/msun/Documents/msun/package.json (relative path: .) ERR! Field 'browser' doesn't contain a valid alias configuration ERR! root path /Users/msun/Documents/msun ERR! using description file: /Users/msun/Documents/msun/package.json (relative path: ./Users/msun/Documents/msun/generated-stories-entry.cjs) ERR! no extension ERR! Field 'browser' doesn't contain a valid alias configuration ERR! /Users/msun/Documents/msun/Users/msun/Documents/msun/generated-stories-entry.cjs doesn't exist ERR! .mjs ERR! Field 'browser' doesn't contain a valid alias configuration ERR! /Users/msun/Documents/msun/Users/msun/Documents/msun/generated-stories-entry.cjs.mjs doesn't exist ERR! .js ERR! Field 'browser' doesn't contain a valid alias configuration ERR! /Users/msun/Documents/msun/Users/msun/Documents/msun/generated-stories-entry.cjs.js doesn't exist ERR! .jsx ERR! Field 'browser' doesn't contain a valid alias configuration ERR! /Users/msun/Documents/msun/Users/msun/Documents/msun/generated-stories-entry.cjs.jsx doesn't exist ERR! .ts ERR! Field 'browser' doesn't contain a valid alias configuration ERR! /Users/msun/Documents/msun/Users/msun/Documents/msun/generated-stories-entry.cjs.ts doesn't exist ERR! .tsx ERR! Field 'browser' doesn't contain a valid alias configuration ERR! /Users/msun/Documents/msun/Users/msun/Documents/msun/generated-stories-entry.cjs.tsx doesn't exist ERR! .json ERR! Field 'browser' doesn't contain a valid alias configuration ERR! /Users/msun/Documents/msun/Users/msun/Documents/msun/generated-stories-entry.cjs.json doesn't exist ERR! .cjs ERR! Field 'browser' doesn't contain a valid alias configuration ERR! /Users/msun/Documents/msun/Users/msun/Documents/msun/generated-stories-entry.cjs.cjs doesn't exist ERR! as directory ERR! /Users/msun/Documents/msun/Users/msun/Documents/msun/generated-stories-entry.cjs doesn't exist ERR! using description file: /Users/msun/Documents/msun/package.json (relative path: ./generated-stories-entry.cjs) ERR! no extension ERR! Field 'browser' doesn't contain a valid alias configuration ERR! /Users/msun/Documents/msun/generated-stories-entry.cjs doesn't exist ERR! .mjs ERR! Field 'browser' doesn't contain a valid alias configuration ERR! /Users/msun/Documents/msun/generated-stories-entry.cjs.mjs doesn't exist ERR! .js ERR! Field 'browser' doesn't contain a valid alias configuration ERR! /Users/msun/Documents/msun/generated-stories-entry.cjs.js doesn't exist ERR! .jsx ERR! Field 'browser' doesn't contain a valid alias configuration ERR! /Users/msun/Documents/msun/generated-stories-entry.cjs.jsx doesn't exist ERR! .ts ERR! Field 'browser' doesn't contain a valid alias configuration ERR! /Users/msun/Documents/msun/generated-stories-entry.cjs.ts doesn't exist ERR! .tsx ERR! Field 'browser' doesn't contain a valid alias configuration ERR! /Users/msun/Documents/msun/generated-stories-entry.cjs.tsx doesn't exist ERR! .json ERR! Field 'browser' doesn't contain a valid alias configuration ERR! /Users/msun/Documents/msun/generated-stories-entry.cjs.json doesn't exist ERR! .cjs ERR! Field 'browser' doesn't contain a valid alias configuration ERR! /Users/msun/Documents/msun/generated-stories-entry.cjs.cjs doesn't exist ERR! as directory ERR! /Users/msun/Documents/msun/generated-stories-entry.cjs doesn't exist info =&gt; Loading presets npm notice npm notice New major version of npm available! 8.19.1 -&gt; 9.1.2 npm notice Changelog: https://github.com/npm/cli/releases/tag/v9.1.2 npm notice Run npm install -g npm@9.1.2 to update! npm notice </code></pre>
[ { "answer_id": 74539085, "author": "mario_sunny", "author_id": 2301287, "author_profile": "https://Stackoverflow.com/users/2301287", "pm_score": 4, "selected": true, "text": "enhanced-resolve install enchanced-resolve 5.10.0 package.json node_modules // package.json\n{\n \"overrides\": {\n \"enhanced-resolve\": \"5.10.0\"\n }\n}\n npm install -g npm@latest // package.json\n{\n \"resolutions\": {\n \"enhanced-resolve\": \"5.10.0\"\n }\n}\n // package.json\n{\n \"pnpm\": {\n \"overrides\": {\n \"enhanced-resolve\": \"5.10.0\"\n }\n }\n}\n warning Resolution field \"enhanced-resolve@5.10.0\" is incompatible with requested version \"enhanced-resolve@x.y.z\" enhanced-resolve \"webpack@5/enhanced-resolve\": \"5.10.0\"\n" }, { "answer_id": 74541985, "author": "Egbert Ganadhi", "author_id": 16875718, "author_profile": "https://Stackoverflow.com/users/16875718", "pm_score": 0, "selected": false, "text": "npm i enhanced-resolve@5.10.0" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2301287/" ]
74,537,085
<p>I am trying to run a Xamarin.Forms application where the <code>.Core</code> project is <code>.NET Standard 2.0</code>. I'm using Visual Studio 2022 and this is the first time I've run a Xamarin solution.</p> <p>The <code>nnn.Core</code> project does not build and gives a series of identical compilation errors</p> <blockquote> <p>CS0656 Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create'</p> </blockquote> <p>When I first ran into this error, I did some searching and discovered <a href="https://mikaelkoskinen.net/post/net-core-standard-missing-compiler-required-member" rel="nofollow noreferrer">this post</a> which states</p> <blockquote> <p>To fix it I had to include I just had to include Microsoft.CSharp from Nuget.</p> </blockquote> <p>So, I opened the project's <code>.csproj</code> file, which is the file containing the line</p> <pre><code>&lt;TargetFramework&gt;netstandard2.0&lt;/TargetFramework&gt; </code></pre> <p>I found the <code>ItemGroup</code> containing the <code>PackageReference</code> elements, so added</p> <pre><code>&lt;PackageReference Include=&quot;Microsoft.CSharp&quot; Version=&quot;4.7.0&quot; /&gt; </code></pre> <p>Rebuilding the solution took the number of errors from ~9 to 4, but the same errors persist. What's strange is that they are just a subset of the original errors, as if only some lines in the <code>.Core</code> project were fixed by the package inclusion, and some were not. Yet, all the lines throwing the build error are in the same project.</p> <p>The first line throwing the build error above is the assignment to a <code>dymamic</code> property (second line):</p> <pre><code>dynamic values = new JObject(); values.LANGUAGE = _localize.GetCurrentCultureInfo().TwoLetterISOLanguageName.ToUpper(); </code></pre> <p>In fact, all the lines still throwing the error are the first line following the creation of a <code>dynamic</code> object, where a property is assigned.</p> <p>What am I missing to fix this?</p> <p><strong>EDIT</strong></p> <p>Specifically, the Android project has a <code>packages.config</code> file which contains</p> <pre><code>&lt;package id=&quot;Microsoft.CSharp&quot; version=&quot;4.7.0&quot; targetFramework=&quot;monoandroid90&quot; /&gt; </code></pre> <p>The iOS project's <code>packages.config</code> file also has</p> <pre><code>&lt;package id=&quot;Microsoft.CSharp&quot; version=&quot;4.7.0&quot; targetFramework=&quot;xamarinios10&quot; /&gt; </code></pre>
[ { "answer_id": 74539085, "author": "mario_sunny", "author_id": 2301287, "author_profile": "https://Stackoverflow.com/users/2301287", "pm_score": 4, "selected": true, "text": "enhanced-resolve install enchanced-resolve 5.10.0 package.json node_modules // package.json\n{\n \"overrides\": {\n \"enhanced-resolve\": \"5.10.0\"\n }\n}\n npm install -g npm@latest // package.json\n{\n \"resolutions\": {\n \"enhanced-resolve\": \"5.10.0\"\n }\n}\n // package.json\n{\n \"pnpm\": {\n \"overrides\": {\n \"enhanced-resolve\": \"5.10.0\"\n }\n }\n}\n warning Resolution field \"enhanced-resolve@5.10.0\" is incompatible with requested version \"enhanced-resolve@x.y.z\" enhanced-resolve \"webpack@5/enhanced-resolve\": \"5.10.0\"\n" }, { "answer_id": 74541985, "author": "Egbert Ganadhi", "author_id": 16875718, "author_profile": "https://Stackoverflow.com/users/16875718", "pm_score": 0, "selected": false, "text": "npm i enhanced-resolve@5.10.0" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/71376/" ]
74,537,101
<p>I have a Spring Boot application which is using Spring Cloud function to expose the functions as an end points. Currently we are using angular application as a consumer of the functions from the spring boot application. When we call the end point using httpClient module in angular, Its showing CORS error. I have tried different Bean configuration to enable the cors.</p> <h2>Spring Boot App:</h2> <pre><code>@CrossOrigin(&quot;*&quot;) -&gt; This did not work @SpringBootApplication public class CloudFunctionApplication { public static void main(String[] args) { SpringApplication.run(CloudFunctionApplication.class, args); } @Bean public Function&lt;String, String&gt; reverseString() { return value -&gt; new StringBuilder(value).reverse().toString(); } @Bean --&gt; This did not work public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping(&quot;/greeting-javaconfig&quot;).allowedOrigins(&quot;*&quot;); } }; } } </code></pre> <h2>Angular Application.</h2> <pre><code>@Injectable() export class HttpService { constructor(private http: Http) { } getReverseStr(): Observable&lt;Response&gt; { const body = {&quot;code&quot;: 123} return this.http.post(&quot;http://localhost:8080/reverseString&quot;, body); --&gt; Giving cors error } } </code></pre> <p>It would be great If some one could help to resolve CORS issue</p>
[ { "answer_id": 74539085, "author": "mario_sunny", "author_id": 2301287, "author_profile": "https://Stackoverflow.com/users/2301287", "pm_score": 4, "selected": true, "text": "enhanced-resolve install enchanced-resolve 5.10.0 package.json node_modules // package.json\n{\n \"overrides\": {\n \"enhanced-resolve\": \"5.10.0\"\n }\n}\n npm install -g npm@latest // package.json\n{\n \"resolutions\": {\n \"enhanced-resolve\": \"5.10.0\"\n }\n}\n // package.json\n{\n \"pnpm\": {\n \"overrides\": {\n \"enhanced-resolve\": \"5.10.0\"\n }\n }\n}\n warning Resolution field \"enhanced-resolve@5.10.0\" is incompatible with requested version \"enhanced-resolve@x.y.z\" enhanced-resolve \"webpack@5/enhanced-resolve\": \"5.10.0\"\n" }, { "answer_id": 74541985, "author": "Egbert Ganadhi", "author_id": 16875718, "author_profile": "https://Stackoverflow.com/users/16875718", "pm_score": 0, "selected": false, "text": "npm i enhanced-resolve@5.10.0" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2098379/" ]
74,537,126
<p>I want to surround each of the following array items with the <code>^</code> sign like this:</p> <pre><code>const signs = [',', '!!', '?!', '!?', '...', '..', '.', '?', '؟!', '!؟', '!', '؟', ':']; const input = 'this is, a text?' // this is the desired result : 'this is ^,^ a text ^?^' </code></pre> <p>as you see if there is no space between the item and the word next to it a space should be added too.</p> <p>I used a complex function to do this but I think this could be done easily with regex too.</p> <p>How would you do this ?</p> <p>here is the function (which still is in development ):</p> <pre><code>function modifySelectedPortion(e) { const translateSigns = translationInput.value.split(' ').filter(s =&gt; acceptedSigns.includes(s)); if(translateSigns.length) { console.log(translateSigns); } const selectionEnd = translationInput.selectionEnd; const selectionStart = translationInput.selectionStart; const color = e.target.dataset.color; if(!color) return; const signs = { blue: '|', red: '$', orange: '^', purple: '#', green: '~', quote: '@', braket: 'braket', pranthesis: 'pranthesis' }; if(color == 'none') return reset(); if(color == 'copy') return copy(); const signA = color == 'bracket' ? '[ ' : color == 'pranthesis' ? '( ' : signs[color]; const signB = color == 'bracket' ? ' ]' : color == 'pranthesis' ? ' )' : signs[color]; const point = translationInput.value[selectionEnd - 1]; const increase = ['bracket', 'pranthesis'].includes(color) ? 2 : 1; // const start = translationInput.selectionStart; const finish = point == ' ' ? selectionEnd + increase - 1: selectionEnd + increase; const textStart = translationInput.value; translationInput.value = textStart.substring(0, selectionStart) + signA + textStart.substring(selectionStart); const textFinish = translationInput.value; translationInput.value = textFinish.substring(0, finish) + signB + textFinish.substring(finish); translationInputPreview(); function reset() { for(let key of Object.keys(signs)) { translationInput.value = translationInput.value.replaceAll(signs[key], ''); } translationInputPreview(); } function copy() { translationInput.value = getCookie('translate-input') || ''; translationInputPreview(); } } </code></pre>
[ { "answer_id": 74537269, "author": "hudy9x", "author_id": 17752111, "author_profile": "https://Stackoverflow.com/users/17752111", "pm_score": 0, "selected": false, "text": "const input = 'this is, a text? are you happy !! haha';\nconst regex = /(!!|,|\\?\\?)/g\nconsole.log(input.replaceAll(regex, \"^$1^\"))\n// output: this is^,^ a text? are you happy ^!!^ haha\n (!!|,|\\?\\?) !! , ?? | [',', '!!', '?!', '!?', '...', '..', '.', '?', '؟!', '!؟', '!', '؟', ':'] |" }, { "answer_id": 74537294, "author": "V Maharajh", "author_id": 1495198, "author_profile": "https://Stackoverflow.com/users/1495198", "pm_score": 0, "selected": false, "text": "signs const pattern = /,|\\?/ ? \"this is, a text?\".replace(pattern, x => '^' + x + '^')\n 'this is^,^ a text^?^'" }, { "answer_id": 74537300, "author": "Konrad", "author_id": 5089567, "author_profile": "https://Stackoverflow.com/users/5089567", "pm_score": 1, "selected": false, "text": "const signs = [',', '!!', '?!', '!?', '...', '..', '.', '?', '؟!', '!؟', '!', '؟', ':'];\n\nconst input = 'this is, a text?'\n\nconst str = signs.map(e => e.replace(/\\?/g, '\\\\?').replace(/\\./g, '\\\\.')).join('|')\n\nconst regex = new RegExp(` ?(${str}) ?`, 'g')\n\nconst result = input.replace(regex, ' ^$1^ ').trim()\n\nconsole.log(result)" }, { "answer_id": 74546868, "author": "Rohìt Jíndal", "author_id": 4116300, "author_profile": "https://Stackoverflow.com/users/4116300", "pm_score": 0, "selected": false, "text": "signs String.replaceAll() const signs = [',', '!!', '?!', '!?', '...', '..', '.', '?', '؟!', '!؟', '!', '؟', ':'];\n\nlet input = 'this is, a text?';\n\nsigns.forEach(c => input = input.replaceAll(c, ` ^${c}^`));\n\nconsole.log(input);" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10715551/" ]
74,537,174
<p>I have a structure that gets rendered via <code>template</code>. e.g.:</p> <pre><code>type Foo struct { Created time.Time ... } </code></pre> <p>I pass this value to a template, and I'd like to this rendered see:</p> <pre><code> Created at 2022-11-22 9:50 (0d1h12m34s ago) </code></pre> <p>Displaying the timestamp (and formatting it) is easy enough, but I can't find a way to calculate the interval.</p> <pre><code>Created at {{.Created}} ({{???}} ago) </code></pre> <p>In go, this would be accomplished by <code>time.Since(foo.Created)</code> which returns a <code>Duration</code>, and then I can convert duration to string in various ways.</p> <p>But doing the calculation in the template itself does not seem possible:</p> <pre><code>function &quot;time&quot; not defined </code></pre> <p>Or is it? Can't find any information that explicitly tells me that <code>time</code> (or other arbitrary functions) are never ever allowed in templates. So I don't know if I'm just calling it wrong.</p> <p>(I know I could create a new <code>FooTemplateValue</code> from a <code>Foo</code> add that field, so the template can render the duration as-is. I was just trying to avoid it if I can and use the actual object as-is).</p>
[ { "answer_id": 74537278, "author": "rrossmiller", "author_id": 16762798, "author_profile": "https://Stackoverflow.com/users/16762798", "pm_score": -1, "selected": false, "text": "package main\n\nimport (\n \"fmt\"\n \"time\"\n)\n\ntype Foo struct {\n Created time.Time\n // ...\n}\n\nfunc main() {\n x := Foo{Created: time.Now()}\n\n fmt.Println(time.Since(x.Created))\n}\n" }, { "answer_id": 74537629, "author": "mkopriva", "author_id": 965900, "author_profile": "https://Stackoverflow.com/users/965900", "pm_score": 2, "selected": true, "text": "template.FuncMap template.New(\"\").Funcs(template.FuncMap{\n \"dur_until_now\": func(t time.Time) time.Duration {\n return time.Now().Sub(t)\n },\n}).Parse(`{{ dur_until_now .Created }}`)\n type MyTime struct{ time.Time }\n\nfunc (t MyTime) DurUntilNow() time.Duration {\n return time.Now().Sub(t.Time)\n}\n\n// ...\n.Parse(`{{ .Created.DurUntilNow }}`)\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/185478/" ]
74,537,192
<p>How can I get rid of the nested lists and only keep the first element of each list in <code>ColumnB</code>?</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ColumnA</th> <th>ColumnB</th> </tr> </thead> <tbody> <tr> <td>first</td> <td>c(1, 2, 3)</td> </tr> <tr> <td>second</td> <td>c(4, 5, 6)</td> </tr> <tr> <td>third</td> <td>c(7, 8, 9)</td> </tr> </tbody> </table> </div> <p>It should look like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ColumnA</th> <th>ColumnB</th> </tr> </thead> <tbody> <tr> <td>first</td> <td>1</td> </tr> <tr> <td>second</td> <td>4</td> </tr> <tr> <td>third</td> <td>7</td> </tr> </tbody> </table> </div> <p>In <a href="/questions/tagged/python" class="post-tag" title="show questions tagged &#39;python&#39;" aria-label="show questions tagged &#39;python&#39;" rel="tag" aria-labelledby="python-container">python</a>, I would try it with a lambda function giving me only the first element of the list.</p>
[ { "answer_id": 74537204, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 3, "selected": true, "text": "map list first library(dplyr)\nlibrary(purrr)\ndf1 %>%\n mutate(ColumnB = map_dbl(ColumnB, first))\n # A tibble: 3 × 2\n ColumnA ColumnB\n <chr> <dbl>\n1 first 1\n2 second 4\n3 third 7\n base R sapply list df1$ColumnB <- sapply(df1$ColumnB, `[`, 1)\n df1 <- structure(list(ColumnA = c(\"first\", \"second\", \"third\"), ColumnB = list(\n c(1, 2, 3), c(4, 5, 6), c(7, 8, 9))), class = c(\"tbl_df\", \n\"tbl\", \"data.frame\"), row.names = c(NA, -3L))\n" }, { "answer_id": 74537272, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 2, "selected": false, "text": "library(tidyr)\nlibrary(dplyr)\n\ndf1 %>% \n unnest(ColumnB) %>% \n group_by(ColumnA) %>% \n slice(1)\n ColumnA ColumnB\n <chr> <dbl>\n1 first 1\n2 second 4\n3 third 7\n library(dplyr)\nlibrary(readr)\ndf %>% \n mutate(ColumnB = parse_number(ColumnB))\n ColumnA ColumnB\n1 first 1\n2 second 4\n3 third 7\n" }, { "answer_id": 74537387, "author": "M--", "author_id": 6461462, "author_profile": "https://Stackoverflow.com/users/6461462", "pm_score": 2, "selected": false, "text": "dplyr library(dplyr)\n\ndf1 %>% \n rowwise() %>% \n mutate(ColumnB = ColumnB[1]) %>%\n ungroup()\n #> # A tibble: 3 x 2\n#> ColumnA ColumnB\n#> <chr> <dbl>\n#> 1 first 1\n#> 2 second 4\n#> 3 third 7\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19985847/" ]
74,537,209
<p>I have a very large vector in which I want to add the total number of elements as a condition that repeat numbers do not characterize a new element, for example:</p> <pre><code>V=[0,5,1,8,9,1,1,] </code></pre> <p>My desired answer would be:5</p> <p>But I can't think of a way to do that because with the count function I would have to know all the elements of my vector.</p> <p>count function not works in this case</p>
[ { "answer_id": 74538555, "author": "PierU", "author_id": 14778592, "author_profile": "https://Stackoverflow.com/users/14778592", "pm_score": 0, "selected": false, "text": "integer function count_unique(x) result(n)\nimplicit none\ninteger, intent(in) :: x(:)\ninteger, allocatable :: y(:)\n\ny = x(:)\nn = 0\ndo while (size(y) > 0)\n n = n+1\n y = pack(y,mask=(y(:) /= y(1)) ! drops all elements that are \n ! equals to the 1st one (included)\nend do\n\nend function count_unique\n \n" }, { "answer_id": 74575593, "author": "lastchance", "author_id": 19767229, "author_profile": "https://Stackoverflow.com/users/19767229", "pm_score": 1, "selected": false, "text": "module treemodule\n implicit none\n\n private\n public numDistinct\n\n type Node\n integer value\n type(Node), pointer :: left => null(), right => null()\n end type node\n\n type, public :: Tree\n private\n type(Node), pointer :: root => null()\n integer :: size = 0\n contains\n procedure insert\n procedure clear\n procedure print\n procedure getsize\n procedure, private :: insertNode\n procedure, private :: deleteNode\n procedure, private :: printNode\n end type Tree\n\ncontains\n integer function numDistinct( A )\n integer, intent(in) :: A(:)\n integer i\n type(Tree) T\n numDistinct = 3\n do i = 1, size( A )\n call T%insert( A(i) )\n end do\n numDistinct = T%getsize()\n ! Comment out the following if you don't need it ...\n write( *, \"(A)\", advance=\"no\" ) \"Distinct elements: \"; call T%print; write( *, * )\n call T%clear\n end function numDistinct\n\n integer function getsize( this )\n class(Tree) this\n getsize = this%size\n end function getsize\n\n subroutine insert( this, value )\n class(Tree) this\n integer, intent(in) :: value\n call this%insertNode( this%root, value )\n end subroutine insert\n\n subroutine print( this )\n class(Tree) this\n call this%printNode( this%root )\n end subroutine print\n\n subroutine clear( this )\n class(Tree) this\n call this%deleteNode( this%root )\n end subroutine clear\n\n recursive subroutine insertNode( this, ptr, value )\n class(Tree) this\n type(Node), pointer, intent(inout) :: ptr\n integer value\n if ( associated( ptr ) ) then\n if ( value < ptr%value ) then\n call this%insertNode( ptr%left, value )\n else if ( value > ptr%value ) then\n call this%insertNode( ptr%right, value )\n end if\n else\n allocate( ptr, source=Node(value) )\n this%size = this%size + 1\n end if\n end subroutine insertNode\n\n recursive subroutine deleteNode( this, ptr )\n class(Tree) this\n type(Node), pointer, intent(inout) :: ptr\n if ( associated( ptr ) ) then\n call this%deleteNode( ptr%left )\n call this%deleteNode( ptr%right )\n deallocate( ptr )\n this%size = this%size - 1\n end if\n end subroutine deleteNode\n\n recursive subroutine printNode( this, ptr )\n class(Tree) this\n type(Node), pointer, intent(in) :: ptr\n if ( associated( ptr ) ) then\n call this%printNode( ptr%left )\n write ( *, \"( i0, 1x )\", advance=\"no\" ) ptr%value\n call this%printNode( ptr%right )\n end if\n end subroutine printNode\n\nend module treemodule\n\n!=======================================================================\n\nprogram main\n use treemodule\n implicit none\n integer, allocatable :: A(:)\n integer C\n\n A = [ 0, 5, 1, 8, 9, 1, 1 ]\n C = numDistinct( A )\n write( *, \"( 'Number of distinct elements = ', i0 )\" ) C\n\nend program main\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20574940/" ]
74,537,222
<p>In pytest, I would like to capture, for example, the result of something like <code>assert a==b</code> in a variable. Any idea how do I do that?</p> <pre><code>var = assert fruit1 == fruit2 </code></pre> <p>does not capture the assert value in var.</p> <p>Thanks in advance!</p> <p>Tried</p> <pre><code>var = assert fruit1 == fruit2 </code></pre> <p>Expecting the value of assert (true or false) to be captured so that I can post the result to database.</p>
[ { "answer_id": 74537457, "author": "psychicesp", "author_id": 13741789, "author_profile": "https://Stackoverflow.com/users/13741789", "pm_score": 0, "selected": false, "text": "var = fruit1 == fruit2\n\nassert var\n def add_to_database(expression, con = \"default_file.txt\"):\n # not sure what database you're appending to so I'm going to write to text file.\n with open(con, 'a') as db:\n db.write(str(expression))\n return expression\n\nassert add_to_database(fruit_1 == fruit_2)\n\n def log_assert(expression, error_text = \"\"):\n try:\n assert expression, error_text\n except AssertionError as error:\n print(f\"AssertionError: {error_text}\") # replace print with whatever function writes to your database of errors\n raise error\n\nfruit_1 = 'apple'\nfruit_2 = 'Apple.'\n\nlog_assert(fruit_1 == fruit_2, \"Not equal\")\n\n def log_assert_equal(var1, var2):\n log_assert(var1 == var2, f\"{var1} is not equal to {var2}\")\n\nlog_assert_equal(fruit_1, fruit_2) \n" }, { "answer_id": 74538161, "author": "C-3PO", "author_id": 4667669, "author_profile": "https://Stackoverflow.com/users/4667669", "pm_score": 2, "selected": true, "text": "Walrus operator assert (var := (fruit1 == fruit2))\nprint('var = ', var)\n# output: var = True # otherwise, the code would have already crashed :)\n if-statements" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13138241/" ]
74,537,227
<p>I have this setup:</p> <pre><code>ID T Date 2 T2 2022-11-18 3 T1 2022-11-21 </code></pre> <p>and in the main fact table there are deals with ID 2 and 3.</p> <p>Date is an attribute and appears, and works correctly, as a slicer in a pivot table in Excel. T is also an attribute, not visible, purely for the calculated members.</p> <p>I created a Calculated Member and it doesn't work:</p> <pre><code>([Date].[T].&amp;[T2], [Measures].[Notional_SUM]) </code></pre> <p>However a check/test using ID does:</p> <pre><code>([Date].[ID].&amp;[2], [Measures].[Notional_SUM]) </code></pre> <p>obviously this works as 2 is actually in the fact table but what have I forgotten such that using T does not work?</p> <p>I want to be able to use T as there'll always be T1 and T2 dates but I may not always know the ID (auto- generated by the SQL script rolling the dates).</p> <p>***EDIT - After testing in Excel I realised that the one I thought does not work actually does if Date is removed from the slicer/top setup.</p> <p>So obviously the top/slicer is a WHERE on just that date meaning my calculated member</p> <pre><code>([Date].[T].&amp;[T2], [Measures].[Notional_SUM]) </code></pre> <p>does not 'find' any T2 in the data it sees.</p> <p>So how can I have a Calculated Member that always shows the T2 data?</p> <p>I'm constructing an SSAS copy of an existing in-memory Java OLAP cube which does this and I have to ensure all dims/measures are the same.</p> <p>Thanks</p> <p>Leigh tilleytech.com</p>
[ { "answer_id": 74537457, "author": "psychicesp", "author_id": 13741789, "author_profile": "https://Stackoverflow.com/users/13741789", "pm_score": 0, "selected": false, "text": "var = fruit1 == fruit2\n\nassert var\n def add_to_database(expression, con = \"default_file.txt\"):\n # not sure what database you're appending to so I'm going to write to text file.\n with open(con, 'a') as db:\n db.write(str(expression))\n return expression\n\nassert add_to_database(fruit_1 == fruit_2)\n\n def log_assert(expression, error_text = \"\"):\n try:\n assert expression, error_text\n except AssertionError as error:\n print(f\"AssertionError: {error_text}\") # replace print with whatever function writes to your database of errors\n raise error\n\nfruit_1 = 'apple'\nfruit_2 = 'Apple.'\n\nlog_assert(fruit_1 == fruit_2, \"Not equal\")\n\n def log_assert_equal(var1, var2):\n log_assert(var1 == var2, f\"{var1} is not equal to {var2}\")\n\nlog_assert_equal(fruit_1, fruit_2) \n" }, { "answer_id": 74538161, "author": "C-3PO", "author_id": 4667669, "author_profile": "https://Stackoverflow.com/users/4667669", "pm_score": 2, "selected": true, "text": "Walrus operator assert (var := (fruit1 == fruit2))\nprint('var = ', var)\n# output: var = True # otherwise, the code would have already crashed :)\n if-statements" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/669774/" ]
74,537,236
<p>I have a table that contains a varchar column which is indexed. The values in this column consist of a prefix and an incrementing number value. It is not necessary the values will be in order.</p> <pre><code>ABC00010 ABC00011 ABC00015 ABC00012 ABC00017 ABC00016 and so on... </code></pre> <p>There may be missing values in the sequence. How can I find the smallest number available for insert?</p> <p>I wrote this and it works. But it takes a few seconds when the numbers are in the thousands.</p> <pre><code>Declare @C int = 1; While Exists(Select 1 From MyTable Where Col='ABC'+Format(@C,'00000')) Set @C=@C+1; Select 'Next Number: ABC'+Format(@C,'00000'); </code></pre> <p>Is there a faster way?</p>
[ { "answer_id": 74537542, "author": "Tim Jarosz", "author_id": 2452207, "author_profile": "https://Stackoverflow.com/users/2452207", "pm_score": 2, "selected": false, "text": "TOP 1 RIGHT JOIN DECLARE @myTable TABLE (\n Col nvarchar(8)\n);\n\nINSERT INTO @myTable\nVALUES ('ABC00001'), ('ABC00002'), ('ABC00005'), ('ABC00003')\n;\n\nWITH x AS (SELECT n FROM (VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) v(n))\n, y as (\n SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) as number\n FROM x ones, x tens, x hundreds, x thousands, x tThousands\n)\n, yMod as (\n SELECT y.number\n , 'ABC' + RIGHT('00000' + CAST(y.number as nvarchar), 5) as Col\n FROM y \n)\nSELECT TOP 1\n ym.Col\nFROM @myTable as mt\n RIGHT OUTER JOIN yMod as ym\n ON ym.Col = mt.Col\nWHERE mt.Col IS NULL\nORDER BY ym.number\n" }, { "answer_id": 74537673, "author": "Olivier Jacot-Descombes", "author_id": 880990, "author_profile": "https://Stackoverflow.com/users/880990", "pm_score": 0, "selected": false, "text": "-- delete\nUPDATE mytable SET deleted = 1 WHERE id = @id;\n -- find record to be reused.\nSELECT MIN(Col) FROM mytable WHERE deleted = 1\n" }, { "answer_id": 74538450, "author": "John Cappelletti", "author_id": 1570000, "author_profile": "https://Stackoverflow.com/users/1570000", "pm_score": 2, "selected": false, "text": "@Prefix Declare @YourTable Table ([Col] varchar(50)) Insert Into @YourTable Values \n ('ABC00010')\n,('ABC00011')\n,('ABC00015')\n,('ABC00012')\n,('ABC00017')\n,('ABC00016')\n\nDeclare @Prefix varchar(25)='ABC'\n\n-- Show Just the Next Value\nSelect distinct NextValue = min(@Prefix+right(concat('00000',try_convert(int,substring(max(Col),len(@Prefix)+1,25))+1),5)) over()\n From (\n Select *\n ,Grp = try_convert(int,substring(Col,len(@Prefix)+1,25)) -row_number() over(order by Col)\n From @YourTable\n Where Col like @Prefix+'%'\n ) A \n Group By Grp\n\n\n\n-- Show All Next Values \nSelect R1=min(Col)\n ,R2=max(Col)\n ,NextValue = left(max(Col),3)+right(concat('00000',try_convert(int,substring(max(Col),len(@Prefix)+1,25))+1),5)\n From (\n Select *\n ,Grp = try_convert(int,substring(Col,len(@Prefix)+1,25)) -row_number() over(order by Col)\n From @YourTable\n Where Col like @Prefix+'%'\n ) A \n Group By Grp\n" }, { "answer_id": 74539566, "author": "Jeff", "author_id": 15394900, "author_profile": "https://Stackoverflow.com/users/15394900", "pm_score": 1, "selected": false, "text": "Declare @testData table (Col varchar(20));\n Insert Into @testData (Col)\n Values ('ABC00001'), ('ABC00002'), ('ABC00012'), ('ABC00013')\n , ('XYZ00002'), ('XYZ00003'), ('XYZ00010'), ('XYX00012');\n\nDeclare @prefix char(3) = 'XYZ';\n\n With gaps\n As (\n Select *\n , grp = v.inc - row_number() Over(Order By v.inc)\n From @testData As td\n Cross Apply (Values (replace(td.Col, @prefix, ''))) As v(inc)\n Where td.Col Like @prefix + '%'\n )\n Select Top 1\n next_value = concat(@prefix, right(concat('00000', max(g.inc) + 1), 5))\n From gaps As g\n Group By\n g.grp\n Order By\n next_value;\n" }, { "answer_id": 74568496, "author": "J.D.", "author_id": 5059085, "author_profile": "https://Stackoverflow.com/users/5059085", "pm_score": 1, "selected": false, "text": "WHERE SUBSTRING() ROW_NUMBER() WITH _ColNumbers AS\n(\n SELECT\n CONVERT(INT, SUBSTRING(Col, 4, LEN(Col) - 3)) AS ColNumber, -- Strip out the prefix and convert the remaining numerical part to an integer \n FROM MyTable\n WHERE Col LIKE 'ABC%'\n),\n_ColNumbersSorted AS\n(\n SELECT \n ColNumber,\n ROW_NUMBER() OVER (ORDER BY ColNumber) AS SortId -- Generate a sequential set of integers in the same order as ColNumber\n FROM _ColNumbers\n),\n_ColNumberLowestUnmatchedSortId AS\n(\n SELECT TOP 1 -- Return the single lowest mismatch\n ColNumber,\n SortId\n FROM _ColNumbersSorted\n WHERE ColNumber <> SortId -- Filter down to only the rows that don't match their ColNumber to their SortId\n ORDER BY SortId -- Sort by the lowest SortId (aka lowest mismatch)\n)\n\n-- Join back to the list of all ColNumbers to get the row just before the lowest mismatch\n-- The lowest available number is 1 more than the previous row's ColNumber\nSELECT \n CNS.ColNumber + 1 AS LowestAvailableNumber \nFROM _ColNumbersSorted AS CNS\nINNER JOIN _ColNumberLowestUnmatchedSortId AS CNLUSI\n ON CNS.SortId = CNLUSI.SortId - 1;\n CONVERT(INT, SUBSTRING(Col, 4, LEN(Col) - 3)) ALTER MyTable\nADD CONVERT(INT, SUBSTRING(Col, 4, LEN(Col) - 3)) AS ColNumber;\n\nCREATE NONCLUSTERED INDEX IX_MyTable_Col_ColNumber ON MyTable (Col, ColNumber);\n WITH _ColNumbersSorted AS\n(\n SELECT \n ColNumber,\n ROW_NUMBER() OVER (ORDER BY ColNumber) AS SortId -- Generate a sequential set of integers in the same order as ColNumber\n FROM MyTable\n WHERE Col LIKE 'ABC%'\n),\n_ColNumberLowestUnmatchedSortId AS\n(\n SELECT TOP 1 -- Return the single lowest mismatch\n ColNumber,\n SortId\n FROM _ColNumbersSorted\n WHERE ColNumber <> SortId -- Filter down to only the rows that don't match their ColNumber to their SortId\n ORDER BY SortId -- Sort by the lowest SortId (aka lowest mismatch)\n)\n\n-- Join back to the list of all ColNumbers to get the row just before the lowest mismatch\n-- The lowest available number is 1 more than the previous row's ColNumber\nSELECT \n CNS.ColNumber + 1 AS LowestAvailableNumber \nFROM _ColNumbersSorted AS CNS\nINNER JOIN _ColNumberLowestUnmatchedSortId AS CNLUSI\n ON CNS.SortId = CNLUSI.SortId - 1;\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1057202/" ]
74,537,246
<p>After installing the following NuGet packages:</p> <ul> <li>cef.redist.x64</li> <li>CefSharp.Common</li> <li>CefSharp.Wpf</li> </ul> <p>And following the following video tutorial: <a href="https://www.youtube.com/watch?v=qputn1dogHU&amp;ab_channel=CodingDotNET" rel="nofollow noreferrer">How to make a Cefsharp Web Browser in WPF C#</a>, adding an app manifest file and uncommenting the Windows 10 key.</p> <p>Then, referencing the <code>CefSharp</code> component in the Xaml window header: <code>xmlns:cef=&quot;clr-namespace:CefSharp.Wpf;assembly=CefSharp.Wpf&quot;</code>.</p> <p>Following these steps, the tag <code>&lt;cef:ChromiumWebBrowser Address=&quot;https://google.ca&quot; Height=&quot;400&quot; Width=&quot;400&quot;/&gt;</code> should construct the browser element. Instead, the following error appears, signaling that Xaml line:</p> <blockquote> <p>Unknown build error, '<strong>Could not find assembly 'CefSharp</strong>, Version=107.1.90.0 ...' <strong>Either explicitly load this assembly using a method such as LoadFromAssemblyPath() or use a MetadataAssemblyResolver that returns a valid assembly.</strong></p> </blockquote> <p>Visual Studio suggests adding a reference to the <code>CefSharp</code> library, but clicking on this suggestion always fails for whatever reason.</p> <p>By <a href="https://github.com/cefsharp/CefSharp/wiki/Quick-Start" rel="nofollow noreferrer">consulting the documentation, one can find a minimal running example</a>. Yet, the quickstart example didn't even work for me (build errors and such).</p> <p>By consulting answers on StackOverflow, <a href="https://stackoverflow.com/a/54126898/4682228">it would appear that the correct Visual C++ Redistributable installation is required</a>, and that not having this installed could cause referencing issues. This did not solve the problem for me.</p> <p>I also tried changing build values, build configurations, uncommenting certain lines in the configuration file, and consulted documentation and other questions on StackOverflow. None of them mentioned having the exact error.</p>
[ { "answer_id": 74537247, "author": "Denis G. Labrecque", "author_id": 4682228, "author_profile": "https://Stackoverflow.com/users/4682228", "pm_score": -1, "selected": false, "text": "C:\\Users\\username\\.nuget" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4682228/" ]
74,537,251
<p>I'm trying to implement a function that will count how many 'n' of rooks can there be in a chess board of 'n' size without colliding in a position that can be attacked by another rook. I have used as a base a 4*4 grid. I'm struggling with the concept to create the array and how to proceed with the recursion (it has to be done with recursion as per exercise request). My recursion is a mess and i still don't know how to fill the array in shape of <code>[ | | | ]</code> x4.</p> <p>I've looked a lot, and this is the Queens problem (just the rooks for now) but still I don't know how to proceed. there are plenty of solutions out there, but none of them require to return a factorial integer (I have tried factorial approach and it works, but is not what the exercise need). Debug shows that <code>solutions</code> never gets updated and when <code>n</code> becomes less than one it enters an infinite loop.</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 calc (size) { // should be incremented each time a rook is placed let rooks = 0; // should increment and let solutions = 0; // where the array should populated ...? const board = []; function recursively (n) { // if size becomes smaller than 1 stop recursion? while (n &gt; 1) { // update solution var? solutions += n * recursively(n -1); } // increment count of rooks rooks++; // return 0 in case there is a size of 0 return 0; } recursively(size); return solutions; } console.log(calc(4));</code></pre> </div> </div> Be mindful that I'm learning JS at this point. Thank you</p>
[ { "answer_id": 74537325, "author": "ControlAltDel", "author_id": 1291492, "author_profile": "https://Stackoverflow.com/users/1291492", "pm_score": 0, "selected": false, "text": "while (n > 1) {\n // update solution var?\n solutions += n * recursively(n -1);\n}\n" }, { "answer_id": 74548887, "author": "Scott Sauyet", "author_id": 1243641, "author_profile": "https://Stackoverflow.com/users/1243641", "pm_score": 2, "selected": true, "text": "n x n (n - 1) x (n - 1) n x n n const countRooks = (n) => n\n const countRooks = (n) => \n n <= 0\n ? 0 \n : 1 + countRooks (n - 1)\n const ourEmpty4x4Board = [\n {c: 'a', r: 4, v: ' '}, {c: 'b', r: 4, v: ' '}, {c: 'c', r: 4, v: ' '}, {c: 'd', r: 4, v: ' '},\n {c: 'a', r: 3, v: ' '}, {c: 'b', r: 3, v: ' '}, {c: 'c', r: 3, v: ' '}, {c: 'd', r: 3, v: ' '},\n {c: 'a', r: 2, v: ' '}, {c: 'b', r: 2, v: ' '}, {c: 'c', r: 2, v: ' '}, {c: 'd', r: 2, v: ' '},\n {c: 'a', r: 1, v: ' '}, {c: 'b', r: 1, v: ' '}, {c: 'c', r: 1, v: ' '}, {c: 'd', r: 1, v: ' '},\n]\n const ourFilled4x4Board = [\n {c: 'a', r: 4, v: 'R'}, {c: 'b', r: 4, v: ' '}, {c: 'c', r: 4, v: ' '}, {c: 'd', r: 4, v: ' '},\n {c: 'a', r: 3, v: ' '}, {c: 'b', r: 3, v: ' '}, {c: 'c', r: 3, v: 'R'}, {c: 'd', r: 3, v: ' '},\n {c: 'a', r: 2, v: ' '}, {c: 'b', r: 2, v: ' '}, {c: 'c', r: 2, v: ' '}, {c: 'd', r: 2, v: 'R'},\n {c: 'a', r: 1, v: ' '}, {c: 'b', r: 1, v: 'R'}, {c: 'c', r: 1, v: ' '}, {c: 'd', r: 1, v: ' '},\n]\n const ourEmpty4x4Board = [\n [\" \", \" \", \" \", \" \"],\n [\" \", \" \", \" \", \" \"],\n [\" \", \" \", \" \", \" \"],\n [\" \", \" \", \" \", \" \"],\n]\n const ourFilled4x4Board = [\n [\"R\", \" \", \" \", \" \"],\n [\" \", \" \", \"R\", \" \"],\n [\" \", \" \", \" \", \"R\"],\n [\" \", \"R\", \" \", \" \"],\n]\n const createEmptyBoard = (size) =>\n Array .from ({length: size}, () => Array .from ({length: size}, () => ' '))\n\ncreateEmptyBoard (4)\n//=> [[\" \", \" \", \" \", \" \"], [\" \", \" \", \" \", \" \"], [\" \", \" \", \" \", \" \"], [\" \", \" \", \" \", \" \"]]\n +---+---+---+---+\n|♜ | | | |\n+---+---+---+---+\n| | |♜ | |\n+---+---+---+---+\n| |♜ | | |\n+---+---+---+---+\n| | | |♜ |\n+---+---+---+---+\n R···\n··R·\n·R··\n···R\n const addRook = (board, row, col) => {\n const newBoard = board .map ((r) => [...r])\n newBoard [row] [col] = 'R'\n return newBoard\n}\n const createEmptyBoard = (size) =>\n Array .from ({length: size}, () => Array .from ({length: size}, () => ' '))\n\nconst addRook = (board, row, col) => {\n const newBoard = board .map ((r) => [...r])\n newBoard [row] [col] = 'R'\n return newBoard\n}\n\nconst display = (board) => \n board .map (row => row .join ('') .replaceAll (/\\s/g, '·')) .join ('\\n') + '\\n'\n\nconst board = createEmptyBoard (4)\nconsole .log (display (board))\n\nconst oneRook = addRook (board, 1, 2)\nconsole .log (display (oneRook))\n\nconst twoRooks = addRook (oneRook, 3, 3)\nconsole .log (display (twoRooks))\n\nconst threeRooks = addRook (twoRooks, 0, 0)\nconsole .log (display (threeRooks))\n\nconst fourRooks = addRook (threeRooks, 2, 1)\nconsole .log (display (fourRooks)) .as-console-wrapper {max-height: 100% !important; top: 0} ······\n·R····\n······\n····R·\n······\n··R···\n ·*····\n*R****\n·*····\n·*··R·\n·*····\n·*R···\n ·*··*·\n*R****\n·*··*·\n****R*\n·*··*·\n·*R·*·\n ·**·*·\n*R****\n·**·*·\n****R*\n·**·*·\n**R***\n eliminate countRooks = (n) => n n n x n m x n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19153279/" ]
74,537,314
<p>I am new to VBA, and i would need some help in dealing with my data.</p> <p>I want to delete the column if every value it contains are equal to zero</p> <p>I have this so far:</p> <pre><code>Sub delete() Dim FinalCol As Integer FinalCol = Range(&quot;A1&quot;).End(xlToRight).Column For i = FinalCol To 1 Step -1 If Application.WorksheetFunction.Sum(Columns(i)) = 0 Then Columns(i).delete End If Next i End Sub </code></pre> <p>The problem is that in some columns the sum is equal to zero but they don't contain only zeros so I want to keep them.</p> <p>Hope you guys can help me.</p> <p>Thank you.</p>
[ { "answer_id": 74537333, "author": "BigBen", "author_id": 9245853, "author_profile": "https://Stackoverflow.com/users/9245853", "pm_score": 2, "selected": false, "text": "CountIfs Sub delete()\n Dim FinalCol As Long\n FinalCol = Cells(1, Columns.Count).End(xlToLeft).Column\n\n Dim i As Long\n For i = FinalCol To 1 Step -1\n If WorksheetFunction.CountIfs(Columns(i), \"<>0\", Columns(i), \"<>\") = 0 Then\n Columns(i).delete\n End If\n Next i\nEnd Sub\n Union Sub delete()\n Dim FinalCol As Long\n FinalCol = Cells(1, Columns.Count).End(xlToLeft).Column\n\n Dim i As Long\n For i = 1 to FinalCol\n If WorksheetFunction.CountIfs(Columns(i), \"<>0\", Columns(i), \"<>\") = 0 Then\n Dim ToDelete As Range\n If ToDelete Is Nothing Then\n Set ToDelete = Columns(i)\n Else\n Set ToDelete = Union(ToDelete, Columns(i))\n End If\n End If\n Next\n\n If Not ToDelete Is Nothing Then \n ToDelete.Delete\n End If\nEnd Sub\n CountIfs CountA If WorksheetFunction.CountIf(Columns(i), 0) = WorksheetFunction.CountA(Columns(i)) Then\n" }, { "answer_id": 74539929, "author": "VBasic2008", "author_id": 9814069, "author_profile": "https://Stackoverflow.com/users/9814069", "pm_score": 0, "selected": false, "text": "Sub DeleteColumns()\n \n Dim ws As Worksheet: Set ws = ActiveSheet ' improve\n \n Dim srg As Range, Data() As Variant, rCount As Long\n \n With ws.UsedRange\n rCount = .Rows.Count - 1 ' use -1 to exclude headers\n Set srg = .EntireColumn\n Data = .Resize(rCount).Offset(1)\n End With\n \n Dim urg As Range, crg As Range, r As Long, c As Long, ZeroFound As Boolean\n \n For c = 1 To UBound(Data, 2)\n For r = 1 To rCount\n ' Blank cells or cells containing '=\"0\"' are not considered!\n If VarType(Data(r, c)) = vbDouble Then ' is a number\n If Data(r, c) = 0 Then ZeroFound = True\n End If\n If ZeroFound Then ZeroFound = False Else Exit For\n Next r\n If r > rCount Then\n Set crg = srg.Columns(c)\n If urg Is Nothing Then Set urg = crg Else Set urg = Union(urg, crg)\n End If\n Next c\n \n If Not urg Is Nothing Then urg.Delete\n \nEnd Sub\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20564413/" ]
74,537,340
<p>Why is &quot;internal const&quot; being overridden in a child class but &quot;protected const&quot; can't?</p> <p>Sample code:</p> <pre><code> class A { internal const string iStr = &quot;baseI&quot;; protected const string pStr = &quot;baseP&quot;; void foo() { string s = B.iStr; //childI string t = B.pStr; //baseP } } class B : A { internal new const string iStr = &quot;childI&quot;; protected new const string pStr = &quot;childP&quot;; } </code></pre> <p>Expected B.pStr to return &quot;childP&quot;.</p>
[ { "answer_id": 74537520, "author": "Sweeper", "author_id": 5133585, "author_profile": "https://Stackoverflow.com/users/5133585", "pm_score": 4, "selected": true, "text": "pStr B A override B B A B internal const string iStr = \"baseI\";\nprotected const string pStr = \"baseP\";\ninternal new const string iStr = \"childI\";\nprotected new const string pStr = \"childP\";\n B B A new B.iStr B.pStr" }, { "answer_id": 74537527, "author": "Olivier Jacot-Descombes", "author_id": 880990, "author_profile": "https://Stackoverflow.com/users/880990", "pm_score": 1, "selected": false, "text": "B.pStr B B A new" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5844128/" ]
74,537,381
<p>When I change the enumerated type variables from 4 bit to 32 bit, my error is appeased. I am wondering why I cannot keep it at 4 bit in this code.</p> <p>Here are some pertinent snippets; I have deleted code related to non-pertinent variables:</p> <p>Testbench:</p> <pre><code>module ALUtestbench; //Variable Declaration typedef enum {ADD = 32'b00, SUB = 32'b01, INV = 32'b10, RED = 32'b11} opcode_t; opcode_t opcode; //declare typed variable //Module Instance alu alu_inst( .opcode(opcode)); initial begin opcode = opcode.first(); #10; do begin $display(opcode); $display(&quot;For opcode %s the result is: %0h&quot;, opcode.name, result); opcode = opcode.next; #10; end while (opcode != opcode.first); end endmodule </code></pre> <p>Design:</p> <pre><code>module ALU; input reg A [4:0]; inout reg B [4:0]; output reg C [4:0]; initial begin always @ (*) begin case(opcode) ADD : C = A + B; SUB : C = A - B; INV : C = ~A; endcase end endmodule </code></pre> <p>At first, I had</p> <pre><code> typedef enum {ADD = 4'b00, SUB = 4'b01, INV = 4'b10, RED = 4'b11} opcode_t; opcode_t opcode; //declare typed variable </code></pre> <p>and the compiler gave me the error:</p> <blockquote> <p>SystemVerilog requires the width of a sized constant in this context to match the width of the enumeration type.</p> </blockquote> <p>I then changed to 32-bit, and the code now does not have this error. I am wondering why I needed to do that. Does the <code>case</code> statement reject anything less than 32-bit?</p>
[ { "answer_id": 74537520, "author": "Sweeper", "author_id": 5133585, "author_profile": "https://Stackoverflow.com/users/5133585", "pm_score": 4, "selected": true, "text": "pStr B A override B B A B internal const string iStr = \"baseI\";\nprotected const string pStr = \"baseP\";\ninternal new const string iStr = \"childI\";\nprotected new const string pStr = \"childP\";\n B B A new B.iStr B.pStr" }, { "answer_id": 74537527, "author": "Olivier Jacot-Descombes", "author_id": 880990, "author_profile": "https://Stackoverflow.com/users/880990", "pm_score": 1, "selected": false, "text": "B.pStr B B A new" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20575008/" ]
74,537,382
<p>I have a file, which contains strings separated by spaces, tabs and carriage return:</p> <pre><code>one two three four </code></pre> <p>I'm trying to remove all spaces, tabs and carriage return:</p> <pre><code>def txt_cleaning(fname): with open(fname) as f: new_txt = [] fname = f.readline().strip() new_txt += [line.split() for line in f.readlines()] return new_txt </code></pre> <p>Output:</p> <pre><code>[['one'], ['two'], [], ['three'], [], ['four']] </code></pre> <p>Expecting, without importing libraries:</p> <pre><code>['one', 'two', 'three', 'four'] </code></pre>
[ { "answer_id": 74537522, "author": "Johnny Mopp", "author_id": 669576, "author_profile": "https://Stackoverflow.com/users/669576", "pm_score": 3, "selected": true, "text": "def txt_cleaning(fname):\n new_text = []\n with open(fname) as f:\n for line in f.readlines():\n new_text += [s.strip() for s in line.split() if s]\n return new_text\n def txt_cleaning(fname):\n with open(fname) as f:\n return [word.strip() for word in f.read().split() if word]\n" }, { "answer_id": 74539091, "author": "user3435121", "author_id": 3435121, "author_profile": "https://Stackoverflow.com/users/3435121", "pm_score": 0, "selected": false, "text": "def txt_cleaning(fname):\n with open(fname) as f:\n return f.read().replace( '\\t', ' ').replace( '\\n', ' ').split()\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3892557/" ]
74,537,431
<p>I have upgraded from react-navigation 5 to 6:</p> <pre><code>- &quot;@react-navigation/bottom-tabs&quot;: &quot;^5.10.6&quot;, - &quot;@react-navigation/material-top-tabs&quot;: &quot;^5.3.15&quot;, - &quot;@react-navigation/native&quot;: &quot;^5.8.6&quot;, - &quot;@react-navigation/routers&quot;: &quot;^5.6.0&quot;, - &quot;@react-navigation/stack&quot;: &quot;^5.12.3&quot;, - &quot;react-native-gesture-handler&quot;: &quot;1.10.3&quot;, NEW DEPS: + &quot;react-native-gesture-handler&quot;: &quot;^2.7.0&quot;, + &quot;@react-navigation/bottom-tabs&quot;: &quot;^6.2.4&quot;, + &quot;@react-navigation/material-top-tabs&quot;: &quot;^6.3.0&quot;, + &quot;@react-navigation/native&quot;: &quot;^6.0.13&quot;, + &quot;@react-navigation/routers&quot;: &quot;^6.1.3&quot;, + &quot;@react-navigation/stack&quot;: &quot;5.14.9&quot;, </code></pre> <p>After the upgrade I noticed that on Android 8 and 9 some stack screens have some strage feature of closing current screen with swipe from top to bottom.</p> <p>Adding <code>gestureEnabled: false</code> as navigator or screen option doesn't seem to have any effect.</p> <p>Screenshots with close on swipe top to bottom:</p> <p><a href="https://i.stack.imgur.com/CU6g1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CU6g1.png" alt="first image when drag started" /></a></p> <p><a href="https://i.stack.imgur.com/oA8r3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oA8r3.png" alt="second drag image" /></a></p> <p>See attached video: <a href="https://drive.google.com/file/d/1Xt08w7S-bFXcOMx01WAzHGwLvLLwAl7e/view" rel="nofollow noreferrer">https://drive.google.com/file/d/1Xt08w7S-bFXcOMx01WAzHGwLvLLwAl7e/view</a></p>
[ { "answer_id": 74545314, "author": "Solly", "author_id": 4948751, "author_profile": "https://Stackoverflow.com/users/4948751", "pm_score": 2, "selected": true, "text": "ScrollView ScrollView react-native-gesture-handler" }, { "answer_id": 74599088, "author": "Florin Dobre", "author_id": 1979861, "author_profile": "https://Stackoverflow.com/users/1979861", "pm_score": 0, "selected": false, "text": "gestureEnabled: true false screenOptions={{\n gestureEnabled: false\n }}\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1979861/" ]
74,537,453
<p>I saw a code snippet here some time ago that dealt with PowerShell and HTML. An HTML code was passed into a variable. The beginning and the end were delimited with @&quot; and &quot;@. In a response, the @ delimiter was labelled with a specific term. Unfortunately, I did not save the post. Can someone tell me what this '@' delimitation is called and how exactly it is used?</p>
[ { "answer_id": 74537591, "author": "frankM_DN", "author_id": 20034020, "author_profile": "https://Stackoverflow.com/users/20034020", "pm_score": 1, "selected": false, "text": "$html = @\"\n<body>\n <h1>Header 1</h1>\n <p>Paragraph</p>\n</body>\n@\"\n /" }, { "answer_id": 74538094, "author": "Mathias R. Jessen", "author_id": 712649, "author_profile": "https://Stackoverflow.com/users/712649", "pm_score": 1, "selected": true, "text": "@\"\nyour string content goes here\n...\n\nand can span multiple lines!\n\"@\n @\"\n1 + 2 = $(1 + 2)!\n\n... and the Process ID of this host application is ${PID}\n\"@\n # no need to escape quotation marks\n@\"\nThe movie was titled \"Jennifer's body\"\n\"@\n \"The movie was titled `\"Jennifer's body`\"\"\n\"The movie was titled \"\"Jennifer's body\"\"\" # this many double-quotes makes me dizzy\n'The movie was titled \"Jennifer''s body\"'\n about_Quoting_Rules" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10167615/" ]
74,537,476
<p>I have an object called <code>dataLookup</code>, the contents of which are <a href="https://pastebin.com/MG4xB8ht" rel="nofollow noreferrer">https://pastebin.com/MG4xB8ht</a>. This is what one item looks like in it:</p> <pre class="lang-js prettyprint-override"><code> { &quot;key&quot;: &quot;Andaman &amp; Nicobar&quot;, &quot;value&quot;: { &quot;state&quot;: &quot;Andaman &amp; Nicobar&quot;, &quot;fcra_registered&quot;: 8, &quot;total&quot;: 140 } }, </code></pre> <p>I want to access the <code>total</code> value for each <code>key</code> and assign that to a prop in another component. I have this:</p> <pre class="lang-js prettyprint-override"><code>z={(d) =&gt; dataLookup.get(d[&quot;state&quot;])[&quot;total&quot;]} </code></pre> <p>This gives me an error:</p> <pre class="lang-js prettyprint-override"><code>Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'total') </code></pre> <p>What am I doing wrong and how can I fix it?</p> <p>Update: I've added a working REPL of the entire issue. You can see the error in the console. <a href="https://svelte.dev/repl/31462bf121c748feac329590351d4fcc?version=3.53.1" rel="nofollow noreferrer">It is here</a>, the error occurs on line 62.</p>
[ { "answer_id": 74537634, "author": "Prabhu", "author_id": 6080567, "author_profile": "https://Stackoverflow.com/users/6080567", "pm_score": -1, "selected": false, "text": "let list = [{\n \"state\": \"Andaman & Nicobar\",\n \"fcra_registered\": 8,\n \"total\": 140\n}]\n\n let map1 = new Map()\n list.map(item => map1.set(item.state,item.total))\n\nconsole.log(map1.get('Andaman & Nicobar'))\n" }, { "answer_id": 74537822, "author": "Andy", "author_id": 1377002, "author_profile": "https://Stackoverflow.com/users/1377002", "pm_score": 0, "selected": false, "text": "LayerCake Map const dataLookup = arr.map(obj => obj.value);\n <LayerCake\n data={dataLookup}\n // etc\n</LayerCake>\n" }, { "answer_id": 74537838, "author": "Aman", "author_id": 4112751, "author_profile": "https://Stackoverflow.com/users/4112751", "pm_score": 0, "selected": false, "text": "Odisha Orissa ?.[colorKey] [colorKey]" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537476", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4112751/" ]
74,537,484
<p>So, I'm trying to make a grade calculator and I have run into some problems with my JS form table.</p> <p>I'm trying to find a way so that if the user does not type in numbers for all 3 of the b, c, and d values it will still give me the user's class grade.</p> <p>However, when the user is not typing in numbers for all 3 of the b, c, and d values, I'm getting the result of <code>NaN</code>. My program works, when there are numbers in all 3 of the b, c, and d values, but I also want it to work when there isn't.</p> <p><em>Note: I am new to both JS and HTML.</em></p> <p>Here's my code:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function calcGrade() { var a = 0; var b = 0; var c = 0; var d = 0; var e = 0; var f = 0; var g = 0; var h = 0; var z = 0; var cg = 0; var cg1 = 0; var cg2 = 0; var cg3 = 0; var cg4 = 0; var cg5 = 0; var cg6 = 0; var cg7 = 0; var cg8 = 0; //First Row var B1 = parseFloat(document.getElementById("b1").valueAsNumber); var C1 = parseFloat(document.getElementById("c1").valueAsNumber); var D1 = parseFloat(document.getElementById("d1").valueAsNumber); //Second Row var B2 = parseFloat(document.getElementById("b2").valueAsNumber); var C2 = parseFloat(document.getElementById("c2").valueAsNumber); var D2 = parseFloat(document.getElementById("d2").valueAsNumber); //Third Row var B3 = parseFloat(document.getElementById("b3").valueAsNumber); var C3 = parseFloat(document.getElementById("c3").valueAsNumber); var D3 = parseFloat(document.getElementById("d3").valueAsNumber); //Fourth Row var B4 = parseFloat(document.getElementById("b4").valueAsNumber); var C4 = parseFloat(document.getElementById("c4").valueAsNumber); var D4 = parseFloat(document.getElementById("d4").valueAsNumber); //Fifth Row var B5 = parseFloat(document.getElementById("b5").valueAsNumber); var C5 = parseFloat(document.getElementById("c5").valueAsNumber); var D5 = parseFloat(document.getElementById("d5").valueAsNumber); //Sixth Row var B6 = parseFloat(document.getElementById("b6").valueAsNumber); var C6 = parseFloat(document.getElementById("c6").valueAsNumber); var D6 = parseFloat(document.getElementById("d6").valueAsNumber); //Seventh Row var B7 = parseFloat(document.getElementById("b7").valueAsNumber); var C7 = parseFloat(document.getElementById("c7").valueAsNumber); var D7 = parseFloat(document.getElementById("d7").valueAsNumber); //Eigth Row var B8 = parseFloat(document.getElementById("b8").valueAsNumber); var C8 = parseFloat(document.getElementById("c8").valueAsNumber); var D8 = parseFloat(document.getElementById("d8").valueAsNumber); //Calculations a = (((B1) / (C1)) * (D1)); b = (((B2) / (C2)) * (D2)); c = (((B3) / (C3)) * (D3)); d = (((B4) / (C4)) * (D4)); e = (((B5) / (C5)) * (D5)); f = (((B6) / (C6)) * (D6)); g = (((B7) / (C7)) * (D7)); h = (((B8) / (C8)) * (D8)); z = parseFloat(D1) + parseFloat(D2) + parseFloat(D3) + parseFloat(D4) + parseFloat(D5) + parseFloat(D6) + parseFloat(D7) + parseFloat(D8); cg = ((((B1) / (C1)) * (D1)) + (((B2) / (C2)) * (D2)) + (((B3) / (C3)) * (D3)) + (((B4) / (C4)) * (D4)) + (((B5) / (C5)) * (D5)) + (((B6) / (C6)) * (D6)) + (((B7) / (C7)) * (D7)) + h) / (z); if (z &gt; 100) { alert("Error, your weight percentage column is over 100, please make sure it is less than or equal to 100!"); } else { document.getElementById("weight").innerHTML = z; document.getElementById("classGrade").innerHTML = cg; } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;form name="classGradeCalc" action&gt; &lt;table&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;Grading Category&lt;/td&gt; &lt;td&gt;Points Earned&lt;/td&gt; &lt;td&gt;Max Poins&lt;/td&gt; &lt;td&gt;Weight&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;input type="text" size="20" id="a1" value=""&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="number" size="5" id="b1" value="0"&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="number" size="5" id="c1" value="0"&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="number" size="5" id="d1" value="0"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;input type="text" size="20" id="a2" value=""&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="number" size="5" id="b2" value="0"&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="number" size="5" id="c2" value="0"&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="number" size="5" id="d2" value="0"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;input type="text" size="20" id="a3" value=""&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="number" size="5" id="b3" value="0"&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="number" size="5" id="c3" value="0"&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="number" size="5" id="d3" value="0"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;input type="text" size="20" id="a4" value=""&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="number" size="5" id="b4" value="0"&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="number" size="5" id="c4" value="0"&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="number" size="5" id="d4" value="0"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;input type="text" size="20" id="a5" value=""&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="number" size="5" id="b5" value="0"&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="number" size="5" id="c5" value="0"&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="number" size="5" id="d5" value="0"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;input type="text" size="20" id="a6" value=""&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="number" size="5" id="b6" value="0"&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="number" size="5" id="c6" value="0"&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="number" size="5" id="d6" value="0"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;input type="text" size="20" id="a7" value=""&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="number" size="5" id="b7" value="0"&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="number" size="5" id="c7" value="0"&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="number" size="5" id="d7" value="0"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;input type="text" size="20" id="a8" value=""&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="number" size="5" id="b8" value="0"&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="number" size="5" id="c8" value="0"&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="number" size="5" id="d8" value="0"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;input type="button" value="Calculate Grade" onclick="calcGrade()"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;table&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;Class Grade&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;input size="5" name="gca1"&gt;&lt;/td&gt; &lt;td&gt;&lt;input size="5" name="gca2"&gt;&lt;/td&gt; &lt;p id="pointsEarned"&gt;&lt;/p&gt; &lt;p id="maxPoints"&gt;&lt;/p&gt; &lt;p id="weight"&gt;&lt;/p&gt; &lt;p id="classGrade"&gt;&lt;/p&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/form&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74537634, "author": "Prabhu", "author_id": 6080567, "author_profile": "https://Stackoverflow.com/users/6080567", "pm_score": -1, "selected": false, "text": "let list = [{\n \"state\": \"Andaman & Nicobar\",\n \"fcra_registered\": 8,\n \"total\": 140\n}]\n\n let map1 = new Map()\n list.map(item => map1.set(item.state,item.total))\n\nconsole.log(map1.get('Andaman & Nicobar'))\n" }, { "answer_id": 74537822, "author": "Andy", "author_id": 1377002, "author_profile": "https://Stackoverflow.com/users/1377002", "pm_score": 0, "selected": false, "text": "LayerCake Map const dataLookup = arr.map(obj => obj.value);\n <LayerCake\n data={dataLookup}\n // etc\n</LayerCake>\n" }, { "answer_id": 74537838, "author": "Aman", "author_id": 4112751, "author_profile": "https://Stackoverflow.com/users/4112751", "pm_score": 0, "selected": false, "text": "Odisha Orissa ?.[colorKey] [colorKey]" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20549635/" ]
74,537,487
<p>I see equivalent operations being done several times in my Matlab code, and I think, there must be a way to condense these and do it all once. In this case it was checking whether some variables were less than a certain epsilon:</p> <pre><code>if abs(beta) &lt; tol beta = 0; end if abs(alpha) &lt; tol alpha = 0; end if abs(gamma) &lt; tol gamma = 0; end </code></pre> <p>I tried combining these into a few lines that deal with the whole boodle,</p> <pre><code>overTol = [alpha,beta,gamma] &gt;= tol; [alpha,beta,gamma] = [alpha,beta,gamma] .* overTol; </code></pre> <p>If this was Python, where a list is a list is a list, that would be fine, but in Matlab, an operation on the right produces one variable on the left except in special situations.</p> <p>After reading <a href="https://stackoverflow.com/questions/5158032/define-multiple-variables-at-the-same-time-in-matlab?noredirect=1&amp;lq=1">Define multiple variables at the same time in MATLAB?</a> and <a href="https://stackoverflow.com/questions/12575027/declare-initialize-variables-in-one-line-in-matlab-without-using-an-array-or-v">Declare &amp; initialize variables in one line in MATLAB without using an array or vector</a>, I tried using <code>deal</code>, but <code>[alpha,beta,gamma] = deal([alpha,beta,gamma] .* overTol);</code> does not distribute the terms of the vector given to the deal function between the terms in the vector on the left, but instead gives a copy of the whole vector to each of the terms.</p> <p>The last thing I want to do is set the right equal to a unique vector and then set alpha, beta, and gamma equal to the terms of that vector, one by one. That's just as ugly as what I started with.</p> <p>Is there an elegant solution to this?</p>
[ { "answer_id": 74537634, "author": "Prabhu", "author_id": 6080567, "author_profile": "https://Stackoverflow.com/users/6080567", "pm_score": -1, "selected": false, "text": "let list = [{\n \"state\": \"Andaman & Nicobar\",\n \"fcra_registered\": 8,\n \"total\": 140\n}]\n\n let map1 = new Map()\n list.map(item => map1.set(item.state,item.total))\n\nconsole.log(map1.get('Andaman & Nicobar'))\n" }, { "answer_id": 74537822, "author": "Andy", "author_id": 1377002, "author_profile": "https://Stackoverflow.com/users/1377002", "pm_score": 0, "selected": false, "text": "LayerCake Map const dataLookup = arr.map(obj => obj.value);\n <LayerCake\n data={dataLookup}\n // etc\n</LayerCake>\n" }, { "answer_id": 74537838, "author": "Aman", "author_id": 4112751, "author_profile": "https://Stackoverflow.com/users/4112751", "pm_score": 0, "selected": false, "text": "Odisha Orissa ?.[colorKey] [colorKey]" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4918319/" ]
74,537,518
<p>I'm trying to implement a class in order to pass the following <strong>test</strong> (Using bytewise operators &amp; and |</p> <pre><code>public void hasFlagTest1() { byte resource = ResourceUtil.getFlag(FLAG_PUBLIC_SECURITY, FLAG_PRIVATE_SECURITY, FLAG_BASIC_LIFE_SUPPORT); Assert.assertTrue(ResourceUtil.hasPublicSecurity(resource)); Assert.assertTrue(ResourceUtil.hasPrivateSecurity(resource)); Assert.assertTrue(ResourceUtil.hasBasicLifeSupport(resource)); Assert.assertFalse(ResourceUtil.hasVolunteers(resource)); Assert.assertFalse(ResourceUtil.hasAllOpts(resource)); } </code></pre> <p>The <strong>constant values</strong> that are passed by parameters are</p> <pre><code>public static final byte FLAG_PRIVATE_SECURITY = 1; public static final byte FLAG_PUBLIC_SECURITY = 2; public static final byte FLAG_BASIC_LIFE_SUPPORT = 4; public static final byte FLAG_VOLUNTEERS = 8; public static final byte FLAG_ALL_OPTS = 15; </code></pre> <p>I have already created a <strong>class</strong> but not sure how to implement all methods in order to make this test pass, here's the class:</p> <p>public class ResourceUtil {</p> <pre><code>public static byte getFlag(byte arg, byte arg2, byte arg3){ return result; //just a value, not implemented }; public static boolean hasPublicSecurity(byte resource) { return true; //just a value, not implemented } public static boolean hasPrivateSecurity(byte resource) { return true; //just a value, not implemented } public static boolean hasBasicLifeSupport(byte resource) { return true; //just a value, not implemented } public static boolean hasVolunteers(byte resource) { return true; //just a value, not implemented } public static boolean hasAllOpts(byte resource) { return true; //just a value, not implemented } </code></pre> <p>}</p> <p>Any idea? I've been trying some</p>
[ { "answer_id": 74537619, "author": "Ben Borchard", "author_id": 4054720, "author_profile": "https://Stackoverflow.com/users/4054720", "pm_score": 1, "selected": false, "text": "public class ResourceUtil {\n\n public static boolean hasPublicSecurity(byte resource) {\n return resource & FLAG_PUBLIC_SECURITY == FLAG_PUBLIC_SECURITY;\n }\n\n public static boolean hasPrivateSecurity(byte resource) {\n return resource & FLAG_PRIVATE_SECURITY == FLAG_PRIVATE_SECURITY;\n }\n\n public static boolean hasBasicLifeSupport(byte resource) {\n return resource & FLAG_BASIC_LIFE_SUPPORT == FLAG_BASIC_LIFE_SUPPORT;\n }\n\n public static boolean hasVolunteers(byte resource) {\n return resource & FLAG_VOLUNTEERS == FLAG_VOLUNTEERS;\n }\n\n public static boolean hasAllOpts(byte resource) {\n return resource & FLAG_ALL_OPTS == FLAG_ALL_OPTS;\n }\n\n}\n getFlags" }, { "answer_id": 74537628, "author": "Yonatan Karp-Rudin", "author_id": 3899765, "author_profile": "https://Stackoverflow.com/users/3899765", "pm_score": 0, "selected": false, "text": "public static boolean hasPublicSecurity(byte resource) {\n return (resource & FLAG_PUBLIC_SECURITY) == FLAG_PUBLIC_SECURITY;\n}\n\npublic static boolean hasPrivateSecurity(byte resource) {\n return (resource & FLAG_PRIVATE_SECURITY) = FLAG_PRIVATE_SECURITY;\n}\n\npublic static boolean hasBasicLifeSupport(byte resource) {\n return (resource & FLAG_BASIC_LIFE_SUPPORT) == FLAG_BASIC_LIFE_SUPPORT;\n}\n\npublic static boolean hasVolunteers(byte resource) {\n return (resource & FLAG_VOLUNTEERS) == FLAG_VOLUNTEERS;\n}\n\npublic static boolean hasAllOpts(byte resource) {\n return (resource & FLAG_ALL_OPTS) == FLAG_ALL_OPTS;\n}\n 111 PUBLIC_SECURITY 111 & 001 == 001\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15416320/" ]
74,537,546
<p>I'm using Airflow airflow-2.3.3 (through GCP Composer)</p> <p>I pass this yaml configuration when deploying my DAG:</p> <pre><code> dag_args: dag_id: FTP_DAILY default_args: owner: 'Dev team' start_date: &quot;00:00:00&quot; max_active_runs: 1 retries: 2 schedule_interval: &quot;0 7 * * *&quot; ftp_conn_id: 'ftp_dev' </code></pre> <p>I want this DAG to run at 7am UTC every morning, but it's not running. In the UI it says next run: <code>2022-11-22, 07:00:00</code> (as of Nov 22nd) and it never runs. How should I configure my <code>start_date</code> and <code>schedule_interval</code> so that the DAG runs at 7am UTC every day, starting from the nearest 7am after the deployment?</p>
[ { "answer_id": 74537619, "author": "Ben Borchard", "author_id": 4054720, "author_profile": "https://Stackoverflow.com/users/4054720", "pm_score": 1, "selected": false, "text": "public class ResourceUtil {\n\n public static boolean hasPublicSecurity(byte resource) {\n return resource & FLAG_PUBLIC_SECURITY == FLAG_PUBLIC_SECURITY;\n }\n\n public static boolean hasPrivateSecurity(byte resource) {\n return resource & FLAG_PRIVATE_SECURITY == FLAG_PRIVATE_SECURITY;\n }\n\n public static boolean hasBasicLifeSupport(byte resource) {\n return resource & FLAG_BASIC_LIFE_SUPPORT == FLAG_BASIC_LIFE_SUPPORT;\n }\n\n public static boolean hasVolunteers(byte resource) {\n return resource & FLAG_VOLUNTEERS == FLAG_VOLUNTEERS;\n }\n\n public static boolean hasAllOpts(byte resource) {\n return resource & FLAG_ALL_OPTS == FLAG_ALL_OPTS;\n }\n\n}\n getFlags" }, { "answer_id": 74537628, "author": "Yonatan Karp-Rudin", "author_id": 3899765, "author_profile": "https://Stackoverflow.com/users/3899765", "pm_score": 0, "selected": false, "text": "public static boolean hasPublicSecurity(byte resource) {\n return (resource & FLAG_PUBLIC_SECURITY) == FLAG_PUBLIC_SECURITY;\n}\n\npublic static boolean hasPrivateSecurity(byte resource) {\n return (resource & FLAG_PRIVATE_SECURITY) = FLAG_PRIVATE_SECURITY;\n}\n\npublic static boolean hasBasicLifeSupport(byte resource) {\n return (resource & FLAG_BASIC_LIFE_SUPPORT) == FLAG_BASIC_LIFE_SUPPORT;\n}\n\npublic static boolean hasVolunteers(byte resource) {\n return (resource & FLAG_VOLUNTEERS) == FLAG_VOLUNTEERS;\n}\n\npublic static boolean hasAllOpts(byte resource) {\n return (resource & FLAG_ALL_OPTS) == FLAG_ALL_OPTS;\n}\n 111 PUBLIC_SECURITY 111 & 001 == 001\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5940480/" ]
74,537,571
<p>I created rdd from CSV lines = sc.textFile(data) now I need to convert lines to key value rdd where value where value will be string (after splitting) and key will be number of column of csv for example CSV</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Col 1</th> <th>Col2</th> </tr> </thead> <tbody> <tr> <td>73</td> <td>230666</td> </tr> <tr> <td>55</td> <td>149610</td> </tr> </tbody> </table> </div> <p>I want to get rdd.take(1): [(1,73), (2, 230666)]</p> <pre><code>I create rdd of lists lines_of_list = lines_data.map(lambda line : line.split(',')) I create function that get list and return list of tuples (key, value) def list_of_tuple (l): list_tup = [] for i in range(len(l[0])): list_tup.append((l[0][i],i)) return(list_tup) But I can’t get the correct result when I try to map this function on RDD </code></pre>
[ { "answer_id": 74537619, "author": "Ben Borchard", "author_id": 4054720, "author_profile": "https://Stackoverflow.com/users/4054720", "pm_score": 1, "selected": false, "text": "public class ResourceUtil {\n\n public static boolean hasPublicSecurity(byte resource) {\n return resource & FLAG_PUBLIC_SECURITY == FLAG_PUBLIC_SECURITY;\n }\n\n public static boolean hasPrivateSecurity(byte resource) {\n return resource & FLAG_PRIVATE_SECURITY == FLAG_PRIVATE_SECURITY;\n }\n\n public static boolean hasBasicLifeSupport(byte resource) {\n return resource & FLAG_BASIC_LIFE_SUPPORT == FLAG_BASIC_LIFE_SUPPORT;\n }\n\n public static boolean hasVolunteers(byte resource) {\n return resource & FLAG_VOLUNTEERS == FLAG_VOLUNTEERS;\n }\n\n public static boolean hasAllOpts(byte resource) {\n return resource & FLAG_ALL_OPTS == FLAG_ALL_OPTS;\n }\n\n}\n getFlags" }, { "answer_id": 74537628, "author": "Yonatan Karp-Rudin", "author_id": 3899765, "author_profile": "https://Stackoverflow.com/users/3899765", "pm_score": 0, "selected": false, "text": "public static boolean hasPublicSecurity(byte resource) {\n return (resource & FLAG_PUBLIC_SECURITY) == FLAG_PUBLIC_SECURITY;\n}\n\npublic static boolean hasPrivateSecurity(byte resource) {\n return (resource & FLAG_PRIVATE_SECURITY) = FLAG_PRIVATE_SECURITY;\n}\n\npublic static boolean hasBasicLifeSupport(byte resource) {\n return (resource & FLAG_BASIC_LIFE_SUPPORT) == FLAG_BASIC_LIFE_SUPPORT;\n}\n\npublic static boolean hasVolunteers(byte resource) {\n return (resource & FLAG_VOLUNTEERS) == FLAG_VOLUNTEERS;\n}\n\npublic static boolean hasAllOpts(byte resource) {\n return (resource & FLAG_ALL_OPTS) == FLAG_ALL_OPTS;\n}\n 111 PUBLIC_SECURITY 111 & 001 == 001\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20573070/" ]
74,537,597
<p>I have an array of strings <code>a</code> that I would like to print like e.g.</p> <pre><code>'a1','a2','a3' </code></pre> <p>where <code>a1 = a[0]</code>, <code>a2 = a[1]</code>, <code>a3 = a[2]</code>.</p> <p>For some reason</p> <pre><code>printformat = '' for i in range(3): printformat+=a[i]+&quot;',&quot; </code></pre> <p>prints instead</p> <pre><code>&quot;a1',a2',a3',&quot; </code></pre>
[ { "answer_id": 74537619, "author": "Ben Borchard", "author_id": 4054720, "author_profile": "https://Stackoverflow.com/users/4054720", "pm_score": 1, "selected": false, "text": "public class ResourceUtil {\n\n public static boolean hasPublicSecurity(byte resource) {\n return resource & FLAG_PUBLIC_SECURITY == FLAG_PUBLIC_SECURITY;\n }\n\n public static boolean hasPrivateSecurity(byte resource) {\n return resource & FLAG_PRIVATE_SECURITY == FLAG_PRIVATE_SECURITY;\n }\n\n public static boolean hasBasicLifeSupport(byte resource) {\n return resource & FLAG_BASIC_LIFE_SUPPORT == FLAG_BASIC_LIFE_SUPPORT;\n }\n\n public static boolean hasVolunteers(byte resource) {\n return resource & FLAG_VOLUNTEERS == FLAG_VOLUNTEERS;\n }\n\n public static boolean hasAllOpts(byte resource) {\n return resource & FLAG_ALL_OPTS == FLAG_ALL_OPTS;\n }\n\n}\n getFlags" }, { "answer_id": 74537628, "author": "Yonatan Karp-Rudin", "author_id": 3899765, "author_profile": "https://Stackoverflow.com/users/3899765", "pm_score": 0, "selected": false, "text": "public static boolean hasPublicSecurity(byte resource) {\n return (resource & FLAG_PUBLIC_SECURITY) == FLAG_PUBLIC_SECURITY;\n}\n\npublic static boolean hasPrivateSecurity(byte resource) {\n return (resource & FLAG_PRIVATE_SECURITY) = FLAG_PRIVATE_SECURITY;\n}\n\npublic static boolean hasBasicLifeSupport(byte resource) {\n return (resource & FLAG_BASIC_LIFE_SUPPORT) == FLAG_BASIC_LIFE_SUPPORT;\n}\n\npublic static boolean hasVolunteers(byte resource) {\n return (resource & FLAG_VOLUNTEERS) == FLAG_VOLUNTEERS;\n}\n\npublic static boolean hasAllOpts(byte resource) {\n return (resource & FLAG_ALL_OPTS) == FLAG_ALL_OPTS;\n}\n 111 PUBLIC_SECURITY 111 & 001 == 001\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2820579/" ]
74,537,598
<p>I am very new at this, so bear with me please.</p> <p>I do this:</p> <pre><code>example= index Date Column_1 Column_2 1 2019-06-17 Car Red 2 2019-08-10 Car Yellow 3 2019-08-15 Truck Yellow 4 2020-08-12 Truck Yellow data = example.groupby([pd.Grouper(freq='Y', key='Date'),'Column_1']).nunique() df1=pd.DataFrame(data) df2 = df1.reset_index(level=['Column_1','Date']) df2 = df2.rename(columns={'Date':'interval_year','Column_2':'Sum'}) </code></pre> <p>In order to get this:</p> <pre><code>df2= index interval_year Column_1 Sum 1 2019-12-31 Car 2 2 2019-12-31 Truck 1 3 2020-12-31 Car 1 </code></pre> <p>I get the expected result but my code gives me a lot of headache. I create 2 additional DataFrames and sometimes, when I get 2 columns with same name (one as index), the code becomes even more complicated.</p> <p>Any solution how to make this more efficient?</p> <p>Thank you</p>
[ { "answer_id": 74537619, "author": "Ben Borchard", "author_id": 4054720, "author_profile": "https://Stackoverflow.com/users/4054720", "pm_score": 1, "selected": false, "text": "public class ResourceUtil {\n\n public static boolean hasPublicSecurity(byte resource) {\n return resource & FLAG_PUBLIC_SECURITY == FLAG_PUBLIC_SECURITY;\n }\n\n public static boolean hasPrivateSecurity(byte resource) {\n return resource & FLAG_PRIVATE_SECURITY == FLAG_PRIVATE_SECURITY;\n }\n\n public static boolean hasBasicLifeSupport(byte resource) {\n return resource & FLAG_BASIC_LIFE_SUPPORT == FLAG_BASIC_LIFE_SUPPORT;\n }\n\n public static boolean hasVolunteers(byte resource) {\n return resource & FLAG_VOLUNTEERS == FLAG_VOLUNTEERS;\n }\n\n public static boolean hasAllOpts(byte resource) {\n return resource & FLAG_ALL_OPTS == FLAG_ALL_OPTS;\n }\n\n}\n getFlags" }, { "answer_id": 74537628, "author": "Yonatan Karp-Rudin", "author_id": 3899765, "author_profile": "https://Stackoverflow.com/users/3899765", "pm_score": 0, "selected": false, "text": "public static boolean hasPublicSecurity(byte resource) {\n return (resource & FLAG_PUBLIC_SECURITY) == FLAG_PUBLIC_SECURITY;\n}\n\npublic static boolean hasPrivateSecurity(byte resource) {\n return (resource & FLAG_PRIVATE_SECURITY) = FLAG_PRIVATE_SECURITY;\n}\n\npublic static boolean hasBasicLifeSupport(byte resource) {\n return (resource & FLAG_BASIC_LIFE_SUPPORT) == FLAG_BASIC_LIFE_SUPPORT;\n}\n\npublic static boolean hasVolunteers(byte resource) {\n return (resource & FLAG_VOLUNTEERS) == FLAG_VOLUNTEERS;\n}\n\npublic static boolean hasAllOpts(byte resource) {\n return (resource & FLAG_ALL_OPTS) == FLAG_ALL_OPTS;\n}\n 111 PUBLIC_SECURITY 111 & 001 == 001\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20575159/" ]
74,537,603
<p>usually I use POST or GET requests except for GET.get paginations, but I don't understand the concept there are only two possibilities POST or GET .</p> <p>example even if there is the same effect I do not understand the difference between <code>request.GET.get('page') and request.GET[&quot;page&quot;] request.POST['rate'] and request.POST.get('rate') </code></p>
[ { "answer_id": 74537661, "author": "Anton Shpigunov", "author_id": 8516606, "author_profile": "https://Stackoverflow.com/users/8516606", "pm_score": 1, "selected": false, "text": "request.POST dict dict d[x] dict x d.get(x, default) KeyError d.get()" }, { "answer_id": 74537719, "author": "ilyasbbu", "author_id": 16475089, "author_profile": "https://Stackoverflow.com/users/16475089", "pm_score": 0, "selected": false, "text": "request.POST['sth'] request.POST.get('sth')" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20575141/" ]
74,537,658
<p>I have a requirement where I need to Restart a set of windows services on a set of hosts sequentially with 60 seconds between service start. Appreciate your help</p> <p>Order of Services</p> <ol> <li>Polling Agent Service</li> </ol> <blockquote> <pre><code> wait 60 seconds then start 2) Memcached wait 30 seconds then start 3) watcher </code></pre> </blockquote>
[ { "answer_id": 74537661, "author": "Anton Shpigunov", "author_id": 8516606, "author_profile": "https://Stackoverflow.com/users/8516606", "pm_score": 1, "selected": false, "text": "request.POST dict dict d[x] dict x d.get(x, default) KeyError d.get()" }, { "answer_id": 74537719, "author": "ilyasbbu", "author_id": 16475089, "author_profile": "https://Stackoverflow.com/users/16475089", "pm_score": 0, "selected": false, "text": "request.POST['sth'] request.POST.get('sth')" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18279293/" ]
74,537,660
<p>I have two parallel datasets <code>dataset1</code> and <code>dataset2</code> and following is my code to load them in parallel using <code>SubsetRandomSampler</code> where I provide <code>train_indices</code> for dataloading.</p> <p>P.S. Even after setting <code>num_workers=0</code> and seeding <code>np</code> as well as <code>torch</code>, the samples do not get loaded in parallel. Any suggestions are heartily welcome including methods other than <code>SubsetRandomSampler</code>.</p> <pre><code>import torch, numpy as np from torch.utils.data import Dataset, DataLoader, SubsetRandomSampler dataset1 = torch.tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) dataset2 = torch.tensor([10, 11, 12, 13, 14, 15, 16, 17, 18, 19]) train_indices = list(range(len(dataset1))) torch.manual_seed(12) np.random.seed(12) np.random.shuffle(train_indices) sampler = SubsetRandomSampler(train_indices) dataloader1 = DataLoader(dataset1, batch_size=2, num_workers=0, sampler=sampler) dataloader2 = DataLoader(dataset2, batch_size=2, num_workers=0, sampler=sampler) for i, (data1, data2) in enumerate(zip(dataloader1, dataloader2)): x = data1 y = data2 print(x, y) </code></pre> <p>Output:</p> <pre><code>tensor([5, 1]) tensor([15, 18]) tensor([0, 2]) tensor([14, 12]) tensor([4, 6]) tensor([16, 10]) tensor([8, 9]) tensor([11, 19]) tensor([7, 3]) tensor([17, 13]) </code></pre> <p>Expected Output:</p> <pre><code>tensor([5, 1]) tensor([15, 11]) tensor([0, 2]) tensor([10, 12]) tensor([4, 6]) tensor([14, 16]) tensor([8, 9]) tensor([18, 19]) tensor([7, 3]) tensor([17, 13]) </code></pre>
[ { "answer_id": 74538074, "author": "Pankaj Chandravanshi", "author_id": 17743521, "author_profile": "https://Stackoverflow.com/users/17743521", "pm_score": 1, "selected": false, "text": "dataset1 dataset1 dataset2 dataset2 dataset1 # combine the two datasets into a single dataset of tuples\ncombined_dataset = list(zip(dataset1, dataset2))\n\n# shuffle the combined dataset\ntrain_indices = list(range(len(combined_dataset)))\nnp.random.seed(12)\nnp.random.shuffle(train_indices)\n\n# create the dataloaders\ndataloader = DataLoader(combined_dataset, batch_size=2, num_workers=0, sampler=SubsetRandomSampler(train_indices))\n\n# unpack the elements from the tuples in each batch\nfor i, (data1, data2) in enumerate(dataloader):\n x = data1\n y = data2\n print(x, y)\n" }, { "answer_id": 74553958, "author": "kkgarg", "author_id": 3306097, "author_profile": "https://Stackoverflow.com/users/3306097", "pm_score": 1, "selected": true, "text": "class MySampler(torch.utils.data.sampler.Sampler):\n def __init__(self, indices):\n self.indices = indices\n \n def __iter__(self):\n return iter(self.indices)\n \n def __len__(self):\n return len(self.indices)\n\n\ndataset1 = torch.tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\ndataset2 = torch.tensor([10, 11, 12, 13, 14, 15, 16, 17, 18, 19])\n\ntrain_indices = list(range(len(dataset1)))\nnp.random.seed(12)\nnp.random.shuffle(train_indices)\n\nsampler = MySampler(train_indices)\n\ndataloader1 = DataLoader(dataset1, batch_size=2, num_workers=0, sampler=sampler)\ndataloader2 = DataLoader(dataset2, batch_size=2, num_workers=0, sampler=sampler)\n\nfor i, (data1, data2) in enumerate(zip(dataloader1, dataloader2)):\n x = data1\n y = data2\n print(x, y)\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3306097/" ]
74,537,662
<p>I need help with creating relations between countries in neo4j using python. I have a code, but in neo4j browser it doesn't create relations.</p> <pre><code>from neo4j import GraphDatabase driver = GraphDatabase.driver(&quot;neo4j://localhost:7687&quot;, auth=(&quot;neo4j&quot;, &quot;test&quot;)) def create_country(tx, name,continent,population_mln,govrm_system,bcountry): tx.run(&quot;CREATE (a:Country {name: $name,continent: $continent,population_mln: $population_mln,govrm_system:$govrm_system,bcountry: $bcountry})&quot;, name=name,continent=continent,population_mln=population_mln,govrm_system=govrm_system,bcountry=bcountry) with driver.session() as session: session.execute_write(create_country, &quot;russia&quot;,&quot;Asia&quot;,143,&quot;terrorist state&quot;,[&quot;Kazakhstan&quot;,&quot;Lithuania&quot;,&quot;Finland&quot;,&quot;China&quot;,&quot;Japan&quot;]) session.execute_write(create_country, &quot;India&quot;,&quot;Asia&quot;,1393,&quot;Parliamentary Republic&quot;,&quot;China&quot;) session.execute_write(create_country, &quot;China&quot;,&quot;Asia&quot;,1412,&quot;One-party state&quot;,[&quot;India&quot;,&quot;russia&quot;,&quot;Philipines&quot;,&quot;Japan&quot;]) session.execute_write(create_country, &quot;Poland&quot;,&quot;Europe&quot;,37,&quot;Parliamentary Republic&quot;,[&quot;Lithuania&quot;,&quot;Germany&quot;,&quot;Czechia&quot;]) session.execute_write(create_country, &quot;Kazakhstan&quot;,&quot;Asia&quot;,19,&quot;Presidential system Republic&quot;,&quot;russia&quot;) session.execute_write(create_country, &quot;Lithuania&quot;,&quot;Europe&quot;,2.7,&quot;Parliamentary Republic&quot;,[&quot;russia&quot;,&quot;Poland&quot;]) session.execute_write(create_country, &quot;Finland&quot;,&quot;Europe&quot;,5.5,&quot;Parliamentary Republic&quot;,&quot;russia&quot;) session.execute_write(create_country, &quot;Philipines&quot;,&quot;Asia&quot;,111,&quot;Parliamentary Republic&quot;,[&quot;Japan&quot;,&quot;China&quot;]) session.execute_write(create_country, &quot;Japan&quot;,&quot;Asia&quot;,125,&quot;Constitutional Monarchy&quot;,[&quot;Philipines&quot;,&quot;China&quot;,&quot;russia&quot;]) session.execute_write(create_country, &quot;Germany&quot;,&quot;Europoe&quot;,83,&quot;Parliamentary Republic&quot;,[&quot;Czechia&quot;,&quot;Austria&quot;,&quot;Poland&quot;]) session.execute_write(create_country, &quot;Czechia&quot;,&quot;Europoe&quot;,10,&quot;Parliamentary Republic&quot;,[&quot;Austria&quot;,&quot;Poland&quot;,&quot;Germany&quot;]) session.execute_write(create_country, &quot;Austria&quot;,&quot;Europoe&quot;,9,&quot;Parliamentary Republic&quot;,[&quot;Czechia&quot;,&quot;Germany&quot;]) def create_bordering_country(tx, name, bcountry): tx.run(&quot;FOREACH (n IN a.bcountry | MERGE (bcountry:Country {name: n}) MERGE (a)-[:HAS_BORDER_WITH]-(bcountry))&quot;) </code></pre> <p>It should look like this:</p> <p><a href="https://i.stack.imgur.com/c7hFS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/c7hFS.png" alt="enter image description here" /></a></p> <p>What I get in neo4j:</p> <p><a href="https://i.stack.imgur.com/bHHGP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bHHGP.png" alt="enter image description here" /></a></p> <p>I also tried to do like this, but then I get duplicates of countries:</p> <pre><code>def create_bordering_country(tx, name, bcountry): tx.run(&quot;MATCH (a:Country) WHERE a.name = $name &quot; &quot;MERGE (a)-[:HAS_BORDER_WITH]-(:Country {name: $bcountry}) RETURN DISTINCT a.name&quot;, name=name, bcountry=bcountry) session.execute_write(create_bordering_country, &quot;russia&quot;, &quot;China&quot;) session.execute_write(create_bordering_country, &quot;India&quot;, &quot;China&quot;) session.execute_write(create_bordering_country, &quot;russia&quot;, &quot;Kazakhstan&quot;) session.execute_write(create_bordering_country, &quot;russia&quot;, &quot;Lithuania&quot;) session.execute_write(create_bordering_country, &quot;russia&quot;, &quot;Finland&quot;) session.execute_write(create_bordering_country, &quot;Poland&quot;, &quot;Lithuania&quot;) session.execute_write(create_bordering_country, &quot;China&quot;, &quot;Japan&quot;) session.execute_write(create_bordering_country, &quot;Russia&quot;, &quot;Japan&quot;) session.execute_write(create_bordering_country, &quot;Philipines&quot;, &quot;Japan&quot;) session.execute_write(create_bordering_country, &quot;Philipines&quot;, &quot;China&quot;) session.execute_write(create_bordering_country, &quot;Germany&quot;, &quot;Poland&quot;) session.execute_write(create_bordering_country, &quot;Austria&quot;, &quot;Poland&quot;) session.execute_write(create_bordering_country, &quot;Czechia&quot;, &quot;Poland&quot;) session.execute_write(create_bordering_country, &quot;Czechia&quot;, &quot;Austria&quot;) session.execute_write(create_bordering_country, &quot;Czechia&quot;, &quot;Germany&quot;) session.execute_write(create_bordering_country, &quot;Germany&quot;, &quot;Austria&quot;) </code></pre>
[ { "answer_id": 74540209, "author": "jose_bacoy", "author_id": 7371893, "author_profile": "https://Stackoverflow.com/users/7371893", "pm_score": 2, "selected": true, "text": " MATCH (a:Country) WHERE a.name = $name \n MERGE (a)-[:HAS_BORDER_WITH]-(:Country {name: $bcountry}) \n RETURN DISTINCT a.name\n MERGE (a:Country) WHERE a.name = $name \n MERGE (b:Country) WHERE b.name = $bcountry \n MERGE (a)-[:HAS_BORDER_WITH]-(b) \n RETURN a.name\n" }, { "answer_id": 74549315, "author": "Nathan Smith", "author_id": 12205676, "author_profile": "https://Stackoverflow.com/users/12205676", "pm_score": 0, "selected": false, "text": "import pandas as pd\nfrom neo4j import GraphDatabase\ndriver = GraphDatabase.driver(\"neo4j://localhost:7687\",\n auth=(\"neo4j\", \"test\"))\n\ncountry_df = pd.DataFrame([\n [\"russia\",\"Asia\",143,\"terrorist state\",[\"Kazakhstan\",\"Lithuania\",\"Finland\",\"China\",\"Japan\"]],\n [\"India\",\"Asia\",1393,\"Parliamentary Republic\",[\"China\"]],\n [\"China\",\"Asia\",1412,\"One-party state\", [\"India\",\"russia\",\"Philipines\",\"Japan\"]],\n [\"Poland\",\"Europe\",37,\"Parliamentary Republic\",[\"Lithuania\",\"Germany\",\"Czechia\"]],\n [\"Kazakhstan\",\"Asia\",19,\"Presidential system Republic\", [\"russia\"]],\n [\"Lithuania\",\"Europe\",2.7,\"Parliamentary Republic\",[\"russia\",\"Poland\"]],\n [\"Finland\",\"Europe\",5.5,\"Parliamentary Republic\",[\"russia\"]],\n [\"Philipines\",\"Asia\",111,\"Parliamentary Republic\",[\"Japan\",\"China\"]],\n [\"Japan\",\"Asia\",125,\"Constitutional Monarchy\",[\"Philipines\",\"China\",\"russia\"]],\n [\"Germany\",\"Europoe\",83,\"Parliamentary Republic\",[\"Czechia\",\"Austria\",\"Poland\"]],\n [\"Czechia\",\"Europoe\",10,\"Parliamentary Republic\",[\"Austria\",\"Poland\",\"Germany\"]],\n [\"Austria\",\"Europoe\",9,\"Parliamentary Republic\",[\"Czechia\",\"Germany\"]]], \n columns=['name', 'continent', 'populationMillion', 'governmentSystem', 'neighboringCountries'])\n\nnode_dicts = country_df[['name', 'continent', 'populationMillion', 'governmentSystem']].to_dict(\"records\")\nrel_dicts = country_df[['name', 'neighboringCountries']].to_dict(\"records\")\n\ndef create_countries(tx, node_dicts):\n result = tx.run(\"\"\"UNWIND $nodeDicts as nodeDict\n MERGE (c:Country {name: nodeDict['name']})\n SET c.continent = nodeDict['continent'] ,\n c.populationMillion = nodeDict['populationMillion'],\n c.governmentSystem = nodeDict['governmentSystem']\"\"\",\n {\"nodeDicts\": node_dicts})\n summary = result.consume()\n return summary.counters\n\ndef create_neighbor_relationships(tx, rel_dicts):\n result = tx.run(\"\"\"UNWIND $relDicts as relDict\n MATCH (c:Country {name: relDict['name']})\n UNWIND relDict['neighboringCountries'] as neighbor\n MATCH (n:Country {name: neighbor})\n MERGE (c)-[:HAS_BORDER_WITH]->(n)\"\"\",\n {\"relDicts\": rel_dicts})\n summary = result.consume()\n return summary.counters\n\nwith driver.session() as session:\n node_results = session.write_transaction(create_countries, node_dicts)\n print(node_results)\n rel_results = session.write_transaction(create_neighbor_relationships, rel_dicts)\n print(rel_results)\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20263206/" ]
74,537,667
<p>I want my code to concat a array with its index, using Join</p> <p>x=['G','r','e','e','t'] x.join(<code>${index}</code>) then x should be G0r1e2e3t4</p> <p>can I achieve this using join?</p>
[ { "answer_id": 74537695, "author": "Dimava", "author_id": 5734961, "author_profile": "https://Stackoverflow.com/users/5734961", "pm_score": 1, "selected": false, "text": "['G','r','e','e','t'].map((e, i) => e + i).join('')\n" }, { "answer_id": 74537712, "author": "Boguz", "author_id": 5509709, "author_profile": "https://Stackoverflow.com/users/5509709", "pm_score": 0, "selected": false, "text": "const arr = ['G','r','e','e','t'];\nconst result = arr.reduce(\n (accumulator, current, index) => accumulator + current + index,\n []\n);" }, { "answer_id": 74538274, "author": "Andrew Parks", "author_id": 5898421, "author_profile": "https://Stackoverflow.com/users/5898421", "pm_score": 0, "selected": false, "text": "console.log(\n ['G','r','e','e','t'].reduce((a,c,i)=>a+c+i,'')\n)" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7741379/" ]
74,537,690
<p>I have a dataframe column that looks like this:</p> <pre><code> paths 0 ['/api/v2/clouds', '/api/v2/clouds/{cloud}'] 1 ['/v0.1/book-lists/{type}/{date}', '/v0.1/book-lists] 2 ['/v1/Video/Rooms', '/v1/Video/Rooms/{RoomSid}'....] 3 ['/v3/attachments/{attachmentId}', '/v3/attachments] 4 '/v0.1/patrons', '/v0.2/patrons', '/v0.3/patrons/dependents] </code></pre> <p>I want to extract the <code>versions</code> from the column in such a format:</p> <p>My desired output is :</p> <pre><code> paths Path_Version 0 ['/api/v2/clouds', '/api/v2/clouds/{cloud}'] v2 1 ['/v0.1/book-lists/{type}/{date}', '/v0.1/book-lists] v0.1 2 ['/v1/Video/Rooms', '/v1/Video/Rooms/{RoomSid}'....] v2 3 ['/v3/attachments/{attachmentId}', '/v3/attachments] v3 4 ['/v0.1/patrons', '/v0.2/patrons', '/v0.3/patrons/dependents] v0.1/v0.2/v0.3 </code></pre> <p>I have tried this:</p> <pre><code>keywords = ['v1', 'v2', 'v3', 'v4', 'v1.0', 'v1.2', 'v1.1', 'v0.1', 'v0.2','v1.3', 'v1.4', 'v3.1', 'v3.2', '0.1.0', '3.1', 'v0.0.2', 'v0.0.3', 'v0.0.4', '1.0.0'] final_api['Path_Version'] = final_api['paths'].str.findall('(' + '|'.join(keywords) + ')') </code></pre> <p>But yields no result. I have looked at other codes as well, but none of them give me the desired output. I am struggling to figure this out, any help will be appreciated.</p>
[ { "answer_id": 74537793, "author": "Tim Roberts", "author_id": 1883316, "author_profile": "https://Stackoverflow.com/users/1883316", "pm_score": 2, "selected": false, "text": "import pandas as pd\nimport re\n\ndata = [\n [['/api/v2/clouds', '/api/v2/clouds/{cloud}']],\n [['/v0.1/book-lists/{type}/{date}', '/v0.1/book-lists']],\n [['/v1/Video/Rooms', '/v1/Video/Rooms/{RoomSid}']],\n [['/v3/attachments/{attachmentId}', '/v3/attachments']],\n [['/v0.1/patrons', '/v0.2/patrons', '/v0.3/patrons/dependents']]\n]\n\ndf = pd.DataFrame(data, columns=['paths'])\n\nver = re.compile(r'/(v\\d(\\.\\d)?)/')\ndef getver(row):\n vsets = set()\n for p in row:\n chk = ver.search(p)\n vsets.add( chk.group(1) )\n return '/'.join(vsets)\n\ndf['Version'] = df.paths.apply(getver)\nprint(df)\n paths Version\n0 [/api/v2/clouds, /api/v2/clouds/{cloud}] v2\n1 [/v0.1/book-lists/{type}/{date}, /v0.1/book-li... v0.1\n2 [/v1/Video/Rooms, /v1/Video/Rooms/{RoomSid}] v1\n3 [/v3/attachments/{attachmentId}, /v3/attachments] v3\n4 [/v0.1/patrons, /v0.2/patrons, /v0.3/patrons/d... v0.2/v0.3/v0.1\n" }, { "answer_id": 74537849, "author": "abokey", "author_id": 16120011, "author_profile": "https://Stackoverflow.com/users/16120011", "pm_score": 4, "selected": true, "text": "pandas.Series.str.findall df[\"Path_Version\"]= (\n df[\"paths\"].str.findall(r\"(v\\d\\.?\\d?)\")\n .apply(lambda x: \"/\".join(set(x)))\n )\n print(df.to_string())\n paths Path_Version\n0 ['/api/v2/clouds', '/api/v2/clouds/{cloud}'] v2\n1 ['/v0.1/book-lists/{type}/{date}', '/v0.1/book-lists] v0.1\n2 ['/v1/Video/Rooms', '/v1/Video/Rooms/{RoomSid}'....] v1\n3 ['/v3/attachments/{attachmentId}', '/v3/attachments] v3\n4 '/v0.1/patrons', '/v0.2/patrons', '/v0.3/patrons/dependents] v0.2/v0.3/v0.1\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17192742/" ]
74,537,763
<p>I am trying to work on a bash script that will take files from one github repo and copy them over to another one.</p> <p>I have this mostly working however 1 file I am trying to move over has spaces on all of its blank lines like so:</p> <pre><code>FROM metrics_flags ORDER BY DeliveryDate ASC ) SELECT * FROM selected; &quot;&quot;&quot;; </code></pre> <p>Notice how its not just a blank line, there are actually 10-20 spaces in between the 2 blocks of code on that blank line. Is there some unix command that can parse the file and remove the spaces (but keep the blank line)?</p> <p>I tried</p> <pre><code>awk 'NF { $1=$1; print }' file.txt </code></pre> <p>and</p> <pre><code>sed -e 's/^[ \t]*//' file.txt </code></pre> <p>with no success.</p>
[ { "answer_id": 74537793, "author": "Tim Roberts", "author_id": 1883316, "author_profile": "https://Stackoverflow.com/users/1883316", "pm_score": 2, "selected": false, "text": "import pandas as pd\nimport re\n\ndata = [\n [['/api/v2/clouds', '/api/v2/clouds/{cloud}']],\n [['/v0.1/book-lists/{type}/{date}', '/v0.1/book-lists']],\n [['/v1/Video/Rooms', '/v1/Video/Rooms/{RoomSid}']],\n [['/v3/attachments/{attachmentId}', '/v3/attachments']],\n [['/v0.1/patrons', '/v0.2/patrons', '/v0.3/patrons/dependents']]\n]\n\ndf = pd.DataFrame(data, columns=['paths'])\n\nver = re.compile(r'/(v\\d(\\.\\d)?)/')\ndef getver(row):\n vsets = set()\n for p in row:\n chk = ver.search(p)\n vsets.add( chk.group(1) )\n return '/'.join(vsets)\n\ndf['Version'] = df.paths.apply(getver)\nprint(df)\n paths Version\n0 [/api/v2/clouds, /api/v2/clouds/{cloud}] v2\n1 [/v0.1/book-lists/{type}/{date}, /v0.1/book-li... v0.1\n2 [/v1/Video/Rooms, /v1/Video/Rooms/{RoomSid}] v1\n3 [/v3/attachments/{attachmentId}, /v3/attachments] v3\n4 [/v0.1/patrons, /v0.2/patrons, /v0.3/patrons/d... v0.2/v0.3/v0.1\n" }, { "answer_id": 74537849, "author": "abokey", "author_id": 16120011, "author_profile": "https://Stackoverflow.com/users/16120011", "pm_score": 4, "selected": true, "text": "pandas.Series.str.findall df[\"Path_Version\"]= (\n df[\"paths\"].str.findall(r\"(v\\d\\.?\\d?)\")\n .apply(lambda x: \"/\".join(set(x)))\n )\n print(df.to_string())\n paths Path_Version\n0 ['/api/v2/clouds', '/api/v2/clouds/{cloud}'] v2\n1 ['/v0.1/book-lists/{type}/{date}', '/v0.1/book-lists] v0.1\n2 ['/v1/Video/Rooms', '/v1/Video/Rooms/{RoomSid}'....] v1\n3 ['/v3/attachments/{attachmentId}', '/v3/attachments] v3\n4 '/v0.1/patrons', '/v0.2/patrons', '/v0.3/patrons/dependents] v0.2/v0.3/v0.1\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14540137/" ]
74,537,823
<p>I'm having trouble understanding a very basic x86 instruction. The instruction is</p> <pre><code>0x080491d7 &lt;+1&gt;: mov %esp,%ebp </code></pre> <p>I know that it moves the value of esp into ebp. But I'm trying to understand the opcodes. The instruction is 2 bytes long, not 1 which I'm confused about. I would've thought it would only be 1 byte.</p> <p>The memory for this instruction is:</p> <pre><code>0x80491d7 &lt;main+1&gt;: 0x89 0xe5 </code></pre> <p>I know that <code>0x89</code> is one of the opcodes <a href="https://www.felixcloutier.com/x86/mov" rel="nofollow noreferrer">for MOV</a>. I've been reading the Intel manuals. I don't know what <code>0xe5</code> is for. Is it like a suffix or another opcode value or something else? The Intel manual is a little confusing.</p> <p>The c program is compiled for x86 32 bit and the Linux server is x86_64.</p>
[ { "answer_id": 74537996, "author": "jcmvbkbc", "author_id": 1943346, "author_profile": "https://Stackoverflow.com/users/1943346", "pm_score": 2, "selected": false, "text": "8B /r /r — Indicates that the ModR/M byte of the instruction contains a register operand and an r/m operand." }, { "answer_id": 74539880, "author": "Sep Roland", "author_id": 3144770, "author_profile": "https://Stackoverflow.com/users/3144770", "pm_score": 2, "selected": false, "text": "mov %esp, %ebp mov ebp, esp ESP/EBP mov %esp, %ebp" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20574523/" ]
74,537,834
<p>I'm working with OpenGL in rust currently.</p> <p>and i want to create objects like VAOs and Textures into structs</p> <p>now, i wrote a custom drop implementation that calls something like <code>glDeleteTexture</code> when the objects lifetime is finished so that it clears up the memory in VRAM.</p> <p>Will the actual data of the object still remain in the RAM if i dont specifically call <code>drop(struct_attribute)</code> for all the attributes</p> <p>I'm expecting for rust to automatically call drop on every attribute but i just wanna make sure so that i dont waste my time or memory if im wrong.</p>
[ { "answer_id": 74537883, "author": "jthulhu", "author_id": 5956261, "author_profile": "https://Stackoverflow.com/users/5956261", "pm_score": 1, "selected": false, "text": "drop fn drop<T>(_: T) {}" }, { "answer_id": 74537888, "author": "Filipe Rodrigues", "author_id": 6655004, "author_profile": "https://Stackoverflow.com/users/6655004", "pm_score": 3, "selected": true, "text": "struct A {\n handle: i32,\n a: String,\n // ...\n}\n\nimpl Drop for A {\n fn drop(&mut self) {\n // Do something with `handle`\n // ...\n\n // `a` will be dropped *after* this function returns automatically\n }\n}\n Drop::drop &mut self self.a drop Drop" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14608746/" ]
74,537,839
<p>I get segmentation fault exception on the next code:</p> <pre><code>class A { public: A() {} virtual ~A(){} double m_d; }; class B : public A { public: B() {} virtual ~B(){} int x; }; int main() { A* ptr = new B[5]; delete[] ptr; return 0; } </code></pre> <p>If delete d'tors, no exception. Expected to NOT receive an exception.</p> <p>Compiler: g++ (Ubuntu 11.2.0-19ubuntu1) 11.2.0</p>
[ { "answer_id": 74538139, "author": "HolyBlackCat", "author_id": 2752075, "author_profile": "https://Stackoverflow.com/users/2752075", "pm_score": 4, "selected": false, "text": "delete [expr.delete]/2 delete delete [expr.delete]/3" }, { "answer_id": 74538204, "author": "Maciej Polański", "author_id": 19165018, "author_profile": "https://Stackoverflow.com/users/19165018", "pm_score": 3, "selected": false, "text": "5.3.5 [expr.delete] p3 #include <iostream> \n\nclass A {\npublic:\n A() {}\n virtual ~A(){ std::cout << m_d << \" ; \";}\n double m_d {0.5};\n};\nclass B : public A {\npublic:\n B() {}\n virtual ~B(){ std::cout << x << \" : \"; }\n int x {2};\n};\nint main()\n{\n A* ptr = new B[5];\n delete[] ptr;\n std::cout << \"Hi, nothing crashed here!\\n\";\n return 0;\n}\n 2.07634e-317 ; 0.5 ; 9.88131e-324 ; 2.07634e-317 ; 0.5 ; Hi, nothing crashed here! Program returned: 139 2 : 0.5 ; 2 : 0.5 ; 2 : 0.5 ; 2 : 0.5 ; 2 : 0.5 ; Hi, nothing crashed here" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17101210/" ]
74,537,844
<p>I have a table similar to the following</p> <pre><code>CREATE TABLE `main.viewings` ( event_time TIMESTAMP, other_columns INT64, more_columns STRING ) PARTITION BY DATE(event_time) OPTIONS( partition_expiration_days=365 ); </code></pre> <p>I then aggregate every new day's data and append that into a reporting table similar to below</p> <pre><code>DECLARE from_event_time TIMESTAMP DEFAULT (SELECT TIMESTAMP(DATE_ADD(IFNULL(MAX(`date`), '2022-10-31'), INTERVAL 1 DAY)) FROM main.`reporting_table`); DECLARE to_event_time TIMESTAMP DEFAULT TIMESTAMP(CURRENT_DATE()); SELECT DISTINCT DATE(event_time) AS `date` FROM main.`viewings` WHERE event_time &gt;= from_event_time AND event_time &lt; to_event_time; </code></pre> <p>Due to some reason, bigquery incorrectly estimates and bills me for the entire size of the viewings table. If I hard code the values for from_event_time and to_event_time, then it correctly estimates a much smaller value.</p> <p>What's more perplexing, if I only have <code>event_time &gt;= from_event_time</code> in the WHERE condition, then too it estimates it correctly. Only when I add <code>event_time &lt; to_event_time</code>, it starts messing up.</p> <p>Has anyone faced something similar?</p>
[ { "answer_id": 74538139, "author": "HolyBlackCat", "author_id": 2752075, "author_profile": "https://Stackoverflow.com/users/2752075", "pm_score": 4, "selected": false, "text": "delete [expr.delete]/2 delete delete [expr.delete]/3" }, { "answer_id": 74538204, "author": "Maciej Polański", "author_id": 19165018, "author_profile": "https://Stackoverflow.com/users/19165018", "pm_score": 3, "selected": false, "text": "5.3.5 [expr.delete] p3 #include <iostream> \n\nclass A {\npublic:\n A() {}\n virtual ~A(){ std::cout << m_d << \" ; \";}\n double m_d {0.5};\n};\nclass B : public A {\npublic:\n B() {}\n virtual ~B(){ std::cout << x << \" : \"; }\n int x {2};\n};\nint main()\n{\n A* ptr = new B[5];\n delete[] ptr;\n std::cout << \"Hi, nothing crashed here!\\n\";\n return 0;\n}\n 2.07634e-317 ; 0.5 ; 9.88131e-324 ; 2.07634e-317 ; 0.5 ; Hi, nothing crashed here! Program returned: 139 2 : 0.5 ; 2 : 0.5 ; 2 : 0.5 ; 2 : 0.5 ; 2 : 0.5 ; Hi, nothing crashed here" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4635851/" ]
74,537,845
<p>I'm trying to synchronize two JTextFields. If I write in one JTextField, I want to write the same text in other JTextField simultaneously.</p> <p>I'm not sure what event use for this requirement.</p> <p>My example code:</p> <pre><code>private void txt_idEstablecimientoActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: txt_codigoEstablecimiento.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { txt_codEstabQVT.setText(txt_codigoEstablecimiento.getText().trim()); System.out.println(txt_codEstabQVT); } }); } </code></pre> <p>My example code:</p> <pre><code> private void txt_idEstablecimientoActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: txt_codigoEstablecimiento.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { txt_codEstabQVT.setText(txt_codigoEstablecimiento.getText().trim()); System.out.println(txt_codEstabQVT); } }); } </code></pre>
[ { "answer_id": 74538465, "author": "camickr", "author_id": 131872, "author_profile": "https://Stackoverflow.com/users/131872", "pm_score": 2, "selected": false, "text": "Document JTextField textField1 = new JTextField(...);\nJTextField textField2 = new JTextField(...);\ntextField2.setDocument( textField1.getDocument() );\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12144967/" ]
74,537,855
<p>I am trying to create a demo website for users to test. I want to restore the databse every x hours. When I run the php script in browser it works. It drops the tables and restores the databse without any issues. When I add the same file in cron, the tables are dropped but it does not restore the databse. I am not sure why it's not restoring the database.</p> <pre><code> &lt;?php $mysqli = new mysqli(&quot;localhost&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;); $mysqli-&gt;query('SET foreign_key_checks = 0'); if ($result = $mysqli-&gt;query(&quot;SHOW TABLES&quot;)) { while($row = $result-&gt;fetch_array(MYSQLI_NUM)) { $mysqli-&gt;query('DROP TABLE IF EXISTS '.$row[0]); } } $mysqli-&gt;query('SET foreign_key_checks = 1'); echo &quot;Deleted databse&quot;; sleep(5); $sqlScript = file('demo.sql'); foreach ($sqlScript as $line) { $startWith = substr(trim($line), 0 ,2); $endWith = substr(trim($line), -1 ,1); if (empty($line) || $startWith == '--' || $startWith == '/*' || $startWith == '//') { continue; } $query = $query . $line; if ($endWith == ';') { mysqli_query($mysqli,$query) or die('&lt;div class=&quot;error-response sql-import-response&quot;&gt;Problem in executing the SQL query &lt;b&gt;' . $query. '&lt;/b&gt;&lt;/div&gt;'); $query= ''; } } $mysqli-&gt;close(); echo '&lt;div class=&quot;success-response sql-import-response&quot;&gt;SQL file imported successfully&lt;/div&gt;'; ?&gt; </code></pre> <p>Cron job</p> <pre><code>*/10 * * * * /usr/local/bin/php /home/demo/public_html/db.php </code></pre>
[ { "answer_id": 74537989, "author": "DoMajor7th", "author_id": 6654885, "author_profile": "https://Stackoverflow.com/users/6654885", "pm_score": 0, "selected": false, "text": "*/10 * * * * cd /home/demo/public_html/ && /usr/local/bin/php /home/demo/public_html/db.php\n" }, { "answer_id": 74538027, "author": "Mangesh Yadav", "author_id": 6504229, "author_profile": "https://Stackoverflow.com/users/6504229", "pm_score": -1, "selected": true, "text": "/etc/cron file('demo.sql');" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6504229/" ]
74,537,912
<p><a href="https://fr.wikipedia.org/wiki/Plus_petit_commun_multiple" rel="nofollow noreferrer">PPCM</a> which is the least common multiple, lowest common multiple, or smallest common multiple of two integers a and b, is the smallest positive integer that is divisible by both a and b. Since division of integers by zero is undefined, this definition has meaning only if a and b are both different from zero. However, some authors define lcm(a,0) as 0 for all a, since 0 is the only common multiple of a and 0.</p> <pre class="lang-py prettyprint-override"><code>a=int(input(&quot;Valeur de a ?&quot;)) b=int(input(&quot;Valeur de b ?&quot;)) print('les diviseures de a : ') tab_a = [] tab_b = [] tab_c = [] for i in range(1,a+1): if(a%i==0): tab_a.append(i) print(tab_a) print('les diviseures de b : ') for j in range(1,b+1): if(b%j==0): tab_b.append(j) print(tab_b) l=0 if(a&gt;b): sh = len(tab_b) lg = len(tab_a) arr_sh = tab_b arr_lg = tab_a else: sh = len(tab_a) lg = len(tab_b) arr_sh = tab_a arr_lg = tab_b for i in range(0,sh): for j in range(0,lg): if(arr_sh[i]==arr_lg[j]): tab_c.append(arr_sh[i]) print(tab_c) print('PPCM est :',tab_c[0]) </code></pre> <p>I think my approach is long, how can I improve it?</p>
[ { "answer_id": 74538108, "author": "Samwise", "author_id": 3799759, "author_profile": "https://Stackoverflow.com/users/3799759", "pm_score": 0, "selected": false, "text": ">>> def lcm(a, b):\n... a, b = sorted((a, b))\n... return next(i for i in range(b, a * b + 1, b) if i % a == 0)\n...\n>>> lcm(2, 4)\n4\n>>> lcm(20, 16)\n80\n" }, { "answer_id": 74538275, "author": "Yves Daoust", "author_id": 1196549, "author_profile": "https://Stackoverflow.com/users/1196549", "pm_score": 1, "selected": false, "text": "lcm gcd def gcd(a, b):\n while b > 0:\n a, b= b, a % b\n return a\n\ndef lcm(a, b):\n return a * b // gcd(a, b)\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20522314/" ]
74,537,932
<p>How to use the <code>name</code> property in this object:</p> <pre><code>const obj = { name: 'root/branch/subbranch/leaf', value: 'my-value' } </code></pre> <p>To create an object with the following format:</p> <pre><code>{ root: { branch: { subbranch: { leaf: 'my-value' } } } } </code></pre>
[ { "answer_id": 74575531, "author": "Sedat Polat", "author_id": 668572, "author_profile": "https://Stackoverflow.com/users/668572", "pm_score": 1, "selected": false, "text": "const obj = {\n name: 'root/branch/subbranch/leaf',\n value: 'my-value'\n}\n\nconst recursiveNest = (result, value, arr, index = 0) => { \n const path = arr[index]\n if (index < arr.length - 1) {\n result[path] = {}\n index +=1;\n recursiveNest(result[path], value, arr, index)\n } else {\n result[arr[index]] = value; \n }\n};\n\nconst createNestedObject = (obj, splitBy) => {\n let result = {}\n recursiveNest(result, obj.value, obj.name.split(splitBy))\n return result;\n}\n\nconsole.log(createNestedObject(obj, '/'));" }, { "answer_id": 74575677, "author": "xehpuk", "author_id": 1178016, "author_profile": "https://Stackoverflow.com/users/1178016", "pm_score": 0, "selected": false, "text": "setWith(object, path, value, [customizer]) const obj = {\n name: 'root/branch/subbranch/leaf',\n value: 'my-value'\n}\n\nconsole.log(_.setWith({}, obj.name.split('/'), obj.value, _.stubObject)) <script src=\"https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js\"></script>" }, { "answer_id": 74575707, "author": "Cjmarkham", "author_id": 630780, "author_profile": "https://Stackoverflow.com/users/630780", "pm_score": 2, "selected": true, "text": "const obj = {\n name: 'root/branch/subbranch/leaf',\n value: 'my-value'\n}\n\n\nlet newObj = {}\nconst parts = obj.name.split('/')\nparts.reduce((prev, curr, i) => (\n Object.assign(\n prev, \n {[curr]: i === parts.length - 1 ? obj.value : Object(prev[curr])}\n ), \n prev[curr]\n), newObj)\n\nconsole.log(newObj)" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2667374/" ]
74,537,941
<p>I am quite new to VSTO and C# programming and am self-learning. I created an Outlook addin that does several things. One of the features is that it takes all sent items and adds them to our DB. When the user sends an email from Outlook it works as expected and prompts/adds it perfectly. But when they sent an email from their phone it only prompt them for the last email sent. I expected that once they open Outlook and it downloads the latest Sent items, it would prompt them for each item to save to the DB. But it is only prompting the last downloaded item, not each one as they download. I think some sort of queue would be reqiured but I can't find any examples. Any help would be greatly appreciated.</p> <p>here is my code.</p> <pre><code>private void ThisAddIn_Startup(object sender, System.EventArgs e) { Outlook.Application application = this.Application; _items = Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderSentMail).Items; _items.ItemAdd += new Outlook.ItemsEvents_ItemAddEventHandler(SentFolderItemAdded); } private void SentFolderItemAdded(object item) { // Code to prompt the user and add it to the DB } </code></pre>
[ { "answer_id": 74575531, "author": "Sedat Polat", "author_id": 668572, "author_profile": "https://Stackoverflow.com/users/668572", "pm_score": 1, "selected": false, "text": "const obj = {\n name: 'root/branch/subbranch/leaf',\n value: 'my-value'\n}\n\nconst recursiveNest = (result, value, arr, index = 0) => { \n const path = arr[index]\n if (index < arr.length - 1) {\n result[path] = {}\n index +=1;\n recursiveNest(result[path], value, arr, index)\n } else {\n result[arr[index]] = value; \n }\n};\n\nconst createNestedObject = (obj, splitBy) => {\n let result = {}\n recursiveNest(result, obj.value, obj.name.split(splitBy))\n return result;\n}\n\nconsole.log(createNestedObject(obj, '/'));" }, { "answer_id": 74575677, "author": "xehpuk", "author_id": 1178016, "author_profile": "https://Stackoverflow.com/users/1178016", "pm_score": 0, "selected": false, "text": "setWith(object, path, value, [customizer]) const obj = {\n name: 'root/branch/subbranch/leaf',\n value: 'my-value'\n}\n\nconsole.log(_.setWith({}, obj.name.split('/'), obj.value, _.stubObject)) <script src=\"https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js\"></script>" }, { "answer_id": 74575707, "author": "Cjmarkham", "author_id": 630780, "author_profile": "https://Stackoverflow.com/users/630780", "pm_score": 2, "selected": true, "text": "const obj = {\n name: 'root/branch/subbranch/leaf',\n value: 'my-value'\n}\n\n\nlet newObj = {}\nconst parts = obj.name.split('/')\nparts.reduce((prev, curr, i) => (\n Object.assign(\n prev, \n {[curr]: i === parts.length - 1 ? obj.value : Object(prev[curr])}\n ), \n prev[curr]\n), newObj)\n\nconsole.log(newObj)" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12699232/" ]
74,537,948
<p>I can't figure out why the system bars still remain in landscape although I have used</p> <pre><code>WindowCompat.setDecorFitsSystemWindows(window, true) WindowInsetsControllerCompat(window, nView).let { controller -&gt; controller.hide(WindowInsetsCompat.Type.systemBars()) controller.systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE } </code></pre> <p>But it seems it just hides the 'icons <a href="https://i.stack.imgur.com/xBd81.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xBd81.jpg" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/F6EqF.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/F6EqF.jpg" alt="enter image description here" /></a></p> <p>Any idea is appreciated</p> <p><strong>Later Edit: Made a test and realized is from the activity layout androidx.drawerlayout.widget.DrawerLayout</strong></p>
[ { "answer_id": 74575531, "author": "Sedat Polat", "author_id": 668572, "author_profile": "https://Stackoverflow.com/users/668572", "pm_score": 1, "selected": false, "text": "const obj = {\n name: 'root/branch/subbranch/leaf',\n value: 'my-value'\n}\n\nconst recursiveNest = (result, value, arr, index = 0) => { \n const path = arr[index]\n if (index < arr.length - 1) {\n result[path] = {}\n index +=1;\n recursiveNest(result[path], value, arr, index)\n } else {\n result[arr[index]] = value; \n }\n};\n\nconst createNestedObject = (obj, splitBy) => {\n let result = {}\n recursiveNest(result, obj.value, obj.name.split(splitBy))\n return result;\n}\n\nconsole.log(createNestedObject(obj, '/'));" }, { "answer_id": 74575677, "author": "xehpuk", "author_id": 1178016, "author_profile": "https://Stackoverflow.com/users/1178016", "pm_score": 0, "selected": false, "text": "setWith(object, path, value, [customizer]) const obj = {\n name: 'root/branch/subbranch/leaf',\n value: 'my-value'\n}\n\nconsole.log(_.setWith({}, obj.name.split('/'), obj.value, _.stubObject)) <script src=\"https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js\"></script>" }, { "answer_id": 74575707, "author": "Cjmarkham", "author_id": 630780, "author_profile": "https://Stackoverflow.com/users/630780", "pm_score": 2, "selected": true, "text": "const obj = {\n name: 'root/branch/subbranch/leaf',\n value: 'my-value'\n}\n\n\nlet newObj = {}\nconst parts = obj.name.split('/')\nparts.reduce((prev, curr, i) => (\n Object.assign(\n prev, \n {[curr]: i === parts.length - 1 ? obj.value : Object(prev[curr])}\n ), \n prev[curr]\n), newObj)\n\nconsole.log(newObj)" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3288058/" ]
74,537,975
<p>This is a follow-up question to this: <a href="https://stackoverflow.com/questions/74510669/how-to-use-paste0-with-input-in-shiny">How to use paste0 with input$ in shiny</a></p> <p>I don't know if this is possible and I have been through all the persistent storage history the last years (here is a representative example of a former question: <a href="https://stackoverflow.com/questions/63329561/r-shiny-load-data-in-to-form-fields-from-previously-persistent-stored-data">r shiny: Load data in to form fields from previously persistent stored data</a></p> <p><strong>Now I want to create a form in shiny where people can fill in the form and press a button to send the data, this is done with this code:</strong></p> <pre><code>library(shiny) library(shinyWidgets) ui &lt;- fluidPage( sidebarLayout( # Sidebar to demonstrate various slider options ---- sidebarPanel(width = 4, setSliderColor(c(&quot;DeepPink &quot;, &quot;#FF4500&quot;, &quot;Teal&quot;), c(1, 2, 3)), # Input: Simple integer interval ---- div(class = &quot;label-left&quot;, Map(function(id, lbl) { list( div(style=&quot;display: inline-block;vertical-align:middle; width: 300px;&quot;,sliderInput(id, lbl, min = 0, max = 3, value = 0, width = &quot;250px&quot;)), div(style=&quot;display: inline-block;vertical-align:middle; width: 150px;&quot;,textInput(paste0(&quot;txt_&quot;, id), label = NULL, value = 0, width = &quot;40px&quot; )) ) }, c(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;), c(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;)) ) ), # Main panel for displaying outputs ---- mainPanel( titlePanel(&quot;Sliders&quot;), # Output: Table summarizing the values entered ---- tableOutput(&quot;values&quot;) ) ) ) server &lt;- function(input, output, session) { Map(function(id) { list( observeEvent(input[[paste0(&quot;txt_&quot;, id)]], { if(as.numeric(input[[paste0(&quot;txt_&quot;, id)]]) != input[[id]]) { updateSliderInput( session = session, inputId = id, value = input[[paste0(&quot;txt_&quot;, id)]] ) # updateSliderInput }#if }), observeEvent(input[[id]], { if(as.numeric(input[[paste0(&quot;txt_&quot;, id)]]) != input[[id]]) { updateTextInput( session = session, inputId = paste0(&quot;txt_&quot;, id), value = input[[id]] ) # updateTextInput }#if }) ) }, c(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;)) # Reactive expression to create data frame of all input values ---- sliderValues &lt;- reactive({ data.frame( Name = c(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;), Value = as.character(c(input$a, input$b, input$c )), stringsAsFactors = FALSE) }) # Show the values in an HTML table ---- output$values &lt;- renderTable({ sliderValues() }) } shinyApp(ui, server) </code></pre> <p>And NOW I would like to save the actual filled in data to <strong>the hard disk</strong> as csv or any other format. And if the same user comes again next time the new data should be appended to the existing data.</p> <p>Is this possible?</p>
[ { "answer_id": 74613533, "author": "asd-tm", "author_id": 5043424, "author_profile": "https://Stackoverflow.com/users/5043424", "pm_score": 3, "selected": true, "text": "app.R library(shiny)\nlibrary(shinyWidgets)\nlibrary(dplyr)\nlibrary(openxlsx)\n\ndefaultDF <- data.frame(Name = c(\"A\", \"B\", \"C\"),\n Value = rep(0L, 3))\n\nMyColors = c(\"DeepPink \", \"#FF4500\", \"Teal\")\n\nui <- fluidPage(\n sidebarLayout(\n # Sidebar to demonstrate various slider options ----\n sidebarPanel(width = 4,\n setSliderColor(MyColors, \n c(1:3)),\n # Input: Simple integer interval ----\n div(class = \"label-left\",\n Map(function(id, lbl, val) {\n list(\n div(style=\"display: inline-block;vertical-align:middle; width: 300px;\",\n sliderInput(id, lbl, min = 0, max = 3, value = val, width = \"250px\")),\n div(style=\"display: inline-block;vertical-align:middle; width: 150px;\",\n textInput(paste0(\"txt_\", id), label = NULL, value = 0, width = \"40px\" ))\n )\n }, defaultDF %>% select(Name) %>% pull(), \n defaultDF %>% select(Name) %>% pull(), \n defaultDF %>% select(Value) %>% pull())\n ),\n downloadButton(\"xlsxDownload\", \"Download dataframe\"),\n fileInput(\n \"xlsxUpload\",\n \"Files with stored values\",\n #placeholder = \"Select files\",\n #buttonLabel = \"Обзор\",\n #accept = c(\".xml\",\".zip\"),\n accept = c(\".xlsx\"),\n multiple = F\n )\n ),\n # Main panel for displaying outputs ----\n mainPanel(\n titlePanel(\"Sliders\"),\n # Output: Table summarizing the values entered ----\n tableOutput(\"values\")\n \n )\n )\n)\nserver <- function(input, output, session) {\n\n currentDF <- reactiveVal(defaultDF)\n \n # Show the values in an HTML table ----\n output$values <- renderTable({\n currentDF()\n })\n output$xlsxDownload <- downloadHandler(\n filename = \n function() { \"myDataframe.xlsx\"\n },\n content = \n function(file) {\n openxlsx::write.xlsx(\n currentDF(), \n file)\n }\n \n )\n \n observe({\n file1 <- input$xlsxUpload\n if (!is.null(file1)) {\n \n \n ext <- tools::file_ext(file1$datapath)\n req(file1)\n validate(need(ext %in% c(\"xlsx\"), 'All files must have extension xlsx')) # Add all other validation checks as well\n\n\n transformedData <- openxlsx::read.xlsx(file1$datapath)\n #do necessary checks and data transformations here\n transformedData\n currentDF(transformedData)\n }\n })\n \n observe({\n cdf <- currentDF()\n Map(function(Nm) updateSliderInput(\n session = session,\n inputId = Nm,\n value = cdf %>% filter(Name == Nm) %>% select(Value) %>% pull()\n ),\n c(\"A\", \"B\", \"C\")\n )\n })\n \n observe({\n cdf <- currentDF()\n Map(function(Nm) updateTextInput(\n session = session,\n inputId = paste0(\"txt_\", Nm),\n value = cdf %>% filter(Name == Nm) %>% select(Value) %>% pull()\n ),\n c(\"A\", \"B\", \"C\")\n )\n })\n\n toListen <- reactive({\n list(input$A, input$B, input$C)\n })\n toListen2 <- reactive({\n list(input$txt_A, input$txt_B, input$txt_C)\n })\n \n observeEvent(toListen(),{ Map(function(id) {cdf <- currentDF() \n cdf$Value[cdf$Name == id] <- input[[id]]\n currentDF(cdf)\n },\n c(\"A\", \"B\", \"C\")\n )\n }\n )\n \n observeEvent(toListen2(),{ Map(function(id) {cdf <- currentDF() \n cdf$Value[cdf$Name == id] <- input[[paste0(\"txt_\", id)]]\n currentDF(cdf)\n },\n c(\"A\", \"B\", \"C\")\n )\n }\n )\n \n}\nshinyApp(ui, server)\n" }, { "answer_id": 74654239, "author": "e382df99a7950919789725ceeec126", "author_id": 237209, "author_profile": "https://Stackoverflow.com/users/237209", "pm_score": 1, "selected": false, "text": "write.csv() # Reactive expression to create data frame of all input values ----\n sliderValues <- reactive({\n \n data.frame(\n Name = c(\"A\",\n \"B\",\n \"C\"),\n Value = as.character(c(input$a,\n input$b,\n input$c\n )),\n stringsAsFactors = FALSE)\n \n })\n \n # Save the values to a CSV file on the hard disk ----\n saveData <- reactive({\n write.csv(sliderValues(), file = \"slider_values.csv\", append = TRUE)\n })\n saveData() # Sidebar to demonstrate various slider options ----\n sidebarPanel(width = 4,\n setSliderColor(c(\"DeepPink \", \"#FF4500\", \"Teal\"),\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74537975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13321647/" ]
74,538,022
<p>I need to fetch my array field in dataframe and assign it to a variable for further proceeding further. I am using collect() function, but its not working properly.</p> <p><strong>Input dataframe:</strong></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Department</th> <th>Language</th> </tr> </thead> <tbody> <tr> <td>[A, B, C]</td> <td>English</td> </tr> <tr> <td>[]</td> <td>Spanish</td> </tr> </tbody> </table> </div> <p><strong>How can i fetch and assign variable like below:</strong></p> <p>English = [A,B,C]</p> <p>Spanish = []</p>
[ { "answer_id": 74538371, "author": "psychicesp", "author_id": 13741789, "author_profile": "https://Stackoverflow.com/users/13741789", "pm_score": 1, "selected": false, "text": "# To recreate your dataframe\n\ndf = pd.DataFrame({\n 'Department': [['A','B', 'C']],\n 'Language': 'English'\n})\n\ndf.loc[df.Language == 'English']\n# Will return all rows where Language is English. If you only want Department then:\n\ndf.loc[df.Language == 'English'].Department\n# This will return a list containing your list. If you are always expecting a single match add [0] as in:\n\ndf.loc[df.Language == 'English'].Department[0]\n#Which will return only your list\n# The alternate method below isn't great but might be preferable in some circumstances, also only if you expect a single match from any query.\n\ndepartment_lookup = df[['Language', 'Department']].set_index('Language').to_dict()['Department']\n\ndepartment_lookup['English']\n#returns your list\n\n# This will make a dictionary where 'Language' is the key and 'Department' is the value. It is more work to set up and only works for a two-column relationship but you might prefer working with dictionaries depending on the use-case\n\n \n# If I saved and reload the df as so: \ndf.to_csv(\"the_df.csv\")\ndf = pd.read_csv(\"the_df.csv\")\n\n# Then we would see that the dtype has become a string, as in \"[A, B, C]\" rather than [\"A\", \"B\", \"C\"]\n\n# We can typically correct this by giving pandas a method for converting the incoming string to list. This is done with the 'converters' argument, which takes a dictionary where trhe keys are column names and the values are functions, as such:\n\ndf = pd.read_csv(\"the_df.csv\", converters = {\"Department\": lambda x: x.strip(\"[]\").split(\", \"))\n\n# df['Department'] should have a dtype of list\n\n" }, { "answer_id": 74538892, "author": "Bartosz Gajda", "author_id": 6870955, "author_profile": "https://Stackoverflow.com/users/6870955", "pm_score": 2, "selected": false, "text": "collect from pyspark.sql.types import StringType, ArrayType, StructType, StructField\n\nschema = StructType([\n StructField(\"Department\", ArrayType(StringType()), True),\n StructField(\"Language\", StringType(), True)\n ])\n\ndf = spark.createDataFrame([([\"A\", \"B\", \"C\"], \"English\"), ([], \"Spanish\")], schema)\n\nEnglish = df.collect()[0][\"Department\"]\nSpanish = df.collect()[1][\"Department\"]\nprint(f\"English: {English}, Spanish: {Spanish}\")\n\n# English: ['A', 'B', 'C'], Spanish: []\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74538022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19701707/" ]
74,538,048
<p>So i'm basicly trying to fetch some data from the duolingo api and make all the different parts accesible via a class (I think that's the best way to make the data accesible in other files?)</p> <p>I currently have this code:</p> <pre><code>class DuoData: def __init__(self, username): self.username = username self.URL = &quot;https://www.duolingo.com/2017-06-30/users?username={username}&quot; self.data = requests.get(self.URL.format(username=self.username)) self.data_json = self.data.json() def get_streak(self): return self.data_json['users'][0]['streak'] class ActiveLanguage: def __init__(self, data_json): super().__init__() self.active_language = data_json['users'][0]['courses'][0] def get_name(self): return self.active_language['title'] def get_xp(self): return self.active_language['xp'] def get_crowns(self): return self.active_language['crowns'] </code></pre> <p>the get_streak fucntion works perfectly, so</p> <pre><code>duo = DuoData(&quot;username&quot;) print(duo.get_streak()) </code></pre> <p>prints the streak number like I want, but the following code doesn't work: <code>print(duo.ActiveLanguage.get_name())</code></p> <p>I want it so that <code>duo.ActiveLanguage.getname()</code> returns the name of the language but it doesn't work like this, I get the following error: TypeError: DuoData.ActiveLanguage.get_name() missing 1 required positional argument: 'self' I already tried lots of different things and this was my best approach but it still doesn't work, can anyone help me? This is my first time working with classes (in Python) I think maybe subclasses aren't the right approach?</p> <p>My question is: can i have a class or whatever with a few categories that each have different values? like: <code>data.userdata.streak</code> and <code>data.userdata.id</code> and <code>data.activelanguage.name</code> and so on?</p>
[ { "answer_id": 74538371, "author": "psychicesp", "author_id": 13741789, "author_profile": "https://Stackoverflow.com/users/13741789", "pm_score": 1, "selected": false, "text": "# To recreate your dataframe\n\ndf = pd.DataFrame({\n 'Department': [['A','B', 'C']],\n 'Language': 'English'\n})\n\ndf.loc[df.Language == 'English']\n# Will return all rows where Language is English. If you only want Department then:\n\ndf.loc[df.Language == 'English'].Department\n# This will return a list containing your list. If you are always expecting a single match add [0] as in:\n\ndf.loc[df.Language == 'English'].Department[0]\n#Which will return only your list\n# The alternate method below isn't great but might be preferable in some circumstances, also only if you expect a single match from any query.\n\ndepartment_lookup = df[['Language', 'Department']].set_index('Language').to_dict()['Department']\n\ndepartment_lookup['English']\n#returns your list\n\n# This will make a dictionary where 'Language' is the key and 'Department' is the value. It is more work to set up and only works for a two-column relationship but you might prefer working with dictionaries depending on the use-case\n\n \n# If I saved and reload the df as so: \ndf.to_csv(\"the_df.csv\")\ndf = pd.read_csv(\"the_df.csv\")\n\n# Then we would see that the dtype has become a string, as in \"[A, B, C]\" rather than [\"A\", \"B\", \"C\"]\n\n# We can typically correct this by giving pandas a method for converting the incoming string to list. This is done with the 'converters' argument, which takes a dictionary where trhe keys are column names and the values are functions, as such:\n\ndf = pd.read_csv(\"the_df.csv\", converters = {\"Department\": lambda x: x.strip(\"[]\").split(\", \"))\n\n# df['Department'] should have a dtype of list\n\n" }, { "answer_id": 74538892, "author": "Bartosz Gajda", "author_id": 6870955, "author_profile": "https://Stackoverflow.com/users/6870955", "pm_score": 2, "selected": false, "text": "collect from pyspark.sql.types import StringType, ArrayType, StructType, StructField\n\nschema = StructType([\n StructField(\"Department\", ArrayType(StringType()), True),\n StructField(\"Language\", StringType(), True)\n ])\n\ndf = spark.createDataFrame([([\"A\", \"B\", \"C\"], \"English\"), ([], \"Spanish\")], schema)\n\nEnglish = df.collect()[0][\"Department\"]\nSpanish = df.collect()[1][\"Department\"]\nprint(f\"English: {English}, Spanish: {Spanish}\")\n\n# English: ['A', 'B', 'C'], Spanish: []\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74538048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20561150/" ]
74,538,092
<p>So I was adding columns and the buttons wouldn't line up well is there a way to fix this?</p> <p><img src="https://i.stack.imgur.com/Do0LG.png" alt="enter image description here" /></p> <p><img src="https://i.stack.imgur.com/Do0LG.png" alt="" /></p> <p>Tried changing the div code inside but it still wouldn't do anything.</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>.desc { color: rgb(232, 14, 14); font-size: 16px; padding: 5px; } .game:hover { color: rgb(120, 9, 9); background-color: rgb(52, 3, 3); } .game { border: none; outline: 0; display: inline-block; padding: 8px; color: rgba(0, 0, 0, 0.741); border-radius: 10px; background-color: rgb(129, 5, 5); text-align: center; cursor: pointer; width: 100%; font-size: 18px; } .flex-container { display: flex; flex-wrap: wrap; align-items: center; align-content: center; } .flex-container&gt;div { margin: 1px; padding: 3px; } .card { box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2); max-width: 300px; border-radius: 10px; background-color: black; text-align: center; font-family: arial; } .thumb { border-radius: 10px; } .button { background-color: orange; border: none; color: black; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; border-radius: 12px; } .center-screen { text-align: center; font-family: "Arial"; font-size: 20px; } form { background-color: #4654e1; width: 300px; height: 44px; border-radius: 5px; display: flex; flex-direction: row; align-items: center; } input { all: unset; font: 16px system-ui; color: #fff; height: 100%; width: 100%; padding: 6px 10px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="search" class="flex-container"&gt; &lt;div&gt; &lt;div class="card"&gt; &lt;img class="thumb" width="300" height="300" src="/Pages/games/wpnfire/wpnfire.jpg" alt="#" /&gt; &lt;h1 style="color: white;"&gt;Text&lt;/h1&gt; &lt;p class="desc"&gt;Text&lt;/p&gt; &lt;div style="margin: 24px 0;"&gt; &lt;i class="fa-solid fa-keyboard"&gt;&lt;/i&gt; &lt;/div&gt; &lt;a class="game" href="/Pages/games/wpnfire/"&gt;Press to play&lt;/a&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>That is the CSS and HTML of the page and the columns</p> <p>I don't know what to change in the code to get it to align up.</p>
[ { "answer_id": 74538371, "author": "psychicesp", "author_id": 13741789, "author_profile": "https://Stackoverflow.com/users/13741789", "pm_score": 1, "selected": false, "text": "# To recreate your dataframe\n\ndf = pd.DataFrame({\n 'Department': [['A','B', 'C']],\n 'Language': 'English'\n})\n\ndf.loc[df.Language == 'English']\n# Will return all rows where Language is English. If you only want Department then:\n\ndf.loc[df.Language == 'English'].Department\n# This will return a list containing your list. If you are always expecting a single match add [0] as in:\n\ndf.loc[df.Language == 'English'].Department[0]\n#Which will return only your list\n# The alternate method below isn't great but might be preferable in some circumstances, also only if you expect a single match from any query.\n\ndepartment_lookup = df[['Language', 'Department']].set_index('Language').to_dict()['Department']\n\ndepartment_lookup['English']\n#returns your list\n\n# This will make a dictionary where 'Language' is the key and 'Department' is the value. It is more work to set up and only works for a two-column relationship but you might prefer working with dictionaries depending on the use-case\n\n \n# If I saved and reload the df as so: \ndf.to_csv(\"the_df.csv\")\ndf = pd.read_csv(\"the_df.csv\")\n\n# Then we would see that the dtype has become a string, as in \"[A, B, C]\" rather than [\"A\", \"B\", \"C\"]\n\n# We can typically correct this by giving pandas a method for converting the incoming string to list. This is done with the 'converters' argument, which takes a dictionary where trhe keys are column names and the values are functions, as such:\n\ndf = pd.read_csv(\"the_df.csv\", converters = {\"Department\": lambda x: x.strip(\"[]\").split(\", \"))\n\n# df['Department'] should have a dtype of list\n\n" }, { "answer_id": 74538892, "author": "Bartosz Gajda", "author_id": 6870955, "author_profile": "https://Stackoverflow.com/users/6870955", "pm_score": 2, "selected": false, "text": "collect from pyspark.sql.types import StringType, ArrayType, StructType, StructField\n\nschema = StructType([\n StructField(\"Department\", ArrayType(StringType()), True),\n StructField(\"Language\", StringType(), True)\n ])\n\ndf = spark.createDataFrame([([\"A\", \"B\", \"C\"], \"English\"), ([], \"Spanish\")], schema)\n\nEnglish = df.collect()[0][\"Department\"]\nSpanish = df.collect()[1][\"Department\"]\nprint(f\"English: {English}, Spanish: {Spanish}\")\n\n# English: ['A', 'B', 'C'], Spanish: []\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74538092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20066054/" ]
74,538,102
<p>As per the title, I am trying to create a JS script that cycles through a series of images in the same <code>&lt;div&gt;</code>. The images will be cycled through to create a smooth animation. So far, I have this. The images cycle through but without a smooth transition.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var slideIndex = 0; showSlides(); function showSlides() { var i; var slides = document.getElementsByClassName("mySlides"); for (i = 0; i &lt; slides.length; i++) { slides[i].style.display = "none"; slides[i].style.opacity = "0"; } slideIndex++; if (slideIndex &gt; slides.length) { slideIndex = 1 } slides[slideIndex - 1].style.display = "block"; slides[slideIndex - 1].style.opacity = "1"; setTimeout(showSlides, 2500); // Add a transition to the images. slides[slideIndex - 1].style.transition = "all 2.50s"; // Add a delay to the images. slides[slideIndex - 1].style.transitionDelay = "2.50s"; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="p-centered"&gt; &lt;img src="https://picsum.photos/200?1" class="img-responsive mySlides" alt=""&gt; &lt;img src="https://picsum.photos/200?2" class="img-responsive mySlides" alt=""&gt; &lt;img src="https://picsum.photos/200?3" class="img-responsive mySlides" alt=""&gt; &lt;img src="https://picsum.photos/200?4" class="img-responsive mySlides" alt=""&gt; &lt;img src="https://picsum.photos/200?5" class="img-responsive mySlides" alt=""&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74538242, "author": "edemaine", "author_id": 7797661, "author_profile": "https://Stackoverflow.com/users/7797661", "pm_score": 1, "selected": false, "text": "display: block opacity display: none position: absolute p-centered let slideIndex = 0;\n\nfunction showSlides() {\n const slides = document.getElementsByClassName(\"slide\");\n // Hide existing shown slides\n for (let i = 0; i < slides.length; i++) {\n slides[i].classList.remove('show');\n }\n // Show current slide\n slides[slideIndex % slides.length].classList.add('show');\n slideIndex++;\n setTimeout(showSlides, 2500);\n}\n\nwindow.addEventListener('load', showSlides); .container {\n height: 274px; /* maximum image height */\n}\n\n.slide {\n position: absolute;\n opacity: 0; /* hide until `show` class */\n transition: opacity 0.5s;\n}\n.slide.show {\n opacity: 1;\n} <h1>Before Container</h1>\n\n<div class=\"container\">\n <img class=\"slide\" src=\"https://www.wikipedia.org/portal/wikipedia.org/assets/img/Wikipedia-logo-v2@1.5x.png\">\n <img class=\"slide\" src=\"https://www.wikiversity.org/portal/wikiversity.org/assets/img/Wikiversity-logo-tiles_1.5x.png\">\n</div>\n\n<h1>After Container</h1>" }, { "answer_id": 74538483, "author": "Shivangam Soni", "author_id": 16659219, "author_profile": "https://Stackoverflow.com/users/16659219", "pm_score": 1, "selected": false, "text": "var slides = document.getElementsByClassName(\"mySlides\");\nvar slideIndex = 0;\n\n// Sow the First Image Initially\nslides[0].classList.add(\"show\");\n\nsetInterval(showSlides, 2500);\n\nfunction showSlides() {\n // Hide Current\n slides[slideIndex].classList.remove(\"show\");\n\n // Change Index\n slideIndex++;\n if (slideIndex >= slides.length) {\n slideIndex = 0\n }\n \n // Show New Current\n slides[slideIndex].classList.add(\"show\");\n} .p-centered {\n position: relative;\n}\n\n.mySlides {\n position: absolute;\n top: 0;\n left: 0;\n opacity: 0;\n transition: all 2000ms;\n}\n\n.mySlides.show {\n opacity: 1;\n} <div class=\"p-centered\">\n <img src=\"https://picsum.photos/200?1\" class=\"img-responsive mySlides\" alt=\"\">\n <img src=\"https://picsum.photos/200?2\" class=\"img-responsive mySlides\" alt=\"\">\n <img src=\"https://picsum.photos/200?3\" class=\"img-responsive mySlides\" alt=\"\">\n <img src=\"https://picsum.photos/200?4\" class=\"img-responsive mySlides\" alt=\"\">\n <img src=\"https://picsum.photos/200?5\" class=\"img-responsive mySlides\" alt=\"\">\n</div>" }, { "answer_id": 74538823, "author": "John Li", "author_id": 20436957, "author_profile": "https://Stackoverflow.com/users/20436957", "pm_score": 2, "selected": false, "text": "pointer-events display: grid var slideIndex = 0;\nvar slides = document.getElementsByClassName(\"mySlides\");\n\n// Moved some static styles to CSS to keep it clean here\nshowSlides();\n\nfunction showSlides() {\n // Show the current image\n slides[slideIndex].classList.add(\"active\"); \n // Hide the previous image\n const prevIndex = slideIndex === 0 ? slides.length - 1 : slideIndex - 1;\n slides[prevIndex].classList.remove(\"active\");\n // Add index for next cycle\n slideIndex === slides.length - 1 ? (slideIndex = 0) : slideIndex++;\n // Set delay for next cycle\n setTimeout(showSlides, 2500);\n} .p-centered {\n display: grid;\n width: fit-content;\n}\n\n.mySlides {\n grid-area: 1/ 1/ 1 /1;\n opacity: 0;\n pointer-events: none;\n transition: opacity 0.50s linear;\n}\n\n.active {\n opacity: 1;\n pointer-events: auto;\n} <div class=\"p-centered\">\n <img src=\"https://picsum.photos/200?1\" class=\"img-responsive mySlides\" alt=\"\">\n <img src=\"https://picsum.photos/200?2\" class=\"img-responsive mySlides\" alt=\"\">\n <img src=\"https://picsum.photos/200?3\" class=\"img-responsive mySlides\" alt=\"\">\n <img src=\"https://picsum.photos/200?4\" class=\"img-responsive mySlides\" alt=\"\">\n <img src=\"https://picsum.photos/200?5\" class=\"img-responsive mySlides\" alt=\"\">\n</div>" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74538102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1925934/" ]
74,538,164
<p>I need to run:</p> <pre class="lang-sql prettyprint-override"><code>select arrayagg(o_clerk) within group (order by o_orderkey desc) OVER (PARTITION BY o_orderkey order by o_orderkey ROWS BETWEEN 3 PRECEDING AND CURRENT ROW) AS RESULT from sample_data </code></pre> <p>But Snowflake returns the error <code>Sliding window frame unsupported for function ARRAYAGG</code>. If I try to accumulate all without a sliding window, I get the error <code>Cumulative window frame unsupported for function ARRAY_AGG</code>.</p> <p>How can I achieve this?</p> <p>Sample data:</p> <pre class="lang-sql prettyprint-override"><code>create or replace table sample_data as ( with data as ( select 1 a, [1,3,2,4,7,8,10] b union all select 2, [1,3,2,4,7,8,10] ) select 'Ord'||a o_orderkey, 'c'||value o_clerk, index from data, table(flatten(b)) ) ; </code></pre> <p><a href="https://i.stack.imgur.com/cEjP7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cEjP7.png" alt="enter image description here" /></a></p> <p>Desired result:</p> <p><a href="https://i.stack.imgur.com/gZwVr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gZwVr.png" alt="enter image description here" /></a></p> <p>(<a href="https://community.snowflake.com/s/question/0D53r0000BySd2JCQS/migrate-from-big-query-to-snowflake-as-per-the-documentation-arrayagg-does-not-support-window-framehow-to-achieve-a-big-query-arrayagg-implementation-in-snowflake" rel="nofollow noreferrer">source</a>, for a BigQuery migration)</p>
[ { "answer_id": 74538165, "author": "Felipe Hoffa", "author_id": 132438, "author_profile": "https://Stackoverflow.com/users/132438", "pm_score": 1, "selected": false, "text": "ARRAY_AGG() with numbered as (\n select o_orderkey, o_clerk, index\n from sample_data\n), crossed as (\n select a.o_orderkey, a.index ai, b.index bi, b.o_clerk\n from numbered a\n join numbered b\n on a.o_orderkey = b.o_orderkey\n and a.index between b.index and b.index+3\n)\n\nselect o_orderkey, array_agg(o_clerk) within group (order by bi)\nfrom crossed\ngroup by o_orderkey, ai\norder by o_orderkey, max(bi)\n index" }, { "answer_id": 74538423, "author": "Lukasz Szozda", "author_id": 5070879, "author_profile": "https://Stackoverflow.com/users/5070879", "pm_score": 1, "selected": false, "text": "ARRAY_AGG ARRAY_SLICE SELECT *\n ,IFF(ROW_NUMBER() OVER(PARTITION BY o_orderkey ORDER BY INDEX) <= 4, 0, \n ROW_NUMBER() OVER(PARTITION BY o_orderkey ORDER BY INDEX)-4) AS start_index\n ,IFF(ROW_NUMBER() OVER(PARTITION BY o_orderkey ORDER BY INDEX) <= 4, \n ROW_NUMBER() OVER(PARTITION BY o_orderkey ORDER BY INDEX),4) AS num_elem\n\n ,ARRAY_SLICE(\n ARRAY_AGG(o_clerk) WITHIN GROUP (ORDER BY INDEX)\n OVER(PARTITION BY o_orderkey)\n ,start_index\n ,start_index + num_elem) \nFROM sample_data\nORDER BY O_ORDERKEY, INDEX;\n ROWS BETWEEN PRECEDING prec AND FOLLOWING foll SELECT *\n ,ROW_NUMBER() OVER(PARTITION BY o_orderkey ORDER BY INDEX) AS rn\n ,3 AS prec\n ,0 AS foll\n ,ARRAY_SLICE(\n ARRAY_AGG(o_clerk) WITHIN GROUP (ORDER BY INDEX) \n OVER(PARTITION BY o_orderkey)\n ,IFF(rn <= prec+1, 0, rn-(prec+1))\n ,IFF(rn <= prec+1, 0, rn-(prec+1)) + IFF(rn <= prec+1, rn+foll,prec+1+foll)\n ) \nFROM sample_data\nORDER BY O_ORDERKEY, INDEX;\n" }, { "answer_id": 74564838, "author": "Emanuel Oliveira", "author_id": 8225104, "author_profile": "https://Stackoverflow.com/users/8225104", "pm_score": 3, "selected": true, "text": "select o_orderkey, \n array_compact([\n lag(o_clerk, 3) over(partition by o_orderkey order by index)\n , lag(o_clerk, 2) over(partition by o_orderkey order by index)\n , lag(o_clerk, 1) over(partition by o_orderkey order by index)\n , o_clerk\n ])\nfrom sample_data" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74538164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/132438/" ]
74,538,172
<p>I have the code which is running properly, how can i write this piece of code better</p> <pre><code>if (!this.isThis) { return [ { label: this.$t('profile'), value: this.acc.AccountNumber, id: 'ProfileNumber' }, ] } else { return [ { label: this.$t('market'), value: this.acc.label, id: 'market' }, { label: this.$t('profile'), value: this.acc.AccountNumber, id: 'ProfileNumber' }, { label: this.$t('account'), value: this.acc.profile, id: 'account' } ] } </code></pre> <p>can i use some better js code to handle this, above works but there are better ways to write</p>
[ { "answer_id": 74538165, "author": "Felipe Hoffa", "author_id": 132438, "author_profile": "https://Stackoverflow.com/users/132438", "pm_score": 1, "selected": false, "text": "ARRAY_AGG() with numbered as (\n select o_orderkey, o_clerk, index\n from sample_data\n), crossed as (\n select a.o_orderkey, a.index ai, b.index bi, b.o_clerk\n from numbered a\n join numbered b\n on a.o_orderkey = b.o_orderkey\n and a.index between b.index and b.index+3\n)\n\nselect o_orderkey, array_agg(o_clerk) within group (order by bi)\nfrom crossed\ngroup by o_orderkey, ai\norder by o_orderkey, max(bi)\n index" }, { "answer_id": 74538423, "author": "Lukasz Szozda", "author_id": 5070879, "author_profile": "https://Stackoverflow.com/users/5070879", "pm_score": 1, "selected": false, "text": "ARRAY_AGG ARRAY_SLICE SELECT *\n ,IFF(ROW_NUMBER() OVER(PARTITION BY o_orderkey ORDER BY INDEX) <= 4, 0, \n ROW_NUMBER() OVER(PARTITION BY o_orderkey ORDER BY INDEX)-4) AS start_index\n ,IFF(ROW_NUMBER() OVER(PARTITION BY o_orderkey ORDER BY INDEX) <= 4, \n ROW_NUMBER() OVER(PARTITION BY o_orderkey ORDER BY INDEX),4) AS num_elem\n\n ,ARRAY_SLICE(\n ARRAY_AGG(o_clerk) WITHIN GROUP (ORDER BY INDEX)\n OVER(PARTITION BY o_orderkey)\n ,start_index\n ,start_index + num_elem) \nFROM sample_data\nORDER BY O_ORDERKEY, INDEX;\n ROWS BETWEEN PRECEDING prec AND FOLLOWING foll SELECT *\n ,ROW_NUMBER() OVER(PARTITION BY o_orderkey ORDER BY INDEX) AS rn\n ,3 AS prec\n ,0 AS foll\n ,ARRAY_SLICE(\n ARRAY_AGG(o_clerk) WITHIN GROUP (ORDER BY INDEX) \n OVER(PARTITION BY o_orderkey)\n ,IFF(rn <= prec+1, 0, rn-(prec+1))\n ,IFF(rn <= prec+1, 0, rn-(prec+1)) + IFF(rn <= prec+1, rn+foll,prec+1+foll)\n ) \nFROM sample_data\nORDER BY O_ORDERKEY, INDEX;\n" }, { "answer_id": 74564838, "author": "Emanuel Oliveira", "author_id": 8225104, "author_profile": "https://Stackoverflow.com/users/8225104", "pm_score": 3, "selected": true, "text": "select o_orderkey, \n array_compact([\n lag(o_clerk, 3) over(partition by o_orderkey order by index)\n , lag(o_clerk, 2) over(partition by o_orderkey order by index)\n , lag(o_clerk, 1) over(partition by o_orderkey order by index)\n , o_clerk\n ])\nfrom sample_data" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74538172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20045615/" ]
74,538,180
<p>I've seen plenty of threads on how to find all combinations that add up to a number with one list, but wanted to know how to expand this such that you can only pick one number at a time, from a list of lists</p> <p><strong>Question:</strong><br/> You must select 1 number from each list, how do you find all combinations that sum to N?</p> <p><strong>Given:</strong><br/> 3 lists of differing fixed lengths [e.g. l1 will always have 6 values, l2 will always have 10 values, etc]:</p> <pre><code>l1 = [0.013,0.014,0.015,0.016,0.017,0.018] l2 = [0.0396,0.0408,0.042,0.0432,0.0444,0.045,0.0468,0.048,0.0492,0.0504] l3 = [0.0396,0.0408] </code></pre> <p><strong>Desired Output:</strong><br/> If N = .0954 then the output is [0.015, 0.396, 0.408],[0.015, 0.408, 0.0396].</p> <p><strong>What I have tried:</strong><br/></p> <pre><code>output = sum(list(product(l1,l2,l3,l4,l5,l6,l7,l8))) </code></pre> <p>However this is too intensive as my largest bucket has 34 values, creating too many combinations.</p> <p>Any help/tips on how to approach this in a more efficient manner would be greatly appreciated!</p>
[ { "answer_id": 74538165, "author": "Felipe Hoffa", "author_id": 132438, "author_profile": "https://Stackoverflow.com/users/132438", "pm_score": 1, "selected": false, "text": "ARRAY_AGG() with numbered as (\n select o_orderkey, o_clerk, index\n from sample_data\n), crossed as (\n select a.o_orderkey, a.index ai, b.index bi, b.o_clerk\n from numbered a\n join numbered b\n on a.o_orderkey = b.o_orderkey\n and a.index between b.index and b.index+3\n)\n\nselect o_orderkey, array_agg(o_clerk) within group (order by bi)\nfrom crossed\ngroup by o_orderkey, ai\norder by o_orderkey, max(bi)\n index" }, { "answer_id": 74538423, "author": "Lukasz Szozda", "author_id": 5070879, "author_profile": "https://Stackoverflow.com/users/5070879", "pm_score": 1, "selected": false, "text": "ARRAY_AGG ARRAY_SLICE SELECT *\n ,IFF(ROW_NUMBER() OVER(PARTITION BY o_orderkey ORDER BY INDEX) <= 4, 0, \n ROW_NUMBER() OVER(PARTITION BY o_orderkey ORDER BY INDEX)-4) AS start_index\n ,IFF(ROW_NUMBER() OVER(PARTITION BY o_orderkey ORDER BY INDEX) <= 4, \n ROW_NUMBER() OVER(PARTITION BY o_orderkey ORDER BY INDEX),4) AS num_elem\n\n ,ARRAY_SLICE(\n ARRAY_AGG(o_clerk) WITHIN GROUP (ORDER BY INDEX)\n OVER(PARTITION BY o_orderkey)\n ,start_index\n ,start_index + num_elem) \nFROM sample_data\nORDER BY O_ORDERKEY, INDEX;\n ROWS BETWEEN PRECEDING prec AND FOLLOWING foll SELECT *\n ,ROW_NUMBER() OVER(PARTITION BY o_orderkey ORDER BY INDEX) AS rn\n ,3 AS prec\n ,0 AS foll\n ,ARRAY_SLICE(\n ARRAY_AGG(o_clerk) WITHIN GROUP (ORDER BY INDEX) \n OVER(PARTITION BY o_orderkey)\n ,IFF(rn <= prec+1, 0, rn-(prec+1))\n ,IFF(rn <= prec+1, 0, rn-(prec+1)) + IFF(rn <= prec+1, rn+foll,prec+1+foll)\n ) \nFROM sample_data\nORDER BY O_ORDERKEY, INDEX;\n" }, { "answer_id": 74564838, "author": "Emanuel Oliveira", "author_id": 8225104, "author_profile": "https://Stackoverflow.com/users/8225104", "pm_score": 3, "selected": true, "text": "select o_orderkey, \n array_compact([\n lag(o_clerk, 3) over(partition by o_orderkey order by index)\n , lag(o_clerk, 2) over(partition by o_orderkey order by index)\n , lag(o_clerk, 1) over(partition by o_orderkey order by index)\n , o_clerk\n ])\nfrom sample_data" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74538180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7787537/" ]
74,538,190
<p>Currently I'm using checkmarx to find vulnerabilities on mi code. The javascript files aparently haev some potential xss vulnerabilites when I use jquery val() function and then try to append this val. How should I solve, sanitize or encode this to avoid this problem?</p> <p>Here some examples about what checkmarx mark as vulnerability:</p> <pre><code>function insertContactToTable(table) { var ContactId = jQuery(&quot;#select_contacts&quot;).val(); var ContactName = jQuery(&quot;#select_contacts option:selected&quot;).text(); var Type = jQuery(&quot;#select_contact_type&quot;).val(); if (ContactId != &quot;&quot; &amp;&amp; Type != &quot;&quot;) { var ID = ContactId + &quot;_&quot; + Type; var Img = &quot;&lt;img class='image pointer-item' src='/app/assets/img/icon-package/cross.png' alt='cross' onClick='removeTableLine(\&quot;&quot; + ID + &quot;\&quot;)'/&gt;&quot;; if (jQuery(&quot;#&quot; + table + &quot; tbody tr:last&quot;).length &gt; 0) { jQuery(&quot;#&quot; + table + &quot; tbody tr:last&quot;).after(&quot;&lt;tr id='&quot; + ID + &quot;' name='&quot; + ID + &quot;'&gt;&lt;td id='&quot; + ID + &quot;' name='contact_list'&gt;&quot; + ContactName + &quot;&lt;/td&gt;&lt;td&gt;&quot; + Type + &quot;&lt;/td&gt;&lt;td&gt;&quot; + Img + &quot;&lt;/td&gt;&lt;/tr&gt;&quot;); } else { jQuery(&quot;#&quot; + table + &quot; tbody&quot;).html(&quot;&lt;tr id='&quot; + ID + &quot;' name='&quot; + ID + &quot;'&gt;&lt;td id='&quot; + ID + &quot;' name='contact_list'&gt;&quot; + ContactName + &quot;&lt;/td&gt;&lt;td&gt;&quot; + Type + &quot;&lt;/td&gt;&lt;td&gt;&quot; + Img + &quot;&lt;/td&gt;&lt;/tr&gt;&quot;); } } ... </code></pre> <p>It marks the following error:</p> <blockquote> <p>The application's insertContactToTable embeds untrusted data in the generated output with after, at line 542 of app\assets\js\administration.js. This untrusted data is embedded straight into the output without proper sanitization or encoding, enabling an attacker to inject malicious code into the output.</p> </blockquote> <p>The line <strong>542</strong> is the <em><strong>jQuery(&quot;#select_contacts&quot;).val();</strong></em> but it happens the same with the others lines that use .val() and .text() function.</p> <p>Also, on other functions happens the same while getting this .val() or .text() functions and trying to use them with append() or html() functions.</p> <p>Finally, I also have same issue while getting ajax response and try to append it with append() o html().</p> <p>Note: I'm using php on my project, sanitizing most of the variables with it.</p> <p><strong>Edit</strong> I changed to DOM object as suggested in comments and the code now looks like this:</p> <pre><code>var ContactId = jQuery(&quot;#select_contacts&quot;).val(); var ContactName = jQuery(&quot;#select_contacts option:selected&quot;).text(); var Type = jQuery(&quot;#select_contact_type&quot;).val(); if (ContactId != &quot;&quot; &amp;&amp; Type != &quot;&quot;) { var ID = ContactId + &quot;_&quot; + Type; var Img = jQuery(&quot;&lt;img&gt;&quot;, { &quot;class&quot;: 'image pointer-item', alt: 'cross', &quot;src&quot;: '/app/assets/img/icon-package/cross.png' }).on(&quot;click&quot;, function() { removeTableLine(ID); }); var row = $(&quot;&lt;tr&gt;&quot;, { id:&quot;TR_&quot; +ID , name: ID }) .append($(&quot;&lt;td&gt;&quot;, { id: ID, name: 'contact_list', text: ContactName })) .append($(&quot;&lt;td&gt;&quot;, { text: Type })) .append($(&quot;&lt;td&gt;&quot;).append(Img)); $(&quot;#&quot; + table + &quot; tbody&quot;).append(row); } </code></pre> <p>but I still have the problem</p>
[ { "answer_id": 74538356, "author": "Barmar", "author_id": 1491895, "author_profile": "https://Stackoverflow.com/users/1491895", "pm_score": 0, "selected": false, "text": "if (ContactId != \"\" && Type != \"\") {\n var ID = ContactId + \"_\" + Type;\n var Img = jQuery(\"<img>\", {\n \"class\": 'image pointer-item',\n alt: 'cross'\n }).click(function() {\n removeTableLine(ID);\n });\n\n var row = $(\"<tr>\", {\n id: ID,\n name: ID\n })\n .append($(\"<td>\", {\n id: ID,\n name: 'contact_list',\n text: ContactName\n }))\n .append($(\"<td>\").append(Img))\n $(\"#\" + table + \" tbody\").append(row);\n} <tr> <td>" }, { "answer_id": 74585098, "author": "securecodeninja", "author_id": 4327668, "author_profile": "https://Stackoverflow.com/users/4327668", "pm_score": -1, "selected": false, "text": "var ContactId = DOMPurify.sanitize(jQuery(\"#select_contacts\").val());\n var ContactName = DOMPurify.sanitize(jQuery(\"#select_contacts option:selected\").text());\n var Type = DOMPurify.sanitize(jQuery(\"#select_contact_type\").val());\n if (ContactId != \"\" && Type != \"\") {\n var ID = ContactId + \"_\" + Type;\n var Img = jQuery(\"<img>\", { \"class\": 'image pointer-item', alt: 'cross', \"src\": '/app/assets/img/icon-package/cross.png'\n }).on(\"click\", function() {\n removeTableLine(ID);\n });\n\n var row = $(\"<tr>\", { id:\"TR_\" +ID , name: ID })\n .append($(\"<td>\", { id: ID, name: 'contact_list', text: ContactName }))\n .append($(\"<td>\", { text: Type }))\n .append($(\"<td>\").append(Img));\n $(\"#\" + table + \" tbody\").append(row);\n } \n // allow only <b> and <q> with style attributes\nvar clean = DOMPurify.sanitize(dirty, {ALLOWED_TAGS: ['b', 'q'], ALLOWED_ATTR: ['style']});\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74538190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13502705/" ]
74,538,199
<p>Here is a small example of the kind of data I have:</p> <pre class="lang-r prettyprint-override"><code>transactions &lt;- tibble(id = seq(1:7), day = paste(rep(&quot;day&quot;, each = 7), seq(1:7), sep = &quot;&quot;), sent_to = c(NA, &quot;Garden Cinema&quot;, &quot;Pasta House&quot;, NA, &quot;Blue Superstore&quot;, &quot;Jane&quot;, &quot;Joe&quot;), received_from = c(&quot;ATM&quot;, NA, NA, &quot;Sarah&quot;, NA, NA, NA), reference = c(&quot;add_cash&quot;, &quot;cinema_tickets&quot;, &quot;meal&quot;, &quot;gift&quot;, &quot;shopping&quot;, &quot;reimbursed&quot;, &quot;reimbursed&quot;), decrease = c(NA, 10.8, 12.5, NA, 15.25, NA, NA), increase = c(50, NA, NA, 30, NA, 5.40, 7.25)) # # A tibble: 7 × 7 # id day sent_to received_from reference decrease increase # &lt;int&gt; &lt;chr&gt; &lt;chr&gt; &lt;chr&gt; &lt;chr&gt; &lt;dbl&gt; &lt;dbl&gt; # 1 1 day1 NA ATM add_cash NA 50 # 2 2 day2 Garden Cinema NA cinema_tickets 10.8 NA # 3 3 day3 Pasta House NA meal 12.5 NA # 4 4 day4 NA Sarah gift NA 30 # 5 5 day5 Blue Superstore NA shopping 15.2 NA # 6 6 day6 Jane NA reimbursed NA 5.4 # 7 7 day7 Joe NA reimbursed NA 7.25 </code></pre> <p>I would like to add a &quot;balance&quot; column to this dataset where:</p> <ul> <li>Row 1: starts with 50</li> <li>Row 2: has previous balance amount + increase - decrease</li> <li>Row 3, etc.: same as row 2 formula</li> </ul> <p>I've been struggling to do this myself as I don't know if there are any existing functions which help with this types of data manipulation. The only function that comes to mind is the <code>dplyr::lag()</code> but I'm not sure how to use it.</p> <p>Any help is appreciated :)</p>
[ { "answer_id": 74538279, "author": "stefan", "author_id": 12993861, "author_profile": "https://Stackoverflow.com/users/12993861", "pm_score": 3, "selected": true, "text": "change purrr::accumulate balance library(dplyr, warn = FALSE)\nlibrary(purrr)\n\ntransactions |> \n mutate(change = coalesce(increase, -decrease),\n balance = accumulate(change, ~ .x + .y))\n#> # A tibble: 7 × 9\n#> id day sent_to received_…¹ refer…² decre…³ incre…⁴ change balance\n#> <int> <chr> <chr> <chr> <chr> <dbl> <dbl> <dbl> <dbl>\n#> 1 1 day1 <NA> ATM add_ca… NA 50 50 50 \n#> 2 2 day2 Garden Cinema <NA> cinema… 10.8 NA -10.8 39.2\n#> 3 3 day3 Pasta House <NA> meal 12.5 NA -12.5 26.7\n#> 4 4 day4 <NA> Sarah gift NA 30 30 56.7\n#> 5 5 day5 Blue Superstore <NA> shoppi… 15.2 NA -15.2 41.4\n#> 6 6 day6 Jane <NA> reimbu… NA 5.4 5.4 46.8\n#> 7 7 day7 Joe <NA> reimbu… NA 7.25 7.25 54.1\n#> # … with abbreviated variable names ¹​received_from, ²​reference, ³​decrease,\n#> # ⁴​increase\n" }, { "answer_id": 74538395, "author": "Flap", "author_id": 20520733, "author_profile": "https://Stackoverflow.com/users/20520733", "pm_score": 2, "selected": false, "text": "change cumsum balance transactions <- transactions %>%\n mutate(\n change = case_when( \n !is.na(decrease) ~ -1*decrease, #make values negative if decrease \n !is.na(increase) ~ increase),\n balance = cumsum(change))\n > transactions\n# A tibble: 7 × 9\n id day sent_to received_from reference decrease increase change balance\n <int> <chr> <chr> <chr> <chr> <dbl> <dbl> <dbl> <dbl>\n1 1 day1 NA ATM add_cash NA 50 50 50 \n2 2 day2 Garden Cinema NA cinema_tickets 10.8 NA -10.8 39.2\n3 3 day3 Pasta House NA meal 12.5 NA -12.5 26.7\n4 4 day4 NA Sarah gift NA 30 30 56.7\n5 5 day5 Blue Superstore NA shopping 15.2 NA -15.2 41.4\n6 6 day6 Jane NA reimbursed NA 5.4 5.4 46.8\n7 7 day7 Joe NA reimbursed NA 7.25 7.25 54.1\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74538199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14315663/" ]
74,538,224
<p>Node's <code>path.relative</code> has an unexpected quirk when resolving a file that is in the <code>from</code> directory. Below the <code>path.relative</code> returns <code>meta_url.ts</code> instead of <code>./meta_url.ts</code>, is there a node path function to help me convert <code>meta_url.ts</code> to <code>./meta_url.ts</code> in an os-agnostic way?</p> <pre><code>const from = &quot;/Users/thomasreggi/Documents/GitHub/htmx-components/custom_import&quot; const to = &quot;./meta_url.ts&quot; path.relative(from, to) // meta_url.ts </code></pre>
[ { "answer_id": 74538279, "author": "stefan", "author_id": 12993861, "author_profile": "https://Stackoverflow.com/users/12993861", "pm_score": 3, "selected": true, "text": "change purrr::accumulate balance library(dplyr, warn = FALSE)\nlibrary(purrr)\n\ntransactions |> \n mutate(change = coalesce(increase, -decrease),\n balance = accumulate(change, ~ .x + .y))\n#> # A tibble: 7 × 9\n#> id day sent_to received_…¹ refer…² decre…³ incre…⁴ change balance\n#> <int> <chr> <chr> <chr> <chr> <dbl> <dbl> <dbl> <dbl>\n#> 1 1 day1 <NA> ATM add_ca… NA 50 50 50 \n#> 2 2 day2 Garden Cinema <NA> cinema… 10.8 NA -10.8 39.2\n#> 3 3 day3 Pasta House <NA> meal 12.5 NA -12.5 26.7\n#> 4 4 day4 <NA> Sarah gift NA 30 30 56.7\n#> 5 5 day5 Blue Superstore <NA> shoppi… 15.2 NA -15.2 41.4\n#> 6 6 day6 Jane <NA> reimbu… NA 5.4 5.4 46.8\n#> 7 7 day7 Joe <NA> reimbu… NA 7.25 7.25 54.1\n#> # … with abbreviated variable names ¹​received_from, ²​reference, ³​decrease,\n#> # ⁴​increase\n" }, { "answer_id": 74538395, "author": "Flap", "author_id": 20520733, "author_profile": "https://Stackoverflow.com/users/20520733", "pm_score": 2, "selected": false, "text": "change cumsum balance transactions <- transactions %>%\n mutate(\n change = case_when( \n !is.na(decrease) ~ -1*decrease, #make values negative if decrease \n !is.na(increase) ~ increase),\n balance = cumsum(change))\n > transactions\n# A tibble: 7 × 9\n id day sent_to received_from reference decrease increase change balance\n <int> <chr> <chr> <chr> <chr> <dbl> <dbl> <dbl> <dbl>\n1 1 day1 NA ATM add_cash NA 50 50 50 \n2 2 day2 Garden Cinema NA cinema_tickets 10.8 NA -10.8 39.2\n3 3 day3 Pasta House NA meal 12.5 NA -12.5 26.7\n4 4 day4 NA Sarah gift NA 30 30 56.7\n5 5 day5 Blue Superstore NA shopping 15.2 NA -15.2 41.4\n6 6 day6 Jane NA reimbursed NA 5.4 5.4 46.8\n7 7 day7 Joe NA reimbursed NA 7.25 7.25 54.1\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74538224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/340688/" ]
74,538,263
<p>I am using React and an API in order to fetch data and prefill it to form fields, so that the user can edit an existing record.</p> <p>However, the child component seems to only be receiving the version of the <code>longhorn</code> entity created in the beginning, instead of the one fetched by the API, also failing to update.</p> <p>Relevant parent page code:</p> <pre><code>React.useEffect(() =&gt; { async function getLonghorn() { let response = await fetch(`http://127.0.0.1:8081/longhorns/${longhornID}`, { method: 'get' }) let data = await response.json(); setLonghorn(await data[0]); }; if (longhorn.Name === &quot;&quot;) { getLonghorn(); } }, [longhorn.Name, longhornID]); return ( &lt;&gt; &lt;Navbar /&gt; &lt;AdminImageUploadUI type=&quot;longhorn&quot; id={longhornID} imageList={imageList}&gt;&lt;/AdminImageUploadUI&gt; &lt;AdminEditLonghornForm {...longhorn} &gt;&lt;/AdminEditLonghornForm&gt; &lt;/&gt; ) </code></pre> <p>Relevant child component code:</p> <pre><code>import React from 'react' import { render } from 'react-dom'; import GetRequest from '../../Get'; type props = { LonghornID: number, Name: string, RanchPrefix: string, RoleID: number, SexID: number, IsExternal:number, FatherLonghornID:number, MotherLonghornID: number, ReferenceNumber: string, DOB: string, Description:string}; class AdminEditLonghornForm extends React.Component&lt;{}, { LonghornID: number, Name: string, RanchPrefix: string, RoleID: number, SexID: number, IsExternal:number, FatherLonghornID:number, MotherLonghornID: number, ReferenceNumber: string, DOB: string, Description:string, message: string}&gt; { constructor(props: props) { super(props) this.state = { LonghornID: props.LonghornID, Name: props.Name, RanchPrefix: props.RanchPrefix, RoleID: props.RoleID, SexID: props.SexID, IsExternal: props.IsExternal, FatherLonghornID: props.FatherLonghornID, MotherLonghornID: props.MotherLonghornID, ReferenceNumber: props.ReferenceNumber, DOB: props.DOB, Description: props.Description, message: '' } } </code></pre> <p>If I console.log the longhorn object in the parent, it duplicates the logs several times, showing the empty default set of data in the first three or so, then showing the filled data in the final few logs. Logging the received props in the child shows empty data every time. I've tried creating a new object and destructuring that in the sent props list but it falls victim to the same initial data showing issues.</p> <p>I suspect it is misusage of the React.UseEffect, but I was having to rely on that to make my async fetch function work properly. Sorry if my code and structure is a bit of a mess, still new to JavaScript</p>
[ { "answer_id": 74538279, "author": "stefan", "author_id": 12993861, "author_profile": "https://Stackoverflow.com/users/12993861", "pm_score": 3, "selected": true, "text": "change purrr::accumulate balance library(dplyr, warn = FALSE)\nlibrary(purrr)\n\ntransactions |> \n mutate(change = coalesce(increase, -decrease),\n balance = accumulate(change, ~ .x + .y))\n#> # A tibble: 7 × 9\n#> id day sent_to received_…¹ refer…² decre…³ incre…⁴ change balance\n#> <int> <chr> <chr> <chr> <chr> <dbl> <dbl> <dbl> <dbl>\n#> 1 1 day1 <NA> ATM add_ca… NA 50 50 50 \n#> 2 2 day2 Garden Cinema <NA> cinema… 10.8 NA -10.8 39.2\n#> 3 3 day3 Pasta House <NA> meal 12.5 NA -12.5 26.7\n#> 4 4 day4 <NA> Sarah gift NA 30 30 56.7\n#> 5 5 day5 Blue Superstore <NA> shoppi… 15.2 NA -15.2 41.4\n#> 6 6 day6 Jane <NA> reimbu… NA 5.4 5.4 46.8\n#> 7 7 day7 Joe <NA> reimbu… NA 7.25 7.25 54.1\n#> # … with abbreviated variable names ¹​received_from, ²​reference, ³​decrease,\n#> # ⁴​increase\n" }, { "answer_id": 74538395, "author": "Flap", "author_id": 20520733, "author_profile": "https://Stackoverflow.com/users/20520733", "pm_score": 2, "selected": false, "text": "change cumsum balance transactions <- transactions %>%\n mutate(\n change = case_when( \n !is.na(decrease) ~ -1*decrease, #make values negative if decrease \n !is.na(increase) ~ increase),\n balance = cumsum(change))\n > transactions\n# A tibble: 7 × 9\n id day sent_to received_from reference decrease increase change balance\n <int> <chr> <chr> <chr> <chr> <dbl> <dbl> <dbl> <dbl>\n1 1 day1 NA ATM add_cash NA 50 50 50 \n2 2 day2 Garden Cinema NA cinema_tickets 10.8 NA -10.8 39.2\n3 3 day3 Pasta House NA meal 12.5 NA -12.5 26.7\n4 4 day4 NA Sarah gift NA 30 30 56.7\n5 5 day5 Blue Superstore NA shopping 15.2 NA -15.2 41.4\n6 6 day6 Jane NA reimbursed NA 5.4 5.4 46.8\n7 7 day7 Joe NA reimbursed NA 7.25 7.25 54.1\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74538263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20489556/" ]
74,538,264
<p>For example, I have the word: <code>sh0rt-t3rm</code>. How can I get the <code>t3rm</code> part using perl regex?</p> <p>I could get <code>sh0rt</code> by using <code>[(a-zA-Z0-9)+]\[-\]</code>, but <code>\[-\][(a-zA-Z0-9)+]</code> doesn't work to get <code>t3rm</code>.</p>
[ { "answer_id": 74538365, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 2, "selected": false, "text": "-([a-zA-Z0-9]+) -" }, { "answer_id": 74538368, "author": "zdim", "author_id": 4653379, "author_profile": "https://Stackoverflow.com/users/4653379", "pm_score": 2, "selected": false, "text": "sh0rt-t3rm - my ($capture) = $string =~ /-(.+)/;\n 1 '' - - my ($capture) = $string =~ /.*-(.+)/;\n * . - my ($capture) = $string =~ /\\b.*?-(.+?)\\b/;\n .+ ? $string \\w . my ($capture) = $string =~ /\\w*?-(\\w+)/;\n \\w [a-zA-Z0-9_]" }, { "answer_id": 74538374, "author": "The fourth bird", "author_id": 5424988, "author_profile": "https://Stackoverflow.com/users/5424988", "pm_score": 3, "selected": true, "text": "sh0rt t3rm sh0rt sh0rt-t3rm \\b - (?=-) t3rm sh0rt-t3rm - - \\K" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74538264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17518144/" ]
74,538,311
<p>I need to merge/combine 4 objects inside and array. The objects are:</p> <pre><code>{&quot;field&quot;: &quot;name&quot;,&quot;lang&quot;: &quot;it&quot;,&quot;text&quot;: &quot;RegoleAziendali&quot;} {&quot;field&quot;: &quot;pdf_url&quot;,&quot;lang&quot;: &quot;it&quot;, &quot;text&quot;: &quot;docs/it/file.pdf&quot;} {&quot;field&quot;: &quot;name&quot;,&quot;lang&quot;: &quot;en&quot;,&quot;text&quot;: &quot;CompanyRules&quot;} {&quot;field&quot;: &quot;pdf_url&quot;,&quot;lang&quot;: &quot;en&quot;, &quot;text&quot;: &quot;docs/en/file.pdf&quot;} </code></pre> <p>Expected Result Should Be made of 2 objects merged by the language.</p> <pre><code>{&quot;lang&quot;: &quot;it&quot;,&quot;name&quot;: &quot;RegoleAziendali&quot;,&quot;pdf_url&quot;:&quot;docs/it/file.pdf&quot;} {&quot;lang&quot;: &quot;en&quot;,&quot;name&quot;: &quot;CompanyRules&quot;,&quot;pdf_url&quot;:&quot;docs/en/file.pdf&quot;} </code></pre> <p>At the moment I am using array.forEach to merge two objects by lang. But I can not find a way to manipulate the values/properties. As you can see the property &quot;field&quot; is no longer needed in the merged objects.</p>
[ { "answer_id": 74538406, "author": "cmgchess", "author_id": 13583510, "author_profile": "https://Stackoverflow.com/users/13583510", "pm_score": 3, "selected": true, "text": "lang reduce Object.values const x = [\n{\"field\": \"name\",\"lang\": \"it\",\"text\": \"RegoleAziendali\"},\n{\"field\": \"pdf_url\",\"lang\": \"it\", \"text\": \"docs/it/file.pdf\"},\n{\"field\": \"name\",\"lang\": \"en\",\"text\": \"CompanyRules\"},\n{\"field\": \"pdf_url\",\"lang\": \"en\", \"text\": \"docs/en/file.pdf\"}\n]\n\nconst res = Object.values(x.reduce((acc,{field,lang,text}) => {\n acc[lang] = acc[lang] || {lang}\n acc[lang][field] = text\n return acc\n},{}))\n\nconsole.log(res) const x = [{\"field\": \"name\",\"lang\": \"it\",\"text\": \"RegoleAziendali\"},{\"field\": \"pdf_url\",\"lang\": \"it\", \"text\": \"docs/it/file.pdf\"},{\"field\": \"name\",\"lang\": \"en\",\"text\": \"CompanyRules\"},{\"field\": \"pdf_url\",\"lang\": \"en\", \"text\": \"docs/en/file.pdf\"}]\n\nconst res = {}\nfor (const entry of x){\n const {field,lang,text} = entry\n res[lang] = res[lang] || {lang}\n res[lang][field] = text\n}\n\nconsole.log(Object.values(res))" }, { "answer_id": 74538441, "author": "Andrew Parks", "author_id": 5898421, "author_profile": "https://Stackoverflow.com/users/5898421", "pm_score": 1, "selected": false, "text": "const data = [\n {\"field\": \"name\",\"lang\": \"it\",\"text\": \"RegoleAziendali\"},\n {\"field\": \"pdf_url\",\"lang\": \"it\", \"text\": \"docs/it/file.pdf\"},\n {\"field\": \"name\",\"lang\": \"en\",\"text\": \"CompanyRules\"},\n {\"field\": \"pdf_url\",\"lang\": \"en\", \"text\": \"docs/en/file.pdf\"}\n]\n\nconst lookup = (lang, field) => ({\n [field]: data.find(i=>i.lang===lang && i.field===field).text\n})\n\nconsole.log([...new Set(data.map(i=>i.lang))].map(lang=>({\n lang, ...lookup(lang, 'name'), ...lookup(lang, 'pdf_url')\n})))" }, { "answer_id": 74538454, "author": "Asraf", "author_id": 20361860, "author_profile": "https://Stackoverflow.com/users/20361860", "pm_score": 2, "selected": false, "text": "const arr = [{\"field\": \"name\",\"lang\": \"it\",\"text\": \"RegoleAziendali\"}, {\"field\": \"pdf_url\",\"lang\": \"it\", \"text\": \"docs/it/file.pdf\"}, {\"field\": \"name\",\"lang\": \"en\",\"text\": \"CompanyRules\"}, {\"field\": \"pdf_url\",\"lang\": \"en\", \"text\": \"docs/en/file.pdf\"}];\n\n\nconst ans = arr.reduce((a,{field,lang,text}) => ({...a, [lang]: {...a[lang], [field]: text, lang }}), {});\n\nconsole.log(Object.values(ans));" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74538311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8488158/" ]