qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,623,821
|
<p>I want to install python3.7 by anaconda and the anaconda list is shown below:
<a href="https://i.stack.imgur.com/6bc5c.png" rel="nofollow noreferrer">anaconda version list</a>。
My question is how can I know a anaconda installer is for a special verison of python?</p>
<p>Actually, I know "Anaconda3-2020.05-Linux-x86_64.sh" is for python3.7。However, I am confused that by what infomation we can get the answer before we finish installing it.</p>
|
[
{
"answer_id": 74635235,
"author": "NetMage",
"author_id": 2557128,
"author_profile": "https://Stackoverflow.com/users/2557128",
"pm_score": 3,
"selected": true,
"text": "foreach while (MoveNext()) try finally Dispose() Select finally try catch try catch Select foreach foreach Dispose AggregateException foreach var b = true;\nvar query = Enumerable.Range(1, 3)\n .AsParallel()\n .Select(x => {\n Thread.Sleep(50 * (x - 1));\n Console.WriteLine($\"Select({x})\");\n if (x >= 2) {\n throw new Exception($\"Oops {x}!\");\n }\n return x;\n });\n\ntry {\n query.ForEachAggregatingExceptions(item => {\n Console.WriteLine($\"Consuming item #{item} started\");\n if (b) {\n throw new Exception($\"Consuming item #{item} failed\");\n }\n });\n}\ncatch (AggregateException aex) {\n Console.WriteLine($\"AggregateException ({aex.InnerExceptions.Count})\");\n foreach (Exception ex in aex.InnerExceptions)\n Console.WriteLine($\"- {ex.GetType().Name}: {ex.Message}\");\n}\ncatch (Exception ex) {\n Console.WriteLine($\"{ex.GetType().Name}: {ex.Message}\");\n}\n\npublic static class ParallelQueryExt {\n public static void ForEachAggregatingExceptions<T>(this ParallelQuery<T> pq, Action<T> processFn) {\n Exception FirstException = null;\n var e = pq.GetEnumerator();\n try {\n while (e.MoveNext())\n processFn(e.Current);\n }\n catch (Exception ex) {\n FirstException = ex;\n }\n finally {\n if (e != null) {\n try {\n e.Dispose();\n }\n catch (AggregateException aex) { // combine exceptions from Dispose with FirstException if any\n if (FirstException != null) {\n throw new AggregateException(aex.InnerExceptions.Prepend(FirstException));\n }\n else\n throw;\n }\n catch (Exception ex) { // combine single exception from Dispose with FirstException if any\n throw new AggregateException(new[] { ex, FirstException });\n }\n if (FirstException != null) // re-throw FirstException if no others occurred\n throw FirstException;\n }\n }\n }\n}\n b if while if throw"
},
{
"answer_id": 74673923,
"author": "Theodor Zoulias",
"author_id": 11178549,
"author_profile": "https://Stackoverflow.com/users/11178549",
"pm_score": 0,
"selected": false,
"text": "Dispose Dispose Task Task TaskScheduler.UnobservedTaskException Dispose Task AggregateException Dispose TaskScheduler.UnobservedTaskException Task.FromException /// <summary>\n/// Suppresses the error that might be thrown by the enumerator on Dispose.\n/// The error triggers the TaskScheduler.UnobservedTaskException event.\n/// </summary>\npublic static IEnumerable<TSource> SuppressDisposeException<TSource>(\n this IEnumerable<TSource> source)\n{\n ArgumentNullException.ThrowIfNull(source);\n IEnumerator<TSource> enumerator = source.GetEnumerator();\n try\n {\n while (enumerator.MoveNext()) yield return enumerator.Current;\n try { enumerator.Dispose(); } finally { enumerator = null; }\n }\n finally\n {\n try { enumerator?.Dispose(); }\n catch (Exception ex) { _ = Task.FromException(ex); }\n }\n}\n false MoveNext Dispose IEnumerable<int> query = Enumerable.Range(1, 2)\n .AsParallel()\n .Select(x => /* ... */ x)\n .SuppressDisposeException();\n TaskScheduler.UnobservedTaskException GC.Collect Dispose break foreach"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20328371/"
] |
74,623,843
|
<p>I wanted to add some css to my html, but whenever I tried to use external css, the style is never applied. When I use inline or internal css everything works as intended, and I can't find what went wrong.</p>
<p>Here I am using external css for my first div and inline css for my second div. The css applied to the two divs are basically the same. The css for the first div doesn't work but it does on the second so the problem isn't with the code, it with linking to the css file, but I should be doing the link tag right. The two files are definitely in the same folder.</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>.q {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<title>Search</title>
<link rel="stylesheet" href="index.css" />
</head>
<body>
<form action="https://google.com/search">
<div class="q">
<input type="text" name="q">
</div>
<div class="button" style="position:absolute; left:50%; top: 50%; transform: translate(-50%, 90%);">
<input type="submit" value="Google Search">
</div>
</form>
</body>
</html></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74624090,
"author": "madhushankarox",
"author_id": 1633386,
"author_profile": "https://Stackoverflow.com/users/1633386",
"pm_score": -1,
"selected": false,
"text": "404"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20472757/"
] |
74,623,848
|
<p>I'm trying to add dynamic event key to button.</p>
<pre><code>interface ButtonProps{
actionType: string,
actionCb: any
}
const Button = (props: ButtonProps)=>{
return (
<button {props.actionType}={props.actionCB}>
Click me
</button>
)
}
</code></pre>
<p>is it possible to do something like this? or is there any other workaround for this?
thanks!</p>
|
[
{
"answer_id": 74624090,
"author": "madhushankarox",
"author_id": 1633386,
"author_profile": "https://Stackoverflow.com/users/1633386",
"pm_score": -1,
"selected": false,
"text": "404"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1534398/"
] |
74,623,851
|
<pre><code>from django.shortcuts import render
# Create your views here.
def home(request):
return render(request, 'dashboard/home.html')
</code></pre>
<pre><code>from django.urls import path
from . import views
urlpatterns = [
path('', views.home),
]
</code></pre>
<p>Plz Help me to Resolve the Problem</p>
<p>adding path in template_DIRs</p>
|
[
{
"answer_id": 74624090,
"author": "madhushankarox",
"author_id": 1633386,
"author_profile": "https://Stackoverflow.com/users/1633386",
"pm_score": -1,
"selected": false,
"text": "404"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19680867/"
] |
74,623,860
|
<p>so im fiddling around in pytbon cuz im bored and i realise i try to slow print a input i have earlier in the code i bave defined slow print ive imported every thing i need but when i run it it saw its got 1 positional argument buts been give 2 and im not that good at coding and am only a young student so coupd anyone be a huge help and explain it in basic terms</p>
<p>`</p>
<pre><code>import sys
import os
import time
def print_slow(str):
for letter in str:
sys.stdout.write(letter)
sys.stdout.flush()
time.sleep(0.1)
num1 = int(input("Chose any number: "))
print_slow("Did you say",num1)
</code></pre>
<p>so my issue is that i cant seem to get it to slow print i expected this to work like it always does but i've never slow printed an input before</p>
|
[
{
"answer_id": 74624090,
"author": "madhushankarox",
"author_id": 1633386,
"author_profile": "https://Stackoverflow.com/users/1633386",
"pm_score": -1,
"selected": false,
"text": "404"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20599987/"
] |
74,623,868
|
<p>So i recently updated my code with the latest admob SDK and dependencies.
it is supposed to show an interstitial ad before going to the next page.
upon running it the StartActivity is stuck on process dialog and wont go to the next page.
here is the code</p>
<pre><code>
//Start Here
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(StartActivity.this,StartActivity.this.getString(R.string.main_inter), adRequest,
new InterstitialAdLoadCallback() {
@Override
public void onAdLoaded(@NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
pd.dismiss();
mInterstitialAd = interstitialAd;
mInterstitialAd.show(StartActivity.this);
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback(){
@Override
public void onAdClicked() {
// Called when a click is recorded for an ad.
}
@Override
public void onAdDismissedFullScreenContent() {
// Called when ad is dismissed.
// Set the ad reference to null so you don't show the ad a second time.
pd.dismiss();
mInterstitialAd = null;
startActivity(new Intent(StartActivity.this, MainActivity.class));
StartActivity.this.finish();
}
@Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
// Called when ad fails to show.
mInterstitialAd = null;
}
@Override
public void onAdImpression() {
// Called when an impression is recorded for an ad.
}
@Override
public void onAdShowedFullScreenContent() {
// Called when ad is shown.
}
});
}
@Override
public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
// Handle the error
mInterstitialAd = null;
}
});
}
});
}
}
</code></pre>
|
[
{
"answer_id": 74624090,
"author": "madhushankarox",
"author_id": 1633386,
"author_profile": "https://Stackoverflow.com/users/1633386",
"pm_score": -1,
"selected": false,
"text": "404"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20642163/"
] |
74,623,899
|
<p>I am preparing for Oracle certification exam so could you explain how 10!=2 is getting true and compilation error, I have mention a small program below.
10!=2 : why it is true
"Hello "+10!=2 : why it is compile time error</p>
<p>public class Demo1 {</p>
<pre><code>public static void main(String[] args1) {
System.out.println(10!=2); //Output is True
System.out.println("Hello "+10!=2); //Compile Time Error
}
</code></pre>
<p>}</p>
|
[
{
"answer_id": 74624090,
"author": "madhushankarox",
"author_id": 1633386,
"author_profile": "https://Stackoverflow.com/users/1633386",
"pm_score": -1,
"selected": false,
"text": "404"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1619854/"
] |
74,623,953
|
<p>I used the bottom sheet and I'm using navigator.pop on the button inside the bottom sheet but want to refresh the first screen when calling popup...</p>
<p><strong>code</strong></p>
<pre><code>showModalBottomSheet(
context: context,
builder: (BuildContext bc) {
return Container(
child: Wrap(
children: <Widget>[
ListTile(
leading: Icon(Icons.delete),
title: Text('delete'),
onTap: () async {
try {
final file = await File(path);
print(path);
await file.delete();
print(file);
} catch (e) {
print(e.toString());
}
Navigator.pop(context);
setState(() {
print('delete');
});
</code></pre>
|
[
{
"answer_id": 74624090,
"author": "madhushankarox",
"author_id": 1633386,
"author_profile": "https://Stackoverflow.com/users/1633386",
"pm_score": -1,
"selected": false,
"text": "404"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20378705/"
] |
74,623,963
|
<p>I need to find all occurrences of duplicate records in a PySpark DataFrame. Following is the sample dataset:</p>
<pre><code># Prepare Data
data = [("A", "A", 1), \
("A", "A", 2), \
("A", "A", 3), \
("A", "B", 4), \
("A", "B", 5), \
("A", "C", 6), \
("A", "D", 7), \
("A", "E", 8), \
]
# Create DataFrame
columns= ["col_1", "col_2", "col_3"]
df = spark.createDataFrame(data = data, schema = columns)
df.show(truncate=False)
</code></pre>
<p><a href="https://i.stack.imgur.com/42tmY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/42tmY.png" alt="enter image description here" /></a></p>
<p>When I try the following code:</p>
<pre><code>primary_key = ['col_1', 'col_2']
duplicate_records = df.exceptAll(df.dropDuplicates(primary_key))
duplicate_records.show()
</code></pre>
<p>The output will be:</p>
<p><a href="https://i.stack.imgur.com/HGLUP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HGLUP.png" alt="enter image description here" /></a></p>
<p>As you can see, I don't get all occurrences of duplicate records based on the Primary Key since one instance of duplicate records is present in "df.dropDuplicates(primary_key)". The 1st and the 4th records of the dataset must be in the output.</p>
<p>Any idea to solve this issue?</p>
|
[
{
"answer_id": 74624090,
"author": "madhushankarox",
"author_id": 1633386,
"author_profile": "https://Stackoverflow.com/users/1633386",
"pm_score": -1,
"selected": false,
"text": "404"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9668218/"
] |
74,623,982
|
<p>I am very fresh in Python. I would like to read JSON files in Python, but I did not get what are the problems. Please see the image.</p>
<p><a href="https://i.stack.imgur.com/ne61h.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ne61h.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74624059,
"author": "imad97",
"author_id": 18183846,
"author_profile": "https://Stackoverflow.com/users/18183846",
"pm_score": 1,
"selected": false,
"text": "with open(r'path/to/read/','r') as file: \n data = json.load(file)\n"
},
{
"answer_id": 74624157,
"author": "Ugur Baran",
"author_id": 17837629,
"author_profile": "https://Stackoverflow.com/users/17837629",
"pm_score": 0,
"selected": false,
"text": "import sys\nimport os\nimport json\n\ndef JsonRead(str):\n with open(str, encoding='utf-8') as f:\n data = json.load(f)\n return data\n\nnew_Data = JsonRead(filePath)\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19198536/"
] |
74,624,004
|
<p>this is going to be a body of the particular Question.</p>
<p>which function we are using in array .</p>
|
[
{
"answer_id": 74624059,
"author": "imad97",
"author_id": 18183846,
"author_profile": "https://Stackoverflow.com/users/18183846",
"pm_score": 1,
"selected": false,
"text": "with open(r'path/to/read/','r') as file: \n data = json.load(file)\n"
},
{
"answer_id": 74624157,
"author": "Ugur Baran",
"author_id": 17837629,
"author_profile": "https://Stackoverflow.com/users/17837629",
"pm_score": 0,
"selected": false,
"text": "import sys\nimport os\nimport json\n\ndef JsonRead(str):\n with open(str, encoding='utf-8') as f:\n data = json.load(f)\n return data\n\nnew_Data = JsonRead(filePath)\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20642045/"
] |
74,624,023
|
<p>I have table <code>element_types</code> with column <code>element_type</code> containing amount types <code>Basic Salary</code> and <code>Housing Allowance</code>, i want to produce 2 column, one for <code>Basic Salary</code> and another for <code>Housing Allowance</code>, these types are linked to another table like employees and the values for those types ..etc, so I want to make 2 separate columns and not displaying types and amounts in rows.</p>
<pre><code>SELECT .....,
(SELECT element_name
FROM pay_element_types_tl
WHERE element_name IN ('Basic Salary')) Salary,
(SELECT element_name
FROM pay_element_types_tl
WHERE element_name IN ('Housing Allowance')) Housing
</code></pre>
<p>this gives error</p>
<blockquote>
<pre><code>single-row subquery returns multiple rows
</code></pre>
</blockquote>
<p>how can I achieve what I want?</p>
<p>i've tried to use multi-rows subquery using <code>where</code> but i want more than a column with different names derived from the same column</p>
|
[
{
"answer_id": 74624108,
"author": "Jonas Metzler",
"author_id": 18794826,
"author_profile": "https://Stackoverflow.com/users/18794826",
"pm_score": 2,
"selected": true,
"text": "CASE WHEN SELECT \nCASE WHEN element_name = 'Basic Salary'\n THEN element_name END AS Salary,\nCASE WHEN element_name = 'Housing Allowance'\n THEN element_name END AS Housing\nFROM PAY_ELEMENT_TYPES_TL;\n MAX MIN"
},
{
"answer_id": 74624631,
"author": "Barbaros Özhan",
"author_id": 5841306,
"author_profile": "https://Stackoverflow.com/users/5841306",
"pm_score": 0,
"selected": false,
"text": "SELECT MAX(CASE\n WHEN element_name = 'Basic Salary' THEN\n element_name\n END) AS Salary,\n MAX(CASE\n WHEN element_name = 'Housing Allowance' THEN\n element_name\n END) AS Housing\n FROM pay_element_types_tl\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20642292/"
] |
74,624,072
|
<p>I have a dataframe with the following format:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>Income</th>
<th>Year</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>100</td>
<td>2000</td>
</tr>
<tr>
<td>2</td>
<td>200</td>
<td>2000</td>
</tr>
<tr>
<td>3</td>
<td>300</td>
<td>2000</td>
</tr>
<tr>
<td>4</td>
<td>500</td>
<td>2001</td>
</tr>
<tr>
<td>5</td>
<td>1000</td>
<td>2001</td>
</tr>
<tr>
<td>6</td>
<td>1500</td>
<td>2001</td>
</tr>
<tr>
<td>7</td>
<td>10000</td>
<td>2002</td>
</tr>
<tr>
<td>8</td>
<td>15000</td>
<td>2002</td>
</tr>
<tr>
<td>9</td>
<td>20000</td>
<td>2002</td>
</tr>
</tbody>
</table>
</div>
<p>I'd like to add a column called income_cat with three possible levels; "low", "medium" and "high" depending on whether the income is in the lower 33th percentile, the middle 33th percentile or the top 33th percentile of that specific year.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>Income</th>
<th>Year</th>
<th>income_cat</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>100</td>
<td>2000</td>
<td>low</td>
</tr>
<tr>
<td>2</td>
<td>200</td>
<td>2000</td>
<td>medium</td>
</tr>
<tr>
<td>3</td>
<td>300</td>
<td>2000</td>
<td>high</td>
</tr>
<tr>
<td>4</td>
<td>500</td>
<td>2001</td>
<td>low</td>
</tr>
<tr>
<td>5</td>
<td>1000</td>
<td>2001</td>
<td>medium</td>
</tr>
<tr>
<td>6</td>
<td>1500</td>
<td>2001</td>
<td>high</td>
</tr>
<tr>
<td>7</td>
<td>10000</td>
<td>2002</td>
<td>low</td>
</tr>
<tr>
<td>8</td>
<td>15000</td>
<td>2002</td>
<td>medium</td>
</tr>
<tr>
<td>9</td>
<td>20000</td>
<td>2002</td>
<td>high</td>
</tr>
</tbody>
</table>
</div>
<p>I struggle to find the proper way to do this and would be very thankful for any suggestions!</p>
|
[
{
"answer_id": 74624274,
"author": "Tom Hoel",
"author_id": 17213355,
"author_profile": "https://Stackoverflow.com/users/17213355",
"pm_score": 2,
"selected": true,
"text": "library(tidyverse) \n\ndf %>% \n group_by(Year) %>% \n mutate(income_cat = case_when(Income > quantile(Income, 0.66) ~ \"High\", \n Income < quantile(Income, 0.33) ~ \"Low\", \n between(Income, \n quantile(Income, 0.33),\n quantile(Income, 0.66)) ~ \"Medium\"))\n\n# A tibble: 9 x 4\n# Groups: Year [3]\n ID Income Year income_cat\n <dbl> <dbl> <dbl> <chr> \n1 1 100 2000 Low \n2 2 200 2000 Medium \n3 3 300 2000 High \n4 4 500 2001 Low \n5 5 1000 2001 Medium \n6 6 1500 2001 High \n7 7 10000 2002 Low \n8 8 15000 2002 Medium \n9 9 20000 2002 High \n"
},
{
"answer_id": 74624303,
"author": "Thoughtful_monkey",
"author_id": 19039483,
"author_profile": "https://Stackoverflow.com/users/19039483",
"pm_score": 1,
"selected": false,
"text": "df$income_cat=as.factor(ifelse(df$Income<quantile(df$Income,0.33), 'low', \n ifelse(df$Income<quantile(df$Income,0.66), 'medium', 'high')))\n"
},
{
"answer_id": 74624334,
"author": "diomedesdata",
"author_id": 10366237,
"author_profile": "https://Stackoverflow.com/users/10366237",
"pm_score": 0,
"selected": false,
"text": "data.table df <- data.table(id = 1:9, income = 100+100*(1:9), year = rep(2000+1:3, each = 3))\n\n id income year\n1: 1 200 2001\n2: 2 300 2001\n3: 3 400 2001\n4: 4 500 2002\n5: 5 600 2002\n6: 6 700 2002\n7: 7 800 2003\n8: 8 900 2003\n9: 9 1000 2003\n by year data.table::fcase quantile library(data.table)\nsetDT(df)\n\ndf[, income_cat := fcase(income < quantile(income, 0.33), \"low\",\n income < quantile(income, 0.66), \"mid\",\n default = \"high\"), \n by = year]\n df\n id income year income_cat\n1: 1 200 2001 low\n2: 2 300 2001 mid\n3: 3 400 2001 high\n4: 4 500 2002 low\n5: 5 600 2002 mid\n6: 6 700 2002 high\n7: 7 800 2003 low\n8: 8 900 2003 mid\n9: 9 1000 2003 high\n"
},
{
"answer_id": 74625064,
"author": "Yuriy Saraykin",
"author_id": 12025483,
"author_profile": "https://Stackoverflow.com/users/12025483",
"pm_score": 0,
"selected": false,
"text": "library(data.table)\nlibrary(magrittr)\n\ndf <- data.table(id = 1:9, income = 100+100*(1:9), year = rep(2000+1:3, each = 3))\n\ndf[, res := cut(\n x = income, \n breaks = c(-Inf, quantile(x = income, probs = seq(0, 1, 1 /3))[2:3], +Inf),\n labels = c(\"Low\", \"Medium\", \"High\")), by = year] %>%\n .[]\n#> id income year res\n#> 1: 1 200 2001 Low\n#> 2: 2 300 2001 Medium\n#> 3: 3 400 2001 High\n#> 4: 4 500 2002 Low\n#> 5: 5 600 2002 Medium\n#> 6: 6 700 2002 High\n#> 7: 7 800 2003 Low\n#> 8: 8 900 2003 Medium\n#> 9: 9 1000 2003 High\n"
},
{
"answer_id": 74625262,
"author": "MarBlo",
"author_id": 4282026,
"author_profile": "https://Stackoverflow.com/users/4282026",
"pm_score": 0,
"selected": false,
"text": "year findInterval library(dplyr)\n\ndf %>%\n group_by(year) %>%\n mutate(quantile = findInterval(income,\n quantile(income, probs=c(0.3, .66)))) |> \n mutate(quantile = factor(quantile, labels = c(\"low\", \"medium\", \"high\")))\n#> # A tibble: 30 × 3\n#> # Groups: year [3]\n#> income year quantile\n#> <int> <dbl> <fct> \n#> 1 258 2000 medium \n#> 2 278 2000 high \n#> 3 113 2000 low \n#> 4 294 2000 high \n#> 5 269 2000 medium \n#> 6 149 2000 low \n#> 7 217 2000 medium \n#> 8 142 2000 low \n#> 9 298 2000 high \n#> 10 297 2000 high \n#> # … with 20 more rows\n set.seed(123)\nincome <- c(sample(100:300, 10),\n sample(500:1500,10),\n sample(10000:20000, 10))\nyear <- c(rep(2000,10), rep(2001,10), rep(2002,10))\n\ndf <- data.frame(income, year)\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20642281/"
] |
74,624,076
|
<p>I am opening 10 tabs (same URL) in chrome browser Successfully. but problem is that, my URL takes 1 minute to load page and i don't want to wait 1 minute at each tab.</p>
<p>i need to let it load and want to open another tab and i know final tab compulsory take one minute to load but no problem but i don't want to wait 1 minute for each tab.</p>
<p>what can i do to achieve it?</p>
<p>i have used <code>time.sleep()</code>, <code>WebDriverWait</code>, <code>driver.switch_to.window(x)</code> but no use.</p>
<p>Thanks in Advance</p>
<p>This is my Code:</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common import window
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)
options.add_argument("start-maximized")
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
url = 'http://my_url/Index'
driver.get(url)
for _ in range(10):
driver.get(url)
driver.switch_to.new_window(window.WindowTypes.TAB)
</code></pre>
|
[
{
"answer_id": 74624274,
"author": "Tom Hoel",
"author_id": 17213355,
"author_profile": "https://Stackoverflow.com/users/17213355",
"pm_score": 2,
"selected": true,
"text": "library(tidyverse) \n\ndf %>% \n group_by(Year) %>% \n mutate(income_cat = case_when(Income > quantile(Income, 0.66) ~ \"High\", \n Income < quantile(Income, 0.33) ~ \"Low\", \n between(Income, \n quantile(Income, 0.33),\n quantile(Income, 0.66)) ~ \"Medium\"))\n\n# A tibble: 9 x 4\n# Groups: Year [3]\n ID Income Year income_cat\n <dbl> <dbl> <dbl> <chr> \n1 1 100 2000 Low \n2 2 200 2000 Medium \n3 3 300 2000 High \n4 4 500 2001 Low \n5 5 1000 2001 Medium \n6 6 1500 2001 High \n7 7 10000 2002 Low \n8 8 15000 2002 Medium \n9 9 20000 2002 High \n"
},
{
"answer_id": 74624303,
"author": "Thoughtful_monkey",
"author_id": 19039483,
"author_profile": "https://Stackoverflow.com/users/19039483",
"pm_score": 1,
"selected": false,
"text": "df$income_cat=as.factor(ifelse(df$Income<quantile(df$Income,0.33), 'low', \n ifelse(df$Income<quantile(df$Income,0.66), 'medium', 'high')))\n"
},
{
"answer_id": 74624334,
"author": "diomedesdata",
"author_id": 10366237,
"author_profile": "https://Stackoverflow.com/users/10366237",
"pm_score": 0,
"selected": false,
"text": "data.table df <- data.table(id = 1:9, income = 100+100*(1:9), year = rep(2000+1:3, each = 3))\n\n id income year\n1: 1 200 2001\n2: 2 300 2001\n3: 3 400 2001\n4: 4 500 2002\n5: 5 600 2002\n6: 6 700 2002\n7: 7 800 2003\n8: 8 900 2003\n9: 9 1000 2003\n by year data.table::fcase quantile library(data.table)\nsetDT(df)\n\ndf[, income_cat := fcase(income < quantile(income, 0.33), \"low\",\n income < quantile(income, 0.66), \"mid\",\n default = \"high\"), \n by = year]\n df\n id income year income_cat\n1: 1 200 2001 low\n2: 2 300 2001 mid\n3: 3 400 2001 high\n4: 4 500 2002 low\n5: 5 600 2002 mid\n6: 6 700 2002 high\n7: 7 800 2003 low\n8: 8 900 2003 mid\n9: 9 1000 2003 high\n"
},
{
"answer_id": 74625064,
"author": "Yuriy Saraykin",
"author_id": 12025483,
"author_profile": "https://Stackoverflow.com/users/12025483",
"pm_score": 0,
"selected": false,
"text": "library(data.table)\nlibrary(magrittr)\n\ndf <- data.table(id = 1:9, income = 100+100*(1:9), year = rep(2000+1:3, each = 3))\n\ndf[, res := cut(\n x = income, \n breaks = c(-Inf, quantile(x = income, probs = seq(0, 1, 1 /3))[2:3], +Inf),\n labels = c(\"Low\", \"Medium\", \"High\")), by = year] %>%\n .[]\n#> id income year res\n#> 1: 1 200 2001 Low\n#> 2: 2 300 2001 Medium\n#> 3: 3 400 2001 High\n#> 4: 4 500 2002 Low\n#> 5: 5 600 2002 Medium\n#> 6: 6 700 2002 High\n#> 7: 7 800 2003 Low\n#> 8: 8 900 2003 Medium\n#> 9: 9 1000 2003 High\n"
},
{
"answer_id": 74625262,
"author": "MarBlo",
"author_id": 4282026,
"author_profile": "https://Stackoverflow.com/users/4282026",
"pm_score": 0,
"selected": false,
"text": "year findInterval library(dplyr)\n\ndf %>%\n group_by(year) %>%\n mutate(quantile = findInterval(income,\n quantile(income, probs=c(0.3, .66)))) |> \n mutate(quantile = factor(quantile, labels = c(\"low\", \"medium\", \"high\")))\n#> # A tibble: 30 × 3\n#> # Groups: year [3]\n#> income year quantile\n#> <int> <dbl> <fct> \n#> 1 258 2000 medium \n#> 2 278 2000 high \n#> 3 113 2000 low \n#> 4 294 2000 high \n#> 5 269 2000 medium \n#> 6 149 2000 low \n#> 7 217 2000 medium \n#> 8 142 2000 low \n#> 9 298 2000 high \n#> 10 297 2000 high \n#> # … with 20 more rows\n set.seed(123)\nincome <- c(sample(100:300, 10),\n sample(500:1500,10),\n sample(10000:20000, 10))\nyear <- c(rep(2000,10), rep(2001,10), rep(2002,10))\n\ndf <- data.frame(income, year)\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18974013/"
] |
74,624,097
|
<p>I was reading this article about Promise Basics on <a href="https://javascript.info" rel="nofollow noreferrer">Javascript.info</a> and came across an example about a usecase for the <code>.finally()</code> method.</p>
<p>It says:</p>
<blockquote>
<p>The idea of finally is to set up a handler for performing cleanup/finalizing after the previous operations are complete.</p>
</blockquote>
<blockquote>
<p>E.g. stopping loading indicators, closing no longer needed connections, etc.</p>
</blockquote>
<p>I'm not sure about the implementation of a loading indicator, but I assume this example doesn't jump to conclusions.</p>
<p>So assuming that I have some loading indicator that waits for some promise to settle, then it gets settled. Why would the loading indicator stay active if the promise was settled then?</p>
<p>It's just an abstract question.</p>
|
[
{
"answer_id": 74624147,
"author": "jfriend00",
"author_id": 816620,
"author_profile": "https://Stackoverflow.com/users/816620",
"pm_score": 1,
"selected": false,
"text": ".finally() .finally() .finally() .then() .catch() .then() .finally()"
},
{
"answer_id": 74624151,
"author": "Quentin",
"author_id": 19068,
"author_profile": "https://Stackoverflow.com/users/19068",
"pm_score": 1,
"selected": true,
"text": "const loading = document.createElement('img');\nloading.src=\"loading.gif\";\nloading.alt=\"Loading!\";\n\ndocument.body.append(loading);\ndo_something().finally(() => loading.remove());\n"
},
{
"answer_id": 74624197,
"author": "Sridhar Murali",
"author_id": 10362033,
"author_profile": "https://Stackoverflow.com/users/10362033",
"pm_score": 0,
"selected": false,
"text": "isLoading then() catch() finally() isLoading"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10969106/"
] |
74,624,115
|
<p>i have a situation in which i have to do like this <a href="https://i.stack.imgur.com/L7gft.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/L7gft.png" alt="Column-> Row-> Two List Views" /></a></p>
<p>i have tried many solutions but unable to store is it possible??</p>
<pre><code>Expanded(
child: Row(
// mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
ListView.builder(
shrinkWrap: true,
itemCount: selectedMainCasteIds?.length,
itemBuilder: (context, index) {
return Text('${selectedMainCasteIds![index].mainCasteName}',style: TextStyle(fontSize: 10),);
},
),
Text('ddddd'),
ListView.builder(
shrinkWrap: true,
itemCount: selectedMainCasteIds?.length,
itemBuilder: (context, index) {
return Text('${selectedMainCasteIds![index].mainCasteName}',style: TextStyle(fontSize: 10),);
},
),
],
),
),
</code></pre>
|
[
{
"answer_id": 74624147,
"author": "jfriend00",
"author_id": 816620,
"author_profile": "https://Stackoverflow.com/users/816620",
"pm_score": 1,
"selected": false,
"text": ".finally() .finally() .finally() .then() .catch() .then() .finally()"
},
{
"answer_id": 74624151,
"author": "Quentin",
"author_id": 19068,
"author_profile": "https://Stackoverflow.com/users/19068",
"pm_score": 1,
"selected": true,
"text": "const loading = document.createElement('img');\nloading.src=\"loading.gif\";\nloading.alt=\"Loading!\";\n\ndocument.body.append(loading);\ndo_something().finally(() => loading.remove());\n"
},
{
"answer_id": 74624197,
"author": "Sridhar Murali",
"author_id": 10362033,
"author_profile": "https://Stackoverflow.com/users/10362033",
"pm_score": 0,
"selected": false,
"text": "isLoading then() catch() finally() isLoading"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19381126/"
] |
74,624,123
|
<p><strong>I am trying to create a simple path system with C# in Unity.</strong></p>
<p>So far, everything works perfectly. But to create a path follower, I need the position to which the follower should move every frame. The paths always have a radius, a starting point and a length, the rest is unknown.</p>
<p>Now, <strong>how do I calculate</strong> the position of the path follower in each frame, i.e. <strong>point on the arc</strong>? I need a function that takes as argument the percentage position of the follower on the path and that returns a global position in the scene.
Here is an example: the length of the arc L, the radius r and the starting point A are given. What I am trying to calculate is the random point D:
<a href="https://i.stack.imgur.com/m0aay.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/m0aay.png" alt="Description of problem" /></a></p>
<p>The point that I calculate on my own is just a mess and doesn't work, even though I've already done some research. So I am looking for a simple and understandable solution.</p>
|
[
{
"answer_id": 74624147,
"author": "jfriend00",
"author_id": 816620,
"author_profile": "https://Stackoverflow.com/users/816620",
"pm_score": 1,
"selected": false,
"text": ".finally() .finally() .finally() .then() .catch() .then() .finally()"
},
{
"answer_id": 74624151,
"author": "Quentin",
"author_id": 19068,
"author_profile": "https://Stackoverflow.com/users/19068",
"pm_score": 1,
"selected": true,
"text": "const loading = document.createElement('img');\nloading.src=\"loading.gif\";\nloading.alt=\"Loading!\";\n\ndocument.body.append(loading);\ndo_something().finally(() => loading.remove());\n"
},
{
"answer_id": 74624197,
"author": "Sridhar Murali",
"author_id": 10362033,
"author_profile": "https://Stackoverflow.com/users/10362033",
"pm_score": 0,
"selected": false,
"text": "isLoading then() catch() finally() isLoading"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17478939/"
] |
74,624,135
|
<p>I'm trying to learn a little Airflow by running the official airflow docker compose image
[ per instructions here: https://airflow.apache.org/docs/apache-airflow/2.0.1/start/docker.html ].
I was able to launch all the services such that when I dropped my test DAG in the ./dags
folder I eventually saw my DAG in the UI and could run it.</p>
<p>But this took several minutes. And continues to take several minutes every time I 'deploy' a new dag into ./dags.</p>
<p>I'm wondering if there is some configuration option that would cause the scanning of the
./dags folder to happen faster so I don't have to wait around as much. Thanks in advance !</p>
|
[
{
"answer_id": 74625864,
"author": "S N",
"author_id": 2894345,
"author_profile": "https://Stackoverflow.com/users/2894345",
"pm_score": 2,
"selected": true,
"text": "dag_dir_list_interval = 300\n docker restart your_airflow_webserver_container_id \n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1224363/"
] |
74,624,161
|
<p>I have just started using PostgreSQL as Back End database. As the title suggested, users will input data into the DB tables through MS ACCESS connected using psql ODBC driver. But I observed a very strange behavior from a <strong>linked table</strong> in ACCESS.</p>
<p>The table has Primary Key (PK) named transaction_id with sequence attached to the column, incrementing 1 at a time. When the transaction_id is left empty in MS ACCESS <strong>ON INSERT</strong>, PostgreSQL will automatically assign a number for transaction_id, as expected.</p>
<p>Frequently and randomly though, when inserting new data into the table, transaction_id would persistently take a previous value from the table, instead of incrementing at 1.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: center;">table_id (PK)</th>
<th style="text-align: center;">date</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: center;">1</td>
<td style="text-align: center;">14-11-2022</td>
</tr>
<tr>
<td style="text-align: center;">2</td>
<td style="text-align: center;">14-11-2022</td>
</tr>
<tr>
<td style="text-align: center;">3</td>
<td style="text-align: center;">14-11-2022</td>
</tr>
<tr>
<td style="text-align: center;">4</td>
<td style="text-align: center;">14-11-2022</td>
</tr>
<tr>
<td style="text-align: center;"><strong>3</strong></td>
<td style="text-align: center;">14-11-2022</td>
</tr>
<tr>
<td style="text-align: center;"><strong>3</strong></td>
<td style="text-align: center;">14-11-2022</td>
</tr>
<tr>
<td style="text-align: center;"><strong>3</strong></td>
<td style="text-align: center;">14-11-2022</td>
</tr>
<tr>
<td style="text-align: center;"><strong>3</strong></td>
<td style="text-align: center;">14-11-2022</td>
</tr>
</tbody>
</table>
</div>
<p>Refreshing the linked table would change transaction_id as it should be, but <strong>IMMEDIATE</strong> new insert on the linked table would use the same persistent previous value as a PK.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: center;">transaction_id (PK)</th>
<th style="text-align: center;">date</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: center;">1</td>
<td style="text-align: center;">14-11-2022</td>
</tr>
<tr>
<td style="text-align: center;">2</td>
<td style="text-align: center;">14-11-2022</td>
</tr>
<tr>
<td style="text-align: center;">3</td>
<td style="text-align: center;">14-11-2022</td>
</tr>
<tr>
<td style="text-align: center;">4</td>
<td style="text-align: center;">14-11-2022</td>
</tr>
<tr>
<td style="text-align: center;">5</td>
<td style="text-align: center;">14-11-2022</td>
</tr>
<tr>
<td style="text-align: center;">6</td>
<td style="text-align: center;">14-11-2022</td>
</tr>
<tr>
<td style="text-align: center;">7</td>
<td style="text-align: center;">14-11-2022</td>
</tr>
<tr>
<td style="text-align: center;">8</td>
<td style="text-align: center;">14-11-2022</td>
</tr>
<tr>
<td style="text-align: center;">3 <strong>(immediate new data)</strong></td>
<td style="text-align: center;">14-11-2022</td>
</tr>
<tr>
<td style="text-align: center;">3 <strong>(immediate new data)</strong></td>
<td style="text-align: center;">14-11-2022</td>
</tr>
</tbody>
</table>
</div>
<p>I have to wait for a while before the PK went back to normal behavior of incrementing at 1.</p>
<p>However, if I were to change the date value, the PK will reflect it's true number.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: center;">transaction_id (PK)</th>
<th style="text-align: center;">date</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: center;">...</td>
<td style="text-align: center;">...</td>
</tr>
<tr>
<td style="text-align: center;">3</td>
<td style="text-align: center;">14-11-2022</td>
</tr>
<tr>
<td style="text-align: center;">3</td>
<td style="text-align: center;">14-11-2022</td>
</tr>
<tr>
<td style="text-align: center;">11</td>
<td style="text-align: center;">10-11-2022</td>
</tr>
<tr>
<td style="text-align: center;">12</td>
<td style="text-align: center;">12-11-2022</td>
</tr>
<tr>
<td style="text-align: center;">3</td>
<td style="text-align: center;">14-11-2022</td>
</tr>
<tr>
<td style="text-align: center;">14</td>
<td style="text-align: center;">01-02-2022</td>
</tr>
</tbody>
</table>
</div>
<p>I have a subform that is dependent on transaction_id for its foreign field, therefore, if the linked table suddenly show previous value, the subform will take the value. Effectively, duplicating the id.</p>
<p>So far, I have tried to refresh the linked table in MS ACCESS, closing the table and reopening it, also changing refresh interval from 60s to 30s, and lastly deleting transaction_id sequence and replacing it with identity column, but none of those works.</p>
<p>Can anyone please help me with this? I am desperate...</p>
<p><em><strong>I am running PostgreSQL 10 with MS ACCESS 2007</strong></em></p>
<p>Edits:</p>
<p>Here is the table definition</p>
<pre><code> CREATE TABLE transactionlist (
transaction_id bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
transaction_date date,
description VARCHAR(255),
source VARCHAR(50),
input_user int,
input_date date);
</code></pre>
|
[
{
"answer_id": 74625864,
"author": "S N",
"author_id": 2894345,
"author_profile": "https://Stackoverflow.com/users/2894345",
"pm_score": 2,
"selected": true,
"text": "dag_dir_list_interval = 300\n docker restart your_airflow_webserver_container_id \n"
}
] |
2022/11/15
|
[
"https://Stackoverflow.com/questions/74624161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11329364/"
] |
74,624,187
|
<p>Recently, I found that by adding <code>-Wall</code> and <code>-Wextra</code> to <code>CFLAGS</code> can raise the compilation warning level.
And this exposes some hidden bugs.</p>
<p>But I do not wish to edit the warnings in the 3rd party code.</p>
<p>The project I used is an open source RTOS: <a href="https://github.com/RT-Thread/rt-thread" rel="nofollow noreferrer">RT-Thread</a></p>
<p>As we know, the bottom layer of scons is gcc,
so I found <a href="https://stackoverflow.com/questions/15053776/how-do-you-disable-the-unused-variable-warnings-coming-out-of-gcc-in-3rd-party-c">a gcc's solution in stack-overflow</a>.</p>
<p>The top solution recommends keeping the warning on, but use <code>-isystem</code> instead of <code>-I</code> to include directories of third-party projects.
Then I used the <code>scons --verbose</code> and found that the scons used <code>-I</code> by default.</p>
<p><strong>How to use <code>-isystem</code> instead of <code>-I</code> to include directories of third-party projects in scons?</strong></p>
|
[
{
"answer_id": 74625864,
"author": "S N",
"author_id": 2894345,
"author_profile": "https://Stackoverflow.com/users/2894345",
"pm_score": 2,
"selected": true,
"text": "dag_dir_list_interval = 300\n docker restart your_airflow_webserver_container_id \n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7023732/"
] |
74,624,190
|
<p>Good work, I decided to write facebook login for my app. I used this package <code>flutter_facebook_auth: ^5.0.6</code></p>
<p><a href="https://i.stack.imgur.com/pDlsU.png" rel="nofollow noreferrer">enter image description here</a></p>
<p><a href="https://i.stack.imgur.com/hzaAA.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>I changed the sdk version to 33 but the error persists</p>
|
[
{
"answer_id": 74625864,
"author": "S N",
"author_id": 2894345,
"author_profile": "https://Stackoverflow.com/users/2894345",
"pm_score": 2,
"selected": true,
"text": "dag_dir_list_interval = 300\n docker restart your_airflow_webserver_container_id \n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20545194/"
] |
74,624,195
|
<p>I'm a newbie at PureScript trying out some code at <a href="https://try.purescript.org/?code=LYewJgrgNgpgBAWQIYEsB2cDuALGAnGAKEJWAAcQ8AXOABQKgjCJPMpoBEkqkA6AMRBQwSAEaw4ACgBmQsAEpWFanC49eAFQhlYS9qu59kZOEgDOiJGT0q1fADIozVGzQCi06TADGNSR69fRVJld08fKl4AYRA0MyF4SSgQAHNgthUNPABPWggCAGVvPBQyF0IRHjgASSoYYFM4AF44exhpGiRiKhAdGAA3GCgOHycUWIsALknLMl5jKQKqErQ0qVr6uCWVtMIevsHh0bNxuObZ3mk8EGBBYTEJAG04LT64ACIAORAqFGlsmpoMAofooSBIKBmd6EOBSNodD43FBUOpgd7yAA0L20EneAEEzGYYITgDA0FR3nD2jR3kiUTA0fI4ABdYgpGBUDS4fgoPDOapoV4SaZwpw0AC0AD5sX0mVLWmLCOzOdzefzBTj4EhztJnHAADyGuAQNAAL1KpmIwFQGBaBCB%2BGaRswyOwMTiCTgYBAMLgyRScAAJHBlVyYDy%2BVQBUL4PtYIcRt4xhNfUA" rel="nofollow noreferrer">this link</a>. I've pasted the code here:</p>
<pre><code>module Main where
import Prelude
import Data.Foldable (fold)
import Data.Tuple
import Data.Map as Map
import Data.List
import Effect (Effect)
import Effect.Console (log)
import TryPureScript
data Item a = Left a
toplevelDecisions :: Map.Map (String) (Item String)
toplevelDecisions = Map.fromFoldable [ Tuple "Notify Individuals" (Left "omitted"), Tuple "Assessment" (Left "omitted") ]
getTheFirstInTuple :: (List -> Tuple) -> List
getTheFirstInTuple a = fst <<< unzip a
main = render =<< withConsole do
log $ getTheFirstInTuple toplevelDecisions
</code></pre>
<p>I encountered this error: <code>Could not match kind Type -> Type with kind Type</code>. Does anyone know how to resolve this problem? What I'm trying to do is to convert a List of Tuples into a Tuple of 2 Lists, and then extracting just the first List.</p>
|
[
{
"answer_id": 74625864,
"author": "S N",
"author_id": 2894345,
"author_profile": "https://Stackoverflow.com/users/2894345",
"pm_score": 2,
"selected": true,
"text": "dag_dir_list_interval = 300\n docker restart your_airflow_webserver_container_id \n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8256981/"
] |
74,624,196
|
<p>I was wondering if an ssl certificate can be added to a tcp load balancer or does this require an http load balancer?</p>
<p>I do this through google cloud platform.</p>
|
[
{
"answer_id": 74625864,
"author": "S N",
"author_id": 2894345,
"author_profile": "https://Stackoverflow.com/users/2894345",
"pm_score": 2,
"selected": true,
"text": "dag_dir_list_interval = 300\n docker restart your_airflow_webserver_container_id \n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20513644/"
] |
74,624,204
|
<p>I have a few items from various classes, I would like to write a method taking generic object (<strong>Object</strong> is the superclass of all other classes)</p>
<ul>
<li>verify items all have getId() method</li>
<li>then collect the getId() value.</li>
</ul>
<p>Note the object could really by anything - it cannot be bounded</p>
<p>I tried something like</p>
<pre><code> String getObjectId(Object item) throws Exception {
// If the getId() method is not implemented, throw exception
if (Arrays.stream(item.getClass().getMethods())
.filter(method -> "getId".equals(method.getName()))
.findFirst()
.isEmpty()) {
throw new Exception(...);
}
return item.getId();
}
</code></pre>
<p>The problem is the compiler ignores this verification - i always get this error even though I just verified it has the method</p>
<pre><code>
cannot find symbol
return item.getId();
^
</code></pre>
<p>How can I call a method in this case?</p>
|
[
{
"answer_id": 74624279,
"author": "Rustam",
"author_id": 15322661,
"author_profile": "https://Stackoverflow.com/users/15322661",
"pm_score": 3,
"selected": true,
"text": "item.getId(); getId Method getIdMethod = item.getClass().getMethod(\"getId\");\nObject result = getIdMethod.invoke(item);\nreturn result == null? null: result.toString();\n getId() public interface Identifiable {\n String getId();\n\n void setId(String value);\n}\n\nclass A implements Identifiable {\n...\n}\n\nclass B implements Identifiable {\n\n}\n\n Collection<? extends Identifiable> coll = new ArrayList<>();\n...\ncoll.stream().map(Identifiable::getId).collect(Collectors.toList());\n"
},
{
"answer_id": 74624410,
"author": "SimonC",
"author_id": 2921426,
"author_profile": "https://Stackoverflow.com/users/2921426",
"pm_score": 0,
"selected": false,
"text": "IMyInterface MyAbstractClass IGetInfo package com.me;\n\npublic class MyWorker implements IGetInfo {\n\n public String getObjectInfo() {\n return \"MyWorker\";\n } \n\n public String getObjectInfo(IGetInfo x) {\n return x.getObjectInfo();\n }\n\n \n public String getObjectInfo(IMyInterface x) {\n return x.getId();\n }\n\n // and so on\n\n}\n Object"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20642519/"
] |
74,624,236
|
<p>getting the response from express api how can change the array data like this thanks in advance help me !</p>
<pre><code>input = [
{ secId: "12", stuName: "aaa", stuGrade: "A", stuTotal: 100 },
{ secId: "12", stuName: "bbb", stuGrade: "A+", stuTotal: 98 },
{ secId: "13", stuName: "ccc", stuGrade: "B", stuTotal: 95 },
{ secId: "13", stuName: "ddd", stuGrade: "A", stuTotal: 70 },
];
</code></pre>
<pre><code>output = [
{
secId: 12,
stuDetails: [
{ stuName: "aaa", stuGrade: "A", stuTotal: 100 },
{ stuName: "bbb", stuGrade: "A+", stuTotal: 98 },
],
},
{
secId: 13,
stuDetails: [
{ stuName: "ccc", stuGrade: "B", stuTotal: 95 },
{ stuName: "ddd", stuGrade: "A", stuTotal: 70 },
],
},
];
</code></pre>
|
[
{
"answer_id": 74624279,
"author": "Rustam",
"author_id": 15322661,
"author_profile": "https://Stackoverflow.com/users/15322661",
"pm_score": 3,
"selected": true,
"text": "item.getId(); getId Method getIdMethod = item.getClass().getMethod(\"getId\");\nObject result = getIdMethod.invoke(item);\nreturn result == null? null: result.toString();\n getId() public interface Identifiable {\n String getId();\n\n void setId(String value);\n}\n\nclass A implements Identifiable {\n...\n}\n\nclass B implements Identifiable {\n\n}\n\n Collection<? extends Identifiable> coll = new ArrayList<>();\n...\ncoll.stream().map(Identifiable::getId).collect(Collectors.toList());\n"
},
{
"answer_id": 74624410,
"author": "SimonC",
"author_id": 2921426,
"author_profile": "https://Stackoverflow.com/users/2921426",
"pm_score": 0,
"selected": false,
"text": "IMyInterface MyAbstractClass IGetInfo package com.me;\n\npublic class MyWorker implements IGetInfo {\n\n public String getObjectInfo() {\n return \"MyWorker\";\n } \n\n public String getObjectInfo(IGetInfo x) {\n return x.getObjectInfo();\n }\n\n \n public String getObjectInfo(IMyInterface x) {\n return x.getId();\n }\n\n // and so on\n\n}\n Object"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17375598/"
] |
74,624,280
|
<p>would like to make a contact book using dictinaries but i cant figure out how to add a nested dict to the current dict i have.</p>
<p>would be something like this</p>
<pre><code>my_contacts = {"1": { "Tom Jones", "911", "22.10.1995"},
"2": { "Bob Marley", "0800838383", "22.10.1991"}
}
def add_contact():
user_input = int(input("please enter how many contacts you wanna add: "))
for i in range(user_input):
name = input("Enter the name: ")
number = input("Enter the number: ")
birthday = input("Enter the birthday")
adress = input("Enter the address")
my_contacts[name] = number
my_contacts[birthday] = adress
</code></pre>
<p>but unforunatly this doesnt add them as a dict. so how can i add them as one dict inside my current dict?</p>
<pre><code>my_contacts = {"1": { "Tom Jones", "911", "22.10.1995"},
"2": { "Bob Marley", "0800838383", "22.10.1991"}
}
def add_contact():
user_input = int(input("please enter how many contacts you wanna add: "))
for i in range(user_input):
name = input("Enter the name: ")
number = input("Enter the number: ")
birthday = input("Enter the birthday")
adress = input("Enter the address")
my_contacts[name] = number
my_contacts[birthday] = adress
</code></pre>
|
[
{
"answer_id": 74624279,
"author": "Rustam",
"author_id": 15322661,
"author_profile": "https://Stackoverflow.com/users/15322661",
"pm_score": 3,
"selected": true,
"text": "item.getId(); getId Method getIdMethod = item.getClass().getMethod(\"getId\");\nObject result = getIdMethod.invoke(item);\nreturn result == null? null: result.toString();\n getId() public interface Identifiable {\n String getId();\n\n void setId(String value);\n}\n\nclass A implements Identifiable {\n...\n}\n\nclass B implements Identifiable {\n\n}\n\n Collection<? extends Identifiable> coll = new ArrayList<>();\n...\ncoll.stream().map(Identifiable::getId).collect(Collectors.toList());\n"
},
{
"answer_id": 74624410,
"author": "SimonC",
"author_id": 2921426,
"author_profile": "https://Stackoverflow.com/users/2921426",
"pm_score": 0,
"selected": false,
"text": "IMyInterface MyAbstractClass IGetInfo package com.me;\n\npublic class MyWorker implements IGetInfo {\n\n public String getObjectInfo() {\n return \"MyWorker\";\n } \n\n public String getObjectInfo(IGetInfo x) {\n return x.getObjectInfo();\n }\n\n \n public String getObjectInfo(IMyInterface x) {\n return x.getId();\n }\n\n // and so on\n\n}\n Object"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20642580/"
] |
74,624,293
|
<p>Code looks like this:</p>
<pre><code><Pressable>
<Text>Click me</Text>
</Pressable>
</code></pre>
<p>When pressable is clicked, background color of text is changing, how to prevent it in react-native from changing?</p>
|
[
{
"answer_id": 74624279,
"author": "Rustam",
"author_id": 15322661,
"author_profile": "https://Stackoverflow.com/users/15322661",
"pm_score": 3,
"selected": true,
"text": "item.getId(); getId Method getIdMethod = item.getClass().getMethod(\"getId\");\nObject result = getIdMethod.invoke(item);\nreturn result == null? null: result.toString();\n getId() public interface Identifiable {\n String getId();\n\n void setId(String value);\n}\n\nclass A implements Identifiable {\n...\n}\n\nclass B implements Identifiable {\n\n}\n\n Collection<? extends Identifiable> coll = new ArrayList<>();\n...\ncoll.stream().map(Identifiable::getId).collect(Collectors.toList());\n"
},
{
"answer_id": 74624410,
"author": "SimonC",
"author_id": 2921426,
"author_profile": "https://Stackoverflow.com/users/2921426",
"pm_score": 0,
"selected": false,
"text": "IMyInterface MyAbstractClass IGetInfo package com.me;\n\npublic class MyWorker implements IGetInfo {\n\n public String getObjectInfo() {\n return \"MyWorker\";\n } \n\n public String getObjectInfo(IGetInfo x) {\n return x.getObjectInfo();\n }\n\n \n public String getObjectInfo(IMyInterface x) {\n return x.getId();\n }\n\n // and so on\n\n}\n Object"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10223815/"
] |
74,624,299
|
<p>I want to add an array of integer fields in my model</p>
<pre><code>class Schedule(models.Model):
name = models.CharField(max_length=100)
start_time = models.DateTimeField(auto_now_add=True)
end_time = models.DateTimeField(null=True, blank=True)
day_of_the_week = ?? ( array of integer )
</code></pre>
<p>I tried with</p>
<pre><code>class Schedule(models.Model):
name = models.CharField(max_length=100)
start_time = models.DateTimeField(auto_now_add=True)
end_time = models.DateTimeField(null=True, blank=True)
day_of_the_week = models.CharField(max_length=100)
</code></pre>
<p>and in the serializer add ListField</p>
<pre><code>class ScheduleSerializer(serializers.ModelSerializer):
day_of_the_week = serializers.ListField()
class Meta():
model = Schedule
fields = "__all__"
</code></pre>
<p>but this one is not working can anyone suggest me how to deal with this issue?</p>
|
[
{
"answer_id": 74624363,
"author": "Daniel Robinson",
"author_id": 20631228,
"author_profile": "https://Stackoverflow.com/users/20631228",
"pm_score": 0,
"selected": false,
"text": "models.CharField(validators=[int_list_validator], max_length=100)\n"
},
{
"answer_id": 74624378,
"author": "Adrian Kurzeja",
"author_id": 8571154,
"author_profile": "https://Stackoverflow.com/users/8571154",
"pm_score": 2,
"selected": true,
"text": "class Schedule(models.Model):\n name = models.CharField(max_length=100)\n start_time = models.DateTimeField(auto_now_add=True)\n end_time = models.DateTimeField(null=True, blank=True)\n day_of_the_week = models.JSONField(default=list)\n\nclass ScheduleSerializer(serializers.ModelSerializer):\n day_of_the_week = serializers.ListField(\n child=serializers.IntegerField(),\n )\n\n class Meta():\n model = Schedule\n fields = \"__all__\"\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14439683/"
] |
74,624,331
|
<p><a href="https://i.stack.imgur.com/Cp5z2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Cp5z2.png" alt="enter image description here" /></a></p>
<p>I have a dataframe named "df" as the picture.
In this dataframe there are "null" as object(dtype) and numerics.
I wish to round(2) only the numeric values in multiple columns.
I have written this code but keep getting "TypeError: 'int' object is not iterable" as TypeError.
*The first line code is to convert na's to "null", since other numbers need to be numeric dtype.</p>
<pre><code>df['skor_change_w_ts']=pd.to_numeric(df['skor_change_w_ts'], errors='coerce').fillna("null", downcast='infer')
for i in len(df):
if df['skor_change_w_ts'][i] is float:
df['skor_change_w_ts'][i]=df['skor_change_w_ts'][i].round(2)
</code></pre>
<p>What would be the most simple code to round(2) only numeric values in multiple columns?</p>
|
[
{
"answer_id": 74624363,
"author": "Daniel Robinson",
"author_id": 20631228,
"author_profile": "https://Stackoverflow.com/users/20631228",
"pm_score": 0,
"selected": false,
"text": "models.CharField(validators=[int_list_validator], max_length=100)\n"
},
{
"answer_id": 74624378,
"author": "Adrian Kurzeja",
"author_id": 8571154,
"author_profile": "https://Stackoverflow.com/users/8571154",
"pm_score": 2,
"selected": true,
"text": "class Schedule(models.Model):\n name = models.CharField(max_length=100)\n start_time = models.DateTimeField(auto_now_add=True)\n end_time = models.DateTimeField(null=True, blank=True)\n day_of_the_week = models.JSONField(default=list)\n\nclass ScheduleSerializer(serializers.ModelSerializer):\n day_of_the_week = serializers.ListField(\n child=serializers.IntegerField(),\n )\n\n class Meta():\n model = Schedule\n fields = \"__all__\"\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624331",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11848695/"
] |
74,624,343
|
<p>Everything works fine until I delete all the objects and try to trigger the url, then it gives me this <code>traceback: list index out of range</code>. I can't use <code>get</code> because there might be more than one object and using <code>[0]</code> with <code>filter</code> leads me to this error when there's no object present, any way around this? I'm trying to get the recently created object of the Ticket model (if created that is) and then perform the logic, so that if the customer doesn't have any tickets, nothing happens but if the customer does then the logic happens</p>
<p>Models</p>
<pre><code>class Ticket(models.Model):
date_posted = models.DateField(auto_now_add=True, blank=True, null=True)
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True)
</code></pre>
<p>Views</p>
<pre><code>try:
ticket = Ticket.objects.filter(customer=customer).order_by("-id")[0]
now = datetime.now().date()
set_date = ticket.date_posted
check_time = now - set_date <= timedelta(hours=24)
if check_time:
print('working')
else:
print('not working')
except Ticket.DoesNotExist:
ticket = None
context = {"check_time": check_time}
</code></pre>
|
[
{
"answer_id": 74624796,
"author": "ruddra",
"author_id": 2696165,
"author_profile": "https://Stackoverflow.com/users/2696165",
"pm_score": 2,
"selected": true,
"text": "ticket = Ticket.objects.filter(customer=customer).order_by(\"-id\")[0]\n exists() tickets = Ticket.objects.filter(customer=customer).order_by(\"-id\")\nif tickets.exists():\n ticket = tickets.first()\nelse:\n ticket = None\n tickets = Ticket.objects.filter(customer=customer, date_posted__lte=timezone.now().date() - timedelta(hours=24))\n\ncontext = {\"check_time\": tickets.exists()}\n"
},
{
"answer_id": 74625407,
"author": "Osman",
"author_id": 3466206,
"author_profile": "https://Stackoverflow.com/users/3466206",
"pm_score": 2,
"selected": false,
"text": "ticket = Ticket.objects.filter(customer=customer).order_by(\"-id\").first() or None\nif ticket is not None: \n now = datetime.now().date()\n set_date = ticket.date_posted\n check_time = now - set_date <= timedelta(hours=24)\n if check_time:\n print('working')\n else:\n print('not working')\n context = {\"check_time\": check_time}\n ticket = Ticket.objects.filter(customer=customer).order_by(\"-id\")[0]\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18982716/"
] |
74,624,355
|
<p>I have Spring Boot application with Log4j2 XML configuration file placed in <code>resources/log4j2.xml</code>. One external library I use is installed via Maven dependency and have own logging configuration in <code>logback.xml</code>.It seems that this file overwrites my Log4J2 configuration and logging is now controlled by this config file.</p>
<p>I'm getting logger instance (<code>org.apache.logging.log4j.Logger</code>) this way:</p>
<p><code>private static final Logger LOGGER = LogManager.getLogger(Foo.class);</code></p>
<p><strong>Q: How can I disable Log4J configuration from external library?</strong></p>
<p>Edit 1: Added Maven dependencies related to Log4j2</p>
<pre><code><dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>${spring.boot.version}</version>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
<version>${spring.boot.version}</version>
</dependency>
</code></pre>
|
[
{
"answer_id": 74624796,
"author": "ruddra",
"author_id": 2696165,
"author_profile": "https://Stackoverflow.com/users/2696165",
"pm_score": 2,
"selected": true,
"text": "ticket = Ticket.objects.filter(customer=customer).order_by(\"-id\")[0]\n exists() tickets = Ticket.objects.filter(customer=customer).order_by(\"-id\")\nif tickets.exists():\n ticket = tickets.first()\nelse:\n ticket = None\n tickets = Ticket.objects.filter(customer=customer, date_posted__lte=timezone.now().date() - timedelta(hours=24))\n\ncontext = {\"check_time\": tickets.exists()}\n"
},
{
"answer_id": 74625407,
"author": "Osman",
"author_id": 3466206,
"author_profile": "https://Stackoverflow.com/users/3466206",
"pm_score": 2,
"selected": false,
"text": "ticket = Ticket.objects.filter(customer=customer).order_by(\"-id\").first() or None\nif ticket is not None: \n now = datetime.now().date()\n set_date = ticket.date_posted\n check_time = now - set_date <= timedelta(hours=24)\n if check_time:\n print('working')\n else:\n print('not working')\n context = {\"check_time\": check_time}\n ticket = Ticket.objects.filter(customer=customer).order_by(\"-id\")[0]\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1315357/"
] |
74,624,362
|
<p>I have a view on blade view with DateTime as a column of datatable. the DateTime timezone is UTC. I wanted to change it to the local timezone with the client browser.</p>
<p>so if the data is 00:00 a.m., then for someone accessing from UTC+5, the DateTime will be 05:00.</p>
<p>the column is currently like this, it generates me <em>2022-01-02 00:00am</em>:</p>
<pre><code> <td>
{{ $data->createdDate->format('d M Y H:ia') }}
</td>
</code></pre>
<p>and then I try to manipulate the DateTime using the timezone below and it works. but I hard-coded the timezone on it. so I got <em>2022-01-01 19:00pm</em> which is correct (UTC-5).</p>
<pre><code> {{ $data->createdDate->setTimezone('America/New_York')->format('d M Y H:ia') }}
</code></pre>
<p>is there a way to dynamically set the timezone ('America/New_York') on the view page?</p>
<p>because the users could be accessed from different regions.</p>
<p>I know on javascript I can generate the timezone using</p>
<pre><code>Intl.DateTimeFormat().resolvedOptions().timeZone
</code></pre>
<p>but how can I pass the timezone to that?</p>
|
[
{
"answer_id": 74624796,
"author": "ruddra",
"author_id": 2696165,
"author_profile": "https://Stackoverflow.com/users/2696165",
"pm_score": 2,
"selected": true,
"text": "ticket = Ticket.objects.filter(customer=customer).order_by(\"-id\")[0]\n exists() tickets = Ticket.objects.filter(customer=customer).order_by(\"-id\")\nif tickets.exists():\n ticket = tickets.first()\nelse:\n ticket = None\n tickets = Ticket.objects.filter(customer=customer, date_posted__lte=timezone.now().date() - timedelta(hours=24))\n\ncontext = {\"check_time\": tickets.exists()}\n"
},
{
"answer_id": 74625407,
"author": "Osman",
"author_id": 3466206,
"author_profile": "https://Stackoverflow.com/users/3466206",
"pm_score": 2,
"selected": false,
"text": "ticket = Ticket.objects.filter(customer=customer).order_by(\"-id\").first() or None\nif ticket is not None: \n now = datetime.now().date()\n set_date = ticket.date_posted\n check_time = now - set_date <= timedelta(hours=24)\n if check_time:\n print('working')\n else:\n print('not working')\n context = {\"check_time\": check_time}\n ticket = Ticket.objects.filter(customer=customer).order_by(\"-id\")[0]\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6632876/"
] |
74,624,382
|
<p><strong>I'm trying to understand Array Method, when I write code in vs code and call only array.prototype.concate.call() gives me the correct result,</strong></p>
<pre><code>console.log(Array.prototype.concat({}, 1, 2, 3));
</code></pre>
<p><strong>but when I try to array.concate() it gives me an error.</strong></p>
<pre><code>console.log(Array.concat({}, 1, 2, 3));
</code></pre>
<p>error message:</p>
<pre><code>TypeError: Array.concat is not a function
</code></pre>
|
[
{
"answer_id": 74624796,
"author": "ruddra",
"author_id": 2696165,
"author_profile": "https://Stackoverflow.com/users/2696165",
"pm_score": 2,
"selected": true,
"text": "ticket = Ticket.objects.filter(customer=customer).order_by(\"-id\")[0]\n exists() tickets = Ticket.objects.filter(customer=customer).order_by(\"-id\")\nif tickets.exists():\n ticket = tickets.first()\nelse:\n ticket = None\n tickets = Ticket.objects.filter(customer=customer, date_posted__lte=timezone.now().date() - timedelta(hours=24))\n\ncontext = {\"check_time\": tickets.exists()}\n"
},
{
"answer_id": 74625407,
"author": "Osman",
"author_id": 3466206,
"author_profile": "https://Stackoverflow.com/users/3466206",
"pm_score": 2,
"selected": false,
"text": "ticket = Ticket.objects.filter(customer=customer).order_by(\"-id\").first() or None\nif ticket is not None: \n now = datetime.now().date()\n set_date = ticket.date_posted\n check_time = now - set_date <= timedelta(hours=24)\n if check_time:\n print('working')\n else:\n print('not working')\n context = {\"check_time\": check_time}\n ticket = Ticket.objects.filter(customer=customer).order_by(\"-id\")[0]\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14758149/"
] |
74,624,448
|
<pre><code>char mode;
printf("---------------------------------------")
scanf(" %c", mode);
FILE * fpointer = fopen("kkkkkkkk.txt", mode);`
</code></pre>
<p>I tried but no result. compiler doesn't gives me error but not getting the program run completely.</p>
|
[
{
"answer_id": 74624499,
"author": "Noufal Ibrahim",
"author_id": 229602,
"author_profile": "https://Stackoverflow.com/users/229602",
"pm_score": 1,
"selected": false,
"text": "fopen(3) const char * char #include <stdio.h>\n\nint main(void) {\n char mode[5];\n scanf(\"%s\", mode);\n printf(\"Received mode is '%s'\\n\", mode);\n FILE *fp = fopen(\"sample.txt\", mode);\n if (fp == NULL) {\n perror(\"Couldn't open file \");\n } else {\n printf(\"Done! Closing\\n\");\n fclose(fp);\n }\n}\n ن ./sample\nr\nReceived mode is 'r'\nCouldn't open file : No such file or directory\n \"r\" sample.txt ن ./sample\nw\nReceived mode is 'w'\nDone! Closing\n\nن ./sample\nr\nReceived mode is 'r'\nDone! Closing\n \"w\" \"r\" sample.txt"
},
{
"answer_id": 74627666,
"author": "John Bode",
"author_id": 134554,
"author_profile": "https://Stackoverflow.com/users/134554",
"pm_score": 0,
"selected": false,
"text": "mode r+ wb wbx+ mode char char mode[5]; // up to 4 characters plus string terminator\n %s scanf fgets #define MODE_LEN 4\n#define FILENAME_LEN 255\n\nFILE *fp = NULL;\nchar filename[FILENAME_LEN+1] = {0}; // +1 for string terminator\nchar mode[MODE_LEN+1] = {0}; // initialize to all 0\n\nprintf( \"Gimme a file name: \" );\nif ( !fgets( filename, sizeof filename, stdin ) )\n{\n // input error, bail out here\n exit( 0 );\n}\n\nprintf( \"Gimme the fopen mode: \" );\nif ( !fgets( mode, sizeof mode, stdin ) )\n{\n // input error, bail out here\n exit( 0 );\n}\n\nfp = fopen( filename, mode );\nif ( !fp )\n{\n fprintf( stderr, \"Could not open %s with mode %s\\n\", \n filename, mode );\n exit( 0 );\n}\n\n// read/write fp here\n\nfclose( fp );\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20642702/"
] |
74,624,453
|
<p>In my calculator I tried firstly to make one operation functioning to have integers be displayed properly and when someone inputted a character it would say invalid.
When I input two integers it say's invalid. Not the actual sum of it.</p>
<pre><code>#include <stdio.h>
#include <conio.h>
int main(){
char op;
int num1, num2;
int result;
printf("Enter (+, -, /, *): ");
scanf("%c", &op);
printf("Enter Two Integers: \n");
scanf("%d %d", &num1, &num2);
switch (op){
case '+':
result = num1+num2;
if(!(num1 == '+' && num2 == '+')){
printf("Invalid");
}
else{
printf("Sum: %d ", result);
}
break;
case '-':
result = num1-num2;
printf("Difference: %d ", result);
break;
case '/':
result = num1/num2;
printf("Quotient: %d ", result);
break;
case '*':
result = num1*num2;
printf("Product: %d ", result);
break;
default:
break;
}
getch();
return 0;
}
</code></pre>
<p>I expected that with that new line of condition it will make characters and symbols print "Invalid"</p>
|
[
{
"answer_id": 74624546,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 0,
"selected": false,
"text": "scanf num1 num2 int %d + scanf(\"%d %d\", &num1, &num2) 0 $ cat > testing.c\n#include <stdio.h>\nint main(void) {\n int op;\n int result = scanf(\"%d\", &op);\n printf(\"%d\\n\", result);\n}\n$ gcc testing.c\n$ ./a.out\n+\n0\n$ ./a.out\n67\n1\n num1 num2 '+' \"Invalid.\" 43 '+' num1 num2 43 86"
},
{
"answer_id": 74624995,
"author": "Lundin",
"author_id": 584518,
"author_profile": "https://Stackoverflow.com/users/584518",
"pm_score": 1,
"selected": false,
"text": "if(!(num1 == '+' && num2 == '+'))\n if(num1 != '+' || num2 != '+') if(!(num1 == '+' || num2 == '+')) '+' scanf int result; \ndo\n{\n result = scanf(\"%d %d\", &num1, &num2);\n if(result != 2)\n {\n printf(\"You must enter two numbers!\\n\");\n }\n}\nwhile(result != 2);\n fgets <conio.h>"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20163069/"
] |
74,624,455
|
<p>I am building a node.js program using ES6 standard.</p>
<p>Here is my package.json:</p>
<pre><code>{
"name": "react18es6",
"version": "0.1.0",
"private": true,
"type": "module",
"dependencies": {
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^13.2.0",
"@testing-library/user-event": "^13.5.0",
"activedirectory": "^0.7.2",
"bootstrap": "^5.1.3",
"cross-env": "^7.0.3",
"dotenv": "^16.0.3",
"express": "^4.18.1",
"mysql2": "^2.3.3",
"nodemon": "^2.0.20",
"npm-run-all": "^4.1.5",
"react": "^18.1.0",
"react-bootstrap": "2.2.1",
"react-dom": "^18.1.0",
"react-scripts": "^5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"build": "react-scripts build",
"dev": "cross-env NODE_ENV=development run-p server start",
"eject": "react-scripts eject",
"prod": "cross-env NODE_ENV=production npm run server",
"server": "nodemon -r dotenv/config ./server/index.js",
"start": "react-scripts start",
"testServer":"cross-env NODE_ENV=development node -r dotenv/config ./server/index.js",
"test": "react-scripts test"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
</code></pre>
<p>My .env.development:</p>
<pre><code>DATABASE_CHARSET=utf8
</code></pre>
<p>My config.js:</p>
<pre><code>export class dbConfig{
static charset =process.env["DATABASE_CHARSET"];
}
</code></pre>
<p>My index.js:</p>
<pre><code>import dotenv from 'dotenv';
import {dbConfig} from './config.js';
dotenv.config({ path: '.env.'+process.env.NODE_ENV });
console.log(dbConfig);
console.log(process.env["DATABASE_CHARSET"])
</code></pre>
<p>I am using the following command to execute the code:</p>
<p><code>npm run testServer</code></p>
<p>The output of <code>index.js</code> is as the following:</p>
<pre><code>[class dbConfig] {
charset: undefined
}
utf8
</code></pre>
<p>Why the <code>dbConfig.js</code> can not get the environment variable?</p>
<p>I have tried the <a href="https://stackoverflow.com/questions/42817339/es6-import-happening-before-env-import">suggested solution</a>, but unfortunately, it does not work.</p>
|
[
{
"answer_id": 74624546,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 0,
"selected": false,
"text": "scanf num1 num2 int %d + scanf(\"%d %d\", &num1, &num2) 0 $ cat > testing.c\n#include <stdio.h>\nint main(void) {\n int op;\n int result = scanf(\"%d\", &op);\n printf(\"%d\\n\", result);\n}\n$ gcc testing.c\n$ ./a.out\n+\n0\n$ ./a.out\n67\n1\n num1 num2 '+' \"Invalid.\" 43 '+' num1 num2 43 86"
},
{
"answer_id": 74624995,
"author": "Lundin",
"author_id": 584518,
"author_profile": "https://Stackoverflow.com/users/584518",
"pm_score": 1,
"selected": false,
"text": "if(!(num1 == '+' && num2 == '+'))\n if(num1 != '+' || num2 != '+') if(!(num1 == '+' || num2 == '+')) '+' scanf int result; \ndo\n{\n result = scanf(\"%d %d\", &num1, &num2);\n if(result != 2)\n {\n printf(\"You must enter two numbers!\\n\");\n }\n}\nwhile(result != 2);\n fgets <conio.h>"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2018278/"
] |
74,624,458
|
<p>I've been trying to make a smoke particle effect in Forge Viewer for several days. I want to achieve something like <a href="https://i.stack.imgur.com/7B5wk.png" rel="nofollow noreferrer">this</a> in the Forge Viewer. I find some threejs particle engine samples. But all of them can't use in version r71(which used by Forge Viewer). So I decided to write my own particle engine. But there's a problem I can't figured it out why.</p>
<p>At first ,I've tried it in threejs (not in Forge Viewer)(with version r71 of course) and I can do something like <a href="https://i.stack.imgur.com/An1e0.png" rel="nofollow noreferrer">this</a>. It seems good for me, I think I can start writing my particle engine. But when I test it in Forge Viewer, things aren't going well.</p>
<p>Back to Forge Viewer, I have tested point cloud with custom shader and it worked <a href="https://i.stack.imgur.com/07qtm.png" rel="nofollow noreferrer">well</a> in the Forge Viewer. I can customize every attributes such as color, size, position to every single point. But when I try to add an image texture using <strong>texture2D</strong> in my fragmentShader. The browser shows me some warnings and nothing show on the viewer.</p>
<p>Here are the warnings showed by browser:</p>
<pre><code>WebGL: INVALID_OPERATION: getUniformLocation: program not linked
WebGL: INVALID_OPERATION: getAttribLocation: program not linked
WebGL: INVALID_OPERATION: useProgram: program not valid
</code></pre>
<p>vertexShader:</p>
<pre><code>attribute float customSize;
void main() {
vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
gl_Position = projectionMatrix * mvPosition;
gl_PointSize = customSize;
}
</code></pre>
<p>fragmentShader:</p>
<pre><code>uniform sampler2D texture;
void main() {
vec4 color = texture2D(texture,gl_PointCoord); //when I comment out this line, everything works well
gl_FragColor = color;
}
</code></pre>
<p>function for create points:</p>
<pre><code> createPoints() {
const width = 100;
const height = 100;
const pointCount = width * height;
const positions = new Float32Array(pointCount * 3);
//const colors = new Float32Array(pointCount * 4);
const sizes = new Float32Array(pointCount);
const geometry = new THREE.BufferGeometry();
const material = new THREE.ShaderMaterial({
uniforms: {
texture: { type: "t", value: this.particleTexture }
},
vertexShader: this.vertexShader,
fragmentShader: this.fragmentShader,
transparent: true,
depthTest: true,
blending: THREE.NormalBlending
});
material.supportsMrtNormals = true;
let i = 0;
for (var x = 0; x < width; x++) {
for (var y = 0; y < height; y++) {
const u = x / width, v = y / height;
positions[i * 3] = u * 20;
positions[i * 3 + 1] = v * 20;
positions[i * 3 + 2] = Math.sin(u * 20) + Math.cos(v * 20);
sizes[i] = 1 + THREE.Math.randFloat(1, 5);
colors[i * 4] = THREE.Math.random();
colors[i * 4 + 1] = THREE.Math.random();
colors[i * 4 + 2] = THREE.Math.random();
colors[i * 4 + 3] = 1;
i++;
}
}
//const colorsAttribute = new THREE.BufferAttribute(colors, 4);
//colorsAttribute.normalized = true;
geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
geometry.addAttribute("customSize", new THREE.BufferAttribute(sizes, 1));
//geometry.addAttribute("customColor", colorsAttribute);
geometry.computeBoundingBox();
geometry.isPoints = true;
points = new THREE.PointCloud(geometry, material);
viewer.impl.createOverlayScene('pointclouds');
viewer.impl.addOverlay('pointclouds', points);
}
</code></pre>
<p>in the createPoints() function, <strong>this.particleTexture</strong> comes from :</p>
<pre><code>THREE.ImageUtils.loadTexture("../img/smokeparticle.png")
</code></pre>
<p>vertexShader ,fragmentShader and the createPoints() function are all the same between threejs testing app on browser(not in Forge Viewer) and in Forge Viewer app. But it works well only when it's not running in Forge Viewer.</p>
<p>I have searched a lot of tutorials and blogs, but just can't find a solution that fits me. Can anyone help? Or maybe there's a better way to make smoke effect in Forge Viewer? Thx for help!</p>
<p>(If I missed some information just tell me. I would update them!)</p>
|
[
{
"answer_id": 74629852,
"author": "Petr Broz",
"author_id": 1759915,
"author_profile": "https://Stackoverflow.com/users/1759915",
"pm_score": 0,
"selected": false,
"text": "THREE.Points"
},
{
"answer_id": 74634745,
"author": "AlexAR",
"author_id": 9365707,
"author_profile": "https://Stackoverflow.com/users/9365707",
"pm_score": 2,
"selected": true,
"text": "texture tex texture uniform sampler2D tex;\nvoid main() {\n vec4 color = texture2D(tex,gl_PointCoord);\n gl_FragColor = color;\n}\n const material = new THREE.ShaderMaterial({\n uniforms: {\n tex: { type: \"t\", value: this.particleTexture }\n },\n vertexShader: this.vertexShader,\n fragmentShader: this.fragmentShader,\n transparent: true,\n depthTest: true,\n blending: THREE.NormalBlending\n\n});\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20589852/"
] |
74,624,497
|
<p>I have two lists, one containing true values selected by humans and a second list with extracted values. I would like to measure how well the pipeline is performing based on how many true values are contained in the extracted list. Example:</p>
<pre><code>extracted_value = ["value", "of", "words", "that", "were", "tracked"]
real_value = ["value", "words", "that"]
</code></pre>
<p>I need a metric that describes:
3 out of 3 real values were extracted</p>
<p>For multiple Documents:
5 out of 10 real values were extracted
2 out of 3 real values were extracted
1 out of 9 real values were extracted</p>
<p>Based on the individual comparison, can I get a score that describes how well the extracted keywords perform on average across all documents?</p>
|
[
{
"answer_id": 74624540,
"author": "svfat",
"author_id": 2419628,
"author_profile": "https://Stackoverflow.com/users/2419628",
"pm_score": 1,
"selected": false,
"text": "score = len([x for x in real_value if x in extracted_value])/len(extracted_value)\nprint(score)\n>>> 0.5\n"
},
{
"answer_id": 74624645,
"author": "Lukas Schmid",
"author_id": 11437648,
"author_profile": "https://Stackoverflow.com/users/11437648",
"pm_score": 0,
"selected": false,
"text": "sum len"
},
{
"answer_id": 74624666,
"author": "Cybergenik",
"author_id": 7187906,
"author_profile": "https://Stackoverflow.com/users/7187906",
"pm_score": 0,
"selected": false,
"text": "recall = len(set(real_value) & set(extracted_value))/len(real_values)\n len shared_vals = set(real_value) & set(extracted_value)\n recall = len(shared_vals)/len(real_value)\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20099097/"
] |
74,624,506
|
<p>The question to solve is that this code should get numbers in separate lines until 0 is given. Then it should print y number, y times. For example if number 3 is given, it should print 3, 3 times in separate lines.
I try to get the inputs from the user in separate lines. I mean one input in one line. Then print the numbers in separate lines. I don't know where to add <code>\n</code> to solve it.</p>
<p>This is my code:</p>
<pre><code>#include <stdio.h>
int main() {
int y = 1;
while (y != 0) {
scanf("%d", &y);
if (y == (0)) {
break;
}
for (int i = 1; i <= y; i++) {
printf("%d\n", y);
}
}
}
</code></pre>
<p>I tried to add <code>\n</code> beside <code>%d</code> of <code>scanf</code> but it didn't work as I expected.</p>
<p>The output of this code is like this:</p>
<pre><code>1
1
2
2
2
3
3
3
3
4
4
4
4
4
0
</code></pre>
<p>What I expect is that all the inputs should be given in separate lines before output is printed.
input like this:</p>
<pre><code>1
2
3
4
0
</code></pre>
<p>output like this:</p>
<pre><code>1
2
2
3
3
3
4
4
4
4
</code></pre>
|
[
{
"answer_id": 74624858,
"author": "suman dangol",
"author_id": 20632825,
"author_profile": "https://Stackoverflow.com/users/20632825",
"pm_score": 1,
"selected": false,
"text": "#include<stdio.h>\n\nint main()\n{\n\n int y;\n do\n {\n \n scanf(\"%d\",&y);\n \n for(int i = 1;i <= y;i++)\n {\n printf(\"%d\\n\", y);\n }\n \n \n }while(y != 0);\n \n \n}\n"
},
{
"answer_id": 74624900,
"author": "Allan Wind",
"author_id": 9706,
"author_profile": "https://Stackoverflow.com/users/9706",
"pm_score": 2,
"selected": false,
"text": "char [] int input[LEN] #include <stdio.h>\n\n#define LEN 5\n\nint main(void) {\n // input\n int input[LEN];\n int i = 0;\n for(; i < LEN; i++) {\n if(scanf(\"%d\",input + i) != 1) {\n printf(\"scanf failed\\n\");\n return 1;\n }\n if(!input[i])\n break;\n }\n\n // output (copy of input other than 0)\n for(int j = 0; j < i; j++) {\n printf(\"%d\\n\", input[j]);\n }\n\n // output (repeated based on input)\n for(int j = 0; j < i; j++) {\n for(int k = 0; k < input[j]; k++) {\n printf(\"%d\\n\", input[j]);\n }\n }\n}\n 1 # input\n2\n3\n4\n0\n1 # output (copy of input other than 0)\n2\n3\n4\n1 # output (repeated based on input)\n2\n2\n3\n3\n3\n4\n4\n4\n4\n #include <stdio.h>\n#include <stdlib.h>\n\nvoid read_then_print() {\n // input\n int d;\n if(scanf(\"%d\", &d) != 1) {\n printf(\"scanf failed\\n\");\n exit(1);\n }\n\n if(d) {\n // output before recursion\n printf(\"%d\\n\", d); \n read_then_print();\n }\n\n // output after recursion\n for(int i = 0; i < d; i++) {\n printf(\"%d\\n\", d);\n }\n}\n\nint main(void) {\n read_then_print();\n}\n 1 # input\n1 # output before recursion\n2 # input\n2 # output before recursion\n3 # ...\n3\n4\n4\n0\n4 # output after recursion\n4\n4\n4\n3\n3\n3\n2\n2\n1\n"
},
{
"answer_id": 74630300,
"author": "chqrlie",
"author_id": 4593267,
"author_profile": "https://Stackoverflow.com/users/4593267",
"pm_score": 0,
"selected": false,
"text": "0 #include <stdio.h>\n\n#define MAX_LINES 256\n\nint main() {\n int input[MAX_LINES];\n int y, n = 0;\n\n while (n < MAX_LINES && scanf(\"%d\", &y) == 1 && y != 0) {\n input[n++] = y;\n }\n for (int i = 0; i < n; i++) {\n y = input[i];\n for (int i = 0; i < y; i++) {\n printf(\"%d\\n\", y);\n }\n }\n return 0;\n}\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,624,508
|
<p><strong>Sourcecode to showcase the issue: <a href="https://github.com/Snuffsis/ConverterExample" rel="nofollow noreferrer">https://github.com/Snuffsis/ConverterExample</a></strong></p>
<p>So I have an issue that is exactly the same as in this stackoverflow question:</p>
<p><a href="https://stackoverflow.com/questions/67420877/c-sharp-newtonsoft-json-custom-deserializer">C# Newtonsoft.Json Custom Deserializer</a></p>
<p>And while that answer does help for properties that are simple types (int, bool, string etc) it doesn't work when there needs to be a nested object. As it throws an exception for <code>Newtonsoft.Json.JsonSerializationException: Self referecing loop detected for property 'Value' with type ...</code> where the type is the json object, in this case soBillingContact.</p>
<p>It should be able to handle these two JSON formats<br />
Example:</p>
<pre class="lang-json prettyprint-override"><code>{
"printNoteOnInternalDocuments": {
"value": true
},
"soBillingContact": {
"value": {
"overrideContact": {
"value": true
},
"name": {
"value": "string"
},
"attention": {
"value": "string"
},
"email": {
"value": "string"
},
"web": {
"value": "string"
},
"phone1": {
"value": "string"
},
"phone2": {
"value": "string"
},
"fax": {
"value": "string"
}
}
}
}
</code></pre>
<pre class="lang-json prettyprint-override"><code>{
"printNoteOnInternalDocuments": true,
"soBillingContact": {
"overrideContact": true,
"contactId": 0,
"name": "string",
"attention": "string",
"email": "string",
"web": "string",
"phone1": "string",
"phone2": "string",
"fax": "string"
}
}
</code></pre>
<p>The solution in the linked question works fine for the object itself if i create the object as a root. It's only when it's a nested object that it becomes a problem.</p>
<p>I am trying to avoid having to write a custom converter for each json object that exists, and instead try to make a generic one. Which is probably my issue and maybe should be abandoned. But just checking if anyone might have any ideas for a solution.</p>
<p>And aside from that solution above, I have written my own converters that does similar stuff which works fine. Along with custom converter for each specific nested objects, which also works fine.</p>
<p>This is the code that i made myself that works when its for a specific object:
<code>Main</code>:</p>
<pre><code>static void Main(string[] args)
{
var vSalesOrder = new SalesOrder()
{
Project = 1,
PrintDescriptionOnInvoice = true,
PrintNoteOnExternalDocuments = true,
SoBillingContact = new Contact
{
Attention = "attention",
Email = "@whatever.se",
Fax = "lolfax"
}
};
var jsonString = JsonConvert.SerializeObject(vSalesOrder);
}
</code></pre>
<p>Expected output after this should have similar structure as the json above, except for the few properties that have been left out.</p>
<p><code>SalesOrder</code> Class:<br />
WrapWithValueConverter code can be found in the linked overflow question at the top.</p>
<pre><code>public class SalesOrder
{
[JsonProperty("project", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(WrapWithValueConverter<int?>))]
public int? Project { get; set; }
[JsonProperty("printDescriptionOnInvoice", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(WrapWithValueConverter<bool>))]
public bool PrintDescriptionOnInvoice { get; set; }
[JsonProperty("printNoteOnExternalDocuments", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(WrapWithValueConverter<bool>))]
public bool PrintNoteOnExternalDocuments { get; set; }
[JsonProperty("printNoteOnInternalDocuments", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(WrapWithValueConverter<bool>))]
public bool PrintNoteOnInternalDocuments { get; set; }
[JsonProperty("soBillingContact", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(ContactDtoJsonConverter))]
public Contact SoBillingContact { get; set; }
}
</code></pre>
<p><code>ContactDtoJsonConverter</code> Class:</p>
<pre><code>public class ContactDtoJsonConverter : JsonConverter<Contact>
{
public override bool CanRead => false;
public override bool CanWrite => true;
public override Contact ReadJson(JsonReader reader, Type objectType, Contact existingValue, bool hasExistingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override void WriteJson(JsonWriter writer, Contact value, JsonSerializer serializer)
{
var dtoContact = new DtoContact
{
Value = value
};
JToken t = JToken.FromObject(dtoContact);
JObject o = (JObject)t;
o.WriteTo(writer);
}
}
</code></pre>
<p><code>DtoContact</code> Class:</p>
<pre><code>public class DtoContact
{
[JsonProperty("value", NullValueHandling = NullValueHandling.Ignore)]
public Contact Value { get; set; }
}
</code></pre>
<p><code>Contact</code> Class:</p>
<pre><code>public class Contact
{
[JsonProperty("overrideContact", NullValueHandling = NullValueHandling.Ignore)]
public bool OverrideContact { get;set; }
[JsonProperty("attention", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(StringDtoJsonConverter))]
public string Attention { get; set; }
[JsonProperty("email", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(StringDtoJsonConverter))]
public string Email { get; set; }
[JsonProperty("fax", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(StringDtoJsonConverter))]
public string Fax { get; set; }
[JsonProperty("name", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(StringDtoJsonConverter))]
public string Name { get; set; }
[JsonProperty("phone1", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(StringDtoJsonConverter))]
public string Phone1 { get; set; }
[JsonProperty("phone2", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(StringDtoJsonConverter))]
public string Phone2 { get; set; }
[JsonProperty("web", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(StringDtoJsonConverter))]
public string Web { get; set; }
}
</code></pre>
<p><code>StringDtoJsonConverter</code> Class:</p>
<pre><code>public class StringDtoJsonConverter : JsonConverter<string>
{
public override string ReadJson(JsonReader reader, Type objectType, string existingValue, bool hasExistingValue, JsonSerializer serializer)
{
return (string)reader.Value;
}
public override void WriteJson(JsonWriter writer, string value, JsonSerializer serializer)
{
JToken t = JToken.FromObject(value);
if (t.Type != JTokenType.Object)
{
var dtoValue = new DtoString
{
Value = value
};
serializer.Serialize(writer, dtoValue);
}
}
}
</code></pre>
|
[
{
"answer_id": 74628757,
"author": "Serge",
"author_id": 11392290,
"author_profile": "https://Stackoverflow.com/users/11392290",
"pm_score": 0,
"selected": false,
"text": " var jsonObj = JObject.Parse(json);\n\n SalesOrder salesOrder = null;\n \n if (jsonObj[\"printNoteOnInternalDocuments\"].Type == JTokenType.Boolean) \n salesOrder = jsonObj.ToObject<SalesOrder>();\nelse\n{\n var newJsonObj = new JObject\n {\n [\"printNoteOnInternalDocuments\"] = jsonObj[\"printNoteOnInternalDocuments\"][\"value\"],\n\n [\"soBillingContact\"] = new JObject( ((JObject) jsonObj[\"soBillingContact\"][\"value\"]).Properties()\n .Select(p=> new JProperty( p.Name,p.Value[\"value\"])))\n };\n\n salesOrder = newJsonObj.ToObject<SalesOrder>();\n}\n"
},
{
"answer_id": 74633560,
"author": "dbc",
"author_id": 3744182,
"author_profile": "https://Stackoverflow.com/users/3744182",
"pm_score": 2,
"selected": false,
"text": "Self referecing loop [JsonProperty(ReferenceLoopHandling = ReferenceLoopHandling.Serialize)] DTO.value sealed class DTO { [JsonConverter(typeof(NoConverter)), JsonProperty(ReferenceLoopHandling = ReferenceLoopHandling.Serialize)] public TValue value { get; set; } public object GetValue() => value; }\n [JsonConverter(typeof(WrapWithValueConverter<T>))] public class WrapWithValueContractResolver : DefaultContractResolver\n{\n protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)\n {\n var property = base.CreateProperty(member, memberSerialization);\n if (property.Converter == null && property.ItemConverter == null) // property.Converter check is required to avoid applying the converter to WrapWithValueConverter<TValue>.DTO.value\n property.Converter = (JsonConverter)Activator.CreateInstance(typeof(WrapWithValueConverter<>).MakeGenericType(property.PropertyType));\n return property;\n }\n}\n\npublic class WrapWithValueConverter<TValue> : JsonConverter\n{\n // Here we take advantage of the fact that a converter applied to a property has highest precedence to avoid an infinite recursion.\n sealed class DTO { [JsonConverter(typeof(NoConverter)), JsonProperty(ReferenceLoopHandling = ReferenceLoopHandling.Serialize)] public TValue value { get; set; } public object GetValue() => value; }\n\n public override bool CanConvert(Type objectType) => typeof(TValue).IsAssignableFrom(objectType);\n\n public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)\n => serializer.Serialize(writer, new DTO { value = (TValue)value });\n\n public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)\n => serializer.Deserialize<DTO>(reader)?.GetValue();\n}\n\npublic class NoConverter : JsonConverter\n{\n // NoConverter taken from this answer https://stackoverflow.com/a/39739105/3744182\n // By https://stackoverflow.com/users/3744182/dbc\n // To https://stackoverflow.com/questions/39738714/selectively-use-default-json-converter\n public override bool CanConvert(Type objectType) { throw new NotImplementedException(); /* This converter should only be applied via attributes */ }\n public override bool CanRead => false;\n public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) => throw new NotImplementedException();\n public override bool CanWrite => false;\n public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => throw new NotImplementedException();\n}\n DefaultContractResolver resolver = new WrapWithValueContractResolver // Cache statically and reuse for best performance\n{\n //NamingStrategy = new CamelCaseNamingStrategy(), // Uncomment if you need camel case\n}; \n\nvar json = JsonConvert.SerializeObject(vSalesOrder, Formatting.Indented, settings);\n\nvar order2 = JsonConvert.DeserializeObject<SalesOrder>(json, settings);\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4560420/"
] |
74,624,518
|
<pre><code>class Product(models.Model):
name = models.CharField(max_length=80)
product_image = models.ImageField(upload_to='product/product/images/%Y/%m/%d/', blank=True)
price = models.IntegerField()
</code></pre>
<pre><code>class Cart(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
</code></pre>
<pre><code>class CartItem(models.Model):
item = models.ForeignKey(Product, null=True, on_delete=models.CASCADE)
qty = models.IntegerField(default=1)
cart = models.ForeignKey(Cart, null=True, on_delete=models.CASCADE)
</code></pre>
<p>I'm trying to get an automatic total price that will be shown on check out page. I want to add a 'total_price' column on CartItem model and set the default 'item.price * qty', but when I tried to add this line to the class:</p>
<pre><code> total_price = models.IntegerField(default=item.price)
</code></pre>
<p>since default value for qty is 1 but I got AttributeError: 'ForeignKey' object has no attribute 'price' error.</p>
<p>I also tried add this to the class:</p>
<pre><code>@property
def total_price(self):
item = self.object.get(product=self.item)
return self.item.price
</code></pre>
<p>but I'm not sure which model will have the property? And when I added this method, I lost total_price column which I set its default as 0. I apologize for the lacking quality of solutions!</p>
|
[
{
"answer_id": 74624729,
"author": "Osman",
"author_id": 3466206,
"author_profile": "https://Stackoverflow.com/users/3466206",
"pm_score": 1,
"selected": false,
"text": " class CartItem(models.Model):\n cart = models.ForeignKey(Cart, null=True, on_delete=models.CASCADE, \n related_name=\"orders\") \n \n @property\n def total_price(self):\n return self.qty * self.item.price\n class Cart(models.Model):\n\n @property\n def total_amount(self):\n self.orders.annotate(total_spent=Sum(\n F('item__price') * \n F('qty'), \n output_field=models.FloatField()\n ))\n"
},
{
"answer_id": 74624734,
"author": "ruddra",
"author_id": 2696165,
"author_profile": "https://Stackoverflow.com/users/2696165",
"pm_score": 3,
"selected": true,
"text": "Cart.objects.all().annotate(total_spent=Sum(\n F('cartitem__item__price') * \n F('cartitem__qty'), \n output_field=models.FloatField()\n ))\n class Cart(...):\n ....\n\n @property\n def total_price(self):\n return self.cartitem_set.aggregate(price=Sum(\n F('item__price') * \n F('qty'), \n output_field=models.FloatField()\n )['price']\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16204358/"
] |
74,624,537
|
<p>I'm just porting some code from javascript to C++. As some might know, in JS it's pretty ususal to buffer callbacks in a vector, but how can I do the same in C++?</p>
<p>Consider the following - not yet working - code. What I'm doing here is for an object <code>tree</code> to register a callback with its <code>leaf</code> (sorry couldn't think of better names). As the callback function will access members within <code>tree</code> itself, it needs to capture the this-pointer. The problem that arises now is twofold:</p>
<ol>
<li><p>The leaf class layout needs to be known, therefore I need to provide the type of the callable to the vector. But it's impossible to know the type of a lambda beforehand, especially if it catches the this ptr.</p>
</li>
<li><p>Even if the type could be deduced beforehand, I still have the problem that the lambda type would probably only allow this-pointers of a specific object to be embedded into its type, thus rendering every call to <code>register_callback()</code> that doesn't originate from <code>tree</code> as unavailable.</p>
</li>
</ol>
<p><a href="https://godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(filename:%271%27,fontScale:14,fontUsePx:%270%27,j:1,lang:c%2B%2B,selection:(endColumn:11,endLineNumber:5,positionColumn:11,positionLineNumber:5,selectionStartColumn:11,selectionStartLineNumber:5,startColumn:11,startLineNumber:5),source:%27%23include+%3Cvector%3E%0A%23include+%3Ccstdio%3E%0A%0Atemplate+%3Cstd::invocable+Cb%3E%0Aclass+leaf%0A%7B%0Apublic:%0A++++auto+register_callback(Cb)%0A++++%7B%0A%0A++++%7D%0A%0A++++auto+do_leave()%0A++++%7B%0A++++++++for+(auto+cb+:+callbacks_)+%7B%0A++++++++++++cb()%3B%0A++++++++%7D%0A++++%7D%0A%0A++++std::vector%3CCb%3E+callbacks_%3B%0A%7D%3B%0A%0Aclass+tree%0A%7B%0Apublic:%0A++++tree()%0A++++%7B%0A++++++++myleaf_.register_callback(%5Bthis%5D()%7B%0A++++++++++++do_some_messageing()%3B%0A++++++++%7D)%3B%0A++++%7D%0A%0A++++auto+do_some_messageing()+-%3E+void%0A++++%7B%0A++++++++printf(%22Hello+World%5Cn%22)%3B%0A++++%7D%0A%0A++++leaf%3C%3F%3F%3F%3E+myleaf_%3B%0A++++%0A%7D%3B%0A%0Aint+main()%0A%7B%0A++++tree+Tree1%3B%0A%0A++++Tree1.myleaf_.do_leave()%3B%0A%7D%27),l:%275%27,n:%270%27,o:%27C%2B%2B+source+%231%27,t:%270%27)),k:47.31070496083551,l:%274%27,n:%270%27,o:%27%27,s:0,t:%270%27),(g:!((g:!((h:compiler,i:(compiler:g122,deviceViewOpen:%271%27,filters:(b:%270%27,binary:%271%27,commentOnly:%270%27,demangle:%270%27,directives:%270%27,execute:%270%27,intel:%270%27,libraryCode:%270%27,trim:%271%27),flagsViewOpen:%271%27,fontScale:14,fontUsePx:%270%27,j:1,lang:c%2B%2B,libs:!(),options:%27-Wall+-Os+--std%3Dc%2B%2B20%27,selection:(endColumn:1,endLineNumber:1,positionColumn:1,positionLineNumber:1,selectionStartColumn:1,selectionStartLineNumber:1,startColumn:1,startLineNumber:1),source:1),l:%275%27,n:%270%27,o:%27+x86-64+gcc+12.2+(Editor+%231)%27,t:%270%27)),header:(),l:%274%27,m:41.3677130044843,n:%270%27,o:%27%27,s:0,t:%270%27),(g:!((h:output,i:(compilerName:%27x86-64+gcc+12.2%27,editorid:1,fontScale:14,fontUsePx:%270%27,j:1,wrap:%271%27),l:%275%27,n:%270%27,o:%27Output+of+x86-64+gcc+12.2+(Compiler+%231)%27,t:%270%27)),k:50,l:%274%27,m:58.632286995515706,n:%270%27,o:%27%27,s:0,t:%270%27)),k:52.689295039164485,l:%273%27,n:%270%27,o:%27%27,t:%270%27)),l:%272%27,n:%270%27,o:%27%27,t:%270%27)),version:4" rel="nofollow noreferrer">CompilerExplorer</a></p>
<pre><code>#include <vector>
#include <cstdio>
template <std::invocable Cb>
class leaf
{
public:
auto register_callback(Cb)
{
}
auto do_leave()
{
for (auto cb : callbacks_) {
cb();
}
}
std::vector<Cb> callbacks_;
};
class tree
{
public:
tree()
{
myleaf_.register_callback([this](){
do_some_messageing();
});
}
auto do_some_messageing() -> void
{
printf("Hello World\n");
}
leaf<???> myleaf_;
};
int main()
{
tree Tree1;
Tree1.myleaf_.do_leave();
}
</code></pre>
<p>What would I have to do to circumvent those problems? If possible without std::function. I'm also open for different approaches.</p>
|
[
{
"answer_id": 74625630,
"author": "Lasersköld",
"author_id": 3748275,
"author_profile": "https://Stackoverflow.com/users/3748275",
"pm_score": 1,
"selected": false,
"text": "std::function #include <vector>\n#include <cstdio>\n#include <memory>\n\nclass callback_base {\n public:\n virtual void operator() () = 0;\n virtual ~callback_base() = default;\n};\n\ntemplate <typename Cb>\nstruct callback: public callback_base {\n callback(Cb cb): _callback{cb} {}\n\n Cb _callback;\n\n void operator() () override {\n _callback();\n }\n};\n\nclass leaf\n{\npublic:\n template <typename Cb>\n auto register_callback(Cb cb)\n {\n callbacks_.push_back(std::make_unique<callback<Cb>>(cb));\n }\n\n auto do_leave()\n {\n for (auto &cb : callbacks_) {\n (*cb)();\n }\n }\n\n std::vector<std::unique_ptr<callback_base>> callbacks_;\n};\n\nclass tree\n{\npublic:\n tree()\n {\n myleaf_.register_callback([this](){\n do_some_messageing();\n });\n }\n\n auto do_some_messageing() -> void\n {\n printf(\"Hello World\\n\");\n }\n\n leaf myleaf_;\n \n};\n\nint main()\n{\n tree Tree1;\n\n Tree1.myleaf_.do_leave();\n}\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11770390/"
] |
74,624,561
|
<p>I'm using VS code as my code editor (not sure if it's relevant). My first project is on Changing Background Color. Once I'm done writing my codes, how do I get them to show on a browser?</p>
<p>I'm not sure how to get it to show on a browser.</p>
|
[
{
"answer_id": 74624710,
"author": "Zehan Khan",
"author_id": 16884475,
"author_profile": "https://Stackoverflow.com/users/16884475",
"pm_score": 0,
"selected": false,
"text": "http://127.0.0.1:5500/\n"
},
{
"answer_id": 74624722,
"author": "Oley",
"author_id": 18898615,
"author_profile": "https://Stackoverflow.com/users/18898615",
"pm_score": 0,
"selected": false,
"text": " <script src=\"script.js\" defer></script>\n <head></head>"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17573575/"
] |
74,624,578
|
<p>I tried with all possible nodejs version and npm via nvm, I tried to downgrade/upgrade ng core and ng cli tried to install sass-node and removed sass and vice versa nothing seems to work.
I've googled all stack overflow question there are many very similar to mine but nothing seems to solve</p>
|
[
{
"answer_id": 74624710,
"author": "Zehan Khan",
"author_id": 16884475,
"author_profile": "https://Stackoverflow.com/users/16884475",
"pm_score": 0,
"selected": false,
"text": "http://127.0.0.1:5500/\n"
},
{
"answer_id": 74624722,
"author": "Oley",
"author_id": 18898615,
"author_profile": "https://Stackoverflow.com/users/18898615",
"pm_score": 0,
"selected": false,
"text": " <script src=\"script.js\" defer></script>\n <head></head>"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5270318/"
] |
74,624,610
|
<p>I have a table like this</p>
<pre><code>CREATE TABLE userinteractions
(
userid bigint,
dobyr int,
-- lots more fields that are not relevant to the question
);
</code></pre>
<p>My problem is that some of the data is polluted with multiple <code>dobyr</code> values for the same user.</p>
<p>The table is used as the basis for further processing by creating a new table. These cases need to be removed from the pipeline.</p>
<p>I want to be able to create a clean table that contains unique <code>userid</code> and <code>dobyr</code> limited to the cases where there is only one value of <code>dobyr</code> for the <code>userid</code> in <code>userinteractions</code>.</p>
<p>For example I start with data like this:</p>
<pre><code>userid,dobyr
1,1995
1,1995
2,1999
3,1990 # dobyr values not equal
3,1999 # dobyr values not equal
4,1989
4,1989
</code></pre>
<p>And I want to select from this to get a table like this:</p>
<pre><code>userid,dobyr
1,1995
2,1999
4,1989
</code></pre>
<p>Is there an elegant, efficient way to get this in a single sql query?</p>
<p>I am using postgres.</p>
<p>EDIT: I do not have permissions to modify the <code>userinteractions</code> table, so I need a <code>SELECT</code> solution, not a <code>DELETE</code> solution.</p>
|
[
{
"answer_id": 74629117,
"author": "Zegarek",
"author_id": 5298879,
"author_profile": "https://Stackoverflow.com/users/5298879",
"pm_score": 1,
"selected": false,
"text": "userid dobyr userid dobyr create table userinteractions_clean as \nselect distinct on (userid,dobyr) * \nfrom userinteractions\nwhere userid in ( \n select userid\n from userinteractions\n group by userid\n having count(distinct dobyr)=1 )\norder by userid,dobyr;\n not in not exists exists order by userid (userid,dobyr) create table userinteractions_whitelist as\nselect userid\nfrom userinteractions\ngroup by userid\nhaving count(distinct dobyr)=1\n"
},
{
"answer_id": 74629307,
"author": "MatBailie",
"author_id": 53341,
"author_profile": "https://Stackoverflow.com/users/53341",
"pm_score": 0,
"selected": false,
"text": "SELECT\n userid,\n MAX(dobyr) AS dobyr\nFROM\n userinteractions\nGROUP BY\n userid\nHAVING\n COUNT(DISTINCT dobyr) = 1\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/837451/"
] |
74,624,613
|
<p>I want to write a method that returns the name field of the person whose color id I entered. How do I do this? For example, when I type 97, the name "Veli" will give to me.</p>
<pre class="lang-js prettyprint-override"><code>const data = [
{
id: 1,
name: "Ali",
colorList: [
{
id: 99,
color_name: 'yellow',
}
],
},
{
id: 2,
name: "Veli",
colorList: [
{
id: 98,
color_name: 'red',
},
{
id: 97,
color_name: 'blue',
},
]
}
]
</code></pre>
|
[
{
"answer_id": 74629117,
"author": "Zegarek",
"author_id": 5298879,
"author_profile": "https://Stackoverflow.com/users/5298879",
"pm_score": 1,
"selected": false,
"text": "userid dobyr userid dobyr create table userinteractions_clean as \nselect distinct on (userid,dobyr) * \nfrom userinteractions\nwhere userid in ( \n select userid\n from userinteractions\n group by userid\n having count(distinct dobyr)=1 )\norder by userid,dobyr;\n not in not exists exists order by userid (userid,dobyr) create table userinteractions_whitelist as\nselect userid\nfrom userinteractions\ngroup by userid\nhaving count(distinct dobyr)=1\n"
},
{
"answer_id": 74629307,
"author": "MatBailie",
"author_id": 53341,
"author_profile": "https://Stackoverflow.com/users/53341",
"pm_score": 0,
"selected": false,
"text": "SELECT\n userid,\n MAX(dobyr) AS dobyr\nFROM\n userinteractions\nGROUP BY\n userid\nHAVING\n COUNT(DISTINCT dobyr) = 1\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19301566/"
] |
74,624,629
|
<p>Basically, I have a set of BigDecimal values for example
<strong>[3.2,3.10,3.12,3.17,3.9].</strong></p>
<p>I want to sort them based on the values after the dot using java.
The expected output should be like <strong>[3.2,3.9,3.10,3.12,3.17]</strong>.
how do I write a code for this can you please help?</p>
|
[
{
"answer_id": 74625227,
"author": "user16320675",
"author_id": 16320675,
"author_profile": "https://Stackoverflow.com/users/16320675",
"pm_score": 0,
"selected": false,
"text": "scale 3.10 10 private static BigDecimal decimalPart(BigDecimal num) {\n var dec = num.remainder(BigDecimal.ONE); // decimal part (e.g. 0.10)\n var adj = dec.movePointRight(dec.scale());\n return adj;\n}\n Comparator var byDecimalPart = Comparator.comparing(SortedDecimal::decimalPart);\nvar sorted = input\n .stream()\n .sorted(byDecimalPart)\n .toList(); // or .collect(...) or .forEach(...)\n"
},
{
"answer_id": 74631269,
"author": "Holger",
"author_id": 2711488,
"author_profile": "https://Stackoverflow.com/users/2711488",
"pm_score": 1,
"selected": false,
"text": "BigDecimal BigDecimal public record Version(int major, int minor) implements Comparable<Version> {\n public static Version parse(String s) {\n int dot = s.indexOf('.');\n return dot < 0? new Version(Integer.parseInt(s), 0):\n new Version(Integer.parseInt(s, 0, dot, 10),\n Integer.parseInt(s, dot + 1, s.length(), 10));\n }\n\n @Override\n public int compareTo(Version v) {\n return major != v.major?\n Integer.compare(major, v.major): Integer.compare(minor, v.minor);\n }\n\n @Override\n public String toString() {\n return major + \".\" + minor;\n }\n}\n Stream.of(\"3.2\",\"3.10\",\"3.12\",\"3.17\",\"3.9\").map(Version::parse)\n .sorted().forEachOrdered(System.out::println);\n 3.2\n3.9\n3.10\n3.12\n3.17\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5741251/"
] |
74,624,641
|
<p>Im making a filter where you can select colors and select newest. It would filter them, but the order by doesn't work for some reason.</p>
<p>I tried it this way. It outputs the colors that match the database table, but it doesn't sort them by date.</p>
<pre><code>$color_arr = ["red", "blue", "white"];
foreach($color_arr as $color) {
$data = $conn->query("SELECT * FROM `prod_items` WHERE item_color LIKE '%$color%' ORDER BY `item_date` DESC");
while ($row = $data->fetch()) {
print_r($row);
}
}
</code></pre>
|
[
{
"answer_id": 74625227,
"author": "user16320675",
"author_id": 16320675,
"author_profile": "https://Stackoverflow.com/users/16320675",
"pm_score": 0,
"selected": false,
"text": "scale 3.10 10 private static BigDecimal decimalPart(BigDecimal num) {\n var dec = num.remainder(BigDecimal.ONE); // decimal part (e.g. 0.10)\n var adj = dec.movePointRight(dec.scale());\n return adj;\n}\n Comparator var byDecimalPart = Comparator.comparing(SortedDecimal::decimalPart);\nvar sorted = input\n .stream()\n .sorted(byDecimalPart)\n .toList(); // or .collect(...) or .forEach(...)\n"
},
{
"answer_id": 74631269,
"author": "Holger",
"author_id": 2711488,
"author_profile": "https://Stackoverflow.com/users/2711488",
"pm_score": 1,
"selected": false,
"text": "BigDecimal BigDecimal public record Version(int major, int minor) implements Comparable<Version> {\n public static Version parse(String s) {\n int dot = s.indexOf('.');\n return dot < 0? new Version(Integer.parseInt(s), 0):\n new Version(Integer.parseInt(s, 0, dot, 10),\n Integer.parseInt(s, dot + 1, s.length(), 10));\n }\n\n @Override\n public int compareTo(Version v) {\n return major != v.major?\n Integer.compare(major, v.major): Integer.compare(minor, v.minor);\n }\n\n @Override\n public String toString() {\n return major + \".\" + minor;\n }\n}\n Stream.of(\"3.2\",\"3.10\",\"3.12\",\"3.17\",\"3.9\").map(Version::parse)\n .sorted().forEachOrdered(System.out::println);\n 3.2\n3.9\n3.10\n3.12\n3.17\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624641",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20642874/"
] |
74,624,654
|
<p>I created this nav bar recently, it's the first nav bar I've made and I'm quite happy with it, that being said it didn't fully meet my vision:</p>
<p><a href="https://i.stack.imgur.com/N2owJ.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/N2owJ.gif" alt="First Nav" /></a></p>
<p>What I am trying to create is a nav bar that will respond relative to where you are on the page. For example if I'm at the top of the <em>about</em> section it would look like this:</p>
<p><a href="https://i.stack.imgur.com/WINBtm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WINBtm.png" alt="Mock up 1." /></a></p>
<p>As you continue to scroll through the various sections, they would scroll along side the nav bar, once reaching the top of the next section sitting at the top underneath the previous.</p>
<p>I've looked at Spyscroll but I haven't seen anything on the docs, nor any examples anywhere else of it having being responsive the the manor I described. Rather I see it being either on the section or off the section.</p>
<p>I'm just looking to be pointed in the right direction as I'm sure something like this is possible, unfortunately I'm quite new to web dev and you don't know what you don't know!</p>
<p>On a side note I'm also curious as to if this is a bad idea from a UI/UX standpoint as I haven't been able to find any examples of this.</p>
<p><strong>Edit for clarity</strong></p>
<p>I am not asking for help to fix broken code. I'm asking if what I'm looking to achieve is feasible and what I need to look into to create it.</p>
<p>If you're interested in seeing the code for the nav bar I created previously it is available here:
<a href="https://github.com/Kal-Toh/Simple-side-Nav-with-hover-effect" rel="nofollow noreferrer">Simple Navigation Bar</a></p>
|
[
{
"answer_id": 74624799,
"author": "cloned",
"author_id": 4733161,
"author_profile": "https://Stackoverflow.com/users/4733161",
"pm_score": 3,
"selected": true,
"text": "let options = {\n rootMargin: '-50px 0px -55%' // whatever suits your usecase, see documentation for this!\n}\n\nlet observer = new IntersectionObserver(callback, options);\n let entries = document.querySelectorAll('section');\nentries.forEach(entry => {observer.observe(entry);})\n const observer = new IntersectionObserver(function (entries, self) {\n entries.forEach(entry => {\n if (entry.isIntersecting) {\n //specify what should happen if an element is coming into view, like defined in the options. \n }\n });\n}, config);\n"
},
{
"answer_id": 74625208,
"author": "Chezo",
"author_id": 16993334,
"author_profile": "https://Stackoverflow.com/users/16993334",
"pm_score": -1,
"selected": false,
"text": "function changeCss() {\n var first = document.querySelector(\".first\");\n var second = document.querySelector(\".second\");\n var third = document.querySelector(\".third\");\n\n if (this.scrollY > 1500) {\n first.style.marginBottom = \"0px\";\n second.style.marginBottom = \"0px\";\n third.style.marginBottom = \"40px\";\n } else if (this.scrollY > 1000) {\n first.style.marginBottom = \"0px\";\n second.style.marginBottom = \"40px\";\n third.style.marginBottom = \"0px\";\n } else {\n first.style.marginBottom = \"40px\";\n second.style.marginBottom = \"0px\";\n third.style.marginBottom = \"0px\";\n\n }\n}\n\nwindow.addEventListener(\"scroll\", changeCss, false); body{\n background-color: white;\n height: 1000vh\n}\n.menu{\n position:fixed;\n}\nnav a{\n padding: 10px 12px;\n color: black;\n text-transform:uppercase;\n text-decoration: none\n}\n\n.first{\n margin-bottom: 40px;\n} <nav class=\"menu\">\n\n <div class=\"first\">\n <a href=\"#\">Home</a> <br />\n </div> \n <div class=\"second\">\n <a href=\"#\">About</a> <br />\n </div> \n <div class=\"third\">\n <a href=\"#\">Contact</a> <br />\n </div>\n\n</nav>"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19127509/"
] |
74,624,663
|
<p>How can I setup a framework for API calling in flutter ?</p>
<p>Instead of just creating a api call function need to create a framework that can be used for multiple future projects</p>
|
[
{
"answer_id": 74624799,
"author": "cloned",
"author_id": 4733161,
"author_profile": "https://Stackoverflow.com/users/4733161",
"pm_score": 3,
"selected": true,
"text": "let options = {\n rootMargin: '-50px 0px -55%' // whatever suits your usecase, see documentation for this!\n}\n\nlet observer = new IntersectionObserver(callback, options);\n let entries = document.querySelectorAll('section');\nentries.forEach(entry => {observer.observe(entry);})\n const observer = new IntersectionObserver(function (entries, self) {\n entries.forEach(entry => {\n if (entry.isIntersecting) {\n //specify what should happen if an element is coming into view, like defined in the options. \n }\n });\n}, config);\n"
},
{
"answer_id": 74625208,
"author": "Chezo",
"author_id": 16993334,
"author_profile": "https://Stackoverflow.com/users/16993334",
"pm_score": -1,
"selected": false,
"text": "function changeCss() {\n var first = document.querySelector(\".first\");\n var second = document.querySelector(\".second\");\n var third = document.querySelector(\".third\");\n\n if (this.scrollY > 1500) {\n first.style.marginBottom = \"0px\";\n second.style.marginBottom = \"0px\";\n third.style.marginBottom = \"40px\";\n } else if (this.scrollY > 1000) {\n first.style.marginBottom = \"0px\";\n second.style.marginBottom = \"40px\";\n third.style.marginBottom = \"0px\";\n } else {\n first.style.marginBottom = \"40px\";\n second.style.marginBottom = \"0px\";\n third.style.marginBottom = \"0px\";\n\n }\n}\n\nwindow.addEventListener(\"scroll\", changeCss, false); body{\n background-color: white;\n height: 1000vh\n}\n.menu{\n position:fixed;\n}\nnav a{\n padding: 10px 12px;\n color: black;\n text-transform:uppercase;\n text-decoration: none\n}\n\n.first{\n margin-bottom: 40px;\n} <nav class=\"menu\">\n\n <div class=\"first\">\n <a href=\"#\">Home</a> <br />\n </div> \n <div class=\"second\">\n <a href=\"#\">About</a> <br />\n </div> \n <div class=\"third\">\n <a href=\"#\">Contact</a> <br />\n </div>\n\n</nav>"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11925795/"
] |
74,624,724
|
<p>I usually run Python on Google Colab, however I need to run a script in the terminal in Ubuntu.</p>
<p>I have the following script
test.py:</p>
<pre><code>#!/usr/bin/env python
# testing a func
def hello(x):
if x > 5:
return "good"
else:
return "bad"
hello(2)
</code></pre>
<p>When executed it fails to return anything. Now I could just replace the return statements with a print statement. However, for other scripts I have, a return statement is needed.</p>
<p>I tried:</p>
<pre><code>python test.py
</code></pre>
<p>You see, on Google Colab, I can simply call the function (hello(2)) and it will execute.</p>
<p>Desired output:</p>
<pre><code>> python test.py
> bad
</code></pre>
|
[
{
"answer_id": 74624795,
"author": "milanbalazs",
"author_id": 11502612,
"author_profile": "https://Stackoverflow.com/users/11502612",
"pm_score": 3,
"selected": true,
"text": "STDOUT good bad hello(2) print(hello(2)) hello(2) STDOUT"
},
{
"answer_id": 74625839,
"author": "CamiloSDA",
"author_id": 10603412,
"author_profile": "https://Stackoverflow.com/users/10603412",
"pm_score": 0,
"selected": false,
"text": "#!/usr/bin/env python\nimport sys\n\ndef hello(x):\n if x > 5:\n return \"good\"\n else:\n return \"bad\"\n\n print(hello(int(sys.argv[1])))\n python test.py 6\n > python test.py 6\n> good\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11586653/"
] |
74,624,744
|
<p>I am a beginner in react trying to fetch an object from firebase and I would like to initialise the useState with the data fetched from the database,but each time the data renders undefined value.Here is my truncated code</p>
<pre><code>const ProductDetails = () => {
const [tab, setTab] = useState("desc");
const [products, setProducts] = useState([]);
const reviewUser = useRef("");
const reviewMsg = useRef("");
const dispatch = useDispatch();
const [rating, setRating] = useState(null);
const { id } = useParams();
const product = products.find(
async (item) => (await item.key.slice(1)) === id
);
const {
image: imgUrl,
title: productName,
amount: price,
description,
shortDesc,
category,
} = product.data;
const fetchProducts = async () => {
const db = getDatabase();
const thumbnailRef = ref(db, "Contents/");
onValue(thumbnailRef, (snapshot) => {
snapshot.forEach((childSnapshot) => {
const childData = childSnapshot.val();
const childKey = childSnapshot.key;
setProducts((prev) => [...prev, { key: childKey, data: childData }]);
});
});
};
useEffect(() => {
fetchProducts();
}, []);
</code></pre>
<p>the error I get is "cannot read properties of undefined (reading 'data')".As I said I am a beginner to react and it could be I am making an amateur mistake,</p>
|
[
{
"answer_id": 74624783,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 2,
"selected": true,
"text": "useMemo products const product = useMemo(() => products.find(\n (item) => item.key === id\n ), [products]);\n const {\n image: imgUrl,\n title: productName,\n amount: price,\n description,\n shortDesc,\n category,\n } = product?.data || { image: '',title: '',amount: '',description: '',shortDesc: '',category: '',};\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13541483/"
] |
74,624,816
|
<p>I use Selenium below method.</p>
<ol>
<li><p>open chrome by using chromedriver selenium</p>
</li>
<li><p>manually login</p>
</li>
<li><p>get information of webpage</p>
</li>
</ol>
<p>However, after doing this, Selenium seems to get the html code when not logged in.</p>
<p>Is there a solution?</p>
|
[
{
"answer_id": 74624783,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 2,
"selected": true,
"text": "useMemo products const product = useMemo(() => products.find(\n (item) => item.key === id\n ), [products]);\n const {\n image: imgUrl,\n title: productName,\n amount: price,\n description,\n shortDesc,\n category,\n } = product?.data || { image: '',title: '',amount: '',description: '',shortDesc: '',category: '',};\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12355248/"
] |
74,624,842
|
<p><a href="https://i.stack.imgur.com/tY8We.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tY8We.png" alt="enter image description here" /></a></p>
<p>If you see the above graph, no nodes next to each other has the same color. I created a grid graph with diagonal edges across nodes using networkx python and applied greedy color to it.</p>
<pre><code>greed = nx.coloring.greedy_color(G)
print(greed)
</code></pre>
<p>which gives the output</p>
<pre><code>{(1, 1): 0, (1, 2): 1, (1, 3): 0, (1, 4): 1, (1, 5): 0, (1, 6): 1, (1, 7): 0, (1, 8): 1, (2, 1): 2, (2, 2): 3, (2, 3): 2, (2, 4): 3, (2, 5): 2, (2, 6): 3, (2, 7): 2, (2, 8): 3, (3, 1): 0, (3, 2): 1, (3, 3): 0, (3, 4): 1, (3, 5): 0, (3, 6): 1, (3, 7): 0, (3, 8): 1, (4, 1): 2, (4, 2): 3, (4, 3): 2, (4, 4): 3, (4, 5): 2, (4, 6): 3, (4, 7): 2, (4, 8): 3, (5, 1): 0, (5, 2): 1, (5, 3): 0, (5, 4): 1, (5, 5): 0, (5, 6): 1, (5, 7): 0, (5, 8): 1, (6, 1): 2, (6, 2): 3, (6, 3): 2, (6, 4): 3, (6, 5): 2, (6, 6): 3, (6, 7): 2, (6, 8): 3, (7, 1): 0, (7, 2): 1, (7, 3): 0, (7, 4): 1, (7, 5): 0, (7, 6): 1, (7, 7): 0, (7, 8): 1, (8, 1): 2, (8, 2): 3, (8, 3): 2, (8, 4): 3, (8, 5): 2, (8, 6): 3, (8, 7): 2, (8, 8): 3, (0, 1): 2, (0, 2): 3, (0, 3): 2, (0, 4): 3, (0, 5): 2, (0, 6): 3, (0, 7): 2, (0, 8): 3, (1, 0): 1, (1, 9): 0, (2, 0): 3, (2, 9): 2, (3, 0): 1, (3, 9): 0, (4, 0): 3, (4, 9): 2, (5, 0): 1, (5, 9): 0, (6, 0): 3, (6, 9): 2, (7, 0): 1, (7, 9): 0, (8, 0): 3, (8, 9): 2, (9, 1): 0, (9, 2): 1, (9, 3): 0, (9, 4): 1, (9, 5): 0, (9, 6): 1, (9, 7): 0, (9, 8): 1, (0, 0): 3, (0, 9): 2, (9, 0): 1, (9, 9): 0}
</code></pre>
<p>after sorting</p>
<pre><code>{(0, 0): 3, (0, 1): 2, (0, 2): 3, (0, 3): 2, (0, 4): 3, (0, 5): 2, (0, 6): 3, (0, 7): 2, (0, 8): 3, (0, 9): 2, (1, 0): 1, (1, 1): 0, (1, 2): 1, (1, 3): 0, (1, 4): 1, (1, 5): 0, (1, 6): 1, (1, 7): 0, (1, 8): 1, (1, 9): 0, (2, 0): 3, (2, 1): 2, (2, 2): 3, (2, 3): 2, (2, 4): 3, (2, 5): 2, (2, 6): 3, (2, 7): 2, (2, 8): 3, (2, 9): 2, (3, 0): 1, (3, 1): 0, (3, 2): 1, (3, 3): 0, (3, 4): 1, (3, 5): 0, (3, 6): 1, (3, 7): 0, (3, 8): 1, (3, 9): 0, (4, 0): 3, (4, 1): 2, (4, 2): 3, (4, 3): 2, (4, 4): 3, (4, 5): 2, (4, 6): 3, (4, 7): 2, (4, 8): 3, (4, 9): 2, (5, 0): 1, (5, 1): 0, (5, 2): 1, (5, 3): 0, (5, 4): 1, (5, 5): 0, (5, 6): 1, (5, 7): 0, (5, 8): 1, (5, 9): 0, (6, 0): 3, (6, 1): 2, (6, 2): 3, (6, 3): 2, (6, 4): 3, (6, 5): 2, (6, 6): 3, (6, 7): 2, (6, 8): 3, (6, 9): 2, (7, 0): 1, (7, 1): 0, (7, 2): 1, (7, 3): 0, (7, 4): 1, (7, 5): 0, (7, 6): 1, (7, 7): 0, (7, 8): 1, (7, 9): 0, (8, 0): 3, (8, 1): 2, (8, 2): 3, (8, 3): 2, (8, 4): 3, (8, 5): 2, (8, 6): 3, (8, 7): 2, (8, 8): 3, (8, 9): 2, (9, 0): 1, (9, 1): 0, (9, 2): 1, (9, 3): 0, (9, 4): 1, (9, 5): 0, (9, 6): 1, (9, 7): 0, (9, 8): 1, (9, 9): 0}
</code></pre>
<p>But I want it to be in such a way that no two adjacent/neighbor nodes to a node should have the same color <a href="https://i.stack.imgur.com/E7s2g.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/E7s2g.png" alt="enter image description here" /></a></p>
<p>In the above figure, (1,4) [green] has its neighbors (1,3) [red] and (1,5) [red]. In this case both nodes next to node (1,4) are red. But I want (1,3) and (1,5) in different colors. Can anyone tell me how to solve this problem?</p>
<p>I tried greedy color method from networkx to color in such a way that no two nodes adjacent to each other have the same color.</p>
|
[
{
"answer_id": 74638465,
"author": "Alois Christen",
"author_id": 10707092,
"author_profile": "https://Stackoverflow.com/users/10707092",
"pm_score": 1,
"selected": false,
"text": "G2 G n_1 n_2 G G (n_1, n_2) G2 G2 G G2"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13284223/"
] |
74,624,845
|
<p>This is my code:</p>
<pre><code>TextField(
maxLines: 5,
controller: controller,
)
</code></pre>
<p>I want TextFiled nowrap with maxLines, when maxLines was set, the content will be wrap, no horizontal scroll bar, is there any way like in html <code>textarea</code> bellow?</p>
<pre><code> <textarea wrap="off"></textarea>
</code></pre>
<ul>
<li>expect:</li>
</ul>
<p><a href="https://i.stack.imgur.com/8HeTY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8HeTY.png" alt="enter image description here" /></a></p>
<ul>
<li>current:</li>
</ul>
<p><a href="https://i.stack.imgur.com/RuN7g.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RuN7g.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74624918,
"author": "Davis",
"author_id": 10698100,
"author_profile": "https://Stackoverflow.com/users/10698100",
"pm_score": 0,
"selected": false,
"text": "SizedBox(\n\nwidth: 230.0, //your desire width\nchild: TextField(\n controller: controller,\n keyboardType: TextInputType.multiline,\n expands: true,\n maxLines: null,\n)\n)\n"
},
{
"answer_id": 74626559,
"author": "209 Parthiv Rakholiya",
"author_id": 18446348,
"author_profile": "https://Stackoverflow.com/users/18446348",
"pm_score": 1,
"selected": false,
"text": "Container(\nwidth: MediaQuery.of(context).size.width,\nchild: TextField(\n controller: controller,\n keyboardType: TextInputType.multiline,\n expands: true,\n maxLines: null,\n )\n)\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8129004/"
] |
74,624,856
|
<p>Good morning,</p>
<p>I am wondering if someone can point me in the right direction.</p>
<p>I am trying to have a loop go through a list and add them to a printable list.</p>
<p>let's say the user inputs the number two:
Then it should print go pull out two random class-names of the list.
if the user inputs 4 it should pull out 4 random class-names from the list.</p>
<p>this is so i can print out attributes from the classes afterwards depending on the class-names above. with utskrift1=(vars(plane))</p>
<p>i have tried normal loops but it seem to print out the list in it's entirety, and if i ie go print out x=2 then it prints the entire list two times.</p>
<p>#The classes:</p>
<pre><code>import random
class plane:
def __init__(self, dyr, dyrefamilie, antallbein):
self.dyr = 'Hund'
self.dyrefamilie = 'Hundefamilien'
self.antallbein = '4'
def __str__(self):
return f'undulat(={self.dyr},{self.dyrefamilie},{self.antallbein})'
plane2 = plane(dyr='something', dyrefamilie="something", antallbein='4')
class rocket:
def __init__(self, dyr, dyrefamilie, antallbein):
self.dyr = 'something'
self.dyrefamilie = 'something2'
self.antallbein = '4'
def __str__(self):
return f'katt(={self.dyr},{self.dyrefamilie},{self.antallbein})'
rocket2 = rocket(dyr='something', dyrefamilie="something", antallbein='4')
class boat:
def __init__(self, dyr, dyrefamilie, antallbein):
self.dyr = 'something'
self.dyrefamilie = 'something2'
self.antallbein = '5'
def __str__(self):
return f'undulat(={self.dyr},{self.dyrefamilie},{self.antallbein})'
boat2 = boat(dyr='something', dyrefamilie="something", antallbein='2')
</code></pre>
<p>Is it possible to randomise a selectetion and have the list.append(selected random name)
instead of preselecting it like i have done below?</p>
<pre><code>x2=list = []
x1=list = []
# appending instances to list
list.append(plane(1,2,3))
list.append(rocket(1,2,3))
list.append(boat(1,2,3))
random.shuffle(x1) #roterer litt rundt på listen
for i, x1 in enumerate(x1): #kode fra canvas
print('Dyret er en', x1.dyr,'med',x1.antallbein+'-bein'+'.','denne er er en del av', x1.dyrefamilie)
</code></pre>
|
[
{
"answer_id": 74624918,
"author": "Davis",
"author_id": 10698100,
"author_profile": "https://Stackoverflow.com/users/10698100",
"pm_score": 0,
"selected": false,
"text": "SizedBox(\n\nwidth: 230.0, //your desire width\nchild: TextField(\n controller: controller,\n keyboardType: TextInputType.multiline,\n expands: true,\n maxLines: null,\n)\n)\n"
},
{
"answer_id": 74626559,
"author": "209 Parthiv Rakholiya",
"author_id": 18446348,
"author_profile": "https://Stackoverflow.com/users/18446348",
"pm_score": 1,
"selected": false,
"text": "Container(\nwidth: MediaQuery.of(context).size.width,\nchild: TextField(\n controller: controller,\n keyboardType: TextInputType.multiline,\n expands: true,\n maxLines: null,\n )\n)\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9861217/"
] |
74,624,881
|
<p>I had recently with the help of the amazing sehe managed to advance my boost spirit x3 parser for hlsl (high level shading language) that is a c-like language for writing shader kernels for GPU's. Here is the rough grammar I am following...
<a href="https://craftinginterpreters.com/appendix-i.html" rel="nofollow noreferrer">https://craftinginterpreters.com/appendix-i.html</a></p>
<p>Here is the previous question and answer for the curious.</p>
<p><a href="https://stackoverflow.com/questions/74594603/trying-to-parse-nested-expressions-with-boost-spirit-x3">Trying to parse nested expressions with boost spirit x3</a></p>
<p>I am now trying to implement unary and binary operators and have hit a stumbling block with how they recurse. I am able to get it to compile and a single binary operator is parsed, but having multiple nested ones doesn't seem to be working. I suspect the solution is going to be involving semantic actions again to manually propagate values but I struggle to see how to do that yet as the side effects are hard to understand (still working out how it all works).</p>
<p>Here's my compiling example...</p>
<pre><code>#include <boost/fusion/adapted.hpp>
#include <boost/spirit/home/x3.hpp>
#include <boost/spirit/home/x3/support/ast/variant.hpp>
#include <boost/spirit/home/x3/support/utility/error_reporting.hpp>
#include <iomanip>
#include <iostream>
namespace x3 = boost::spirit::x3;
namespace hlsl
{
namespace ast
{
struct Void
{
};
struct Get;
struct Set;
struct Call;
struct Assign;
struct Binary;
struct Unary;
struct Variable
{
std::string name;
};
using Expr = x3::variant<Void, x3::forward_ast<Get>, x3::forward_ast<Set>, Variable, x3::forward_ast<Call>, x3::forward_ast<Assign>, x3::forward_ast<Binary>, x3::forward_ast<Unary>>;
struct Call
{
Expr name;
std::vector<Expr> arguments_;
};
struct Get
{
Expr object_;
std::string property_;
};
struct Set
{
Expr object_;
Expr value_;
std::string name_;
};
struct Assign
{
std::string name_;
Expr value_;
};
struct Binary
{
Expr left_;
std::string op_;
Expr right_;
};
struct Unary
{
std::string op_;
Expr expr_;
};
} // namespace ast
struct printer
{
std::ostream &_os;
using result_type = void;
void operator()(hlsl::ast::Get const &get) const
{
_os << "get { object_:";
get.object_.apply_visitor(*this);
_os << ", property_:" << quoted(get.property_) << " }";
}
void operator()(hlsl::ast::Set const &set) const
{
_os << "set { object_:";
set.object_.apply_visitor(*this);
_os << ", name_:" << quoted(set.name_);
_os << " equals: ";
set.value_.apply_visitor(*this);
_os << " }";
}
void operator()(hlsl::ast::Assign const &assign) const
{
_os << "assign { ";
_os << "name_:" << quoted(assign.name_);
_os << ", value_:";
assign.value_.apply_visitor(*this);
_os << " }";
}
void operator()(hlsl::ast::Variable const &var) const
{
_os << "var{" << quoted(var.name) << "}";
};
void operator()(hlsl::ast::Binary const &bin) const
{
_os << "binary { ";
bin.left_.apply_visitor(*this);
_os << " " << quoted(bin.op_) << " ";
bin.right_.apply_visitor(*this);
_os << " }";
};
void operator()(hlsl::ast::Unary const &un) const
{
_os << "unary { ";
un.expr_.apply_visitor(*this);
_os << quoted(un.op_);
_os << " }";
};
void operator()(hlsl::ast::Call const &call) const
{
_os << "call{";
call.name.apply_visitor(*this);
_os << ", args: ";
for (auto &arg : call.arguments_)
{
arg.apply_visitor(*this);
_os << ", ";
}
_os << /*quoted(call.name) << */ "}";
};
void operator()(hlsl::ast::Void const &) const { _os << "void{}"; };
};
} // namespace hlsl
BOOST_FUSION_ADAPT_STRUCT(hlsl::ast::Variable, name)
BOOST_FUSION_ADAPT_STRUCT(hlsl::ast::Call, name, arguments_)
BOOST_FUSION_ADAPT_STRUCT(hlsl::ast::Get, object_, property_)
BOOST_FUSION_ADAPT_STRUCT(hlsl::ast::Set, object_, value_)
BOOST_FUSION_ADAPT_STRUCT(hlsl::ast::Assign, name_, value_)
BOOST_FUSION_ADAPT_STRUCT(hlsl::ast::Binary, left_, op_, right_)
BOOST_FUSION_ADAPT_STRUCT(hlsl::ast::Unary, op_, expr_)
namespace hlsl::parser
{
struct eh_tag;
struct error_handler
{
template <typename It, typename Exc, typename Ctx>
auto on_error(It &, It, Exc const &x, Ctx const &context) const
{
x3::get<eh_tag>(context)( //
x.where(), "Error! Expecting: " + x.which() + " here:");
return x3::error_handler_result::fail;
}
};
struct program_ : error_handler
{
};
x3::rule<struct identifier_, std::string> const identifier{"identifier"};
x3::rule<struct variable_, ast::Variable> const variable{"variable"};
x3::rule<struct arguments_, std::vector<ast::Expr>> const arguments{"arguments_"};
x3::rule<struct binary_, hlsl::ast::Binary, true> const binary{"binary"};
x3::rule<struct unary_, hlsl::ast::Unary> const unary{"unary"};
x3::rule<struct unarycallwrapper_, hlsl::ast::Expr> const unarycallwrapper{"unarycallwrapper"};
x3::rule<struct get_, ast::Expr> const get{"get"};
x3::rule<struct call_, ast::Expr> const call{"call"};
x3::rule<struct program_, ast::Expr> const program{"program"};
x3::rule<struct primary_, ast::Expr> const primary{"primary"};
x3::rule<struct expression_, ast::Expr> const expression{"expression"};
x3::rule<struct set_, ast::Set, true> const set{"set"};
x3::rule<struct assign_, ast::Assign> const assign{"assign"};
x3::rule<struct assignment_, ast::Expr> const assignment{"assignment"};
auto get_string_from_variable = [](auto &ctx)
{ _val(ctx).name_ = std::move(_attr(ctx).name); };
auto fix_assignExpr = [](auto &ctx)
{ _val(ctx).value_ = std::move(_attr(ctx)); };
auto as_expr = [](auto &ctx)
{ _val(ctx) = ast::Expr(std::move(_attr(ctx))); };
auto as_unary = [](auto &ctx)
{ _val(ctx) = ast::Unary(std::move(_attr(ctx))); };
auto as_call = [](auto &ctx)
{ _val(ctx) = ast::Call{std::move(_val(ctx)), std::move(_attr(ctx))}; };
auto fold_in_get_to_set = [](auto &ctx)
{
auto &val = x3::_val(ctx);
val.name_ = boost::get<x3::forward_ast<ast::Get>>(val.object_).get().property_;
val.object_ = ast::Expr(boost::get<x3::forward_ast<ast::Get>>(val.object_).get().object_);
};
auto as_string = [](auto &ctx)
{ _val(ctx) = std::move(_attr(ctx).name); };
auto as_assign = [](auto &ctx)
{ _val(ctx) = ast::Assign(std::move(_val(ctx)), std::move(_attr(ctx))); };
auto as_get = [](auto &ctx)
{
_val(ctx) = ast::Get{std::move(_val(ctx)), _attr(ctx)};
};
auto variable_def = identifier;
auto primary_def = variable;
auto identifier_def = x3::lexeme[x3::alpha >> *x3::alnum];
auto expression_def = assignment;
auto assignment_def = (assign | set) | binary; // replace binary with call to see the rest working
auto assign_def = variable[get_string_from_variable] >> '=' >> assignment[fix_assignExpr];
auto set_def = (get >> '=' >> assignment)[fold_in_get_to_set];
auto arguments_def = *(expression % ',');
auto get_def = primary[as_expr] >> *('.' >> identifier)[as_get];
auto call_def = primary[as_expr] >> *((x3::lit('(') >> arguments >> x3::lit(')'))[as_call] | ('.' >> identifier)[as_get]);
auto unary_def = (x3::string("-") >> unary);
auto unarycallwrapper_def = unary | call ;
auto binary_def = unarycallwrapper >> x3::string("*") >> unarycallwrapper;
auto program_def = x3::skip(x3::space)[expression];
BOOST_SPIRIT_DEFINE(primary, assign, binary, unary, unarycallwrapper, assignment, get, set, variable, arguments, expression, call, identifier, program);
} // namespace hlsl::parser
int main()
{
using namespace hlsl;
for (std::string const input :
{
"first",
"first.second",
"first.Second.third",
"first.Second().third",
"first.Second(arg1).third",
"first.Second(arg1, arg2).third",
"first = second",
"first.second = third",
"first.second.third = fourth",
"first.second.third = fourth()",
"first.second.third = fourth(arg1)",
"this * that", //binary { var{"this"} "*" var{"that"} }
"this * -that", // binary { var{"this"} "*" unary{'-', var{"that"}} }
"this * that * there",
}) //
{
std::cout << "===== " << quoted(input) << "\n";
auto f = input.begin(), l = input.end();
// Our error handler
auto const p = x3::with<parser::eh_tag>(
x3::error_handler{f, l, std::cerr})[hlsl::parser::program];
if (hlsl::ast::Expr fs; parse(f, l, p, fs))
{
fs.apply_visitor(hlsl::printer{std::cout << "Parsed: "});
std::cout << "\n";
}
else
{
std::cout << "Parse failed at " << quoted(std::string(f, l)) << "\n";
}
}
}
</code></pre>
<p>Any help is appreciated :)</p>
|
[
{
"answer_id": 74638000,
"author": "Daniel Dokipen Elliott",
"author_id": 2089130,
"author_profile": "https://Stackoverflow.com/users/2089130",
"pm_score": 1,
"selected": false,
"text": "_val(ctx) _val(ctx) _attr(ctx) #include <boost/fusion/adapted.hpp>\n#include <boost/spirit/home/x3.hpp>\n#include <boost/spirit/home/x3/support/ast/variant.hpp>\n#include <boost/spirit/home/x3/support/utility/error_reporting.hpp>\n#include <iomanip>\n#include <iostream>\n\nnamespace x3 = boost::spirit::x3;\n\nnamespace hlsl\n{\n namespace ast\n {\n struct Void\n {\n };\n struct Get;\n struct Set;\n struct Call;\n struct Assign;\n struct Divide;\n struct Multiply;\n struct Unary;\n\n struct Variable\n {\n std::string name;\n // operator std::string() const {\n // return name;\n // }\n };\n\n using Expr = x3::variant<Void, x3::forward_ast<Get>, x3::forward_ast<Set>, Variable, x3::forward_ast<Call>, x3::forward_ast<Assign>, x3::forward_ast<Multiply>, x3::forward_ast<Divide>, x3::forward_ast<Unary>>;\n\n struct Call\n {\n Expr name;\n std::vector<Expr> arguments_;\n };\n\n struct Get\n {\n Expr object_;\n std::string property_;\n };\n\n struct Set\n {\n Expr object_;\n Expr value_;\n std::string name_;\n };\n struct Assign\n {\n std::string name_;\n Expr value_;\n };\n // struct Logical\n // {\n // Expr left_;\n // std::string op_;\n // Expr right_;\n // };\n\n struct Multiply\n {\n Expr left_;\n Expr right_;\n };\n\n struct Divide\n {\n Expr left_;\n Expr right_;\n };\n\n struct Unary\n {\n std::string op_;\n Expr expr_;\n };\n } // namespace ast\n\n struct printer\n {\n std::ostream &_os;\n using result_type = void;\n\n void operator()(hlsl::ast::Get const &get) const\n {\n _os << \"get { object_:\";\n get.object_.apply_visitor(*this);\n _os << \", property_:\" << quoted(get.property_) << \" }\";\n }\n\n void operator()(hlsl::ast::Set const &set) const\n {\n _os << \"set { object_:\";\n set.object_.apply_visitor(*this);\n _os << \", name_:\" << quoted(set.name_);\n _os << \" equals: \";\n set.value_.apply_visitor(*this);\n _os << \" }\";\n }\n\n void operator()(hlsl::ast::Assign const &assign) const\n {\n _os << \"assign { \";\n _os << \"name_:\" << quoted(assign.name_);\n _os << \", value_:\";\n assign.value_.apply_visitor(*this);\n _os << \" }\";\n }\n\n void operator()(hlsl::ast::Variable const &var) const\n {\n _os << \"var{\" << quoted(var.name) << \"}\";\n };\n void operator()(hlsl::ast::Divide const &bin) const\n {\n _os << \"divide { \";\n bin.left_.apply_visitor(*this);\n bin.right_.apply_visitor(*this);\n _os << \" }\";\n };\n void operator()(hlsl::ast::Multiply const &bin) const\n {\n _os << \"multiply { \";\n bin.left_.apply_visitor(*this);\n bin.right_.apply_visitor(*this);\n _os << \" }\";\n };\n\n void operator()(hlsl::ast::Unary const &un) const\n {\n _os << \"unary { \";\n un.expr_.apply_visitor(*this);\n _os << quoted(un.op_);\n _os << \" }\";\n };\n void operator()(hlsl::ast::Call const &call) const\n {\n _os << \"call{\";\n call.name.apply_visitor(*this);\n _os << \", args: \";\n\n for (auto &arg : call.arguments_)\n {\n arg.apply_visitor(*this);\n _os << \", \";\n }\n _os << /*quoted(call.name) << */ \"}\";\n };\n void operator()(hlsl::ast::Void const &) const { _os << \"void{}\"; };\n };\n\n} // namespace hlsl\n\nBOOST_FUSION_ADAPT_STRUCT(hlsl::ast::Variable, name)\nBOOST_FUSION_ADAPT_STRUCT(hlsl::ast::Call, name, arguments_)\nBOOST_FUSION_ADAPT_STRUCT(hlsl::ast::Get, object_, property_)\nBOOST_FUSION_ADAPT_STRUCT(hlsl::ast::Set, object_, value_)\nBOOST_FUSION_ADAPT_STRUCT(hlsl::ast::Assign, name_, value_)\nBOOST_FUSION_ADAPT_STRUCT(hlsl::ast::Multiply, left_, right_)\nBOOST_FUSION_ADAPT_STRUCT(hlsl::ast::Divide, left_, right_)\nBOOST_FUSION_ADAPT_STRUCT(hlsl::ast::Unary, op_, expr_)\n\nnamespace hlsl::parser\n{\n struct eh_tag;\n\n struct error_handler\n {\n template <typename It, typename Exc, typename Ctx>\n auto on_error(It &, It, Exc const &x, Ctx const &context) const\n {\n x3::get<eh_tag>(context)( //\n x.where(), \"Error! Expecting: \" + x.which() + \" here:\");\n\n return x3::error_handler_result::fail;\n }\n };\n\n struct program_ : error_handler\n {\n };\n\n x3::rule<struct identifier_, std::string> const identifier{\"identifier\"};\n x3::rule<struct variable_, ast::Variable> const variable{\"variable\"};\n x3::rule<struct arguments_, std::vector<ast::Expr>> const arguments{\"arguments_\"};\n x3::rule<struct binary_, hlsl::ast::Expr> const binary{\"binary\"};\n x3::rule<struct multiply_, hlsl::ast::Expr> const multiply{\"multiply\"};\n x3::rule<struct divide_, hlsl::ast::Expr> const divide{\"divide\"};\n\n x3::rule<struct unary_, hlsl::ast::Unary> const unary{\"unary\"};\n x3::rule<struct unarycallwrapper_, hlsl::ast::Expr> const unarycallwrapper{\"unarycallwrapper\"};\n x3::rule<struct get_, ast::Expr> const get{\"get\"};\n x3::rule<struct call_, ast::Expr> const call{\"call\"};\n x3::rule<struct program_, ast::Expr> const program{\"program\"};\n x3::rule<struct primary_, ast::Expr> const primary{\"primary\"};\n x3::rule<struct expression_, ast::Expr> const expression{\"expression\"};\n x3::rule<struct set_, ast::Set, true> const set{\"set\"};\n x3::rule<struct assign_, ast::Assign> const assign{\"assign\"};\n x3::rule<struct assignment_, ast::Expr> const assignment{\"assignment\"};\n\n auto get_string_from_variable = [](auto &ctx)\n { _val(ctx).name_ = std::move(_attr(ctx).name); };\n\n auto fix_assignExpr = [](auto &ctx)\n { _val(ctx).value_ = std::move(_attr(ctx)); };\n\n auto as_expr = [](auto &ctx)\n { _val(ctx) = ast::Expr(std::move(_attr(ctx))); };\n\n auto as_unary = [](auto &ctx)\n { _val(ctx) = ast::Unary(std::move(_attr(ctx))); };\n\n auto as_call = [](auto &ctx)\n { _val(ctx) = ast::Call{std::move(_val(ctx)), std::move(_attr(ctx))}; };\n\n auto as_multiply = [](auto &ctx)\n { _val(ctx) = ast::Multiply{std::move(_val(ctx)), std::move(_attr(ctx))}; };\n\n auto as_divide = [](auto &ctx)\n { _val(ctx) = ast::Divide{std::move(_val(ctx)), std::move(_attr(ctx))}; };\n\n auto fold_in_get_to_set = [](auto &ctx)\n {\n auto &val = x3::_val(ctx);\n val.name_ = boost::get<x3::forward_ast<ast::Get>>(val.object_).get().property_;\n val.object_ = ast::Expr(boost::get<x3::forward_ast<ast::Get>>(val.object_).get().object_);\n };\n\n auto as_string = [](auto &ctx)\n { _val(ctx) = std::move(_attr(ctx).name); };\n auto as_assign = [](auto &ctx)\n { _val(ctx) = ast::Assign(std::move(_val(ctx)), std::move(_attr(ctx))); };\n auto as_get = [](auto &ctx)\n {\n _val(ctx) = ast::Get{std::move(_val(ctx)), _attr(ctx)};\n };\n\n auto variable_def = identifier;\n auto primary_def = variable;\n auto identifier_def = x3::lexeme[x3::alpha >> *x3::alnum];\n\n auto expression_def = assignment;\n auto assignment_def = (assign | set) | binary; // replace binary with call to see the rest working\n auto assign_def = variable[get_string_from_variable] >> '=' >> assignment[fix_assignExpr];\n auto set_def = (get >> '=' >> assignment)[fold_in_get_to_set];\n\n auto arguments_def = *(expression % ',');\n auto get_def = primary[as_expr] >> *('.' >> identifier)[as_get];\n auto call_def = primary[as_expr] >> *((x3::lit('(') >> arguments >> x3::lit(')'))[as_call] | ('.' >> identifier)[as_get]);\n\n auto unary_def = (x3::string(\"-\") >> unarycallwrapper);\n auto unarycallwrapper_def = call | unary;\n auto binary_def = unarycallwrapper[as_expr] >> *((x3::lit('/') >> unarycallwrapper[as_divide]) | (x3::lit('*') >> unarycallwrapper[as_multiply]));\n auto program_def = x3::skip(x3::space)[expression];\n\n BOOST_SPIRIT_DEFINE(primary, assign, binary, multiply, divide, unary, unarycallwrapper, assignment, get, set, variable, arguments, expression, call, identifier, program);\n\n} // namespace hlsl::parser\n\nint main()\n{\n using namespace hlsl;\n\n for (std::string const input :\n {\n \"first\",\n \"first.second\",\n \"first.Second.third\",\n \"first.Second().third\",\n \"first.Second(arg1).third\",\n \"first.Second(arg1, arg2).third\",\n \"first = second\",\n \"first.second = third\",\n \"first.second.third = fourth\",\n \"first.second.third = fourth()\",\n \"first.second.third = fourth(arg1)\",\n \"this * that\", // binary { var{\"this\"} \"*\" var{\"that\"} }\n \"this * -that\", // binary { var{\"this\"} \"*\" unary{'-', var{\"that\"}} }\n \"this * that * there\",\n \"this * that / there\",\n \"this.inner * that * there.inner2\",\n }) //\n {\n std::cout << \"===== \" << quoted(input) << \"\\n\";\n auto f = input.begin(), l = input.end();\n\n // Our error handler\n auto const p = x3::with<parser::eh_tag>(\n x3::error_handler{f, l, std::cerr})[hlsl::parser::program];\n\n if (hlsl::ast::Expr fs; parse(f, l, p, fs))\n {\n fs.apply_visitor(hlsl::printer{std::cout << \"Parsed: \"});\n std::cout << \"\\n\";\n }\n else\n {\n std::cout << \"Parse failed at \" << quoted(std::string(f, l)) << \"\\n\";\n }\n }\n}\n"
},
{
"answer_id": 74640931,
"author": "Daniel Dokipen Elliott",
"author_id": 2089130,
"author_profile": "https://Stackoverflow.com/users/2089130",
"pm_score": 1,
"selected": false,
"text": "#include <boost/fusion/adapted.hpp>\n#include <boost/spirit/home/x3.hpp>\n#include <boost/spirit/home/x3/support/ast/variant.hpp>\n#include <boost/spirit/home/x3/support/utility/error_reporting.hpp>\n#include <iomanip>\n#include <iostream>\n\nnamespace x3 = boost::spirit::x3;\n\nnamespace hlsl\n{\n namespace ast\n {\n struct Void\n {\n };\n struct Get;\n struct Set;\n struct Call;\n struct Assign;\n struct Divide;\n struct Multiply;\n struct Unary;\n struct Binary2;\n\n struct Variable\n {\n std::string name;\n // operator std::string() const {\n // return name;\n // }\n };\n\n using Expr = x3::variant<Void, x3::forward_ast<Get>, x3::forward_ast<Set>, Variable, x3::forward_ast<Call>, x3::forward_ast<Assign>, x3::forward_ast<Multiply>, x3::forward_ast<Binary2>, x3::forward_ast<Divide>, x3::forward_ast<Unary>>;\n\n struct Call\n {\n Expr name;\n std::vector<Expr> arguments_;\n };\n\n struct Get\n {\n Expr object_;\n std::string property_;\n };\n\n struct Set\n {\n Expr object_;\n Expr value_;\n std::string name_;\n };\n struct Assign\n {\n std::string name_;\n Expr value_;\n };\n // struct Logical\n // {\n // Expr left_;\n // std::string op_;\n // Expr right_;\n // };\n\n struct Multiply\n {\n Expr left_;\n Expr right_;\n };\n\n struct Binary2\n {\n Expr left_;\n std::string op_;\n Expr right_;\n };\n struct Divide\n {\n Expr left_;\n Expr right_;\n };\n\n struct Unary\n {\n std::string op_;\n Expr expr_;\n };\n } // namespace ast\n\n struct printer\n {\n std::ostream &_os;\n using result_type = void;\n\n void operator()(hlsl::ast::Get const &get) const\n {\n _os << \"get { object_:\";\n get.object_.apply_visitor(*this);\n _os << \", property_:\" << quoted(get.property_) << \" }\";\n }\n\n void operator()(hlsl::ast::Set const &set) const\n {\n _os << \"set { object_:\";\n set.object_.apply_visitor(*this);\n _os << \", name_:\" << quoted(set.name_);\n _os << \" equals: \";\n set.value_.apply_visitor(*this);\n _os << \" }\";\n }\n\n void operator()(hlsl::ast::Assign const &assign) const\n {\n _os << \"assign { \";\n _os << \"name_:\" << quoted(assign.name_);\n _os << \", value_:\";\n assign.value_.apply_visitor(*this);\n _os << \" }\";\n }\n\n void operator()(hlsl::ast::Variable const &var) const\n {\n _os << \"var{\" << quoted(var.name) << \"}\";\n };\n void operator()(hlsl::ast::Divide const &bin) const\n {\n _os << \"divide { \";\n bin.left_.apply_visitor(*this);\n bin.right_.apply_visitor(*this);\n _os << \" }\";\n };\n void operator()(hlsl::ast::Multiply const &bin) const\n {\n _os << \"multiply { \";\n bin.left_.apply_visitor(*this);\n bin.right_.apply_visitor(*this);\n _os << \" }\";\n };\n\n void operator()(hlsl::ast::Binary2 const &bin) const\n {\n _os << \"binary2 { \";\n bin.left_.apply_visitor(*this);\n _os << bin.op_ << \", \";\n bin.right_.apply_visitor(*this);\n _os << \" }\";\n };\n\n void operator()(hlsl::ast::Unary const &un) const\n {\n _os << \"unary { \";\n un.expr_.apply_visitor(*this);\n _os << quoted(un.op_);\n _os << \" }\";\n };\n void operator()(hlsl::ast::Call const &call) const\n {\n _os << \"call{\";\n call.name.apply_visitor(*this);\n _os << \", args: \";\n\n for (auto &arg : call.arguments_)\n {\n arg.apply_visitor(*this);\n _os << \", \";\n }\n _os << /*quoted(call.name) << */ \"}\";\n };\n void operator()(hlsl::ast::Void const &) const { _os << \"void{}\"; };\n };\n\n} // namespace hlsl\n\nBOOST_FUSION_ADAPT_STRUCT(hlsl::ast::Variable, name)\nBOOST_FUSION_ADAPT_STRUCT(hlsl::ast::Call, name, arguments_)\nBOOST_FUSION_ADAPT_STRUCT(hlsl::ast::Get, object_, property_)\nBOOST_FUSION_ADAPT_STRUCT(hlsl::ast::Set, object_, value_)\nBOOST_FUSION_ADAPT_STRUCT(hlsl::ast::Assign, name_, value_)\nBOOST_FUSION_ADAPT_STRUCT(hlsl::ast::Multiply, left_, right_)\nBOOST_FUSION_ADAPT_STRUCT(hlsl::ast::Binary2, left_, op_, right_)\nBOOST_FUSION_ADAPT_STRUCT(hlsl::ast::Divide, left_, right_)\nBOOST_FUSION_ADAPT_STRUCT(hlsl::ast::Unary, op_, expr_)\n\nnamespace hlsl::parser\n{\n struct eh_tag;\n\n struct error_handler\n {\n template <typename It, typename Exc, typename Ctx>\n auto on_error(It &, It, Exc const &x, Ctx const &context) const\n {\n x3::get<eh_tag>(context)( //\n x.where(), \"Error! Expecting: \" + x.which() + \" here:\");\n\n return x3::error_handler_result::fail;\n }\n };\n\n struct program_ : error_handler\n {\n };\n\n x3::rule<struct identifier_, std::string> const identifier{\"identifier\"};\n x3::rule<struct binop_, std::string> const binop{\"binop\"};\n\n x3::rule<struct variable_, ast::Variable> const variable{\"variable\"};\n x3::rule<struct arguments_, std::vector<ast::Expr>> const arguments{\"arguments_\"};\n x3::rule<struct binary_, hlsl::ast::Expr> const binary{\"binary\"};\n x3::rule<struct binary2_, hlsl::ast::Expr> const binary2{\"binary2\"};\n\n x3::rule<struct multiply_, hlsl::ast::Expr> const multiply{\"multiply\"};\n x3::rule<struct divide_, hlsl::ast::Expr> const divide{\"divide\"};\n\n x3::rule<struct unary_, hlsl::ast::Unary> const unary{\"unary\"};\n x3::rule<struct unarycallwrapper_, hlsl::ast::Expr> const unarycallwrapper{\"unarycallwrapper\"};\n x3::rule<struct get_, ast::Expr> const get{\"get\"};\n x3::rule<struct call_, ast::Expr> const call{\"call\"};\n x3::rule<struct program_, ast::Expr> const program{\"program\"};\n x3::rule<struct primary_, ast::Expr> const primary{\"primary\"};\n x3::rule<struct expression_, ast::Expr> const expression{\"expression\"};\n x3::rule<struct set_, ast::Set, true> const set{\"set\"};\n x3::rule<struct assign_, ast::Assign> const assign{\"assign\"};\n x3::rule<struct assignment_, ast::Expr> const assignment{\"assignment\"};\n\n auto get_string_from_variable = [](auto &ctx)\n { _val(ctx).name_ = std::move(_attr(ctx).name); };\n\n auto fix_assignExpr = [](auto &ctx)\n { _val(ctx).value_ = std::move(_attr(ctx)); };\n\n auto as_expr = [](auto &ctx)\n { _val(ctx) = ast::Expr(std::move(_attr(ctx))); };\n\n auto as_unary = [](auto &ctx)\n { _val(ctx) = ast::Unary(std::move(_attr(ctx))); };\n\n auto as_call = [](auto &ctx)\n { _val(ctx) = ast::Call{std::move(_val(ctx)), std::move(_attr(ctx))}; };\n\n auto as_multiply = [](auto &ctx)\n { _val(ctx) = ast::Multiply{std::move(_val(ctx)), std::move(_attr(ctx))}; };\n\n auto as_divide = [](auto &ctx)\n { _val(ctx) = ast::Divide{std::move(_val(ctx)), std::move(_attr(ctx))}; };\n\n auto as_binary2A = [](auto &ctx)\n { _val(ctx) = ast::Binary2{std::move(_val(ctx)), std::move(_attr(ctx)), ast::Expr{}}; };\n\n auto as_binary2B = [](auto &ctx)\n { //_val(ctx) = std::move(_val(ctx));\n boost::get<x3::forward_ast<ast::Binary2>>(_val(ctx)).get().right_ = std::move(_attr(ctx)); };\n\n auto fold_in_get_to_set = [](auto &ctx)\n {\n auto &val = x3::_val(ctx);\n val.name_ = boost::get<x3::forward_ast<ast::Get>>(val.object_).get().property_;\n val.object_ = ast::Expr(boost::get<x3::forward_ast<ast::Get>>(val.object_).get().object_);\n };\n\n auto as_string = [](auto &ctx)\n { _val(ctx) = std::move(_attr(ctx).name); };\n auto as_assign = [](auto &ctx)\n { _val(ctx) = ast::Assign(std::move(_val(ctx)), std::move(_attr(ctx))); };\n auto as_get = [](auto &ctx)\n {\n _val(ctx) = ast::Get{std::move(_val(ctx)), _attr(ctx)};\n };\n\n auto variable_def = identifier;\n auto primary_def = variable;\n auto identifier_def = x3::lexeme[x3::alpha >> *x3::alnum];\n\n auto expression_def = assignment;\n auto assignment_def = (assign | set) | binary2; // replace binary with call to see the rest working\n auto assign_def = variable[get_string_from_variable] >> '=' >> assignment[fix_assignExpr];\n auto set_def = (get >> '=' >> assignment)[fold_in_get_to_set];\n\n auto arguments_def = *(expression % ',');\n auto get_def = primary[as_expr] >> *('.' >> identifier)[as_get];\n auto call_def = primary[as_expr] >> *((x3::lit('(') >> arguments >> x3::lit(')'))[as_call] | ('.' >> identifier)[as_get]);\n\n auto unary_def = (x3::string(\"-\") >> unarycallwrapper);\n auto unarycallwrapper_def = unary | call;\n auto binop_def = x3::string(\"*\") | x3::string(\"/\");\n auto binary_def = unarycallwrapper[as_expr] >> *((x3::lit('/') >> unarycallwrapper[as_divide]) | (x3::lit('*') >> unarycallwrapper[as_multiply]));\n auto binary2_def = unarycallwrapper[as_expr] >> *(binop[as_binary2A] >> unarycallwrapper[as_binary2B]);\n\n auto program_def = x3::skip(x3::space)[expression];\n\n BOOST_SPIRIT_DEFINE(primary, assign, binop, binary, binary2, unary, unarycallwrapper, assignment, get, set, variable, arguments, expression, call, identifier, program);\n\n} // namespace hlsl::parser\n\nint main()\n{\n using namespace hlsl;\n\n for (std::string const input :\n {\n \"first\",\n \"first.second\",\n \"first.Second.third\",\n \"first.Second().third\",\n \"first.Second(arg1).third\",\n \"first.Second(arg1, arg2).third\",\n \"first = second\",\n \"first.second = third\",\n \"first.second.third = fourth\",\n \"first.second.third = fourth()\",\n \"first.second.third = fourth(arg1)\",\n \"this * that\", // binary { var{\"this\"} \"*\" var{\"that\"} }\n \"this * -that\", // binary { var{\"this\"} \"*\" unary{'-', var{\"that\"}} }\n \"this * that * there\",\n \"this * that / there\",\n \"this.inner * that * there.inner2\",\n }) //\n {\n std::cout << \"===== \" << quoted(input) << \"\\n\";\n auto f = input.begin(), l = input.end();\n\n // Our error handler\n auto const p = x3::with<parser::eh_tag>(\n x3::error_handler{f, l, std::cerr})[hlsl::parser::program];\n\n if (hlsl::ast::Expr fs; parse(f, l, p, fs))\n {\n fs.apply_visitor(hlsl::printer{std::cout << \"Parsed: \"});\n std::cout << \"\\n\";\n }\n else\n {\n std::cout << \"Parse failed at \" << quoted(std::string(f, l)) << \"\\n\";\n }\n }\n}\n"
},
{
"answer_id": 74649053,
"author": "sehe",
"author_id": 85371,
"author_profile": "https://Stackoverflow.com/users/85371",
"pm_score": 0,
"selected": false,
"text": "namespace Ast {\n //////////////////\n // primitive types\n struct Nil { };\n struct Identifier : std::string { using std::string::string; };\n struct String : std::string { using std::string::string; };\n\n enum class Bool { False, True };\n using Number = boost::multiprecision::cpp_dec_float_50;\n\n //////////////////\n // expressions\n enum class Op {\n Plus, Minus, Multiply, Divide,\n Equal, NotEqual, NOT, OR, AND,\n GT, GTE, LT, LTE,\n Assign\n };\n\n#define FWD(T) boost::recursive_wrapper<struct T>\n using boost::optional;\n using boost::blank; // std::monostate\n using boost::variant;\n\n using Expression = variant< //\n Nil, Bool, Number, Identifier, String, //\n FWD(FunctionCall), //\n FWD(MemberAccess), //\n FWD(Unary), //\n FWD(Binary) //\n >;\n\n using Parameters = std::vector<Identifier>;\n using Arguments = std::vector<Expression>;\n\n struct FunctionCall { Expression fun; Arguments args; };\n struct MemberAccess { Expression obj; Identifier mem; };\n struct Unary { Op op; Expression oper; };\n struct Binary { Op op; Expression lhs, rhs; };\n\n //////////////////\n // Declarations\n struct PrintStmt { Expression value; };\n struct ReturnStmt { optional<Expression> value; };\n\n using Statement = variant< //\n Expression, PrintStmt, ReturnStmt,\n FWD(ForStmt), //\n FWD(IfStmt), //\n FWD(WhileStmt), //\n FWD(Block) //\n >;\n using Statements = std::vector<Statement>;\n\n struct VarDecl {\n Identifier id;\n optional<Expression> init;\n };\n\n struct ForStmt {\n variant<blank, VarDecl, Expression> init;\n optional<Expression> cond, incr;\n optional<Statement> body;\n };\n\n struct IfStmt {\n Expression cond;\n Statement branch1;\n optional<Statement> branch2;\n };\n\n struct WhileStmt { // REVIEW might represent as ForStmt\n Expression cond;\n Statement body;\n };\n\n struct Block {\n Statements stmts;\n };\n\n //////////////////\n // Declarations\n struct FunDecl {\n Identifier id;\n Parameters params;\n Block body;\n };\n\n struct ClassDecl {\n Identifier id;\n optional<Identifier> super;\n std::vector<FunDecl> funcs;\n };\n\n using Declaration = boost::variant<ClassDecl, FunDecl, VarDecl, Statement>;\n using Declarations = std::vector<Declaration>;\n using Program = Declarations;\n} // namespace Ast\n Block Declaration Statement BOOST_FUSION_ADAPT_STRUCT(Ast::PrintStmt, value)\nBOOST_FUSION_ADAPT_STRUCT(Ast::ReturnStmt, value)\nBOOST_FUSION_ADAPT_STRUCT(Ast::ForStmt, init, cond, incr, body)\nBOOST_FUSION_ADAPT_STRUCT(Ast::IfStmt, cond, branch1, branch2)\nBOOST_FUSION_ADAPT_STRUCT(Ast::WhileStmt, cond, body)\nBOOST_FUSION_ADAPT_STRUCT(Ast::Block, stmts)\nBOOST_FUSION_ADAPT_STRUCT(Ast::FunDecl, id, params, body)\nBOOST_FUSION_ADAPT_STRUCT(Ast::ClassDecl, id, super, funcs)\nBOOST_FUSION_ADAPT_STRUCT(Ast::VarDecl, id, init)\n\n// These are not required because they're constructed from semantic actions\n//BOOST_FUSION_ADAPT_STRUCT(Ast::Unary, op, oper)\n//BOOST_FUSION_ADAPT_STRUCT(Ast::Binary, lhs, rhs)\n//BOOST_FUSION_ADAPT_STRUCT(Ast::FunctionCall, fun, args)\n//BOOST_FUSION_ADAPT_STRUCT(Ast::MemberAccess, obj, mem)\n x3::rule<struct declaration, Ast::Declaration> declaration {\"declaration\"};\nx3::rule<struct statement, Ast::Statement> statement {\"statement\"};\nx3::rule<struct expression, Ast::Expression> expression {\"expression\"};\nx3::rule<struct call, Ast::Expression> call {\"call\"};\n x3::rule<struct unary, Ast::Expression> unary {\"unary\"};\nx3::rule<struct factor, Ast::Expression> factor {\"factor\"};\nx3::rule<struct term, Ast::Expression> term {\"term\"};\nx3::rule<struct comparison, Ast::Expression> comparison {\"comparison\"};\nx3::rule<struct equality, Ast::Expression> equality {\"equality\"};\nx3::rule<struct logic_and, Ast::Expression> logic_and {\"logic_and\"};\nx3::rule<struct logic_or, Ast::Expression> logic_or {\"logic_or\"};\nx3::rule<struct assignment, Ast::Expression> assignment {\"assignment\"};\n auto number = AST(Number,\n x3::raw[x3::lexeme[ //\n +x3::digit >> -(\".\" >> +x3::digit) //\n ]][to_number]);\nauto alpha = x3::char_(\"a-zA-Z_\");\nauto alnum = x3::char_(\"a-zA-Z_0-9\");\nauto identifier = AST(Identifier, x3::lexeme[alpha >> *alnum]);\nauto string = AST(String, x3::lexeme['\"' >> *~x3::char_('\"') >> '\"']);\n AST(T, p) auto to_number = [](auto& ctx) {\n auto& raw = _attr(ctx);\n _val(ctx) = Ast::Number{std::string(raw.begin(), raw.end())};\n};\n def for_each(container, action) {\n for (var i = 0; i < = container.size(); ++i) {\n action(container.item(i));\n }\n }\n for_each for // keyword checking\n#if CASE_SENSITIVE\n auto cs(auto p) { return p; };\n#else\n auto cs(auto p) { return x3::no_case[p]; };\n#endif\n auto kw(auto... p) { return x3::lexeme[(cs(p) | ...) >> !alnum]; }\n kw(\"for\") \"for\" (return)(\"key\").index return return (\"key\") \"key\" // utility\nauto bool_ = [] {\n x3::symbols<Ast::Bool> sym;\n sym.add(\"true\", Ast::Bool::True);\n sym.add(\"false\", Ast::Bool::False);\n return kw(sym);\n}();\n// Not specified, use `non_reserved = identifier` to allow those\nauto reserved = kw(\"return\", bool_, \"nil\", \"fun\", \"var\", \"class\");\nauto non_reserved = !reserved >> identifier;\n at<T>(p) template <typename T> auto as(auto p, char const* name) {\n return x3::rule<struct _, T>{name} = std::move(p);\n};\ntemplate <typename T> auto as(auto p) {\n static auto const name = boost::core::demangle(typeid(T).name());\n return as<T>(std::move(p), name.c_str());\n};\n #define AST(T, p) as<Ast::T>(p, #T)\n auto parameters = AST(Parameters, -(non_reserved % \",\"));\nauto block = AST(Block,\"{\" >> *statement >> \"}\");\nauto function = AST(FunDecl, non_reserved >> \"(\" >> parameters >> \")\" >> block);\n // declarations\nauto classDecl = AST(ClassDecl, //\n kw(\"class\") >> non_reserved >> -(\"<\" >> non_reserved) >> //\n \"{\" >> *function >> \"}\" //\n);\nauto funDecl = kw(\"fun\") >> function;\nauto varDecl = kw(\"var\") >> AST(VarDecl, non_reserved >> -(\"=\" >> expression) >> \";\");\n\nauto declaration_def = AST(Declaration, classDecl | funDecl | varDecl | statement);\nauto program = x3::skip(skipper)[AST(Program, *(!x3::eoi >> declaration)) >> x3::eoi];\n auto comment //\n = (\"//\" > *(x3::char_ - x3::eol) > (x3::eoi | x3::eol)) //\n | (\"/*\" > *(x3::char_ - \"*/\") > \"*/\") //\n ; //\n\nauto skipper = x3::space | comment;\n kw(...) AST(T, p) // statements\nauto exprStmt = AST(Expression, expression >> \";\");\nauto forStmt = AST(ForStmt, //\n kw(\"for\") >> \"(\" >> //\n (varDecl | exprStmt | \";\") >> //\n -expression >> \";\" >> //\n -expression >> \")\" >> statement);\nauto ifStmt = AST(IfStmt, //\n kw(\"if\") >> (\"(\" >> expression >> \")\") >> statement >>\n -(kw(\"else\") >> statement));\n\nauto printStmt = AST(PrintStmt, kw(\"print\") >> expression >> \";\");\nauto returnStmt = AST(ReturnStmt, kw(\"return\") >> -expression >> \";\");\nauto whileStmt = AST(WhileStmt, kw(\"while\") >> \"(\" >> expression >> \")\" >> statement);\nauto statement_def = AST(Statement, !(x3::eoi | \"}\") //\n >> (forStmt | ifStmt | printStmt | returnStmt |\n whileStmt | block | exprStmt));\n auto opsym = [] {\n x3::symbols<Ast::Op> sym;\n sym.add //\n (\"+\", Ast::Op::Plus)(\"-\", Ast::Op::Minus) //\n (\"*\", Ast::Op::Multiply)(\"/\", Ast::Op::Divide) //\n (\"==\", Ast::Op::Equal)(\"!=\", Ast::Op::NotEqual) //\n (\"!\", Ast::Op::NOT)(\"or\", Ast::Op::OR)(\"and\", Ast::Op::AND) //\n (\">\", Ast::Op::GT)(\">=\", Ast::Op::GTE) //\n (\"<\", Ast::Op::LT)(\"<=\", Ast::Op::LTE) //\n (\"=\", Ast::Op::Assign);\n return as<Ast::Op>( //\n &identifier >> kw(sym) // if named operator, require keyword boundary\n | sym,\n \"opsym\");\n}();\n kw() andalucia orlando &identifier auto nil = AST(Nil, kw(\"nil\"));\nauto arguments = AST(Arguments, &x3::lit(\")\") | expression % \",\");\n\n// this and super are just builtin identifiers\nauto primary = AST(Expression,\n bool_ | nil | number | string | non_reserved | \"(\" >> expression >> \")\");\n \"this\" \"super\" auto this_ = AST(Identifier, kw(x3::string(\"this\")));\nauto super_ = AST(Identifier, kw(x3::string(\"super\")));\n auto assign = [](auto& ctx) {\n _val(ctx) = _attr(ctx);\n};\nauto mk_call = [](auto& ctx) {\n Ast::Expression expr = _val(ctx);\n Ast::Arguments args = _attr(ctx);\n _val(ctx) = Ast::FunctionCall{expr, args};\n};\nauto mk_member = [](auto& ctx) {\n Ast::Expression obj = _val(ctx);\n Ast::Identifier mem = _attr(ctx);\n _val(ctx) = Ast::MemberAccess{obj, mem};\n};\nauto mk_unary = [](auto& ctx) {\n auto& op = at_c<0>(_attr(ctx));\n auto& rhs = at_c<1>(_attr(ctx));\n _val(ctx) = Ast::Unary{op, rhs};\n};\nauto mk_binary = [](auto& ctx) {\n auto& attr = _attr(ctx);\n auto& op = at_c<0>(attr);\n auto& rhs = at_c<1>(attr);\n _val(ctx) = Ast::Binary{op, _val(ctx), rhs};\n};\n auto call_def = primary[assign] >> //\n *((\"(\" >> arguments >> \")\")[mk_call] //\n | \".\" >> non_reserved[mk_member] //\n );\nauto unary_def = (expect_op(\"!\", \"-\") >> unary)[mk_unary] | call[assign];\nauto assignment_def = //\n (call[assign] >> (expect_op(\"=\") >> assignment)[mk_binary]) | //\n logic_or[assign];\n auto logic_or_def = logic_and[assign] >> *(&kw(\"or\") >> opsym >> logic_and)[mk_binary];\n auto binary_def = [](auto precedent, auto... ops) {\n return precedent[assign] >> *(expect_op(ops...) >> precedent)[mk_binary];\n};\n expect_op auto expect_op(auto... ops) {\n return &x3::lexeme[\n // keyword operator?\n (&identifier >> kw((x3::as_parser(ops) | ...))) |\n // interpunction operator\n ((x3::as_parser(ops) | ...) >> !x3::char_(\"!=><)\"))] >>\n opsym;\n};\n assignment auto factor_def = binary_def(unary, \"/\", \"*\");\nauto term_def = binary_def(factor, \"-\", \"+\");\nauto comparison_def = binary_def(term, \">\", \">=\", \"<\", \"<=\");\nauto equality_def = binary_def(comparison, \"!=\", \"==\");\nauto logic_and_def = binary_def(equality, \"and\");\nauto logic_or_def = binary_def(logic_and, \"or\");\n auto expression_def = assignment;\n\nBOOST_SPIRIT_DEFINE(declaration, statement, expression);\nBOOST_SPIRIT_DEFINE(call, unary, factor, term, comparison, equality, logic_and,\n logic_or, assignment);\n int main() {\n#ifdef COLIRU\n std::string input(std::istreambuf_iterator<char>(std::cin), {});\n#else\n std::string_view input = R\"~(\n class Cat < Animal {\n Cat(name) {\n print format(\"maybe implement member data some day: {}\\n\", name);\n }\n\n bark(volume) {\n for (dummy = Nil; volume>0; volume = volume - 1)\n print \"bark!\";\n\n if (dummy or !(dummy == Nil) and universe_sane()) {\n while(dummy) {{ print \"(just kidding)\"; }}\n } else if (nesting() == \"the shit\") {\n print(\"cool beans\"); // extra parentheses are fine\n return(True != False); // also on return statements\n } else brackets = !\"required\";\n\n return False;\n }\n\n bite() { return \"pain takes no arguments\"; }\n }\n\n var pooky = Cat(\"Pooky\");\n pooky.bark(10);\n pooky = nil; // pooky got offed for being obnoxious :(\n)~\";\n#endif\n {\n if (Ast::Program parsed;\n parse(begin(input), end(input), Grammar::program, parsed))\n std::cout << parsed << \"\\n\";\n else\n std::cout << \"Failed\\n\";\n }\n}\n class `Cat` < `Animal`{\n [fun] `Cat`(`name`) {\n print (`format`(\"maybe implement member data some day: {}\\\\n\",`name`));\n}\n\n [fun] `bark`(`volume`) {\n for((`dummy` = Nil); (`volume` > 0); (`volume` = (`volume` - 1)))\n print \"bark!\";\n if((`dummy` or ((! (`dummy` == Nil)) and (`universe_sane`())))) {\n while(`dummy`)\n{\n {\n print \"(just kidding)\";\n}\n\n}\n\n}\n else if(((`nesting`()) == \"the shit\")) {\n print \"cool beans\";\n return (True != False);\n}\n else (`brackets` = (! \"required\"))\n return False;\n}\n\n [fun] `bite`() {\n return \"pain takes no arguments\";\n}\n\n}\n\nvar `pooky` = (`Cat`(\"Pooky\"));\n((`pooky`.`bark`(10))\n(`pooky` = Nil)\n at_c<N> x = y + (2);"
},
{
"answer_id": 74653958,
"author": "Daniel Dokipen Elliott",
"author_id": 2089130,
"author_profile": "https://Stackoverflow.com/users/2089130",
"pm_score": 0,
"selected": false,
"text": "#include <boost/fusion/adapted.hpp>\n#include <boost/spirit/home/x3.hpp>\n#include <boost/spirit/home/x3/support/ast/variant.hpp>\n#include <boost/spirit/home/x3/support/utility/error_reporting.hpp>\n#include <iomanip>\n#include <iostream>\n\nnamespace x3 = boost::spirit::x3;\n\nnamespace hlsl\n{\n namespace ast\n {\n struct Void\n {\n };\n struct Get;\n struct Set;\n struct Call;\n struct Assign;\n struct CompoundAssign;\n struct Divide;\n struct Multiply;\n struct Unary;\n struct Binary;\n struct Logical;\n struct Bitwise;\n struct Ternary;\n\n struct Variable\n {\n std::string name;\n // operator std::string() const {\n // return name;\n // }\n };\n\n using Expr = x3::variant< Void, \n x3::forward_ast<Get>, \n x3::forward_ast<Set>, \n Variable, \n x3::forward_ast<Call>, \n x3::forward_ast<Assign>, \n x3::forward_ast<CompoundAssign>, \n x3::forward_ast<Multiply>, \n x3::forward_ast<Binary>, \n x3::forward_ast<Logical>, \n x3::forward_ast<Ternary>,\n x3::forward_ast<Bitwise>, \n x3::forward_ast<Divide>, \n x3::forward_ast<Unary>>;\n\n struct Call\n {\n Expr name;\n std::vector<Expr> arguments_;\n };\n\n struct Get\n {\n Expr object_;\n std::string property_;\n };\n\n struct Set\n {\n Expr object_;\n Expr value_;\n std::string name_;\n };\n struct Assign\n {\n std::string name_;\n Expr value_;\n };\n\n struct CompoundAssign\n {\n std::string name_;\n std::string op_;\n Expr value_;\n };\n\n struct Multiply\n {\n Expr left_;\n Expr right_;\n };\n\n struct Binary\n {\n Expr left_;\n std::string op_;\n Expr right_;\n };\n\n struct Logical\n {\n Expr left_;\n std::string op_;\n Expr right_;\n };\n\n struct Bitwise\n {\n Expr left_;\n std::string op_;\n Expr right_;\n };\n\n struct Divide\n {\n Expr left_;\n Expr right_;\n };\n\n struct Unary\n {\n std::string op_;\n Expr expr_;\n };\n\n struct Ternary\n {\n Expr condition_;\n Expr ifexpr_;\n Expr elseexpr_;\n };\n } // namespace ast\n\n struct printer\n {\n std::ostream &_os;\n using result_type = void;\n\n void operator()(hlsl::ast::Get const &get) const\n {\n _os << \"get { object_:\";\n get.object_.apply_visitor(*this);\n _os << \", property_:\" << quoted(get.property_) << \" }\";\n }\n\n void operator()(hlsl::ast::Set const &set) const\n {\n _os << \"set { object_:\";\n set.object_.apply_visitor(*this);\n _os << \", name_:\" << quoted(set.name_);\n _os << \" equals: \";\n set.value_.apply_visitor(*this);\n _os << \" }\";\n }\n\n void operator()(hlsl::ast::Assign const &assign) const\n {\n _os << \"assign { \";\n _os << \"name_:\" << quoted(assign.name_);\n _os << \", value_:\";\n assign.value_.apply_visitor(*this);\n _os << \" }\";\n }\n\n void operator()(hlsl::ast::CompoundAssign const &assign) const\n {\n _os << \"compoundAssign { \";\n _os << \"name_:\" << quoted(assign.name_);\n _os << \"op_:\" << quoted(assign.op_);\n _os << \", value_:\";\n assign.value_.apply_visitor(*this);\n _os << \" }\";\n }\n\n void operator()(hlsl::ast::Variable const &var) const\n {\n _os << \"var{\" << quoted(var.name) << \"}\";\n };\n void operator()(hlsl::ast::Divide const &bin) const\n {\n _os << \"divide { \";\n bin.left_.apply_visitor(*this);\n bin.right_.apply_visitor(*this);\n _os << \" }\";\n };\n void operator()(hlsl::ast::Multiply const &bin) const\n {\n _os << \"multiply { \";\n bin.left_.apply_visitor(*this);\n bin.right_.apply_visitor(*this);\n _os << \" }\";\n };\n\n void operator()(hlsl::ast::Binary const &bin) const\n {\n _os << \"binary { \";\n bin.left_.apply_visitor(*this);\n _os << bin.op_ << \", \";\n bin.right_.apply_visitor(*this);\n _os << \" }\";\n };\n\n void operator()(hlsl::ast::Logical const &bin) const\n {\n _os << \"logical { \";\n bin.left_.apply_visitor(*this);\n _os << bin.op_ << \", \";\n bin.right_.apply_visitor(*this);\n _os << \" }\";\n };\n\n void operator()(hlsl::ast::Bitwise const &bin) const\n {\n _os << \"bitwise { \";\n bin.left_.apply_visitor(*this);\n _os << bin.op_ << \", \";\n bin.right_.apply_visitor(*this);\n _os << \" }\";\n };\n\n void operator()(hlsl::ast::Unary const &un) const\n {\n _os << \"unary { \";\n un.expr_.apply_visitor(*this);\n _os << quoted(un.op_);\n _os << \" }\";\n };\n\n void operator()(hlsl::ast::Ternary const &tern) const\n {\n _os << \"ternary { \";\n tern.condition_.apply_visitor(*this);\n tern.ifexpr_.apply_visitor(*this);\n tern.elseexpr_.apply_visitor(*this);\n _os << \" }\";\n };\n void operator()(hlsl::ast::Call const &call) const\n {\n _os << \"call{\";\n call.name.apply_visitor(*this);\n _os << \", args: \";\n\n for (auto &arg : call.arguments_)\n {\n arg.apply_visitor(*this);\n _os << \", \";\n }\n _os << /*quoted(call.name) << */ \"}\";\n };\n void operator()(hlsl::ast::Void const &) const { _os << \"void{}\"; };\n };\n\n} // namespace hlsl\n\nBOOST_FUSION_ADAPT_STRUCT(hlsl::ast::Variable, name)\nBOOST_FUSION_ADAPT_STRUCT(hlsl::ast::Call, name, arguments_)\nBOOST_FUSION_ADAPT_STRUCT(hlsl::ast::Get, object_, property_)\nBOOST_FUSION_ADAPT_STRUCT(hlsl::ast::Set, object_, value_)\nBOOST_FUSION_ADAPT_STRUCT(hlsl::ast::Assign, name_, value_)\nBOOST_FUSION_ADAPT_STRUCT(hlsl::ast::CompoundAssign, name_, op_, value_)\nBOOST_FUSION_ADAPT_STRUCT(hlsl::ast::Multiply, left_, right_)\nBOOST_FUSION_ADAPT_STRUCT(hlsl::ast::Binary, left_, op_, right_)\nBOOST_FUSION_ADAPT_STRUCT(hlsl::ast::Logical, left_, op_, right_)\nBOOST_FUSION_ADAPT_STRUCT(hlsl::ast::Bitwise, left_, op_, right_)\nBOOST_FUSION_ADAPT_STRUCT(hlsl::ast::Divide, left_, right_)\nBOOST_FUSION_ADAPT_STRUCT(hlsl::ast::Unary, op_, expr_)\nBOOST_FUSION_ADAPT_STRUCT(hlsl::ast::Ternary, condition_, ifexpr_, elseexpr_)\n\n\nnamespace hlsl::parser\n{\n struct eh_tag;\n\n struct error_handler\n {\n template <typename It, typename Exc, typename Ctx>\n auto on_error(It &, It, Exc const &x, Ctx const &context) const\n {\n x3::get<eh_tag>(context)( //\n x.where(), \"Error! Expecting: \" + x.which() + \" here:\");\n\n return x3::error_handler_result::fail;\n }\n };\n\n struct program_ : error_handler\n {\n };\n\n x3::rule<struct identifier_, std::string> const identifier{\"identifier\"};\n x3::rule<struct factor_, std::string> const factor{\"factor\"};\n x3::rule<struct term_, std::string> const term{\"term\"};\n x3::rule<struct compare_op_, std::string> const compare_op{\"compare_op\"};\n x3::rule<struct equality_op_, std::string> const equality_op{\"equality_op\"};\n x3::rule<struct compoundassign_op_, std::string> const compoundassign_op{\"compoundassign_op\"};\n x3::rule<struct bitwise_shift_op_, std::string> const bitwise_shift_op{\"bitwise_shift_op\"};\n\n\n x3::rule<struct variable_, ast::Variable> const variable{\"variable\"};\n x3::rule<struct arguments_, std::vector<ast::Expr>> const arguments{\"arguments_\"};\n\n x3::rule<struct bitwise_or_, hlsl::ast::Expr> const bitwise_or{\"bitwise_or\"};\n x3::rule<struct bitwise_xor_, hlsl::ast::Expr> const bitwise_xor{\"bitwise_xor\"};\n x3::rule<struct bitwise_and_, hlsl::ast::Expr> const bitwise_and{\"bitwise_and\"};\n x3::rule<struct bitwise_shift_, hlsl::ast::Expr> const bitwise_shift{\"bitwise_shift\"};\n\n\n x3::rule<struct addition_, hlsl::ast::Expr> const addition{\"addition\"};\n x3::rule<struct comparison_, hlsl::ast::Expr> const comparison{\"comparison\"};\n x3::rule<struct equality_, hlsl::ast::Expr> const equality{\"equality\"};\n x3::rule<struct logical_or_, hlsl::ast::Expr> const logical_or{\"logical_or\"};\n x3::rule<struct logical_and_, hlsl::ast::Expr> const logical_and{\"logical_and\"};\n\n x3::rule<struct multiply_, hlsl::ast::Expr> const multiply{\"multiply\"};\n x3::rule<struct unary_, hlsl::ast::Unary> const unary{\"unary\"};\n x3::rule<struct unarycallwrapper_, hlsl::ast::Expr> const unarycallwrapper{\"unarycallwrapper\"};\n x3::rule<struct get_, ast::Expr> const get{\"get\"};\n x3::rule<struct call_, ast::Expr> const call{\"call\"};\n x3::rule<struct program_, ast::Expr> const program{\"program\"};\n x3::rule<struct primary_, ast::Expr> const primary{\"primary\"};\n x3::rule<struct expression_, ast::Expr> const expression{\"expression\"};\n x3::rule<struct set_, ast::Set, true> const set{\"set\"};\n x3::rule<struct assign_, ast::Assign> const assign{\"assign\"};\n x3::rule<struct compoundassign_, ast::CompoundAssign> const compoundassign{\"compoundassign\"};\n x3::rule<struct ternary_, ast::Expr> const ternary{\"ternary\"};\n\n\n x3::rule<struct assignment_, ast::Expr> const assignment{\"assignment\"};\n\n auto get_string_from_variable = [](auto &ctx)\n { _val(ctx).name_ = std::move(_attr(ctx).name); };\n\n auto get_string_from_variable_cast = [](auto &ctx)\n { _val(ctx).name_ = std::move(_attr(ctx).name); };\n\n auto fix_assignExpr = [](auto &ctx)\n { _val(ctx).value_ = std::move(_attr(ctx)); };\n\n auto as_expr = [](auto &ctx)\n { _val(ctx) = ast::Expr(std::move(_attr(ctx))); };\n\n auto as_unary = [](auto &ctx)\n { _val(ctx) = ast::Unary(std::move(_attr(ctx))); };\n\n auto as_call = [](auto &ctx)\n { _val(ctx) = ast::Call{std::move(_val(ctx)), std::move(_attr(ctx))}; };\n\n auto as_binary_op = [](auto &ctx)\n { _val(ctx) = ast::Binary{std::move(_val(ctx)), std::move(_attr(ctx)), ast::Expr{}}; };\n\n auto as_binary_wrap = [](auto &ctx)\n { boost::get<x3::forward_ast<ast::Binary>>(_val(ctx)).get().right_ = std::move(_attr(ctx)); };\n\n auto as_logical_op = [](auto &ctx)\n { _val(ctx) = ast::Logical{std::move(_val(ctx)), std::move(_attr(ctx)), ast::Expr{}}; };\n\n auto as_logical_wrap = [](auto &ctx)\n { boost::get<x3::forward_ast<ast::Logical>>(_val(ctx)).get().right_ = std::move(_attr(ctx)); };\n\n auto as_bitwise_op = [](auto &ctx)\n { _val(ctx) = ast::Bitwise{std::move(_val(ctx)), std::move(_attr(ctx)), ast::Expr{}}; };\n\n auto as_bitwise_wrap = [](auto &ctx)\n { boost::get<x3::forward_ast<ast::Bitwise>>(_val(ctx)).get().right_ = std::move(_attr(ctx)); };\n\n auto as_compound_op = [](auto &ctx)\n { _val(ctx).op_ = std::move(_attr(ctx)); };\n\n auto as_ternary_ifexpr = [](auto &ctx)\n { _val(ctx) = ast::Ternary{std::move(_val(ctx)), std::move(_attr(ctx)), ast::Expr{}}; };\n\n auto as_ternary_elseexpr = [](auto &ctx)\n { boost::get<x3::forward_ast<ast::Ternary>>(_val(ctx)).get().elseexpr_ = std::move(_attr(ctx)); };\n\n auto as_compound_wrap = [](auto &ctx)\n { boost::get<x3::forward_ast<ast::CompoundAssign>>(_val(ctx)).get().value_ = std::move(_attr(ctx)); };\n\n auto fold_in_get_to_set = [](auto &ctx)\n {\n auto &val = x3::_val(ctx);\n val.name_ = boost::get<x3::forward_ast<ast::Get>>(val.object_).get().property_;\n val.object_ = ast::Expr(boost::get<x3::forward_ast<ast::Get>>(val.object_).get().object_);\n };\n\n auto as_string = [](auto &ctx)\n { _val(ctx) = std::move(_attr(ctx).name); };\n auto as_assign = [](auto &ctx)\n { _val(ctx) = ast::Assign(std::move(_val(ctx)), std::move(_attr(ctx))); };\n auto as_get = [](auto &ctx)\n {\n _val(ctx) = ast::Get{std::move(_val(ctx)), _attr(ctx)};\n };\n\n\n auto expression_def = assignment;\n\n auto variable_def = identifier;\n auto identifier_def = x3::lexeme[x3::alpha >> *x3::alnum];\n auto set_def = (get >> '=' >> assignment)[fold_in_get_to_set];\n\n auto arguments_def = *(expression % ',');\n \n\n \n auto factor_def = x3::string(\"*\") | x3::string(\"/\");\n auto term_def = x3::string(\"+\") | x3::string(\"-\");\n auto compare_op_def = x3::string(\"<=\") | x3::string(\">=\") | x3::string(\"<\") | x3::string(\">\");\n auto equality_op_def = x3::string(\"!=\") | x3::string(\"==\");\n auto compoundassign_op_def = x3::string(\"*=\") | x3::string(\"/=\") | x3::string(\"%=\") | x3::string(\"+=\") \n | x3::string(\"-=\") | x3::string(\"<<=\") | x3::string(\">>=\") \n | x3::string(\"&=\") | x3::string(\"^=\") | x3::string(\"|=\");\n\n auto bitwise_shift_op_def = x3::string(\">>\") | x3::string(\"<<\");\n\n //auto binary_def = unarycallwrapper[as_expr] >> *((x3::lit('/') >> unarycallwrapper[as_divide]) | (x3::lit('*') >> unarycallwrapper[as_multiply]));\n\n auto assign_def = variable[get_string_from_variable] >> '=' >> assignment[fix_assignExpr];\n auto compoundassign_def = variable[get_string_from_variable] >> compoundassign_op[as_compound_op] >> assignment[fix_assignExpr];\n\n auto assignment_def = (assign | compoundassign | set) | ternary; \n\n auto ternary_def = logical_or[as_expr] >> *('?' >> expression[as_ternary_ifexpr] >> ':' >> ternary[as_ternary_elseexpr]);\n auto logical_or_def = logical_and[as_expr] >> *(x3::string(\"||\")[as_logical_op] >> logical_and[as_logical_wrap]);\n auto logical_and_def = bitwise_or[as_expr] >> *(x3::string(\"&&\")[as_logical_op] >> bitwise_or[as_logical_wrap]);\n auto bitwise_or_def = bitwise_xor[as_expr] >> *((x3::string(\"|\") >> !(x3::lit('|') | x3::lit('=')))[as_bitwise_op] >> bitwise_xor[as_bitwise_wrap]);\n auto bitwise_xor_def = bitwise_and[as_expr] >> *((x3::string(\"^\") > !(x3::lit('^') | x3::lit('=')))[as_bitwise_op] >> bitwise_and[as_bitwise_wrap]);\n auto bitwise_and_def = equality[as_expr] >> *((x3::string(\"&\") >> !(x3::lit('&') | x3::lit('=')))[as_bitwise_op] >> equality[as_bitwise_wrap]);\n auto equality_def = comparison[as_expr] >> *(equality_op[as_binary_op] >> comparison[as_binary_wrap]);\n auto comparison_def = bitwise_shift[as_expr] >> *(compare_op[as_binary_op] >> bitwise_shift[as_binary_wrap]);\n auto bitwise_shift_def = addition[as_expr] >> *(bitwise_shift_op[as_binary_op] >> addition[as_binary_wrap]);\n auto addition_def = multiply[as_expr] >> *(term[as_binary_op] >> multiply[as_binary_wrap]);\n auto multiply_def = unarycallwrapper[as_expr] >> *(factor[as_binary_op] >> unarycallwrapper[as_binary_wrap]);\n auto unarycallwrapper_def = unary | call;\n auto unary_def = (x3::string(\"-\") >> unarycallwrapper);\n auto get_def = primary[as_expr] >> *('.' >> identifier)[as_get];\n auto call_def = primary[as_expr] >> *((x3::lit('(') >> arguments >> x3::lit(')'))[as_call] | ('.' >> identifier)[as_get]);\n\n auto primary_def = variable;\n\n auto program_def = x3::skip(x3::space)[expression];\n\n BOOST_SPIRIT_DEFINE(primary, assign, \n compoundassign, compoundassign_op, bitwise_or, bitwise_xor,\n ternary,\n bitwise_and, bitwise_shift, bitwise_shift_op,\n logical_and, logical_or, equality_op, \n equality, factor, compare_op, comparison, \n term, addition, multiply, unary, unarycallwrapper,\n assignment, get, set, variable, arguments, expression, call, identifier, program);\n\n} // namespace hlsl::parser\n\nint main()\n{\n using namespace hlsl;\n\n for (std::string const input :\n {\n \"first\",\n \"first.second\",\n \"first.Second.third\",\n \"first.Second().third\",\n \"first.Second(arg1).third\",\n \"first.Second(arg1, arg2).third\",\n \"first = second\",\n \"first.second = third\",\n \"first.second.third = fourth\",\n \"first.second.third = fourth()\",\n \"first.second.third = fourth(arg1)\",\n \"this * that\", // binary { var{\"this\"} \"*\" var{\"that\"} }\n \"this * -that\", // binary { var{\"this\"} \"*\" unary{'-', var{\"that\"}} }\n \"this * that * there\",\n \"this * that / there\",\n \"this.inner * that * there.inner2\",\n \"first + second\",\n \"first + second * third\",\n \"first < second\",\n \"first <= second * third\",\n \"first - second > third\",\n \"first != second\",\n \"first == second * third\",\n \"first || second\",\n \"first || second && third\"\n \"first |= second\",\n \"first |= second.third\",\n \"first & second\",\n \"first & second && third\",\n \"first &= second && third\",\n \"first << second && third\",\n \"first ^ second\",\n \"first ^ second ^^ third\", //fails on purpose because this operator doesn't exist!\n \"zero |= first | second || third\",\n \"first ? second : third\",\n \"first > second ? third : fourth\",\n \"first > second ? third : fourth > fifth ? sixth : seventh\"\n }) //\n {\n std::cout << \"===== \" << quoted(input) << \"\\n\";\n auto f = input.begin(), l = input.end();\n\n // Our error handler\n auto const p = x3::with<parser::eh_tag>(\n x3::error_handler{f, l, std::cerr})[hlsl::parser::program];\n\n if (hlsl::ast::Expr fs; parse(f, l, p, fs))\n {\n fs.apply_visitor(hlsl::printer{std::cout << \"Parsed: \"});\n std::cout << \"\\n\";\n }\n else\n {\n std::cout << \"Parse failed at \" << quoted(std::string(f, l)) << \"\\n\";\n }\n }\n}\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2089130/"
] |
74,624,915
|
<pre><code>import { ColorModeContext, useMode } from "./theme";
import { CssBaseline, ThemeProvider } from "@mui/material";
import Topbar from "./scenes/global/Topbar";
import Sidebar from "./scenes/global/Sidebar";
function App() {
const [theme, colorMode] = useMode();
return (
<ColorModeContext.Provider value={colorMode}>
<ThemeProvider theme={theme}>
<CssBaseline/>
<div className="app">
<main className="content">
<Topbar/>
<Sidebar/>
</main>
</div>
</ThemeProvider>
</ColorModeContext.Provider>
);
}
export default App;
</code></pre>
<ul>
<li>List item
npm WARN ERESOLVE overriding peer dependency</li>
</ul>
<p>npm WARN While resolving: react-slidedown@2.4.7</p>
<p>npm WARN Found: react@18.2.0</p>
<p>npm WARN node_modules/react</p>
<p>npm WARN react@"^18.2.0" from the root project</p>
<p>npm WARN 16 more (@emotion/react, @emotion/styled, ...)</p>
<p>npm WARN</p>
<p>npm WARN Could not resolve dependency:</p>
<p>npm WARN peer react@"^16.3.0 || 17" from react-slidedown@2.4.7</p>
<p>npm WARN node_modules/react-pro-sidebar/node_modules/react-slidedown</p>
<p>npm WARN react-slidedown@"^2.4.5" from react-pro-sidebar@0.7.1</p>
<p>npm WARN node_modules/react-pro-sidebar</p>
<p>npm WARN
npm WARN Conflicting peer dependency: react@17.0.2</p>
<p>npm WARN node_modules/react</p>
<p>npm WARN peer react@"^16.3.0 || 17" from react-slidedown@2.4.7</p>
<p>npm WARN node_modules/react-pro-sidebar/node_modules/react-slidedown</p>
<p>npm WARN react-slidedown@"^2.4.5" from react-pro-sidebar@0.7.1</p>
<p>npm WARN node_modules/react-pro-sidebar</p>
<p>npm WARN ERESOLVE overriding peer dependency</p>
<p>npm WARN While resolving: react-slidedown@2.4.7</p>
<p>npm WARN Found: react-dom@18.2.0</p>
<p>npm WARN node_modules/react-dom</p>
<p>npm WARN react-dom@"^18.2.0" from the r</p>
<p>oot project
npm WARN 6 more (@mui/base, @mui/material, @testing-library/react,</p>
<p>...)
npm WARN</p>
<p>npm WARN Could not resolve dependency:
npm WARN peer react-dom@"^16.3.0 || 17" from react-slidedown@2.4.7</p>
<p>npm WARN node_modules/react-pro-sidebar/node_modules/react-slidedown</p>
<p>npm WARN react-slidedown@"^2.4.5" from react-pro-sidebar@0.7.1</p>
<p>npm WARN node_modules/react-pro-sidebar</p>
<p>npm WARN
npm WARN Conflicting peer dependency: react-dom@17.0.2</p>
<p>npm WARN node_modules/react-dom</p>
<p>npm WARN peer react-dom@"^16.3.0 || 17" from react-slidedown@2.4.7</p>
<p>npm WARN node_modules/react-pro-sidebar/node_modules/react-slidedown</p>
<p>npm WARN react-slidedown@"^2.4.5" from react-pro-sidebar@0.7.1</p>
<p>npm WARN node_modules/react-pro-sidebar</p>
<hr />
|
[
{
"answer_id": 74624982,
"author": "Laza Nantenaina",
"author_id": 15368117,
"author_profile": "https://Stackoverflow.com/users/15368117",
"pm_score": 0,
"selected": false,
"text": "npm install npm run start"
},
{
"answer_id": 74625050,
"author": "Alex Yepes",
"author_id": 10339463,
"author_profile": "https://Stackoverflow.com/users/10339463",
"pm_score": 2,
"selected": true,
"text": ".src/ import Topbar from \"./scenes/global/Topbar\"\nimport Sidebar from \"./scenes/global/Sidear\"\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20643065/"
] |
74,624,924
|
<p>I was writing code for a program which performs intersection of elements in the two lists, which means the common elements in both the lists are returned.
changing <em>"in _list"</em> with "<em>in range (len(list))</em>" used for traversing in one of the list changed the output of the function</p>
<p>Input code 1:</p>
<pre><code>def inn(nums1,nums2):
a=set()
b={}
for i in range(len(nums2)):
b[nums2[i]]="h"
print (b)
for j in nums1: #**calling elemnts by in**
if j in b:
print(j)
a.add(j)
return a
inn([1,2,2,1],[2,2])
</code></pre>
<p>Output code 1(correct):</p>
<pre><code> {2: 'h'}
2
2
{2}
</code></pre>
<p>Input code 2:(with changed method in 2nd loop):</p>
<pre><code>def inn(nums1,nums2):
a=set()
b={}
for i in range(len(nums2)):
b[nums2[i]]="h"
print (b)
for j in range(len(nums1)): #**calling elements by range**
if nums1[j] in b:
print(nums1[j])
a.add(j)
return a
inn([1,2,2,1],[2,2])
</code></pre>
<p>output code 2(Incorrect):</p>
<pre><code> {2: 'h'}
2
2
{1, 2}
</code></pre>
|
[
{
"answer_id": 74624982,
"author": "Laza Nantenaina",
"author_id": 15368117,
"author_profile": "https://Stackoverflow.com/users/15368117",
"pm_score": 0,
"selected": false,
"text": "npm install npm run start"
},
{
"answer_id": 74625050,
"author": "Alex Yepes",
"author_id": 10339463,
"author_profile": "https://Stackoverflow.com/users/10339463",
"pm_score": 2,
"selected": true,
"text": ".src/ import Topbar from \"./scenes/global/Topbar\"\nimport Sidebar from \"./scenes/global/Sidear\"\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20615351/"
] |
74,624,937
|
<p>I have a daily scheduler to run the job on Bigquery, however, it crashed due to running out of memory usage. The job consists of the most updated information from each of the 5 tables, which means I used over( ... order by) five times to query the updated record from each table and it consumed a lot of memory usage. Is there any efficient way to fix the error by refactoring the query?</p>
<p>Here's the brief code structure:</p>
<pre><code>CREATE TEMP TABLE main_info AS
WITH orders_1 AS(
select
* except(rnk)
from(
select
*,
ROW_NUMBER() OVER(PARTITION BY order_id ORDER BY update_time DESC) AS rnk
from order_1
)
where rnk = 1
),
orders_2 AS(
select
* except(rnk)
from(
select
*,
ROW_NUMBER() OVER(PARTITION BY order_id ORDER BY update_time DESC) AS rnk
from order_2
)
where rnk = 1
),
orders_3 AS(
select
* except(rnk)
from(
select
*,
ROW_NUMBER() OVER(PARTITION BY order_id ORDER BY update_time DESC) AS rnk
from order_3
)
where rnk = 1
)
SELECT
*
FROM orders_1 o1
LEFT JOIN orders_2 o2
ON o1.order_id = o2.order_id
LEFT JOIN orders_3 o3
ON o1.order_id = o3.order_id
</code></pre>
<p>I was expecting to reduce memory usage under the limit. I did some research and found out to replace row_number() over( ... order by) with array_agg() to optimize the performance or to create the temp table for each table and combine it all? is there any better advice?</p>
|
[
{
"answer_id": 74624982,
"author": "Laza Nantenaina",
"author_id": 15368117,
"author_profile": "https://Stackoverflow.com/users/15368117",
"pm_score": 0,
"selected": false,
"text": "npm install npm run start"
},
{
"answer_id": 74625050,
"author": "Alex Yepes",
"author_id": 10339463,
"author_profile": "https://Stackoverflow.com/users/10339463",
"pm_score": 2,
"selected": true,
"text": ".src/ import Topbar from \"./scenes/global/Topbar\"\nimport Sidebar from \"./scenes/global/Sidear\"\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20163278/"
] |
74,624,944
|
<p>I use a base class (A) that manages some data but without having the storage. The derived class (B) has a storage member and initializes the base class (A) with a pointer to that storage and the size of them.</p>
<p>The code model (clang) in the IDE gives me a warning "Field mStorage is uninitialized when used here" at line
<code>explicit B() : A(mStorage.data(), 10) {}</code></p>
<p>Question 1: Is this a problem as long as I do not use the storage in the base class constructor?</p>
<p>Question 2: If this doesn't cause a problem, is there a way to avoid this warning?</p>
<pre><code>class A
{
public:
explicit A(int* p, size_t s)
: mPtr(p), mSize(s)
{}
void append(int i) { /* ... */ }
private:
int* mPtr = nullptr;
size_t mSize = 0;
};
template <size_t N>
class B : public A
{
public:
explicit B() : A(mStorage.data(), N) {}
private:
std::array<int, N> mStorage {};
};
</code></pre>
<p>Update:</p>
<ul>
<li>add template <size_t N> to class B</li>
<li>My intension is to decouple the normal usage of the class and the template size in class B</li>
</ul>
<pre><code>void worker_function(const A& a)
{
a.append(int(1));
}
// and also
struct Foo
{
Foo(const A& a) : m_a(a) {}
void do_some_work()
{
a.append(int(1));
}
const A& m_a;
};
void main()
{
B<10> b;
worker_function(b);
// and also
Foo foo(b);
foo.do_some_work();
}
</code></pre>
|
[
{
"answer_id": 74624982,
"author": "Laza Nantenaina",
"author_id": 15368117,
"author_profile": "https://Stackoverflow.com/users/15368117",
"pm_score": 0,
"selected": false,
"text": "npm install npm run start"
},
{
"answer_id": 74625050,
"author": "Alex Yepes",
"author_id": 10339463,
"author_profile": "https://Stackoverflow.com/users/10339463",
"pm_score": 2,
"selected": true,
"text": ".src/ import Topbar from \"./scenes/global/Topbar\"\nimport Sidebar from \"./scenes/global/Sidear\"\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7576025/"
] |
74,624,957
|
<blockquote>
<p>docker run -d --name=grafana -p 3000:3000 grafana/grafana-enterprise:9.2.0 Unable to find image 'grafana/grafana-enterprise:9.2.0' locally docker: Error response from daemon: Get "https://registry-1.docker.io/v2/": proxyconnect tcp: dial tcp 192.168.65.1:3128: connect: connection refused.</p>
</blockquote>
<p>How to solve this? <a href="https://registry-1.docker.io/v2/" rel="nofollow noreferrer">https://registry-1.docker.io/v2/</a> the image when tried to access from browser</p>
<p><a href="https://i.stack.imgur.com/T3CQq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/T3CQq.png" alt="enter image description here" /></a></p>
<p>I was trying to implement Grafana in Docker by following <a href="https://grafana.com/docs/grafana/latest/setup-grafana/installation/docker/" rel="nofollow noreferrer">this</a>.</p>
|
[
{
"answer_id": 74624982,
"author": "Laza Nantenaina",
"author_id": 15368117,
"author_profile": "https://Stackoverflow.com/users/15368117",
"pm_score": 0,
"selected": false,
"text": "npm install npm run start"
},
{
"answer_id": 74625050,
"author": "Alex Yepes",
"author_id": 10339463,
"author_profile": "https://Stackoverflow.com/users/10339463",
"pm_score": 2,
"selected": true,
"text": ".src/ import Topbar from \"./scenes/global/Topbar\"\nimport Sidebar from \"./scenes/global/Sidear\"\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18443839/"
] |
74,624,974
|
<p>I have been trying to run the code but its giving error that - "list index out of range"</p>
<p>What is the reason?
And is there any other way to find the transpose of a matrix without using numpy</p>
<p>This is the code I wrote</p>
<pre><code>
n = int(input("Enter the size of square matrix"))
matrix = []
for i in range(n):
a =[]
for j in range(n):
a.append(int(input("Enter the entries rowwise:")))
matrix.append(a)
matrix1 = []
for i in range(0,n):
b = []
for j in range(0,n):
matrix1[i][j] = matrix[j][i]
for i in range(n):
for j in range(n):
print(matrix1[i][j], end = " ")
print()
</code></pre>
<p>What is the reason for the error in the line <code>matrix1[i][j] = matrix[j][i]</code>?
And is there any other way to find the transpose of a matrix without using numpy</p>
|
[
{
"answer_id": 74625075,
"author": "Orfeas Bourchas",
"author_id": 16781682,
"author_profile": "https://Stackoverflow.com/users/16781682",
"pm_score": 3,
"selected": true,
"text": "matrix1 matrix1 n = int(input(\"Enter the size of square matrix\"))\nmatrix = []\nfor i in range(n): \n a =[]\n for j in range(n): \n a.append(int(input(\"Enter the entries rowwise:\")))\n matrix.append(a)\nmatrix1 = []\nfor i in range(0,n):\n b = []\n for j in range(0,n):\n b.append( matrix[j][i])\n matrix1.append(b)\nfor i in range(n):\n for j in range(n):\n print(matrix1[i][j], end = \" \")\nprint()\n"
},
{
"answer_id": 74625103,
"author": "Yash Mehta",
"author_id": 20172954,
"author_profile": "https://Stackoverflow.com/users/20172954",
"pm_score": 1,
"selected": false,
"text": "matrix=[[1,2,3],[4,5,6],[7,8,9]]\n#print(matrix)\nres=[]\nfor i in zip(*matrix):\n res.append(i)\nprint(res)\n [(1, 4, 7), (2, 5, 8), (3, 6, 9)]\n"
},
{
"answer_id": 74625137,
"author": "Gameplay",
"author_id": 15923186,
"author_profile": "https://Stackoverflow.com/users/15923186",
"pm_score": 1,
"selected": false,
"text": "transposed = list(zip(*matrix))\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20284879/"
] |
74,624,986
|
<p>I will try to explain my issue with simple example. Let's say I've a list</p>
<pre><code>lis = ['Elemnt-1' , 'Elemnt-2' , 'Elemnt-3' , '' , '' , 'Elemnt-6' , 'Elemnt-7']
</code></pre>
<p>How can I fill this missing values such that list will become.</p>
<pre><code>lis = ['Elemnt-1' , 'Elemnt-2' , 'Elemnt-3' , 'Elemnt-2' , 'Elemnt-3' , 'Elemnt-6' , 'Elemnt-7']
</code></pre>
<p><strong>Explination with similar animation.</strong></p>
<p><a href="https://i.stack.imgur.com/hdpe0.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hdpe0.gif" alt="enter image description here" /></a></p>
<p>I've figured out solution. Which is too inefficient for a l<strong>onger lists & when I've multiple missing values</strong>. Here is my logic</p>
<pre><code>from itertools import accumulate
lis = ['Elemnt-1' , 'Elemnt-2' , 'Elemnt-3' , '' , '' , 'Elemnt-6' , 'Elemnt-7']
odd_index = lis[::2]
even_index = lis[1::2]
odd_index = list(accumulate(odd_index,lambda x, y: x if y is '' else y))
even_index = list(accumulate(even_index,lambda x, y: x if y is '' else y))
zipper = list(sum(zip(odd_index, even_index+[0]), ())[:-1])
print(zipper)
</code></pre>
<p>Given me #</p>
<pre><code>['Elemnt-1', 'Elemnt-2', 'Elemnt-3', 'Elemnt-2', 'Elemnt-3', 'Elemnt-6', 'Elemnt-7']
</code></pre>
<p>I was looking for a <strong>simpler elegant approach to solve this when there are multiple missing values in middle of list.</strong></p>
<p><strong>More examples:</strong></p>
<pre><code>lis = ['Elemnt-1' , 'Elemnt-2' , 'Elemnt-3' , '' , '' , '' , 'Elemnt-7']
</code></pre>
<p>Need</p>
<pre><code>lis = ['Elemnt-1' , 'Elemnt-2' , 'Elemnt-3' , 'Elemnt-1' , 'Elemnt-2' , 'Elemnt-3' , 'Elemnt-7']
</code></pre>
<p>Another example</p>
<pre><code>lis = ['Elemnt-1' , 'Elemnt-2' , 'Elemnt-3' , '' , '' , 'Elemnt-6' , 'Elemnt-7', '']
</code></pre>
<p>Need</p>
<pre><code>lis = ['Elemnt-1' , 'Elemnt-2' , 'Elemnt-3' , 'Elemnt-2' , 'Elemnt-3' , 'Elemnt-6' , 'Elemnt-7' , 'Elemnt-7']
</code></pre>
<p><strong>Logically n blank elements should be filled with n back elements</strong></p>
|
[
{
"answer_id": 74625075,
"author": "Orfeas Bourchas",
"author_id": 16781682,
"author_profile": "https://Stackoverflow.com/users/16781682",
"pm_score": 3,
"selected": true,
"text": "matrix1 matrix1 n = int(input(\"Enter the size of square matrix\"))\nmatrix = []\nfor i in range(n): \n a =[]\n for j in range(n): \n a.append(int(input(\"Enter the entries rowwise:\")))\n matrix.append(a)\nmatrix1 = []\nfor i in range(0,n):\n b = []\n for j in range(0,n):\n b.append( matrix[j][i])\n matrix1.append(b)\nfor i in range(n):\n for j in range(n):\n print(matrix1[i][j], end = \" \")\nprint()\n"
},
{
"answer_id": 74625103,
"author": "Yash Mehta",
"author_id": 20172954,
"author_profile": "https://Stackoverflow.com/users/20172954",
"pm_score": 1,
"selected": false,
"text": "matrix=[[1,2,3],[4,5,6],[7,8,9]]\n#print(matrix)\nres=[]\nfor i in zip(*matrix):\n res.append(i)\nprint(res)\n [(1, 4, 7), (2, 5, 8), (3, 6, 9)]\n"
},
{
"answer_id": 74625137,
"author": "Gameplay",
"author_id": 15923186,
"author_profile": "https://Stackoverflow.com/users/15923186",
"pm_score": 1,
"selected": false,
"text": "transposed = list(zip(*matrix))\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15358800/"
] |
74,624,996
|
<p>I am new to ILNumerics and am investigating using it to replace a .Net assembly we created using the MATLAB compiler SDK.</p>
<p>I wrote a small sample app that uses some of the MATLAB code converted to ILNumerics. The process was relatively simple, and I was able to get up and running pretty quickly.</p>
<p>The app I wrote is a very simple WinForms app (still my goto when I want something quick and dirty - don't judge). It loads a data file and performs a couple of different optimizations - one simple and the other fairly complex. The optimizations run and the results are close to the results I get with the same optimization in MATLAB. The optimization is a bit slower, but I blame that on there not being an implementation of constrained least squares in ILNumerics.</p>
<p>When I run the more complicated optimization directly from the windows thread, my memory usage skyrockets pretty quickly. I know this type of thing is really bad form, but this is just a test application. Still, I wanted to make sure that the problem was caused by running in the UI thread, and not something else in ILNumerics. So I wrote an async version of the function that I was calling from the UI thread, and started calling that instead. This fixed the memory explosion, but it has caused me another problem. After hitting this async function a few times (with a button press on the UI), calls to any ILNumerics functions started to throw exceptions related to heap corruption or writing to protected memory. I won't include all of the code, but here is a snippet showing the difference between my async call and the standard call:</p>
<pre><code> public static Task<CharacterizationData> CharacterizeAsync(this Component comp, Substrate charSubstrate, double assortmentViscosity)
{
return Task.Run(() =>
{
return comp.Characterize(charSubstrate, assortmentViscosity);
});
}
public static CharacterizationData Characterize(this Component comp, Substrate charSubstrate, double assortmentViscosity)
{
if (comp is null)
{
throw new ArgumentNullException(nameof(comp));
}
// Capture all reflectances in a single array.
Array<double> OW = comp.OW;
Array<double> OB = comp.OB;
var hasOB = OB.Length > 0;
Array<double> refSamples = OW;
</code></pre>
<p>All of the ILNumerics code is embedded in the synchronous call, so I can't see how calling the async version would cause any cross-thread referencing issues that would lead to heap corruption. The Component and Substrate classes use System.Array objects to store the data, which is why you see some of the members being copied to Array objects within the code.</p>
<p>I've read as much as I can find about the rules around creating and manipulating Array objects and I believe that I am following all rules correctly. The fact that the code runs fine within the UI thread leads me to believe that I have not violated any rules, and I just have some missing knowledge about multithreading with ILNumerics.</p>
<p>Does anyone have any insight into what I might be doing wrong here? Has anyone used ILNumerics in an async call like this?</p>
<p>I wrote a number of additional test functions that perform very simple tasks (no optimizations, just straight Array manipulation), and I'm finding the same thing with these simple functions. If I run them in the UI thread, no problem as long as I haven't run any async functions. But running any of these functions asynchronously will eventually lead to heap corruption or protected memory access violations, no matter where I call the functions (UI thread or asynchronously).</p>
|
[
{
"answer_id": 74625170,
"author": "JonasH",
"author_id": 12342238,
"author_profile": "https://Stackoverflow.com/users/12342238",
"pm_score": 2,
"selected": false,
"text": "comp.Characterize"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74624996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12327713/"
] |
74,625,000
|
<p>I'm trying to make something like a digital phonebook. For example. If the user type in 2 I want the second element in my array to show. I tought that if I used cin >> to decide the value of int i it would work. But It only shows the first element in my array.</p>
<p>This is my third week in programming so please be patient. :)</p>
<p>I put all of my code below, if anything else is wrong or if I made som typos please tell me!</p>
<pre><code>#include <iostream>
#include <string>
using namespace std;
struct telefonbok {
string namn;
string arbetsplats;
int nummer;
};
int main()
{
cout << "Beas phonebook" << endl;
cout << "Mamma - 1" << endl;
cout << "Pappa - 2" << endl;
cout << "Emil - 3" << endl;
cout << "Hugo - 4" << endl;
cout << "Matilda - 5" << endl;
telefonbok Beas[5] = {
{"Mamma", "ICA Maxi", 707397136},
{"Pappa", "Granarolo", 705174881},
{"Emil", "BH Bygg AB", 700726477},
{"Hugo", "SeSol", 700357692},
{"Matilda", "Hedebyskolan", 762095177}
};
int i;
cout << "Type in the number of the contact you want to access:" << endl;
cin >> i;
for (int i = 0; i < 5;i++)
{
cout << "Name: " << Beas[i].namn << endl;
cout << "Workplace: " << Beas[i].arbetsplats << endl;
cout << "Number: " << Beas[i].nummer << endl;
}
}
</code></pre>
|
[
{
"answer_id": 74625030,
"author": "john",
"author_id": 882003,
"author_profile": "https://Stackoverflow.com/users/882003",
"pm_score": 2,
"selected": false,
"text": "int i;\ncout << \"Type in the number of the contact you want to access:\" << endl;\ncin >> i;\n\n// show entry at position i\ncout << \"Name: \" << Beas[i - 1].namn << endl;\ncout << \"Workplace: \" << Beas[i - 1].arbetsplats << endl;\ncout << \"Number: \" << Beas[i - 1].nummer << endl;\n"
},
{
"answer_id": 74625701,
"author": "Lajos Arpad",
"author_id": 436560,
"author_profile": "https://Stackoverflow.com/users/436560",
"pm_score": 0,
"selected": false,
"text": " cin >> i;\n\n for (int i = 0; i < 5;i++)\n {\n cout << \"Name: \" << Beas[i].namn << endl;\n cout << \"Workplace: \" << Beas[i].arbetsplats << endl;\n cout << \"Number: \" << Beas[i].nummer << endl;\n }\n i cin i for i i Beas cin >> i;\n int size = sizeof(Beas)/sizeof(Beas[0]);\n\n if (((i - 1) >= 0) && ((i - 1) < size)) //5 is your \n {\n cout << \"Name: \" << Beas[i - 1].namn << endl;\n cout << \"Workplace: \" << Beas[i - 1].arbetsplats << endl;\n cout << \"Number: \" << Beas[i - 1].nummer << endl;\n }\n else\n {\n //Index would be out of bounds, you may handle that here\n }\n i else"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20597417/"
] |
74,625,005
|
<p>I need to create multiple tables in my schema with the exact same DDL. For that I would usually use a command:</p>
<pre><code>CREATE TABLE SCHEMA.XYZ_STORE_TABLE AS SCHEMA.EFG_STORE_TABLE
</code></pre>
<p>This part is easy. Now I have to repeat the same process for 1000s of tables. To make my life easier, I have created a table which will store all the table names that are supposed to be created, whose structure looks like:</p>
<pre><code>CREATE TABLE SCHEMA.ABC_PROCESS(
PROCESS_CD VARCHAR(32),
PROCESS_NAME VARCHAR(100),
PROCESS_STORE_TABLE_NAME VARCHAR(100)
)
</code></pre>
<p>Then I can query <code>SELECT PROCESS_STORE_TABLE_NAME FROM SCHEMA.ABC_PROCESS</code> and get the table names to be created.</p>
<pre><code>| PROCESS_STORE_TABLE_NAME |
| ------------------------ |
| ABC_STORE_TABLE |
| HIJ_STORE_TABLE |
</code></pre>
<p>Now I could write a Java code which will get these table names, store it in an ArrayList and then execute the <code>CREATE TABLE</code> scripts on each element of that ArrayList from Java code.</p>
<p>Is there a simpler way to do it using SQLs itself without writing Java code?
(PS. You can assume that the table names coming from the query don't already exist)</p>
|
[
{
"answer_id": 74625030,
"author": "john",
"author_id": 882003,
"author_profile": "https://Stackoverflow.com/users/882003",
"pm_score": 2,
"selected": false,
"text": "int i;\ncout << \"Type in the number of the contact you want to access:\" << endl;\ncin >> i;\n\n// show entry at position i\ncout << \"Name: \" << Beas[i - 1].namn << endl;\ncout << \"Workplace: \" << Beas[i - 1].arbetsplats << endl;\ncout << \"Number: \" << Beas[i - 1].nummer << endl;\n"
},
{
"answer_id": 74625701,
"author": "Lajos Arpad",
"author_id": 436560,
"author_profile": "https://Stackoverflow.com/users/436560",
"pm_score": 0,
"selected": false,
"text": " cin >> i;\n\n for (int i = 0; i < 5;i++)\n {\n cout << \"Name: \" << Beas[i].namn << endl;\n cout << \"Workplace: \" << Beas[i].arbetsplats << endl;\n cout << \"Number: \" << Beas[i].nummer << endl;\n }\n i cin i for i i Beas cin >> i;\n int size = sizeof(Beas)/sizeof(Beas[0]);\n\n if (((i - 1) >= 0) && ((i - 1) < size)) //5 is your \n {\n cout << \"Name: \" << Beas[i - 1].namn << endl;\n cout << \"Workplace: \" << Beas[i - 1].arbetsplats << endl;\n cout << \"Number: \" << Beas[i - 1].nummer << endl;\n }\n else\n {\n //Index would be out of bounds, you may handle that here\n }\n i else"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2451763/"
] |
74,625,014
|
<p>We're looking for a new way to create multi language email templates. We got the idea to use inky in twig to create clean email HTML and render translations. The problem is that we have Sendgrid (handlebars) that renders variables the same way as twig.</p>
<p>Is there a solution to create a translation in twig having the {{ }} intact. We don't want to translate around the brackets because that could not be compatible with the language its spelling.</p>
<p><strong>example</strong></p>
<pre><code>{% trans %}I am a {{ job }}{% endtrans %}
</code></pre>
<p>gives the following error:</p>
<blockquote>
<p>A message inside a trans tag must be a simple text.</p>
</blockquote>
|
[
{
"answer_id": 74625030,
"author": "john",
"author_id": 882003,
"author_profile": "https://Stackoverflow.com/users/882003",
"pm_score": 2,
"selected": false,
"text": "int i;\ncout << \"Type in the number of the contact you want to access:\" << endl;\ncin >> i;\n\n// show entry at position i\ncout << \"Name: \" << Beas[i - 1].namn << endl;\ncout << \"Workplace: \" << Beas[i - 1].arbetsplats << endl;\ncout << \"Number: \" << Beas[i - 1].nummer << endl;\n"
},
{
"answer_id": 74625701,
"author": "Lajos Arpad",
"author_id": 436560,
"author_profile": "https://Stackoverflow.com/users/436560",
"pm_score": 0,
"selected": false,
"text": " cin >> i;\n\n for (int i = 0; i < 5;i++)\n {\n cout << \"Name: \" << Beas[i].namn << endl;\n cout << \"Workplace: \" << Beas[i].arbetsplats << endl;\n cout << \"Number: \" << Beas[i].nummer << endl;\n }\n i cin i for i i Beas cin >> i;\n int size = sizeof(Beas)/sizeof(Beas[0]);\n\n if (((i - 1) >= 0) && ((i - 1) < size)) //5 is your \n {\n cout << \"Name: \" << Beas[i - 1].namn << endl;\n cout << \"Workplace: \" << Beas[i - 1].arbetsplats << endl;\n cout << \"Number: \" << Beas[i - 1].nummer << endl;\n }\n else\n {\n //Index would be out of bounds, you may handle that here\n }\n i else"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2819164/"
] |
74,625,015
|
<p>I've newly started learning C++ and am stuck with this problem. I need to insert a (user inputted) number of elements in a single line with space separation. If the number of elements was known, I could just write <code>cin >> var1 >> var2 >> ... >> varN;</code>. But how do I do it with any number of elements (loop maybe)?</p>
<p>This is what I'm trying to do:</p>
<pre><code>#include<bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
int arr[n];
for (int i=0; i<n; i++) {
//stuck here
}
}
</code></pre>
<p>I could have written <code>cin >> arr[i];</code> and proceeded, but that would require the user to press enter after every input, which I cannot do due to the question's restrictions. How do I write the code so that all my input for array elements can be given in a single line?</p>
<p>PS: I've seen several similar questions already answered on the site, but most of them involve implementations using vectors or are beyond my current level of understanding. A simpler solution will be appreciated.</p>
|
[
{
"answer_id": 74625115,
"author": "Devansh_Jain_21",
"author_id": 17667319,
"author_profile": "https://Stackoverflow.com/users/17667319",
"pm_score": 3,
"selected": true,
"text": "cin>>arr[i]"
},
{
"answer_id": 74625951,
"author": "Lasersköld",
"author_id": 3748275,
"author_profile": "https://Stackoverflow.com/users/3748275",
"pm_score": 0,
"selected": false,
"text": "std::vector n #include <iostream>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\nint main() {\n int n = 0;\n cin >> n;\n vector<string> arr; // A vector (ie kind of a variable sized array)\n for (int i=0; i<n; i++) {\n string str;\n cin >> str; // Read a word\n arr.push_back(str); // Add a string to the vector\n }\n\n // To use the data\n for (int i = 0; i < arr.size(); ++i) {\n cout << arr.at(i) << \"\\n\"; // Print value of vector\n }\n // or like this\n for (auto str: arr) {\n cout << str << \"\\n\";\n }\n}\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20509246/"
] |
74,625,032
|
<p>I have "ORA-00933: sql command not properly ended" error in this query:</p>
<pre><code>SELECT FILIALE_CHIUSA FROM FILIALI_CHIUSE WHERE FILIALE IN (9909);
</code></pre>
<p>The table is</p>
<pre><code>CREATE TABLE FILIALI_CHIUSE (
FILIALE NUMBER(5,0) NOT NULL,
FILIALE_CHIUSA NUMBER(5,0) NOT NULL
);
</code></pre>
<p>I have checked but the query seems right and with not erroneous clauses, so where is the problem?</p>
|
[
{
"answer_id": 74625067,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 1,
"selected": false,
"text": "create table if not exists SQL> CREATE TABLE IF NOT EXISTS FILIALI_CHIUSE (\n 2 FILIALE NUMBER(5,0) NOT NULL,\n 3 FILIALE_CHIUSA NUMBER(5,0) NOT NULL\n 4 );\nCREATE TABLE IF NOT EXISTS FILIALI_CHIUSE (\n *\nERROR at line 1:\nORA-00922: missing or invalid option\n SQL> CREATE TABLE FILIALI_CHIUSE\n 2 (FILIALE NUMBER(5,0) NOT NULL,\n 3 FILIALE_CHIUSA NUMBER(5,0) NOT NULL\n 4 );\n\nTable created.\n select SQL> SELECT FILIALE_CHIUSA FROM FILIALI_CHIUSE WHERE FILIALE IN (9909);\n\nno rows selected\n\nSQL>\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7674438/"
] |
74,625,033
|
<pre><code>const data = {
"070010": "ABBEY MORTGAGE BANK-070010",
"044": "ACCESS BANK PLC-044",
"323": "AccessMobile-100013",
}
</code></pre>
<p>How can I render the value of the data above in a select tag and on Change on each I will get the key and value.</p>
<pre><code>const [acctname,setAcctname]=useState("")
for (const key in data) {
if (Object.hasOwnProperty.call(data, key)) {
const element = data[key];
setAcctName(Object.values(data))
}
}
</code></pre>
<pre><code>return (
<select>
<option >{acctName}</option>
</select>
)
</code></pre>
<p>but not working</p>
|
[
{
"answer_id": 74625334,
"author": "Mayuri S Kulkarni",
"author_id": 7272723,
"author_profile": "https://Stackoverflow.com/users/7272723",
"pm_score": 0,
"selected": false,
"text": "acctname import { useEffect, useState } from 'react';\n\nconst data = {\n \"070010\": \"ABBEY MORTGAGE BANK-070010\",\n \"044\": \"ACCESS BANK PLC-044\",\n \"323\": \"AccessMobile-100013\",\n}\n\nconst App = () => {\n const [acctname, setAcctname] = useState(\"\");\n\n useEffect(() => {\n for (const key in data) {\n if (Object.hasOwnProperty.call(data, key)) {\n const element = data[key];\n setAcctname(Object.values(data));\n }\n }\n }, []);\n\n const handleChange = (acc) => {\n console.log(\"Selected option: \", acc)\n }\n\n return (\n <div>\n {acctname && <select onChange={(e) => handleChange(e.target.value)}>\n {acctname.map((acc, i) => (\n <option key={i}>{acc}</option>\n ))}\n </select>}\n </div>\n )\n}\n\n"
},
{
"answer_id": 74626543,
"author": "Mayuri S Kulkarni",
"author_id": 7272723,
"author_profile": "https://Stackoverflow.com/users/7272723",
"pm_score": 3,
"selected": true,
"text": "import { useEffect, useState } from 'react';\n\nconst data = {\n \"070010\": \"ABBEY MORTGAGE BANK-070010\",\n \"044\": \"ACCESS BANK PLC-044\",\n \"323\": \"AccessMobile-100013\",\n}\n\nconst App = () => {\n const [acctname, setAcctname] = useState(\"\");\n\n useEffect(() => {\n const entries = Object.entries(data);\n const arraySet = [];\n for (const key in entries) {\n const set = entries[key];\n arraySet.push(`${set[0]}: ${set[1]}`);\n }\n setAcctname(arraySet);\n }, []);\n\n const handleChange = (acc) => {\n let selectedOpt = acctname.filter(val => val.includes(acc))[0]?.split(\":\");\n console.log(\"Selected option key: \", selectedOpt[0]);\n console.log(\"Selected option value: \", selectedOpt[1]);\n }\n\n return (\n <div>\n {acctname.length && <select onChange={(e) => handleChange(e.target.value)}>\n {acctname.map((acc, i) => {\n let set = acc.split(\":\");\n return (\n <option key={i}>{set[1].trim()}</option>\n )\n }\n )}\n </select>}\n </div>\n )\n}\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19267906/"
] |
74,625,066
|
<p>Multiplies large matrices for a very long time. How can this problem be solved. I use the galois library, and numpy, I think it should still work stably. I tried to implement my GF4 arithmetic and multiplied matrices using numpy, but it takes even longer. Thank you for your reply.</p>
<p>When r = 2,3,4,5,6 multiplies quickly, then it takes a long time. As for me, these are not very large sizes of matrices. This is just a code snippet. I get the sizes n, k of matrices of a certain family given r. And I need to multiply the matrices of those obtained parameters.</p>
<pre><code>import numpy as np
import galois
def family_Hamming(q,r):
n = int((q**r-1)/(q-1))
k = int((q**r-1)/(q-1)-r)
res = (n,k)
return res
q = 4
r = 7
n,k = family_Hamming(q,r)
GF = galois.GF(2**2)
#(5461,5461)
a = GF(np.random.randint(4, size=(k, k)))
#(5454,5461)
b = GF(np.random.randint(4, size=(k, n)))
c = np.dot(a,b)
print(c)
</code></pre>
|
[
{
"answer_id": 74625334,
"author": "Mayuri S Kulkarni",
"author_id": 7272723,
"author_profile": "https://Stackoverflow.com/users/7272723",
"pm_score": 0,
"selected": false,
"text": "acctname import { useEffect, useState } from 'react';\n\nconst data = {\n \"070010\": \"ABBEY MORTGAGE BANK-070010\",\n \"044\": \"ACCESS BANK PLC-044\",\n \"323\": \"AccessMobile-100013\",\n}\n\nconst App = () => {\n const [acctname, setAcctname] = useState(\"\");\n\n useEffect(() => {\n for (const key in data) {\n if (Object.hasOwnProperty.call(data, key)) {\n const element = data[key];\n setAcctname(Object.values(data));\n }\n }\n }, []);\n\n const handleChange = (acc) => {\n console.log(\"Selected option: \", acc)\n }\n\n return (\n <div>\n {acctname && <select onChange={(e) => handleChange(e.target.value)}>\n {acctname.map((acc, i) => (\n <option key={i}>{acc}</option>\n ))}\n </select>}\n </div>\n )\n}\n\n"
},
{
"answer_id": 74626543,
"author": "Mayuri S Kulkarni",
"author_id": 7272723,
"author_profile": "https://Stackoverflow.com/users/7272723",
"pm_score": 3,
"selected": true,
"text": "import { useEffect, useState } from 'react';\n\nconst data = {\n \"070010\": \"ABBEY MORTGAGE BANK-070010\",\n \"044\": \"ACCESS BANK PLC-044\",\n \"323\": \"AccessMobile-100013\",\n}\n\nconst App = () => {\n const [acctname, setAcctname] = useState(\"\");\n\n useEffect(() => {\n const entries = Object.entries(data);\n const arraySet = [];\n for (const key in entries) {\n const set = entries[key];\n arraySet.push(`${set[0]}: ${set[1]}`);\n }\n setAcctname(arraySet);\n }, []);\n\n const handleChange = (acc) => {\n let selectedOpt = acctname.filter(val => val.includes(acc))[0]?.split(\":\");\n console.log(\"Selected option key: \", selectedOpt[0]);\n console.log(\"Selected option value: \", selectedOpt[1]);\n }\n\n return (\n <div>\n {acctname.length && <select onChange={(e) => handleChange(e.target.value)}>\n {acctname.map((acc, i) => {\n let set = acc.split(\":\");\n return (\n <option key={i}>{set[1].trim()}</option>\n )\n }\n )}\n </select>}\n </div>\n )\n}\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20643110/"
] |
74,625,068
|
<p>I am trying to iterate over two arrays using foreach and for loop but foreach not working!</p>
<p>I have two arrays <code>$data</code> and <code>$pageNumber</code> I need to iterate over both and store data in SQL accordingly, <code>$data</code> contains image and <code>$pageNumber</code> contains number of pages so count of both arrays always same.
whenever I am trying to store <code>$data</code> elements with respect to <code>$pageNumber</code> like there are 3 images in <code>$data</code> and their serial number are 3,11,20 in <code>$pageNumber</code>, this always result in first element(image) of <code>$data</code> and numbers are 3,11,20 this means images are not iterating same images saved with different numbers.</p>
<p><strong>How Will I save both Image and numbers serial wise simultaneously Like -</strong></p>
<pre><code>$data = ['image1','image2','image3'];
$pageNumber = [22,1,44]
</code></pre>
<p><strong>result should be like -</strong> image1 saved with pagenumber 22, image2 saved with page number1... in SQL table field <code>Image_name</code> and <code>Image_name</code></p>
<pre><code> <?php
$imagecount = 0;
foreach ($data as $base64_string) {
$newFileName = $id . "0" . $imagecount . ".jpg";
// replacing data:image/jpeg;base64, from post request
$base64_string = str_replace('data:image/jpeg;base64,', '', $base64_string);
$base64_string = str_replace(' ', '+', $base64_string);
//base64 data which will store in file
$decoded = base64_decode($base64_string);
$imagecount++;
if (file_put_contents("/record/images/data/" . $imagedirectory . "/" . $newFileName, $decoded)) {
$pages = $_POST['pnumber'];
$pageNumber = explode(',', $pages);
for ($i = 0; $i < count($pageNumber); $i++) {
$insrecords =
"insert into records(
ArticleID, Page_Number,
imagedirectory,
Image_name,
) values (
'" .
$id .
"',
'" .
$pageNumber[$i] .
"',
'" .
$imagedirectory .
"',
'" .
$newFileName .
"',
)";
mysql_query($insrecords) or die(mysql_error());
}
} else {
echo "here";
die();
}
}
?>
</code></pre>
|
[
{
"answer_id": 74656566,
"author": "amit kumar",
"author_id": 20509709,
"author_profile": "https://Stackoverflow.com/users/20509709",
"pm_score": 0,
"selected": false,
"text": " <?php\n $imagecount = 0;\n foreach ($data as $base64_string) {\n $newFileName = $id . \"0\" . $imagecount . \".jpg\";\n\n // replacing data:image/jpeg;base64, from post request\n $base64_string = str_replace('data:image/jpeg;base64,', '', $base64_string);\n\n $base64_string = str_replace(' ', '+', $base64_string);\n\n //base64 data which will store in file\n $decoded = base64_decode($base64_string);\n $imagecount++;\n\n if (file_put_contents(\"/record/images/data/\" . $imagedirectory . \"/\" . $newFileName, $decoded)) {\n $pages = $_POST['pnumber'];\n $pageNumber = explode(',', $pages);\n\n foreach ($pageNumber as $page) {\n $insrecords =\n \"insert into records( \n ArticleID, Page_Number, \n imagedirectory,\n Image_name,\n \n ) values ( \n '\" .\n $id .\n \"',\n '\" .\n $page .\n \"', \n '\" .\n $imagedirectory .\n \"',\n '\" .\n $newFileName .\n \"',\n \n )\";\n mysql_query($insrecords) or die(mysql_error());\n }\n } else {\n echo \"here\";\n\n die();\n }\n }\n\n\n?> \n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20509709/"
] |
74,625,082
|
<p>Here is my code</p>
<pre><code>$search_term = "Hary Kumar";
$filterData = DB::table('signups')->where('name','LIKE',"%{$search_term}%");
</code></pre>
<p>If I am not wrong above code will give me result like:</p>
<pre><code>select * from signups where name like "%Hary Kumar%"
</code></pre>
<p>But, I am trying to get</p>
<pre><code>select * from signups where name like "%Hary%" or name like "%Kumar%"
</code></pre>
|
[
{
"answer_id": 74625591,
"author": "Ahrengot",
"author_id": 641755,
"author_profile": "https://Stackoverflow.com/users/641755",
"pm_score": 0,
"selected": false,
"text": "DB::table('signups')\n ->where('name', 'LIKE', \"%{$first_term}%\")\n ->orWhere('name', 'LIKE', \"%{$second_term}%\");\n"
},
{
"answer_id": 74625931,
"author": "ITtraders Nepal",
"author_id": 16470274,
"author_profile": "https://Stackoverflow.com/users/16470274",
"pm_score": -1,
"selected": false,
"text": "$search_values = explode(\" \",$search_term);\n\n DB::table('signups')\n ->orWhere(function ($query) use($search_values) {\n foreach($search_values as $search_value)\n $query->orwhere('name', 'like', '%' . $search_value .'%');})\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625082",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16470274/"
] |
74,625,117
|
<p>How can I copy specific files from all directories and subdirectories to a new directory while preserving the original subdirectorie structure?</p>
<p>This <a href="https://stackoverflow.com/questions/15617016/copy-all-files-with-a-certain-extension-from-all-subdirectories">answer</a>:</p>
<pre><code>find . -name \*.xls -exec cp {} newDir \;
</code></pre>
<p>solves to copy all xls files from all subdirectories in the same directory newDir. That is not what I want.</p>
<p>If an xls file is in: <code>/s1/s2/</code> then it sould be copied to <code>newDir/s1/s2</code>.</p>
<p>copies all files from all folders and subfolders to a new folder, but the original file structure is lost. Everything is copied to a same new folder on top of each other.</p>
|
[
{
"answer_id": 74625761,
"author": "Renaud Pacalet",
"author_id": 1773798,
"author_profile": "https://Stackoverflow.com/users/1773798",
"pm_score": 2,
"selected": true,
"text": "find . -type f -name '*.xls' -exec sh -c \\\n'd=\"newDir/${1%/*}\"; mkdir -p \"$d\" && cp \"$1\" \"$d\"' sh {} \\;\n d=\"newDir/${1%/*}\"; mkdir -p \"$d\" && cp \"$1\" \"$d\" xls find . -type f -name '*.xls' -exec sh -c \\\n'for f in \"$@\"; do d=\"newDir/${f%/*}\"; mkdir -p \"$d\" && cp \"$f\" \"$d\"; done' sh {} +\n"
},
{
"answer_id": 74626502,
"author": "user1934428",
"author_id": 1934428,
"author_profile": "https://Stackoverflow.com/users/1934428",
"pm_score": 1,
"selected": false,
"text": "# Ensure that newDir exists and is empty. Omit this step if you\n# don't want it.\n[[ -d newDir ]] && rm -r newDir && mkdir newDir\n\n# Copy the xls files.\nrsync -a --include='**/*.xls' --include='*/' --exclude='*' . newDir\n rsync . .xls"
},
{
"answer_id": 74667807,
"author": "len",
"author_id": 4169571,
"author_profile": "https://Stackoverflow.com/users/4169571",
"pm_score": 0,
"selected": false,
"text": "find . -name '*.xls' | cpio -pdm newDir\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4169571/"
] |
74,625,119
|
<p>I have a question:
For example I have 2 lists:<br>
1: <code>Banana</code> <code>Apple</code> <code>Orange</code><br>
2: <code>Yellow</code> <code>Red</code> <code>Orange</code></p>
<p>I want it to list.sort
so it will be:<br>
<code>Apple</code> <code>Banana</code> <code>Orange</code><br>
But in the same time I want the SAME changes happening inside of the Yellow red orange list.
So it would be like this:<br>
<code>Apple</code> <code>Banana</code> <code>Orange</code><br>
<code>Red</code> <code>Yellow</code> <code>Orange</code></p>
<p>I didnt try this because I literally have no idea how to do this and all this is just on the planning board</p>
|
[
{
"answer_id": 74625172,
"author": "Loïc Robert",
"author_id": 19033618,
"author_profile": "https://Stackoverflow.com/users/19033618",
"pm_score": 0,
"selected": false,
"text": "zip sort unzip"
},
{
"answer_id": 74625185,
"author": "Tim Schmelter",
"author_id": 284240,
"author_profile": "https://Stackoverflow.com/users/284240",
"pm_score": 2,
"selected": false,
"text": "public class Fruit\n{\n public string Name {get; set;}\n public string Color {get; set;}\n}\n List<Fruit> fruits = new()\n{\n new Fruit{ Name = \"Banana\", Color = \"Yellow\" },\n new Fruit{ Name = \"Apple\", Color = \"Red\" },\n new Fruit{ Name = \"Orange\", Color = \"Orange\" }\n};\n\nvar orderedFruits = fruits.OrderBy(f => f.Name);\n ToList fruits = fruits.OrderBy(f => f.Name).ToList();\n Zip List<string> fruitNames = new() { \"Banana\", \"Apple\", \"Orange\" };\nList<string> fruitColors = new() { \"Yellow\", \"Red\", \"Orange\" };\nList<(string Name, string Color)> orderedFruits = fruitNames\n .Zip(fruitColors, (n, c) => (Name: n, Color: c))\n .OrderBy(x => x.Name)\n .ToList();\nfruitNames = orderedFruits.Select(x => x.Name).ToList();\nfruitColors = orderedFruits.Select(x => x.Color).ToList();\n"
},
{
"answer_id": 74625610,
"author": "JonasH",
"author_id": 12342238,
"author_profile": "https://Stackoverflow.com/users/12342238",
"pm_score": 0,
"selected": false,
"text": "var fruits = ...\nvar colors = ...\nvar proxy = Enumerable.Range(0, fruits.Length);\nvar sortedProxy = proxy.OrderBy(i => fruits[i]);\nvar sortedColors = sortedProxy.Select(i => colors[i]).ToList();\n i => fruits[i] List.Sort"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20643326/"
] |
74,625,144
|
<p>trying to extract the data between single quotes</p>
<pre><code>import re
a = 'USA-APA HA-WBS-10.152.08.0/24'
print(re.findall(r'()', a))
</code></pre>
<p>expecting the oputput : USA-APA HA-WBS-10.152.08.0/24</p>
|
[
{
"answer_id": 74625385,
"author": "SScotti",
"author_id": 2391859,
"author_profile": "https://Stackoverflow.com/users/2391859",
"pm_score": 1,
"selected": false,
"text": "a = 'USA-APA HA-WBS-10.152.08.0/24'\nprint(a)\n % python3 test.py\nUSA-APA HA-WBS-10.152.08.0/24\n"
},
{
"answer_id": 74625429,
"author": "Vasilis Neris",
"author_id": 10565643,
"author_profile": "https://Stackoverflow.com/users/10565643",
"pm_score": 1,
"selected": true,
"text": "import re\n\na = 'USA-APA HA-WBS-10.152.08.0/24'\nresult = re.findall(r'(.*?)', a)\nprint(\"\".join(result))\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20643339/"
] |
74,625,146
|
<p>`</p>
<pre><code>def conversion():
options = print('Would you like to convert hours to mins, or mins to hours?')
choice = input()
if choice == 'hours to mins':
hours = int(input('How many hours? '))
mins = hours * 60
print(mins, 'Minutes')
elif choice == 'mins to hours':
mins = int(input('How many minutes? '))
hours = mins/60
print(hours, 'Hours')
else:
print('An error has occured')
conversion()
</code></pre>
<p>This is the production code which is meant to be used to write a corresponding test code. `</p>
<p>I am unsure on how to go about writing a test code using 'siminput' 'assert' and the a variable 'actual' to write a working test code for the line of code above for it to properly run in unittest.</p>
|
[
{
"answer_id": 74625534,
"author": "Cpt.Hook",
"author_id": 20599896,
"author_profile": "https://Stackoverflow.com/users/20599896",
"pm_score": 2,
"selected": true,
"text": "pytest pytest-mock # conversion.py\ndef conversion():\n print('Would you like to convert hours to mins, or mins to hours?')\n choice = input()\n\n if choice == 'hours to mins':\n hours = int(input('How many hours? '))\n mins = hours * 60\n print(mins, 'Minutes')\n return mins\n elif choice == 'mins to hours':\n mins = int(input('How many minutes? '))\n hours = mins/60\n print(hours, 'Hours')\n return hours\n else:\n print('An error has occured')\n return False\n # conversion_test.py\ndef test_hrs_to_min(mocker):\n input_provider = mocker.patch('builtins.input')\n # The following line is crucial: You configure the \n # values each call to `Input` will return in order. \n input_provider.side_effect = ['hours to mins', '3']\n result = conversion()\n assert result == 3*60\n pytest -s builtin.print mock_print.assert_called_with(3*60, \"Minutes\") def conversion():\n print('Would you like to convert hours to mins, or mins to hours?')\n choice = input()\n if choice == 'hours to mins':\n hours = int(input('How many hours? '))\n print(hrs2mins(hours), 'Minutes')\n elif choice == 'mins to hours':\n mins = int(input('How many minutes? '))\n print(min2hrs(mins), 'Hours')\n\n print('An error has occurred')\n return False\n\n\ndef hrs2mins(hrs: int) -> int:\n return hrs * 60\n\n\ndef min2hrs(mins: int) -> float:\n return mins/60\n"
},
{
"answer_id": 74625665,
"author": "Sezer BOZKIR",
"author_id": 5942941,
"author_profile": "https://Stackoverflow.com/users/5942941",
"pm_score": 0,
"selected": false,
"text": "def conversion():\n print(\"Would you like to conver...\")\n choice = input()\n\n if choice == 'hour to mins':\n hours = int(input(\"How many hours?\"))\n mins = hours * 60\n print(mins, \"Minutes\")\n else:\n print('An error has occured')\n from unittest import mock\nfrom unittest import TestCase\nfrom test_input import conversion\nfrom io import StringIO\n\n\nclass ConversionTest(TestCase):\n @mock.patch('test_input.input', create=True)\n def test_minutes(self, mocked_input):\n mocked_input.side_effect = [\"hour to mins\", 4]\n with mock.patch('sys.stdout', new=StringIO()) as fake_out:\n conversion()\n output = fake_out.getvalue()\n self.assertEqual(output.replace(\"\\n\", \"\"), 'Would you like to conver...240 Minutes')\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625146",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20635057/"
] |
74,625,150
|
<p>My goal is for this entire block to be scrollable.
I tried all kinds of ways to achieve the goal but without success.
I tried with <code>ListHeaderComponent</code> and moved the entire top view to it and it didn't work.
And I also tried <code><FlatList nestedScrollEnabled /></code>
And it didn't work either.
What is the correct way to reach the scroll?</p>
<p><strong>I come from here :</strong></p>
<pre><code>const renderAccordians = () => {
const items: JSX.Element[] = [];
areaData.forEach(item => {
items.push(<Accordian item={item} key={item.title} />);
});
return items;
};
</code></pre>
<p><strong>To here :</strong></p>
<pre><code>return (
<View>
<View style={styles.row}>
<TouchableOpacity onPress={() => onClickFather()}>
<MaterialIcons size={24} name={data.checked ? 'check-box' : 'check-box-outline-blank'} color={'black'} />
</TouchableOpacity>
<Text style={[styles.title]}>{data.title}</Text>
<TouchableOpacity style={styles.row} onPress={() => toggleExpand()}>
<MaterialIcons name={expanded ? 'arrow-drop-up' : 'arrow-drop-down'} size={30} color={'black'} />
</TouchableOpacity>
</View>
<View style={styles.parentHr} />
{expanded && (
<FlatList
data={data.data}
numColumns={1}
scrollEnabled={false}
renderItem={({ item, index }) => (
<View>
<TouchableOpacity style={[styles.childRow, styles.button]} onPress={() => onClick(index)}>
<MaterialIcons
size={24}
name={item.checked ? 'check-box' : 'check-box-outline-blank'}
color={'black'}
/>
<Text style={[styles.itemInActive]}>{item.key}</Text>
</TouchableOpacity>
<View style={styles.childHr} />
</View>
)}
/>
)}
</View>
);
</code></pre>
|
[
{
"answer_id": 74625515,
"author": "Hend El-Sahli",
"author_id": 9522406,
"author_profile": "https://Stackoverflow.com/users/9522406",
"pm_score": 2,
"selected": true,
"text": "FlatList Accordion ExpandButton Flatlist > ListHeaderComponent FlatList Header keyExtractor FlatList index key listItem id return (\n <View style={{ flex: 1}}> // <<--- Look here\n <View style={styles.row}>\n <TouchableOpacity onPress={() => onClickFather()}>\n <MaterialIcons\n size={24}\n name={data.checked ? 'check-box' : 'check-box-outline-blank'}\n color={'black'}\n />\n </TouchableOpacity>\n <Text style={[styles.title]}>{data.title}</Text>\n <TouchableOpacity style={styles.row} onPress={() => toggleExpand()}>\n <MaterialIcons\n name={expanded ? 'arrow-drop-up' : 'arrow-drop-down'}\n size={30}\n color={'black'}\n />\n </TouchableOpacity>\n </View>\n <View style={styles.parentHr} />\n {expanded && (\n <FlatList\n data={data.data}\n numColumns={1}\n scrollEnabled={true} // <<--- Look here\n keyExtractor={(_, index) => index.toString()} // <<=== Look here\n contentContainerStyle={{flexGrow: 1}} // <<--- Look here\n renderItem={({ item, index }) => (\n <View>\n <TouchableOpacity\n style={[styles.childRow, styles.button]}\n onPress={() => onClick(index)}\n >\n <MaterialIcons\n size={24}\n name={item.checked ? 'check-box' : 'check-box-outline-blank'}\n color={'black'}\n />\n <Text style={[styles.itemInActive]}>{item.key}</Text>\n </TouchableOpacity>\n <View style={styles.childHr} />\n </View>\n )}\n />\n )}\n </View>\n );\n"
},
{
"answer_id": 74625889,
"author": "vuminh",
"author_id": 19520123,
"author_profile": "https://Stackoverflow.com/users/19520123",
"pm_score": 0,
"selected": false,
"text": "<ScrollView\n style={styles.messageContain}\n ref={ref => {\n this.scrollView = ref;\n }}\n {data.data.map((item, index) => {\n return <YourComponent key={index} data={item} />;\n })}\n </ScrollView>\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15832161/"
] |
74,625,152
|
<p>I have a simple app to count the number of repetitions of different exercises.</p>
<p>What I would like to do is to move to a new window (Activity in my case) when the set number of repetitions is reached. To do that, I call a new activity in onSensorChanged like:</p>
<pre><code>override fun onSensorChanged(event: SensorEvent?) {
if(repetitionTracker.getNumberOfRepetitions() <= maxRepetitions ){
intent_next = Intent(this, End::class.java)
intent_next.flags = Intent.FLAG_ACTIVITY_NEW_TASK
startActivity(intent_next)
}
}
</code></pre>
<p>But the application crash when reaching this point</p>
<p>I tried everything that was suggested here: <a href="https://stackoverflow.com/questions/3606596/start-activity-from-service-in-android">Start Activity from Service in Android</a>.</p>
<p>But I couldn't find a way to make it work. I suppose that the problem is to use Android 10+</p>
<p>Do you know what is the right pattern/method to do this kind of operations? I'm also open to not call a new activity but something else if this is the correct way of doing it</p>
|
[
{
"answer_id": 74625515,
"author": "Hend El-Sahli",
"author_id": 9522406,
"author_profile": "https://Stackoverflow.com/users/9522406",
"pm_score": 2,
"selected": true,
"text": "FlatList Accordion ExpandButton Flatlist > ListHeaderComponent FlatList Header keyExtractor FlatList index key listItem id return (\n <View style={{ flex: 1}}> // <<--- Look here\n <View style={styles.row}>\n <TouchableOpacity onPress={() => onClickFather()}>\n <MaterialIcons\n size={24}\n name={data.checked ? 'check-box' : 'check-box-outline-blank'}\n color={'black'}\n />\n </TouchableOpacity>\n <Text style={[styles.title]}>{data.title}</Text>\n <TouchableOpacity style={styles.row} onPress={() => toggleExpand()}>\n <MaterialIcons\n name={expanded ? 'arrow-drop-up' : 'arrow-drop-down'}\n size={30}\n color={'black'}\n />\n </TouchableOpacity>\n </View>\n <View style={styles.parentHr} />\n {expanded && (\n <FlatList\n data={data.data}\n numColumns={1}\n scrollEnabled={true} // <<--- Look here\n keyExtractor={(_, index) => index.toString()} // <<=== Look here\n contentContainerStyle={{flexGrow: 1}} // <<--- Look here\n renderItem={({ item, index }) => (\n <View>\n <TouchableOpacity\n style={[styles.childRow, styles.button]}\n onPress={() => onClick(index)}\n >\n <MaterialIcons\n size={24}\n name={item.checked ? 'check-box' : 'check-box-outline-blank'}\n color={'black'}\n />\n <Text style={[styles.itemInActive]}>{item.key}</Text>\n </TouchableOpacity>\n <View style={styles.childHr} />\n </View>\n )}\n />\n )}\n </View>\n );\n"
},
{
"answer_id": 74625889,
"author": "vuminh",
"author_id": 19520123,
"author_profile": "https://Stackoverflow.com/users/19520123",
"pm_score": 0,
"selected": false,
"text": "<ScrollView\n style={styles.messageContain}\n ref={ref => {\n this.scrollView = ref;\n }}\n {data.data.map((item, index) => {\n return <YourComponent key={index} data={item} />;\n })}\n </ScrollView>\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3784015/"
] |
74,625,177
|
<p>I currently have a piece of code like this:</p>
<pre class="lang-js prettyprint-override"><code> return (
creatable
? <Select
options={options}
value={value}
onChange={(selectedValue) => valueSetter(selectedValue)}
/>
: <CreatableSelect
options={options}
value={value}
onChange={(selectedValue) => valueSetter(selectedValue)}
/>
)
</code></pre>
<p>As you can see, both of the components accept the exact same props. Is there any way that I can increase code reusability in this code (something like putting the props into a dictionary and unpack them)?</p>
<p>Thank you!</p>
|
[
{
"answer_id": 74625224,
"author": "tomleb",
"author_id": 15169145,
"author_profile": "https://Stackoverflow.com/users/15169145",
"pm_score": 4,
"selected": true,
"text": "spread syntax const props = {\n options,\n value,\n onChange: (selectedValue) => valueSetter(selectedValue)\n}\n\nreturn (\n creatable\n ? <Select {...props} />\n : <CreatableSelect {...props} />\n)\n props"
},
{
"answer_id": 74625335,
"author": "Cong Nguyen",
"author_id": 5597680,
"author_profile": "https://Stackoverflow.com/users/5597680",
"pm_score": 1,
"selected": false,
"text": "const props = {\n options,\n value,\n onChange: valueSetter\n}\n\nreturn (\n creatable\n ? <Select {...props} />\n : <CreatableSelect {...props} />\n)\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18285293/"
] |
74,625,186
|
<pre><code>this is my code right now
#h1{
font-family: 'open-sans';
position: absolute;
color: white;
font-size: 16px;
left: 850px;
margin-top: 5px;
position: fixed;
}
</code></pre>
<p>nothing works im in agony also tried using position sticky but it didnt work</p>
|
[
{
"answer_id": 74625229,
"author": "Ali Mir",
"author_id": 10262756,
"author_profile": "https://Stackoverflow.com/users/10262756",
"pm_score": -1,
"selected": false,
"text": ".element {\n position: fixed; \n top: 0; \n left: 0;\n width 100%\n}\n"
},
{
"answer_id": 74625235,
"author": "Grizou",
"author_id": 20068386,
"author_profile": "https://Stackoverflow.com/users/20068386",
"pm_score": -1,
"selected": false,
"text": "position:sticky position: fixed position: absolute"
},
{
"answer_id": 74625274,
"author": "PirateNahid",
"author_id": 20126655,
"author_profile": "https://Stackoverflow.com/users/20126655",
"pm_score": 0,
"selected": false,
"text": "position: absolute; position: fixed; h1{\nposition: fixed;\nfont-family: 'open-sans';\ncolor: white;\nfont-size: 16px;\nbackground-color: black;\ntop: 0;}\n background-color"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20553569/"
] |
74,625,193
|
<p>I had this <strong>Table</strong>, I want when <strong>I print the table</strong>, should print with a fixed header on each paper, and it's doing that, but the headers does not start on the <strong>top</strong> of the paper, <em>something going wrong</em></p>
<pre><code><table id="TableDtl" class="tableClass cellWithborder"
style="width:100%;overflow:scroll; font-weight:bold; border: 1px solid Black;">
<thead>
<th style="height:80px; font-size:x-large;font-weight:bold;">
<header0>ID</header0>
</th>
<th style="height:80px; font-size:x-large;font-weight:bold;">
<header1>NAME</header1>
</th>
<th style="height:80px; font-size:x-large;font-weight:bold;">
<header2>Quantity</header2>
</th>
<th style="height:80px; font-size:x-large;font-weight:bold;">
<header3>Per</header3>
</th>
<th style="height:80px; font-size:x-large;font-weight:bold;">
<header4>Price</header4>
</th>
<th style="height:80px; font-size:x-large;font-weight:bold;">
<header5>Free</header5>
</th>
</thead>
<tbody>
<tr>
<td style="font-size:x-large;font-weight:bold;">100-933-03</td>
<td style=" font-size:x-large;font-weight:bold;width:30%">Just For Test</td>
<td style="font-size:x-large;font-weight:bold;">4</td>
<td style="font-size:x-large;font-weight:bold;">Test</td>
<td style="font-size:x-large;font-weight:bold;">444</td>
<td style="font-size:x-large;font-weight:bold;">6666</td>
</tr>
</tbody>
</table>
</code></pre>
<p><a href="https://i.stack.imgur.com/osy0t.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/osy0t.png" alt="enter image description here" /></a></p>
<p><strong>I search about it a lot</strong> and I try something like this style:</p>
<pre><code><style>
@media print {
@page{
margin:1em;
}
table {
page-break-after:auto;
border-collapse:collapse;
}
tr { page-break-inside:avoid; page-break-after:auto }
td { page-break-inside:avoid; page-break-after:auto }
thead {
display:table-header-group;
}
tfoot { display:table-footer-group }
}
</style>
</code></pre>
<p><strong>It didn't work at all</strong>, and I try playing with (<code>page-break-before</code>, <code>page-break-after</code>, <code>page-break-inside</code>) and also nothing happen </p>
|
[
{
"answer_id": 74625229,
"author": "Ali Mir",
"author_id": 10262756,
"author_profile": "https://Stackoverflow.com/users/10262756",
"pm_score": -1,
"selected": false,
"text": ".element {\n position: fixed; \n top: 0; \n left: 0;\n width 100%\n}\n"
},
{
"answer_id": 74625235,
"author": "Grizou",
"author_id": 20068386,
"author_profile": "https://Stackoverflow.com/users/20068386",
"pm_score": -1,
"selected": false,
"text": "position:sticky position: fixed position: absolute"
},
{
"answer_id": 74625274,
"author": "PirateNahid",
"author_id": 20126655,
"author_profile": "https://Stackoverflow.com/users/20126655",
"pm_score": 0,
"selected": false,
"text": "position: absolute; position: fixed; h1{\nposition: fixed;\nfont-family: 'open-sans';\ncolor: white;\nfont-size: 16px;\nbackground-color: black;\ntop: 0;}\n background-color"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18460115/"
] |
74,625,202
|
<p>How can I use the value from one query into the second one. I tried with an alias "papa" but I read that the order of executions makes the alias not available to the second query.</p>
<p>What would be the appropriate way of achieving something like below ?</p>
<pre><code>select id, name, parent_id as papa, (select name from people where id = papa)
from people;
</code></pre>
|
[
{
"answer_id": 74625244,
"author": "kutschkem",
"author_id": 1319284,
"author_profile": "https://Stackoverflow.com/users/1319284",
"pm_score": 0,
"selected": false,
"text": "select id, name, papa, (select name from people where id = papa)\nfrom (select id, name, parent_id as papa people);\n"
},
{
"answer_id": 74625252,
"author": "a_horse_with_no_name",
"author_id": 330315,
"author_profile": "https://Stackoverflow.com/users/330315",
"pm_score": 3,
"selected": true,
"text": "select p.id, \n p.name, \n p.parent_id as papa_id,\n papa.name as papa_name\nfrom people p\n left join people papa on p.parent_id = papa.id\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625202",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3114664/"
] |
74,625,291
|
<p>I notice that the root element in any XAML file (in WPF) seems to be one of:</p>
<ul>
<li><code>Window</code></li>
<li><code>Page</code></li>
<li><code>UserControl</code></li>
<li><code>ResourceDictionary</code></li>
<li><code>Application</code></li>
</ul>
<p>I tried to change the root element to <code>local:MainWindow</code>, but then the project cannot compile, saying the base class of a partial class should be the same. Then I guess the root element is the base class of the actual class? What is the reason for it? Since the root element cannot be changed to the actual class, I cannot access the dependency properties written in <code>MainWindow.xaml.cs</code>. How can those DPs be referenced in XAML?</p>
<p>Besides, I also notice that some third-party themes also provide special window classes, and in that case, the root element is often changed. How is this being achieved? E.g. <a href="https://ghost1372.github.io/handycontrol/extend_controls/glowWindow/" rel="nofollow noreferrer">GlowWindow from HandyControl</a></p>
|
[
{
"answer_id": 74625656,
"author": "thatguy",
"author_id": 6181599,
"author_profile": "https://Stackoverflow.com/users/6181599",
"pm_score": 2,
"selected": false,
"text": "x:Class x:Class x:Subclass x:ClassModifier x:Class x:Class x:Class Binding RelativeSource MainWindow AncestorType {Binding YourDependencyProperty, RelativeSource={RelativeSource AncestorType={x:Type local:MainWindow}}}\n x:Name ElementName <Window ...\n x:Name=\"MyMainWindow\">\n {Binding YourDependencyProperty, ElementName=MyMainWindow}\n GlowWindow MainWindow x:Class Window GlowWindow MainWindow Window GlowWindow MainWindow"
},
{
"answer_id": 74630871,
"author": "EldHasp",
"author_id": 13349759,
"author_profile": "https://Stackoverflow.com/users/13349759",
"pm_score": 1,
"selected": false,
"text": " public class MainWindowBase : Window\n {\n public int SomeProperty\n {\n get { return (int)GetValue(SomePropertyProperty); }\n set { SetValue(SomePropertyProperty, value); }\n }\n\n public static readonly DependencyProperty SomePropertyProperty =\n DependencyProperty.Register(\"SomeProperty\", typeof(int), typeof(MainWindowBase), new PropertyMetadata(0));\n }\n\n public partial class MainWindow : MainWindowBase\n {\n public MainWindow()\n {\n InitializeComponent();\n <local:MainWindowBase x:Class=\"****.MainWindow\"\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10150864/"
] |
74,625,294
|
<p>This is my code now:</p>
<pre><code>def extract_categories(line: str):
new_line = re.sub('[ +++$+++]', '', line)
newer_line
print(new_line)
</code></pre>
<p>I want it to print this</p>
<pre><code>['action', 'comedy', 'crime', 'drama', 'thriller']
</code></pre>
<p>but it prints this:</p>
<pre><code>m448hrs.19826.9022289['action','comedy','crime','drama','thriller']
</code></pre>
<p>This is the input I am using:</p>
<pre><code>"m4 +++$+++ 48 hrs. +++$+++ 1982 +++$+++ 6.90 +++$+++ 22289 +++$+++ ['action', 'comedy', 'crime', 'drama', 'thriller']"
</code></pre>
<p>I need the first part removed, I tried removing exactly 'm448hrs.19826.9022289' but then also the m's from 'crime' and 'drama' disappeared, what should I do here? Im new to python so any help would be appreciated.</p>
|
[
{
"answer_id": 74625656,
"author": "thatguy",
"author_id": 6181599,
"author_profile": "https://Stackoverflow.com/users/6181599",
"pm_score": 2,
"selected": false,
"text": "x:Class x:Class x:Subclass x:ClassModifier x:Class x:Class x:Class Binding RelativeSource MainWindow AncestorType {Binding YourDependencyProperty, RelativeSource={RelativeSource AncestorType={x:Type local:MainWindow}}}\n x:Name ElementName <Window ...\n x:Name=\"MyMainWindow\">\n {Binding YourDependencyProperty, ElementName=MyMainWindow}\n GlowWindow MainWindow x:Class Window GlowWindow MainWindow Window GlowWindow MainWindow"
},
{
"answer_id": 74630871,
"author": "EldHasp",
"author_id": 13349759,
"author_profile": "https://Stackoverflow.com/users/13349759",
"pm_score": 1,
"selected": false,
"text": " public class MainWindowBase : Window\n {\n public int SomeProperty\n {\n get { return (int)GetValue(SomePropertyProperty); }\n set { SetValue(SomePropertyProperty, value); }\n }\n\n public static readonly DependencyProperty SomePropertyProperty =\n DependencyProperty.Register(\"SomeProperty\", typeof(int), typeof(MainWindowBase), new PropertyMetadata(0));\n }\n\n public partial class MainWindow : MainWindowBase\n {\n public MainWindow()\n {\n InitializeComponent();\n <local:MainWindowBase x:Class=\"****.MainWindow\"\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20323201/"
] |
74,625,332
|
<p>I'm running a simple matlab code via linux terminal with the following command:</p>
<pre><code>% matlab_example_file.m
a = 5;
b = a*a;
c = a*a*a;
d = sqrt(a);
fprintf('%4u square equals %4u \r', a, b)
fprintf('%4u cube equals %4u \r', a, c)
fprintf('The square root of %2u is %6.4f \r', a, d)
</code></pre>
<pre><code>matlab2021a -nodesktop -nosplash -nodisplay -r "run('/path/to/matlab_file/matlab_example_file.m');exit;"
</code></pre>
<p>However, the output in the terminal disappears once the matlab code is executed. Also I only get the last <code>fprintf</code> output on terminal no the entire outputs as expected from the script (which is not the case if I use the matlab GUI).</p>
<p>Can someone comment what am I doing wrong here?</p>
|
[
{
"answer_id": 74639554,
"author": "X Zhang",
"author_id": 1321247,
"author_profile": "https://Stackoverflow.com/users/1321247",
"pm_score": 3,
"selected": true,
"text": "\\r \\n a = 5;\nb = a*a;\nc = a*a*a;\nd = sqrt(a);\nfprintf('%4u square equals %4u \\n', a, b)\nfprintf('%4u cube equals %4u \\n', a, c)\nfprintf('The square root of %2u is %6.4f \\n', a, d)\n \\r \\n"
},
{
"answer_id": 74639624,
"author": "D P",
"author_id": 20622893,
"author_profile": "https://Stackoverflow.com/users/20622893",
"pm_score": 1,
"selected": false,
"text": "matlab -r -nodisplay -nojvm ' \n'myfunction(argument1,argument2)';\n -nodisplay -nojvm matlab -r -nodesktop -nojvm \n'myfunction(argument1,argument2)';\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8547163/"
] |
74,625,339
|
<p>I have an array of objects in my company collection holding grouped values as follows:</p>
<pre><code>"groups" : [
{
"id" : "d278c44333",
"name" : "group 1"
}
],
</code></pre>
<p>so in mongoDB it would be <code>company > groups > 0 > id or name</code></p>
<p>I want to project all of the documents that have the groups array of objects and retrieve the name.</p>
<p>How can I do that?</p>
<p>Here is what i tried:</p>
<pre><code>db.getCollection("Company").aggregate([
{
$match: {
"companyID": "323452343",
}
},
{
$project: {
//this only projects groupName with an array with 0 elements inside.
groupName: "$groups.0.name"
}
}
])
</code></pre>
<p>EDIT:</p>
<p>expected result:</p>
<p><a href="https://i.stack.imgur.com/iYqNf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iYqNf.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74625562,
"author": "nimrod serok",
"author_id": 18482310,
"author_profile": "https://Stackoverflow.com/users/18482310",
"pm_score": 1,
"selected": false,
"text": "db.collection.aggregate([\n {\n $project: {\n groupName: {\n $first: \"$groups.name\"\n }\n }\n }\n])\n db.collection.aggregate([\n {\n $project: {\n groupName: {\n $arrayElemAt: [\"$groups.name\", 0]\n }\n }\n }\n])\n"
},
{
"answer_id": 74637263,
"author": "ojsl",
"author_id": 20231084,
"author_profile": "https://Stackoverflow.com/users/20231084",
"pm_score": 0,
"selected": false,
"text": "$arrayElemAt db.getCollection(\"Comapny\").aggregate([\n \n {\n $match: { \n \"companyID\": \"123456789\",\n \n \n }\n },\n \n {\n $sort: { _updated_at: -1 }\n },\n \n {\n $project: { \n _id: \"$_id\",\n \n groups: {$arrayElemAt: [ \"$groups.name\", 0 ] }, \n\n }\n \n }\n\n])\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20231084/"
] |
74,625,416
|
<p>Here's an example of inheritance in Kotlin:</p>
<pre class="lang-kotlin prettyprint-override"><code>abstract class Animal(val size: Int)
class Dog(val cuteness: Int): Animal(345)
var dog: Dog = Dog(10)
var animal: Animal = dog
var x = 0
...
</code></pre>
<p>If you put a breakpoint on the last line, the variable <code>animal</code> will be set to the instance of <code>dog</code>. However, you can only access the <code>size</code> member in Animal. You can't access the <code>cuteness</code> member in Dog. But Android Studio's debugger still lets you see the value of the cuteness member in the <code>animal</code> variable.</p>
<p>Is there a way in code to access those hidden members? I don't think there is. I think that Android Studio knows what they are and shows them to you for debugging purposes, but because they are not accessible through Kotlin, it will prevent you from actually accessing them in code. Maybe I'm wrong?</p>
|
[
{
"answer_id": 74625819,
"author": "ERTUGRUL KOC",
"author_id": 11577746,
"author_profile": "https://Stackoverflow.com/users/11577746",
"pm_score": 0,
"selected": false,
"text": "(animal as Dog).cuteness\n"
},
{
"answer_id": 74625967,
"author": "z.y",
"author_id": 19023745,
"author_profile": "https://Stackoverflow.com/users/19023745",
"pm_score": 0,
"selected": false,
"text": "Animal cuteness abstract class Animal(val size: Int, open val cuteness: Int)\n\nclass Dog(override val cuteness: Int): Animal(345, cuteness)\n\n Dog Animal cuteness animal.cuteness\n Dog"
},
{
"answer_id": 74626031,
"author": "providerZ",
"author_id": 20457753,
"author_profile": "https://Stackoverflow.com/users/20457753",
"pm_score": 2,
"selected": false,
"text": " val dog: Dog = Dog(10)\n val animal: Animal = dog\n\n println(animal.size)\n println((animal as Dog).cuteness)\n"
},
{
"answer_id": 74626285,
"author": "MoCoding",
"author_id": 11617754,
"author_profile": "https://Stackoverflow.com/users/11617754",
"pm_score": 3,
"selected": true,
"text": "Animal Animal Dog Dog Animal Animal Dog as (animal as Dog).cuteness\n Animal Dog as? Dog? null val safeDog: Dog? = (animal as? Dog)\nsafeDog?.cuteness\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/753632/"
] |
74,625,424
|
<pre><code>num = 0
def calculate1(player1, num):
if player1 == 1:
num = num + player1
print(f"The number is {num}")
return (num)
elif player1 == 2:
num = num + player1
print(f"The number is {num}")
return (num)
elif player1 == 3:
num = num + player1
print(f"The number is {num}")
return (num)
else:
#yrn = yes or no
yrn = input("Are you going to play game? (Y/N) : ").upper()
if yrn == "Y":
player1 = int(input("How many numbers are you going to add? : "))
num = calculate1(player1, num)
</code></pre>
<p>I want to make that if I type more than 3, the programme ask one more time to reenter the number. Please help meeeee</p>
|
[
{
"answer_id": 74625819,
"author": "ERTUGRUL KOC",
"author_id": 11577746,
"author_profile": "https://Stackoverflow.com/users/11577746",
"pm_score": 0,
"selected": false,
"text": "(animal as Dog).cuteness\n"
},
{
"answer_id": 74625967,
"author": "z.y",
"author_id": 19023745,
"author_profile": "https://Stackoverflow.com/users/19023745",
"pm_score": 0,
"selected": false,
"text": "Animal cuteness abstract class Animal(val size: Int, open val cuteness: Int)\n\nclass Dog(override val cuteness: Int): Animal(345, cuteness)\n\n Dog Animal cuteness animal.cuteness\n Dog"
},
{
"answer_id": 74626031,
"author": "providerZ",
"author_id": 20457753,
"author_profile": "https://Stackoverflow.com/users/20457753",
"pm_score": 2,
"selected": false,
"text": " val dog: Dog = Dog(10)\n val animal: Animal = dog\n\n println(animal.size)\n println((animal as Dog).cuteness)\n"
},
{
"answer_id": 74626285,
"author": "MoCoding",
"author_id": 11617754,
"author_profile": "https://Stackoverflow.com/users/11617754",
"pm_score": 3,
"selected": true,
"text": "Animal Animal Dog Dog Animal Animal Dog as (animal as Dog).cuteness\n Animal Dog as? Dog? null val safeDog: Dog? = (animal as? Dog)\nsafeDog?.cuteness\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20634715/"
] |
74,625,442
|
<p>When do we put ( ) in export function in JavaScript?
like what is the difference between these code:</p>
<pre><code>function Hello() {
return "Hello World"
}
export Hello
</code></pre>
<p>and</p>
<pre><code>function Hello() {
return "Hello World"
}
export Hello()
</code></pre>
|
[
{
"answer_id": 74625567,
"author": "Hiếu Nguyễn",
"author_id": 11747527,
"author_profile": "https://Stackoverflow.com/users/11747527",
"pm_score": 0,
"selected": false,
"text": "export { Hello } export default Hello()"
},
{
"answer_id": 74625617,
"author": "Wraithy",
"author_id": 16116506,
"author_profile": "https://Stackoverflow.com/users/16116506",
"pm_score": 3,
"selected": true,
"text": "function Hello() {\n return \"Hello World\"\n}\nexport Hello\n import {Hello} from \"hello.js\"\n\nconsole.log(typeof Hello) // \"function\"\n\nconsole.log(Hello()) // \"Hello World\" \n\n\n function Hello() {\n return \"Hello World\"\n}\nexport Hello()\n Hello function Hello() {\n return \"Hello World\"\n}\nexport default Hello()\n function HelloFc() {\n return \"Hello World\"\n}\nexport const Hello = HelloFc()\n import {Hello} from \"hello.js\"\n\nconsole.log(typeof Hello) // \"string\"\n\nconsole.log(Hello()) // Uncaught TypeError: \"Hello\" is not a function \n\n\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17407727/"
] |
74,625,456
|
<p>I am rendering a table in react using antd</p>
<p>I am trying to show column if the showColumn state is true and hide the column when it is false</p>
<pre><code>const menuColumns = [
{
title: "Date",
dataIndex: "createdAt",
key: "createdAt",
render: (_, { createdAt }) => (
<>
<Moment format="D MMM, YY">{createdAt}</Moment>
</>
),
},
{
title: "Action",
dataIndex: "",
key: "",
className: showColumn ? "show" : "hide",
render: record => (
<>
{!record.kitchen_received ?
<Button type="primary" onClick={() => showModal(record)}>
Delivered
</Button> : <i className='bi-check-lg'></i>}
</>
),
},
];
</code></pre>
|
[
{
"answer_id": 74625638,
"author": "leo",
"author_id": 16552231,
"author_profile": "https://Stackoverflow.com/users/16552231",
"pm_score": 2,
"selected": true,
"text": "menuColumns const menuColumns = [\n {\n title: \"Date\",\n dataIndex: \"createdAt\",\n key: \"createdAt\",\n render: (_, { createdAt }) => (\n <>\n <Moment format=\"D MMM, YY\">{createdAt}</Moment>\n </>\n ),\n },\n (showColumn ? {\n title: \"Action\",\n dataIndex: \"\",\n key: \"\",\n render: record => (\n <>\n {!record.kitchen_received ?\n <Button type=\"primary\" onClick={() => showModal(record)}>\n Delivered\n </Button> : <i className='bi-check-lg'></i>}\n </>\n ),\n } : {})\n];\n classNames hide"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16520980/"
] |
74,625,461
|
<p>Redirect, Navigate and redirect don't work for me</p>
<p>I expect to redirect to the login .
<a href="https://i.stack.imgur.com/76BwK.png" rel="nofollow noreferrer">enter image description here</a></p>
|
[
{
"answer_id": 74625638,
"author": "leo",
"author_id": 16552231,
"author_profile": "https://Stackoverflow.com/users/16552231",
"pm_score": 2,
"selected": true,
"text": "menuColumns const menuColumns = [\n {\n title: \"Date\",\n dataIndex: \"createdAt\",\n key: \"createdAt\",\n render: (_, { createdAt }) => (\n <>\n <Moment format=\"D MMM, YY\">{createdAt}</Moment>\n </>\n ),\n },\n (showColumn ? {\n title: \"Action\",\n dataIndex: \"\",\n key: \"\",\n render: record => (\n <>\n {!record.kitchen_received ?\n <Button type=\"primary\" onClick={() => showModal(record)}>\n Delivered\n </Button> : <i className='bi-check-lg'></i>}\n </>\n ),\n } : {})\n];\n classNames hide"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19916813/"
] |
74,625,495
|
<p>I have a URL and when I send a request by curl, I get a big output.</p>
<pre><code>curl https://www.aparat.com/video/video/embed/videohash/lXhkG/vt/frame -H "Accept: application/json" -s
</code></pre>
<p>I get: <a href="https://pastebin.mozilla.org/QM6FN8MZ#L" rel="nofollow noreferrer">https://pastebin.mozilla.org/QM6FN8MZ#L</a></p>
<p>But I just want to get the URL of 720p, I mean just:</p>
<pre><code>https:\/\/caspian1.cdn.asset.aparat.com\/aparat-video\/de54245e862b62249b6b7958c734276547445778-720p.apt?wmsAuthSign=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbiI6IjQ2NDJhYmQ4NGFiN2UzNDJkNGMxZWI3ZTNkMzlmZmQ5IiwiZXhwIjoxNjY5ODA5NzI1LCJpc3MiOiJTYWJhIElkZWEgR1NJRyJ9.havkkhJyXjBt_jHPVv4poEVb65_7tRsLIxO5pCO7tGE
</code></pre>
<p>Any idea how to do it?</p>
<p>I'm trying to use grep but I don't know how to remove other things from else 720p URL.</p>
<pre><code>curl https://www.aparat.com/video/video/embed/videohash/lXhkG/vt/frame -H "Accept: application/json" -s | grep -e "720p"
</code></pre>
|
[
{
"answer_id": 74626156,
"author": "Daweo",
"author_id": 10785975,
"author_profile": "https://Stackoverflow.com/users/10785975",
"pm_score": 1,
"selected": true,
"text": "AWK wget --quiet -O - https://www.aparat.com/video/video/embed/videohash/lXhkG/vt/frame | awk 'match($0, /http[^\"]*720[^\"]*/){print substr($0,RSTART,RLENGTH)}'\n https:\\/\\/caspian1.cdn.asset.aparat.com\\/aparat-video\\/de54245e862b62249b6b7958c734276547445778-720p.apt?wmsAuthSign=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbiI6IjY1OTcxYTRkNGZiMjkyYjk0NjM0Mjk2ODVkOTc3YjEwIiwiZXhwIjoxNjY5ODIxNDM2LCJpc3MiOiJTYWJhIElkZWEgR1NJRyJ9.NI2_6nwOxLEOxhWghsR2bOqzrXINXqqscbduHpCWwok\n wget --quiet -O - awk http[^\"]*720[^\"]* http * 720 print match substr 720"
},
{
"answer_id": 74629662,
"author": "Thor",
"author_id": 1331399,
"author_profile": "https://Stackoverflow.com/users/1331399",
"pm_score": 1,
"selected": false,
"text": "curl -s https://www.aparat.com/video/video/embed/videohash/lXhkG/vt/frame |\n\n# Normalize html\nxmlstarlet fo -o -H -R 2> /dev/null |\n\n# Extract relevant js bit\nxmlstarlet sel -t -v '_:html/_:body/_:div/_:script' 2> /dev/null |\n\n# Extract relevant json\nsed -nE '/^ *var +options *= */ { s///; s/;$//p; }' |\n\n# Extract desired url, i.e. the 720p in this case\njq -r '.multiSRC[][] | select( .label == \"720p\" ) | .src'\n"
},
{
"answer_id": 74630680,
"author": "Ed Morton",
"author_id": 1745001,
"author_profile": "https://Stackoverflow.com/users/1745001",
"pm_score": 0,
"selected": false,
"text": "$ cat file | awk 'match($0,/\"https?:\\\\\\/\\\\\\/[^\"]*-720p\\.apt\\?[^\"]*\"/) { print substr($0,RSTART+1,RLENGTH-2) }'\nhttps:\\/\\/caspian1.asset.aparat.com\\/aparat-video\\/de54245e862b62249b6b7958c734276547445778-720p.apt?wmsAuthSign=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbiI6ImViODhjZDNlYzZhYzk3OTBhZDc3MWJhMzIyNWQ3NmZlIiwiZXhwIjoxNjY5ODE4Mjc5LCJpc3MiOiJTYWJhIElkZWEgR1NJRyJ9.e6do9Ha9EkDS46NZDoHT2dYHSOezu_TbdGAGblfi2tM\n file cat file curl"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19735495/"
] |
74,625,513
|
<p>I am trying to follow this guide <a href="https://spark.apache.org/docs/latest/quick-start.html" rel="nofollow noreferrer">https://spark.apache.org/docs/latest/quick-start.html</a> (scala). However, I cant complete the last step when I'm supposed to submit the jar file to spark.</p>
<pre><code># Use spark-submit to run your application
$ YOUR_SPARK_HOME/bin/spark-submit \
--class "SimpleApp" \
--master local[4] \
target/scala-2.12/simple-project_2.12-1.0.jar
</code></pre>
<p>I get the following exception</p>
<pre><code>
Exception in thread "main" java.lang.BootstrapMethodError: java.lang.NoClassDefFoundError: scala/Serializable
at SimpleApp$.main(SimpleApp.scala:9)
at SimpleApp.main(SimpleApp.scala)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.spark.deploy.JavaMainApplication.start(SparkApplication.scala:52)
at org.apache.spark.deploy.SparkSubmit.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:958)
at org.apache.spark.deploy.SparkSubmit.doRunMain$1(SparkSubmit.scala:180)
at org.apache.spark.deploy.SparkSubmit.submit(SparkSubmit.scala:203)
at org.apache.spark.deploy.SparkSubmit.doSubmit(SparkSubmit.scala:90)
at org.apache.spark.deploy.SparkSubmit$$anon$2.doSubmit(SparkSubmit.scala:1046)
at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:1055)
at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
Caused by: java.lang.NoClassDefFoundError: scala/Serializable
... 14 more
Caused by: java.lang.ClassNotFoundException: scala.Serializable
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 14 more
</code></pre>
<p>Any idea what is causing this?</p>
|
[
{
"answer_id": 74626156,
"author": "Daweo",
"author_id": 10785975,
"author_profile": "https://Stackoverflow.com/users/10785975",
"pm_score": 1,
"selected": true,
"text": "AWK wget --quiet -O - https://www.aparat.com/video/video/embed/videohash/lXhkG/vt/frame | awk 'match($0, /http[^\"]*720[^\"]*/){print substr($0,RSTART,RLENGTH)}'\n https:\\/\\/caspian1.cdn.asset.aparat.com\\/aparat-video\\/de54245e862b62249b6b7958c734276547445778-720p.apt?wmsAuthSign=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbiI6IjY1OTcxYTRkNGZiMjkyYjk0NjM0Mjk2ODVkOTc3YjEwIiwiZXhwIjoxNjY5ODIxNDM2LCJpc3MiOiJTYWJhIElkZWEgR1NJRyJ9.NI2_6nwOxLEOxhWghsR2bOqzrXINXqqscbduHpCWwok\n wget --quiet -O - awk http[^\"]*720[^\"]* http * 720 print match substr 720"
},
{
"answer_id": 74629662,
"author": "Thor",
"author_id": 1331399,
"author_profile": "https://Stackoverflow.com/users/1331399",
"pm_score": 1,
"selected": false,
"text": "curl -s https://www.aparat.com/video/video/embed/videohash/lXhkG/vt/frame |\n\n# Normalize html\nxmlstarlet fo -o -H -R 2> /dev/null |\n\n# Extract relevant js bit\nxmlstarlet sel -t -v '_:html/_:body/_:div/_:script' 2> /dev/null |\n\n# Extract relevant json\nsed -nE '/^ *var +options *= */ { s///; s/;$//p; }' |\n\n# Extract desired url, i.e. the 720p in this case\njq -r '.multiSRC[][] | select( .label == \"720p\" ) | .src'\n"
},
{
"answer_id": 74630680,
"author": "Ed Morton",
"author_id": 1745001,
"author_profile": "https://Stackoverflow.com/users/1745001",
"pm_score": 0,
"selected": false,
"text": "$ cat file | awk 'match($0,/\"https?:\\\\\\/\\\\\\/[^\"]*-720p\\.apt\\?[^\"]*\"/) { print substr($0,RSTART+1,RLENGTH-2) }'\nhttps:\\/\\/caspian1.asset.aparat.com\\/aparat-video\\/de54245e862b62249b6b7958c734276547445778-720p.apt?wmsAuthSign=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbiI6ImViODhjZDNlYzZhYzk3OTBhZDc3MWJhMzIyNWQ3NmZlIiwiZXhwIjoxNjY5ODE4Mjc5LCJpc3MiOiJTYWJhIElkZWEgR1NJRyJ9.e6do9Ha9EkDS46NZDoHT2dYHSOezu_TbdGAGblfi2tM\n file cat file curl"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20643608/"
] |
74,625,527
|
<p>I have DTOs like this</p>
<pre><code>public class Obj1
{
public string a1 { get; set; };
public Obj2[] a2 { get; set; };
}
public class Obj2
{
public string b1 { get; set; };
public Obj3[] b2 { get; set; };
}
public class Obj3
{
public string Key { get; set; };
}
</code></pre>
<p>So, the object will be like</p>
<pre><code>Obj1 o = new Obj1
{
a1="a";
a2=new[]
{
new Obj2
{
b1="b";
b2=new[]
{
new Obj3
{
Key="c";
}
}
}
}
}
</code></pre>
<p>I have Obj1. How can I group it in the form of dictionary of type</p>
<pre><code>IDictionary<string, IEnumerable<Obj2>>
</code></pre>
<p>where Key is in Obj3.</p>
<p>I tried using GroupBy but did not get the relevant result.</p>
|
[
{
"answer_id": 74626046,
"author": "Guru Stron",
"author_id": 2501279,
"author_profile": "https://Stackoverflow.com/users/2501279",
"pm_score": 1,
"selected": false,
"text": "Obj2 Obj3.Key SelectMany GroupBy var dictionary = o.a2\n .SelectMany(o2 => o2.b3.Select(o3 => (o3.Key, o2)))\n .GroupBy(t => t.Key)\n .ToDictionary(g => g.Key, g => g.ToList());\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20183252/"
] |
74,625,531
|
<pre><code>@charset "UTF-8";
/* import the basis style page */
@import url("body.css");
/* why is this not working? */
/* import alternative style 500px */
@media (min-width: 500px){
@import url("screen_layout_small.css");
}
</code></pre>
<p>The screen_layout_small.css file contains :</p>
<pre><code>@charset "UTF-8";
body {
background-color: red;
}
</code></pre>
<p>The url "screen_layout_small.css" works when it is not in a @media (works when it is not in a responsive command ?)</p>
<p>I tryed to load it when width >= 500px but it doesn't work.</p>
<p>By the way it does not mather if I use min-with or max-with, the file does not load in the @media.</p>
|
[
{
"answer_id": 74626046,
"author": "Guru Stron",
"author_id": 2501279,
"author_profile": "https://Stackoverflow.com/users/2501279",
"pm_score": 1,
"selected": false,
"text": "Obj2 Obj3.Key SelectMany GroupBy var dictionary = o.a2\n .SelectMany(o2 => o2.b3.Select(o3 => (o3.Key, o2)))\n .GroupBy(t => t.Key)\n .ToDictionary(g => g.Key, g => g.ToList());\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17570498/"
] |
74,625,532
|
<p>I want to get first longest string ? How can i do this ?</p>
<pre><code>List<String> list = ['hi', 'hello', 'frozen', 'big mistake', 'cool daddy'];
</code></pre>
|
[
{
"answer_id": 74625606,
"author": "Ashkan Sarlak",
"author_id": 2511775,
"author_profile": "https://Stackoverflow.com/users/2511775",
"pm_score": -1,
"selected": false,
"text": "final longestString = list.fold<String>('', \n (previousValue, element) => \n element.length > previousValue.length ? element : previousValue)\n"
},
{
"answer_id": 74625653,
"author": "Minato",
"author_id": 9977565,
"author_profile": "https://Stackoverflow.com/users/9977565",
"pm_score": 1,
"selected": false,
"text": "long_string(arr) {\n var longest = arr[0];\n for (var i = 1; i < arr.length; i++) {\n if (arr[i].length > longest.length) {\n longest = arr[i];\n }\n }\n return longest;\n }\n var arr = [\"Orebro\", \"Sundsvall\", \"Hudriksvall\", \"Goteborgsdsdsds\"];\n print(long_string(arr));\n"
},
{
"answer_id": 74625729,
"author": "Sparko Sol",
"author_id": 20407048,
"author_profile": "https://Stackoverflow.com/users/20407048",
"pm_score": 4,
"selected": true,
"text": "list.reduce((a, b) {\n return a.length > b.length ? a : b;\n})\n list.sort((a, b) {\n return b.length - a.length;\n});\nprint(list[0]);\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4659987/"
] |
74,625,535
|
<p>I'm concatenating three tuples from a csv but i´m thinking if there is any way to do it with a maximum lenght.
I´m doing this:</p>
<pre><code>df = pd.read_csv(FILE_NAME, header = 0)
df['all'] = df['Header'] + df['Subtitle'] + df['Text']
</code></pre>
<p>I want df['all] to be at most 500 characters</p>
<p>Thank you in advice</p>
|
[
{
"answer_id": 74625606,
"author": "Ashkan Sarlak",
"author_id": 2511775,
"author_profile": "https://Stackoverflow.com/users/2511775",
"pm_score": -1,
"selected": false,
"text": "final longestString = list.fold<String>('', \n (previousValue, element) => \n element.length > previousValue.length ? element : previousValue)\n"
},
{
"answer_id": 74625653,
"author": "Minato",
"author_id": 9977565,
"author_profile": "https://Stackoverflow.com/users/9977565",
"pm_score": 1,
"selected": false,
"text": "long_string(arr) {\n var longest = arr[0];\n for (var i = 1; i < arr.length; i++) {\n if (arr[i].length > longest.length) {\n longest = arr[i];\n }\n }\n return longest;\n }\n var arr = [\"Orebro\", \"Sundsvall\", \"Hudriksvall\", \"Goteborgsdsdsds\"];\n print(long_string(arr));\n"
},
{
"answer_id": 74625729,
"author": "Sparko Sol",
"author_id": 20407048,
"author_profile": "https://Stackoverflow.com/users/20407048",
"pm_score": 4,
"selected": true,
"text": "list.reduce((a, b) {\n return a.length > b.length ? a : b;\n})\n list.sort((a, b) {\n return b.length - a.length;\n});\nprint(list[0]);\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18466776/"
] |
74,625,572
|
<p>I have a JPA specification that needs to be split up in two, but also support backend pagination. I am unsure how to accomplish this.</p>
<p>For example, I have Employess that can be of two types Teachers and Carers. I need to perform a filtered search (the exact search) on both and return a single unionized response, that can support pagination. Although I know how to perform the two requests, I don't know how to process the pagination when combining JPA specifications. Any hints?</p>
<pre><code>class EmployeeEntity {
private Long id;
private EmployeeType type;
private String name;
}
</code></pre>
|
[
{
"answer_id": 74625606,
"author": "Ashkan Sarlak",
"author_id": 2511775,
"author_profile": "https://Stackoverflow.com/users/2511775",
"pm_score": -1,
"selected": false,
"text": "final longestString = list.fold<String>('', \n (previousValue, element) => \n element.length > previousValue.length ? element : previousValue)\n"
},
{
"answer_id": 74625653,
"author": "Minato",
"author_id": 9977565,
"author_profile": "https://Stackoverflow.com/users/9977565",
"pm_score": 1,
"selected": false,
"text": "long_string(arr) {\n var longest = arr[0];\n for (var i = 1; i < arr.length; i++) {\n if (arr[i].length > longest.length) {\n longest = arr[i];\n }\n }\n return longest;\n }\n var arr = [\"Orebro\", \"Sundsvall\", \"Hudriksvall\", \"Goteborgsdsdsds\"];\n print(long_string(arr));\n"
},
{
"answer_id": 74625729,
"author": "Sparko Sol",
"author_id": 20407048,
"author_profile": "https://Stackoverflow.com/users/20407048",
"pm_score": 4,
"selected": true,
"text": "list.reduce((a, b) {\n return a.length > b.length ? a : b;\n})\n list.sort((a, b) {\n return b.length - a.length;\n});\nprint(list[0]);\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2449161/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.