qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,342,783 | <p>Column can also have listview.builder, if the column builds all of its children at a time, does it build listview items at once too?</p>
| [
{
"answer_id": 74342861,
"author": "Delwinn",
"author_id": 16714498,
"author_profile": "https://Stackoverflow.com/users/16714498",
"pm_score": 1,
"selected": false,
"text": "Column"
},
{
"answer_id": 74342872,
"author": "Nguyen family",
"author_id": 19992458,
"author_profile": "https://Stackoverflow.com/users/19992458",
"pm_score": 0,
"selected": false,
"text": "ListView"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74342783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4483891/"
] |
74,342,788 | <p>I want to make a function with loop and conditional, that count only when Actual Result = 1.
So the numbers always increase by 1 if the Actual Result = 1.</p>
<p>This is my dataframe:</p>
<p><img src="https://i.stack.imgur.com/HSoek.png" alt="enter image description here" /></p>
<p>This is my code but it doesnt produce the result that i want :</p>
<pre><code>def func_count(x):
for i in range(1,880):
if x['Actual Result']==1:
result = i
else:
result = '-'
return result
X_machine_learning['Count'] = X_machine_learning.apply(lambda x:func_count(x),axis=1)
</code></pre>
<p>When i check & filter with count != '-' The result will be like this :</p>
<p><img src="https://i.stack.imgur.com/mhprm.png" alt="enter image description here" /></p>
<p>The number always equal to 1 and not increase by 1 everytime the actual result = 1. Any solution?</p>
| [
{
"answer_id": 74342861,
"author": "Delwinn",
"author_id": 16714498,
"author_profile": "https://Stackoverflow.com/users/16714498",
"pm_score": 1,
"selected": false,
"text": "Column"
},
{
"answer_id": 74342872,
"author": "Nguyen family",
"author_id": 19992458,
"author_profile": "https://Stackoverflow.com/users/19992458",
"pm_score": 0,
"selected": false,
"text": "ListView"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74342788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20236488/"
] |
74,342,795 | <p>We use Firestore for our DB and use Vercel's Next.js hosting. We wanted a completely isolated development / production DBs, so we set up two separate projects on Firebase, and this gave us two different API keys for each of the projects.</p>
<p>What is the best way to switch between the two configs depending on the Vercel's production / preview / development settings (perhaps based on <code>NEXT_PUBLIC_VERCEL_ENV</code>)?</p>
<p>We tried creating two different .json files containing the configs, and switching based on the <code>NEXT_PUBLIC_VERCEL_ENV </code> environment variable, but this seems to yield an <code>undefined</code> value for the environment variable on the client rendered pages in my local development build.</p>
<pre><code>const firebaseDevConfig = await import("./configs/dev-config.json");
const firebaseProdConfig = await import("./configs/prod-config.json");
const firebaseConfig =
process.env.NEXT_PUBLIC_VERCEL_ENV === "production"
? firebaseProdConfig
: firebaseDevConfig;
</code></pre>
<p>Update: It seems that the <code>NEXT_PUBLIC_VERCEL_ENV</code> returns the expected value <code>"preview"</code> in the deployed preview version. How do I get it to return "development" in my local dev build?</p>
| [
{
"answer_id": 74342861,
"author": "Delwinn",
"author_id": 16714498,
"author_profile": "https://Stackoverflow.com/users/16714498",
"pm_score": 1,
"selected": false,
"text": "Column"
},
{
"answer_id": 74342872,
"author": "Nguyen family",
"author_id": 19992458,
"author_profile": "https://Stackoverflow.com/users/19992458",
"pm_score": 0,
"selected": false,
"text": "ListView"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74342795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1584032/"
] |
74,342,823 | <p>I have json file something looks like as below and I want to convert this json file into csv file.
When I run the code, it gives me value error.
Can someone please let me know how to convert below json into csv?</p>
<pre><code>[{"VESSEL_NO":"99999","SYSTEM_NAME":"ANEMOMETER","SYSTEM_INSTANCE":"1","EVENT_TIME":"2022-03-05 00:00:00.000","DATA":"{\"/TRUE_WIND_DIRECTION\" : 350.1, \"/TRUE_WIND_SPEED\":22.9}"},{"VESSEL_NO":"99999","SYSTEM_NAME":"ANEMOMETER","SYSTEM_INSTANCE":"1","EVENT_TIME":"2022-03-04 23:59:30.000","DATA":"{\"/TRUE_WIND_DIRECTION\" : 351.4, \"/TRUE_WIND_SPEED\" : 25.85}"},{"VESSEL_NO":"99999","SYSTEM_NAME":"ANEMOMETER","SYSTEM_INSTANCE":"1","EVENT_TIME":"2022-03-04 23:59:00.000","DATA":"{\"/TRUE_WIND_DIRECTION\" : 354.5, \"/TRUE_WIND_SPEED\" : 24.3}"},{"VESSEL_NO":"99999","SYSTEM_NAME":"ANEMOMETER","SYSTEM_INSTANCE":"1","EVENT_TIME":"2022-03-04 23:58:30.000","DATA":"{\"/TRUE_WIND_DIRECTION\" : 351.9, \"/TRUE_WIND_SPEED\" : 23.1}"},{"VESSEL_NO":"99999","SYSTEM_NAME":"ANEMOMETER","SYSTEM_INSTANCE":"1","EVENT_TIME":"2022-03-04 23:58:00.000","DATA":"{\"/TRUE_WIND_DIRECTION\" : 354.1, \"/TRUE_WIND_SPEED\" : 24.9}"},{"VESSEL_NO":"99999","SYSTEM_NAME":"ANEMOMETER","SYSTEM_INSTANCE":"1","EVENT_TIME":"2022-03-04 23:57:30.000","DATA":"{\"/TRUE_WIND_DIRECTION\" : 4.7, \"/TRUE_WIND_SPEED\" : 21.4}"},{"VESSEL_NO":"99999","SYSTEM_NAME":"ANEMOMETER","SYSTEM_INSTANCE":"1","EVENT_TIME":"2022-03-04 23:57:00.000","DATA":"{\"/TRUE_WIND_DIRECTION\" : 3.4, \"/TRUE_WIND_SPEED\" : 22.4}"},{"VESSEL_NO":"99999","SYSTEM_NAME":"ANEMOMETER","SYSTEM_INSTANCE":"1","EVENT_TIME":"2022-03-04 23:56:30.000","DATA":"{\"/TRUE_WIND_DIRECTION\" : 358.1, \"/TRUE_WIND_SPEED\" : 25.3}"}]
import pandas as pd
df = pd.read_json('data.json')
ValueError: Expected object or value
</code></pre>
| [
{
"answer_id": 74342858,
"author": "Faisal Nazik",
"author_id": 13959139,
"author_profile": "https://Stackoverflow.com/users/13959139",
"pm_score": 1,
"selected": false,
"text": "read_json()"
},
{
"answer_id": 74343004,
"author": "Bushmaster",
"author_id": 15415267,
"author_profile": "https://Stackoverflow.com/users/15415267",
"pm_score": 0,
"selected": false,
"text": "import json\nimport ast\n\nwith open ('your_json_file_path') as json_file:\n json = json.load(json_file)\n \ndf=pd.DataFrame(data={'a':json)\ndf=df.join(df['a'].apply(pd.Series)).drop(['a'],axis=1).drop_duplicates()\n\ndf['DATA']=df['DATA'].apply(ast.literal_eval)\ndf=df.join(pd.json_normalize(df.pop('DATA')))\ndf\n\n VESSEL_NO SYSTEM_NAME SYSTEM_INSTANCE EVENT_TIME /TRUE_WIND_DIRECTION /TRUE_WIND_SPEED\n0 99999 ANEMOMETER 1 2022-03-05 00:00:00.000 350.1 22.9\n1 99999 ANEMOMETER 1 2022-03-04 23:59:30.000 351.4 25.85\n2 99999 ANEMOMETER 1 2022-03-04 23:59:00.000 354.5 24.3\n3 99999 ANEMOMETER 1 2022-03-04 23:58:30.000 351.9 23.1\n4 99999 ANEMOMETER 1 2022-03-04 23:58:00.000 354.1 24.9\n5 99999 ANEMOMETER 1 2022-03-04 23:57:30.000 4.7 21.4\n6 99999 ANEMOMETER 1 2022-03-04 23:57:00.000 3.4 22.4\n7 99999 ANEMOMETER 1 2022-03-04 23:56:30.000 358.1 25.3\n\n"
},
{
"answer_id": 74343042,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 0,
"selected": false,
"text": "json_normalize"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74342823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15136121/"
] |
74,342,830 | <p>I have strings on similar format</p>
<p><code>hello this is an example [ a b c ]</code></p>
<p><code>hello this is another example [ cat bird dog elephant ]</code></p>
<p>Which I want to transform to</p>
<p><code>hello this is an example [a,b,c]</code></p>
<p><code>hello this is another example [cat,bird,dog,elephant]</code></p>
<p>But I don't understand how to create a regexp pattern that removes any spaces next to the brackets and replaces any number of spaces between words/characters inside the brackets with a single <code>,</code>.</p>
<p>How would one create such a pattern?</p>
<p>My current attempt is a chain of regexp replacements.</p>
<pre><code>m = re.sub('\[\s+','[',s)
m = re.sub('\s+\]',']',m)
m = re.sub('\s+',' ',m)
m = re.sub(r'\s(?=[^\[\]]*])', ",", m)
</code></pre>
<p>But does anyone have any suggestion on how to make it more efficient or more clean?</p>
| [
{
"answer_id": 74343462,
"author": "Rabinzel",
"author_id": 15521392,
"author_profile": "https://Stackoverflow.com/users/15521392",
"pm_score": 1,
"selected": false,
"text": "re.sub"
},
{
"answer_id": 74343496,
"author": "RobertG",
"author_id": 19925522,
"author_profile": "https://Stackoverflow.com/users/19925522",
"pm_score": 1,
"selected": false,
"text": "foo = 'hello this is another example [ cat bird dog elephant ]'\n\n# get everything between [ and ]\nreg_get_between_square_brackets= re.compile(r'\\[(.*)\\]')\nstr_to_replace = reg_get_between_square_brackets.findall(foo)[0]\n\n# replace spaces with coma\nnew_string = re.sub('\\s+', ',', str_to_replace.strip()) # strip to remove beginning/ending white space\nprint(foo.replace(str_to_replace, new_string)) \n"
},
{
"answer_id": 74344305,
"author": "Marcel Preda",
"author_id": 10919370,
"author_profile": "https://Stackoverflow.com/users/10919370",
"pm_score": 0,
"selected": false,
"text": "import re\n\nstr1 = 'hello this is an example [ a b c ]'\n\nstr2 = 'hello this is another example [ cat bird dog elephant ]'\n\n# remove the SPACES near square brackets\nstr1 = re.sub(r'\\[\\s*(.*\\S)\\s*\\]', r'[\\1]', str1)\nprint(str1)\n# replace the SPACES inside the square brackets until no replacement\nold_str1 = ''\nwhile old_str1 != str1:\n old_str1 = str1\n str1 = re.sub(r'\\[(\\S*)\\s+(.*)\\]', r'[\\1,\\2]', str1, count=0)\nprint(str1)\n\n\nstr2 = re.sub(r'\\[\\s*(.*\\S)\\s*\\]', r'[\\1]', str2)\nprint(str2)\nold_str2 = ''\nwhile old_str2 != str2:\n old_str2 = str2\n str2 = re.sub(r'\\[(\\S*)\\s+(.*)\\]', r'[\\1,\\2]', str2, count=0)\nprint(str2)\n"
},
{
"answer_id": 74353977,
"author": "The fourth bird",
"author_id": 5424988,
"author_profile": "https://Stackoverflow.com/users/5424988",
"pm_score": 3,
"selected": true,
"text": "\\[\\s*([^][]*?)\\s*]\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74342830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7791963/"
] |
74,342,888 | <p>I am trying to delete specific lines from text files, Which is basically a java code in txt format. I am trying to delete multi-comments from the text, which means script should read the files and delete multi-comments starting with "/<em>" and end with /</em> along with "\\" , "package", and "import".</p>
<p>I am using this code, it worked last time for me, but now it is not working</p>
<p>Code</p>
<pre><code>import re
import sys
import codecs
txt = "H:\APK_Source_Code_Merged\sstest1.txt"
with open(txt, 'r',encoding= 'utf-8', errors= 'ignore') as fil:
file = fil.read()
wtalc = re.sub(r"//.*?", '', file, flags=re.S)
wtslc = re.sub(r"/*.*?*/", '', wtalc, flags=re.S)
wtblc = re.sub(r"import.*?", '', wtslc, flags=re.S)
wtblc = re.sub(r"package.*?", '', wtslc, flags=re.S)
print(wtblc)
</code></pre>
<p>Basically, it is a txt file. The above code perfectly work fine, if i read and remove certains lines from text string then it works fine. But if I read and remove from file, it does not remove any line at all.
sstest1 = "</p>
<pre><code>package net.youmi.android.b.a.e.c.g;
import net.youmi.android.b.a.e.a.b.g;
import net.youmi.android.b.a.e.a.b.i;
import net.youmi.android.b.a.e.a.b.l;
import org.json.JSONObject;
//asdasbdaiygd
/* loaded from: classes.dex */
public final class a extends l {
/* JADX WARN: Failed to parse debug info
java.lang.IllegalArgumentException: newPosition > limit: (67103403 > 2726956)
at java.base/java.nio.Buffer.createPositionException(Buffer.java:318)
at java.base/java.nio.Buffer.position(Buffer.java:293)
at java.base/java.nio.ByteBuffer.position(ByteBuffer.java:1158)
at java.base/java.nio.ByteBuffer.position(ByteBuffer.java:263)
at jadx.plugins.input.dex.sections.SectionReader.absPos(SectionReader.java:82)
at jadx.plugins.input.dex.sections.debuginfo.DebugInfoParser.process(DebugInfoParser.java:84)
at jadx.plugins.input.dex.sections.DexCodeReader.getDebugInfo(DexCodeReader.java:118)
at jadx.core.dex.nodes.MethodNode.getDebugInfo(MethodNode.java:546)
at jadx.core.dex.visitors.debuginfo.DebugInfoAttachVisitor.visit(DebugInfoAttachVisitor.java:39)
*/
//Override // net.youmi.android.b.a.e.a.b.l
protected JSONObject a(i iVar, g gVar) {
return null;
}
}
</code></pre>
<p>The above script works perfectly fine if I read and remove certain lines from the text string (from the variable). But if I read and remove it from the file, it does not remove any line at all.</p>
| [
{
"answer_id": 74343077,
"author": "Hannon qaoud",
"author_id": 15678119,
"author_profile": "https://Stackoverflow.com/users/15678119",
"pm_score": 1,
"selected": false,
"text": "\".\""
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74342888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19887155/"
] |
74,342,889 | <pre><code>const strPrivateKey = "30820b82020100300d06092a864886f70d010101050004820b6c30820b680201000282028100acfc585f43ca36ec2dddc518b5c7d1303b658faec58b634aff16ce4b7930b93a23517f8d9c8a260f4e2eb44b01da5b6588fefe63acb68c15677"
decoded, err := hex.DecodeString(strPrivateKey)
if err != nil {
return ""
}
privateKey, err := x509.ParsePKCS8PrivateKey(decoded)
if err != nil {
return ""
}
encypt, err := rsa.EncryptPKCS1v15(rand.Reader, &privateKey.PublicKey, data)
if err != nil {
fmt.Println(err)
return ""
}
</code></pre>
<pre class="lang-none prettyprint-override"><code>privateKey.PublicKey undefined (type any has no field or method PublicKey)
</code></pre>
| [
{
"answer_id": 74343942,
"author": "Zeke Lu",
"author_id": 1369400,
"author_profile": "https://Stackoverflow.com/users/1369400",
"pm_score": 1,
"selected": false,
"text": "*rsa.PrivateKey"
},
{
"answer_id": 74440573,
"author": "Temuujin Oyuntsetseg",
"author_id": 20437546,
"author_profile": "https://Stackoverflow.com/users/20437546",
"pm_score": 0,
"selected": false,
"text": "decodedString, err := hex.DecodeString(utility.StrPrivateKey)\nif err != nil {\n return err\n}\npkcs8PrivateKey, err := x509.ParsePKCS8PrivateKey(decodedString)\nif err != nil {\n return err\n}\nprivateKey := pkcs8PrivateKey.(*rsa.PrivateKey)\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74342889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20437546/"
] |
74,342,903 | <p>I want to convert a string to a list and get the length of the list. I have read <a href="https://stackoverflow.com/q/52288553/16124033">this question</a> and quoted <a href="https://stackoverflow.com/a/52288579/16124033">this answer</a>. But there is a problem, when I use <a href="https://stackoverflow.com/a/52288579/16124033">the answer</a>'s code, I can only use the index to get the item, and I can't read the whole list and get the length of the list.</p>
<p>My code:</p>
<pre><code>import 'dart:convert';
…
final String list = '["a", "b", "c", "d"]';
final dynamic final_list = json.decode(list);
print(final_list[0]); // returns "a" in the debug console
</code></pre>
<p>How to convert string to list and get the length of the list? I would appreciate any help. Thank you in advance!</p>
| [
{
"answer_id": 74342968,
"author": "George Lee",
"author_id": 4402233,
"author_profile": "https://Stackoverflow.com/users/4402233",
"pm_score": 0,
"selected": false,
"text": "void main() {\n var string = 'Hello, World!';\n // make string into a list with map\n var list = string.split('').map((char) => char).toList();\n print(list);\n print(list.length);\n}\n"
},
{
"answer_id": 74342991,
"author": "kunj kanani",
"author_id": 11468648,
"author_profile": "https://Stackoverflow.com/users/11468648",
"pm_score": 1,
"selected": false,
"text": "import 'dart:convert';\n\nvoid main() {\n final String list = '[\"a\", \"b\", \"c\", \"d\"]';\n final List<String> finalList = List<String>.from(json.decode(list));\n print(finalList.length.toString());\n}\n"
},
{
"answer_id": 74342995,
"author": "Younss AIT MOU",
"author_id": 11189668,
"author_profile": "https://Stackoverflow.com/users/11189668",
"pm_score": 2,
"selected": true,
"text": "List"
},
{
"answer_id": 74343163,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 1,
"selected": false,
"text": "final String list = '[\"a\", \"b\", \"c\", \"d\"]';\nint _length = (json.decode(list) as List).length;\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74342903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16124033/"
] |
74,342,962 | <p>Below is the screenshot, where the first box is not selected right now, but i want to make it selected when come to first time on this page.</p>
<p>I attached the full expo-link. <a href="https://snack.expo.dev/@john.ocean/bold-cookies" rel="nofollow noreferrer">click-here</a></p>
<p>I want that 'soup' button selected as by-default.</p>
<p>currently it's working like when come to this page, no-one button is selected but after select the data appears on right black area.</p>
<p><a href="https://i.stack.imgur.com/KpBZE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KpBZE.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74342968,
"author": "George Lee",
"author_id": 4402233,
"author_profile": "https://Stackoverflow.com/users/4402233",
"pm_score": 0,
"selected": false,
"text": "void main() {\n var string = 'Hello, World!';\n // make string into a list with map\n var list = string.split('').map((char) => char).toList();\n print(list);\n print(list.length);\n}\n"
},
{
"answer_id": 74342991,
"author": "kunj kanani",
"author_id": 11468648,
"author_profile": "https://Stackoverflow.com/users/11468648",
"pm_score": 1,
"selected": false,
"text": "import 'dart:convert';\n\nvoid main() {\n final String list = '[\"a\", \"b\", \"c\", \"d\"]';\n final List<String> finalList = List<String>.from(json.decode(list));\n print(finalList.length.toString());\n}\n"
},
{
"answer_id": 74342995,
"author": "Younss AIT MOU",
"author_id": 11189668,
"author_profile": "https://Stackoverflow.com/users/11189668",
"pm_score": 2,
"selected": true,
"text": "List"
},
{
"answer_id": 74343163,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 1,
"selected": false,
"text": "final String list = '[\"a\", \"b\", \"c\", \"d\"]';\nint _length = (json.decode(list) as List).length;\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74342962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16241616/"
] |
74,342,990 | <p>I have data like this:</p>
<pre><code>[
{
"category":"Fruits",
"name":"Apple"
},
{
"category":"Fruits",
"name":"Manggo"
},
{
"category":"Vegetables",
"name":"Water Spinach"
}
]
</code></pre>
<p>I want to grouping by java 8, I've tried with :</p>
<pre><code>Map<String, List<MyData>> myData
= list.stream().collect(Collectors.groupingBy(d -> d.getCategory()));
</code></pre>
<p>But the result is not what I need. Because the result I expected was <code>Fruits = 2, Vegetables = 1</code></p>
| [
{
"answer_id": 74342968,
"author": "George Lee",
"author_id": 4402233,
"author_profile": "https://Stackoverflow.com/users/4402233",
"pm_score": 0,
"selected": false,
"text": "void main() {\n var string = 'Hello, World!';\n // make string into a list with map\n var list = string.split('').map((char) => char).toList();\n print(list);\n print(list.length);\n}\n"
},
{
"answer_id": 74342991,
"author": "kunj kanani",
"author_id": 11468648,
"author_profile": "https://Stackoverflow.com/users/11468648",
"pm_score": 1,
"selected": false,
"text": "import 'dart:convert';\n\nvoid main() {\n final String list = '[\"a\", \"b\", \"c\", \"d\"]';\n final List<String> finalList = List<String>.from(json.decode(list));\n print(finalList.length.toString());\n}\n"
},
{
"answer_id": 74342995,
"author": "Younss AIT MOU",
"author_id": 11189668,
"author_profile": "https://Stackoverflow.com/users/11189668",
"pm_score": 2,
"selected": true,
"text": "List"
},
{
"answer_id": 74343163,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 1,
"selected": false,
"text": "final String list = '[\"a\", \"b\", \"c\", \"d\"]';\nint _length = (json.decode(list) as List).length;\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74342990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20406079/"
] |
74,342,996 | <p>If I run laravel on localhost, it shows me only file, how to fix this <a href="https://i.stack.imgur.com/IJfz8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IJfz8.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74342968,
"author": "George Lee",
"author_id": 4402233,
"author_profile": "https://Stackoverflow.com/users/4402233",
"pm_score": 0,
"selected": false,
"text": "void main() {\n var string = 'Hello, World!';\n // make string into a list with map\n var list = string.split('').map((char) => char).toList();\n print(list);\n print(list.length);\n}\n"
},
{
"answer_id": 74342991,
"author": "kunj kanani",
"author_id": 11468648,
"author_profile": "https://Stackoverflow.com/users/11468648",
"pm_score": 1,
"selected": false,
"text": "import 'dart:convert';\n\nvoid main() {\n final String list = '[\"a\", \"b\", \"c\", \"d\"]';\n final List<String> finalList = List<String>.from(json.decode(list));\n print(finalList.length.toString());\n}\n"
},
{
"answer_id": 74342995,
"author": "Younss AIT MOU",
"author_id": 11189668,
"author_profile": "https://Stackoverflow.com/users/11189668",
"pm_score": 2,
"selected": true,
"text": "List"
},
{
"answer_id": 74343163,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 1,
"selected": false,
"text": "final String list = '[\"a\", \"b\", \"c\", \"d\"]';\nint _length = (json.decode(list) as List).length;\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74342996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20067232/"
] |
74,343,024 | <p>I'm trying to do some data cleaning using pandas. Imagine I have a data frame which has a column call "Number" and contains data like: "1203.10", "4221","3452.11", etc. I want to add an "M" before the numbers, which have a point and a zero at the end. For this example, it would be turning the "1203.10" into "M1203.10".</p>
<p>I know how to obtain a data frame containing the numbers with a point and ending with zero.</p>
<p>Suppose the data frame is call "df".</p>
<pre><code>pointzero = '[0-9]+[.][0-9]+[0]$'
pz = df[df.Number.str.match(pointzero)]
</code></pre>
<p>But I'm not sure on how to add the "M" at the beginning after having "pz". The only way I know is using a for loop, but I think there is a better way. Any suggestions would be great!</p>
| [
{
"answer_id": 74342968,
"author": "George Lee",
"author_id": 4402233,
"author_profile": "https://Stackoverflow.com/users/4402233",
"pm_score": 0,
"selected": false,
"text": "void main() {\n var string = 'Hello, World!';\n // make string into a list with map\n var list = string.split('').map((char) => char).toList();\n print(list);\n print(list.length);\n}\n"
},
{
"answer_id": 74342991,
"author": "kunj kanani",
"author_id": 11468648,
"author_profile": "https://Stackoverflow.com/users/11468648",
"pm_score": 1,
"selected": false,
"text": "import 'dart:convert';\n\nvoid main() {\n final String list = '[\"a\", \"b\", \"c\", \"d\"]';\n final List<String> finalList = List<String>.from(json.decode(list));\n print(finalList.length.toString());\n}\n"
},
{
"answer_id": 74342995,
"author": "Younss AIT MOU",
"author_id": 11189668,
"author_profile": "https://Stackoverflow.com/users/11189668",
"pm_score": 2,
"selected": true,
"text": "List"
},
{
"answer_id": 74343163,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 1,
"selected": false,
"text": "final String list = '[\"a\", \"b\", \"c\", \"d\"]';\nint _length = (json.decode(list) as List).length;\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12848857/"
] |
74,343,043 | <p>I am building a simple game in react. The problem is context is properly updated but the context value inside an event listener function is not updating. If I access the value outside the event function then the new updated value is rendered.</p>
<p>For the first keyup event the value will be 0 but for the next events, it should be a new updated value.</p>
<pre><code> const updateGame = useUpdateGame();
const gameData = useGameData();
//Assume Default gameData.board value is 0
// Assume context value updated to 5
useEffect(() => {
document.addEventListener("keyup", (e) => {
e.stopImmediatePropagation();
console.log(gameData.board) //0
handleKeyPress(e.key, gameData.board, updateGame);
});
}, []);
console.log(gameData.board) //5
</code></pre>
| [
{
"answer_id": 74343084,
"author": "CertainPerformance",
"author_id": 9515207,
"author_profile": "https://Stackoverflow.com/users/9515207",
"pm_score": 0,
"selected": false,
"text": "gameData"
},
{
"answer_id": 74343124,
"author": "Tushar Shahi",
"author_id": 10140124,
"author_profile": "https://Stackoverflow.com/users/10140124",
"pm_score": 3,
"selected": true,
"text": "ref"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9191351/"
] |
74,343,047 | <p>I have list of excel files in a directory. I'm trying to email those files as attachment. However, when I open the email, I could see only one file as attachment. The below script is not attaching multiple files as attachment.</p>
<pre><code>ls *.xls;
#echo "Test Email" | mailx -s "Testing File Conv" -a *.xls test@testmail.com
</code></pre>
<p>Will the above script work?</p>
| [
{
"answer_id": 74343381,
"author": "rezshar",
"author_id": 12261221,
"author_profile": "https://Stackoverflow.com/users/12261221",
"pm_score": -1,
"selected": true,
"text": "test.txt"
},
{
"answer_id": 74343655,
"author": "Léa Gris",
"author_id": 7939871,
"author_profile": "https://Stackoverflow.com/users/7939871",
"pm_score": 2,
"selected": false,
"text": "#!/usr/bin/env bash\n\n# Produces no result if no match for pattern\nshopt -s nullglob\n\n# Captures recipients from script arguments\nrecipients=(\"$@\")\n\n# Populates aray with xls file paths\nxls_files=(./*.xls)\n\n# If there are xls files\nif [ \"${#xls_files[@]}\" -gt 0 ]; then\n\n # Declare an array to store mailx attachment options\n attach_option=()\n\n # Creates an attachment option for each file to be attached\n for file in \"${xls_files[@]}\"; do\n attach_option+=(-a \"$file\")\n done\n\n # Sends mail with all the attachment options\n mailx -s \"Testing File Conv\" \"${attach_option[@]}\" \"${recipients[@]}\"\nfi\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16395449/"
] |
74,343,116 | <p>Since, Microsoft.Azure.DocumentDB package has been deprecated, I am in the process of migrating our codebase to access CosmosDB from Microsoft.Azure.DocumentDB v2.11.6 to use Microsoft.Azure.Cosmos v3.31.1.</p>
<p>I have used below references and migrated some of the code.</p>
<p><a href="https://stackoverflow.com/questions/58277441/migrating-from-microsoft-azure-documentdb-to-microsoft-azure-cosmos-for-data-acc">Migrating from Microsoft.Azure.DocumentDb to Microsoft.Azure.Cosmos for data access. Not all options available</a>
<a href="https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/migrate-dotnet-v3?tabs=dotnet-v3" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/migrate-dotnet-v3?tabs=dotnet-v3</a>
<a href="https://elcamino.cloud/articles/2019-11-05-cosmos-net-sdk-v3-upgrade-guide-and-tips.html" rel="nofollow noreferrer">https://elcamino.cloud/articles/2019-11-05-cosmos-net-sdk-v3-upgrade-guide-and-tips.html</a></p>
<p>But it looks like note all classes and functionality are available in new package.</p>
<p>For below classes, I couldn't find any replacement...</p>
<ol>
<li>Document</li>
<li>Resource (JSONDocument might be used)</li>
<li>AccessCondition</li>
<li>AccessConditionType</li>
</ol>
<p>My codebase is heavily dependent of properties comes with these classes like id, Timestamp, SelfLink etc.</p>
<p>How can I achieve the same with new Cosmos package.</p>
<pre><code> public class WorkPlay : Resource
{
[JsonProperty(PropertyName = "WorkTypeEnum")]
public string WorkTypeEnum { get; set; }
[JsonProperty(PropertyName = "MediaType")]
public string MediaType { get; set; }
[JsonProperty(PropertyName = "Product")]
public string Product { get; set; }
}
AccessCondition ac = new AccessCondition { Type = AccessConditionType.IfNoneMatch };
this._client = new DocumentClient(new Uri(this._endpoint), this._authKey);
ResourceResponse<Document> response = await this._client.ReadDocumentAsync(Item1.SelfLink, new RequestOptions { AccessCondition = ac });
public async Task DeleteItemAsync(string selfLink, string partitionKey)
{
await this._client.DeleteDocumentAsync(selfLink, new RequestOptions() { PartitionKey = new PartitionKey(partitionKey) });
}
</code></pre>
<p>One Solution, I can think of creating my own implementation of Resource and Document class and add all the required properties.</p>
<p>then the problem comes when I retrieve doc with new cosmos APIs, selflink is not being populated. Since my old code is heavily dependent on selflink, I am more interested in a solution where it can retrieve all properties as it is doing with DocumentDB.</p>
| [
{
"answer_id": 74344656,
"author": "NotFound",
"author_id": 9034195,
"author_profile": "https://Stackoverflow.com/users/9034195",
"pm_score": 2,
"selected": false,
"text": "Document"
},
{
"answer_id": 74382045,
"author": "Matias Quaranta",
"author_id": 5641598,
"author_profile": "https://Stackoverflow.com/users/5641598",
"pm_score": 2,
"selected": true,
"text": "Resource"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1667760/"
] |
74,343,130 | <pre><code>class Solution {
public:
int daysBetweenDates(string date1, string date2) {
}
};
</code></pre>
<p>I have this function. Suppose I have parameter</p>
<pre><code>date1 = "2020-01-15", date2 = "2019-12-31"
</code></pre>
<p>How can i find them as Title? Thank you so much!</p>
| [
{
"answer_id": 74343325,
"author": "Ayxan Haqverdili",
"author_id": 10147399,
"author_profile": "https://Stackoverflow.com/users/10147399",
"pm_score": 3,
"selected": false,
"text": "<chrono>"
},
{
"answer_id": 74343875,
"author": "Giogre",
"author_id": 10947572,
"author_profile": "https://Stackoverflow.com/users/10947572",
"pm_score": 2,
"selected": false,
"text": "#include <iostream>\n#include <chrono>\n\nint main()\n{\n std::string date1 = \"2020-01-15\";\n std::tm tm1 = {};\n strptime(date1.c_str(), \"%Y-%m-%d\", &tm1);\n auto tp1 = std::chrono::system_clock::from_time_t(std::mktime(&tm1));\n \n std::string date2 = \"2019-12-31\";\n std::tm tm2 = {};\n strptime(date2.c_str(), \"%Y-%m-%d\", &tm2);\n auto tp2 = std::chrono::system_clock::from_time_t(std::mktime(&tm2));\n \n std::chrono::system_clock::duration d = tp1 - tp2;\n using DayLength = std::chrono::duration<int,std::ratio<60*60*24>>;\n DayLength days = std::chrono::duration_cast<DayLength> (d);\n \n std::cout << days.count() << std::endl;\n\n return 0;\n}\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19798172/"
] |
74,343,136 | <p>If I have a url called youtube.com/user/1/ and I want the number to incrament to youtube.com/user/2/
whilst scraping the whole page, how would I do so? I've been trying to think of some ways to do this but I can't seem to find anything?</p>
<p>BeautifulSoup</p>
<p>It should work like this:
youtube.com/user/1/
You scrape the page and then it moves to
youtube.com/user/2/</p>
<p>If you could find the solution in beautiful soup that would be cool :)
etc.</p>
| [
{
"answer_id": 74343325,
"author": "Ayxan Haqverdili",
"author_id": 10147399,
"author_profile": "https://Stackoverflow.com/users/10147399",
"pm_score": 3,
"selected": false,
"text": "<chrono>"
},
{
"answer_id": 74343875,
"author": "Giogre",
"author_id": 10947572,
"author_profile": "https://Stackoverflow.com/users/10947572",
"pm_score": 2,
"selected": false,
"text": "#include <iostream>\n#include <chrono>\n\nint main()\n{\n std::string date1 = \"2020-01-15\";\n std::tm tm1 = {};\n strptime(date1.c_str(), \"%Y-%m-%d\", &tm1);\n auto tp1 = std::chrono::system_clock::from_time_t(std::mktime(&tm1));\n \n std::string date2 = \"2019-12-31\";\n std::tm tm2 = {};\n strptime(date2.c_str(), \"%Y-%m-%d\", &tm2);\n auto tp2 = std::chrono::system_clock::from_time_t(std::mktime(&tm2));\n \n std::chrono::system_clock::duration d = tp1 - tp2;\n using DayLength = std::chrono::duration<int,std::ratio<60*60*24>>;\n DayLength days = std::chrono::duration_cast<DayLength> (d);\n \n std::cout << days.count() << std::endl;\n\n return 0;\n}\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,343,151 | <p>My dataset looks like this</p>
<pre><code>rows = [("user1",1,2,10),
("user2",2,6,27),
("user3",3,3,21),
("user4",4,7,44)
]
columns = ["id","val1","val2","val3"]
df = spark.createDataFrame(data=rows, schema = columns)
</code></pre>
<p><img src="https://i.stack.imgur.com/PqRtq.png" alt="enter image description here" /></p>
<p>And I want to calculate cosine similarity scores for each user like below,</p>
<p><img src="https://i.stack.imgur.com/4LIIX.png" alt="enter image description here" /></p>
<p>Kindly help in solving this.</p>
<p>Ps: I do not want to use sklearn library as I am dealing with big data.</p>
| [
{
"answer_id": 74343447,
"author": "PieCot",
"author_id": 5359797,
"author_profile": "https://Stackoverflow.com/users/5359797",
"pm_score": 3,
"selected": true,
"text": "UDF"
},
{
"answer_id": 74344447,
"author": "Azhar Khan",
"author_id": 2847330,
"author_profile": "https://Stackoverflow.com/users/2847330",
"pm_score": 1,
"selected": false,
"text": "UDF"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13203569/"
] |
74,343,167 | <p>I want to display components based on the authorization status. How do I make sure that during rendering I do not display components that fit the default state? I tried changing the state in useLayoutEffect, but I still see a second display of the component I didn't need</p>
<p>Check this screens pls<a href="https://i.stack.imgur.com/Y63JX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Y63JX.png" alt="enter image description here" /></a>
<a href="https://i.stack.imgur.com/aqV2q.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aqV2q.png" alt="enter image description here" /></a>[![enter image description here]</p>
<p>I tried to display the components using useEffect & useLayoutEffect, but did not get the desired effect that I expected</p>
| [
{
"answer_id": 74344242,
"author": "Rodrigo Dias",
"author_id": 7746628,
"author_profile": "https://Stackoverflow.com/users/7746628",
"pm_score": 0,
"selected": false,
"text": "import {useSelector} from 'react-redux';\nimport AppRoutes from './app.routes';\nimport AuthRoutes from './auth.routes';\nimport User from './@types'\n\nconst Routes: React.FC = () => {\n const user = useSelector((state: User) => state.user);\n return user?.token ? <AppRoutes /> : <AuthRoutes />;\n};\n\nexport default Routes;```\n\nIn you're App.tsx you can use the Routes(the code above)\n\nreturn (\n<NavigationContainer ref={navigationRef}>\n <NativeBaseProvider>\n <Provider store={Store}>\n <PersistGate loading={null} persistor={Persistor}>\n <Routes />\n </PersistGate>\n </Provider>\n </NativeBaseProvider>\n</NavigationContainer>\n);\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19489675/"
] |
74,343,216 | <p>I am using portal in React and want to get access to elements from other components.</p>
<p>For example, I have components with:</p>
<pre><code>// here I want to put some content via portal
<div id='buttons'></div>
</code></pre>
<p>That is my component where I create portal</p>
<pre><code> const elem = document.getElementById('buttons');
return (
<div className="block-mainContent">
{isLoading ?
<Loader />
:
<Table
data={memoCustomers}
headers={headers}
actionRender={actionRender}
showCheckbox
onSelect={onSelect}
onSelectAll={onSelectAll}
selectedRows={Array.from(selectedIds)}
/>}
<Modal
isOpen={isOpen}
onClose={() => dispatch(closeModalAction())}
content={editModalContent()}
/>
{!!elem && createPortal(<button>test</button>, elem)} // !!! here is my portal !!!
</div>
);
</code></pre>
<p>My problem is <strong>I get such error "Target container is not a DOM element</strong></p>
<p>As I understand, the problem happens because I try to get an element before it is mounted and as result I get null.</p>
<p>How to check if my div elemen exists and then to create portal?</p>
<p>I try to use different approaches. In the code above I use that</p>
<pre><code> {!!elem && createPortal(<button>test</button>, elem)}
// here I check If element exists it will return true and portal will be created
// but it works a bit wrong. Describe it below
</code></pre>
<p>It helps to remove error, but my portal starts working only at the second render. I mean, after loading my page there is no portal. If only I make smth on the page, rerender happens and portal appears.</p>
<p>I tried else</p>
<pre><code> const [mounted, setMounted] = useState(false)
useEffect(() => {
setMounted(true)
}, []);
{mounted && createPortal(<button>test</button>, elem)}
// here I create portal in the first render via useEffect and
</code></pre>
<p>But it throws the same error. No one of my ideas works.</p>
<p>If you know how to fix it, thank you in advance!</p>
| [
{
"answer_id": 74344242,
"author": "Rodrigo Dias",
"author_id": 7746628,
"author_profile": "https://Stackoverflow.com/users/7746628",
"pm_score": 0,
"selected": false,
"text": "import {useSelector} from 'react-redux';\nimport AppRoutes from './app.routes';\nimport AuthRoutes from './auth.routes';\nimport User from './@types'\n\nconst Routes: React.FC = () => {\n const user = useSelector((state: User) => state.user);\n return user?.token ? <AppRoutes /> : <AuthRoutes />;\n};\n\nexport default Routes;```\n\nIn you're App.tsx you can use the Routes(the code above)\n\nreturn (\n<NavigationContainer ref={navigationRef}>\n <NativeBaseProvider>\n <Provider store={Store}>\n <PersistGate loading={null} persistor={Persistor}>\n <Routes />\n </PersistGate>\n </Provider>\n </NativeBaseProvider>\n</NavigationContainer>\n);\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20240444/"
] |
74,343,285 | <p>How do I test private methods and a method with 2 controls in it
How can I write test method for method create and private method checkUsername</p>
<pre><code>public User create(User user) {
checkUsername(user.getUsername());
return userRepository.save(user);
}
</code></pre>
<pre><code>private void checkUsername(String username) {
if (username.equals("dummy")) {
String msg = String.format("Username = '%s is cannot be used!", username);
throw new UsernameUnavailableException(msg);
} else if (!userRepository.existsByUsername(username)) return;
String msg = String.format("Username ='s%s' is being used by another user!", username);
throw new UsernameIsInUseException(msg);
}
</code></pre>
<p>I couldn't find a private method test according to my research, can you help me?</p>
| [
{
"answer_id": 74344762,
"author": "Popeye",
"author_id": 980097,
"author_profile": "https://Stackoverflow.com/users/980097",
"pm_score": 2,
"selected": false,
"text": "checkUsername"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20437855/"
] |
74,343,308 | <p>I have an autoscaling group launching different EC2 instances, each running the same wordpress application. Somewhere on the wordpress page (let's call it home.html), I want to show the EC2 instance id. I can grab the instance id using this curl command: <code>curl http://169.254.169.254/latest/meta-data/instance-id</code>.</p>
<p>Is there a way I can show the instance id using this curl command, or any way I can set an html variable dynamically to display this metadata on the page?</p>
| [
{
"answer_id": 74344762,
"author": "Popeye",
"author_id": 980097,
"author_profile": "https://Stackoverflow.com/users/980097",
"pm_score": 2,
"selected": false,
"text": "checkUsername"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7717729/"
] |
74,343,318 | <p>I am using React Native:</p>
<pre class="lang-none prettyprint-override"><code>npx react-native run-android
</code></pre>
<p>I have many other solutions. Like force or update the targetsdk version and compile the SDK version, but nothing worked.</p>
<p>I tried changing compileSdkVersion 30 to compileSdkVersion 31 and targetSdkVersion 30 to targetSdkVersion 31.</p>
<h3>The issue</h3>
<p>The minCompileSdk (31) specified in a dependency's AAR metadata (META-INF/com/android/build/gradle/aar-metadata.properties) is greater than this module's compileSdkVersion (android-30).</p>
<pre class="lang-none prettyprint-override"><code>Dependency: androidx.appcompat:appcompat:1.4.1.
</code></pre>
<h3>My buiild.gradle file</h3>
<pre class="lang-none prettyprint-override"><code>// Top-level build file where you can add configuration
// options common to all sub-projects/modules.
buildscript {
ext {
buildToolsVersion = "30.0.2"
minSdkVersion = 21
compileSdkVersion = 31
targetSdkVersion = 31
ndkVersion = "21.4.7075529"
firebaseMessagingVersion = "21.1.0"
googlePlayServicesVisionVersion = "19.0.0"
playServicesVersion = "17.0.0" // or find latest version
androidMapsUtilsVersion = "2.2.5"
kotlin_version = "1.5.0"
androidXCore = "1.5.0"
}
repositories {
google()
mavenCentral()
}
dependencies {
classpath("com.android.tools.build:gradle:4.2.2")
classpath('com.google.gms:google-services:4.3.2')
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
mavenLocal()
mavenCentral()
jcenter()
maven {
// All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
url("$rootDir/../node_modules/react-native/android")
}
maven {
// Android JSC is installed from npm
url("$rootDir/../node_modules/jsc-android/dist")
}
maven { url 'https://www.jitpack.io' }
}
}
</code></pre>
<pre class="lang-none prettyprint-override"><code>configurations.all {
resolutionStrategy { force 'androidx.core:core-ktx:1.6.0' }
}
</code></pre>
| [
{
"answer_id": 74355365,
"author": "reggi49",
"author_id": 15849334,
"author_profile": "https://Stackoverflow.com/users/15849334",
"pm_score": 4,
"selected": false,
"text": "def REACT_NATIVE_VERSION = new File(['node', '--print',\"JSON.parse(require('fs').readFileSync(require.resolve('react-native/package.json'), 'utf-8')).version\"].execute(null, rootDir).text.trim())\n\nallprojects {\n configurations.all {\n resolutionStrategy {\n // Remove this override in 0.65+, as a proper fix is included in react-native itself.\n force \"com.facebook.react:react-native:\" + REACT_NATIVE_VERSION\n }\n }\n"
},
{
"answer_id": 74412023,
"author": "Mohammad Al-Tamimi",
"author_id": 12146710,
"author_profile": "https://Stackoverflow.com/users/12146710",
"pm_score": 0,
"selected": false,
"text": "allprojects {\n ...old configuration project\n// Add the following\n configurations.all {\n resolutionStrategy {\n\n force \"com.facebook.react:react-native:{your_reactnative_version}\"\n }\n }\n}\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6741241/"
] |
74,343,332 | <p>If I have a base class with a constructor :</p>
<pre><code>class Base{
Base(std::optional<type0> a, std::optional<type1> b, std::optional<type2> c, std::optional<type3> d) : _a(a), _b(b), _c(c), _d(d) { }
private:
std::optional<type0> _a;
std::optional<type1> _b;
std::optional<type2> _c;
std::optional<type3> _d;
};
</code></pre>
<p>Can my derived classes derive this constructor with only some of the values and will it automatically map it to the right values?
For example if I do:</p>
<pre><code>class Derived{
Derived(std::optional<type1> b, std::optional<type3> d) : Base(b, d) { }
};
</code></pre>
<p>Will it automatically map <code>b to _b</code> and <code>d to _d</code>?</p>
| [
{
"answer_id": 74343385,
"author": "Jason Liam",
"author_id": 12002570,
"author_profile": "https://Stackoverflow.com/users/12002570",
"pm_score": 1,
"selected": false,
"text": "a"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19532610/"
] |
74,343,347 | <p>I need to use custom deserializer for my json string. The problem is that my class I want to serialize in is very complex and constructed from other classes. But all of the examples in the internet show only very basic way of deserializing jsons (i.e. only retrieving one value by name and getting it's value), but I have subclasses and want to use them so I don't need to write manually all of the mapping. Is there any way I can do this? Example to understand what I'm talking about, so let's say I have this structure:</p>
<pre><code>public TestClass{
public Class1 first;
public Class2 second;
...
public Class10 ten;
}
</code></pre>
<p>And all of the classes contain the data, something like this:</p>
<pre><code>public Class1{
public String name;
public int id;
...
}
</code></pre>
<p>Obviously I don't want to manually map all of that, but all of the examples in the internet show exactly that, is there any way to read the values into classes directly without needing doing manual mapping? For example most common example is to do something like this:</p>
<pre><code>@Override
public Item deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
JsonNode node = jp.getCodec().readTree(jp);
int id = (Integer) ((IntNode) node.get("id")).numberValue();
String itemName = node.get("itemName").asText();
int userId = (Integer) ((IntNode) node.get("createdBy")).numberValue();
return new Item(id, itemName, new User(userId, null));
}
</code></pre>
<p>So my question is can I do this more easily, i.e. reading values directly into these classes? (Except the one, that's why I need the custom deserilizing at the first place, but it's better to write only one manual mapping instead of 10).
Summurizing, I want to do something like this:</p>
<pre><code>@Override
public Item deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
...
Testclass test = new Testclass();
Class1 class1 = json...parse(..., Class1.class);
Class2 class2 = json...parse(..., Class2.class);
...
test.setClass1(class1);
test.setClass2(class2);
...
Class10 manualClass = new Class10();
manualClass.setField1(json.get("class10").get("field1").stringValue());
...
test.setClass10(manualClass);
}
</code></pre>
| [
{
"answer_id": 74539561,
"author": "Oleg Ushakov",
"author_id": 4609353,
"author_profile": "https://Stackoverflow.com/users/4609353",
"pm_score": 2,
"selected": false,
"text": "ObjectMapper objectMapper = new ObjectMapper();\nString json = \"...\" //some json from any source with complex structure related to TestClass structure \nTestClass result = objectMapper.readValue(json, TestClass.class)\n"
},
{
"answer_id": 74542129,
"author": "Luke Machowski",
"author_id": 231860,
"author_profile": "https://Stackoverflow.com/users/231860",
"pm_score": 1,
"selected": true,
"text": "ObjectMapper mapper = new ObjectMapper();\nmapper.addMixInAnnotations(Class1.class, Class1Mixin.class);\n\npublic Class1\n{\n public String name;\n public int id; \n}\n\npublic abstract Class1Mixin\n{\n // Override 'name' to serialize as 'fullName'. Leave the id the same.\n @JsonProperty(\"fullName\")\n public String name; \n}\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9560002/"
] |
74,343,355 | <p><a href="https://i.stack.imgur.com/5E5Cr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5E5Cr.png" alt="enter image description here" /></a></p>
<p>how to control slider with add and subtract buttons in flutter UI</p>
| [
{
"answer_id": 74343459,
"author": "Arijeet",
"author_id": 15387120,
"author_profile": "https://Stackoverflow.com/users/15387120",
"pm_score": 2,
"selected": false,
"text": "import 'package:flutter/material.dart';\n\nvoid main() => runApp(const MyApp());\n\nclass MyApp extends StatelessWidget {\n const MyApp({super.key});\n\n static const String _title = 'Flutter Code Sample';\n\n @override\n Widget build(BuildContext context) {\n return MaterialApp(\n title: _title,\n home: Scaffold(\n appBar: AppBar(title: const Text(_title)),\n body: const MyStatefulWidget(),\n ),\n );\n }\n}\n\nclass MyStatefulWidget extends StatefulWidget {\n const MyStatefulWidget({super.key});\n\n @override\n State<MyStatefulWidget> createState() => _MyStatefulWidgetState();\n}\n\nclass _MyStatefulWidgetState extends State<MyStatefulWidget> {\n double _currentSliderValue = 20;\n int divisons=20;\n\n @override\n Widget build(BuildContext context) {\n return Column(\n children: [\n Row(\n children: [\n IconButton(\n icon: Icon(Icons.remove),\n onPressed: () {\n setState(() {\n _currentSliderValue -= divisons;\n });\n },\n ),\n Text(_currentSliderValue.toString()),\n IconButton(\n icon: Icon(Icons.add),\n onPressed: () {\n setState(() {\n _currentSliderValue += divisons;\n });\n },\n ),\n ],\n ),\n Slider(\n value: _currentSliderValue,\n max: 100,\n divisions: 5,\n label: _currentSliderValue.round().toString(),\n onChanged: (double value) {\n setState(() {\n _currentSliderValue = value;\n });\n },\n ),\n ],\n );\n }\n}\n"
},
{
"answer_id": 74343543,
"author": "Ye Lwin Oo",
"author_id": 19209151,
"author_profile": "https://Stackoverflow.com/users/19209151",
"pm_score": 0,
"selected": false,
"text": "class MyWidget extends StatefulWidget{\n @override\n _MyWidgetState createState() => _MyWidgetState();\n}\n\n\nclass _MyWidgetState extends State<MyWidget> {\n int _value = 5;\n double min = 1.0;\n double max = 20.0;\n @override\n Widget build(BuildContext context) {\n return Column(\n children:[\n Row(\n mainAxisAlignment: MainAxisAlignment.spaceEvenly,\n children:[\n IconButton(onPressed:(){\n setState((){\n if(_value < max){\n /// Add as many as you want\n _value++;\n }\n });\n }, icon: const Icon(Icons.add)),\n IconButton(onPressed:(){\n setState((){\n if(_value > min){\n /// Subtract as many as you want\n _value--;\n }\n \n });\n }, icon: const Icon(Icons.remove)),\n ]\n ),\n Slider( \n value: _value.toDouble(), \n min: min, \n max: max, \n activeColor: Colors.green, \n inactiveColor: Colors.orange, \n label: 'Set volume value', \n onChanged: (double newValue) { \n setState(() { \n _value = newValue.round(); \n }); \n }, \n \n ), \n ]);\n }\n}\n"
},
{
"answer_id": 74343621,
"author": "Irfan Ganatra",
"author_id": 18817235,
"author_profile": "https://Stackoverflow.com/users/18817235",
"pm_score": 0,
"selected": false,
"text": "\nclass _SliderPageState extends State<SliderPage> {\n double _currentSliderValue=15.0;\n\n @override\n Widget build(BuildContext context) {\n return Scaffold(\n body: Center(\n child: Column(\n mainAxisAlignment: MainAxisAlignment.center,\n children: [\n Row(\n mainAxisAlignment: MainAxisAlignment.spaceEvenly,\n children: [\n IconButton(onPressed: (){\n setState(() {\n if(_currentSliderValue<100)\n _currentSliderValue=_currentSliderValue+1;\n\n });\n\n }, icon: Icon(Icons.add)),\n Text(_currentSliderValue.round().toString(),style: TextStyle(fontWeight: FontWeight.bold,fontSize: 24),),\n IconButton(onPressed: (){\n setState(() {\n if(_currentSliderValue>1)\n _currentSliderValue=_currentSliderValue-1;\n\n });\n }, icon: Icon(Icons.remove)),\n\n ],),\n Slider(\n value: _currentSliderValue,\n max: 100,\n divisions: 100,\n //label: _currentSliderValue.round().toString(),\n onChanged: (double value) {\n setState(() {\n _currentSliderValue = value;\n });\n },\n ),\n\n ],)\n ),\n );\n }\n}\n\n\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20405031/"
] |
74,343,387 | <p>Edit: Q1. is answered. please help me in the Q2. Also, please suggest if i should make a new thread of this question ?</p>
<p><strong>Q1.</strong> I am making a digital clock in my app. I have set my Timer, so that setState should run after each second. and in the UI, it seems fine. But in terminal you can see it runs a lot of times in a second. How to stop that?</p>
<p><strong>Q2.</strong> I have two pages in flutter app. Even when i move to secondpage (using <code>navigator.push</code>), the timer still runs in background. ( I know it because i am printing it in terminal also).
Also, I already tried canceling my Timer in <code>dispose</code> method. it does not work.
Also, If I use <code>navigator.pushRemoved</code>, it solves the problem of Timer being run in background, but i wont be able to go back to this page.</p>
<pre><code>import 'dart:async';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:provider_2_practice/controller/controller_file.dart';
import 'new_screen.dart';
class MyHomePageUI extends StatefulWidget {
@override
State<MyHomePageUI> createState() => _MyHomePageUIState();
}
class _MyHomePageUIState extends State<MyHomePageUI> {
Timer? timer ;
String abc ='df-1'; //default value: 'df-1'
String refreshTime(){
timer?.cancel();
timer = Timer.periodic(Duration(seconds: 1), (timer) {
if(mounted){
setState( () {
abc = DateFormat('hh:mm:ss a').format(DateTime.now());
print(abc);
} );
}
});
return abc ;
}
@override
void dispose() {
// TODO: implement dispose
print('test');
timer?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.lightBlue[900],
floatingActionButton: FloatingActionButton(
onPressed: (){
Navigator.of(context).push(MaterialPageRoute(builder: (context) => NewScreen()));
},
child: Icon(Icons.add, color: Colors.white),
backgroundColor: Colors.blue,
),
body: Column(
children: [
SizedBox(height:100,),
Text(refreshTime(), style: TextStyle(fontSize: 45, fontWeight: FontWeight.bold,color: Colors.white70),),
Text('current time', style: TextStyle( fontWeight: FontWeight.bold,color: Colors.white),),
],
),
);
}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/2v0In.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2v0In.jpg" alt="first page" /></a></p>
<p><a href="https://i.stack.imgur.com/uBKMZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uBKMZ.png" alt="second page, Timer still running. see the consol" /></a></p>
| [
{
"answer_id": 74343662,
"author": "Ivo",
"author_id": 1514861,
"author_profile": "https://Stackoverflow.com/users/1514861",
"pm_score": 2,
"selected": false,
"text": "refreshTime()"
},
{
"answer_id": 74345160,
"author": "Saad Mansoor",
"author_id": 11565523,
"author_profile": "https://Stackoverflow.com/users/11565523",
"pm_score": -1,
"selected": false,
"text": "timer?.cancel()"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11565523/"
] |
74,343,396 | <p>During the OpenMDAO workshop in 2022 it has been mentioned that someone did some work on the analytic (or algorithmic?) derivatives for a Boundary Element Method solver, for the use in gradient-based optimisations, and would be willing to share. Is there any reference to that work?</p>
| [
{
"answer_id": 74343662,
"author": "Ivo",
"author_id": 1514861,
"author_profile": "https://Stackoverflow.com/users/1514861",
"pm_score": 2,
"selected": false,
"text": "refreshTime()"
},
{
"answer_id": 74345160,
"author": "Saad Mansoor",
"author_id": 11565523,
"author_profile": "https://Stackoverflow.com/users/11565523",
"pm_score": -1,
"selected": false,
"text": "timer?.cancel()"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17456502/"
] |
74,343,405 | <p><strong>AAPT: error: resource android: attr/IStar not found.</strong></p>
<p>This error occurred suddenly, it was working fine last week.</p>
<p><a href="https://i.stack.imgur.com/w2567.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/w2567.png" alt="enter image description here" /></a></p>
<p>I've tried many solutions but none works. Solutions tried:</p>
<ol>
<li>Delete, reinstall npm, using <code>npm install</code></li>
<li>clean gradle with <code>./gradlew clean</code> in /android</li>
<li>Cleaning npm cache with <code>npm cache clean --force</code></li>
<li>add <code>org.gradle.jvmargs=-Xmx4608m</code> in /android/gradle.properties</li>
<li>In /android/build.gradle, inside <code>ext{}</code> add <code>androidXCore = "1.6.0"</code></li>
<li><code>npm update @react-native-community/netinfo</code></li>
<li>androidx.core:core-ktx:+ to androidx.core:core-ktx:1.6.0 but I've searched through my project, there is no 'androidx.core:core-ktx:+. So this solution I found is irrelevant.</li>
</ol>
<p><strong>Version:</strong></p>
<pre><code>"react-native": "0.63.4",
compileSdkVersion = 29
targetSdkVersion = 29
</code></pre>
| [
{
"answer_id": 74343412,
"author": "ZFloc Technologies",
"author_id": 10657559,
"author_profile": "https://Stackoverflow.com/users/10657559",
"pm_score": 4,
"selected": true,
"text": "android/buld.gradle"
},
{
"answer_id": 74343785,
"author": "Wahidullah Shadab",
"author_id": 13857453,
"author_profile": "https://Stackoverflow.com/users/13857453",
"pm_score": 2,
"selected": false,
"text": "React-native 0.63"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11834362/"
] |
74,343,443 | <p>I have my app locked down by allowing only authorised users at hosts.cshtml and using the AuthorizeView tag in app.razor. The net affect is to force all users to a login page if they are unauthorized.</p>
<p>This works perfectly well until someone on a higher paycheck then me decides that one or two pages should be annonymous. Setting the page to @attribute [AllowAnonymous] has no effect because the page is never reached.</p>
<p>Is there a strategy to implement this, hopefully in app.razor?</p>
<p>Here is my hosts.cshtml...</p>
<pre><code>
@page "/"
@using Microsoft.AspNetCore.Authorization
@attribute [Authorize]
@namespace U3A.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = "_Layout";
}
<component type="typeof(App)" render-mode="ServerPrerendered" />
</code></pre>
<p>And app.razor looks like ...</p>
<pre><code><CascadingAuthenticationState>
<Router AppAssembly="@typeof(App).Assembly">
<Found Context="routeData">
<AuthorizeView>
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
<FocusOnNavigate RouteData="@routeData" Selector="h1" />
</AuthorizeView>
</Found>
<NotFound>
<PageTitle>Not found</PageTitle>
<LayoutView Layout="@typeof(MainLayout)">
<p role="alert">Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
</CascadingAuthenticationState>
</code></pre>
<p>Thank you</p>
| [
{
"answer_id": 74343412,
"author": "ZFloc Technologies",
"author_id": 10657559,
"author_profile": "https://Stackoverflow.com/users/10657559",
"pm_score": 4,
"selected": true,
"text": "android/buld.gradle"
},
{
"answer_id": 74343785,
"author": "Wahidullah Shadab",
"author_id": 13857453,
"author_profile": "https://Stackoverflow.com/users/13857453",
"pm_score": 2,
"selected": false,
"text": "React-native 0.63"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16630285/"
] |
74,343,450 | <p>I have the following data:</p>
<pre><code> A B
0 27.9 1.0
1 20.6 1.0
2 10.3 1.0
3 0.0 1.0
4 349.7 1.0
5 339.4 2.0
6 329.1 1.0
7 318.9 1.0
</code></pre>
<p>And I would like every time there is a number higher than 1 in B, then the column will be duplicated by that number. The output of this data should be then:</p>
<pre><code> A B
0 27.9 1.0
1 20.6 1.0
2 10.3 1.0
3 0.0 1.0
4 349.7 1.0
5 339.4 2.0
6 339.4 2.0 --> basically inserting this one here
7 329.1 1.0
8 318.9 1.0
</code></pre>
<p>I have tried with pandas but I don't seem to get it right. Thanks in advance!</p>
| [
{
"answer_id": 74343412,
"author": "ZFloc Technologies",
"author_id": 10657559,
"author_profile": "https://Stackoverflow.com/users/10657559",
"pm_score": 4,
"selected": true,
"text": "android/buld.gradle"
},
{
"answer_id": 74343785,
"author": "Wahidullah Shadab",
"author_id": 13857453,
"author_profile": "https://Stackoverflow.com/users/13857453",
"pm_score": 2,
"selected": false,
"text": "React-native 0.63"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343450",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20438008/"
] |
74,343,461 | <p>I was reading the solution to reverse a linked list. It mentions to use swapping the links but I can't get an intuition as how author have come up with previous and next pointer approach. It feels like I have to memorize this order. Can some one give me the intuition of the below piece of code.</p>
<pre><code>public static <T> void reverse(SinglyLinkedList<T> list){
SinglyLinkedList<T>.Node previous = null; //To keep track of the previous element, will be used in swapping links
SinglyLinkedList<T>.Node current = list.headNode; //firstElement
SinglyLinkedList<T>.Node next = null;
//While Traversing the list, swap links
while (current != null) {
next = current.nextNode;
current.nextNode = previous;
previous = current;
current = next;
}
//Linking Head Node with the new First Element
list.headNode = previous;
}
</code></pre>
| [
{
"answer_id": 74345351,
"author": "Alexander Ivanchenko",
"author_id": 17949945,
"author_profile": "https://Stackoverflow.com/users/17949945",
"pm_score": 0,
"selected": false,
"text": "[Node1] => [Node2] => [Node3] - initial list\n <- <- - new links\n"
},
{
"answer_id": 74347354,
"author": "trincot",
"author_id": 5459839,
"author_profile": "https://Stackoverflow.com/users/5459839",
"pm_score": 2,
"selected": false,
"text": "previous: null\nnext: null\n\n current\n ↓\n ┌────────────┐ ┌────────────┐ ┌────────────────┐\n │ data: 1 │ │ data: 2 │ │ data: 3 │\n │ nextNode: ───► │ nextNode: ───► │ nextNode: null │\n └────────────┘ └────────────┘ └────────────────┘\n ▲\n ┌───────────│─┐\n │ headNode: ┘ │\n └─────────────┘\n ↑\n list\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10254216/"
] |
74,343,469 | <p>Is there way to create a dataframe(using pandas) from start date to End date with random values</p>
<p>For example, the required data frame:</p>
<pre><code>date value
2015-06-25 12
2015-06-26 23
2015-06-27 3.4
2015-06-28 5.6
</code></pre>
<p>Is this dataframe I need to set "from date" to "To date" so that there is no need to type manually because the rows keep on increasing and "value" column should have values generated randomly</p>
| [
{
"answer_id": 74343775,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": true,
"text": "pandas.date_range"
},
{
"answer_id": 74343793,
"author": "tturbo",
"author_id": 12284585,
"author_profile": "https://Stackoverflow.com/users/12284585",
"pm_score": 0,
"selected": false,
"text": "import pandas as pd\nimport numpy as np\nbeg = '2015-06-25 '\nend = '2015-06-28'\nindex = pd.date_range(beg, end)\nvalues = np.random.rand(len(index))\ndf = pd.DataFrame(values, index=index)\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20377357/"
] |
74,343,475 | <p>I had a child component <code>UploadImage.js</code> and parent component <code>Parent.js</code>. I am uploading an image and want to pass the value of file name to the <code>Parent.js</code> component. How can I do so?</p>
<p><strong>UploadImage.js</strong></p>
<pre><code>import React, { useEffect, useState } from 'react';
import { useDropzone } from 'react-dropzone';
.
.
.
const UploadImage = () => {
const [files, setFiles] = useState([]);
const { getRootProps, getInputProps } = useDropzone({
accept: {
'image/*': []
},
onDrop: acceptedFiles => {
setFiles(acceptedFiles.map(file => Object.assign(file, {
preview: URL.createObjectURL(file)
})));
}
});
//preview component
const thumbs = files.map(file => (
<div style={thumb} className="d-flex flex-row mt-1 col-12 mx-auto" key={file.name}>
<div style={thumbInner}>
<img
src={file.preview}
style={img}
// Revoke data uri after image is loaded
onLoad={() => { URL.revokeObjectURL(file.preview) }}
/>
</div>
</div>
)
);
//wanted to pass file[0].name to Parent Component
console.log(files.length > 0 ? files[0].name : "")
useEffect(() => {
// Make sure to revoke the data uris to avoid memory leaks, will run on unmount
return () => files.forEach(file => URL.revokeObjectURL(file.preview));
}, []);
return (
<section className="container">
<div {...getRootProps({ className: 'dropzone mx-3 text-center mt-4 mb-2 p-3 bg-light border border-primary border-1 rounded-4 ' })}>
<input {...getInputProps()} />
<p className='fw-bold text-primary'>Drag 'n' drop some files here, or click to select files</p>
</div>
<aside style={thumbsContainer} className="d-flex flex-row">
{thumbs}
</aside>
</section>
);
}
export default UploadImage;
</code></pre>
<p>And my Parent component is like this</p>
<pre><code>import React, { useState} from "react";
import UploadImage from "../components/uploadImage";
const Parent = () => {
const [uploadFileName, setUploadFileName] = useState("");
return (
<div className="mx-3 mt-4 mb-2">
<UploadImage />
<h3 className="m-3">{uploadFileName} </h3>
</div>
);
};
export default UploadButton;
</code></pre>
<p>How can I display the file name from <code>UploadImage.js</code> to <code>Parent.js</code> in the uploadFileName state ???</p>
| [
{
"answer_id": 74343775,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": true,
"text": "pandas.date_range"
},
{
"answer_id": 74343793,
"author": "tturbo",
"author_id": 12284585,
"author_profile": "https://Stackoverflow.com/users/12284585",
"pm_score": 0,
"selected": false,
"text": "import pandas as pd\nimport numpy as np\nbeg = '2015-06-25 '\nend = '2015-06-28'\nindex = pd.date_range(beg, end)\nvalues = np.random.rand(len(index))\ndf = pd.DataFrame(values, index=index)\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10962364/"
] |
74,343,485 | <p>I have this layout made with CSS grid.</p>
<p><a href="https://i.stack.imgur.com/FJFjl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FJFjl.png" alt="enter image description here" /></a></p>
<p>It's adding extra space at the bottom of each element. I'd like the red background(grid cell) to take up the minimum height of it's content.</p>
<p>Something like:</p>
<p><code>grid-template-rows: <minimum height> <minimum height> <minimum height>;</code></p>
<p>How do I acheive this?</p>
<p>I know I can just change the HTML and make it easier but since the title comes first on smaller screens, I can't change the structure.</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>.container {
display: grid;
grid-template-areas: "image image title"
"image image desc-1"
"image image desc-2";
gap: 1rem;
width: 500px;
margin: 0 auto;
}
.item {
background: tomato;
}
.title {
grid-area: title;
}
.image {
grid-area: image;
}
.desc-1 {
grid-area: desc-1;
}
.desc-2 {
grid-area: desc-2;
}
.image img {
display: block;
}
.title, .desc-1, .desc-2 {
margin-block: 0;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="container">
<h2 class="item title">Lorem ipsum</h2>
<div class="image">
<img src="https://picsum.photos/300/200.jpg" />
</div>
<p class="item desc-1">Lorem ipsum dolor sit amet.</p>
<p class="item desc-2">Sed ut perspiciatis unde.</p>
</section></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74343596,
"author": "Stacks Queue",
"author_id": 14820590,
"author_profile": "https://Stackoverflow.com/users/14820590",
"pm_score": 0,
"selected": false,
"text": "grid-auto-rows"
},
{
"answer_id": 74344095,
"author": "XRaycat",
"author_id": 7744154,
"author_profile": "https://Stackoverflow.com/users/7744154",
"pm_score": 0,
"selected": false,
"text": "align-items: start"
},
{
"answer_id": 74344586,
"author": "Temani Afif",
"author_id": 8620333,
"author_profile": "https://Stackoverflow.com/users/8620333",
"pm_score": 2,
"selected": true,
"text": ".container {\n display: grid;\n grid-template-columns: 2fr 1fr; /* size of columns */\n gap: 1rem;\n width: 500px;\n margin: 0 auto;\n}\n.item {\n background: tomato;\n}\n.image {\n grid-row: 1/span 4; /* placed at 1st row and takes 4 rows */\n grid-column: 1; /* places at 1st column */\n}\n.image img {\n display: block;\n}\n.title, .desc-1, .desc-2 {\n margin-block: 0;\n}"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10301756/"
] |
74,343,497 | <p>I am currently stuck on how should i change the current code to show if user selected Not Suit and it will show Movie and Drama checkbox or else if uncheck it disappear movie and drama checkbox and only showing Not Suit checkbox</p>
<p>my current code in Movie.kt</p>
<pre><code>chkBoxNotsuit.setOnCheckedChangeListener {
if (chkBoxNotsuit.isChecked == true)
chkBoxMovie.isVisible = !isChecked
chkBoxDrama.isVisible = !isChecked
else
chkBoxMovie.isInvisible = !notChecked
chkBoxDrama.isInvisible = !notChecked
displayToast(message)
}
fun displayToast(message:String){
Toast.makeText(this,message,Toast.LENGTH_LONG).show()
}
</code></pre>
| [
{
"answer_id": 74343596,
"author": "Stacks Queue",
"author_id": 14820590,
"author_profile": "https://Stackoverflow.com/users/14820590",
"pm_score": 0,
"selected": false,
"text": "grid-auto-rows"
},
{
"answer_id": 74344095,
"author": "XRaycat",
"author_id": 7744154,
"author_profile": "https://Stackoverflow.com/users/7744154",
"pm_score": 0,
"selected": false,
"text": "align-items: start"
},
{
"answer_id": 74344586,
"author": "Temani Afif",
"author_id": 8620333,
"author_profile": "https://Stackoverflow.com/users/8620333",
"pm_score": 2,
"selected": true,
"text": ".container {\n display: grid;\n grid-template-columns: 2fr 1fr; /* size of columns */\n gap: 1rem;\n width: 500px;\n margin: 0 auto;\n}\n.item {\n background: tomato;\n}\n.image {\n grid-row: 1/span 4; /* placed at 1st row and takes 4 rows */\n grid-column: 1; /* places at 1st column */\n}\n.image img {\n display: block;\n}\n.title, .desc-1, .desc-2 {\n margin-block: 0;\n}"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19166242/"
] |
74,343,509 | <p>I have used <code>.find()</code> on my string to find the index of the word that the user wants to remove from the string, but now how do i use this index to them remove said word?</p>
<p>The function is as follows:</p>
<pre><code>sentence = "The quick brown fox jumps over the lazy dog."
print("The sentence is: "+ sentence)
user_removal = input("Which word would you like to remove? ")
user_removal_word = sentence.find(user_removal)
</code></pre>
<p>I've used if statements and then formatting to then remove the word from the sentence and then recreate it but I'm sure that there is a better way to do it.</p>
| [
{
"answer_id": 74343596,
"author": "Stacks Queue",
"author_id": 14820590,
"author_profile": "https://Stackoverflow.com/users/14820590",
"pm_score": 0,
"selected": false,
"text": "grid-auto-rows"
},
{
"answer_id": 74344095,
"author": "XRaycat",
"author_id": 7744154,
"author_profile": "https://Stackoverflow.com/users/7744154",
"pm_score": 0,
"selected": false,
"text": "align-items: start"
},
{
"answer_id": 74344586,
"author": "Temani Afif",
"author_id": 8620333,
"author_profile": "https://Stackoverflow.com/users/8620333",
"pm_score": 2,
"selected": true,
"text": ".container {\n display: grid;\n grid-template-columns: 2fr 1fr; /* size of columns */\n gap: 1rem;\n width: 500px;\n margin: 0 auto;\n}\n.item {\n background: tomato;\n}\n.image {\n grid-row: 1/span 4; /* placed at 1st row and takes 4 rows */\n grid-column: 1; /* places at 1st column */\n}\n.image img {\n display: block;\n}\n.title, .desc-1, .desc-2 {\n margin-block: 0;\n}"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20357515/"
] |
74,343,537 | <p>I have a question to which I am trying to figure out the answer</p>
<p>For example, I structured the sockets like this</p>
<pre><code>const io = require('socket.io')(server, {
cors: {
origin: "*"
}
});
</code></pre>
<pre><code>// sockets events
const onConnection = require('./sockets/events/connection');
</code></pre>
<pre><code>io.on("connection", onConnection);
</code></pre>
<pre><code>const search = require('./s');earch
const onConnection = async (socket) => {
console.log(`Client connected ${socket.id}`);
socket.on('search', search);
socket.on('disconnect', (reason) => {
console.log(`Client disconnected with reason: ${reason}`)
})
};
module.exports = onConnection;
</code></pre>
<p>But in that search function, I would also like to pass the "socket" argument so that I can still have access to the socket functions</p>
<pre><code>const onSearch = async (socket) => {
console.log(socket);
console.log(500);
}
module.exports = onSearch;
</code></pre>
<p>So my question is when I access that event (search) in socket.on, how could I send the socket further?</p>
<p>I tried to pass as a function</p>
<pre><code>socket.on('search', metasearch(socket);
</code></pre>
<p>But it didn't work..</p>
| [
{
"answer_id": 74343596,
"author": "Stacks Queue",
"author_id": 14820590,
"author_profile": "https://Stackoverflow.com/users/14820590",
"pm_score": 0,
"selected": false,
"text": "grid-auto-rows"
},
{
"answer_id": 74344095,
"author": "XRaycat",
"author_id": 7744154,
"author_profile": "https://Stackoverflow.com/users/7744154",
"pm_score": 0,
"selected": false,
"text": "align-items: start"
},
{
"answer_id": 74344586,
"author": "Temani Afif",
"author_id": 8620333,
"author_profile": "https://Stackoverflow.com/users/8620333",
"pm_score": 2,
"selected": true,
"text": ".container {\n display: grid;\n grid-template-columns: 2fr 1fr; /* size of columns */\n gap: 1rem;\n width: 500px;\n margin: 0 auto;\n}\n.item {\n background: tomato;\n}\n.image {\n grid-row: 1/span 4; /* placed at 1st row and takes 4 rows */\n grid-column: 1; /* places at 1st column */\n}\n.image img {\n display: block;\n}\n.title, .desc-1, .desc-2 {\n margin-block: 0;\n}"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19665210/"
] |
74,343,557 | <p>I have template, which contains simple icon template:</p>
<pre><code><span class="icon {{unbound pperson.medical.diseases '=' 0 'hidden'}}">
<img class="icon" src="/assets/img/icons/icon.svg
</span>
</code></pre>
<p>As can be seen I need a flag to show/display it and I'm using <code>hidden</code> class for it. And I have data-array 'diseases'. So if it's empty I should not display icon, if it's not empty I should display this icon. I tried condition:</p>
<pre><code>{unbound pperson.medical.diseases '=' 0 'hidden'}}
</code></pre>
<p>This gives error. I found that it was possible to write ember <code>handle bar</code> function and to use but I would like to find inline approach without creating aditional functions. is it possible?</p>
| [
{
"answer_id": 74344750,
"author": "Sam Fisher",
"author_id": 8336836,
"author_profile": "https://Stackoverflow.com/users/8336836",
"pm_score": 1,
"selected": false,
"text": " <span class=\"icon {{unbound (unless (or null-undefined pperson.medical.disease pperson.medical.diseases.length '=' 0 ) 'hidden')}}\">\n"
},
{
"answer_id": 74524440,
"author": "jelhan",
"author_id": 3167221,
"author_profile": "https://Stackoverflow.com/users/3167221",
"pm_score": 0,
"selected": false,
"text": "<span class=\"icon {{unless pperson.medical.diseases 'hidden'}}\"> \n <img class=\"icon\" src=\"/assets/img/icons/icon.svg \n</span>\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8336836/"
] |
74,343,571 | <p>i created a function to view products in products view page i tried so many times but cant find any one help me please</p>
<p>here is my code</p>
<p><code>views.py</code>:</p>
<pre class="lang-py prettyprint-override"><code>
def product_view(request,cate_slug,prod_slug):
if (Category.objects.filter(slug=cate_slug, status=0)):
if (Products.objects.filter(slug=prod_slug, status=0)):
product = Products.objects.filter(slug=prod_slug, status=0)
contex = {
'product':product,
}
else:
messages.warning(request,"product not found")
return redirect("collection")
else:
messages.error(request,"something went wrong")
return redirect("collection")
return render(request,"product_view.html",contex)
</code></pre>
<p><code>urls.py</code>:</p>
<pre class="lang-py prettyprint-override"><code>path('collection/<str:cate_slug>/<str:prod_slug>',views.product_view,name="product"),
</code></pre>
<p><code>product view.html</code>:</p>
<pre class="lang-html prettyprint-override"><code>{% extends 'auth.html' %}
{% load static %}
{% block content %}
<h1> {{ products.name }} </h1>
{% endblock %}
</code></pre>
<p>i just want to see product detils in product view html page any one help me because i am new to django</p>
| [
{
"answer_id": 74343964,
"author": "haduki",
"author_id": 18229792,
"author_profile": "https://Stackoverflow.com/users/18229792",
"pm_score": 0,
"selected": false,
"text": "{{product.name}}"
},
{
"answer_id": 74344191,
"author": "Manoj Tolagekar",
"author_id": 17808039,
"author_profile": "https://Stackoverflow.com/users/17808039",
"pm_score": 1,
"selected": false,
"text": "def product_view(request,cate_slug,prod_slug):\n if (Category.objects.filter(slug=cate_slug, status=0)):\n if (Products.objects.filter(slug=prod_slug, status=0)):\n product = Products.objects.filter(slug=prod_slug, status=0)\n \n else:\n messages.warning(request,\"product not found\") \n return redirect(\"collection\")\n else:\n messages.error(request,\"something went wrong\")\n return redirect(\"collection\")\n return render(request,\"product_view.html\",{'product':product}) #I have removed context from if statement and added directly here.\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17193865/"
] |
74,343,606 | <p>I want to concatenate multiple columns in a DataFrame into a single column and transpose them into a single row, but when I call transpose it remains a single column.</p>
<pre><code>import pandas as pd
df = pd.DataFrame(
{
0: [1, 2, 3],
1: [11, 12, 13]
}
)
print( df)
df = pd.concat( [df[0], df[1]])
df = df.T.copy()
print( '--------')
print( df)
</code></pre>
<p>Even with "df = df.T.copy()" (even without it), after transpose, as follows;</p>
<pre><code> 0 1
0 1 11
1 2 12
2 3 13
--------
0 1
1 2
2 3
0 11
1 12
2 13
dtype: int64
</code></pre>
<p>Below is the shape I want.</p>
<pre><code> 0 1 2 3 4 5
0 1 2 3 11 12 13
</code></pre>
<p>Please, somebody give me some advice.</p>
| [
{
"answer_id": 74343679,
"author": "sammywemmy",
"author_id": 7175713,
"author_profile": "https://Stackoverflow.com/users/7175713",
"pm_score": 3,
"selected": true,
"text": "import pandas as pd\nimport numpy as np\n\nout = df.to_numpy().ravel(order='F')\npd.DataFrame([out])\n 0 1 2 3 4 5\n0 1 2 3 11 12 13\n"
},
{
"answer_id": 74343726,
"author": "Panda Kim",
"author_id": 20430449,
"author_profile": "https://Stackoverflow.com/users/20430449",
"pm_score": 1,
"selected": false,
"text": "df = pd.DataFrame(\n {\n 0: [1, 2, 3],\n 1: [11, 12, 13]\n }\n)\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19614296/"
] |
74,343,674 | <p>I have a simple table. When a user clicks on a row, a jscript gets triggered. How can I get a value from row/cell to use in jscript to check true or false please? There is also a seperate click-row script but ignore that for now.</p>
<pre><code><tbody>
@if (Model != null)
{
foreach (CELIntranet.Models.tblReportsList item in Model)
{
<tr class="clickable-row" id="myid" data-mydata1=UserPermission href="@Url.Action("ShowReport", new { ReportViewName = item.ReportViewName,
ReportController = item.ReportController, UserPermission = (User.IsInRole(item.ReportUserRoles) || User.IsInRole("Administrator")) })">
<td>@Html.Raw(item.ReportNumber)</td>
<td>@Html.Raw(item.ReportName)</td>
<td>@Html.Raw(item.ReportGroup)</td>
<td>@Html.Raw(item.ReportStatus)</td>
@if (User.IsInRole(item.ReportUserRoles) || User.IsInRole("Administrator"))
{
<td style="color:dodgerblue">Granted</td>
}
else
{
<td style="color:orangered">Restricted</td>
}
</tr>
}
}
</tbody>
<script type="text/javascript">
$(function () {
var ClickedTableRowCellValue = ("Need some code to get UserPermission value from the clicked row");
$('table > tbody > tr').click(function () {
if (ClickedTableRowCellValue == True) {
alert("Granted");
Popup();
}
alert("Restricted");
});
});
</script>
// Click row ignore this code for now!
@section Scripts {
<script type="text/javascript">
var clicker = new TableCliker();
$(document).ready(function () {
clicker.Initialise();
//alert("Test");
//Popup();
});
</script>
</code></pre>
| [
{
"answer_id": 74343679,
"author": "sammywemmy",
"author_id": 7175713,
"author_profile": "https://Stackoverflow.com/users/7175713",
"pm_score": 3,
"selected": true,
"text": "import pandas as pd\nimport numpy as np\n\nout = df.to_numpy().ravel(order='F')\npd.DataFrame([out])\n 0 1 2 3 4 5\n0 1 2 3 11 12 13\n"
},
{
"answer_id": 74343726,
"author": "Panda Kim",
"author_id": 20430449,
"author_profile": "https://Stackoverflow.com/users/20430449",
"pm_score": 1,
"selected": false,
"text": "df = pd.DataFrame(\n {\n 0: [1, 2, 3],\n 1: [11, 12, 13]\n }\n)\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10707396/"
] |
74,343,698 | <p>I have in my code the specificacions of the bool to return true or false but I don't figure how to printf depending if it is true or false.
I have some float prompted by the user and the bool to determine if it is true or false.
How can I use these both datas to printf depending?</p>
<pre><code>bool valid_triangle(float x, float y, float z);
int main(void)
{
float x;
float y;
float z;
do
{
x = get_float("Enter a length: ");
}
while(x <= 0);
do
{
y = get_float("Enter other length: ");
}
while(y <= 0);
do
{
z = get_float("The last one: ");
}
while(z <= 0);
}
if(valid_triangle = 1)
{
printf("It's a triangle");
}
bool valid_triangle(float x, float y, float z)
{
if(x <= 0 || y <= 0 || z <= 0)
{
return false;
}
if((x + y <= z) || (x + z <= y) || (y + z <= x))
{
return false;
}
return true;
}
</code></pre>
<p>I tried an if conditional with the bool but doesn`t compile.
<a href="https://i.stack.imgur.com/6LTzU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6LTzU.png" alt="Image from the error" /></a></p>
| [
{
"answer_id": 74343732,
"author": "brmRush",
"author_id": 9483598,
"author_profile": "https://Stackoverflow.com/users/9483598",
"pm_score": 1,
"selected": false,
"text": "if(valid_triangle(x, y, z) == true)\n{\n printf(\"It's a triangle\");\n} else {\n printf(\"It's not a triangle\");\n\n}\n"
},
{
"answer_id": 74343735,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 2,
"selected": false,
"text": "if(valid_triangle = 1)\n"
},
{
"answer_id": 74455981,
"author": "Luis Colorado",
"author_id": 3899431,
"author_profile": "https://Stackoverflow.com/users/3899431",
"pm_score": 0,
"selected": false,
"text": " printf(\"%s a triangle\\n\", \n valid_triangle(x, y, z) \n ? \"It's\" \n : \"It is not\");\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20438035/"
] |
74,343,705 | <p>I have a list of lists each containing tuples with some co-ordinates which sort of look like this:</p>
<p><code>[[(x1, y1), (x2, y2), (x3, y3) ... (xn, yn)], [(x1, y1), (x2, y2), (x3, y3) ... (xn, yn)], [(x1, y1), (x2, y2), (x3, y3) ... (xn, yn)]]</code></p>
<p>Considering orders, lets call the outer list - L0, and the inner list - L1</p>
<p>The number of tuples inside of L1 may vary with incoming data but will be constant for all elements of L0. For example, if there are 3 tuples in L1, there will be 3 tuples in all the rest of the lists.</p>
<p>My goal is to get minimum values of all xn co-ordinates and the maximum values of all yn co-ordinates across all L1 elements and return a list which looks something like this:</p>
<p><code>[(x1min, y1max), (x2min, y2max), (x3min, y3max) ... (xnmin, ynmax)]</code></p>
<p>I tried approaching this by looping through L0 and then again looping through L1 only to get individual elements and then trying to construct a new list of the expected output but it is very long and I think would be inefficient.</p>
<p>I am not at all able to figure out how to approach this problem and I am pretty sure there is a very clever and efficient way of solving this. I would be really grateful for any help I can get on this.</p>
<p><em>Note: I am a newbie learning python so please forgive me if I am accidently using any wrong terms and stuff. Also, this problem might probably be a very easy one but I cannot develop a method to approach this yet. I also tried searching for it everywhere but couldn't find a solution that fits my problem.</em></p>
| [
{
"answer_id": 74343732,
"author": "brmRush",
"author_id": 9483598,
"author_profile": "https://Stackoverflow.com/users/9483598",
"pm_score": 1,
"selected": false,
"text": "if(valid_triangle(x, y, z) == true)\n{\n printf(\"It's a triangle\");\n} else {\n printf(\"It's not a triangle\");\n\n}\n"
},
{
"answer_id": 74343735,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 2,
"selected": false,
"text": "if(valid_triangle = 1)\n"
},
{
"answer_id": 74455981,
"author": "Luis Colorado",
"author_id": 3899431,
"author_profile": "https://Stackoverflow.com/users/3899431",
"pm_score": 0,
"selected": false,
"text": " printf(\"%s a triangle\\n\", \n valid_triangle(x, y, z) \n ? \"It's\" \n : \"It is not\");\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20438100/"
] |
74,343,728 | <p>Well, that is, there are two Johns and one Quill, you need to output the number of those people who have the same name. In one column there should be the total number of students with the same names</p>
<pre><code>SELECT COUNT(id) as count
FROM student
GROUP BY LOWER(first_name) HAVING COUNT(LOWER(first_name)) > 1;
</code></pre>
<p>it will output for each name the count, how to make the total?</p>
| [
{
"answer_id": 74343815,
"author": "Thorsten Kettner",
"author_id": 2270762,
"author_profile": "https://Stackoverflow.com/users/2270762",
"pm_score": 2,
"selected": true,
"text": "SELECT SUM(cnt)\nFROM\n(\n SELECT COUNT(*) AS cnt\n FROM student\n GROUP BY LOWER(first_name)\n HAVING COUNT(*) > 1\n) counts;\n"
},
{
"answer_id": 74343838,
"author": "Amjad Khan",
"author_id": 20438263,
"author_profile": "https://Stackoverflow.com/users/20438263",
"pm_score": 0,
"selected": false,
"text": "SELECT SUM(COUNT(id)) as Total\nFROM student\nGROUP BY LOWER(first_name) HAVING COUNT(LOWER(first_name)) > 1;\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20265121/"
] |
74,343,752 | <p>I was creating a shopping cart using react and redux and everything works perfectly without any errors I'm wondering how do I calculate the total price by adding up all the items in the cart</p>
<p>my cart-slice file</p>
<pre><code>import { createSlice } from '@reduxjs/toolkit';
const cartSlice = createSlice({
name: 'cart',
initialState: {
items: [],
totalQuantity: 0,
},
reducers: {
addItemToCart(state, action) {
const newItem = action.payload;
const existingItem = state.items.find((item) => item.id === newItem.id);
state.totalQuantity++;
if (!existingItem) {
state.items.push({
id: newItem.id,
price: newItem.price,
quantity: 1,
totalPrice: newItem.price,
name: newItem.title,
});
} else {
existingItem.quantity++;
existingItem.totalPrice = existingItem.totalPrice + newItem.price;
}
},
removeItemFromCart(state, action) {
const id = action.payload;
const existingItem = state.items.find(item => item.id === id);
state.totalQuantity--;
if (existingItem.quantity === 1) {
state.items = state.items.filter(item => item.id !== id);
} else {
existingItem.quantity--;
existingItem.totalPrice = existingItem.totalPrice - existingItem.price;
}
},
},
});
export const cartActions = cartSlice.actions;
export default cartSlice;
</code></pre>
<p>the cart.js file</p>
<pre><code>import { useSelector } from 'react-redux';
import Card from '../UI/Card';
import classes from './Cart.module.css';
import CartItem from './CartItem';
const Cart = (props) => {
const cartItems = useSelector((state) => state.cart.items);
return (
<Card className={classes.cart}>
<h2>Your Shopping Cart</h2>
<ul>
{cartItems.map((item) => (
<CartItem
key={item.id}
item={{
id: item.id,
title: item.name,
quantity: item.quantity,
total: item.totalPrice,
price: item.price,
}}
/>
))}
</ul>
</Card>
);
};
export default Cart;
</code></pre>
<p>the cart item file</p>
<pre><code>import { useDispatch } from 'react-redux';
import classes from './CartItem.module.css';
import { cartActions } from '../../store/cart-slice';
import { useState } from 'react';
const CartItem = (props) => {
const dispatch = useDispatch();
const { title, quantity, total, price, id } = props.item;
const removeItemHandler = (e) => {
dispatch(cartActions.removeItemFromCart(id));
};
const addItemHandler = () => {
dispatch(
cartActions.addItemToCart({
id,
title,
price,
})
);
};
return (
<>
<li className={classes.item}>
<header>
<h3>{title}</h3>
<div className={classes.price}>
${total.toFixed(2)}{' '}
<span className={classes.itemprice}>(${price.toFixed(2)}/item)</span>
</div>
</header>
<div className={classes.details}>
<div className={classes.quantity}>
x <span>{quantity}</span>
</div>
<div className={classes.actions}>
<button onClick={removeItemHandler}>-</button>
<button onClick={addItemHandler}>+</button>
</div>
</div>
</li>
</>
);
};
export default CartItem;
</code></pre>
<p>can somebody please help me on how do we calculate the total price of the cart?</p>
| [
{
"answer_id": 74343815,
"author": "Thorsten Kettner",
"author_id": 2270762,
"author_profile": "https://Stackoverflow.com/users/2270762",
"pm_score": 2,
"selected": true,
"text": "SELECT SUM(cnt)\nFROM\n(\n SELECT COUNT(*) AS cnt\n FROM student\n GROUP BY LOWER(first_name)\n HAVING COUNT(*) > 1\n) counts;\n"
},
{
"answer_id": 74343838,
"author": "Amjad Khan",
"author_id": 20438263,
"author_profile": "https://Stackoverflow.com/users/20438263",
"pm_score": 0,
"selected": false,
"text": "SELECT SUM(COUNT(id)) as Total\nFROM student\nGROUP BY LOWER(first_name) HAVING COUNT(LOWER(first_name)) > 1;\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19768549/"
] |
74,343,755 | <p>I am using Python to analyze a data set that has a column with a year range (see below for example):</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Name</th>
<th>Years Range</th>
</tr>
</thead>
<tbody>
<tr>
<td>Andy</td>
<td>1985 - 1987</td>
</tr>
<tr>
<td>Bruce</td>
<td>2011 - 2018</td>
</tr>
</tbody>
</table>
</div>
<p>I am trying to convert the "Years Range" column that has a string of start and end years into two separate columns within the data frame to: "Year Start" and "Year End".</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Name</th>
<th>Years Range</th>
<th>Year Start</th>
<th>Year End</th>
</tr>
</thead>
<tbody>
<tr>
<td>Andy</td>
<td>1985 - 1987</td>
<td>1985</td>
<td>1987</td>
</tr>
<tr>
<td>Bruce</td>
<td>2011 - 2018</td>
<td>2011</td>
<td>2018</td>
</tr>
</tbody>
</table>
</div> | [
{
"answer_id": 74343881,
"author": "Bhargav",
"author_id": 15358800,
"author_profile": "https://Stackoverflow.com/users/15358800",
"pm_score": 3,
"selected": true,
"text": "split"
},
{
"answer_id": 74343953,
"author": "koding_buse",
"author_id": 20166777,
"author_profile": "https://Stackoverflow.com/users/20166777",
"pm_score": 1,
"selected": false,
"text": "str.extract"
},
{
"answer_id": 74344260,
"author": "mildgrey",
"author_id": 20189731,
"author_profile": "https://Stackoverflow.com/users/20189731",
"pm_score": 0,
"selected": false,
"text": "df['start']=''#create a blank column name 'start'\ndf['end']=''#create a blank column name 'end'\n#loop over the data frame\nfor i in range(len(df)):\n df['start'][i]=df['Year'][i].split('-')[0]#split each data and store first element\n df['end'][i]=df['Year'][i].split('-')[1]#split each data and store second element\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20437267/"
] |
74,343,766 | <p>I am using the <code>RadzenDatePicker</code> to get time value only. I have managed to make it show only time instead of the calendar, however, I can't bind it's value which is <code>DateTime</code> to <code>TimeOnly</code>.</p>
<p>Is there a way I can bind the <code>RadzenDatePicker</code> below to <code>TimeOnly</code> property?</p>
<p>Code:</p>
<pre class="lang-razor prettyprint-override"><code><RadzenDatePicker style="display: block; width: 100%"
@bind-Value="@station.OpenTime"
Name="OpenTime"
TValue="TimeOnly"
ShowTime="true"
HourFormat="12"
TimeOnly="true"/>
</code></pre>
<p>Control:</p>
<p><a href="https://i.stack.imgur.com/jv27w.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jv27w.png" alt="Radzen DatePicker to TimeSpan" /></a></p>
<p>Error:</p>
<pre class="lang-cmd prettyprint-override"><code>System.InvalidCastException: Unable to cast object of type 'System.DateTime' to type 'System.TimeOnly'.
at Radzen.Blazor.RadzenDatePicker`1.OnChange()
at Radzen.Blazor.RadzenDatePicker`1.OkClick()
at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task)
at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle, ComponentState owningComponentState)
</code></pre>
| [
{
"answer_id": 74343881,
"author": "Bhargav",
"author_id": 15358800,
"author_profile": "https://Stackoverflow.com/users/15358800",
"pm_score": 3,
"selected": true,
"text": "split"
},
{
"answer_id": 74343953,
"author": "koding_buse",
"author_id": 20166777,
"author_profile": "https://Stackoverflow.com/users/20166777",
"pm_score": 1,
"selected": false,
"text": "str.extract"
},
{
"answer_id": 74344260,
"author": "mildgrey",
"author_id": 20189731,
"author_profile": "https://Stackoverflow.com/users/20189731",
"pm_score": 0,
"selected": false,
"text": "df['start']=''#create a blank column name 'start'\ndf['end']=''#create a blank column name 'end'\n#loop over the data frame\nfor i in range(len(df)):\n df['start'][i]=df['Year'][i].split('-')[0]#split each data and store first element\n df['end'][i]=df['Year'][i].split('-')[1]#split each data and store second element\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8316900/"
] |
74,343,790 | <p>I'm trying to verify a Firebase generated JWT token with an Ambassador Edge Stack (datawire/edge-stack version 3.3.0) Filter.</p>
<p>The Firebase token is generated using a login/password authent mechanism on firebase, something like (in Python):</p>
<pre class="lang-py prettyprint-override"><code> email=input("Enter email: ")
password=input("Enter password: ")
user = authentication.sign_in_with_email_and_password(email, password)
custom_token = auth.create_custom_token(user["localId"], additional_claims)
print("JWT Token :")
print(custom_token)
</code></pre>
<p>After the token is generated, I use it with a curl command such as:</p>
<pre class="lang-bash prettyprint-override"><code>curl -H "Authorization: Bearer $TOKEN" https://ambassador-ip.nip.io/hello-world/
</code></pre>
<p>and the curl command returns the following error:</p>
<pre class="lang-bash prettyprint-override"><code> },
"message": "Token validation error: token is invalid: errorFlags=0x00000002=(ValidationErrorUnverifiable) wrappedError=(KeyID=\"50***redacted***1\": JWK not found)",
"status_code": 401
}
</code></pre>
<p>Here is the ambassador Filter I've declared:</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: getambassador.io/v2
kind: Filter
metadata:
name: "firebase-filter"
namespace: ${kubernetes_namespace.hello_world.metadata[0].name}
spec:
JWT:
jwksURI: "https://www.googleapis.com/service_accounts/v1/metadata/x509/securetoken@system.gserviceaccount.com"
audience: "${local.project_id}"
issuer: "https://securetoken.google.com/${local.project_id}"
</code></pre>
<p>And the policy filter applied to my backend:</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: getambassador.io/v3alpha1
kind: FilterPolicy
metadata:
name: "firebase-filter-policy"
namespace: ${kubernetes_namespace.hello_world.metadata[0].name}
spec:
rules:
- host: "*"
path: "/hello-world/"
filters:
- name: "firebase-filter"
namespace: "${kubernetes_namespace.hello_world.metadata[0].name}"
</code></pre>
<p>For the record, the curl command with the same token works on a deployed hello-world Cloud Run with a GCP API gateway configured as follow:</p>
<pre class="lang-yaml prettyprint-override"><code>swagger: '2.0'
info:
title: Example Firebase auth Gateway
description: API Gateway with firebase auth
version: 1.0.0
schemes:
- https
produces:
- application/json
securityDefinitions:
firebase:
authorizationUrl: ''
flow: implicit
type: oauth2
x-google-issuer: "https://securetoken.google.com/${project_id}"
x-google-jwks_uri: "https://www.googleapis.com/service_accounts/v1/metadata/x509/securetoken@system.gserviceaccount.com"
x-google-audiences: "${project_id}"
paths:
/v1/hello:
get:
security:
- firebase: []
description: Hello
operationId: hello
responses:
'200':
description: Success
x-google-backend:
address: 'https://hello-redacted-ew.a.run.app'
</code></pre>
<p>Any idea why the Ambassador filter is misconfigured ?</p>
| [
{
"answer_id": 74343881,
"author": "Bhargav",
"author_id": 15358800,
"author_profile": "https://Stackoverflow.com/users/15358800",
"pm_score": 3,
"selected": true,
"text": "split"
},
{
"answer_id": 74343953,
"author": "koding_buse",
"author_id": 20166777,
"author_profile": "https://Stackoverflow.com/users/20166777",
"pm_score": 1,
"selected": false,
"text": "str.extract"
},
{
"answer_id": 74344260,
"author": "mildgrey",
"author_id": 20189731,
"author_profile": "https://Stackoverflow.com/users/20189731",
"pm_score": 0,
"selected": false,
"text": "df['start']=''#create a blank column name 'start'\ndf['end']=''#create a blank column name 'end'\n#loop over the data frame\nfor i in range(len(df)):\n df['start'][i]=df['Year'][i].split('-')[0]#split each data and store first element\n df['end'][i]=df['Year'][i].split('-')[1]#split each data and store second element\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1823046/"
] |
74,343,792 | <p>This is my code below and I cant seem to make my while loop run continuosly.</p>
<pre><code>#alphabet list
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
# user input message
text = input("Type your message:\n")
# user input shift amount
shift = int(input("Type the shift number:\n"))
# def function
def encode(plain_text, shift_amount):
cipher_text = ''
for letter in plain_text:
position = alphabet.index(letter)
new_position = position + shift_amount
new_letter = alphabet[new_position]
cipher_text += new_letter
print(f'The encoded string is: {cipher_text}')
encode(plain_text = text, shift_amount = shift)
while True:
if text != 'q':
continue
</code></pre>
<p>I am not sure if I set this up correctly.</p>
| [
{
"answer_id": 74343881,
"author": "Bhargav",
"author_id": 15358800,
"author_profile": "https://Stackoverflow.com/users/15358800",
"pm_score": 3,
"selected": true,
"text": "split"
},
{
"answer_id": 74343953,
"author": "koding_buse",
"author_id": 20166777,
"author_profile": "https://Stackoverflow.com/users/20166777",
"pm_score": 1,
"selected": false,
"text": "str.extract"
},
{
"answer_id": 74344260,
"author": "mildgrey",
"author_id": 20189731,
"author_profile": "https://Stackoverflow.com/users/20189731",
"pm_score": 0,
"selected": false,
"text": "df['start']=''#create a blank column name 'start'\ndf['end']=''#create a blank column name 'end'\n#loop over the data frame\nfor i in range(len(df)):\n df['start'][i]=df['Year'][i].split('-')[0]#split each data and store first element\n df['end'][i]=df['Year'][i].split('-')[1]#split each data and store second element\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20438282/"
] |
74,343,796 | <p>I want to get a random character from MongoDB, but my call keeps getting used in another GET method.</p>
<pre><code>// Get Specific Character by ID
router.get('/:char_id', async (req, res, next) => {
try {
const character = await Character.find({ char_id: req.params.char_id });
if (character.length == 0) return res.status(404).json({ message: 'No characters found with ID: ' + req.params.char_id });
else { res.status(200).json(character) };
} catch (err) {
res.status(500).json({ message: err.message });
}
});
// Get Random Character
router.get('/random', async (req, res, next) => {
try {
const characters = await Character.find();
if (characters.length == 0) return res.status(404).json({ message: 'No characters found in the database. Something must have went wrong.' });
else {
const random = Math.floor(Math.random() * characters.length);
res.status(200).json(characters[random]);
};
} catch (err) {
res.status(500).json({ message: err.message });
}
});
</code></pre>
<p>When I call /characters/random, I get this error because first GET method above tries to pass word random to find character by ID (If I'm not wrong).</p>
<blockquote>
<p>"message": "Cast to Number failed for value "random" (type string) at path "char_id" for model "Character""</p>
</blockquote>
<p>How do I avoid this?</p>
| [
{
"answer_id": 74343881,
"author": "Bhargav",
"author_id": 15358800,
"author_profile": "https://Stackoverflow.com/users/15358800",
"pm_score": 3,
"selected": true,
"text": "split"
},
{
"answer_id": 74343953,
"author": "koding_buse",
"author_id": 20166777,
"author_profile": "https://Stackoverflow.com/users/20166777",
"pm_score": 1,
"selected": false,
"text": "str.extract"
},
{
"answer_id": 74344260,
"author": "mildgrey",
"author_id": 20189731,
"author_profile": "https://Stackoverflow.com/users/20189731",
"pm_score": 0,
"selected": false,
"text": "df['start']=''#create a blank column name 'start'\ndf['end']=''#create a blank column name 'end'\n#loop over the data frame\nfor i in range(len(df)):\n df['start'][i]=df['Year'][i].split('-')[0]#split each data and store first element\n df['end'][i]=df['Year'][i].split('-')[1]#split each data and store second element\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14510980/"
] |
74,343,859 | <p>I want to override a class from the JMS/serializer bundle. Unfortunately this class is marked "final" and I can't override it. What would be the best method to circumvent this problem please?
I'm on symfony5.4</p>
<p>Here is the class I want to override :</p>
<pre><code><?php
declare(strict_types=1);
namespace JMS\Serializer\Handler;
use JMS\Serializer\GraphNavigatorInterface;
use JMS\Serializer\Visitor\SerializationVisitorInterface;
use JMS\Serializer\XmlSerializationVisitor;
use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Contracts\Translation\TranslatorInterface as TranslatorContract;
use function get_class;
final class FormErrorHandler implements SubscribingHandlerInterface
{
/**
* @var TranslatorInterface|null
*/
private $translator;
/**
* @var string
*/
private $translationDomain;
</code></pre>
| [
{
"answer_id": 74344222,
"author": "hassan",
"author_id": 2359679,
"author_profile": "https://Stackoverflow.com/users/2359679",
"pm_score": 1,
"selected": false,
"text": "SerializeBuilder"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20089108/"
] |
74,343,860 | <p><a href="https://imgur.com/a/BYCCRPs" rel="nofollow noreferrer">https://imgur.com/a/BYCCRPs</a> how do i move the start button down using alignment axies? i have created another page for the start button to go into that new page (settingpage.dart).
how to i navigate to the next page ?</p>
<p>Thanks for your help.</p>
<pre><code>import 'dart:async';
import 'package:flutter/material.dart';
import 'package:myapp/updown.dart';
class Homepage extends StatefulWidget {
const Homepage({super.key});
@override
State<Homepage> createState() => _HomepageState();
}
class _HomepageState extends State<Homepage> {
double UpdownY = -0.6;
void jump() {
Timer.periodic(const Duration(milliseconds: 50), (timer) {
setState(() {
UpdownY -= 0.05;
});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Expanded(
child: Container(
color: Colors.black,
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Updown(
updownY: UpdownY,
),
GestureDetector(
onLongPress: () => "Navigate",
child: const Image(
height: 100,
width: 100,
image: AssetImage("lib/images/start-png.png")))
],
)),
))
],
),
);
}
}
</code></pre>
| [
{
"answer_id": 74344222,
"author": "hassan",
"author_id": 2359679,
"author_profile": "https://Stackoverflow.com/users/2359679",
"pm_score": 1,
"selected": false,
"text": "SerializeBuilder"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20438315/"
] |
74,343,868 | <p>I use postman call my api and here is the response.</p>
<p>I want to modify this object key into "id" and value is auto increment(1,2,3....), the value of original key( "amount 100~1000": 2) as "count" like expect to get down below.</p>
<pre><code>data = {
"amount 100~1000": 2,
"amount 1001~2000": 4,
"amount 2001~3000": 1,
"amount 3001~4000": 2,
}
</code></pre>
<p>here is what i tried, i really don't know how to do this using for loop (or maybe forEach is better way?)</p>
<pre><code>const x = Object.values(data[0])
let id = 1;
let count;
let arr = [];
for (let index = 0; index < x.length; index++) {
id++
const obj = { id: index }
arr.push(obj)
}
console.log(arr);// [ { id: 0 }, { id: 1 }, { id: 2 }, { id: 3 } ]
</code></pre>
<p>expect to get:</p>
<pre><code>{
"id":1, // amount 100~1000
"count": 2,
},
{
"id":2, // amount 1001~2000
"count": 4,
},
{
"id":3, // amount 2001~3000
"count": 1,
},
.
.
.
</code></pre>
| [
{
"answer_id": 74343936,
"author": "Nir Levy",
"author_id": 130304,
"author_profile": "https://Stackoverflow.com/users/130304",
"pm_score": 2,
"selected": true,
"text": "const input = data[0];\nconst keys = Object.keys(input);\nconst output = [];\nkeys.sort((a, b) => a.localeCompare(b, { numeric: true })).forEach((key, idx) => {\n output.push({id: idx+1, count: input[key]})\n})\nconsole.log(output);\n"
},
{
"answer_id": 74343990,
"author": "Raphael Ben Hamo",
"author_id": 8776661,
"author_profile": "https://Stackoverflow.com/users/8776661",
"pm_score": 0,
"selected": false,
"text": "let data = {\n \"amount 100~1000\": 2,\n \"amount 1001~2000\": 4,\n \"amount 2001~3000\": 1,\n \"amount 3001~4000\": 2,\n}\n\nlet list = []\n\nlet dataValuesList = Object.values(data)\n\nfor(let i = 1; i <= dataValuesList.length;i++){\n list.push({\n id: i,\n count: dataValuesList[i-1]\n })\n}\n\nconsole.table(list)"
},
{
"answer_id": 74344176,
"author": "Selim",
"author_id": 14384258,
"author_profile": "https://Stackoverflow.com/users/14384258",
"pm_score": 0,
"selected": false,
"text": "Object.keys()"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19304185/"
] |
74,343,895 | <p>I have a column with data like
9 years 3 months 22 days. How to convert it into
=9+(3/12)+(22/365)
=9.31</p>
<p>I want output as 9.31.</p>
<p>How to do the same in python? Please anyone can help me out?</p>
| [
{
"answer_id": 74343936,
"author": "Nir Levy",
"author_id": 130304,
"author_profile": "https://Stackoverflow.com/users/130304",
"pm_score": 2,
"selected": true,
"text": "const input = data[0];\nconst keys = Object.keys(input);\nconst output = [];\nkeys.sort((a, b) => a.localeCompare(b, { numeric: true })).forEach((key, idx) => {\n output.push({id: idx+1, count: input[key]})\n})\nconsole.log(output);\n"
},
{
"answer_id": 74343990,
"author": "Raphael Ben Hamo",
"author_id": 8776661,
"author_profile": "https://Stackoverflow.com/users/8776661",
"pm_score": 0,
"selected": false,
"text": "let data = {\n \"amount 100~1000\": 2,\n \"amount 1001~2000\": 4,\n \"amount 2001~3000\": 1,\n \"amount 3001~4000\": 2,\n}\n\nlet list = []\n\nlet dataValuesList = Object.values(data)\n\nfor(let i = 1; i <= dataValuesList.length;i++){\n list.push({\n id: i,\n count: dataValuesList[i-1]\n })\n}\n\nconsole.table(list)"
},
{
"answer_id": 74344176,
"author": "Selim",
"author_id": 14384258,
"author_profile": "https://Stackoverflow.com/users/14384258",
"pm_score": 0,
"selected": false,
"text": "Object.keys()"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2567340/"
] |
74,343,919 | <p>I am practicing a simple application that reads and writes to a file.
I'm using <strong>writeFile</strong> from <strong>"fs/promises"</strong></p>
<p>When I import the file with the correct string I get the desired file</p>
<pre><code>const content: Employe_T_nodel[] = require('../databace/employees.json')
</code></pre>
<p>But when I try to write to the file, I get an error:
no such file or directory, open 'D: ...</p>
<p>This is the code I use.
Note that I use the exact same string</p>
<pre><code>async function saveAllEmployeesAsync(employeesArr: Employe_T_nodel[]) {
const content: string = JSON.stringify(employeesArr)
await writeFile('../databace/employees.json', content)
return console.log("Employees saved sucsessfuly")
}
</code></pre>
<p>I don't understand why one function gets the path string and one doesn't</p>
| [
{
"answer_id": 74344022,
"author": "Tsvetan Ganev",
"author_id": 8597510,
"author_profile": "https://Stackoverflow.com/users/8597510",
"pm_score": 3,
"selected": true,
"text": "require()"
},
{
"answer_id": 74344596,
"author": "fatima hassan",
"author_id": 8891459,
"author_profile": "https://Stackoverflow.com/users/8891459",
"pm_score": 0,
"selected": false,
"text": "fs.writeFile(dir, data, err => {\n if (err) {\n console.log(\"File not saved! \", err);\n return err;\n } else {\n console.log(\"File saved!\");\n return 200;\n }\n});\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18182422/"
] |
74,343,930 | <p>Environment
Laravel v9 + vite, PHP 8.1, vue3, VPS linux distro. UBUNTU</p>
<p><a href="https://i.stack.imgur.com/yIyC7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yIyC7.png" alt="enter image description here" /></a></p>
<p>I am having this error in the vue.js component of my Laravel project,it says that the profile_picture has a null value in the object but I also put the check for this</p>
<pre><code> <div v-if="typeof rep.user.profile_picture != null">
<img :src="rep.user.profile_picture" :alt="rep.user.name" class="commenter-image rounded-circle"/>
</div>
<div v-else>
<img src="/assets/images/user-placeholder-1.jpg" alt="Commenter-placeholder" class="commenter-image rounded-circle"/>
</div>
</code></pre>
<p>I have carefully searched for this profile_picture property in the file it's not anywhere else except this. but still having this issue
also, it doesn't have any relation with the sweetalert2 library but still, console is pointing to this library
Any thoughts about this error??
extra help meterial>></p>
<p><a href="https://i.stack.imgur.com/KezD7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KezD7.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74344016,
"author": "Sergey Andreev",
"author_id": 8427699,
"author_profile": "https://Stackoverflow.com/users/8427699",
"pm_score": 2,
"selected": false,
"text": "v-if=\"typeof rep.user.profile_picture != null\""
},
{
"answer_id": 74344193,
"author": "Rohìt Jíndal",
"author_id": 4116300,
"author_profile": "https://Stackoverflow.com/users/4116300",
"pm_score": 2,
"selected": true,
"text": "rep"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12120881/"
] |
74,343,960 | <p>I am trying to understand JWT based authentication , following one of the you tube channel. It was mentioned to add the following contents in appsettings.json</p>
<pre><code> "AllowedHosts": "*",
"JWT": {
"SecretKey": "A247DB24-C8AE-4B8A-8CB2-59637754BF2F",
"Issuer": "JokenTokenAuthorize",
"Audience" : "JokenTokenAuthorize"
}
</code></pre>
<p>use the following code for the generation of JWT</p>
<pre><code>var SecretKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(token));
var authClaims = new List<Claim>
{
new Claim(ClaimTypes.Name , userDetails.UserName),
new Claim(ClaimTypes.Email, userDetails.UserName),
new Claim(JwtRegisteredClaimNames.Jti , Guid.NewGuid().ToString())
};
var tokengnerate = new JwtSecurityToken(
issuer: Configuration["JWT:Issuer"],
audience: Configuration["JWT:Audience"],
claims: authClaims,
expires: DateTime.Now.AddDays(1),
signingCredentials: new SigningCredentials(SecretKey, SecurityAlgorithms.HmacSha256Signature)
var tokenDAta = new JwtSecurityTokenHandler().WriteToken(tokengnerate);
</code></pre>
<p>As per the link
<a href="https://stackoverflow.com/questions/31309759/what-is-secret-key-for-jwt-based-authentication-and-how-to-generate-it">What is secret key for JWT based authentication and how to generate it?</a>
The algorithm (HS256) used to sign the JWT means that the secret is a symmetric key that is known by both the sender and the receiver</p>
<p>What's the secret key means -> the one which is stored at server (appsettings.json) or the one which is returned by var SecretKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(token));</p>
<p>Got confused with terms secret, public or private keys</p>
| [
{
"answer_id": 74344016,
"author": "Sergey Andreev",
"author_id": 8427699,
"author_profile": "https://Stackoverflow.com/users/8427699",
"pm_score": 2,
"selected": false,
"text": "v-if=\"typeof rep.user.profile_picture != null\""
},
{
"answer_id": 74344193,
"author": "Rohìt Jíndal",
"author_id": 4116300,
"author_profile": "https://Stackoverflow.com/users/4116300",
"pm_score": 2,
"selected": true,
"text": "rep"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18451141/"
] |
74,343,961 | <p>I'm trying to save file name , my filename should be like this "doc00012dsadfile5.jpg"</p>
<pre><code>filename = "doc00012dsad.pdf"
mypath = "/desktop/myfolder/"
_path = os.path.join(mypath,"images")
num = 5
#filename.split(".pdf",1)[0]
os.path.join(_path, file%d.jpg" % num), xx)
</code></pre>
| [
{
"answer_id": 74344016,
"author": "Sergey Andreev",
"author_id": 8427699,
"author_profile": "https://Stackoverflow.com/users/8427699",
"pm_score": 2,
"selected": false,
"text": "v-if=\"typeof rep.user.profile_picture != null\""
},
{
"answer_id": 74344193,
"author": "Rohìt Jíndal",
"author_id": 4116300,
"author_profile": "https://Stackoverflow.com/users/4116300",
"pm_score": 2,
"selected": true,
"text": "rep"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74343961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20437152/"
] |
74,344,033 | <p>I am getting below response from api .
Below is sample respone not real
Each object has createdDate , I have to group value is days wise like on 2022-09-20 (Tuesday) there are 2 customerId created and on 2022-09-21 (Wednesday) only one.</p>
<pre><code>{
"data": {
"fetchOrdersAndRequest": [
{
"id": "PI786971",
"customerId": [
"C200147"
],
"createdDate": "2022-09-21T04:46:00.126Z",
}
{
"id": "PI786969",
"customerId": [
"C200146"
],
"createdDate": "2022-09-20T04:46:00.126Z",
}
{
"id": "PI786968",
"customerId": [
"C200145"
],
"createdDate": "2022-09-20T04:46:00.126Z",
}
]
}
}
</code></pre>
<p>I have to convert the response like , Tuesday I have 2 response so it should come in tue array and
Wedensday one so only one and rest emply , but if data come for other days also it should filled in there days .</p>
<pre><code> {
period:'lastWeek',
data:[
{
"key":"SUN",
"value" : []
},
{
"key":"MON",
"value" : []
},
{
"key":"TUE",
"value" : [{},{}],
},
{
"key":"WED",
"value" : [{}],
},
{
"key":"THU",
"value" : []
},
{
"key":"FRI",
"value" : []
},
{
"key":"SAT",
"value" : []
}
]
</code></pre>
<p>Please help .
Thank you</p>
| [
{
"answer_id": 74344273,
"author": "cmgchess",
"author_id": 13583510,
"author_profile": "https://Stackoverflow.com/users/13583510",
"pm_score": 2,
"selected": true,
"text": "Date"
},
{
"answer_id": 74344276,
"author": "Gijs Beijer",
"author_id": 2224937,
"author_profile": "https://Stackoverflow.com/users/2224937",
"pm_score": 0,
"selected": false,
"text": "new Date(item.createdDate).getDay()"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74344033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6419405/"
] |
74,344,065 | <p>I'm trying to change the value of the text which is the 'placeholder' in this method. But for some reason it's not updating to the new value that i wrote & retrieved from the dialog. I even tested to see what's the value of 'placeholder' and it returned the correct value/text that i wrote in the dialog but still it wasn't updated in the card.</p>
<pre><code>Widget buildTextField(
String subtitle, String placeholder,icon) {
// ignore: dead_code
return Padding(
padding: const EdgeInsets.only(bottom: 15.0),
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0)),
color: Colors.white,
margin: EdgeInsets.fromLTRB(100, 10, 100, 10),
child: ListTile(
title: Text(placeholder),
subtitle: Text(subtitle),
leading: Icon(
icon,
color: Color.fromARGB(255, 44, 148, 233),
),
trailing: IconButton(
onPressed: () async {
final name = await openDialog(subtitle,placeholder);
if(name == null || name.isEmpty) return;
print(name);
setState(() => placeholder = name);
print(placeholder);
//this.title: Text(placeholder);
// setState(() {
// placeholder = this.name;
// });
},
icon: Icon(Icons.edit_outlined),
), ),
),
);
}
Future <String?>openDialog(String subtitle, String placeholder) => showDialog<String>
(
context: context, builder: (context)=> AlertDialog(
title: Text(subtitle),
content: TextField(autofocus: true,
decoration: InputDecoration(hintText: 'Enter your name'),
controller: controller ..text = placeholder,
// controller: controller,
),
actions: [
TextButton(onPressed: submit,
child: Text('Save'))
],
),
);
void submit(){
// Navigator.of(context).pop(controller.text);
Navigator.of(context, rootNavigator: true).pop(controller.text);
}
</code></pre>
| [
{
"answer_id": 74344273,
"author": "cmgchess",
"author_id": 13583510,
"author_profile": "https://Stackoverflow.com/users/13583510",
"pm_score": 2,
"selected": true,
"text": "Date"
},
{
"answer_id": 74344276,
"author": "Gijs Beijer",
"author_id": 2224937,
"author_profile": "https://Stackoverflow.com/users/2224937",
"pm_score": 0,
"selected": false,
"text": "new Date(item.createdDate).getDay()"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74344065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18464277/"
] |
74,344,072 | <p>I'm developing the interface of a music web app , so i fetched data from an API and stored in state, all executed by one function , to be displayed on the interphase .The code is below :</p>
<pre><code>/* function fetching the data*/
function getUsChart() {
const options = {
method: 'GET',
headers: {
'X-RapidAPI-Key': '036795ec2amsh8c2b98ef8a502acp146724jsn6f3538b26522',
'X-RapidAPI-Host': 'shazam-core.p.rapidapi.com'
}
};
fetch('https://shazam-core.p.rapidapi.com/v1/charts/genre-country?country_code=US&genre_code=HIP_HOP_RAP', options)
.then(response => response.json())
.then(response => setUsHopChart(response))
.catch(err => console.error(err));
/*I stored it in state here*/
setChartImg(usHopChart[1]?.images?.coverart)
}
</code></pre>
<pre><code>/*I displayed it here*/
<img src={chartImg} className='chart-img rounded-3xl' alt='chart-image'/>
</code></pre>
<p><strong>The issue:</strong>
After the function is executed , the data is fetched but not stored it in the state immediately until it's executed the second time. Hence causing this :
<a href="https://i.stack.imgur.com/F8doV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/F8doV.png" alt="enter image description here" /></a></p>
<p>What can i do about this please?</p>
| [
{
"answer_id": 74344273,
"author": "cmgchess",
"author_id": 13583510,
"author_profile": "https://Stackoverflow.com/users/13583510",
"pm_score": 2,
"selected": true,
"text": "Date"
},
{
"answer_id": 74344276,
"author": "Gijs Beijer",
"author_id": 2224937,
"author_profile": "https://Stackoverflow.com/users/2224937",
"pm_score": 0,
"selected": false,
"text": "new Date(item.createdDate).getDay()"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74344072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17492736/"
] |
74,344,078 | <p>I'm new to c++ and don't know how to let main thread wait for all async threads done. I refered <a href="https://stackoverflow.com/questions/66265652/wait-for-async-file-write-to-finish-before-exiting-main-thread">this</a> but makes void consume() not parallel.</p>
<pre><code>#include <iostream>
#include <vector>
#include <unistd.h> // sleep
#include <future>
using namespace std;
class Myclass {
private:
std::vector<int> resources;
std::vector<int> res;
std::mutex resMutex;
std::vector<std::future<void>> m_futures;
public:
Myclass() {
for (int i = 0; i < 10; i++) resources.push_back(i); // add task
res.reserve(resources.size());
}
void consume() {
for (int i = 0; i < resources.size(); i++) {
m_futures.push_back(std::async(std::launch::async, &Myclass::work, this, resources[i]));
// m_futures.back().wait();
}
}
void work(int x) {
sleep(1); // Simulation time-consuming
std::lock_guard<std::mutex> lock(resMutex);
res.push_back(x);
printf("%d be added.---done by %d.\n", x, std::this_thread::get_id());
}
std::vector<int> &getRes() { return res;}
};
int main() {
Myclass obj;
obj.consume();
auto res = obj.getRes();
cout << "Done. res.size = " << res.size() << endl;
for (int i : res) cout << i << " ";
cout <<"main thread over\n";
}
</code></pre>
<p>Main thread ends up when res = 0. I want obj.getRes() be be executed when all results be added into res.</p>
<pre><code>Done. res.size = 0
main thread over
4 be added.---done by 6.
9 be added.---done by 11...
</code></pre>
| [
{
"answer_id": 74344319,
"author": "Frodyne",
"author_id": 11829247,
"author_profile": "https://Stackoverflow.com/users/11829247",
"pm_score": 1,
"selected": false,
"text": "m_futures.back().wait();"
},
{
"answer_id": 74344361,
"author": "Artyom Grigorian",
"author_id": 17489971,
"author_profile": "https://Stackoverflow.com/users/17489971",
"pm_score": 0,
"selected": false,
"text": "consume()"
},
{
"answer_id": 74344459,
"author": "GAVD",
"author_id": 4983082,
"author_profile": "https://Stackoverflow.com/users/4983082",
"pm_score": 0,
"selected": false,
"text": "m_futures"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74344078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19936966/"
] |
74,344,080 | <p>I want to list customer_id's that have made purchases from every distinctly available year from a column.</p>
<p>The column is in sales.orders called 'order_date'</p>
<p>This is what I've done so far (didn't work):</p>
<pre><code>--List customers who've made purchases in every year
SELECT customer_id
FROM sales.orders
WHERE year(order_date) = ALL (
select distinct YEAR(order_date)
from sales.orders
)
</code></pre>
<p>I wanted something that shows the customer_id only if they've made purchases at least once a year since opening.</p>
| [
{
"answer_id": 74344319,
"author": "Frodyne",
"author_id": 11829247,
"author_profile": "https://Stackoverflow.com/users/11829247",
"pm_score": 1,
"selected": false,
"text": "m_futures.back().wait();"
},
{
"answer_id": 74344361,
"author": "Artyom Grigorian",
"author_id": 17489971,
"author_profile": "https://Stackoverflow.com/users/17489971",
"pm_score": 0,
"selected": false,
"text": "consume()"
},
{
"answer_id": 74344459,
"author": "GAVD",
"author_id": 4983082,
"author_profile": "https://Stackoverflow.com/users/4983082",
"pm_score": 0,
"selected": false,
"text": "m_futures"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74344080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15407573/"
] |
74,344,082 | <p>How to make Extended floating popup in bottomBarNavigation, like in this image</p>
<p><a href="https://i.stack.imgur.com/TYYef.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TYYef.png" alt="Want this type of design" /></a></p>
| [
{
"answer_id": 74344317,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 3,
"selected": true,
"text": "BottomNavigationBar"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74344082",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16220278/"
] |
74,344,085 | <p>As of now, I can delete a record based on rank without checking if it exists, after that, it will pop up a message "Movie deleted" to notify the user.</p>
<pre><code>protected void bn_delete_Click(object sender, EventArgs e)
{
string rank = tb_rank.Text;
string query = "SELECT * FROM MovieList WHERE Rank= @Rank";
new System.Data.OleDb.OleDbCommand(query, new System.Data.OleDb.OleDbConnection(connectionString));
System.Data.OleDb.OleDbCommand ocmd =
new System.Data.OleDb.OleDbCommand(query,
new System.Data.OleDb.OleDbConnection(connectionString));
ocmd.CommandType = CommandType.Text;
ocmd.CommandText = "DELETE FROM MovieList WHERE Rank= @Rank";
ocmd.Parameters.AddWithValue("@Rank", rank);
ocmd.Connection.Open();
ocmd.ExecuteNonQuery();
ocmd.Connection.Close();
string notification = "Movie deleted";
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + notification + "');", true);
}
</code></pre>
<p>How can I make sure that the record exists first before deleting it?
If the record does not exist, I want to pop up a message showing "Movie not exists" and do nothing.</p>
<p>Thank you!</p>
| [
{
"answer_id": 74344167,
"author": "rbdeenk",
"author_id": 18278998,
"author_profile": "https://Stackoverflow.com/users/18278998",
"pm_score": 1,
"selected": false,
"text": "ExecuteNonQuery()"
},
{
"answer_id": 74344178,
"author": "Zohar Peled",
"author_id": 3094533,
"author_profile": "https://Stackoverflow.com/users/3094533",
"pm_score": 3,
"selected": true,
"text": "ExecuteNonQuery()"
},
{
"answer_id": 74344390,
"author": "Relaxed Coder",
"author_id": 20314053,
"author_profile": "https://Stackoverflow.com/users/20314053",
"pm_score": 0,
"selected": false,
"text": "ExecuteNonQuery"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74344085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20438172/"
] |
74,344,124 | <p>I have this time here : <code>2017-08-05T05:21:10.6582942Z</code><br />
And I want to convert it into <code>%Y-%m-%d %H:%M:%S</code><br />
I can do that using some funky methods such as :</p>
<pre class="lang-py prettyprint-override"><code>date = "2017-08-05T05:21:10.6582942Z"
new_date = date[:11] + " " + date[12:][:-9]
</code></pre>
<p>But is there any way I can do something cleaner with <code>datetime</code> or some libraries made for this specific purpose ?</p>
| [
{
"answer_id": 74344362,
"author": "The Myth",
"author_id": 15042008,
"author_profile": "https://Stackoverflow.com/users/15042008",
"pm_score": 0,
"selected": false,
"text": "datetime"
},
{
"answer_id": 74344503,
"author": "S3DEV",
"author_id": 6340496,
"author_profile": "https://Stackoverflow.com/users/6340496",
"pm_score": 1,
"selected": false,
"text": "datetime"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74344124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12025753/"
] |
74,344,136 | <p>Its probably a <em>very</em> basic thing.</p>
<p>but i was wondering how to calculate and sum up the result in a new column.</p>
<p>lets say i have a variable that holds this table below</p>
<pre><code>fresh apples eaten
------------ -----
2 1
71 15
89 32
</code></pre>
<hr />
<p>i was wondering then, how i could calculate and present <strong>this</strong>:</p>
<pre><code>fresh apples eaten available
------------ ----- ---------
2 1 1
71 15 56
89 32 57
</code></pre>
<hr />
<p>Any tips or help would be <strong>awesome :)</strong></p>
| [
{
"answer_id": 74344362,
"author": "The Myth",
"author_id": 15042008,
"author_profile": "https://Stackoverflow.com/users/15042008",
"pm_score": 0,
"selected": false,
"text": "datetime"
},
{
"answer_id": 74344503,
"author": "S3DEV",
"author_id": 6340496,
"author_profile": "https://Stackoverflow.com/users/6340496",
"pm_score": 1,
"selected": false,
"text": "datetime"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74344136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17070371/"
] |
74,344,183 | <p>I have to create a progress bar that has to be fully responsive. In order to be responsive I don't want the progress bar class to have a fixed width, but when I put auto in width, line of progress bar is detached from the star also if I give to them auto width</p>
<p>Fixed width: look good
<a href="https://i.stack.imgur.com/n3yu7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/n3yu7.png" alt="enter image description here" /></a></p>
<p>Width auto
<a href="https://i.stack.imgur.com/zs2KF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zs2KF.png" alt="enter image description here" /></a></p>
<p>First how can I fix this issue, and perhaps someone can help me achieve this progress bar to be responsive on mobile also so that the line of progress bar will be vertical.</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>.progress-bar {
width: 750px;
display: flex;
margin: 40px 0;
}
.progress-bar .step {
text-align: center;
width: 100%;
}
.progress-bar .step .bullet {
position: relative;
height: 25px;
width: 25px;
display: inline-block;
}
.progress-bar .step:last-child .bullet:before,
.progress-bar .step:last-child .bullet::after {
display: none;
}
.progress-bar .step .bullet:before,
.progress-bar .step .bullet::after {
position: absolute;
content: "";
height: 3px;
right: -136px;
bottom: 11px;
width: 142px;
background: #C1C1C1;
}
.active-bullet {
z-index: 1;
}
.active-check {
z-index: 2;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="progress-bar">
<div class="step">
<div class="bullet active-bullet">
<img src="star-pb-active.svg">
</div>
<div class="check active-check" style="
border-bottom: 2px solid black;
padding: 2px;
DISPLAY: table-cell;
LEFT: 40px;
POSITION: relative;
">Order placed</div>
</div>
<div class="step">
<div class="bullet">
<img src="star-pb.svg">
</div>
<div class="check">Jewerly Creation</div>
</div>
<div class="step">
<div class="bullet">
<img src="star-pb.svg">
</div>
<div class="check">Packing & Quality Control</div>
</div>
<div class="step">
<div class="bullet">
<img src="star-pb.svg">
</div>
<div class="check">Shipped</div>
</div>
<div class="step">
<div class="bullet">
<img src="star-pb.svg">
</div>
<div class="check">Estimated Delivery</div>
</div>
</div></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74345421,
"author": "Alexis",
"author_id": 13986485,
"author_profile": "https://Stackoverflow.com/users/13986485",
"pm_score": 3,
"selected": true,
"text": "display: flex"
},
{
"answer_id": 74345814,
"author": "MAYUR SANCHETI",
"author_id": 12238257,
"author_profile": "https://Stackoverflow.com/users/12238257",
"pm_score": 0,
"selected": false,
"text": "let step = 'step1';\n\nconst step1 = document.getElementById('step1');\nconst step2 = document.getElementById('step2');\nconst step3 = document.getElementById('step3');\nconst step4 = document.getElementById('step4');\n\nfunction next() {\n if (step === 'step1') {\n step = 'step2';\n step1.classList.remove(\"is-active\");\n step1.classList.add(\"is-complete\");\n step2.classList.add(\"is-active\");\n\n } else if (step === 'step2') {\n step = 'step3';\n step2.classList.remove(\"is-active\");\n step2.classList.add(\"is-complete\");\n step3.classList.add(\"is-active\");\n\n } else if (step === 'step3') {\n step = 'step4d';\n step3.classList.remove(\"is-active\");\n step3.classList.add(\"is-complete\");\n step4.classList.add(\"is-active\");\n\n } else if (step === 'step4d') {\n step = 'complete';\n step4.classList.remove(\"is-active\");\n step4.classList.add(\"is-complete\");\n\n } else if (step === 'complete') {\n step = 'step1';\n step4.classList.remove(\"is-complete\");\n step3.classList.remove(\"is-complete\");\n step2.classList.remove(\"is-complete\");\n step1.classList.remove(\"is-complete\");\n step1.classList.add(\"is-active\");\n }\n}"
},
{
"answer_id": 74346909,
"author": "Ron. Yell",
"author_id": 14840485,
"author_profile": "https://Stackoverflow.com/users/14840485",
"pm_score": 1,
"selected": false,
"text": ".progress-bar {\n width: auto;\n display: flex;\n margin: 40px 0;\n}\n\n.progress-bar .step {\n text-align: center;\n position: relative;\n isolation: isolate;\n width: 100%;\n}\n\n.progress-bar .step::after {\n content: \"\";\n position: absolute;\n z-index: -1;\n height: 3px;\n top: 12px; /* 1/2 of .bullet's height */\n width: 100%;\n background: #C1C1C1;\n}\n\n.progress-bar .step:last-child::after {\n display: none;\n}\n\n.progress-bar .step .bullet {\n position: relative;\n height: 25px;\n width: 25px;\n display: inline-block;\n}\n\n.active-bullet {\n z-index: 1;\n}\n\n.active-check {\n z-index: 2;\n}\n\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74344183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19533023/"
] |
74,344,198 | <p>I am trying to get a stream of data displaying on my console, but I'm probably not aware of the right tools. If I try to get the data from curl it works fine and looks like this:</p>
<pre><code>C:\Users\user>curl localhost:8080/slow/5
5
4
3
2
1
0
C:\Users\user>
</code></pre>
<p>First I tried to use a standard http get request,</p>
<pre><code>constructor(
private http: HttpClient,
private ngzone: NgZone
) {
this.http.get('/slow/5').subscribe(x => console.log(x))
}
</code></pre>
<p>and this is the error I get after 5 secs:</p>
<pre><code>error: Object { error: SyntaxError, text: "5\n4\n3\n2\n1\n0\n" }
</code></pre>
<p>I tried to use the EventSource method, but that doesn't even manage to connect it. Proxies work fine. Any ideas?</p>
| [
{
"answer_id": 74344505,
"author": "Ali Celebi",
"author_id": 5033499,
"author_profile": "https://Stackoverflow.com/users/5033499",
"pm_score": 0,
"selected": false,
"text": "of"
},
{
"answer_id": 74344992,
"author": "Tobias S.",
"author_id": 8613630,
"author_profile": "https://Stackoverflow.com/users/8613630",
"pm_score": 2,
"selected": true,
"text": "XMLHttpRequest"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74344198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9419947/"
] |
74,344,212 | <p>I want to create a login method for my spring application. But when I try to call the
<code>getUserByAuthentication</code>
method, I get a null pointer exception. Here is my code:
Function calling the error:</p>
<pre><code>@PostMapping(path = "/online")
public ResponseEntity<?> onlineRequest(@RequestBody OnlineRequest onlineRequest) {
User user = null;
UserManager userManager = new UserManager();
user = userManager.getUserByAuthentication(onlineRequest.getUsername(), onlineRequest.getPassword());
if (user!=null){
user.setLatestTimeStamp(System.currentTimeMillis());
return new ResponseEntity<>("You are now online, Enjoy!", HttpStatus.OK);
} else {
return new ResponseEntity<>("Invalid login", HttpStatus.valueOf(403));
}
}
</code></pre>
<p>Get User by Authentication class:</p>
<pre><code>public class UserManager {
@Autowired
private UserRepository userRepository;
public User getUserByID(int id){
return userRepository.findById(id).get();
}
public User getUserByAuthentication(String name, String password){
Iterable<User> userList = userRepository.findAll();
ArrayList<User> users = new ArrayList<>();
userList.forEach(users::add);
User user = null;
for (User u : users){
if (u.getUsername().equals(name) && u.getPassword().equals(password)){
user = u;
}
}
return user;
}
}
</code></pre>
<p>Repository:</p>
<pre><code>@Repository
public interface UserRepository extends CrudRepository<User, Integer> {
}
</code></pre>
<p>User class:</p>
<pre><code>@Entity
@Table
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
//Initialize
private String username;
private String password;
private boolean hasAccess;
ArrayList<Integer> inChannels;
long latestTimeStamp;
public long getLatestTimeStamp() {
return latestTimeStamp;
}
public void setLatestTimeStamp(long latestTimeStamp) {
this.latestTimeStamp = latestTimeStamp;
}
public ArrayList<Integer> getInChannels() {
return inChannels;
}
public void setInChannels(ArrayList<Integer> inChannels) {
this.inChannels = inChannels;
}
public Long getId() {
return id;
}
public User() {
}
public boolean hasAccess() {
return hasAccess;
}
public void setAccess(boolean hasAccess) {
this.hasAccess = hasAccess;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
</code></pre>
| [
{
"answer_id": 74344282,
"author": "YCF_L",
"author_id": 5558072,
"author_profile": "https://Stackoverflow.com/users/5558072",
"pm_score": 3,
"selected": true,
"text": "@Autowired"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74344212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20377250/"
] |
74,344,217 | <p>When I run this code via <code>uvicorn main:app</code> everything works, but when I run it using Deta, I get <code>Internal Server Error</code> and only <code>GET</code> endpoint works (the <code>POST</code> one is not even called as it was supposed to).
Can you please help me? Thanks in advance.</p>
<pre class="lang-py prettyprint-override"><code>import os
from pathlib import Path
from fastapi import FastAPI, Form, UploadFile
from fastapi.responses import FileResponse, HTMLResponse
from pdfpad import pdfpad, save_pdf
app = FastAPI()
@app.post("/processfile/")
async def process_file(file: UploadFile) -> FileResponse:
path = file.filename
if os.getenv("DETA_RUNTIME") == "true":
path = Path("/tmp") / file.filename
saved_path = save_pdf(pdfpad(await file.read()), path)
return FileResponse(saved_path)
@app.get("/")
async def main():
content = """
<body>
<form action="/processfile/" enctype="multipart/form-data" method="post" id="form1">
<label for file>Choose PDF:</label>
file: <input name="file" type="file" form="form1">
<br><br>
<input type="submit">
</form>
</body>
"""
return HTMLResponse(content=content)
</code></pre>
| [
{
"answer_id": 74346221,
"author": "Chris",
"author_id": 17865804,
"author_profile": "https://Stackoverflow.com/users/17865804",
"pm_score": 1,
"selected": false,
"text": "/tmp"
},
{
"answer_id": 74347629,
"author": "arseniybelkov",
"author_id": 13861972,
"author_profile": "https://Stackoverflow.com/users/13861972",
"pm_score": -1,
"selected": false,
"text": "poppler-utils"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74344217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13861972/"
] |
74,344,241 | <p>I have a dataframe like:</p>
<pre><code>name address result
rishi los angeles true
tushar california false
keerthi texas false
</code></pre>
<p>I want to iterate through each row of the dataframe and check if result value is "true" or "false"</p>
<p>if true i want to copy the address to another address new column and if false i want to make address new column as "Null"</p>
<p>how to achieve this using pyspark?</p>
<p>result should be</p>
<pre><code>name address result address_new
rishi los angeles true los angeles
tushar california false null
keerthi texas false null
</code></pre>
| [
{
"answer_id": 74344327,
"author": "Joakim Torsvik",
"author_id": 19277819,
"author_profile": "https://Stackoverflow.com/users/19277819",
"pm_score": 1,
"selected": false,
"text": "new_df = df[df['result'] == True]\n"
},
{
"answer_id": 74344386,
"author": "FFGH",
"author_id": 9396975,
"author_profile": "https://Stackoverflow.com/users/9396975",
"pm_score": 0,
"selected": false,
"text": "when()"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74344241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,344,248 | <p>I want to run a macro in a <code>COPY INTO</code> statement to S3 bucket. Apparently in snowflake I can't do dynamic path. So I'm doing a hacky way to solve this.</p>
<pre><code>{% macro unload_snowflake_to_s3() %}
{# Get all tables and views from the information schema. #}
{%- set query -%}
select concat('COPY INTO @MY_STAGE/year=', year(current_date()), '/my_file FROM (SELECT OBJECT_CONSTRUCT(*) from my_table)');
{%- endset -%}
-- {%- set final_query = run_query(query) -%}
-- {{ dbt_utils.log_info(final_query) }}
-- {{ dbt_utils.log_info(final_query.rows.values()[0]) }}
{%- do run_query(final_query.columns.values()[0]) -%}
-- {% do final_query.print_table() %}
{% endmacro %}
</code></pre>
<p>Based on above macros, what I'm trying to do is:</p>
<ol>
<li>Use <code>CONCAT</code> to add <code>year</code> in the bucket path. Hence, the query becomes a string.</li>
<li>Use the concatenated query to <code>do run_query()</code>again to actually run the <code>COPY INTO</code> statement.</li>
</ol>
<p>Output and error I got from dbt log:</p>
<pre><code>09:06:08 09:06:08 + | column | data_type |
| ----------------------------------------------------------------------------------------------------------- | --------- |
| COPY INTO @MY_STAGE/year=', year(current_date()), '/my_file FROM (SELECT OBJECT_CONSTRUCT(*) from my_table) | Text |
09:06:08 09:06:08 + <agate.Row: ('COPY INTO @MY_STAGE/year=2022/my_file FROM (SELECT OBJECT_CONSTRUCT(*) from my_table)')>
09:06:09 Encountered an error while running operation: Database Error
001003 (42000): SQL compilation error:
syntax error line 1 at position 0 unexpected '<'.
root@2c50ba8af043:/dbt#
</code></pre>
<p>I think the error is that I didn't extract the row and column specifically which is in <code>agate</code> format. How can I convert/extract this to string?</p>
| [
{
"answer_id": 74344327,
"author": "Joakim Torsvik",
"author_id": 19277819,
"author_profile": "https://Stackoverflow.com/users/19277819",
"pm_score": 1,
"selected": false,
"text": "new_df = df[df['result'] == True]\n"
},
{
"answer_id": 74344386,
"author": "FFGH",
"author_id": 9396975,
"author_profile": "https://Stackoverflow.com/users/9396975",
"pm_score": 0,
"selected": false,
"text": "when()"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74344248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6308605/"
] |
74,344,266 | <p>I have data as follows:</p>
<pre><code>library(data.table)
dat <- fread("varA, varB
some_string a1
other_string a3
blabla a3_2")
renaming_list <- c(
some_name = "a1",
other_name = "a3")
</code></pre>
<p>I am probably overthinking this, but I would like to match <code>var_B</code> with the naming list to make:</p>
<pre><code>dat <- fread("varA, varB name
some_string a1 some_name
other_string a3 other_name
blabla NA")
</code></pre>
<p>How should I match these? I was previously using a code that uses non-exact matches,</p>
<pre><code>dat[, panel_name:=apply(outer(renaming_list, varB, Vectorize(grepl)), 2, \(x)
if (any(x)) names(which(x)) else NA)]
</code></pre>
<p>but now I only want exact matches. How should I adapt this code?</p>
| [
{
"answer_id": 74344327,
"author": "Joakim Torsvik",
"author_id": 19277819,
"author_profile": "https://Stackoverflow.com/users/19277819",
"pm_score": 1,
"selected": false,
"text": "new_df = df[df['result'] == True]\n"
},
{
"answer_id": 74344386,
"author": "FFGH",
"author_id": 9396975,
"author_profile": "https://Stackoverflow.com/users/9396975",
"pm_score": 0,
"selected": false,
"text": "when()"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74344266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8071608/"
] |
74,344,312 | <p>I have three Table. The first Table contains a Rezipe with a id, the second Table contains the rezeptid with the ingredients and the third Table shows the ingredient with a restriction(vegan, meat...).</p>
<p>Im looking for a way to select a recipe if the ingredients dont contain a specific restriction and if it contains the restriction then return Null.</p>
<p>I first joined the three tables together and wrote the restriction in the where clausel, but i dont wanna return the recipe, if it contains a specific value</p>
<pre><code>SELECT *
FROM `rezepte`
JOIN rezeptezutaten ON rezepte.REZEPTEID = rezeptezutaten.REZEPTEID
JOIN inhaltsstoffe ON inhaltsstoffe.ZUTATENNR = rezeptezutaten.ZUTATENNR
WHERE inhaltsstoffe.INHALTSSTOFFEID != 1;
</code></pre>
| [
{
"answer_id": 74344327,
"author": "Joakim Torsvik",
"author_id": 19277819,
"author_profile": "https://Stackoverflow.com/users/19277819",
"pm_score": 1,
"selected": false,
"text": "new_df = df[df['result'] == True]\n"
},
{
"answer_id": 74344386,
"author": "FFGH",
"author_id": 9396975,
"author_profile": "https://Stackoverflow.com/users/9396975",
"pm_score": 0,
"selected": false,
"text": "when()"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74344312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18308928/"
] |
74,344,323 | <p>I can't find the solution to this apparently simple problem.</p>
<p>I have a large dataframe. Every time a 0 appears in the index column it means that the data comes from a different source. I would like to substitute the first '0' with the first element of my list until the next '0'. The second '0' with the second list element and so on.
The number of 0s match the number of list elements.</p>
<pre><code>d = {
'Index': ['0', '1', '0','1', '0', '1', '2','3'],
'user_id': ['id11', 'id54', 'id544','id659', 'id18', 'id549', 'id59','id59'],
'launchingRole': ['writer', 'writer', 'writer','writer', 'reader', 'reader', 'reader','reader']
}
df2 = pd.DataFrame(d)
sessions_list = ['id599', '08749', '489w']
</code></pre>
<p>I've tried several solutions but none seems to work . Any help is greatly appreciated.</p>
| [
{
"answer_id": 74344327,
"author": "Joakim Torsvik",
"author_id": 19277819,
"author_profile": "https://Stackoverflow.com/users/19277819",
"pm_score": 1,
"selected": false,
"text": "new_df = df[df['result'] == True]\n"
},
{
"answer_id": 74344386,
"author": "FFGH",
"author_id": 9396975,
"author_profile": "https://Stackoverflow.com/users/9396975",
"pm_score": 0,
"selected": false,
"text": "when()"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74344323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20438589/"
] |
74,344,335 | <p>I have a class and I want to know when my class leave my tree widget. I think I can do that with lifecycle of app but I don't know how to do that.<br />
please help</p>
| [
{
"answer_id": 74344327,
"author": "Joakim Torsvik",
"author_id": 19277819,
"author_profile": "https://Stackoverflow.com/users/19277819",
"pm_score": 1,
"selected": false,
"text": "new_df = df[df['result'] == True]\n"
},
{
"answer_id": 74344386,
"author": "FFGH",
"author_id": 9396975,
"author_profile": "https://Stackoverflow.com/users/9396975",
"pm_score": 0,
"selected": false,
"text": "when()"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74344335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20184483/"
] |
74,344,337 | <p>I am trying to build ionic app and this error shows:
<code>ionic build</code></p>
<pre><code>> vue-cli-service build
[INFO] Looks like @vue/cli-service isn't installed in this project.
This package is required for this command to work properly.
? Install @vue/cli-service? Yes
> npm i -D -E @vue/cli-service
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: ionic-files@0.0.1
npm ERR! Found: @capacitor/core@2.4.6
npm ERR! node_modules/@capacitor/core
npm ERR! @capacitor/core@"2.4.6" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer @capacitor/core@"~2.5.0" from @capacitor/android@2.5.0
npm ERR! node_modules/@capacitor/android
npm ERR! @capacitor/android@"^2.4.6" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See /home/sariful/.npm/eresolve-report.txt for a full report.
npm ERR! A complete log of this run can be found in:
npm ERR! /home/sariful/.npm/_logs/2022-11-07T09_21_25_101Z-debug-0.log
[ERROR] An error occurred while running subprocess npm.
npm i -D -E @vue/cli-service exited with exit code 1.
Re-running this command with the --verbose flag may provide more information.
</code></pre>
| [
{
"answer_id": 74344327,
"author": "Joakim Torsvik",
"author_id": 19277819,
"author_profile": "https://Stackoverflow.com/users/19277819",
"pm_score": 1,
"selected": false,
"text": "new_df = df[df['result'] == True]\n"
},
{
"answer_id": 74344386,
"author": "FFGH",
"author_id": 9396975,
"author_profile": "https://Stackoverflow.com/users/9396975",
"pm_score": 0,
"selected": false,
"text": "when()"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74344337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7043908/"
] |
74,344,366 | <p>I want to know how methods are declared in Laravel's facades. For example, I want to create a user-defined function to index my login page. Firstly, I need to check whether the user is already authenticated. To do that, I will use Laravel's Auth facade.</p>
<pre><code>public function indexLogin() {
if (Auth::check()) {
return redirect('/mainpage');
}
}
</code></pre>
<p>But, when I wanted to learn more about this method, the only thing I came across were declarations made in the PHPDoc section.</p>
<pre><code>/*
*
* @method static bool check()
*
*/
</code></pre>
<p>For this case, I know what the method does but also want to know how it works. I believe the declarations that were made in PHPDoc sections are not enough to run methods.</p>
<p>I checked Laravel's official documentation but found nothing.</p>
| [
{
"answer_id": 74344327,
"author": "Joakim Torsvik",
"author_id": 19277819,
"author_profile": "https://Stackoverflow.com/users/19277819",
"pm_score": 1,
"selected": false,
"text": "new_df = df[df['result'] == True]\n"
},
{
"answer_id": 74344386,
"author": "FFGH",
"author_id": 9396975,
"author_profile": "https://Stackoverflow.com/users/9396975",
"pm_score": 0,
"selected": false,
"text": "when()"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74344366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16386326/"
] |
74,344,367 | <p>I have a data frame:</p>
<pre><code>pl.DataFrame({'no_of_docs':[[9,4,2],
[3,9,1,10],
[10,3,2,1],
[10,30],
[1,2,3,6,4,5]]})
</code></pre>
<p>Here the column: no_of_docs is a list[int] type one: i would like to add a new column with the max value index from each list?</p>
<p>Another case:</p>
<pre><code>pl.DataFrame({'no_of_docs':[['9','4','2'],
['3','9','1','10'],
['10','3','2','1'],
['10','30'],
['1','2','3','6','4','5']]})
</code></pre>
<p>Here no_of_docs is a type of list[str] and how to convert it to int and get an index of max value.</p>
<p>Expected output:</p>
<p><a href="https://i.stack.imgur.com/gBtI5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gBtI5.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74344620,
"author": "myamulla_ciencia",
"author_id": 9479925,
"author_profile": "https://Stackoverflow.com/users/9479925",
"pm_score": 2,
"selected": false,
"text": "df.with_column(pl.col('no_of_docs').arr.arg_max().alias('idx')\n"
},
{
"answer_id": 74344776,
"author": "Khaled DELLAL",
"author_id": 15852600,
"author_profile": "https://Stackoverflow.com/users/15852600",
"pm_score": 0,
"selected": false,
"text": "df['idx']=[sub_list.index(max(sub_list)) for sub_list in df['no_of_docs']]\n"
},
{
"answer_id": 74349147,
"author": "alexp",
"author_id": 10120952,
"author_profile": "https://Stackoverflow.com/users/10120952",
"pm_score": 2,
"selected": true,
"text": "df.with_column(\n pl.col(\"no_of_docs\").cast(pl.List(pl.Int64)).arr.arg_max().alias('idx')\n)\n\nshape: (5, 2)\n┌──────────────────────┬─────┐\n│ no_of_docs ┆ idx │\n│ --- ┆ --- │\n│ list[str] ┆ u32 │\n╞══════════════════════╪═════╡\n│ [\"9\", \"4\", \"2\"] ┆ 0 │\n├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┤\n│ [\"3\", \"9\", ... \"10\"] ┆ 3 │\n├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┤\n│ [\"10\", \"3\", ... \"1\"] ┆ 0 │\n├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┤\n│ [\"10\", \"30\"] ┆ 1 │\n├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┤\n│ [\"1\", \"2\", ... \"5\"] ┆ 3 │\n└──────────────────────┴─────┘\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74344367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9479925/"
] |
74,344,388 | <p>I'm trying to find a fast way to solve the subset sum problem with a few modifications, I know the exact size of the subset I need to get the target number and I also know the input array to be a range from 1 to 2000. My questions is if there is any way to improve upon the base subset sum problem solution to make it even faster when knowing these conditions as the normal solutions are too slow. Basically the only changing part is the wanted target sum.</p>
<p>I would preferably want it to return all the possible subsets of the given size that add up to the target value if its possible without slowing the program down too much. An example code in python or a similar language would be appriciated.</p>
<p>I've tried many of the solutions for the base subset sum problem but they are too slow to execute due to the size of the input array.</p>
| [
{
"answer_id": 74344923,
"author": "DrosvarG",
"author_id": 11502610,
"author_profile": "https://Stackoverflow.com/users/11502610",
"pm_score": 1,
"selected": false,
"text": "O(input array size)"
},
{
"answer_id": 74348545,
"author": "Dave",
"author_id": 2041077,
"author_profile": "https://Stackoverflow.com/users/2041077",
"pm_score": 1,
"selected": true,
"text": "Ruby code:\n\ndef f(target, width)\n arr = []\n\n # put in center of array\n if width % 2 == 0\n arr.append target / width\n arr.append target / width + 1\n else\n arr.append target/width\n end\n \n # repeatedly prepend next smallest integer\n # and append next largest integer\n while arr.length < width\n arr.unshift(arr[0] - 1)\n arr.append(arr[-1] + 1)\n end\n \n # increase the last element of the array to match\n # the target sum. This is only necessary if there is no\n # contiguous solution. Because of integer division, \n # where we need to adjust it will always be to increase\n # the sum of the array.\n arr[-1] += target - arr.sum\n \n return arr\nend\n\nExample run:\n> f(12342, 7)\n=> [1760, 1761, 1762, 1763, 1764, 1765, 1767]\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74344388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12243641/"
] |
74,344,396 | <p>I'm trying to find a regex pattern to extract some names that apprear in a string after the first comma (David Peter Richard) below.</p>
<p>Example string:
PALMER, David Peter Richard</p>
<p>I came across <a href="https://stackoverflow.com/questions/8224270/regular-expression-to-get-all-characters-before">this thread that successfully extracts the name before</a>, but require all the names after the comma.</p>
<p>I've tried to modify the ^.*?(?=,), but not having any joy. Needs to be JavaScript Regex and capture groups are not supported in the platform i'm using (Bubble)</p>
<p>Any help appreciated, thanks a lot!</p>
<p>I tried this: (?<=,)[^,]+</p>
<p>Which seems to work on Desktop, however on a wrapped mobile app, it doesn't seem to work.</p>
<p>Similarly for the Name before, I was using ^[^,]+ and experiencing the same issue, but when I use the pattern in the ^.*?(?=,) it works fine.</p>
<p>So now I just need the pattern to be adjusted for the names after.</p>
| [
{
"answer_id": 74344923,
"author": "DrosvarG",
"author_id": 11502610,
"author_profile": "https://Stackoverflow.com/users/11502610",
"pm_score": 1,
"selected": false,
"text": "O(input array size)"
},
{
"answer_id": 74348545,
"author": "Dave",
"author_id": 2041077,
"author_profile": "https://Stackoverflow.com/users/2041077",
"pm_score": 1,
"selected": true,
"text": "Ruby code:\n\ndef f(target, width)\n arr = []\n\n # put in center of array\n if width % 2 == 0\n arr.append target / width\n arr.append target / width + 1\n else\n arr.append target/width\n end\n \n # repeatedly prepend next smallest integer\n # and append next largest integer\n while arr.length < width\n arr.unshift(arr[0] - 1)\n arr.append(arr[-1] + 1)\n end\n \n # increase the last element of the array to match\n # the target sum. This is only necessary if there is no\n # contiguous solution. Because of integer division, \n # where we need to adjust it will always be to increase\n # the sum of the array.\n arr[-1] += target - arr.sum\n \n return arr\nend\n\nExample run:\n> f(12342, 7)\n=> [1760, 1761, 1762, 1763, 1764, 1765, 1767]\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74344396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1686633/"
] |
74,344,473 | <p>When calling a function that gets returned from a custom hook (<code>useOutput</code>) in one of my components, I get an Invalid hook call error with the following message:</p>
<pre><code>Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
at Object.throwInvalidHookError (plugin:flow:17739:539)
at useRef (plugin:flow:1768:25)
at useSyncExternalStoreWithSelector (plugin:flow:3976:21)
at useStore$1 (plugin:flow:4083:17)
at useBoundStore (plugin:flow:4089:51)
at useOutput (plugin:flow:13158:9)
at setOutput (plugin:flow:13195:45)
at onClickButton (plugin:flow:13200:9)
at HTMLUnknownElement.callCallback (plugin:flow:15894:119)
at Object.invokeGuardedCallbackDev (plugin:flow:15914:45)
throwInvalidHookError @ plugin:flow:17739
useRef @ plugin:flow:1768
useSyncExternalStoreWithSelector @ plugin:flow:3976
useStore$1 @ plugin:flow:4083
useBoundStore @ plugin:flow:4089
useOutput @ plugin:flow:13158
setOutput @ plugin:flow:13195
onClickButton @ plugin:flow:13200
callCallback @ plugin:flow:15894
invokeGuardedCallbackDev @ plugin:flow:15914
invokeGuardedCallback @ plugin:flow:15933
invokeGuardedCallbackAndCatchFirstError @ plugin:flow:15942
executeDispatch @ plugin:flow:16822
processDispatchQueueItemsInOrder @ plugin:flow:16822
processDispatchQueue @ plugin:flow:16822
dispatchEventsForPlugins @ plugin:flow:16824
eval @ plugin:flow:16878
batchedEventUpdates$1 @ plugin:flow:19004
batchedEventUpdates @ plugin:flow:15839
dispatchEventForPluginEventSystem @ plugin:flow:16878
attemptToDispatchEvent @ plugin:flow:16266
dispatchEvent @ plugin:flow:16244
unstable_runWithPriority @ plugin:flow:14064
runWithPriority$1 @ plugin:flow:17299
discreteUpdates$1 @ plugin:flow:19005
discreteUpdates @ plugin:flow:15839
dispatchDiscreteEvent @ plugin:flow:16234
</code></pre>
<p>This is my code:</p>
<p>Inside react component:</p>
<pre><code>const flowName = useContext(FlowNameContext);
const setOutput = (output: OutputData, outputId: string) =>
useOutput(outputId, id, flowName)[1](output);
</code></pre>
<p>useOutput hook</p>
<pre><code>export const useOutput = (
outputId: string,
nodeId: string,
flowName: string
): MutableHookResult<OutputData> => {
return [
useAppModel(
(store) =>
selectOutputs(nodeId, selectFlow(flowName, store)?.editorModel)[
outputId
]
),
(output: OutputData) =>
useAppModel.setState(
produce((draft: AppModel) => {
setOutput(output, outputId, nodeId, flowName, draft);
})
),
];
};
</code></pre>
<p>setOutput function:</p>
<pre><code>export const setOutput = (
output: OutputData,
id: string,
nodeId: string,
flowName: string,
appModel: AppModel
): void => {
// update outputs
const editorModel = selectFlow(flowName, appModel).editorModel;
const node = selectNode(nodeId, editorModel);
if (node) node.data.outputs[id] = output;
// update inputs
const connectedNodes = selectConnectedNodes(nodeId, false, id, editorModel);
connectedNodes.forEach((connectedNode) => {
connectedNode.node.data.inputs[connectedNode.connectedOn] = output;
});
};
</code></pre>
<p>(the select functions are just helpers to select properties of the state object, they are vanilla ts)</p>
<p>What's the issue here?</p>
| [
{
"answer_id": 74344591,
"author": "TalOrlanczyk",
"author_id": 13582100,
"author_profile": "https://Stackoverflow.com/users/13582100",
"pm_score": 0,
"selected": false,
"text": "useOutput(outputId, id, flowName)[1](output);\n"
},
{
"answer_id": 74344654,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 2,
"selected": true,
"text": "export const useOutput = () => {\n\n const getResult = (outputId: string, nodeId: string, flowName: string): MutableHookResult<OutputData> => {\n return [\n useAppModel(\n (store) =>\n selectOutputs(nodeId, selectFlow(flowName, store)?.editorModel)[\n outputId\n ]\n ),\n (output: OutputData) =>\n useAppModel.setState(\n produce((draft: AppModel) => {\n setOutput(output, outputId, nodeId, flowName, draft);\n })\n ),\n ];\n }\n\n return {getResult}\n \n};\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74344473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14432451/"
] |
74,344,489 | <p>This is the signature of my object create function:</p>
<p><code>struct object *object_create();</code></p>
<p>If the object is successfully created it it returns pointer to the object, and <code>0</code> otherwise.</p>
<p>How would I return some error codes from the same function? I need about ten codes.</p>
<p>I suppose mixing error codes and object pointer is not the way to go?</p>
| [
{
"answer_id": 74344577,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "errno"
},
{
"answer_id": 74344664,
"author": "chrslg",
"author_id": 20037042,
"author_profile": "https://Stackoverflow.com/users/20037042",
"pm_score": 0,
"selected": false,
"text": "#include <stdio.h>\n#include <stdlib.h>\n\n# define ONE (struct object *)1\n\n// Example structure\nstruct object {\n char *name;\n};\n\nstruct object *object_create(){\n struct object *ret=(struct object *)malloc(sizeof(struct object));\n if(!ret) return NULL;\n ret->name = malloc(80);\n if(!ret->name){\n free(ret);\n return ONE;\n }\n return ret;\n}\n\nint main(){\n struct object *myobj=object_create();\n if(myobj==NULL){\n fprintf(stderr, \"Cannot create object\\n\");\n return 1;\n }\n if(myobj==ONE){\n fprintf(stderr, \"Cannot allocate memory for name\\n\");\n return 2;\n }\n // start playing with myobj\n sprintf(myobj->name, \"Hello\");\n}\n"
},
{
"answer_id": 74345207,
"author": "Lundin",
"author_id": 584518,
"author_profile": "https://Stackoverflow.com/users/584518",
"pm_score": 3,
"selected": true,
"text": "struct object *object_create (myerr_t* result, /* ... */);"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74344489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1202172/"
] |
74,344,520 | <p>I am new to angular and i have been trying to display some data in the website.
But all i am getting is error</p>
<p>Here is my code snippet.</p>
<pre><code>ngOnInit(): void {
window.scrollTo(0, 0)
this.loggeduser = JSON.parse(localStorage.getItem('user'))
console.log(this.loggeduser)
this.customer_id = this.loggeduser[0].CUSTOMER_ID
console.log(this.customer_id)
this.http.post('http://localhost:3000/getAdminOrders', JSON.stringify({ 'id': this.customer_id }), { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }).subscribe((res) => {
console.log("res", res)
this.stored = res
console.log(this.stored)
// for (let x = 0; x < this.stored.length; x++) {
// this.stored[x].PURCHASE_DATE = new Date(this.stored[x].PURCHASE_DATE)
// }
})
</code></pre>
<p>Here's the template content.</p>
<pre><code><div class="table-responsive">
<table class="table table-striped" style="width:100%">
<thead>
<tr class="table-secondary">
<th scope="col">Product</th>
<th scope="col">Price</th>
<th scope="col">Order Placed</th>
<th scope="col">Order Id</th>
<th scope="col">Payment Mode</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let stores of stored">
<td>
<div class="media">
<!-- image -->
<div class="d-flex">
<img src="http://localhost:3000/{{stores.PRODUCT_IMAGE}}" height="150px" alt="">
</div>
<div class="media-body">
<h5>{{stores.PRODUCT_PURCHASED}}</h5>
</div>
</div>
</td>
<td>
<h5>{{stores.PRODUCT_PRICE | currency: "&#8377;"}}</h5>
</td>
<td style="width:20%;">
<h5>{{stores.PURCHASE_DATE| date: 'MMM d, y'}}&nbsp;{{stores.PURCHASE_TIME}}</h5>
</td>
<td>
<h5>{{stores.ORDER_ID}}</h5>
</td>
<td style="width:14%">
<h5>{{stores.PAYMENT_MODE}}</h5>
</td>
</tr>
</tbody>
</table>
</div>
</code></pre>
<p>Can someone tell me what's wrong with this?</p>
<p>I can see the data that is fetched from the backend in the console.
<img src="https://i.stack.imgur.com/wQL8F.jpg" alt="Image" /></p>
| [
{
"answer_id": 74344577,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "errno"
},
{
"answer_id": 74344664,
"author": "chrslg",
"author_id": 20037042,
"author_profile": "https://Stackoverflow.com/users/20037042",
"pm_score": 0,
"selected": false,
"text": "#include <stdio.h>\n#include <stdlib.h>\n\n# define ONE (struct object *)1\n\n// Example structure\nstruct object {\n char *name;\n};\n\nstruct object *object_create(){\n struct object *ret=(struct object *)malloc(sizeof(struct object));\n if(!ret) return NULL;\n ret->name = malloc(80);\n if(!ret->name){\n free(ret);\n return ONE;\n }\n return ret;\n}\n\nint main(){\n struct object *myobj=object_create();\n if(myobj==NULL){\n fprintf(stderr, \"Cannot create object\\n\");\n return 1;\n }\n if(myobj==ONE){\n fprintf(stderr, \"Cannot allocate memory for name\\n\");\n return 2;\n }\n // start playing with myobj\n sprintf(myobj->name, \"Hello\");\n}\n"
},
{
"answer_id": 74345207,
"author": "Lundin",
"author_id": 584518,
"author_profile": "https://Stackoverflow.com/users/584518",
"pm_score": 3,
"selected": true,
"text": "struct object *object_create (myerr_t* result, /* ... */);"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74344520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15238153/"
] |
74,344,542 | <p>I have a list. I want to convert it to string. However, the results are a bit different from what I expected.</p>
<p>Expected result:</p>
<pre><code>'["a", "b", "c", "d"]'
</code></pre>
<p>Actual result:</p>
<pre><code>[a, b, c, d]
</code></pre>
<p>My code:</p>
<pre><code>final List list = ["a", "b", "c", "d"];
print(list.toString());
</code></pre>
<p>How can I get my expected results? I would appreciate any help. Thank you in advance!</p>
| [
{
"answer_id": 74344573,
"author": "Ivo",
"author_id": 1514861,
"author_profile": "https://Stackoverflow.com/users/1514861",
"pm_score": 3,
"selected": true,
"text": "jsonEncode"
},
{
"answer_id": 74344623,
"author": "Sachin Kumawat",
"author_id": 11830339,
"author_profile": "https://Stackoverflow.com/users/11830339",
"pm_score": 0,
"selected": false,
"text": "jsonEncode"
},
{
"answer_id": 74344649,
"author": "Sparko Sol",
"author_id": 20407048,
"author_profile": "https://Stackoverflow.com/users/20407048",
"pm_score": 1,
"selected": false,
"text": "json.encode()"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74344542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16124033/"
] |
74,344,550 | <p>I want to pass data from the request via axios in the root component to the child using Vue. Unfortunately, only one field is displayed correctly - "title". But I also need to output "body".</p>
<p>Ps: This is my first time working with Vue, and I would like to know how it can be done correctly</p>
<p>App.vue</p>
<pre><code><template>
<app-news
v-for="item in news"
:key="item.id"
:title="item.title"
:id="item.id"
:body="item.body"
>
</app-news>
</template>
export default {
data () {
return {
news: []
}
mounted() {
axios
.get('https://jsonplaceholder.typicode.com/posts?_start=0&_limit=5')
.then((resp) =>
this.news = resp.data
)
},
provide () {
return {
title: 'List of all news:',
news: this.news
}
},
</code></pre>
<p>AppNews.vue</p>
<pre><code><template>
<div>
<hr/>
<p v-for="item in news" :key="item.id">{{ item.body }}</p> // Need to pass here body content of the response from json
</div>
</template>
props: {
news: [], // -> I think here the problem, I need to get the response as a prop and validate them as well, as shown below
title: {
type: String,
required: true
},
id: {
type: Number,
required: true
},
body: {
type: String,
required: true
},
}
},
</code></pre>
| [
{
"answer_id": 74344573,
"author": "Ivo",
"author_id": 1514861,
"author_profile": "https://Stackoverflow.com/users/1514861",
"pm_score": 3,
"selected": true,
"text": "jsonEncode"
},
{
"answer_id": 74344623,
"author": "Sachin Kumawat",
"author_id": 11830339,
"author_profile": "https://Stackoverflow.com/users/11830339",
"pm_score": 0,
"selected": false,
"text": "jsonEncode"
},
{
"answer_id": 74344649,
"author": "Sparko Sol",
"author_id": 20407048,
"author_profile": "https://Stackoverflow.com/users/20407048",
"pm_score": 1,
"selected": false,
"text": "json.encode()"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74344550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11742613/"
] |
74,344,580 | <p>Hey i looking for a option to get the Element of a Control by finding the Parent.
Does this function exist in Xamarin.Forms / .Net MAUI?</p>
<p><strong>(Parents are GRID and Childrens are Frames)</strong></p>
<p>It needs to be find the current Parent and remove the children.
After that it should add the diced numbers + the old Parent (name is in numbers) and Add to the children to new calculated Parent.</p>
<p>Example Player1 is on F4 and diced 10. Player1 should be removed from F4 and replaced on F14.</p>
<p>This all can be done with long redundant code but in WinForms you can easily find out everything you need.
.Net MAUI doesn't look that familiar to me.</p>
<pre><code>string field = "F";
int diced = 10;
private void AddPlayer1(int diced)
{
// What i want
field = field + diced.ToString();
field.Children.Add(player1)
// what i have
F1.Children.Add(player1);
}
Element parent;
private void RemovePlayer1()
{
// What i want
parent = GetParent(player1);
parent.Children.Remove(player1);
// what i have (long and redundant)
if (player1.Parent == F0)
F0.Children.Remove(player1);
else if (player1.Parent == F1)
F1.Children.Remove(player1);
else if (player1.Parent == F2)
F2.Children.Remove(player1);
else if (player1.Parent == F3)
F3.Children.Remove(player1);
else if (player1.Parent == F4)
F4.Children.Remove(player1);
else if (player1.Parent == F5)
F5.Children.Remove(player1);
else if (player1.Parent == F6)
F6.Children.Remove(player1);
else if (player1.Parent == F7)
F7.Children.Remove(player1);
else if (player1.Parent == F8)
F8.Children.Remove(player1);
else if (player1.Parent == F9)
F9.Children.Remove(player1);
else if (player1.Parent == F10)
F10.Children.Remove(player1);
else if (player1.Parent == F11)
F11.Children.Remove(player1);
else if (player1.Parent == F12)
F12.Children.Remove(player1);
else if (player1.Parent == F13)
F13.Children.Remove(player1);
else if (player1.Parent == F14)
F14.Children.Remove(player1);
else if (player1.Parent == F15)
F15.Children.Remove(player1);
else if (player1.Parent == F16)
F16.Children.Remove(player1);
else if (player1.Parent == F17)
F17.Children.Remove(player1);
else if (player1.Parent == F18)
F18.Children.Remove(player1);
}
</code></pre>
| [
{
"answer_id": 74345776,
"author": "Himanshu Dwivedi",
"author_id": 3421104,
"author_profile": "https://Stackoverflow.com/users/3421104",
"pm_score": 1,
"selected": false,
"text": "var parent = grid.Children;\n//loop through your rowNumber and columnNumber such as 1,1/1,2....\nvar children = parent .Children.Where(c => Grid.GetRow(c) == rowNumber && Grid.GetColumn(c)== columnNumber);\n//Similarly you can find the children and replace by specifying the row and column\n"
},
{
"answer_id": 74346086,
"author": "Seth Macis",
"author_id": 19416551,
"author_profile": "https://Stackoverflow.com/users/19416551",
"pm_score": 2,
"selected": false,
"text": " //Declare\n Random dice = new Random();\n string field = \"F\";\n int current = 0;\n int diced;\n\n //Dice\n diced = dice.Next(1,7); \n\n //FindByName\n Grid FRemove = FindByName(field + current.ToString()) as Grid; \n Grid FAdd = FindByName(field + diced.ToString()) as Grid;\n\n //Remove and Add\n FRemove.Children.Remove(player1);\n FAdd.Children.Add(player1);\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74344580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19416551/"
] |
74,344,593 | <p>I have React app that would like to make 20% app bar on top and 80% or the rest of the height fulfill with parent height.</p>
<pre><code><div>
//Like to make 20% height
<div>
<p>App bar</p>
</div>
//Like to make 80% height
<div>
<div>Content A</div>
<div>Content B</div>
<div>Content C</div>
</div>
</div>
</code></pre>
| [
{
"answer_id": 74344612,
"author": "xpcrts AKA Rithisak",
"author_id": 8200791,
"author_profile": "https://Stackoverflow.com/users/8200791",
"pm_score": -1,
"selected": false,
"text": "<div style={{display:\"flex\", flexDirection:\"column\"}}>\n <div style={{height: \"20vh\"}}>\n <p>App bar</p>\n </div>\n <div style={{height: \"80vh\", border:\"1px solid blue\"}}>\n <div>Content A</div>\n <div>Content B</div>\n <div>Content C</div>\n </div>\n</div>\n"
},
{
"answer_id": 74344748,
"author": "Pengson",
"author_id": 4172742,
"author_profile": "https://Stackoverflow.com/users/4172742",
"pm_score": -1,
"selected": false,
"text": "<div class=\"parent\">\n <div class=\"app-bar\">\n <p>App bar</p>\n </div>\n <div class=\"rest\">\n <div>Content A</div>\n <div>Content B</div>\n <div>Content C</div>\n </div>\n</div>\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74344593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8200791/"
] |
74,344,618 | <p>I have this html code where it has a main content on the left and a side bar on the right. My goal is to have the last sidebar (the one with the "faq" class) stick to it's position whenever I scrolled down in the main content and when I scroll back up, it should return all the div class(about,contact,faq)to its position. I've tried using the 'position: sticky;' on the "faq" class but the problem is that it doesn't stick. What should I do?</p>
<p>This is the HTML&CSS code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
box-sizing: border-box;
}
/* Add a gray background color with some padding */
body {
font-family: Arial;
padding: 20px;
background: #f1f1f1;
}
/* Header/Blog Title */
.header {
padding: 30px;
font-size: 40px;
text-align: center;
}
/* Create two unequal columns that floats next to each other */
/* Left column */
.leftcolumn {
float: left;
width: 75%;
padding-left: 90px;
}
/* Right column */
.rightcolumn {
float: left;
width: 25%;
height: 100%;
padding-left: 20px;
padding-right: 90px;
}
/* Fake image */
.fakeimg {
background-color: #aaa;
width: 100%;
padding: 20px;
}
/* Add a card effect for articles */
.card {
background-color: white;
padding: 20px;
margin-top: 20px;
}
/* Clear floats after the columns */
.row:after {
content: "";
display: table;
clear: both;
}
/* Footer */
.footer {
padding: 20px;
text-align: center;
background: #ddd;
margin-top: 20px;
}
/* Responsive layout - when the screen is less than 800px wide, make the two columns stack on top of each other instead of next to each other */
@media screen and (max-width: 800px) {
.leftcolumn,
.rightcolumn {
width: 100%;
padding: 0;
}
}
/* this is for the side bar, this is where I should implement the sticky feature*/
.about {
background-color: white;
padding: 20px;
margin-top: 20px;
}
.contact {
background-color: white;
padding: 20px;
margin-top: 20px;
}
.faq {
background-color: white;
padding: 20px;
margin-top: 20px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Eat Blog-a</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="header">
<h2>Blog Name</h2>
</div>
<div class="row">
<div class="leftcolumn">
<div class="card">
<h5>Posted by (Username)</h5>
<h2>Description</h2>
<p>Content</p>
<div class="fakeimg" style="height: 200px">Image</div>
</div>
<div class="card">
<h5>Posted by (Username)</h5>
<h2>Description</h2>
<p>Content</p>
<div class="fakeimg" style="height: 200px">Image</div>
</div>
</div>
<div class="rightcolumn">
<div class="about">
<p>This is where we will put the about area</p>
</div>
<div class="contact">
<p>This is where we will put the about contact</p>
</div>
<div class="faq">
<p>This is where we will put the about FAQ</p>
</div>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74344973,
"author": "Anh Le Hoang",
"author_id": 16315750,
"author_profile": "https://Stackoverflow.com/users/16315750",
"pm_score": 1,
"selected": true,
"text": "Sticky"
},
{
"answer_id": 74344975,
"author": "FUZIION",
"author_id": 13050564,
"author_profile": "https://Stackoverflow.com/users/13050564",
"pm_score": 0,
"selected": false,
"text": "/* jQuery */\nwindow.onscroll = function JQanchorOnScroll() {\n var $anchor = $(\".faq-anchor\");\n var $element = $('.faq');\n\n var move = function() {\n var scrollTop = $(window).scrollTop();\n var OffsetTop = $anchor.offset().top;\n if (scrollTop > OffsetTop) {\n $element.css({\n position: \"fixed\",\n top: \"0px\"\n });\n } else {\n $element.css({\n position: \"relative\",\n top: \"\"\n });\n }\n };\n $(window).scroll(move);\n move();\n}"
},
{
"answer_id": 74344977,
"author": "Mohammed Shahed",
"author_id": 19067773,
"author_profile": "https://Stackoverflow.com/users/19067773",
"pm_score": -1,
"selected": false,
"text": ".rightcolumn {\n float: left;\n width: 25%;\n height: 100%;\n padding-left: 20px;\n padding-right: 90px;\n position: sticky;\n top: 0;\n}\n\n/*to test it it's sticky\ndo this */\n\n.leftcolumn {\n float: left;\n width: 75%;\n padding-left: 90px;\n min-height: 200vh;\n}\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74344618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18909694/"
] |
74,344,626 | <p>I want to be able to download a file named approved_leads.zip when clicking on the a tag, but for some reason I keep getting the message "failed - no file". Even though the path looks correct to me.</p>
<pre><code><a href="../../assets/approved_leads.zip" download>Download File</a>
</code></pre>
<p>And, here's the folder structure of it, right now the a tag is inside the jsx file called "LeadsPage.jsx" and the .zip file inside the assets folder.</p>
<p><a href="https://i.stack.imgur.com/aHLGA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aHLGA.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74344973,
"author": "Anh Le Hoang",
"author_id": 16315750,
"author_profile": "https://Stackoverflow.com/users/16315750",
"pm_score": 1,
"selected": true,
"text": "Sticky"
},
{
"answer_id": 74344975,
"author": "FUZIION",
"author_id": 13050564,
"author_profile": "https://Stackoverflow.com/users/13050564",
"pm_score": 0,
"selected": false,
"text": "/* jQuery */\nwindow.onscroll = function JQanchorOnScroll() {\n var $anchor = $(\".faq-anchor\");\n var $element = $('.faq');\n\n var move = function() {\n var scrollTop = $(window).scrollTop();\n var OffsetTop = $anchor.offset().top;\n if (scrollTop > OffsetTop) {\n $element.css({\n position: \"fixed\",\n top: \"0px\"\n });\n } else {\n $element.css({\n position: \"relative\",\n top: \"\"\n });\n }\n };\n $(window).scroll(move);\n move();\n}"
},
{
"answer_id": 74344977,
"author": "Mohammed Shahed",
"author_id": 19067773,
"author_profile": "https://Stackoverflow.com/users/19067773",
"pm_score": -1,
"selected": false,
"text": ".rightcolumn {\n float: left;\n width: 25%;\n height: 100%;\n padding-left: 20px;\n padding-right: 90px;\n position: sticky;\n top: 0;\n}\n\n/*to test it it's sticky\ndo this */\n\n.leftcolumn {\n float: left;\n width: 75%;\n padding-left: 90px;\n min-height: 200vh;\n}\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74344626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19389593/"
] |
74,344,644 | <p>I need to use nested lists, but I can't give them a height, because lists can have their own length depending on the amount of information that comes from the server. I tried sketching a variation but it doesn't work, I get an error - <em><strong>Incorrect use of ParentDataWidget.</strong></em></p>
<p>Below is my code -</p>
<pre><code>return Drawer(
child: Container(
margin: const EdgeInsets.symmetric(vertical: 13, horizontal: 13),
child: ListView.builder(
physics: const NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemCount: catalogDrawer.length,
itemBuilder: (BuildContext context, int index) {
var one = catalogDrawer[index].one;
return Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(catalogDrawer[index].name, style: TextStyle(fontSize: 15, fontWeight: FontWeight.w600),),
Expanded(
child: ListView.builder(
physics: const NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemCount: catalogDrawer[index].one.length,
itemBuilder: (BuildContext context, int i) {
var two = catalogDrawer[index].one[i].two;
return Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
margin: const EdgeInsets.only(left: 10),
padding: const EdgeInsets.all(10),
color: Colors.yellow,
child: Text(one[i].name,style: TextStyle(fontWeight: FontWeight.w500, fontSize: 15),),
),
Expanded(
// height: two.length > 1 ? 76 : 38,
child: ListView.builder(
physics: const NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemCount: catalogDrawer[index].one[i].two.length,
itemBuilder: (BuildContext context, int a) {
return Container(
margin: const EdgeInsets.only(left: 30),
padding: const EdgeInsets.all(10),
color: Colors.red,
child: Text(two[a].name, style: TextStyle(fontWeight: FontWeight.w500, fontSize: 15),),
);
},
),
),
],
)
);
},
),
),
],
)
);
},
),
),
);
</code></pre>
<p>My question can be rephrased - How to use nested lists but don't specify a height</p>
| [
{
"answer_id": 74344973,
"author": "Anh Le Hoang",
"author_id": 16315750,
"author_profile": "https://Stackoverflow.com/users/16315750",
"pm_score": 1,
"selected": true,
"text": "Sticky"
},
{
"answer_id": 74344975,
"author": "FUZIION",
"author_id": 13050564,
"author_profile": "https://Stackoverflow.com/users/13050564",
"pm_score": 0,
"selected": false,
"text": "/* jQuery */\nwindow.onscroll = function JQanchorOnScroll() {\n var $anchor = $(\".faq-anchor\");\n var $element = $('.faq');\n\n var move = function() {\n var scrollTop = $(window).scrollTop();\n var OffsetTop = $anchor.offset().top;\n if (scrollTop > OffsetTop) {\n $element.css({\n position: \"fixed\",\n top: \"0px\"\n });\n } else {\n $element.css({\n position: \"relative\",\n top: \"\"\n });\n }\n };\n $(window).scroll(move);\n move();\n}"
},
{
"answer_id": 74344977,
"author": "Mohammed Shahed",
"author_id": 19067773,
"author_profile": "https://Stackoverflow.com/users/19067773",
"pm_score": -1,
"selected": false,
"text": ".rightcolumn {\n float: left;\n width: 25%;\n height: 100%;\n padding-left: 20px;\n padding-right: 90px;\n position: sticky;\n top: 0;\n}\n\n/*to test it it's sticky\ndo this */\n\n.leftcolumn {\n float: left;\n width: 75%;\n padding-left: 90px;\n min-height: 200vh;\n}\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74344644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18540229/"
] |
74,344,662 | <p>I use the following script to make the background of my website change automatically. However, I want a different background to appear after a certain width.</p>
<p>I am still quite inexperienced when it comes to jquery and javascript in general, so I need help with this.</p>
<p>How can I use multiple breakpoints in this script?</p>
<pre><code>jQuery(function ($) {
function changeColor(selector, colors, time) {
/* Params:
* selector: string,
* colors: array of color strings,
* every: integer (in mili-seconds)
*/
var curCol = 0,
timer = setInterval(function () {
if (curCol === colors.length) curCol = 0;
$(selector).css("background", colors[curCol]);
curCol++;
}, time);
}
$(window).load(function () {
changeColor("#shop .container", ["url(c-l-s.png) no-repeat","url(c-w-s.png) no-repeat", "url(c-m-s.png) no-repeat", "url(c-b-s.png) no-repeat"], 5000);
});
});
</code></pre>
<p>I need something like:</p>
<blockquote>
<p>If width 1023px then</p>
</blockquote>
<pre><code>$(window).load(function () {
changeColor("#shop .container", ["url(c-l.png) no-repeat","url(c-w.png) no-repeat", "url(c-m.png) no-repeat", "url(c-b.png) no-repeat"], 5000);
});
</code></pre>
<p>So far I have considered solving the problem by hiding a div and displaying a new one starting at 1023 px wide. However, I would then have a double content, which is not the most optimal way in my opinion. Nevertheless, I would have the same result.</p>
| [
{
"answer_id": 74344973,
"author": "Anh Le Hoang",
"author_id": 16315750,
"author_profile": "https://Stackoverflow.com/users/16315750",
"pm_score": 1,
"selected": true,
"text": "Sticky"
},
{
"answer_id": 74344975,
"author": "FUZIION",
"author_id": 13050564,
"author_profile": "https://Stackoverflow.com/users/13050564",
"pm_score": 0,
"selected": false,
"text": "/* jQuery */\nwindow.onscroll = function JQanchorOnScroll() {\n var $anchor = $(\".faq-anchor\");\n var $element = $('.faq');\n\n var move = function() {\n var scrollTop = $(window).scrollTop();\n var OffsetTop = $anchor.offset().top;\n if (scrollTop > OffsetTop) {\n $element.css({\n position: \"fixed\",\n top: \"0px\"\n });\n } else {\n $element.css({\n position: \"relative\",\n top: \"\"\n });\n }\n };\n $(window).scroll(move);\n move();\n}"
},
{
"answer_id": 74344977,
"author": "Mohammed Shahed",
"author_id": 19067773,
"author_profile": "https://Stackoverflow.com/users/19067773",
"pm_score": -1,
"selected": false,
"text": ".rightcolumn {\n float: left;\n width: 25%;\n height: 100%;\n padding-left: 20px;\n padding-right: 90px;\n position: sticky;\n top: 0;\n}\n\n/*to test it it's sticky\ndo this */\n\n.leftcolumn {\n float: left;\n width: 75%;\n padding-left: 90px;\n min-height: 200vh;\n}\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74344662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20438799/"
] |
74,344,666 | <p>How do I encrypt a bash script file as aes 256 base64 and convert it to a linux executable?</p>
<p>I encrypted it as aes 256 base64 but I can't run it</p>
| [
{
"answer_id": 74345252,
"author": "Ivan",
"author_id": 12607443,
"author_profile": "https://Stackoverflow.com/users/12607443",
"pm_score": 0,
"selected": false,
"text": "$ cat enc\n#!/bin/bash\nsed '1,/encrypted part/d;1,/encrypted part/d' $0 | base64 -d > test2\nchmod +x test2\n./test2\nexit\n#-------------{ encrypted part }---------------\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74344666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20073616/"
] |
74,344,678 | <p>Sup' I would like to link an IFC file with Revit Design-Automation, not to directly open it because opening causes troubles: <a href="https://www.cadlinecommunity.co.uk/hc/en-us/articles/4624032130205-Revit-2022-Tip-Working-with-IFC-files-Elements-missing-limited-functionality-" rel="nofollow noreferrer">Working with IFC files? Elements missing, limited functionality?</a>, so I'm OMW 2 link it using code from that <a href="https://adndevblog.typepad.com/aec/2015/02/revitapi-how-to-insert-revit-link-file.html" rel="nofollow noreferrer">article</a>:</p>
<pre><code>ModelPath mp = ModelPathUtils.ConvertUserVisiblePathToModelPath(@"C:\input.ifc");
RevitLinkOptions rlo = new RevitLinkOptions(false);
var linkType = RevitLinkType.Create(RevitDoc, mp, rlo);
var instance = RevitLinkInstance.Create(RevitDoc, linkType.ElementId);
</code></pre>
<p>The first step is to be able to create a new empty document, however what I'm seeing so far is that <code>NewProjectDocument</code> is available on <code>Application</code> but not on <code>ControlledApplication</code> which is the object available when running in DA.</p>
<p>My question then, is there a way to create a new document from DA? Alternatively is there a way to link the input ifc instead of directly opening it in DA?</p>
<p>Thanks for the insights.</p>
| [
{
"answer_id": 74345252,
"author": "Ivan",
"author_id": 12607443,
"author_profile": "https://Stackoverflow.com/users/12607443",
"pm_score": 0,
"selected": false,
"text": "$ cat enc\n#!/bin/bash\nsed '1,/encrypted part/d;1,/encrypted part/d' $0 | base64 -d > test2\nchmod +x test2\n./test2\nexit\n#-------------{ encrypted part }---------------\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74344678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4916074/"
] |
74,344,756 | <p>In the second foreach loop I have a dropdown list I want to display when I press the edit button. I want to display the dropdown list for which row I want to edit, right now it displays the top row matter the edit button I click. I guess I need to clarify each foreach value with an Id and connect each edit button with that id, but I don't know how. any help is appreciated.</p>
<p>index.cshtml</p>
<pre><code><table id="tblCustomers" class="table table-striped">
<tbody>
@foreach (var item in Model.Organisations)
{
<tr>
<td>
<span>@item.HsaId</span>
</td>
<td>
<span>@item.OrgsName</span>
</td>
<td class="PartnerOrg">
<span>@item.PartnersLgId</span>
<div id="lgpartners">
<select multiple="multiple">
@foreach (var p in Model.Partners)
{
<option>@p.LgId</option>
}
</select>
</div>
</td>
<td>
<a id="Edit" onclick="becomevisible()">Edit</a>
<a id="Update" style="display:none">Update</a>
<a id="Cancel" style="display:none" onclick="becomehidden()">Cancel</a>
<a id="Delete">Delete</a>
</td>
</tr>
}
</tbody>
</table>
</code></pre>
<p>javascript.js</p>
<pre><code>function becomevisible() {
document.getElementById("lgpartners").style.display = "block";
}
function becomehidden() {
document.getElementById("lgpartners").style.display = "none";
}
</code></pre>
<p>I have searched on Google and tried finding the answer to my question but haven't found one I liked yet</p>
| [
{
"answer_id": 74345252,
"author": "Ivan",
"author_id": 12607443,
"author_profile": "https://Stackoverflow.com/users/12607443",
"pm_score": 0,
"selected": false,
"text": "$ cat enc\n#!/bin/bash\nsed '1,/encrypted part/d;1,/encrypted part/d' $0 | base64 -d > test2\nchmod +x test2\n./test2\nexit\n#-------------{ encrypted part }---------------\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74344756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20438775/"
] |
74,344,758 | <p>I using Grid Bootstrap</p>
<p><a href="https://i.stack.imgur.com/giJOI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/giJOI.png" alt="enter image description here" /></a></p>
<p>when I switch back to my Mobile screen I want
<a href="https://i.stack.imgur.com/RYPJm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RYPJm.png" alt="enter image description here" /></a></p>
<p>I tried many ways but still can't solve. Thanks for reading!</p>
<p>use bootstrap grid and have corresponding response</p>
| [
{
"answer_id": 74345335,
"author": "dante velli",
"author_id": 19338216,
"author_profile": "https://Stackoverflow.com/users/19338216",
"pm_score": 0,
"selected": false,
"text": "height"
},
{
"answer_id": 74345411,
"author": "Vladimir",
"author_id": 19636184,
"author_profile": "https://Stackoverflow.com/users/19636184",
"pm_score": -1,
"selected": false,
"text": "<div class=\"container\">\n <div class=\"row\">\n <div class=\"col-md-3 col-6\" id=\"col1\">\n <h2>1</h2>\n </div>\n\n <div class=\"col-md-3 col-6\" id=\"col2\">\n <h2>2</h2>\n </div>\n\n <div class=\"col-md-3 col-6\" id=\"col3\">\n <h2>3</h2>\n </div>\n </div>\n </div>\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74344758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15941000/"
] |
74,344,760 | <p>Trying to return Ok response but getting the exception:</p>
<pre><code>Cannot access a disposed object.\nObject name: 'AsyncCursor
</code></pre>
<p>Getting this on first line in if condition</p>
<pre><code> var users = await _userCollection.FindAsync(user => user.Phone == loginUser.phone);
// if user found then login
// else create empty doc
if (users.ToList().Count > 0)
{
var user = await users.FirstAsync();
string token = new ShirtDeck.Utils.JwtUtil(configuration).GenerateJWT(user);
return Ok(new { user = user, token = token });
}
</code></pre>
<p>Expected to read the first document from the list.</p>
| [
{
"answer_id": 74345335,
"author": "dante velli",
"author_id": 19338216,
"author_profile": "https://Stackoverflow.com/users/19338216",
"pm_score": 0,
"selected": false,
"text": "height"
},
{
"answer_id": 74345411,
"author": "Vladimir",
"author_id": 19636184,
"author_profile": "https://Stackoverflow.com/users/19636184",
"pm_score": -1,
"selected": false,
"text": "<div class=\"container\">\n <div class=\"row\">\n <div class=\"col-md-3 col-6\" id=\"col1\">\n <h2>1</h2>\n </div>\n\n <div class=\"col-md-3 col-6\" id=\"col2\">\n <h2>2</h2>\n </div>\n\n <div class=\"col-md-3 col-6\" id=\"col3\">\n <h2>3</h2>\n </div>\n </div>\n </div>\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74344760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11668651/"
] |
74,344,812 | <p>How to mock the following statement :</p>
<pre><code>int var = func1(func2(obj.func3()));
</code></pre>
<p>Expecting the entire result to be mocked to return some value to var</p>
| [
{
"answer_id": 74344852,
"author": "YCF_L",
"author_id": 5558072,
"author_profile": "https://Stackoverflow.com/users/5558072",
"pm_score": 2,
"selected": false,
"text": "when(obj.func3()).thenReturn(someValue);\nwhen(func2(any())).thenReturn(someValue2);\n"
},
{
"answer_id": 74344991,
"author": "Rishab Sud",
"author_id": 19030239,
"author_profile": "https://Stackoverflow.com/users/19030239",
"pm_score": 0,
"selected": false,
"text": "Mockito.when(obj.func3()).thenReturn(value);\n\nMockito.when(func2(value)).thenReturn(value2);\n\nMockito.when(obj.func1(value2)).thenReturn(int);\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74344812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1473330/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.