qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,526,041
|
<p>I am trying to understand the pointer used in line of code below written by the user <a href="https://stackoverflow.com/users/8542346/h-s">H.S</a> in <a href="https://stackoverflow.com/questions/48333430/iterate-through-argv/74523715#74523715">this post</a>. Could anyone help me?</p>
<pre><code>for (char **pargv = argv+1; *pargv != argv[argc]; pargv++)
</code></pre>
<p>The whole code:</p>
<pre><code>#include <stdio.h>
int main(int argc, char *argv[])
{
if (argc < 2) {
printf("ERROR: You need at least one argument.\n");
return -1;
}
for (char **pargv = argv+1; *pargv != argv[argc]; pargv++) {
/* Explaination:
* Initialization -
* char **pargv = argv+1; --> pargv pointer pointing second element of argv
* The first element of argument vector is program name
* Condition -
* *pargv != argv[argc]; --> *pargv iterate to argv array
* argv[argc] represents NULL
* So, the condition is *pargv != NULL
* This condition (*pargv != argv[argc]) is for your understanding
* If using only *pragv is also okay
* Loop iterator increment -
* pargv++
*/
printf ("Vowels in string \"%s\" : ", *pargv);
for (char *ptr = *pargv; *ptr != '\0'; ptr++) {
if (*ptr == 'a' || *ptr == 'e' || *ptr == 'i' || *ptr == 'o' || *ptr == 'u'
|| *ptr == 'A' || *ptr == 'E' || *ptr == 'I' || *ptr == 'O' || *ptr == 'U') {
printf ("%c ", *ptr);
}
}
printf ("\n");
}
return 0;
}
</code></pre>
<p><strong>Questions:</strong></p>
<ol>
<li><p>The two dereference operators used in the first <code>**pargv = argv+1</code> are used because the argv is an array of pointers, therefore it is necessary to use a pointer to a pointer (**pargv) to refer to it.
<strong>Is this statement correct?</strong></p>
</li>
<li><p>Why is it necessary to point to the address of the argv <code>(argv+1)</code> or <code>(&argv[1])</code> and not the value (*argv[1]) that is inside it?</p>
</li>
</ol>
<p>In my mind pointing to the address would bring the int number of the address, but I know the code is correct this way. So why pointing to the address return the value inside?</p>
<p>I have tried to change the piece of code below by replacing the <code>argv+1</code> for <code>argv[1]</code> because in my mind I should point to the value inside of the array and not to the address that leads to the value but I got an error from the compiler (GCC).</p>
<pre><code>for (char **pargv = argv+1; *pargv != argv[argc]; pargv++)
</code></pre>
|
[
{
"answer_id": 74526365,
"author": "John Bollinger",
"author_id": 2402272,
"author_profile": "https://Stackoverflow.com/users/2402272",
"pm_score": 1,
"selected": false,
"text": "**pargv = argv+1 ** pargv char ** char argv argv (argv+1) (&argv[1]) *pargv for (int i = 1; argv[i] != argv[argc]; i++) {\n char **pargv = argv + i;\n // ...\n argv+1 argv[1] argv+1 argv[1] char ** char * argv[1] *((argv)+1) argv+1 &argv[1]"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74526041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18534979/"
] |
74,526,043
|
<p>I am trying to make my bash script ssh into each server and then grep Selinux=enforcing/replace with Selinux=permissive. The issue I am facing is it checks the first server and but not the second server. I believe it arises from my if statement.</p>
<pre><code>#!/bin/bash
selinux_path=/opt/configtest
hosts=(server1 server2)
for my_hosts in "${hosts[@]}"
do
ssh -q -o "StrictHostKeyChecking no" root@${my_hosts} "
if [ $(grep -c SELINUX=enforcing $selinux_path) -ne 0 ]
then
echo "------------------------------------------------"
echo "${my_hosts}"
echo "------------------------------------------------"
sed -i 's/SELINUX=enforcing/SELINUX=permissive/g' ${selinux_path}
echo "Selinux has been changed to permissive"
cat ${selinux_path}
else
echo "------------------------------------------------"
echo "${my_hosts}"
echo "------------------------------------------------"
echo "Selinux has already been changed to permissive"
cat ${selinux_path}
fi
"
done
</code></pre>
|
[
{
"answer_id": 74526365,
"author": "John Bollinger",
"author_id": 2402272,
"author_profile": "https://Stackoverflow.com/users/2402272",
"pm_score": 1,
"selected": false,
"text": "**pargv = argv+1 ** pargv char ** char argv argv (argv+1) (&argv[1]) *pargv for (int i = 1; argv[i] != argv[argc]; i++) {\n char **pargv = argv + i;\n // ...\n argv+1 argv[1] argv+1 argv[1] char ** char * argv[1] *((argv)+1) argv+1 &argv[1]"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74526043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20565135/"
] |
74,526,051
|
<p>I am looking for help in a scenario where I have a scala dataframe PARENT. I need to</p>
<ul>
<li><p>loop through each record in PARENT dataframe</p>
</li>
<li><p>Query the records from a database based on a filter using ID value of
parent (the output of this step is dataframe)</p>
</li>
<li><p>append few attributes from parent to queried dataframe</p>
<p>Ex:</p>
<pre><code> ParentDF
id parentname
1 X
2 Y
Queried Dataframe for id 1
id queryid name
1 23 lobo
1 45 sobo
1 56 aobo
Queried Dataframe for id 2
id queryid name
2 53 lama
2 67 dama
2 56 pama
</code></pre>
</li>
</ul>
<pre><code>Final output required :
id parentname queryid name
1 X 23 lobo
1 X 45 sobo
1 X 56 aobo
2 Y 53 lama
2 Y 67 dama
2 Y 56 pama
</code></pre>
<p>Update1:</p>
<p>I tried using foreachpartition and use foreach internally to loop through each record and got below error.</p>
<pre><code>error: Unable to find encoder for type org.apache.spark.sql.DataFrame. An implicit Encoder[org.apache.spark.sql.DataFrame] is needed to store org.apache.spark.sql.DataFrame instances in a Dataset. Primitive types (Int, String, etc) and Product types (case classes) are supported by importing spark.implicits._ Support for serializing other types will be added in future releases.
falttenedData.map(row=>{
I need to do this with scalability plz. Any help is really appreciated.
</code></pre>
|
[
{
"answer_id": 74582042,
"author": "Koedlt",
"author_id": 15405732,
"author_profile": "https://Stackoverflow.com/users/15405732",
"pm_score": 1,
"selected": false,
"text": ".join val df = Seq((1, \"X\"), (2, \"Y\")).toDF(\"id\", \"parentname\")\ndf.show\n+---+----------+ \n| id|parentname| \n+---+----------+ \n| 1| X| \n| 2| Y| \n+---+----------+\n\nval df2 = Seq((1, 23, \"lobo\"), (1, 45, \"sobo\"), (1, 56, \"aobo\"), (2, 53, \"lama\"), (2, 67, \"dama\"), (2, 56, \"pama\")).toDF(\"id\", \"queryid\", \"name\")\ndf2.show\n+---+-------+----+ \n| id|queryid|name| \n+---+-------+----+ \n| 1| 23|lobo| \n| 1| 45|sobo| \n| 1| 56|aobo| \n| 2| 53|lama| \n| 2| 67|dama| \n| 2| 56|pama| \n+---+-------+----+\n\nval output=df.join(df2, Seq(\"id\"))\noutput.show\n+---+----------+-------+----+ \n| id|parentname|queryid|name| \n+---+----------+-------+----+ \n| 1| X| 23|lobo| \n| 1| X| 45|sobo| \n| 1| X| 56|aobo| \n| 2| Y| 53|lama| \n| 2| Y| 67|dama| \n| 2| Y| 56|pama| \n+---+----------+-------+----+\n"
},
{
"answer_id": 74598757,
"author": "Fragan",
"author_id": 9134545,
"author_profile": "https://Stackoverflow.com/users/9134545",
"pm_score": 2,
"selected": false,
"text": "join parentDF.join(\n otherDF,\n Seq(\"id\"),\n \"left\"\n)\n parentDF.join(broadcast(otherDF), Seq(\"id\"), \"left)"
},
{
"answer_id": 74659772,
"author": "hakkikonu",
"author_id": 1848929,
"author_profile": "https://Stackoverflow.com/users/1848929",
"pm_score": 0,
"selected": false,
"text": "import org.apache.spark.sql.functions._\n\n// Load the parent dataframe\nval parentDF = spark.read.parquet(\"/path/to/parent.parquet\")\n\n// Loop through each row in the parent dataframe\nparentDF.foreach { row =>\n val parentID = row.getAs[Long](\"id\")\n\n // Query the records from the database using the parent ID\n val query = s\"SELECT * FROM my_table WHERE parent_id = $parentID\"\n val childDF = spark.sql(query)\n\n // Append the attributes from the parent row to the child dataframe\n val childWithParentDF = childDF.withColumn(\"parent_name\", lit(row.getAs[String](\"name\")))\n .withColumn(\"parent_email\", lit(row.getAs[String](\"email\")))\n\n // Append the child dataframe to the output dataframe\n val outputDF = outputDF.union(childWithParentDF)\n}\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74526051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2201536/"
] |
74,526,053
|
<p>I need to setup ViewPager2 in a way where I dynamically update the Fragments that are displayed within the ViewPager2.</p>
<p>To facilitate this, I've created a view model LiveData object that includes a list of items that represent the data the fragments should display:</p>
<pre><code>val items: LiveData<List<Item>>
</code></pre>
<p>In my Fragment that contains the ViewPager2, in onViewCreated I setup observing the items:</p>
<pre><code>override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel.items.observe(viewLifecycleOwner) { items ->
binding.viewPager.adapter = createFragmentStateAdapter(items)
}
}
</code></pre>
<p>This is all working fine except when I test with "Don't keep activities" turned on. When I background/foreground the app I see that the Fragment containing the ViewPager2 is recreated and that the items observable is broadcasting an update. However, for some reason the ViewPager2 is showing an older Fragment and appears to be ignoring the new adapter that is created in the items observe block.</p>
<p>How do I get the ViewPager2 to update correctly when the adapter changes?</p>
<p>I believe what might be happening is that the ViewPager2 is trying to restore its own state but in the process is ignoring recent changes to the adapter to use.</p>
|
[
{
"answer_id": 74526073,
"author": "corporate_fun",
"author_id": 1840956,
"author_profile": "https://Stackoverflow.com/users/1840956",
"pm_score": 0,
"selected": false,
"text": "getItemId containsItem FragmentStateAdapter"
},
{
"answer_id": 74526580,
"author": "่ฑๆชๅผ",
"author_id": 18241066,
"author_profile": "https://Stackoverflow.com/users/18241066",
"pm_score": 1,
"selected": false,
"text": " class DemoAdapter: RecyclerView.Adapter<DemoAdapter.VHolder>(){\n class VHolder(view: View): RecyclerView.ViewHolder(view)\n \n private var dataList: List<String> = emptyList()\n \n fun setDataList(dataList: List<String>) {\n this.dataList = dataList\n notifyDataSetChanged()\n }\n\n override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VHolder {\n // create ViewHolder\n return VHolder(View(parent.context))\n }\n\n override fun onBindViewHolder(holder: VHolder, position: Int) {\n // bind data\n }\n\n override fun getItemCount(): Int {\n \n }\n }\n val adapter = DemoAdapter()\nbinding.viewPager.adapter = adapter\nviewModel.items.observe(viewLifecycleOwner) { items ->\n adapter.setDataList(items)\n}\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74526053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1840956/"
] |
74,526,064
|
<p>I'm trying to write a scope that sorts on one of two columns--if the first (<code>scheduled_at</code>) has data in it then use that data, otherwise resort to <code>created_at</code>.</p>
<pre><code>def self.by_scheduled_at
if scheduled_at
order(scheduled_at: :desc)
else
order(created_at: :desc)
end
end
</code></pre>
<p>This code fails because <code>scheduled_at</code> is an instance attribute and this is a class method.</p>
<p>How can I write this scope so it sorts the collection based on whether <code>scheduled_at</code> is present?</p>
|
[
{
"answer_id": 74526073,
"author": "corporate_fun",
"author_id": 1840956,
"author_profile": "https://Stackoverflow.com/users/1840956",
"pm_score": 0,
"selected": false,
"text": "getItemId containsItem FragmentStateAdapter"
},
{
"answer_id": 74526580,
"author": "่ฑๆชๅผ",
"author_id": 18241066,
"author_profile": "https://Stackoverflow.com/users/18241066",
"pm_score": 1,
"selected": false,
"text": " class DemoAdapter: RecyclerView.Adapter<DemoAdapter.VHolder>(){\n class VHolder(view: View): RecyclerView.ViewHolder(view)\n \n private var dataList: List<String> = emptyList()\n \n fun setDataList(dataList: List<String>) {\n this.dataList = dataList\n notifyDataSetChanged()\n }\n\n override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VHolder {\n // create ViewHolder\n return VHolder(View(parent.context))\n }\n\n override fun onBindViewHolder(holder: VHolder, position: Int) {\n // bind data\n }\n\n override fun getItemCount(): Int {\n \n }\n }\n val adapter = DemoAdapter()\nbinding.viewPager.adapter = adapter\nviewModel.items.observe(viewLifecycleOwner) { items ->\n adapter.setDataList(items)\n}\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74526064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1153022/"
] |
74,526,091
|
<pre><code>testdata = ["One,For,The,Money", "Two,For,The,Show", "Three,To,Get,Ready", "Now,Go,Cat,Go"]
#My Code:
def chop(string):
x = 0
y = 0
while x < 5:
y = string.find(",") + 1
z = string.find(",", y)
x = x + 1
return y, z
#My Code Ends
for i in range(4):
uno, dos, tres, cuatro = chop(testdata[i])
print(uno + ":" + dos + ":" + tres + ":" + cuatro)
</code></pre>
<p>It say I don't have enough values, I previously tried appending similar code to a list and it said I had too many</p>
|
[
{
"answer_id": 74526073,
"author": "corporate_fun",
"author_id": 1840956,
"author_profile": "https://Stackoverflow.com/users/1840956",
"pm_score": 0,
"selected": false,
"text": "getItemId containsItem FragmentStateAdapter"
},
{
"answer_id": 74526580,
"author": "่ฑๆชๅผ",
"author_id": 18241066,
"author_profile": "https://Stackoverflow.com/users/18241066",
"pm_score": 1,
"selected": false,
"text": " class DemoAdapter: RecyclerView.Adapter<DemoAdapter.VHolder>(){\n class VHolder(view: View): RecyclerView.ViewHolder(view)\n \n private var dataList: List<String> = emptyList()\n \n fun setDataList(dataList: List<String>) {\n this.dataList = dataList\n notifyDataSetChanged()\n }\n\n override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VHolder {\n // create ViewHolder\n return VHolder(View(parent.context))\n }\n\n override fun onBindViewHolder(holder: VHolder, position: Int) {\n // bind data\n }\n\n override fun getItemCount(): Int {\n \n }\n }\n val adapter = DemoAdapter()\nbinding.viewPager.adapter = adapter\nviewModel.items.observe(viewLifecycleOwner) { items ->\n adapter.setDataList(items)\n}\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74526091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20567408/"
] |
74,526,134
|
<p>Context: I roughly have a dictionary of about 130 lists in the form of a key and a list of indexes.</p>
<p><code>{โkey1โ:[0,1,2], โkey2โ: [2, 3, 4], โkey3โ:[5, 6],โฆ, โkey130โ:[0, 450, 1103, 500,โฆ]}</code></p>
<p>Lists are all different sizes.</p>
<p>This is a two-part problem where:</p>
<ol>
<li><p>I want some form of data structure to store the number of overlaps between lists</p>
</li>
<li><p>If possible, I want a diagram that shows the overlap</p>
</li>
</ol>
<p>PART 1:</p>
<p>The most similar StackOverflow questions answers were that we could find list similarities by utilizing <code>set.intersection</code></p>
<p><code>List1 = [10,10,11,12,15,16,18,19]</code></p>
<p><code>List2 = [10,11,13,15,16,19,20]</code></p>
<p><code>List3 = [10,11,11,12,15,19,21,23]</code></p>
<p><code>print(set(List1).intersection(List2)) #compare between list 2 and 3</code></p>
<p>Which gives you:</p>
<p><code>set([10, 11, 15, 16, 19])</code></p>
<p>I could then use a for loop to traverse through each list to compare it with the next list in the dictionary and get the length of the list. This would then give me a dictionary such as:</p>
<p><code>{โkey1_key2โ:1, โkey2_key3โ:0, โkey3_key4โโฆ, โkey130_key1โ: [29]}</code></p>
<p>PART 2:</p>
<p>I have in my head that a comparison table would be the best to visualize the similarities:</p>
<pre><code>
Key1 Key2 Key3 โฆ Key130
Key1 X X X X
Key2 0 X X X
Key3 4 6 X X
โฆ X โฆ
Key130 X
</code></pre>
<p>However, I couldnโt find many results on how this can be achieved.</p>
<p>Another option was UpSetPlot as it can allow for pretty nice yet perhaps a little excessive comparison in this case: <a href="https://upsetplot.readthedocs.io/en/stable/" rel="nofollow noreferrer">https://upsetplot.readthedocs.io/en/stable/</a></p>
<p>Of course, Iโm sure both diagrams would need the similarities result to be stored a bit differently? Iโm not too sure for the Comparison Table but UpSetPlot would need the dictionary (?) to be a pandaSeries. I would be interested in both diagrams to test how it would look.</p>
<p>Reproducible Example:</p>
<p><code>{'key1': [10,10,11,12,15,16,18,19], 'key2': [10,11,13,15,16,19,20], 'key3':[10,11,11,12,15,19,21,23], 'key4':[], 'key5':[0], 'key6':[10,55,66,77]}</code></p>
<p>Some of the more useful resources I looked at:<br />
<a href="https://stackoverflow.com/questions/36356430/how-to-compare-more-than-2-lists-in-python">How to compare more than 2 Lists in Python?</a> <a href="https://stackoverflow.com/questions/3852780/python-intersection-of-multiple-lists">Python -Intersection of multiple lists?</a> <a href="https://stackoverflow.com/questions/66825448/python-comparing-multiple-lists-into-comparison-table">Python comparing multiple lists into Comparison Table</a></p>
<p>If there are some other sites that I missed that would be applicable to this Q, please let me know. Thank you in advance!</p>
|
[
{
"answer_id": 74526474,
"author": "CryptoFool",
"author_id": 7631480,
"author_profile": "https://Stackoverflow.com/users/7631480",
"pm_score": 0,
"selected": false,
"text": "from pprint import pprint\n\n# Build the comparison structure\ndef build_comparisons(input, sparse=True):\n comparisons = {}\n for key1 in input.keys():\n comparisons[key1] = {}\n for key2 in input.keys():\n if key2 in comparisons and key1 in comparisons[key2]:\n # If we've already computed the intersection for this pair of keys...\n if sparse:\n # For a sparse structure, don't include values for keys that\n # already exist in the structure in the opposite order of keys\n continue\n # Use the already computed value\n comparisons[key1][key2] = comparisons[key2][key1]\n elif key1 == key2:\n # If the keys are the same, use the length of that key's value\n comparisons[key1][key2] = len(input[key1])\n else:\n # Compute the intersection between the two keys and take its length\n l1 = set(input[key1])\n l2 = set(input[key2])\n comparisons[key1][key2] = len(l1.intersection(l2))\n return comparisons\n\n# Look up the intersection for a keypair. This function is only necessary\n# to make it easier to look up values in a sparse structure\ndef get_comparison(comparisons, key1, key2):\n if key1 in comparisons and key2 in comparisons[key1]:\n return comparisons[key1][key2]\n return comparisons[key2][key1]\n\n# Display the lengths of each intersection in a table format\ndef display_comparisons(comparisons):\n\n cell_width = max([len(key) for key in comparisons.keys()]) + 2\n\n def print_cell(val):\n print(f\"{str(val):<{cell_width}}\", end='')\n\n print_cell('')\n [print_cell(key) for key in comparisons.keys()]\n print()\n for key1 in comparisons.keys():\n print_cell(key1)\n for key2 in comparisons.keys():\n print_cell(get_comparison(comparisons, key1, key2))\n print()\n\ninput = {'key1': [10,10,11,12,15,16,18,19], 'key2': [10,11,13,15,16,19,20], 'key3':[10,11,11,12,15,19,21,23], 'key4':[], 'key5':[0], 'key6':[10,55,66,77]}\n\n# Build the comparison structure\ncomparisons = build_comparisons(input)\n\n# Show the resulting data structure\npprint(comparisons)\n\nprint()\n\n# Display the lengths of each intersection in a table format\ndisplay_comparisons(comparisons)\n {'key1': {'key1': 8, 'key2': 5, 'key3': 5, 'key4': 0, 'key5': 0, 'key6': 1},\n 'key2': {'key2': 7, 'key3': 4, 'key4': 0, 'key5': 0, 'key6': 1},\n 'key3': {'key3': 8, 'key4': 0, 'key5': 0, 'key6': 1},\n 'key4': {'key4': 0, 'key5': 0, 'key6': 0},\n 'key5': {'key5': 1, 'key6': 0},\n 'key6': {'key6': 4}}\n\n key1 key2 key3 key4 key5 key6 \nkey1 8 5 5 0 0 1 \nkey2 5 7 4 0 0 1 \nkey3 5 4 8 0 0 1 \nkey4 0 0 0 0 0 0 \nkey5 0 0 0 0 1 0 \nkey6 1 1 1 0 0 4 \n sparse False {'key1': {'key1': 8, 'key2': 5, 'key3': 5, 'key4': 0, 'key5': 0, 'key6': 1},\n 'key2': {'key1': 5, 'key2': 7, 'key3': 4, 'key4': 0, 'key5': 0, 'key6': 1},\n 'key3': {'key1': 5, 'key2': 4, 'key3': 8, 'key4': 0, 'key5': 0, 'key6': 1},\n 'key4': {'key1': 0, 'key2': 0, 'key3': 0, 'key4': 0, 'key5': 0, 'key6': 0},\n 'key5': {'key1': 0, 'key2': 0, 'key3': 0, 'key4': 0, 'key5': 1, 'key6': 0},\n 'key6': {'key1': 1, 'key2': 1, 'key3': 1, 'key4': 0, 'key5': 0, 'key6': 4}}\n"
},
{
"answer_id": 74526874,
"author": "Ben. S.",
"author_id": 12261629,
"author_profile": "https://Stackoverflow.com/users/12261629",
"pm_score": 2,
"selected": true,
"text": "import numpy as np\nimport pandas as pd\n\nd = {'key1':[0,1,2], 'key2': [2, 3, 4], 'key3':[5, 6]}\ns = []\n[s.append(list(set(x) & set(y))) for x in d.values() for y in d.values()]\n\nmatrix1 = np.array(s, dtype = object)\nmatrix2 = matrix1.reshape(int(np.sqrt(len(matrix1))),int(np.sqrt(len(matrix1))))\nmatrix2 = np.vectorize(len)(matrix2)\n\ndf = pd.DataFrame(matrix2)\ndf.columns = d.keys()\ndf.index = d.keys()\n\nprint(df)\n key1 key2 key3\nkey1 3 1 0\nkey2 1 3 0\nkey3 0 0 2\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74526134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11445194/"
] |
74,526,167
|
<p>I'm trying to pass an ArrayList from an AsyncTask in the MainActivity to a fragment, but I'm getting a <em>NullPointerException</em> for invoking
<code> CategoryAdapter.getItemCount()</code> even if I'm passing the array after the BroadCastReceiver Invoke.</p>
<p>What Am I doing wrong?</p>
<p><strong>MainActivity</strong></p>
<pre class="lang-java prettyprint-override"><code> class GetBooksAsync extends AsyncTask<Void, Void, Void> {
LocalBroadcastManager manager = LocalBroadcastManager.getInstance(getApplicationContext());
@Override
protected Void doInBackground(Void... voids) {
for (ECategories category : ECategories.values()) {
try {
categories.add(new Category(category.toString(), apiClient.getBooks(category)));
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Intent intent = new Intent("com.android.mainapp");
intent.putExtra("categories", categories);
manager.sendBroadcast(intent);
replaceFragment(new HomeFragment());
}
}
</code></pre>
<p><strong>HomeFragment</strong></p>
<pre class="lang-java prettyprint-override"><code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
initBroadCastReceiver();
categoryAdapter = new CategoryAdapter(categories,getContext());
View view = inflater.inflate(R.layout.fragment_home, container, false);
recyclerView = view.findViewById(R.id.parent_rv);
recyclerView.setAdapter(categoryAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
categoryAdapter.notifyDataSetChanged();
return view;
}
private void initBroadCastReceiver() {
manager = LocalBroadcastManager.getInstance(getContext());
MyBroadCastReceiver receiver = new MyBroadCastReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("com.android.mainapp");
manager.registerReceiver(receiver,filter);
}
class MyBroadCastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//get the categories from the intent
categories = new ArrayList<Category>();
categories = (ArrayList<Category>) intent.getSerializableExtra("categories");
}
}
</code></pre>
<p>i've also tried attaching the recyclerView from the OnReceive Method, but it's not getting attached.
Thank you in advance!</p>
|
[
{
"answer_id": 74526474,
"author": "CryptoFool",
"author_id": 7631480,
"author_profile": "https://Stackoverflow.com/users/7631480",
"pm_score": 0,
"selected": false,
"text": "from pprint import pprint\n\n# Build the comparison structure\ndef build_comparisons(input, sparse=True):\n comparisons = {}\n for key1 in input.keys():\n comparisons[key1] = {}\n for key2 in input.keys():\n if key2 in comparisons and key1 in comparisons[key2]:\n # If we've already computed the intersection for this pair of keys...\n if sparse:\n # For a sparse structure, don't include values for keys that\n # already exist in the structure in the opposite order of keys\n continue\n # Use the already computed value\n comparisons[key1][key2] = comparisons[key2][key1]\n elif key1 == key2:\n # If the keys are the same, use the length of that key's value\n comparisons[key1][key2] = len(input[key1])\n else:\n # Compute the intersection between the two keys and take its length\n l1 = set(input[key1])\n l2 = set(input[key2])\n comparisons[key1][key2] = len(l1.intersection(l2))\n return comparisons\n\n# Look up the intersection for a keypair. This function is only necessary\n# to make it easier to look up values in a sparse structure\ndef get_comparison(comparisons, key1, key2):\n if key1 in comparisons and key2 in comparisons[key1]:\n return comparisons[key1][key2]\n return comparisons[key2][key1]\n\n# Display the lengths of each intersection in a table format\ndef display_comparisons(comparisons):\n\n cell_width = max([len(key) for key in comparisons.keys()]) + 2\n\n def print_cell(val):\n print(f\"{str(val):<{cell_width}}\", end='')\n\n print_cell('')\n [print_cell(key) for key in comparisons.keys()]\n print()\n for key1 in comparisons.keys():\n print_cell(key1)\n for key2 in comparisons.keys():\n print_cell(get_comparison(comparisons, key1, key2))\n print()\n\ninput = {'key1': [10,10,11,12,15,16,18,19], 'key2': [10,11,13,15,16,19,20], 'key3':[10,11,11,12,15,19,21,23], 'key4':[], 'key5':[0], 'key6':[10,55,66,77]}\n\n# Build the comparison structure\ncomparisons = build_comparisons(input)\n\n# Show the resulting data structure\npprint(comparisons)\n\nprint()\n\n# Display the lengths of each intersection in a table format\ndisplay_comparisons(comparisons)\n {'key1': {'key1': 8, 'key2': 5, 'key3': 5, 'key4': 0, 'key5': 0, 'key6': 1},\n 'key2': {'key2': 7, 'key3': 4, 'key4': 0, 'key5': 0, 'key6': 1},\n 'key3': {'key3': 8, 'key4': 0, 'key5': 0, 'key6': 1},\n 'key4': {'key4': 0, 'key5': 0, 'key6': 0},\n 'key5': {'key5': 1, 'key6': 0},\n 'key6': {'key6': 4}}\n\n key1 key2 key3 key4 key5 key6 \nkey1 8 5 5 0 0 1 \nkey2 5 7 4 0 0 1 \nkey3 5 4 8 0 0 1 \nkey4 0 0 0 0 0 0 \nkey5 0 0 0 0 1 0 \nkey6 1 1 1 0 0 4 \n sparse False {'key1': {'key1': 8, 'key2': 5, 'key3': 5, 'key4': 0, 'key5': 0, 'key6': 1},\n 'key2': {'key1': 5, 'key2': 7, 'key3': 4, 'key4': 0, 'key5': 0, 'key6': 1},\n 'key3': {'key1': 5, 'key2': 4, 'key3': 8, 'key4': 0, 'key5': 0, 'key6': 1},\n 'key4': {'key1': 0, 'key2': 0, 'key3': 0, 'key4': 0, 'key5': 0, 'key6': 0},\n 'key5': {'key1': 0, 'key2': 0, 'key3': 0, 'key4': 0, 'key5': 1, 'key6': 0},\n 'key6': {'key1': 1, 'key2': 1, 'key3': 1, 'key4': 0, 'key5': 0, 'key6': 4}}\n"
},
{
"answer_id": 74526874,
"author": "Ben. S.",
"author_id": 12261629,
"author_profile": "https://Stackoverflow.com/users/12261629",
"pm_score": 2,
"selected": true,
"text": "import numpy as np\nimport pandas as pd\n\nd = {'key1':[0,1,2], 'key2': [2, 3, 4], 'key3':[5, 6]}\ns = []\n[s.append(list(set(x) & set(y))) for x in d.values() for y in d.values()]\n\nmatrix1 = np.array(s, dtype = object)\nmatrix2 = matrix1.reshape(int(np.sqrt(len(matrix1))),int(np.sqrt(len(matrix1))))\nmatrix2 = np.vectorize(len)(matrix2)\n\ndf = pd.DataFrame(matrix2)\ndf.columns = d.keys()\ndf.index = d.keys()\n\nprint(df)\n key1 key2 key3\nkey1 3 1 0\nkey2 1 3 0\nkey3 0 0 2\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74526167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20567458/"
] |
74,526,175
|
<p>I'm currently writing a script that uses the function <code>walk</code> in jq, which I'm using to check for the value of a field, which can appear multiple times in the file. If any instance of that field is not <code>true</code>, I want to echo an error notifying users that the field is invalid. Similar to below:</p>
<pre><code>flag=false
cat file.json | jq 'walk (
if type == "object" and has "foo" and (.foo != true); then
flag=true
else . end
)'
if [[ "$flag" == true ]]; then
echo "ERROR"
exit 1
fi
</code></pre>
<p>How can I notify the rest of the program if the check inside <code>walk</code> fails ? Any help is much appreciated!</p>
|
[
{
"answer_id": 74526228,
"author": "pmf",
"author_id": 2158479,
"author_profile": "https://Stackoverflow.com/users/2158479",
"pm_score": 3,
"selected": true,
"text": "all --exit-status -e if jq -e 'all(.. | objects | select(has(\"foo\")); .foo)' file.json >/dev/null\nthen\n echo \"All true\"\nelse\n echo \"At least one not true\"\nfi\n"
},
{
"answer_id": 74527116,
"author": "peak",
"author_id": 997358,
"author_profile": "https://Stackoverflow.com/users/997358",
"pm_score": 0,
"selected": false,
"text": "jq 'if all(.. | objects | select(has(\"foo\")); .foo) \n then \"All truthy\" \n else \"At least one not truthy\"\n end'\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74526175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9030977/"
] |
74,526,183
|
<p>I need to sort a ranking of points by descending order. The users and points are inside <code>lista_ranking</code> which includes de following code:</p>
<p>[{'partido': {'codigo': 'AAA', 'fecha': datetime.date(2022, 11, 20), 'hora': '13:00hs', 'equipo_local': 'Catar', 'equipo_visitante': 'Ecuador', 'estado': 'Finalizado', 'goles_local': 0, 'goles_visitante': 1}, 'usuario': {'cedula': '123', 'nombre': 'Gon', 'apellido': 'Henderson', 'fecha': '(2003, 3, 12)', 'puntaje': 5}, 'goles_local': 1, 'goles_visitante': 0}, {'partido': {'codigo': 'AAA', 'fecha': datetime.date(2022, 11, 20), 'hora': '13:00hs', 'equipo_local': 'Catar', 'equipo_visitante': 'Ecuador', 'estado': 'Finalizado', 'goles_local': 0, 'goles_visitante': 1}, 'usuario': {'cedula': '1234', 'nombre': 'George', 'apellido': 'Stev', 'fecha': '(2003, 3, 12)', 'puntaje': 8}, 'goles_local': 0, 'goles_visitante': 1}]</p>
<p>With the code</p>
<pre><code>ranking_high_to_low=sorted([(numeros['usuario']['puntaje'], numeros['usuario']['nombre'], numeros['usuario']['apellido']) for numeros in lista_ranking], reverse=True) print(ranking_high_to_low)
</code></pre>
<p>It prints the ranking from highest to lowest like this:</p>
<pre><code>[(8, 'George', 'Stev'), (5, 'Gon', 'Henderson')]
</code></pre>
<p>Which <code>for</code> should I use in order for it to print the ranking as follows:</p>
<pre><code>George Stev 8
Gon Henderson 5
</code></pre>
<p>UPDATE:
@arsho
When I use your updated code:</p>
<pre><code>def ranking():
ranking_high_to_low = sorted([(numeros['usuario']['puntaje'],
numeros['usuario']['nombre'],
numeros['usuario']['apellido']) for numeros in lista_ranking], reverse=True)
players = {}
for info in ranking_high_to_low:
player_name = ' '.join(info[1:])
players[player_name] = players.get(player_name, 0) + info[0]
for player, score in sorted(players.items(), key=lambda x: x[1], reverse=True):
print(f"{player} {score}")
for info in ranking_ordenado:
print(f"{' '.join(info[1:])} {info[0]}")
</code></pre>
<p>The output of this is:</p>
<pre><code>Juan Ha 8
Santi Stev 8
Gon Va 10
Gon Va 10
Santi Stev 8
Santi Stev 8
Juan Ha 8
Juan Ha 8
Gon Va 20
Gon Va 10
Gon Va 10
Santi Stev 8
Santi Stev 8
Juan Ha 8
Juan Ha 8
Santi Stev 16
Gon Va 10
Gon Va 10
Santi Stev 8
Santi Stev 8
Juan Ha 8
Juan Ha 8
Gon Va 20
Gon Va 10
Gon Va 10
Santi Stev 8
Santi Stev 8
Juan Ha 8
Juan Ha 8
Santi Stev 16
Gon Va 10
Gon Va 10
Santi Stev 8
Santi Stev 8
Juan Ha 8
Juan Ha 8
Juan Ha 8
Gon Va 10
Gon Va 10
Santi Stev 8
Santi Stev 8
Juan Ha 8
Juan Ha 8
Gon Va 20
Gon Va 10
Gon Va 10
Santi Stev 8
Santi Stev 8
Juan Ha 8
Juan Ha 8
Santi Stev 16
Gon Va 10
Gon Va 10
Santi Stev 8
Santi Stev 8
Juan Ha 8
Juan Ha 8
Juan Ha 16
Gon Va 10
Gon Va 10
Gon Va 20
Gon Va 10
Gon Va 10
Santi Stev 8
Santi Stev 8
Juan Ha 8
Juan Ha 8
Santi Stev 16
Gon Va 10
Gon Va 10
Santi Stev 8
Santi Stev 8
Juan Ha 8
Juan Ha 8
Juan Ha 16
Gon Va 10
Gon Va 10
Santi Stev 8
Santi Stev 8
Juan Ha 8
Juan Ha 8
</code></pre>
|
[
{
"answer_id": 74526220,
"author": "aaryanm23",
"author_id": 17690095,
"author_profile": "https://Stackoverflow.com/users/17690095",
"pm_score": 0,
"selected": false,
"text": " for (num, first, last) in ranking_high_to_low:\n print(\"{} {} {}\".format(first, last, num))\n"
},
{
"answer_id": 74526249,
"author": "arsho",
"author_id": 3129414,
"author_profile": "https://Stackoverflow.com/users/3129414",
"pm_score": 2,
"selected": true,
"text": "import datetime\n\nlista_ranking = [\n {'partido': {'codigo': 'AAA', 'fecha': datetime.date(2022, 11, 20),\n 'hora': '13:00hs', 'equipo_local': 'Catar',\n 'equipo_visitante': 'Ecuador', 'estado': 'Finalizado',\n 'goles_local': 0, 'goles_visitante': 1},\n 'usuario': {'cedula': '123', 'nombre': 'Gon',\n 'apellido': 'Henderson',\n 'fecha': '(2003, 3, 12)', 'puntaje': 5},\n 'goles_local': 1,\n 'goles_visitante': 0}, {\n 'partido': {'codigo': 'AAA',\n 'fecha': datetime.date(2022, 11, 20),\n 'hora': '13:00hs', 'equipo_local': 'Catar',\n 'equipo_visitante': 'Ecuador',\n 'estado': 'Finalizado',\n 'goles_local': 0, 'goles_visitante': 1},\n 'usuario': {'cedula': '1234', 'nombre': 'George',\n 'apellido': 'Stev', 'fecha': '(2003, 3, 12)',\n 'puntaje': 8}, 'goles_local': 0,\n 'goles_visitante': 1}]\nranking_high_to_low = sorted([(numeros['usuario']['puntaje'],\n numeros['usuario']['nombre'],\n numeros['usuario']['apellido']) for numeros in\n lista_ranking], reverse=True)\nfor info in ranking_high_to_low:\n print(f\"{' '.join(info[1:])} {info[0]}\")\n George Stev 8\nGon Henderson 5\n join import datetime\n\nlista_ranking = [\n {'partido': {'codigo': 'AAA', 'fecha': datetime.date(2022, 11, 20),\n 'hora': '13:00hs', 'equipo_local': 'Catar',\n 'equipo_visitante': 'Ecuador', 'estado': 'Finalizado',\n 'goles_local': 0, 'goles_visitante': 1},\n 'usuario': {'cedula': '123', 'nombre': 'Gon',\n 'apellido': 'Henderson',\n 'fecha': '(2003, 3, 12)', 'puntaje': 5},\n 'goles_local': 1,\n 'goles_visitante': 0},\n {'partido': {'codigo': 'AAA', 'fecha': datetime.date(2022, 11, 20),\n 'hora': '13:00hs', 'equipo_local': 'Catar',\n 'equipo_visitante': 'Ecuador', 'estado': 'Finalizado',\n 'goles_local': 0, 'goles_visitante': 1},\n 'usuario': {'cedula': '123', 'nombre': 'Gon',\n 'apellido': 'Henderson',\n 'fecha': '(2003, 3, 12)', 'puntaje': 5},\n 'goles_local': 1,\n 'goles_visitante': 0}\n , {\n 'partido': {'codigo': 'AAA',\n 'fecha': datetime.date(2022, 11, 20),\n 'hora': '13:00hs', 'equipo_local': 'Catar',\n 'equipo_visitante': 'Ecuador',\n 'estado': 'Finalizado',\n 'goles_local': 0, 'goles_visitante': 1},\n 'usuario': {'cedula': '1234', 'nombre': 'George',\n 'apellido': 'Stev', 'fecha': '(2003, 3, 12)',\n 'puntaje': 8}, 'goles_local': 0,\n 'goles_visitante': 1}]\nranking_high_to_low = [(numeros['usuario']['puntaje'],\n numeros['usuario']['nombre'],\n numeros['usuario']['apellido']) for numeros in\n lista_ranking]\n\nplayers = {}\nfor info in ranking_high_to_low:\n player_name = ' '.join(info[1:])\n players[player_name] = players.get(player_name, 0) + info[0]\n\nfor player, score in sorted(players.items(), key=lambda x: x[1], reverse=True):\n print(f\"{player} {score}\")\n Gon Henderson 10\nGeorge Stev 8\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74526183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20531685/"
] |
74,526,223
|
<p>I used the following process the generate a <code>numpy array</code> with size = <code>(720, 720, 3)</code>. In principle, it should cost <code>720 * 720 * 3 * 8Byte = 12.3MB</code>. <strong>However, in the <code>ans = memory_benchmark()</code>, it costs <code>188 MB</code>.</strong> Why does it cost much more memory than expected? <strong>I think it should have same cost as the line <code>m1 = np.ones((720, 720, 3))</code>.</strong></p>
<p>I have following two Environments. Both have same problem.</p>
<p><strong>Environment1: numpy=1.23.4, memory_profiler=0.61.0, python=3.10.6, MacOS 12.6.1(Intel not M1)</strong></p>
<p><strong>Environment2: numpy=1.19.5, memory_profiler=0.61.0, python=3.8.15, MacOS 12.6.1(Intel not M1)</strong></p>
<p>I did memory profile in the following</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
from memory_profiler import profile
@profile
def memory_benchmark():
m1 = np.ones((720, 720, 3))
m2 = np.random.randint(128, size=(720, 720, 77, 3))
a = m2[:, :, :, 0].astype(np.uint16)
b = m2[:, :, :, 1].astype(np.uint16)
ans = np.array(m1[b, a].sum(axis=2))
m2 = None
a = None
b = None
m1 = None
return ans
@profile
def f():
ans = memory_benchmark()
print(ans.shape)
print("finished")
if __name__ == '__main__':
f()
</code></pre>
<pre><code>(720, 720, 3)
finished
Line # Mem usage Increment Occurrences Line Contents
=============================================================
5 59.3 MiB 59.3 MiB 1 @profile
6 def memory_benchmark():
7 71.2 MiB 11.9 MiB 1 m1 = np.ones((720, 720, 3))
8 984.8 MiB 913.7 MiB 1 m2 = np.random.randint(128, size=(720, 720, 77, 3))
9 1061.0 MiB 76.1 MiB 1 a = m2[:, :, :, 0].astype(np.uint16)
10 1137.1 MiB 76.1 MiB 1 b = m2[:, :, :, 1].astype(np.uint16)
11 1160.9 MiB 23.8 MiB 1 ans = np.array(m1[b, a].sum(axis=2))
12 247.3 MiB -913.6 MiB 1 m2 = None
13 247.3 MiB 0.0 MiB 1 a = None
14 247.3 MiB 0.0 MiB 1 b = None
15 247.3 MiB 0.0 MiB 1 m1 = None
16 247.3 MiB 0.0 MiB 1 return ans
Line # Mem usage Increment Occurrences Line Contents
=============================================================
19 59.3 MiB 59.3 MiB 1 @profile
20 def f():
21 247.3 MiB 188.0 MiB 1 ans = memory_benchmark()
22 247.3 MiB 0.0 MiB 1 print(ans.shape)
23 247.3 MiB 0.0 MiB 1 print("finished")
</code></pre>
<p>If I <code>print(type(m1[0, 0, 0]))</code> yields <code><class 'numpy.float64'></code>, <code>print(type(m2[0, 0, 0, 0]))</code> yields <code><class 'numpy.int64'></code>, <code>print(type(ans[0, 0, 0]))</code> yields <code><class 'numpy.float64'></code></p>
<p><strong>However, in my Ubuntu VM, I don't have above problem.</strong></p>
|
[
{
"answer_id": 74526220,
"author": "aaryanm23",
"author_id": 17690095,
"author_profile": "https://Stackoverflow.com/users/17690095",
"pm_score": 0,
"selected": false,
"text": " for (num, first, last) in ranking_high_to_low:\n print(\"{} {} {}\".format(first, last, num))\n"
},
{
"answer_id": 74526249,
"author": "arsho",
"author_id": 3129414,
"author_profile": "https://Stackoverflow.com/users/3129414",
"pm_score": 2,
"selected": true,
"text": "import datetime\n\nlista_ranking = [\n {'partido': {'codigo': 'AAA', 'fecha': datetime.date(2022, 11, 20),\n 'hora': '13:00hs', 'equipo_local': 'Catar',\n 'equipo_visitante': 'Ecuador', 'estado': 'Finalizado',\n 'goles_local': 0, 'goles_visitante': 1},\n 'usuario': {'cedula': '123', 'nombre': 'Gon',\n 'apellido': 'Henderson',\n 'fecha': '(2003, 3, 12)', 'puntaje': 5},\n 'goles_local': 1,\n 'goles_visitante': 0}, {\n 'partido': {'codigo': 'AAA',\n 'fecha': datetime.date(2022, 11, 20),\n 'hora': '13:00hs', 'equipo_local': 'Catar',\n 'equipo_visitante': 'Ecuador',\n 'estado': 'Finalizado',\n 'goles_local': 0, 'goles_visitante': 1},\n 'usuario': {'cedula': '1234', 'nombre': 'George',\n 'apellido': 'Stev', 'fecha': '(2003, 3, 12)',\n 'puntaje': 8}, 'goles_local': 0,\n 'goles_visitante': 1}]\nranking_high_to_low = sorted([(numeros['usuario']['puntaje'],\n numeros['usuario']['nombre'],\n numeros['usuario']['apellido']) for numeros in\n lista_ranking], reverse=True)\nfor info in ranking_high_to_low:\n print(f\"{' '.join(info[1:])} {info[0]}\")\n George Stev 8\nGon Henderson 5\n join import datetime\n\nlista_ranking = [\n {'partido': {'codigo': 'AAA', 'fecha': datetime.date(2022, 11, 20),\n 'hora': '13:00hs', 'equipo_local': 'Catar',\n 'equipo_visitante': 'Ecuador', 'estado': 'Finalizado',\n 'goles_local': 0, 'goles_visitante': 1},\n 'usuario': {'cedula': '123', 'nombre': 'Gon',\n 'apellido': 'Henderson',\n 'fecha': '(2003, 3, 12)', 'puntaje': 5},\n 'goles_local': 1,\n 'goles_visitante': 0},\n {'partido': {'codigo': 'AAA', 'fecha': datetime.date(2022, 11, 20),\n 'hora': '13:00hs', 'equipo_local': 'Catar',\n 'equipo_visitante': 'Ecuador', 'estado': 'Finalizado',\n 'goles_local': 0, 'goles_visitante': 1},\n 'usuario': {'cedula': '123', 'nombre': 'Gon',\n 'apellido': 'Henderson',\n 'fecha': '(2003, 3, 12)', 'puntaje': 5},\n 'goles_local': 1,\n 'goles_visitante': 0}\n , {\n 'partido': {'codigo': 'AAA',\n 'fecha': datetime.date(2022, 11, 20),\n 'hora': '13:00hs', 'equipo_local': 'Catar',\n 'equipo_visitante': 'Ecuador',\n 'estado': 'Finalizado',\n 'goles_local': 0, 'goles_visitante': 1},\n 'usuario': {'cedula': '1234', 'nombre': 'George',\n 'apellido': 'Stev', 'fecha': '(2003, 3, 12)',\n 'puntaje': 8}, 'goles_local': 0,\n 'goles_visitante': 1}]\nranking_high_to_low = [(numeros['usuario']['puntaje'],\n numeros['usuario']['nombre'],\n numeros['usuario']['apellido']) for numeros in\n lista_ranking]\n\nplayers = {}\nfor info in ranking_high_to_low:\n player_name = ' '.join(info[1:])\n players[player_name] = players.get(player_name, 0) + info[0]\n\nfor player, score in sorted(players.items(), key=lambda x: x[1], reverse=True):\n print(f\"{player} {score}\")\n Gon Henderson 10\nGeorge Stev 8\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74526223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10969942/"
] |
74,526,251
|
<p>I wanted to run different error handling with React Promise.
API 1 and 2 should have different error handlings.</p>
<ol>
<li>Execute APIs all at once to save time.</li>
<li>Run different error handling statements for each API as soon as possible, without waiting for the others.</li>
<li>Each API should continue even if one fails.</li>
</ol>
<p>How can this be done?</p>
<p><strong>Reference:</strong></p>
<p><a href="https://stackoverflow.com/questions/46241827/fetch-api-requesting-multiple-get-requests">Fetch API requesting multiple get requests</a></p>
<pre><code>Promise.all([
fetch(api1).then(value => value.json()),
fetch(api2).then(value => value.json())
])
.then((value) => {
console.log(value)
//json response
})
.catch((err) => {
console.log(err);
});
</code></pre>
|
[
{
"answer_id": 74526301,
"author": "gerrod",
"author_id": 127497,
"author_profile": "https://Stackoverflow.com/users/127497",
"pm_score": 2,
"selected": true,
"text": "Promise.all const fetchFromApi1 = async () => {\n try {\n const response = await fetch(api1);\n return response.json();\n\n } catch (err) {\n console.log('API 1 failed');\n \n // Throw a custom error\n throw {\n errorSource: 'API_CALL_1',\n message: 'API call 1 failed',\n };\n }\n};\n\nconst fetchFromApi2 = async () => {\n // ----- 8< -----\n};\n Promise.all const fetchAllTheThings = async () => {\n try {\n const [response1, response2] = await Promise.all([\n fetchFromApi1(),\n fetchFromApi2(),\n ]);\n\n } catch (err) {\n const { errorSource, message } = err;\n // do something....\n }\n};\n allSettled const fetchAllTheThings = async () => {\n const [result1, result2] = await Promise.allSettled([\n fetchFromApi1(),\n fetchFromApi2(),\n ]);\n\n if (result1.status === 'rejected') {\n // Sad for promise 1\n }\n\n if (result2.status === 'rejected') {\n // Sad for promise 2\n }\n};\n"
},
{
"answer_id": 74526824,
"author": "WestMountain",
"author_id": 9331978,
"author_profile": "https://Stackoverflow.com/users/9331978",
"pm_score": 0,
"selected": false,
"text": "const p1 = new Promise((res, rej) => {\n setTimeout(() => {\n res(\"p1 success\")\n }, 1000)\n})\nconst p2 = new Promise((res, rej) => {\n setTimeout(() => {\n res(\"p2 success\")\n }, 3000)\n})\nconst p3 = new Promise((res, rej) => {\n setTimeout(() => {\n rej(\"p3 failed\")\n }, 1000)\n})\nconst p4 = new Promise((res, rej) => {\n setTimeout(() => {\n rej(\"p4 failed\")\n }, 2000)\n})\n\nPromise.allSettled([p1, p2, p3, p4])\n .then(console.log)"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74526251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15435022/"
] |
74,526,263
|
<p>I have a problem with make dropdown menu and submenu with bootstrap on Vue 3 and bootstrap 5.2</p>
<p>There is my json menu data:</p>
<pre><code>[
{
"id": 1,
"name": "Menu 1",
"active": 1,
"created_at": "2022-11-20T03:27:47.000000Z",
"updated_at": "2022-11-20T03:27:47.000000Z",
"sub_menus": [
{
"id": 1,
"menuId": 1,
"name": "Sub Menu 1",
"active": 1,
"created_at": "2022-11-20T03:27:57.000000Z",
"updated_at": "2022-11-20T03:27:57.000000Z"
},
{
"id": 2,
"menuId": 1,
"name": "Sub Menu 2",
"active": 1,
"created_at": "2022-11-20T06:31:59.000000Z",
"updated_at": "2022-11-20T06:31:59.000000Z"
}
]
},
{
"id": 2,
"name": "Menu 2",
"active": 1,
"created_at": "2022-11-20T12:02:16.000000Z",
"updated_at": "2022-11-20T12:02:16.000000Z",
"sub_menus": []
}
]
</code></pre>
<p>And its should be:</p>
<pre><code>Menu 1
Sub Menu 1
Sub Menu 2
Menu 2
</code></pre>
<p>And then there is my html script:</p>
<pre><code> <div class="nav-link dropdown-toggle" v-for="(menu, menuIndex) in menus" :key="menuIndex" role="button"
id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
{{ menu.name }}
<div class="dropdown-menu" aria-labelledby="dropdownMenuLink">
<a class="dropdown-item" href="#" v-for="(item, index) in menu.sub_menus" :key="index">{{ item.name }}</a>
</div>
</div>
</code></pre>
<p>But the result is not what i expected, its showing like this:</p>
<pre><code>Menu 1
Sub Menu 1
Sub Menu 2
Menu 2
Sub Menu 1
Sub Menu 2
</code></pre>
<p>And its not correctly. Maybe the problem is with my bootstrap class. Is there any suggestion for this problem? Thanks before for the help.</p>
|
[
{
"answer_id": 74526301,
"author": "gerrod",
"author_id": 127497,
"author_profile": "https://Stackoverflow.com/users/127497",
"pm_score": 2,
"selected": true,
"text": "Promise.all const fetchFromApi1 = async () => {\n try {\n const response = await fetch(api1);\n return response.json();\n\n } catch (err) {\n console.log('API 1 failed');\n \n // Throw a custom error\n throw {\n errorSource: 'API_CALL_1',\n message: 'API call 1 failed',\n };\n }\n};\n\nconst fetchFromApi2 = async () => {\n // ----- 8< -----\n};\n Promise.all const fetchAllTheThings = async () => {\n try {\n const [response1, response2] = await Promise.all([\n fetchFromApi1(),\n fetchFromApi2(),\n ]);\n\n } catch (err) {\n const { errorSource, message } = err;\n // do something....\n }\n};\n allSettled const fetchAllTheThings = async () => {\n const [result1, result2] = await Promise.allSettled([\n fetchFromApi1(),\n fetchFromApi2(),\n ]);\n\n if (result1.status === 'rejected') {\n // Sad for promise 1\n }\n\n if (result2.status === 'rejected') {\n // Sad for promise 2\n }\n};\n"
},
{
"answer_id": 74526824,
"author": "WestMountain",
"author_id": 9331978,
"author_profile": "https://Stackoverflow.com/users/9331978",
"pm_score": 0,
"selected": false,
"text": "const p1 = new Promise((res, rej) => {\n setTimeout(() => {\n res(\"p1 success\")\n }, 1000)\n})\nconst p2 = new Promise((res, rej) => {\n setTimeout(() => {\n res(\"p2 success\")\n }, 3000)\n})\nconst p3 = new Promise((res, rej) => {\n setTimeout(() => {\n rej(\"p3 failed\")\n }, 1000)\n})\nconst p4 = new Promise((res, rej) => {\n setTimeout(() => {\n rej(\"p4 failed\")\n }, 2000)\n})\n\nPromise.allSettled([p1, p2, p3, p4])\n .then(console.log)"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74526263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8402887/"
] |
74,526,266
|
<p>If I want to construct a temporary valueset for testing, I can do something like this:</p>
<pre><code>SELECT * FROM (VALUES (97.99), (98.01), (99.00))
</code></pre>
<p>which will result in this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;"></th>
<th style="text-align: left;">COLUMN1</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">1</td>
<td style="text-align: left;">97.99</td>
</tr>
<tr>
<td style="text-align: left;">2</td>
<td style="text-align: left;">98.01</td>
</tr>
<tr>
<td style="text-align: left;">3</td>
<td style="text-align: left;">99.00</td>
</tr>
</tbody>
</table>
</div>
<p>However, if I want to construct a result set where one of the columns contains an <code>ARRAY</code>, like this:</p>
<pre><code>SELECT * FROM (VALUES (97.99, [14, 37]), (98.01, []), (99.00, [14]))
</code></pre>
<p>I would expect this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;"></th>
<th style="text-align: left;">COLUMN1</th>
<th style="text-align: left;">COLUMN2</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">1</td>
<td style="text-align: left;">97.99</td>
<td style="text-align: left;">[14, 37]</td>
</tr>
<tr>
<td style="text-align: left;">2</td>
<td style="text-align: left;">98.01</td>
<td style="text-align: left;">[]</td>
</tr>
<tr>
<td style="text-align: left;">3</td>
<td style="text-align: left;">99.00</td>
<td style="text-align: left;">[14]</td>
</tr>
</tbody>
</table>
</div>
<p>but I actually get the following error:</p>
<blockquote>
<p>Invalid expression [ARRAY_CONSTRUCT(14, 37)] in VALUES clause</p>
</blockquote>
<p>I don't see anything in the documentation for the <code>VALUES</code> clause that explains why this is invalid. What am I doing wrong here and how can I generate a result set with an ARRAY column?</p>
|
[
{
"answer_id": 74526301,
"author": "gerrod",
"author_id": 127497,
"author_profile": "https://Stackoverflow.com/users/127497",
"pm_score": 2,
"selected": true,
"text": "Promise.all const fetchFromApi1 = async () => {\n try {\n const response = await fetch(api1);\n return response.json();\n\n } catch (err) {\n console.log('API 1 failed');\n \n // Throw a custom error\n throw {\n errorSource: 'API_CALL_1',\n message: 'API call 1 failed',\n };\n }\n};\n\nconst fetchFromApi2 = async () => {\n // ----- 8< -----\n};\n Promise.all const fetchAllTheThings = async () => {\n try {\n const [response1, response2] = await Promise.all([\n fetchFromApi1(),\n fetchFromApi2(),\n ]);\n\n } catch (err) {\n const { errorSource, message } = err;\n // do something....\n }\n};\n allSettled const fetchAllTheThings = async () => {\n const [result1, result2] = await Promise.allSettled([\n fetchFromApi1(),\n fetchFromApi2(),\n ]);\n\n if (result1.status === 'rejected') {\n // Sad for promise 1\n }\n\n if (result2.status === 'rejected') {\n // Sad for promise 2\n }\n};\n"
},
{
"answer_id": 74526824,
"author": "WestMountain",
"author_id": 9331978,
"author_profile": "https://Stackoverflow.com/users/9331978",
"pm_score": 0,
"selected": false,
"text": "const p1 = new Promise((res, rej) => {\n setTimeout(() => {\n res(\"p1 success\")\n }, 1000)\n})\nconst p2 = new Promise((res, rej) => {\n setTimeout(() => {\n res(\"p2 success\")\n }, 3000)\n})\nconst p3 = new Promise((res, rej) => {\n setTimeout(() => {\n rej(\"p3 failed\")\n }, 1000)\n})\nconst p4 = new Promise((res, rej) => {\n setTimeout(() => {\n rej(\"p4 failed\")\n }, 2000)\n})\n\nPromise.allSettled([p1, p2, p3, p4])\n .then(console.log)"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74526266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3121975/"
] |
74,526,291
|
<p>I have React Router wrapping my root div but I can't seem to figure out how to handle a popup window when a link is clicked.</p>
<p>I know I can instead load a static HTML page in the public folder but I'd like it to be a .js file in src.</p>
<p>This is what I want:</p>
<pre><code>import { Link } from "react-router-dom";
import Test from './pages/test.js';
function Example() {
return (
<>
<Link onClick={() => window.open(<Test />, "Popup", "toolbar=no, location=no, statusbar=no, menubar=no, scrollbars=1, resizable=0, width=650, height=400, top=30")}>
Hello
</Link>
</>
);
}
export default Example;
</code></pre>
<p>This is the only thing that works and then I obviously lose the functionality of React (unless I'm looking at it wrong?) The URL path is to a directory in <code>public</code></p>
<pre><code>import { Link } from "react-router-dom";
import Test from './pages/test.js';
function Example() {
return (
<>
<Link onClick={() => window.open('/example', "Popup", "toolbar=no, location=no, statusbar=no, menubar=no, scrollbars=1, resizable=0, width=650, height=400, top=30")}>
Hello
</Link>
</>
);
}
export default Example;
</code></pre>
|
[
{
"answer_id": 74526465,
"author": "andres martinez",
"author_id": 13625491,
"author_profile": "https://Stackoverflow.com/users/13625491",
"pm_score": 0,
"selected": false,
"text": "onClick={() => {\n var myWindow = window.open(\n \"\",\n \"Popup\",\n \"toolbar=no, location=no, statusbar=no, menubar=no, scrollbars=1, resizable=0, width=650, height=400, top=30\"\n );\n myWindow && ReactDOM.render(<ReactElement color=\"error\" variant=\"contained\">this is a element of react</ReactElement>, myWindow.document.body);\n }}\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74526291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18305379/"
] |
74,526,310
|
<p>I have a react form that has several dropdowns and it was working, however, the WebAPI changed and now the data is being returned slightly different and now none of the dropdowns are populated.</p>
<p>The old JSON format was like:</p>
<pre><code> {
"data":
[{
"id" : 1,
"name" : "Michelle Smith",
},
{
"id" : 2,
"name" : "Jenn Arnold"
}
]
}
</code></pre>
<p>the drop down binding is:</p>
<pre><code> const [ admins, setAdmin] = useState([]);
useEffect(() => {
getAdmins();
},[]);
//calls a JS file that connects to the API using axios
const getAdmins = () => {
adminGroups.GetAllAdmins()
.then((response) => {
setAdmins(response.data.data)
}
}
return (
<select>
<option>...</option>
{admins.map(data => {
<option
value={admin.id}
>
{admins.name}
<option>
</select>
)
</code></pre>
<p>The new JSON format is:</p>
<pre><code>[{
"id" : 1,
"name" : "Michelle Smith",
},
{
"id" : 2,
"name" : "Jenn Arnold"
}]
</code></pre>
<p>There is no parent "data" tag in the new format, what would've caused the drop downs to stop binding with the new format? When the page loads, I can see the API being called (under the network tab) and if I go to the URL I can see data, just not in the React App. Is there another way I should be binding the dropdown?</p>
<p>[I'm fairly new to React and converting an Access app over to the web using React as the UI]</p>
|
[
{
"answer_id": 74526465,
"author": "andres martinez",
"author_id": 13625491,
"author_profile": "https://Stackoverflow.com/users/13625491",
"pm_score": 0,
"selected": false,
"text": "onClick={() => {\n var myWindow = window.open(\n \"\",\n \"Popup\",\n \"toolbar=no, location=no, statusbar=no, menubar=no, scrollbars=1, resizable=0, width=650, height=400, top=30\"\n );\n myWindow && ReactDOM.render(<ReactElement color=\"error\" variant=\"contained\">this is a element of react</ReactElement>, myWindow.document.body);\n }}\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74526310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8382717/"
] |
74,526,320
|
<p>i want to add button color but it didnt show up</p>
<p>here is the drawable
rounded_button.xml</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<shape android:shape="rectangle" xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#47D476"/>
<corners android:radius="15dp"/>
</shape>
</code></pre>
<p>and this the layout</p>
<pre><code><Button
android:id="@+id/buttonOKE"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:background="@drawable/rounded_button"
android:text="SUBMIT"
/>
</code></pre>
<p>how to set the colors it didnt change to green</p>
<p><a href="https://i.stack.imgur.com/KXft6.png" rel="nofollow noreferrer">color from the rounded_button.xml</a></p>
<p><a href="https://i.stack.imgur.com/TdauK.png" rel="nofollow noreferrer">the result </a></p>
<p>thank you.</p>
|
[
{
"answer_id": 74526498,
"author": "่ฑๆชๅผ",
"author_id": 18241066,
"author_profile": "https://Stackoverflow.com/users/18241066",
"pm_score": 0,
"selected": false,
"text": "app:backgroundTint=\"@null\"\n"
},
{
"answer_id": 74528432,
"author": "Kushal Prajapati",
"author_id": 14070467,
"author_profile": "https://Stackoverflow.com/users/14070467",
"pm_score": 0,
"selected": false,
"text": " <TextView\n android:id=\"@+id/tvDiscount\"\n style=\"@style/txt_white_small\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_gravity=\"start\n android:background=\"@drawable/discount_horizontal\"\n android:gravity=\"center\"\n android:paddingLeft=\"@dimen/_5sdp\"\n android:paddingRight=\"@dimen/_5sdp\"\n android:text=\"\" />\n\n\n"
},
{
"answer_id": 74528598,
"author": "TANIMUL ISLAM",
"author_id": 18262004,
"author_profile": "https://Stackoverflow.com/users/18262004",
"pm_score": 2,
"selected": true,
"text": " app:backgroundTint=\"@null\"\n <Button\n android:id=\"@+id/buttonOKE\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_margin=\"10dp\"\n android:text=\"SUBMIT\"\n app:backgroundTint=\"@null\"\n android:background=\"@drawable/rounded_button\"\n app:layout_constraintBottom_toBottomOf=\"parent\"\n app:layout_constraintEnd_toEndOf=\"parent\"\n app:layout_constraintStart_toStartOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\"\n />\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74526320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20308102/"
] |
74,526,345
|
<p>I was wondering why sympy won't solve the following problem:</p>
<pre><code>from sympy import *
ss = symbols('s', real = True)
a = symbols('a', real = True)
f = Function('f')
g = Function('g')
eq = Integral(a*g(ss) + f(ss),(ss,0,oo))
solve(eq, a)
</code></pre>
<p>The return is an empty solution list. I want to tell sympy enough stuff so that I get as a solution:</p>
<pre><code>-1*Integral(f(ss),(ss,0,oo))/Integral(g(ss),(ss,0,oo))
</code></pre>
<p>That is, its safe to assume integrals converge, are real-valued and non-zero.
Is there any other assumption/function I can use to get the desired output?
Thanks</p>
|
[
{
"answer_id": 74526675,
"author": "Alex P",
"author_id": 11554968,
"author_profile": "https://Stackoverflow.com/users/11554968",
"pm_score": 2,
"selected": true,
"text": "Integral(g(ss),(ss,0,oo)) Integral doit from sympy import *\n\nx = symbols('x', real = True)\na = symbols('a', real = True)\nf = Function('f')\n\neq = a+Integral(f(x), (x, 0, oo))\nprint('Eq.1', solve(eq, a))\n\neq2 = Integral(a+f(x), (x, 0, oo))\nprint('Eq.2', solve(eq2.doit(), a))\n\neq3 = Integral(a+f(x), (x, 0, 1))\nprint('Eq.3', solve(eq3.doit(), a))\n\neq4 = Integral(a+2, (x, 0, 3))\nprint('Eq.4', solve(eq4, a))\nprint('Eq.4', solve(eq4.doit(), a))\n Eq.1 [-Integral(f(x), (x, 0, oo))]\nEq.2 []\nEq.3 []\nEq.4 []\nEq.4 [-2]\n a doit expand from sympy import *\n\nx = symbols('x', real = True)\na = symbols('a', real = True)\nf = Function('f')\ng = Function('g')\n\neq5 = a+Integral(a+f(x), (x, 0, 1))\nprint('Eq.5', solve(eq5.expand().doit(), a))\n\neq6 = Integral(a+f(x), (x, 0, 1))\nprint('Eq.6', solve(eq6.expand().doit(), a))\n\neq7 = Integral(a*g(x)+f(x), (x, 0, oo))\nprint('Eq.7', solve(eq7.expand().doit(), a))\n Eq.5 [-Integral(f(x), (x, 0, 1))/2]\nEq.6 [-Integral(f(x), (x, 0, 1))]\nEq.7 [-Integral(f(x), (x, 0, oo))/Integral(g(x), (x, 0, oo))]\n oo"
},
{
"answer_id": 74531632,
"author": "Oscar Benjamin",
"author_id": 9450991,
"author_profile": "https://Stackoverflow.com/users/9450991",
"pm_score": 0,
"selected": false,
"text": "In [9]: eq\nOut[9]: \nโ \nโ \nโฎ (aโ
g(s) + f(s)) ds\nโก \n0 \n a a solve a In [10]: eq.expand()\nOut[10]: \nโ \nโ \nโฎ (aโ
g(s) + f(s)) ds\nโก \n0 \n\nIn [11]: eq.expand(force=True)\nOut[11]: \nโ โ \nโ โ \nโฎ aโ
g(s) ds + โฎ f(s) ds\nโก โก \n0 0 \n\nIn [12]: factor_terms(eq.expand(force=True))\nOut[12]: \n โ โ \n โ โ \naโ
โฎ g(s) ds + โฎ f(s) ds\n โก โก \n 0 0 \n\nIn [13]: solve(factor_terms(eq.expand(force=True)), a)\nOut[13]: \nโก โ โค\nโข โ โฅ\nโข-โฎ f(s) ds โฅ\nโข โก โฅ\nโข 0 โฅ\nโขโโโโโโโโโโโโฅ\nโข โ โฅ\nโข โ โฅ\nโข โฎ g(s) ds โฅ\nโข โก โฅ\nโฃ 0 โฆ\n force=True expand oo"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74526345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4207869/"
] |
74,526,464
|
<p>Given the sentence "I want to eat fish and I want to buy a car. Therefore, I have to make money."</p>
<p>I want to split the sentene by</p>
<p>['I want to eat fish', 'I want to buy a car", Therefore, 'I have to make money']</p>
<p>I am trying to split the sentence</p>
<pre><code>re.split('.|and', sentence)
</code></pre>
<p>However, it splits the sentence by '.', 'a', 'n', and 'd'.</p>
<p>How can I split the sentence by '.' and 'and'?</p>
|
[
{
"answer_id": 74526501,
"author": "Dan Nagle",
"author_id": 2202018,
"author_profile": "https://Stackoverflow.com/users/2202018",
"pm_score": 1,
"selected": false,
"text": ". import re\n\ns = \"I want to eat fish and I want to buy a car. Therefore, I have to make money.\"\n\nre.split('\\.|and', s)\n ['I want to eat fish ',\n ' I want to buy a car',\n ' Therefore, I have to make money',\n '']\n"
},
{
"answer_id": 74526526,
"author": "blhsing",
"author_id": 6890912,
"author_profile": "https://Stackoverflow.com/users/6890912",
"pm_score": 3,
"selected": true,
"text": ". re.split('\\s*(?:\\.|and)\\s*(?=\\S)', sentence)\n ['I want to eat fish', 'I want to buy a car', 'Therefore, I have to make money.']\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74526464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7229276/"
] |
74,526,492
|
<p>I tried to program a local notification by expo, following the code provide on:
<a href="https://docs.expo.dev/versions/latest/sdk/notifications/#getpermissionsasync-promisenotificationpermissionsstatus" rel="nofollow noreferrer">here - docs.expo.dev</a></p>
<p>The problem: the notification simple don't appear in my phone - IOS. When I click into the button, nothing happens.</p>
<p>My App.js file:</p>
<pre><code>import { StyleSheet, Button, View } from 'react-native';
import * as Notifications from 'expo-notifications';
Notifications.setNotificationHandler({
handleNotification: async () => {
return {
shouldPlaySound: false,
shouldSetBadge: false,
shouldShowAlert: true,
};
}
});
export default function App() {
function scheduleNotificationHandler() {
Notifications.scheduleNotificationAsync({
content: {
title: 'My first local notification',
body: 'This is the body of the notification.',
},
trigger: {
seconds: 5
}
});
}
return (
<View style={styles.container}>
<Button
title="Schedule Notification"
onPress={scheduleNotificationHandler}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
</code></pre>
<p>Could anybody help me? Thanks for your attention.</p>
<p>I think the problem can be in the permissions of my device.</p>
|
[
{
"answer_id": 74526501,
"author": "Dan Nagle",
"author_id": 2202018,
"author_profile": "https://Stackoverflow.com/users/2202018",
"pm_score": 1,
"selected": false,
"text": ". import re\n\ns = \"I want to eat fish and I want to buy a car. Therefore, I have to make money.\"\n\nre.split('\\.|and', s)\n ['I want to eat fish ',\n ' I want to buy a car',\n ' Therefore, I have to make money',\n '']\n"
},
{
"answer_id": 74526526,
"author": "blhsing",
"author_id": 6890912,
"author_profile": "https://Stackoverflow.com/users/6890912",
"pm_score": 3,
"selected": true,
"text": ". re.split('\\s*(?:\\.|and)\\s*(?=\\S)', sentence)\n ['I want to eat fish', 'I want to buy a car', 'Therefore, I have to make money.']\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74526492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19118458/"
] |
74,526,532
|
<p>I'm sorry if my Title seems kinda weird, English is not my first Language and I didn't know how to express myself correctly.</p>
<p>I have a list and I want to add a word every time after a particular word:
Example:</p>
<pre><code>list = ['add', 'add', 'ball', 'cup', 'add']
</code></pre>
<p>Expected result:</p>
<pre><code>list = ['add','Nice', 'add', 'Nice, 'ball', 'cup', 'add','Nice']
</code></pre>
<p>I tried including a:</p>
<pre><code>for word in list:
if 'add' in word:
list.insert(((list.index(word))+1,'Nice')
</code></pre>
<p>But my loop keeps adding only on the first 'add', and go eternal.</p>
<p>I tried doing something like this:</p>
<pre><code>for word in list:
if 'add' in word:
local = list.index(word) + 1
if list[local] == 'Nice':
pass
else:
list.insert(local,'Nice')
</code></pre>
<p>It stops the eternal loop, but the second 'add' doesn't get a 'Nice',<br />
I get a: <code>['add', 'Nice', 'add', 'ball', 'cup', 'add']</code></p>
<p>It looks like my "for word in list" only sees a singular 'add'.</p>
|
[
{
"answer_id": 74526566,
"author": "blhsing",
"author_id": 6890912,
"author_profile": "https://Stackoverflow.com/users/6890912",
"pm_score": 2,
"selected": true,
"text": "lst = ['add', 'add', 'ball', 'cup', 'add']\noutput = []\nfor word in lst:\n output.append(word)\n if word == 'add':\n output.append('Nice')\nprint(output)\n ['add', 'Nice', 'add', 'Nice', 'ball', 'cup', 'add', 'Nice']\n"
},
{
"answer_id": 74526663,
"author": "gahooa",
"author_id": 64004,
"author_profile": "https://Stackoverflow.com/users/64004",
"pm_score": 0,
"selected": false,
"text": "sum() words = ['add', 'add', 'ball', 'cup', 'add']\n\nsum(([v,'Nice'] if v == 'add' else [v] for v in words), [])\n ['add', 'Nice', 'add', 'Nice', 'ball', 'cup', 'add', 'Nice']\n itertools.chain()"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74526532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5764318/"
] |
74,526,554
|
<p>I have the following code snippet with me.</p>
<pre><code>public class SomeClass
{
private int[] items;
public unsafe T DoSomething<T>(delegate*<int[], T> abc)
{
return abc(items);
}
}
</code></pre>
<p>I want to pass <code>HowToDoSomething(int[] values)</code> to above the <code>Dosomething</code> method without using <code>Func</code>.</p>
<pre><code>class Program
{
static void Main(string[] args)
{
int[] myItems= { 1, 2, 3, 4};
SomeClass sc = new SomeClass(myItems);
//How to call DoSomething here with delegate*<int[], T>
//without using changing DoSomething signature with Func
}
public static int HowToDoSomething(int[] values)
{
return 1;
}
}
</code></pre>
<p>P.S. What does the asterisk symbol does in <code>public unsafe T DoSomething<T>(delegate*<int[], T> abc)</code>? Is it a type pattern?</p>
<p>UPDATE:</p>
<p>I tried below yet I am a stuck atm on figuring out how to pass the delegate to sc.DoSomething</p>
<pre><code>class Program
{
static void Main(string[] args)
{
int[] myItems= { 1, 2, 3, 4};
SomeClass sc = new SomeClass(myItems);
HowToDoSomethingDelegate hwtdsd = new HowToDoSomethingDelegate(HowToDoSomething);
//How to call DoSomething here with delegate*<int[], T>
//without using changing DoSomething signature with Func
}
public static int HowToDoSomething(int[] values)
{
return 1;
}
public delegate int HowToDoSomethingDelegate(int[] vs)
}
</code></pre>
|
[
{
"answer_id": 74526657,
"author": "Rivo R.",
"author_id": 18123471,
"author_profile": "https://Stackoverflow.com/users/18123471",
"pm_score": -1,
"selected": false,
"text": "Func public T DoSomething<T>(Func<int[],T> abc)\n{\n return abc(items);\n}\n SomeClass sc = new SomeClass();\nstring s = sc.DoSomething<string>((items) =>\n{\n return \"Hello\";\n});\n"
},
{
"answer_id": 74526773,
"author": "NineBerry",
"author_id": 101087,
"author_profile": "https://Stackoverflow.com/users/101087",
"pm_score": 3,
"selected": true,
"text": "public unsafe T DoSomething<T>(delegate*<int[], T> abc)\n{\n return abc(items);\n}\n abc int[] T unsafe DoSomething unsafe unsafe & private void button1_Click(object sender, EventArgs e)\n{\n SomeClass c = new SomeClass();\n unsafe\n {\n c.DoSomething<int>(&HowToDoSomething);\n }\n}\n\npublic static int HowToDoSomething(int[] values)\n{\n return 1;\n}\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74526554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4053100/"
] |
74,526,575
|
<p>I couldn't find the solution.
How to get date in <code>"Tuesday 22.11.2022"</code> format.</p>
<p>this is how i did it</p>
<pre><code> const date = new Date();
const day = date.getDate();
const month = date.getMonth() + 1;
const year = date.getFullYear();
const today = day + '.' + month + '.' + year;
const tomorrow = day + 1 + '.' + month + '.' + year;
</code></pre>
<p>Is there any way to get today's and tomorrow's date?</p>
|
[
{
"answer_id": 74526692,
"author": "WestMountain",
"author_id": 9331978,
"author_profile": "https://Stackoverflow.com/users/9331978",
"pm_score": -1,
"selected": false,
"text": "dateFns.format(new Date, \"DD.MM.YYYY dddd\")\n"
},
{
"answer_id": 74526781,
"author": "Paulo",
"author_id": 15649348,
"author_profile": "https://Stackoverflow.com/users/15649348",
"pm_score": 0,
"selected": false,
"text": "const options = {\n weekday: 'long',\n day: 'numeric',\n month: 'numeric',\n year: 'numeric',\n};\n\nconst date = new Date();\nvar date2 = new Date();\ndate2.setDate(date.getDate() + 1);\n\n\nconst today = date.toLocaleDateString(\n 'en-gb', options\n).split('/').join('.').replace(/,/g, '');\n\nconst tommorow = date2.toLocaleDateString(\n 'en-gb', options\n).split('/').join('.').replace(/,/g, '');\n\n\nconsole.log(today);\nconsole.log(tommorow); var today = moment().format('dddd DD.MM.YYYY');\nvar tomorrow = moment().add(1, 'days').format('dddd DD.MM.YYYY');\n\nconsole.log(today);\nconsole.log(tomorrow); <script src=\"https://momentjs.com/downloads/moment.min.js\"></script>"
},
{
"answer_id": 74526833,
"author": "Phil",
"author_id": 283366,
"author_profile": "https://Stackoverflow.com/users/283366",
"pm_score": 3,
"selected": true,
"text": "/ . const today = new Date();\nconst tomorrow = new Date(today);\ntomorrow.setDate(tomorrow.getDate() + 1);\n\nconst locale = \"tr\"; // set to `undefined` to use the browser default\n\n// Using \"en\" for the day name since you seem to want it in English\nconst dayFormatter = new Intl.DateTimeFormat(\"en\", { weekday: \"long\" });\nconst dateFormatter = new Intl.DateTimeFormat(locale, {\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n});\n\nconst formatDate = (date) =>\n `${dayFormatter.format(date)} ${dateFormatter.format(date)}`;\n\nconsole.log(\"today:\", formatDate(today));\nconsole.log(\"tomorrow:\", formatDate(tomorrow)); Date"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74526575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18004537/"
] |
74,526,576
|
<pre><code> if (test1 === 'hi' && test2 === 'bye' && test3 = 'joe' && test4 === 'sam') {
console.log("all 4 statements are true!!);
};
</code></pre>
<p>getting an r value error which im assuming is syntax. Could someone help me what would be the correct format/method to do this?</p>
|
[
{
"answer_id": 74526692,
"author": "WestMountain",
"author_id": 9331978,
"author_profile": "https://Stackoverflow.com/users/9331978",
"pm_score": -1,
"selected": false,
"text": "dateFns.format(new Date, \"DD.MM.YYYY dddd\")\n"
},
{
"answer_id": 74526781,
"author": "Paulo",
"author_id": 15649348,
"author_profile": "https://Stackoverflow.com/users/15649348",
"pm_score": 0,
"selected": false,
"text": "const options = {\n weekday: 'long',\n day: 'numeric',\n month: 'numeric',\n year: 'numeric',\n};\n\nconst date = new Date();\nvar date2 = new Date();\ndate2.setDate(date.getDate() + 1);\n\n\nconst today = date.toLocaleDateString(\n 'en-gb', options\n).split('/').join('.').replace(/,/g, '');\n\nconst tommorow = date2.toLocaleDateString(\n 'en-gb', options\n).split('/').join('.').replace(/,/g, '');\n\n\nconsole.log(today);\nconsole.log(tommorow); var today = moment().format('dddd DD.MM.YYYY');\nvar tomorrow = moment().add(1, 'days').format('dddd DD.MM.YYYY');\n\nconsole.log(today);\nconsole.log(tomorrow); <script src=\"https://momentjs.com/downloads/moment.min.js\"></script>"
},
{
"answer_id": 74526833,
"author": "Phil",
"author_id": 283366,
"author_profile": "https://Stackoverflow.com/users/283366",
"pm_score": 3,
"selected": true,
"text": "/ . const today = new Date();\nconst tomorrow = new Date(today);\ntomorrow.setDate(tomorrow.getDate() + 1);\n\nconst locale = \"tr\"; // set to `undefined` to use the browser default\n\n// Using \"en\" for the day name since you seem to want it in English\nconst dayFormatter = new Intl.DateTimeFormat(\"en\", { weekday: \"long\" });\nconst dateFormatter = new Intl.DateTimeFormat(locale, {\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n});\n\nconst formatDate = (date) =>\n `${dayFormatter.format(date)} ${dateFormatter.format(date)}`;\n\nconsole.log(\"today:\", formatDate(today));\nconsole.log(\"tomorrow:\", formatDate(tomorrow)); Date"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74526576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19102374/"
] |
74,526,585
|
<p>Learning command arguments in Java, trying to print only names in a string of names and ages.</p>
<p>So instead of Bill 32 Mary 42 Bob 29 Lisa 20</p>
<p>I should get Bill Mary Bob Lisa</p>
<pre><code>class CmdArgsNameAgePairs
{
public static void main(String[] args)
{
java CmdArgs Bill 32 Mary 42 Bob 29 Lisa 20
//Bill is 32
//Mary is 42
int i=0;//initial index
while (i <= args.length-1)
{
System.out.println(args[i]);
i++;
}
}
}
// System.out.println(args[0]);
// System.out.println(args[2]);
// System.out.println(args[4]);
// System.out.println(args[6]);
</code></pre>
|
[
{
"answer_id": 74526635,
"author": "DevilsHnd",
"author_id": 4725875,
"author_profile": "https://Stackoverflow.com/users/4725875",
"pm_score": 1,
"selected": false,
"text": "int i = 0;\nwhile (i < args.length) {\n if (i % 2 == 0) {\n System.out.println(args[i]);\n }\n i++; \n}\n"
},
{
"answer_id": 74526904,
"author": "Jose",
"author_id": 3811075,
"author_profile": "https://Stackoverflow.com/users/3811075",
"pm_score": 0,
"selected": false,
"text": "int i=0;//initial index\nwhile (i <= args.length-1) {\n if(args[i].matches (\"[a-zA-Z]+\")){\n System.out.println(args[i]);\n }\n i++;\n}\n"
},
{
"answer_id": 74527275,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "for (int i = 0; i < args.length; i += 2)\n System.out.println(args[i]);\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74526585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11981085/"
] |
74,526,609
|
<p>Example URL: mywebsite.com/wp-admin/post.php?post=1234&action=edit</p>
<p>I have found hooks that fire when a post is created/edited/status changed, but nothing that works for just viewing a post.</p>
<p>I need to check some meta data and update it before the post is displayed to the user</p>
<p>I have tried several hooks already but none let me edit post meta at the correct time (when viewing a post)</p>
<p>Solution: Adding this to admin_init allowed me to update post meta for a given post after the post data was loaded</p>
<pre class="lang-php prettyprint-override"><code>if (isset($_GET['post']) && (isset($_GET['action']) && $_GET['action'] == 'edit'))
{
$post = get_post($_GET['post']);
if ($post->post_type == 'program')
{
// do stuff
}
}
</code></pre>
|
[
{
"answer_id": 74526635,
"author": "DevilsHnd",
"author_id": 4725875,
"author_profile": "https://Stackoverflow.com/users/4725875",
"pm_score": 1,
"selected": false,
"text": "int i = 0;\nwhile (i < args.length) {\n if (i % 2 == 0) {\n System.out.println(args[i]);\n }\n i++; \n}\n"
},
{
"answer_id": 74526904,
"author": "Jose",
"author_id": 3811075,
"author_profile": "https://Stackoverflow.com/users/3811075",
"pm_score": 0,
"selected": false,
"text": "int i=0;//initial index\nwhile (i <= args.length-1) {\n if(args[i].matches (\"[a-zA-Z]+\")){\n System.out.println(args[i]);\n }\n i++;\n}\n"
},
{
"answer_id": 74527275,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "for (int i = 0; i < args.length; i += 2)\n System.out.println(args[i]);\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74526609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14479332/"
] |
74,526,812
|
<p>So, let's just say I have a field for items at a store. I have a field called price and a field called color. If I want to display the top values for each price, I can do that easily by searching for "<strong>top price</strong>". Suppose I want to filter and make a table by showing all of the top values for the blue items only. The percentages calculated by the top command still include all possible colors of items, I just only want the blue items to show up in the table. Hope that makes sense.</p>
|
[
{
"answer_id": 74535396,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 0,
"selected": false,
"text": "index=ndx sourcetype=srctp rating=\"bad\" color=\"blue\" price=*\n| top price by color rating\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74526812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5848304/"
] |
74,526,831
|
<p>I was a developing a flutter app when I suddenly came across an error that I simply can't solve. I have a few variables declared in between the two classes of a stateful widget, and when I use <code>setState()</code> to update their values from within the <code><state></code> class, the app lags massively, and when more UI elements are added, the app will crash. I have never run into this issue before, and I have used the same principle to make it easier to access variables outside of the file.</p>
<p>This has happened on Flutter 3.6 beta, 3.3.8, and 3.0.0, meaning it's not a Flutter version issue. It doesn't matter whether the variables are null or not, it doesn't matter whether the variables are called outside of <code>initState</code> or after a delay. The app loads this page directly from <code>main.dart</code>, meaning it's also not because of any prior discrepancy.<br></p>
<p>I have reduced the error into a single file. Create a new project, copy the below code, and replace with the existing code in <code>main.dart</code>.</p>
<pre><code>import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const ErrorTest(),
);
}
}
class ErrorTest extends StatefulWidget {
const ErrorTest({super.key});
@override
State<ErrorTest> createState() => _ErrorTestState();
}
int? points;
String? firstName;
String? lastName;
String? email;
String? profilePicture;
int? timestamp;
String? date;
String? time;
String? institution;
String? address;
class _ErrorTestState extends State<ErrorTest> {
@override
void initState() {
setState(() {
firstName = "johny";
lastName = "johny";
email = "eeaeaa";
profilePicture = "a url";
timestamp = 123456789;
date = "2021-09-09";
time = "09:09:09";
institution = "123456789";
address = "123456789";
points = 123456789;
});
super.initState();
}
@override
Widget build(BuildContext context) {
return Text(
firstName.toString(),
);
}
}
</code></pre>
<p>Error log<br></p>
<pre><code>Launching lib\main.dart on sdk gphone64 x86 64 in debug mode...
โ Built build\app\outputs\flutter-apk\app-debug.apk.
Connecting to VM Service at ws://127.0.0.1:54124/Kq8WOPDGOY8=/ws
I/scudo ( 5917): Stats: SizeClassAllocator64: 266M mapped (0M rss) in 322652 allocations; remains 269165
I/scudo ( 5917): 00 ( 64): mapped: 256K popped: 2171 pushed: 1950 inuse: 221 total: 728 rss: 0K releases: 0 last released: 0K region: 0x7dc6b6ce2000 (0x7dc6b6cd7000)
I/scudo ( 5917): 01 ( 32): mapped: 256K popped: 4498 pushed: 1950 inuse: 2548 total: 2548 rss: 0K releases: 0 last released: 0K region: 0x7dc6c6ce3000 (0x7dc6c6cd7000)
I/scudo ( 5917): 02 ( 48): mapped: 512K popped: 16055 pushed: 8268 inuse: 7787 total: 7800 rss: 0K releases: 0 last released: 0K region: 0x7dc6d6ce7000 (0x7dc6d6cd7000)
I/scudo ( 5917): 03 ( 64): mapped: 512K popped: 8412 pushed: 2132 inuse: 6280 total: 6332 rss: 0K releases: 0 last released: 0K region: 0x7dc6e6cdf000 (0x7dc6e6cd7000)
I/scudo ( 5917): 04 ( 80): mapped: 256K popped: 4771 pushed: 2444 inuse: 2327 total: 2444 rss: 0K releases: 0 last released: 0K region: 0x7dc6f6ce1000 (0x7dc6f6cd7000)
I/scudo ( 5917): 05 ( 96): mapped: 256K popped: 1079 pushed: 286 inuse: 793 total: 832 rss: 0K releases: 0 last released: 0K region: 0x7dc706ce7000 (0x7dc706cd7000)
I/scudo ( 5917): 06 ( 112): mapped: 256K popped: 1625 pushed: 1313 inuse: 312 total: 728 rss: 0K releases: 0 last released: 0K region: 0x7dc716ce2000 (0x7dc716cd7000)
I/scudo ( 5917): 07 ( 144): mapped: 256K popped: 1989 pushed: 650 inuse: 1339 total: 1352 rss: 0K releases: 0 last released: 0K region: 0x7dc726cdd000 (0x7dc726cd7000)
I/scudo ( 5917): 08 ( 176): mapped: 512K popped: 2711 pushed: 1443 inuse: 1268 total: 1853 rss: 0K releases: 0 last released: 0K region: 0x7dc736ce0000 (0x7dc736cd7000)
I/scudo ( 5917): 09 ( 192): mapped: 256K popped: 169 pushed: 13 inuse: 156 total: 156 rss: 0K releases: 0 last released: 0K region: 0x7dc746cdf000 (0x7dc746cd7000)
I/scudo ( 5917): 10 ( 224): mapped: 512K popped: 1365 pushed: 26 inuse: 1339 total: 1378 rss: 0K releases: 0 last released: 0K region: 0x7dc756ce6000 (0x7dc756cd7000)
I/scudo ( 5917): 11 ( 288): mapped: 256K popped: 650 pushed: 26 inuse: 624 total: 624 rss: 0K releases: 0 last released: 0K region: 0x7dc766ce2000 (0x7dc766cd7000)
I/scudo ( 5917): 12 ( 352): mapped: 256K popped: 1105 pushed: 949 inuse: 156 total: 728 rss: 0K releases: 6 last released: 124K region: 0x7dc776ce0000 (0x7dc776cd7000)
I/scudo ( 5917): 13 ( 448): mapped: 256K popped: 364 pushed: 91 inuse: 273 total: 312 rss: 0K releases: 1 last released: 4K region: 0x7dc786cdd000 (0x7dc786cd7000)
I/scudo ( 5917): 14 ( 592): mapped: 256K popped: 507 pushed: 247 inuse: 260 total: 416 rss: 0K releases: 4 last released: 8K region: 0x7dc796cd8000 (0x7dc796cd7000)
I/scudo ( 5917): 15 ( 800): mapped: 256K popped: 90 pushed: 0 inuse: 90 total: 120 rss: 0K releases: 0 last released: 0K region: 0x7dc7a6cde000 (0x7dc7a6cd7000)
I/scudo ( 5917): F 16 ( 1104): mapped: 261888K popped: 274165 pushed: 31255 inuse: 242910 total: 242910 rss: 0K releases: 31 last released: 3396K region: 0x7dc7b6cd9000 (0x7dc7b6cd7000)
I/scudo ( 5917): 17 ( 1648): mapped: 256K popped: 60 pushed: 4 inuse: 56 total: 64 rss: 0K releases: 0 last released: 0K region: 0x7dc7c6ce7000 (0x7dc7c6cd7000)
I/scudo ( 5917): 18 ( 2096): mapped: 256K popped: 78 pushed: 24 inuse: 54 total: 60 rss: 0K releases: 2 last released: 8K region: 0x7dc7d6ce1000 (0x7dc7d6cd7000)
I/scudo ( 5917): 19 ( 2576): mapped: 256K popped: 96 pushed: 0 inuse: 96 total: 96 rss: 0K releases: 0 last released: 0K region: 0x7dc7e6cde000 (0x7dc7e6cd7000)
I/scudo ( 5917): 20 ( 3120): mapped: 256K popped: 36 pushed: 2 inuse: 34 total: 40 rss: 0K releases: 1 last released: 8K region: 0x7dc7f6ce3000 (0x7dc7f6cd7000)
I/scudo ( 5917): 21 ( 4112): mapped: 512K popped: 224 pushed: 161 inuse: 63 total: 67 rss: 0K releases: 4 last released: 4K region: 0x7dc806cdf000 (0x7dc806cd7000)
I/scudo ( 5917): 22 ( 4624): mapped: 256K popped: 5 pushed: 2 inuse: 3 total: 8 rss: 0K releases: 2 last released: 20K region: 0x7dc816ce3000 (0x7dc816cd7000)
I/scudo ( 5917): 23 ( 7120): mapped: 512K popped: 99 pushed: 48 inuse: 51 total: 56 rss: 0K releases: 32 last released: 24K region: 0x7dc826ce3000 (0x7dc826cd7000)
I/scudo ( 5917): 24 ( 8720): mapped: 256K popped: 27 pushed: 0 inuse: 27 total: 28 rss: 0K releases: 0 last released: 0K region: 0x7dc836cdc000 (0x7dc836cd7000)
I/scudo ( 5917): 25 ( 11664): mapped: 256K popped: 22 pushed: 2 inuse: 20 total: 22 rss: 0K releases: 1 last released: 8K region: 0x7dc846cdd000 (0x7dc846cd7000)
I/scudo ( 5917): 26 ( 14224): mapped: 512K popped: 24 pushed: 2 inuse: 22 total: 26 rss: 0K releases: 1 last released: 12K region: 0x7dc856ce7000 (0x7dc856cd7000)
I/scudo ( 5917): 27 ( 16400): mapped: 256K popped: 16 pushed: 1 inuse: 15 total: 15 rss: 0K releases: 2 last released: 28K region: 0x7dc866cdc000 (0x7dc866cd7000)
I/scudo ( 5917): 28 ( 18448): mapped: 256K popped: 5 pushed: 0 inuse: 5 total: 8 rss: 0K releases: 0 last released: 0K region: 0x7dc876cde000 (0x7dc876cd7000)
I/scudo ( 5917): 29 ( 23056): mapped: 256K popped: 9 pushed: 1 inuse: 8 total: 8 rss: 0K releases: 3 last released: 84K region: 0x7dc886ce0000 (0x7dc886cd7000)
I/scudo ( 5917): 30 ( 29456): mapped: 512K popped: 13 pushed: 4 inuse: 9 total: 12 rss: 0K releases: 2 last released: 24K region: 0x7dc896ce4000 (0x7dc896cd7000)
I/scudo ( 5917): 31 ( 33296): mapped: 256K popped: 197 pushed: 192 inuse: 5 total: 7 rss: 0K releases: 5 last released: 28K region: 0x7dc8a6cdd000 (0x7dc8a6cd7000)
I/scudo ( 5917): 32 ( 65552): mapped: 1024K popped: 15 pushed: 1 inuse: 14 total: 15 rss: 0K releases: 1 last released: 60K region: 0x7dc8b6ce5000 (0x7dc8b6cd7000)
I/scudo ( 5917): Scudo OOM: The process has exhausted 256M for size class 1104.
E/SurfaceSyncer( 5917): Failed to find sync for id=0
W/Parcel ( 5917): Expecting binder but got null!
Reloaded 1 of 594 libraries in 597ms (compile: 55 ms, reload: 129 ms, reassemble: 155 ms).
D/EGL_emulation( 5917): app_time_stats: avg=8695.38ms min=53.84ms max=25809.32ms count=3
Reloaded 1 of 594 libraries in 2,177ms (compile: 18 ms, reload: 126 ms, reassemble: 1910 ms).
D/EGL_emulation( 5917): app_time_stats: avg=18633.52ms min=18633.52ms max=18633.52ms count=1
Lost connection to device.
Exited (sigterm)
</code></pre>
|
[
{
"answer_id": 74535396,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 0,
"selected": false,
"text": "index=ndx sourcetype=srctp rating=\"bad\" color=\"blue\" price=*\n| top price by color rating\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74526831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16727709/"
] |
74,526,841
|
<p>I am trying to create a boxplot but only have two values per factor, which I want to use as a starting and ending point for the boxplot bars.</p>
<p>I have a data frame (df) that looks like this:</p>
<pre><code> ID **spp** **lrr** Est SE
1 25 species 1 -1.029 -0.423814246776361 0.309105763160605
2 25 species 1 0.1820 -0.423814246776361 0.309105763160605
5 24 species 2 -3.694 -1.67397643357167 1.03077640640442
6 24 species 2 0.3463 -1.67397643357167 1.03077640640442
7 21 species 3 0.5181 2.484906649788 1.4142135623731
8 21 species 3 4.4516 2.484906649788 1.4142135623731
</code></pre>
<p>I need a bar per species (<strong>spp</strong>) using the values in <strong>lrr</strong>. For example, I expect the bar from species 1 to range from -1.029 to 0.1820, the bar from species 2 to range from -3.694 to 0.3463 and so on.</p>
<p>I tried using the following code:</p>
<pre><code>ggplot(df) +
aes(x = lrr, y = spp) +
geom_boxplot() +
theme_minimal()
</code></pre>
<p>However, instead of creating a single bar per species, it creates two separate points. I have also tried to rearrange the data by having two lrr columns (one for the starting point and one for the endpoint):</p>
<pre><code> ID **spp** **lrr1** **lrr2** Est SE
1 25 species 1 -1.029 0.1820 -0.423814246776361 0.309105763160605
5 24 species 2 -3.694 0.3463 -1.67397643357167 1.03077640640442
7 21 species 3 0.5181 4.4516 2.484906649788 1.4142135623731
</code></pre>
<p>However, I still do not know how to force bars into a starting and ending point. Any help is appreciated.</p>
|
[
{
"answer_id": 74527414,
"author": "neilfws",
"author_id": 89482,
"author_profile": "https://Stackoverflow.com/users/89482",
"pm_score": 0,
"selected": false,
"text": "geom_crossbar library(dplyr)\nlibrary(ggplot2)\nlibrary(scales)\n\ndf1 %>% \n group_by(spp) %>% \n mutate(upper = max(lrr), \n lower = min(lrr)) %>% \n ungroup() %>% \n ggplot(aes(spp, lrr)) + \n geom_crossbar(aes(ymin = lower, \n ymax = upper), \n fatten = 1,\n width = 0.5) + \n scale_y_continuous(breaks = pretty_breaks())\n df1 <- structure(list(ID = c(25L, 25L, 24L, 24L, 21L, 21L), spp = c(\"species 1\", \n\"species 1\", \"species 2\", \"species 2\", \"species 3\", \"species 3\"\n), lrr = c(-1.029, 0.182, -3.694, 0.3463, 0.5181, 4.4516), Est = c(-0.423814246776361, \n-0.423814246776361, -1.67397643357167, -1.67397643357167, 2.484906649788, \n2.484906649788), SE = c(0.309105763160605, 0.309105763160605, \n1.03077640640442, 1.03077640640442, 1.4142135623731, 1.4142135623731\n)), class = \"data.frame\", row.names = c(\"1\", \"2\", \"5\", \"6\", \"7\", \n\"8\"))\n"
},
{
"answer_id": 74527439,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 1,
"selected": false,
"text": "stat = \"identity\" geom_boxplot() library(ggplot2)\n\nggplot(df_wide) +\n geom_boxplot(\n aes(\n y = spp, \n xmin = lrr1, xlower = lrr1, \n xupper = lrr2, xmax = lrr2, \n xmiddle = (lrr1 + lrr2)/2\n ),\n stat = \"identity\"\n )\n geom = \"bar\" stat_summary() ggplot(df, aes(lrr, spp)) +\n stat_summary(\n fun.min = min, \n fun = median, \n fun.max = max, \n geom = \"bar\", \n color = \"black\", \n fill = \"white\"\n )\n\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74526841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17187761/"
] |
74,526,849
|
<p>I have a Blazor service which accepts any draggable object, boxed as <code>object</code>. It could be a dragged user, or a classroom, or a scheduled item or almost anything else I might dream up later.</p>
<p>When the draggable is dropped into any component which supports dropping, the component needs to check if it's the right kind of object. For example, the StudentList.razor component will only accept drops if they are <code>IdentityUser</code> or the duple <code>(IdentityUser, string)</code> where the string might be a role name or some other arbitrary info (TBD later):</p>
<pre><code> <div class="class-students-drop" @ondrop="_=>HandleStudentDrop()">
. . .
</div>
@code {
async Task HandleStudentDrop()
{
if (DM.GetItem() is IdentityUser Person)
{
// Do generic user thing (works fine)
}
if (DM.GetItem() is (IdentityUser person,string role) RolePerson)
{
// Do thing based on specified role
// Error (active) CS1061 'object' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'object' could be found
}
}
}
</code></pre>
<p><strong>I can pattern-check a class instance like <code>IdentityUser</code>, but I can't figure out how to check if the boxed object fits a particular duple form.</strong></p>
<p><strong>My question: what's the right syntax (if any) to check the signature of a duple using the 'is' keyword?</strong></p>
<p>I've seen examples with pattern-matching duples with values using <code>switch</code>, but I really just want to check if the boxed object is an `(IdentityUser, string) duple.</p>
<p>My references:</p>
<p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/functional/pattern-matching" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/functional/pattern-matching</a>
<a href="https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/functional/deconstruct" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/functional/deconstruct</a></p>
|
[
{
"answer_id": 74527414,
"author": "neilfws",
"author_id": 89482,
"author_profile": "https://Stackoverflow.com/users/89482",
"pm_score": 0,
"selected": false,
"text": "geom_crossbar library(dplyr)\nlibrary(ggplot2)\nlibrary(scales)\n\ndf1 %>% \n group_by(spp) %>% \n mutate(upper = max(lrr), \n lower = min(lrr)) %>% \n ungroup() %>% \n ggplot(aes(spp, lrr)) + \n geom_crossbar(aes(ymin = lower, \n ymax = upper), \n fatten = 1,\n width = 0.5) + \n scale_y_continuous(breaks = pretty_breaks())\n df1 <- structure(list(ID = c(25L, 25L, 24L, 24L, 21L, 21L), spp = c(\"species 1\", \n\"species 1\", \"species 2\", \"species 2\", \"species 3\", \"species 3\"\n), lrr = c(-1.029, 0.182, -3.694, 0.3463, 0.5181, 4.4516), Est = c(-0.423814246776361, \n-0.423814246776361, -1.67397643357167, -1.67397643357167, 2.484906649788, \n2.484906649788), SE = c(0.309105763160605, 0.309105763160605, \n1.03077640640442, 1.03077640640442, 1.4142135623731, 1.4142135623731\n)), class = \"data.frame\", row.names = c(\"1\", \"2\", \"5\", \"6\", \"7\", \n\"8\"))\n"
},
{
"answer_id": 74527439,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 1,
"selected": false,
"text": "stat = \"identity\" geom_boxplot() library(ggplot2)\n\nggplot(df_wide) +\n geom_boxplot(\n aes(\n y = spp, \n xmin = lrr1, xlower = lrr1, \n xupper = lrr2, xmax = lrr2, \n xmiddle = (lrr1 + lrr2)/2\n ),\n stat = \"identity\"\n )\n geom = \"bar\" stat_summary() ggplot(df, aes(lrr, spp)) +\n stat_summary(\n fun.min = min, \n fun = median, \n fun.max = max, \n geom = \"bar\", \n color = \"black\", \n fill = \"white\"\n )\n\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74526849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3433178/"
] |
74,526,866
|
<p><a href="https://i.stack.imgur.com/0rj83.png" rel="nofollow noreferrer">enter image description here</a>
<a href="https://i.stack.imgur.com/sFKiK.png" rel="nofollow noreferrer">enter image description here</a>
I think is same array type, but, Javascript doesn't import data to second type 'proj_name'.</p>
<p>I use axios to fetching data</p>
<p>This is my axios request tsx file</p>
<pre><code>import axios,{ AxiosRequestConfig } from 'axios';
import { Projects , Tree } from './PmHomeMenuDataTypes';
const axios_config: AxiosRequestConfig = {
method: "get",
baseURL: "http://localhost:8000/",
url: "service/projects/all",
responseType: "json",
}
export const getAllProjects = () => {
const menulist: Tree = [];
axios(axios_config)
.then((response) => {
response.data.map((item: Projects) => {
menulist.push(item);
})
});
console.log(menulist);
return menulist;
}
</code></pre>
<p>I use to fetch data this tsx file</p>
<pre><code>import PmHomeTreeComponent from './PmHomeTreeComponent';
import { getAllProjects } from './PmHomeMenuDataGet';
const PmHomeTreeMenu = () => {
return <PmHomeTreeComponent menuData={getAllProjects()} />
}
export default PmHomeTreeMenu;
</code></pre>
<p>I don't know what is a problem</p>
|
[
{
"answer_id": 74527414,
"author": "neilfws",
"author_id": 89482,
"author_profile": "https://Stackoverflow.com/users/89482",
"pm_score": 0,
"selected": false,
"text": "geom_crossbar library(dplyr)\nlibrary(ggplot2)\nlibrary(scales)\n\ndf1 %>% \n group_by(spp) %>% \n mutate(upper = max(lrr), \n lower = min(lrr)) %>% \n ungroup() %>% \n ggplot(aes(spp, lrr)) + \n geom_crossbar(aes(ymin = lower, \n ymax = upper), \n fatten = 1,\n width = 0.5) + \n scale_y_continuous(breaks = pretty_breaks())\n df1 <- structure(list(ID = c(25L, 25L, 24L, 24L, 21L, 21L), spp = c(\"species 1\", \n\"species 1\", \"species 2\", \"species 2\", \"species 3\", \"species 3\"\n), lrr = c(-1.029, 0.182, -3.694, 0.3463, 0.5181, 4.4516), Est = c(-0.423814246776361, \n-0.423814246776361, -1.67397643357167, -1.67397643357167, 2.484906649788, \n2.484906649788), SE = c(0.309105763160605, 0.309105763160605, \n1.03077640640442, 1.03077640640442, 1.4142135623731, 1.4142135623731\n)), class = \"data.frame\", row.names = c(\"1\", \"2\", \"5\", \"6\", \"7\", \n\"8\"))\n"
},
{
"answer_id": 74527439,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 1,
"selected": false,
"text": "stat = \"identity\" geom_boxplot() library(ggplot2)\n\nggplot(df_wide) +\n geom_boxplot(\n aes(\n y = spp, \n xmin = lrr1, xlower = lrr1, \n xupper = lrr2, xmax = lrr2, \n xmiddle = (lrr1 + lrr2)/2\n ),\n stat = \"identity\"\n )\n geom = \"bar\" stat_summary() ggplot(df, aes(lrr, spp)) +\n stat_summary(\n fun.min = min, \n fun = median, \n fun.max = max, \n geom = \"bar\", \n color = \"black\", \n fill = \"white\"\n )\n\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74526866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20032012/"
] |
74,526,881
|
<p>The Stockfish chess engine needs to store, for its evaluation, both an endgame score and a middlegame score.</p>
<p>Instead of storing them separately, it packs them into one <code>int</code>. The middlegame score is stored in the lower 16 bits. The endgame score is stored in the higher 16 bits, as-is if the middlegame score is positive or minus one if it is negative.</p>
<p>This has the advantage that operations (addition, subtraction, negation and multiplication) can be done for both numbers in parallel.</p>
<p><a href="https://github.com/official-stockfish/Stockfish/blob/d8f3209fb4053bec406645e6df0f8a4d71f5a749/src/types.h#L281-L364" rel="nofollow noreferrer">Here is the code:</a></p>
<pre class="lang-cpp prettyprint-override"><code>/// Score enum stores a middlegame and an endgame value in a single integer (enum).
/// The least significant 16 bits are used to store the middlegame value and the
/// upper 16 bits are used to store the endgame value. We have to take care to
/// avoid left-shifting a signed int to avoid undefined behavior.
enum Score : int { SCORE_ZERO };
constexpr Score make_score(int mg, int eg) {
return Score((int)((unsigned int)eg << 16) + mg);
}
/// Extracting the signed lower and upper 16 bits is not so trivial because
/// according to the standard a simple cast to short is implementation defined
/// and so is a right shift of a signed integer.
inline Value eg_value(Score s) {
union { uint16_t u; int16_t s; } eg = { uint16_t(unsigned(s + 0x8000) >> 16) };
return Value(eg.s);
}
inline Value mg_value(Score s) {
union { uint16_t u; int16_t s; } mg = { uint16_t(unsigned(s)) };
return Value(mg.s);
}
#define ENABLE_BASE_OPERATORS_ON(T) \
constexpr T operator+(T d1, int d2) { return T(int(d1) + d2); } \
constexpr T operator-(T d1, int d2) { return T(int(d1) - d2); } \
constexpr T operator-(T d) { return T(-int(d)); } \
inline T& operator+=(T& d1, int d2) { return d1 = d1 + d2; } \
inline T& operator-=(T& d1, int d2) { return d1 = d1 - d2; }
ENABLE_BASE_OPERATORS_ON(Score)
/// Only declared but not defined. We don't want to multiply two scores due to
/// a very high risk of overflow. So user should explicitly convert to integer.
Score operator*(Score, Score) = delete;
/// Division of a Score must be handled separately for each term
inline Score operator/(Score s, int i) {
return make_score(mg_value(s) / i, eg_value(s) / i);
}
/// Multiplication of a Score by an integer. We check for overflow in debug mode.
inline Score operator*(Score s, int i) {
Score result = Score(int(s) * i);
assert(eg_value(result) == (i * eg_value(s)));
assert(mg_value(result) == (i * mg_value(s)));
assert((i == 0) || (result / i) == s);
return result;
}
</code></pre>
<p>I understand how addition, subtraction and negation work, but what I have trouble understanding is multiplication. How does multiplying the integer multiplies both the endgame and the middlegame scores together correctly?</p>
|
[
{
"answer_id": 74526932,
"author": "Jeffrey",
"author_id": 4474230,
"author_profile": "https://Stackoverflow.com/users/4474230",
"pm_score": 2,
"selected": false,
"text": "23 31 230031 69 93 230031 * 3 690093"
},
{
"answer_id": 74527051,
"author": "Ranoiaetep",
"author_id": 12861639,
"author_profile": "https://Stackoverflow.com/users/12861639",
"pm_score": 1,
"selected": false,
"text": "mg = -10 ed = 3 mg = | 1111 1111 1111 0110\ned = 0000 0000 0000 0011 | \n-------------------------+--------------------\n 0000 0000 0000 0011 | 1111 1111 1111 0110\n make_score Score((int)((unsigned int)eg << 16) + mg)\n int 1111 1111 1111 1111 | 1111 1111 1111 0110\n + 0000 0000 0000 0011 | 0000 0000 0000 0000\n-------------------------+--------------------\n (1) 0000 0000 0000 0010 | 1111 1111 1111 0110\n ^\n this bit is different\n 0000 0000 0110 1111 | 0000 0000 0000 0000\n - 0000 0000 0000 0000 | 0000 0001 0111 0010\n-------------------------+--------------------\n 0 0000 0000 0110 1110 | 1111 1110 1000 1110\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74526881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7884305/"
] |
74,526,925
|
<p>So I'm trying to plot a bunch of coordinates on the earth and track how many coordinates are in each country. I have plotted the map and coordinates fine, but when I try to use the intersection to count how many coordinates fall within each country (polygon) it results in error. I've tried using the st_make_valid function to fix the earth shape file but it messes up the geometry. I'm new to using R so any help would be greatly appreciated.</p>
<p>I have used the following code to plot the earth shape file and the coordinates on top:</p>
<pre><code>library(tidyverse)
library(sf)
library(rmapshaper)
library(rnaturalearth)
library(rnaturalearthdata)
library(sp)
library(raster)
###############
# Load Data
###############
# Read in data from .csv file
MeteoriteData <- read.csv("C:/Users/ChaseDickson_/Desktop/College/AERO 689/Semester Project/Meteorite Landings.csv")
# Convert these points to an SF object, specifying the X and Y
# column names, and supplying the CRS as 4326 (which is WGS84)
MeteoriteData.sf <- st_as_sf(MeteoriteData, coords=c('long', 'lat'), crs=4326)
world <- (ne_countries(scale = "medium", returnclass = "sf"))
MeteoriteMap <- ggplot(data = world) +
geom_sf() +
geom_sf(data = MeteoriteData.sf, size = 0.5, shape = 23, fill = "darkred") +
theme_bw()
MeteoriteMap
</code></pre>
<p>Which gives the following plot</p>
<p><a href="https://i.stack.imgur.com/aYh2F.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aYh2F.png" alt="enter image description here" /></a></p>
<p>However, when getting the intersection of the code I used this</p>
<p><code>intersection <- st_intersection(x = world, y = MeteoriteData.sf)</code></p>
<p>But it gave the error</p>
<pre><code>Error in wk_handle.wk_wkb(wkb, s2_geography_writer(oriented = oriented, :
Loop 96 is not valid: Edge 743 crosses edge 998
</code></pre>
<p>To fix this I changed the world sf by adding st_make_valid like so:</p>
<p><code>world <- st_make_valid(ne_countries(scale = "small", returnclass = "sf"))</code></p>
<p>Now this allows the intersection function to work as such:</p>
<pre><code>intersection <- st_intersection(x = world, y = MeteoriteData.sf)
int_result <- intersection %>%
group_by(sovereignt) %>%
count()
</code></pre>
<p>And the output is recorded shown below</p>
<p><a href="https://i.stack.imgur.com/YiP9h.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YiP9h.png" alt="enter image description here" /></a></p>
<p>However, this messes the countries (polygons) up in the plot and will give inaccurate data as the new earth shape file is shown below:</p>
<p><a href="https://i.stack.imgur.com/OCDFo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OCDFo.png" alt="enter image description here" /></a></p>
<p>Any help figuring out how to maintain the first plot, but still get the intersection function and count to work after adding st_make_valid would be greatly appreciated!</p>
|
[
{
"answer_id": 74528874,
"author": "Jindra Lacko",
"author_id": 7756889,
"author_profile": "https://Stackoverflow.com/users/7756889",
"pm_score": 4,
"selected": true,
"text": "{rnaturalearth} {maps} library(sf)\n\nrnaturalearth::ne_countries(scale = \"medium\", returnclass = \"sf\")|>\n st_is_valid() |>\n table()\n\n# FALSE TRUE \n# 6 235 \n {giscoR} giscoR::gisco_get_countries(resolution = \"20\") |>\n st_is_valid() |>\n table()\n\n# TRUE \n# 257 \n"
},
{
"answer_id": 74546446,
"author": "margusl",
"author_id": 646761,
"author_profile": "https://Stackoverflow.com/users/646761",
"pm_score": 2,
"selected": false,
"text": "st_intersection() st_join() st_intersects() library(sf)\nlibrary(ggplot2)\ncountries <- giscoR::gisco_get_countries(resolution = \"20\")\n\nset.seed(1)\nrandom_points <- data.frame(x = runif(100,-180,180), y = runif(100,-90,90)) |> \n st_as_sf(coords = c(\"x\",\"y\"), crs = \"WGS84\")\n\n#> Measure st_intersection():\nsystem.time({\n countries_isect <- st_intersection(countries, random_points)\n})\n#> user system elapsed \n#> 15.97 0.47 16.50\n\n#> Measure st_intersects():\nsystem.time({\n countries$hits <- lengths(st_intersects(countries, random_points))\n})\n#> user system elapsed \n#> 0.22 0.00 0.22\n\nggplot(countries) +\n geom_sf(data = countries) +\n geom_sf(data = random_points) +\n theme_void()\n lengths(st_intersects(countries, random_points)) countries[countries$hits > 0,c(\"NAME_ENGL\",\"hits\")] |> st_drop_geometry()\n#> NAME_ENGL hits\n#> 4 Antarctica 7\n#> 13 Australia 1\n#> 30 Brazil 4\n#> 31 China 3\n#> 48 Greenland 1\n#> 55 Canada 3\n#> 116 Kazakhstan 1\n#> 117 Laos 1\n#> 125 Cambodia 1\n#> 141 Mauritania 1\n#> 155 Oman 1\n#> 162 Paraguay 1\n#> 184 Mali 1\n#> 185 Russian Federation 5\n#> 221 United States 3\n#> 223 Venezuela 1\n#> 249 Thailand 1\n\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74526925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20534438/"
] |
74,526,990
|
<p>So, this bug has something to do with converting the player choice 1-9 to displaying it on the board with a X or O. It displays correctly it's just they can over loop each other buy just putting in the same input and I'm not quite sure how to fix this. I've tried moving the convert() around the play game() in the for loop to see if that would somehow fix it by trial and error but no it seems its a coding issue in the convert() function I just don't know where or what that issue is. I'm still learning C++ I'm just testing myself I saw a few people make a tik tac toe game online and I wanted to give it a shot, so any advice is appreciated.</p>
<pre><code>#include "functions.h"
#include <iostream>
#include <vector>
using namespace std;
vector<string> player_icons = { "X", "O" };
vector<string> grid = {" ", " ", " ", " ", " ", " ", " ", " ", " ", " "};
int player1 = 0;
int player2 = 0;
string who_Won1 = "Player 1";
string who_Won2 = "Player 2";
void intro() {//The intro sequence to game
cout << "==================\n";
cout << " Tic Tac Toe Game \n";
cout << "==================\n";
cout << "\n";
cout << "Instructions: This game will require 2 players\n";
cout << "To win you need to match 3 in a row of the same\n";
cout << "\n";
cout << "Player 1: X\n";
cout << "Player 2: O\n";
cout << "\n";
cout << " | | \n";
cout << " 1 | 2 | 3 \n";
cout << "_____|_____|_____ \n";
cout << " | | \n";
cout << " 4 | 5 | 6 \n";
cout << "_____|_____|_____ \n";
cout << " | | \n";
cout << " 7 | 8 | 9 \n";
cout << " | | \n";
cout << "\n";
cout << "Above is the example of what the grid is going to look like when you play\n";
cout << "Each player must select a number 1-9 to put there X or O there\n";
}
void board_make() {//outputs to the terminal the actual tic tac toe board
std::cout << " | | \n";
std::cout << " " << grid[0] << " | " << grid[1] << " | " << grid[2] << "\n";
std::cout << "_____|_____|_____ \n";
std::cout << " | | \n";
std::cout << " " << grid[3] << " | " << grid[4] << " | " << grid[5] << "\n";
std::cout << "_____|_____|_____ \n";
std::cout << " | | \n";
std::cout << " " << grid[6] << " | " << grid[7] << " | " << grid[8] << "\n";
std::cout << " | | \n";
}
bool win_condition() {//its in the name it checks for wins
bool winner = false;
//rows
if ((grid[0] == grid[1]) && (grid[1] == grid[2]) && grid[0] != " ") {
winner = true;
}
else if ((grid[3] == grid[4]) && (grid[4] == grid[5]) && grid[3] != " ") {
winner = true;
}
else if ((grid[6] == grid[7]) && (grid[7] == grid[8]) && grid[6] != " ") {
winner = true;
}
//columns
if ((grid[0] == grid[3]) && (grid[3] == grid[6]) && grid[0] != " ") {
winner = true;
}
else if ((grid[1] == grid[4]) && (grid[4] == grid[7]) && grid[1] != " ") {
winner = true;
}
else if ((grid[2] == grid[5]) && (grid[5] == grid[8]) && grid[2] != " ") {
winner = true;
}
//across
if ((grid[0] == grid[4]) && (grid[4] == grid[8]) && grid[0] != " ") {
winner = true;
}
else if ((grid[2] == grid[4]) && (grid[4] == grid[6]) && grid[2] != " ") {
winner = true;
}
return winner;
}
void game_start() {
for (int i = 0; i < 5; i ++) {//iterates through both players turns till after the
//Player 1's turn
cout << "\n";
cout << "Player 1 its your turn please enter 1-9 to select your choice: "; cin >> player1; convert(); cout << "\n";
board_make();
win();
cout << "\n";
//Player 2's turn
cout << "\n";
cout << "Player 2 its now your turn select your choice 1-9: "; cin >> player2; convert(); cout << "\n";
board_make();
win();
cout << "\n";
}
}
void convert() {
for (int i = 0; i < 8; i++) {
//Player 1 checking
if (player1 == i + 1 && player2 != i + 1) {
grid.at(i) = "X";
}
if (player2 == i + 1 && player1 != i + 1) {
grid.at(i) = "O";
}
}
}
void win() {
if (win_condition()) {
if ((grid[0] == grid[1]) && (grid[1] == grid[2]) && grid[0] != " ") {
if (grid[0] == "X") {
cout << who_Won1 << " Won\n";
exit(0);
}
else if (grid[0] == "O") {
cout << who_Won2 << " Won\n";
exit(0);
}
}
else if ((grid[3] == grid[4]) && (grid[4] == grid[5]) && grid[3] != " ") {
if (grid[3] == "X") {
cout << who_Won1 << " Won\n";
exit(0);
}
else if (grid[3] == "O") {
cout << who_Won2 << " Won\n";
exit(0);
}
}
else if ((grid[6] == grid[7]) && (grid[7] == grid[8]) && grid[6] != " ") {
if (grid[6] == "X") {
cout << who_Won1 << " Won\n";
exit(0);
}
else if (grid[6] == "O") {
cout << who_Won2 << " Won\n";
exit(0);
}
}
//columns
if ((grid[0] == grid[3]) && (grid[3] == grid[6]) && grid[0] != " ") {
if (grid[0] == "X") {
cout << who_Won1 << " Won\n";
exit(0);
}
else if (grid[0] == "O") {
cout << who_Won2 << " Won\n";
exit(0);
}
}
else if ((grid[1] == grid[4]) && (grid[4] == grid[7]) && grid[1] != " ") {
if (grid[1] == "X") {
cout << who_Won1 << " Won\n";
exit(0);
}
else if (grid[1] == "O") {
cout << who_Won2 << " Won\n";
exit(0);
}
}
else if ((grid[2] == grid[5]) && (grid[5] == grid[8]) && grid[2] != " ") {
if (grid[2] == "X") {
cout << who_Won1 << " Won\n";
exit(0);
}
else if (grid[2] == "O") {
cout << who_Won2 << " Won\n";
exit(0);
}
}
//across
if ((grid[0] == grid[4]) && (grid[4] == grid[8]) && grid[0] != " ") {
if (grid[0] == "X") {
cout << who_Won1 << " Won\n";
exit(0);
}
else if (grid[0] == "O") {
cout << who_Won2 << " Won\n";
exit(0);
}
}
else if ((grid[2] == grid[4]) && (grid[4] == grid[6]) && grid[2] != " ") {
if (grid[2] == "X") {
cout << who_Won1 << " Won\n";
exit(0);
}
else if (grid[2] == "O") {
cout << who_Won2 << " Won\n";
exit(0);
}
}
}
}
</code></pre>
|
[
{
"answer_id": 74528909,
"author": "w o h",
"author_id": 12381721,
"author_profile": "https://Stackoverflow.com/users/12381721",
"pm_score": 1,
"selected": false,
"text": "player1 player2 \" \""
},
{
"answer_id": 74536589,
"author": "shractic",
"author_id": 20568176,
"author_profile": "https://Stackoverflow.com/users/20568176",
"pm_score": 0,
"selected": false,
"text": " #include \"functions.h\"\n #include <iostream>\n #include <vector>\n using namespace std;\n\n\n vector<string> player_icons = { \"X\", \"O\" };\n vector<string> grid = {\" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \"};\n int player1 = 0;\n int player2 = 0;\n string who_Won1 = \"Player 1\";\n string who_Won2 = \"Player 2\";\n bool filled = false;\n\n void intro() {//The intro sequence to game\n\n\n cout << \"==================\\n\";\n cout << \" Tic Tac Toe Game \\n\";\n cout << \"==================\\n\";\n cout << \"\\n\";\n\n cout << \"Instructions: This game will require 2 players\\n\";\n cout << \"To win you need to match 3 in a row of the same\\n\";\n cout << \"\\n\";\n\n cout << \"Player 1: X\\n\";\n cout << \"Player 2: O\\n\";\n cout << \"\\n\";\n\n cout << \" | | \\n\";\n cout << \" 1 | 2 | 3 \\n\";\n cout << \"_____|_____|_____ \\n\";\n cout << \" | | \\n\";\n cout << \" 4 | 5 | 6 \\n\";\n cout << \"_____|_____|_____ \\n\";\n cout << \" | | \\n\";\n cout << \" 7 | 8 | 9 \\n\";\n cout << \" | | \\n\";\n cout << \"\\n\";\n\n cout << \"Above is the example of what the grid is going to look like when you play\\n\";\n cout << \"Each player must select a numer 1-9 to put there X or O there\\n\";\n\n }\n\n void board_make() {\n\n std::cout << \" | | \\n\";\n\n std::cout << \" \" << grid[0] << \" | \" << grid[1] << \" | \" << grid[2] << \"\\n\";\n\n std::cout << \"_____|_____|_____ \\n\";\n std::cout << \" | | \\n\";\n\n std::cout << \" \" << grid[3] << \" | \" << grid[4] << \" | \" << grid[5] << \"\\n\";\n\n std::cout << \"_____|_____|_____ \\n\";\n std::cout << \" | | \\n\";\n\n std::cout << \" \" << grid[6] << \" | \" << grid[7] << \" | \" << grid[8] << \"\\n\";\n std::cout << \" | | \\n\";\n\n\n }\n\n void win_condition() {//its in the name it checks for wins \n\n\n\n //rows\n if ((grid[0] == grid[1]) && (grid[1] == grid[2]) && grid[0] != \" \") {\n win(0);\n \n }\n else if ((grid[3] == grid[4]) && (grid[4] == grid[5]) && grid[3] != \" \") {\n win(3);\n }\n else if ((grid[6] == grid[7]) && (grid[7] == grid[8]) && grid[6] != \" \") {\n win(6);\n }\n\n // columns\n if ((grid[0] == grid[3]) && (grid[3] == grid[6]) && grid[0] != \" \") {\n win(0);\n }\n else if ((grid[1] == grid[4]) && (grid[4] == grid[7]) && grid[1] != \" \") {\n win(1);\n }\n else if ((grid[2] == grid[5]) && (grid[5] == grid[8]) && grid[2] != \" \") {\n win(2);\n }\n\n //across\n if ((grid[0] == grid[4]) && (grid[4] == grid[8]) && grid[0] != \" \") {\n win(0);\n }\n else if ((grid[2] == grid[4]) && (grid[4] == grid[6]) && grid[2] != \" \") {\n win(2);\n }\n }\n\n void game_start() {\n\n for (int i = 0; i < 5; i ++) {//iterates through both players turns till after the \n //Player 1's turn\n cout << \"\\n\";\n cout << \"Player 1 its your turn please enter 1-9 to select your choice: \"; cin >> player1; convert(); cout << \"\\n\";\n board_make();\n win_condition();\n cout << \"\\n\";\n //Player 2's turn\n cout << \"\\n\";\n cout << \"Player 2 its now your turn select your choice 1-9: \"; cin >> player2; convert(); cout << \"\\n\";\n board_make();\n win_condition();\n cout << \"\\n\";\n }\n }\n\n void convert() {\n for (int i = 0; i < 8; i++) {\n //checks if the spot is filled if it is filled it sets filled to true\n if ((grid[i] == \"X\" || grid[i] == \"O\") && grid[i] != \" \") {\n filled = true;\n }\n else if (grid[i] == \" \"){\n filled = false;\n }\n\n if (filled == true && player1 == i + 1 && grid[i] != \" \") {//if filled is true and player choice is a option that was filled then it outputs whats below\n cout << \"Looks like that spot is already taken, please select another space\\n\";\n }\n \n if (filled == true && player2 == i + 1 && grid[i] != \" \") {//if filled is true and player choice is a option that was filled then it outputs whats below\n cout << \"Looks like that spot is already taken, please select another space\\n\";\n }\n\n //converting the player choice 1-9 to a X or O\n if (filled == false && player1 == i + 1 && player2 != i + 1) {\n grid.at(i) = \"X\";\n }\n\n if (filled == false && player2 == i + 1 && player1 != i + 1) {\n grid.at(i) = \"O\";\n }\n }\n }\n\n void win(int num) {\n if (grid[num] == \"X\") {\n cout << who_Won1 << \" Won\\n\";\n exit(0);\n }\n else if (grid[num] == \"O\") {\n cout << who_Won2 << \" Won\\n\";\n exit(0);\n }\n }\n}\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74526990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20568176/"
] |
74,526,999
|
<p>I want to make a dynamic array that stores a game board (chess) but the board is stored in a 2d array. how can I update an array by increasing the size without deleting the stored data?</p>
<pre><code>String[][] TablaInicial = new String[17][17];
List<List<String>> Prueba = new ArrayList<List<String>>();
for (i=0; i<17; i++) {
for (y=0; y<17; y++) {
Prueba.get(i).get(y).add(TablaInicial[i][y]);
}
}
</code></pre>
<p>But I get this error: The method add(String) is undefined for the type String</p>
|
[
{
"answer_id": 74528909,
"author": "w o h",
"author_id": 12381721,
"author_profile": "https://Stackoverflow.com/users/12381721",
"pm_score": 1,
"selected": false,
"text": "player1 player2 \" \""
},
{
"answer_id": 74536589,
"author": "shractic",
"author_id": 20568176,
"author_profile": "https://Stackoverflow.com/users/20568176",
"pm_score": 0,
"selected": false,
"text": " #include \"functions.h\"\n #include <iostream>\n #include <vector>\n using namespace std;\n\n\n vector<string> player_icons = { \"X\", \"O\" };\n vector<string> grid = {\" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \"};\n int player1 = 0;\n int player2 = 0;\n string who_Won1 = \"Player 1\";\n string who_Won2 = \"Player 2\";\n bool filled = false;\n\n void intro() {//The intro sequence to game\n\n\n cout << \"==================\\n\";\n cout << \" Tic Tac Toe Game \\n\";\n cout << \"==================\\n\";\n cout << \"\\n\";\n\n cout << \"Instructions: This game will require 2 players\\n\";\n cout << \"To win you need to match 3 in a row of the same\\n\";\n cout << \"\\n\";\n\n cout << \"Player 1: X\\n\";\n cout << \"Player 2: O\\n\";\n cout << \"\\n\";\n\n cout << \" | | \\n\";\n cout << \" 1 | 2 | 3 \\n\";\n cout << \"_____|_____|_____ \\n\";\n cout << \" | | \\n\";\n cout << \" 4 | 5 | 6 \\n\";\n cout << \"_____|_____|_____ \\n\";\n cout << \" | | \\n\";\n cout << \" 7 | 8 | 9 \\n\";\n cout << \" | | \\n\";\n cout << \"\\n\";\n\n cout << \"Above is the example of what the grid is going to look like when you play\\n\";\n cout << \"Each player must select a numer 1-9 to put there X or O there\\n\";\n\n }\n\n void board_make() {\n\n std::cout << \" | | \\n\";\n\n std::cout << \" \" << grid[0] << \" | \" << grid[1] << \" | \" << grid[2] << \"\\n\";\n\n std::cout << \"_____|_____|_____ \\n\";\n std::cout << \" | | \\n\";\n\n std::cout << \" \" << grid[3] << \" | \" << grid[4] << \" | \" << grid[5] << \"\\n\";\n\n std::cout << \"_____|_____|_____ \\n\";\n std::cout << \" | | \\n\";\n\n std::cout << \" \" << grid[6] << \" | \" << grid[7] << \" | \" << grid[8] << \"\\n\";\n std::cout << \" | | \\n\";\n\n\n }\n\n void win_condition() {//its in the name it checks for wins \n\n\n\n //rows\n if ((grid[0] == grid[1]) && (grid[1] == grid[2]) && grid[0] != \" \") {\n win(0);\n \n }\n else if ((grid[3] == grid[4]) && (grid[4] == grid[5]) && grid[3] != \" \") {\n win(3);\n }\n else if ((grid[6] == grid[7]) && (grid[7] == grid[8]) && grid[6] != \" \") {\n win(6);\n }\n\n // columns\n if ((grid[0] == grid[3]) && (grid[3] == grid[6]) && grid[0] != \" \") {\n win(0);\n }\n else if ((grid[1] == grid[4]) && (grid[4] == grid[7]) && grid[1] != \" \") {\n win(1);\n }\n else if ((grid[2] == grid[5]) && (grid[5] == grid[8]) && grid[2] != \" \") {\n win(2);\n }\n\n //across\n if ((grid[0] == grid[4]) && (grid[4] == grid[8]) && grid[0] != \" \") {\n win(0);\n }\n else if ((grid[2] == grid[4]) && (grid[4] == grid[6]) && grid[2] != \" \") {\n win(2);\n }\n }\n\n void game_start() {\n\n for (int i = 0; i < 5; i ++) {//iterates through both players turns till after the \n //Player 1's turn\n cout << \"\\n\";\n cout << \"Player 1 its your turn please enter 1-9 to select your choice: \"; cin >> player1; convert(); cout << \"\\n\";\n board_make();\n win_condition();\n cout << \"\\n\";\n //Player 2's turn\n cout << \"\\n\";\n cout << \"Player 2 its now your turn select your choice 1-9: \"; cin >> player2; convert(); cout << \"\\n\";\n board_make();\n win_condition();\n cout << \"\\n\";\n }\n }\n\n void convert() {\n for (int i = 0; i < 8; i++) {\n //checks if the spot is filled if it is filled it sets filled to true\n if ((grid[i] == \"X\" || grid[i] == \"O\") && grid[i] != \" \") {\n filled = true;\n }\n else if (grid[i] == \" \"){\n filled = false;\n }\n\n if (filled == true && player1 == i + 1 && grid[i] != \" \") {//if filled is true and player choice is a option that was filled then it outputs whats below\n cout << \"Looks like that spot is already taken, please select another space\\n\";\n }\n \n if (filled == true && player2 == i + 1 && grid[i] != \" \") {//if filled is true and player choice is a option that was filled then it outputs whats below\n cout << \"Looks like that spot is already taken, please select another space\\n\";\n }\n\n //converting the player choice 1-9 to a X or O\n if (filled == false && player1 == i + 1 && player2 != i + 1) {\n grid.at(i) = \"X\";\n }\n\n if (filled == false && player2 == i + 1 && player1 != i + 1) {\n grid.at(i) = \"O\";\n }\n }\n }\n\n void win(int num) {\n if (grid[num] == \"X\") {\n cout << who_Won1 << \" Won\\n\";\n exit(0);\n }\n else if (grid[num] == \"O\") {\n cout << who_Won2 << \" Won\\n\";\n exit(0);\n }\n }\n}\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74526999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20568230/"
] |
74,527,010
|
<p>I am new to programming and I am trying below code in Flutter:</p>
<pre><code>DateTime dt2 = DateTime.parse(strDateToCompare).toLocal();
</code></pre>
<p>where value of <code>strDateToCompare</code> is <strong>14 Nov 2022</strong></p>
<p>It gives me below error:</p>
<blockquote>
<p>FormatException: Invalid date format 14 Nov 2022</p>
</blockquote>
<p>I think I am doing some silly mistake here. What might be the issue? Thanks in advance.</p>
|
[
{
"answer_id": 74527072,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 3,
"selected": true,
"text": "DateTime.parse() \"2012-02-27\"\n\"2012-02-27 13:27:00\"\n\"2012-02-27 13:27:00.123456789z\"\n\"2012-02-27 13:27:00,123456789z\"\n\"20120227 13:27:00\"\n\"20120227T132700\"\n\"20120227\"\n\"+20120227\"\n\"2012-02-27T14Z\"\n\"2012-02-27T14+00:00\"\n\"-123450101 00:00:00 Z\": in the year -12345.\n\"2002-02-27T14:00:00-0500\"\n 14 Nov 2022 2022-11-14 DateTime dt2 = DateTime.parse(`2022-11-14`).toLocal(); //\n 14 Nov 2022 2022-11-14 String properFormatForDate(String invalidFormat) {\n int index= 1;\n final monthsAbbr = Map.fromIterable(\n [\n \"jan\",\n \"feb\",\n \"mar\",\n \"apr\",\n \"may\",\n \"jun\",\n \"jul\",\n \"aug\",\n \"sep\",\n \"oct\",\n \"nov\",\n \"dec\"\n ],\n key: (e) => e,\n value: (e) => index++,\n );\n final listSeparated = invalidFormat.split(\" \").reversed.toList();\n int monthInNumber = monthsAbbr[listSeparated[1].toLowerCase()]! ;\n listSeparated[1] = monthInNumber.toString();\n\n return listSeparated.join(\"-\");\n }\n \n print(properFormatForDate(\"14 Nov 2022\")); // 2022-11-14\n"
},
{
"answer_id": 74527133,
"author": "pmatatias",
"author_id": 12838877,
"author_profile": "https://Stackoverflow.com/users/12838877",
"pm_score": 2,
"selected": false,
"text": "import 'package:intl/intl.dart';\n\nvoid main() {\n final a = DateFormat('d MMM y').format(DateTime.now());\n print(a); // 22 Nov 2022\n DateTime temp = DateFormat('d MMM y').parse(a);\n print(temp); //. 2022-11-22 00:00:00.000\n \n\n /// now you can use that format:\n DateTime dt2 = DateFormat('d MMM y').parse('14 Nov 2022').toLocal();\n \n print(dt2); // 2022-11-14 00:00:00.000\n \n}\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4827817/"
] |
74,527,011
|
<p>I'm using OpenMP to parallelize the loop, that is internally using AVX-512 with <a href="https://github.com/vectorclass" rel="nofollow noreferrer">Agner Fog's VCL Vector Class Library.</a></p>
<p>Here is the code:</p>
<pre><code>double HarmonicSeries(const unsigned long long int N) {
unsigned long long int i;
Vec8d divV(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0);
Vec8d sumV(0.0);
const Vec8d addV(8.0);
const Vec8d oneV(1.0);
#pragma omp parallel for reduction(+:sumV,divV)
for(i=0; i<N; ++i) {
sumV += oneV / divV;
divV += addV;
}
return horizontal_add(sumV);
}
</code></pre>
<p>When trying to compile the code above, I'm getting</p>
<pre><code>g++ -Wall -Wextra -O3 -g -I include -fopenmp -m64 -mavx2 -mfma -std=c++17 -o harmonic_series harmonic_series.cpp
harmonic_series.cpp:87:40: error: user defined reduction not found for โsumVโ
87 | #pragma omp parallel for reduction(+:sumV,divV)
| ^~~~
harmonic_series.cpp:87:45: error: user defined reduction not found for โdivVโ
87 | #pragma omp parallel for reduction(+:sumV,divV)
</code></pre>
<p>Any hints on how to solve this and provide the user-defined reduction for the <code>Vec8d</code> class? It's simply the plus operator which is defined by the VCL class, but I cannot find any example how to code this.</p>
<p>Thanks a lot for any help!</p>
|
[
{
"answer_id": 74527072,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 3,
"selected": true,
"text": "DateTime.parse() \"2012-02-27\"\n\"2012-02-27 13:27:00\"\n\"2012-02-27 13:27:00.123456789z\"\n\"2012-02-27 13:27:00,123456789z\"\n\"20120227 13:27:00\"\n\"20120227T132700\"\n\"20120227\"\n\"+20120227\"\n\"2012-02-27T14Z\"\n\"2012-02-27T14+00:00\"\n\"-123450101 00:00:00 Z\": in the year -12345.\n\"2002-02-27T14:00:00-0500\"\n 14 Nov 2022 2022-11-14 DateTime dt2 = DateTime.parse(`2022-11-14`).toLocal(); //\n 14 Nov 2022 2022-11-14 String properFormatForDate(String invalidFormat) {\n int index= 1;\n final monthsAbbr = Map.fromIterable(\n [\n \"jan\",\n \"feb\",\n \"mar\",\n \"apr\",\n \"may\",\n \"jun\",\n \"jul\",\n \"aug\",\n \"sep\",\n \"oct\",\n \"nov\",\n \"dec\"\n ],\n key: (e) => e,\n value: (e) => index++,\n );\n final listSeparated = invalidFormat.split(\" \").reversed.toList();\n int monthInNumber = monthsAbbr[listSeparated[1].toLowerCase()]! ;\n listSeparated[1] = monthInNumber.toString();\n\n return listSeparated.join(\"-\");\n }\n \n print(properFormatForDate(\"14 Nov 2022\")); // 2022-11-14\n"
},
{
"answer_id": 74527133,
"author": "pmatatias",
"author_id": 12838877,
"author_profile": "https://Stackoverflow.com/users/12838877",
"pm_score": 2,
"selected": false,
"text": "import 'package:intl/intl.dart';\n\nvoid main() {\n final a = DateFormat('d MMM y').format(DateTime.now());\n print(a); // 22 Nov 2022\n DateTime temp = DateFormat('d MMM y').parse(a);\n print(temp); //. 2022-11-22 00:00:00.000\n \n\n /// now you can use that format:\n DateTime dt2 = DateFormat('d MMM y').parse('14 Nov 2022').toLocal();\n \n print(dt2); // 2022-11-14 00:00:00.000\n \n}\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3082774/"
] |
74,527,018
|
<p>so i have data frame as below</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: right;">A1</th>
<th style="text-align: right;">A2</th>
<th style="text-align: right;">A3</th>
<th style="text-align: right;">A4</th>
<th style="text-align: right;">A5</th>
<th style="text-align: right;">A6</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: right;">1</td>
<td style="text-align: right;">nan</td>
<td style="text-align: right;">3</td>
<td style="text-align: right;">7</td>
<td style="text-align: right;">nan</td>
<td style="text-align: right;">8</td>
</tr>
<tr>
<td style="text-align: right;">nan</td>
<td style="text-align: right;">5</td>
<td style="text-align: right;">nan</td>
<td style="text-align: right;">11</td>
<td style="text-align: right;">9</td>
<td style="text-align: right;">nan</td>
</tr>
<tr>
<td style="text-align: right;">54</td>
<td style="text-align: right;">6</td>
<td style="text-align: right;">84</td>
<td style="text-align: right;">12</td>
<td style="text-align: right;">3</td>
<td style="text-align: right;">nan</td>
</tr>
<tr>
<td style="text-align: right;">10</td>
<td style="text-align: right;">nan</td>
<td style="text-align: right;">nan</td>
<td style="text-align: right;">16</td>
<td style="text-align: right;">nan</td>
<td style="text-align: right;">45</td>
</tr>
<tr>
<td style="text-align: right;">12</td>
<td style="text-align: right;">93</td>
<td style="text-align: right;">13</td>
<td style="text-align: right;">31</td>
<td style="text-align: right;">5</td>
<td style="text-align: right;">91</td>
</tr>
<tr>
<td style="text-align: right;">73</td>
<td style="text-align: right;">nan</td>
<td style="text-align: right;">45</td>
<td style="text-align: right;">nan</td>
<td style="text-align: right;">nan</td>
<td style="text-align: right;">9</td>
</tr>
</tbody>
</table>
</div>
<p>i want to shift the whole data frame n rows such that it skips nan rows but still preserve it.
desire output:
for n =2</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: right;">A1</th>
<th style="text-align: right;">A2</th>
<th style="text-align: right;">A3</th>
<th style="text-align: right;">A4</th>
<th style="text-align: right;">A5</th>
<th style="text-align: right;">A6</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: right;">nan</td>
<td style="text-align: right;">nan</td>
<td style="text-align: right;">nan</td>
<td style="text-align: right;">nan</td>
<td style="text-align: right;">nan</td>
<td style="text-align: right;">nan</td>
</tr>
<tr>
<td style="text-align: right;">nan</td>
<td style="text-align: right;">nan</td>
<td style="text-align: right;">nan</td>
<td style="text-align: right;">nan</td>
<td style="text-align: right;">nan</td>
<td style="text-align: right;">nan</td>
</tr>
<tr>
<td style="text-align: right;">nan</td>
<td style="text-align: right;">nan</td>
<td style="text-align: right;">nan</td>
<td style="text-align: right;">7</td>
<td style="text-align: right;">nan</td>
<td style="text-align: right;">nan</td>
</tr>
<tr>
<td style="text-align: right;">1</td>
<td style="text-align: right;">nan</td>
<td style="text-align: right;">nan</td>
<td style="text-align: right;">11</td>
<td style="text-align: right;">nan</td>
<td style="text-align: right;">nan</td>
</tr>
<tr>
<td style="text-align: right;">54</td>
<td style="text-align: right;">5</td>
<td style="text-align: right;">3</td>
<td style="text-align: right;">12</td>
<td style="text-align: right;">9</td>
<td style="text-align: right;">8</td>
</tr>
<tr>
<td style="text-align: right;">10</td>
<td style="text-align: right;">nan</td>
<td style="text-align: right;">84</td>
<td style="text-align: right;">nan</td>
<td style="text-align: right;">nan</td>
<td style="text-align: right;">45</td>
</tr>
</tbody>
</table>
</div>
<p>i tried the following:</p>
<pre><code>df['dummy'] = df.apply(lambda x: 1 if pd.notnull(x[column]) else 0, axis=1)
df['dummy2'] = df.groupby(['dummy'])[column].shift(n)
df[column] = df.apply(lambda x: x['dummy2'] if x['dummy']==1 else x[column], axis=1)
</code></pre>
<p>which is good if there is only a few columns i need to shift.</p>
<p>i also tried the applymap function</p>
<pre><code>dummy_df = df.applymap(lambda x: 1 if pd.notnull(x) else 0)
</code></pre>
<p>which returns a dummy data frame to separate groups that i want to shift, just have no idea what to do next with it.
the problem is that there are thousands of columns i need to shift row wise.</p>
<p>Is there any ways i can do this using minimum loops? And are there any ways to do it with groupby function using dummy_df?</p>
|
[
{
"answer_id": 74527072,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 3,
"selected": true,
"text": "DateTime.parse() \"2012-02-27\"\n\"2012-02-27 13:27:00\"\n\"2012-02-27 13:27:00.123456789z\"\n\"2012-02-27 13:27:00,123456789z\"\n\"20120227 13:27:00\"\n\"20120227T132700\"\n\"20120227\"\n\"+20120227\"\n\"2012-02-27T14Z\"\n\"2012-02-27T14+00:00\"\n\"-123450101 00:00:00 Z\": in the year -12345.\n\"2002-02-27T14:00:00-0500\"\n 14 Nov 2022 2022-11-14 DateTime dt2 = DateTime.parse(`2022-11-14`).toLocal(); //\n 14 Nov 2022 2022-11-14 String properFormatForDate(String invalidFormat) {\n int index= 1;\n final monthsAbbr = Map.fromIterable(\n [\n \"jan\",\n \"feb\",\n \"mar\",\n \"apr\",\n \"may\",\n \"jun\",\n \"jul\",\n \"aug\",\n \"sep\",\n \"oct\",\n \"nov\",\n \"dec\"\n ],\n key: (e) => e,\n value: (e) => index++,\n );\n final listSeparated = invalidFormat.split(\" \").reversed.toList();\n int monthInNumber = monthsAbbr[listSeparated[1].toLowerCase()]! ;\n listSeparated[1] = monthInNumber.toString();\n\n return listSeparated.join(\"-\");\n }\n \n print(properFormatForDate(\"14 Nov 2022\")); // 2022-11-14\n"
},
{
"answer_id": 74527133,
"author": "pmatatias",
"author_id": 12838877,
"author_profile": "https://Stackoverflow.com/users/12838877",
"pm_score": 2,
"selected": false,
"text": "import 'package:intl/intl.dart';\n\nvoid main() {\n final a = DateFormat('d MMM y').format(DateTime.now());\n print(a); // 22 Nov 2022\n DateTime temp = DateFormat('d MMM y').parse(a);\n print(temp); //. 2022-11-22 00:00:00.000\n \n\n /// now you can use that format:\n DateTime dt2 = DateFormat('d MMM y').parse('14 Nov 2022').toLocal();\n \n print(dt2); // 2022-11-14 00:00:00.000\n \n}\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20567944/"
] |
74,527,021
|
<p>I have a table named <code>orders</code> in a SQL database that looks like this:</p>
<pre><code> user_id email segment destination revenue
1 joe@smith.com basic New York 500
1 joe@smith.com luxury London 750
1 joe@smith.com luxury London 500
1 joe@smith.com basic New York 625
1 joe@smith.com basic Miami 925
1 joe@smith.com basic Los Angeles 218
1 joe@smith.com basic Sydney 200
2 mary@jones.com basic Chicago 375
2 mary@jones.com luxury New York 1500
2 mary@jones.com basic Toronto 2800
2 mary@jones.com basic Miami 750
2 mary@jones.com basic New York 500
2 mary@jones.com basic New York 625
3 mike@me.com luxury New York 650
3 mike@me.com basic New York 875
4 sally@you.com luxury Chicago 1300
4 sally@you.com basic New York 1200
4 sally@you.com basic New York 1000
4 sally@you.com luxury Sydney 725
5 bob@gmail.com basic London 500
5 bob@gmail.com luxury London 750
</code></pre>
<p>Here's a SQL Fiddle: <a href="http://www.sqlfiddle.com/#!9/22f40a/1" rel="nofollow noreferrer">http://www.sqlfiddle.com/#!9/22f40a/1</a></p>
<p>I'd like to be able to apply the following logic to get the final result set:</p>
<p>Return only the distinct <code>user_id</code> and the user's <code>email</code> based on the following conditions:</p>
<ol>
<li>where <code>segment</code> is equal to <code>luxury</code> <em><strong>and</strong></em> <code>destination</code> is equal to New York</li>
</ol>
<p><em><strong>OR</strong></em></p>
<ol start="2">
<li>where <code>segment</code> is equal to <code>luxury</code> <em><strong>and</strong></em> <code>destination</code> is equal to <code>London</code></li>
</ol>
<p><em><strong>OR</strong></em></p>
<ol start="3">
<li>where <code>segment</code> is equal to <code>basic</code> <em><strong>and</strong></em> <code>destination</code> is equal to <code>New York</code> <em><strong>and</strong></em> the given user has a <code>revenue</code> amount in the <code>basic</code> and <code>New York</code> records that sums to greater than $2,000</li>
</ol>
<p><em><strong>BUT</strong></em></p>
<ol start="4">
<li>a given user has <em><strong>not</strong></em> previously been to <code>destination</code> equal to <code>Miami</code></li>
</ol>
<p>Based on my sample data, I would like to see the following returned:</p>
<pre><code>user_id email
3 mike@me.com
4 sally@you.com
5 bob@gmail.com
</code></pre>
<p>I tried to use the following to get <em><strong>part</strong></em> of what I need:</p>
<pre><code>SELECT
DISTINCT(user_id),
email
FROM orders o
WHERE
(o.segment = 'luxury' AND o.destination = 'New York')
OR
(o.segment = 'luxury' AND o.destination = 'London')
</code></pre>
<p>But, this query doesn't handle conditions #3 and #4 above. I feel like a window function might be helpful here, but I don't know quite how to implement it.</p>
<p>If someone could help me with this query, I would be incredibly grateful!</p>
<p>Thanks!</p>
|
[
{
"answer_id": 74527126,
"author": "gbellmann",
"author_id": 3465108,
"author_profile": "https://Stackoverflow.com/users/3465108",
"pm_score": 3,
"selected": true,
"text": "SELECT\n DISTINCT(o.user_id),\n o.email\nFROM orders o\nWHERE\n (\n -- Clause 1\n (o.segment = 'luxury' AND o.destination = 'New York')\n OR\n -- Clause 2\n (o.segment = 'luxury' AND o.destination = 'London')\n OR\n -- Clause 3\n (o.user_id IN (\n SELECT DISTINCT(o.user_id)\n FROM orders o\n WHERE o.segment = 'basic' AND o.destination = 'New York'\n GROUP BY o.user_id, o.email, o.segment, o.destination\n HAVING SUM(o.revenue) > 2000\n ))\n )\n AND\n -- Clause 4\n o.user_id NOT IN (\n SELECT DISTINCT(o.user_id)\n FROM orders o\n WHERE o.destination = 'Miami'\n )\n \n"
},
{
"answer_id": 74527221,
"author": "JHH",
"author_id": 20127235,
"author_profile": "https://Stackoverflow.com/users/20127235",
"pm_score": 1,
"selected": false,
"text": "group by having SELECT user_id, email,\n SUM(case\n when segment='luxury' and destination in ('New York','London') then 1 \n else 0 \n end) as is_luxury,\n SUM(case\n when segment='basic' and destination in ('New York') then 1\n else 0\n end) as is_basic, \n SUM(case\n when segment='basic' and destination in ('New York') then revenue\n else 0\n end) as basic_revenue,\n SUM(case when destination in ('Miami') then 1 else 0 end) as is_miami\nFROM orders\nGROUP BY 1,2\nHAVING (is_luxury > 0 OR (is_basic > 0 AND basic_revenue > 2000))\n AND NOT is_miami;\n \n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5179643/"
] |
74,527,056
|
<p>I want to return a chain of Promises into a single Promise. I want to know how acheive it.</p>
<pre><code>function xbox(){
let games = "https://api.rawg.io/api/games?key=f648fbbe7d024a9d9b021bbd24cea8b5"
let pages = []
let videogames = []
let play
for(let i = 1; i <= 5; i++){
let response = fetch(games + `&page=${i}`)
pages.push(response)
let game = response.then(res => res.json()).then(data => data.results.map((e) => {
let allgames = {
ID: e.id
}
return allgames
}))
videogames = videogames.concat(game)
play = Promise.all(videogames.flat(1))
}
return play
}
</code></pre>
<p>Output</p>
<p><a href="https://i.stack.imgur.com/iUR9Q.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iUR9Q.png" alt="enter image description here" /></a></p>
<p>Basically my desired output would be a single Promise instead of showing a chain of 5 Promises with 20 results, a single Promise with 100 results.</p>
<p>I appreciate any help with my inquiry!</p>
|
[
{
"answer_id": 74527095,
"author": "CertainPerformance",
"author_id": 9515207,
"author_profile": "https://Stackoverflow.com/users/9515207",
"pm_score": 3,
"selected": true,
"text": "Promise.all return play\n .then(results => results.flat());\n function xbox(){\n let games = \"https://api.rawg.io/api/games?key=f648fbbe7d024a9d9b021bbd24cea8b5\"\n let pages = []\n let videogames = []\n let play\n for(let i = 1; i <= 5; i++){\n let response = fetch(games + `&page=${i}`)\n pages.push(response)\n let game = response.then(res => res.json()).then(data => data.results.map((e) => {\n let allgames = {\n ID: e.id\n }\n return allgames\n }))\n videogames = videogames.concat(game)\n play = Promise.all(videogames.flat(1))\n }\n return play\n .then(results => results.flat());\n}\nxbox().then(console.log); function xbox(){\n const baseUrl = \"https://api.rawg.io/api/games?key=f648fbbe7d024a9d9b021bbd24cea8b5\";\n return Promise.all(Array.from(\n { length: 5 },\n (_, i) => fetch(baseUrl + '&page=' + (i + 1))\n .then(res => res.json())\n .then(data => data.results.map(({ id }) => ({ ID: id })))\n ))\n .then(results => results.flat());\n}\nxbox().then(console.log);"
},
{
"answer_id": 74527125,
"author": "Code Maniac",
"author_id": 9624435,
"author_profile": "https://Stackoverflow.com/users/9624435",
"pm_score": 1,
"selected": false,
"text": "function xbox() {\n let games = \"https://api.rawg.io/api/games?key=f648fbbe7d024a9d9b021bbd24cea8b5\"\n return Promise.all(Array.from({\n length: 5\n }, (a, i) => i + 1).map(v => {\n return fetch(games + `&page=${v}`).then(res => res.json()).then(data => data.results.map((e) => {\n let allgames = {\n ID: e.id\n }\n return allgames\n }))\n }))\n}\n\nxbox().then(d => console.log(d.flat(1)))"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15201746/"
] |
74,527,058
|
<p>I have a <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/Conv2D" rel="nofollow noreferrer"><code>tf.keras.layers.Conv2D</code></a> constructed like so:</p>
<pre class="lang-py prettyprint-override"><code>>>> conv2d_layer = tf.keras.layers.Conv2D(filters=128, kernel_size=(3, 3), strides=2)
</code></pre>
<p>For reference that layer is part of a network where the prior layer is <code>prior_layer = Conv2D(filters=64, kernel_size=(3, 3), strides=2)</code>.</p>
<p>When I call <code>conv2d_layer.get_weights()</code>, it returns a list with two entries:</p>
<pre class="lang-py prettyprint-override"><code>>>> [w.shape for w in conv2d_layer.get_weights()]
[(3, 3, 64, 128), (128,)]
</code></pre>
<p>Why are there two <code>np.ndarray</code>s in <code>conv2d_layer.get_weights()</code>? What are their respective meanings?</p>
|
[
{
"answer_id": 74527095,
"author": "CertainPerformance",
"author_id": 9515207,
"author_profile": "https://Stackoverflow.com/users/9515207",
"pm_score": 3,
"selected": true,
"text": "Promise.all return play\n .then(results => results.flat());\n function xbox(){\n let games = \"https://api.rawg.io/api/games?key=f648fbbe7d024a9d9b021bbd24cea8b5\"\n let pages = []\n let videogames = []\n let play\n for(let i = 1; i <= 5; i++){\n let response = fetch(games + `&page=${i}`)\n pages.push(response)\n let game = response.then(res => res.json()).then(data => data.results.map((e) => {\n let allgames = {\n ID: e.id\n }\n return allgames\n }))\n videogames = videogames.concat(game)\n play = Promise.all(videogames.flat(1))\n }\n return play\n .then(results => results.flat());\n}\nxbox().then(console.log); function xbox(){\n const baseUrl = \"https://api.rawg.io/api/games?key=f648fbbe7d024a9d9b021bbd24cea8b5\";\n return Promise.all(Array.from(\n { length: 5 },\n (_, i) => fetch(baseUrl + '&page=' + (i + 1))\n .then(res => res.json())\n .then(data => data.results.map(({ id }) => ({ ID: id })))\n ))\n .then(results => results.flat());\n}\nxbox().then(console.log);"
},
{
"answer_id": 74527125,
"author": "Code Maniac",
"author_id": 9624435,
"author_profile": "https://Stackoverflow.com/users/9624435",
"pm_score": 1,
"selected": false,
"text": "function xbox() {\n let games = \"https://api.rawg.io/api/games?key=f648fbbe7d024a9d9b021bbd24cea8b5\"\n return Promise.all(Array.from({\n length: 5\n }, (a, i) => i + 1).map(v => {\n return fetch(games + `&page=${v}`).then(res => res.json()).then(data => data.results.map((e) => {\n let allgames = {\n ID: e.id\n }\n return allgames\n }))\n }))\n}\n\nxbox().then(d => console.log(d.flat(1)))"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11163122/"
] |
74,527,076
|
<p>I'm looking for a way to draw a special shape like in the picture using Css3. Any idea or drawing way to draw that shape using Css3?</p>
<img src="https://i.stack.imgur.com/uK3R7.png" width="300">
<p>I have referenced several ways but it just draws into a normal triangle.</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>#shape {
width: 0;
height: 0;
border-left: 72px solid transparent;
border-right: 0px solid transparent;
border-bottom: 72px solid red;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="shape"></div></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74527679,
"author": "Junaid Shaikh",
"author_id": 17033432,
"author_profile": "https://Stackoverflow.com/users/17033432",
"pm_score": 0,
"selected": false,
"text": "#shape{\n width: 100px;\n height: 100px;\n border-left: 0px solid transparent;\n border-top: 0px solid transparent;\n border-right: 1px solid blue;\n border-bottom:1px solid blue; \n border-bottom-right-radius: 25px;\n position: relative;\n overflow: hidden;\n}\n#shape::after{\n content:\"\";\n position: absolute;\n background-color: blue;\n width: 1px;\n height: 150%;\n bottom: 0;\n transform-origin: bottom;\n transform: rotateZ(45deg);\n} <div id=\"shape\"></div>"
},
{
"answer_id": 74527767,
"author": "Stacks Queue",
"author_id": 14820590,
"author_profile": "https://Stackoverflow.com/users/14820590",
"pm_score": 2,
"selected": true,
"text": "border-bottom-right-radius #shape border-left #shape {\n width: 0;\n border-left: 72px solid white;\n border-right: 0px solid transparent;\n border-bottom: 72px solid red;\n border-bottom-right-radius: 20px;\n} <div id=\"shape\"></div>"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17443697/"
] |
74,527,084
|
<p>I tried to install pyplot using 'pip install pyplot' in command prompt while it was installing by mistake i closed command prompt then again i am trying to install pyplot using the same command but it was not installing.Can anyone guide me how to install pyplot<a href="https://i.stack.imgur.com/gs9RZ.png" rel="nofollow noreferrer">Kindly find the error in this image</a></p>
<p>error rectification in installing pyplot</p>
|
[
{
"answer_id": 74527649,
"author": "Dat Le",
"author_id": 20568538,
"author_profile": "https://Stackoverflow.com/users/20568538",
"pm_score": 0,
"selected": false,
"text": "from matplotlib import pyplot\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20281849/"
] |
74,527,114
|
<p>In python, we can use such code to fetch all pixels under mask:</p>
<pre><code>src_img = cv2.imread("xxx")
mask = src_img > 50
fetch = src_img[mask]
</code></pre>
<p>what we get is a ndarray including all pixels matching condition mask. How to implement the same function using C++opencv ?</p>
<p>I've found that <code>copyTo</code> can select pixels under specified mask, but it can only copy those pixels to another <code>Mat</code> instead of what python did.</p>
|
[
{
"answer_id": 74527570,
"author": "stateMachine",
"author_id": 12728244,
"author_profile": "https://Stackoverflow.com/users/12728244",
"pm_score": 2,
"selected": false,
"text": "C++ std::vector // Read the input image:\nstd::string imageName = \"D://opencvImages//grayDog.png\";\ncv::Mat inputImage = cv::imread( imageName );\n\n// Convert BGR to Gray:\ncv::Mat grayImage;\ncv::cvtColor( inputImage, grayImage, cv::COLOR_RGB2GRAY );\n\ncv::Mat mask;\nint thresholdValue = 50;\ncv::threshold( grayImage, mask, thresholdValue, 255, cv::THRESH_BINARY );\n cv::Mat 255 0 mask = src_img > 50 cv::Mat // Create grayscale mask:\ncv::Mat output;\ngrayImage.copyTo( output, mask );\n // Locate the non-zero pixel values:\nstd::vector< cv::Point > pixelLocations;\ncv::findNonZero( output, pixelLocations );\n std::vector cv::Point // Extract each pixel value using its location:\nstd::vector< int > pixelValues;\nint totalPoints = (int)pixelLocations.size();\n\nfor( int i = 0; i < totalPoints; i++ ){\n // Get pixel location:\n cv::Point currentPoint = pixelLocations[i];\n\n // Get pixel value:\n int currentPixel = (int)grayImage.at<uchar>( currentPoint );\n pixelValues.push_back( currentPixel );\n\n // Print info:\n std::cout<<\"i: \"<<i<<\" currentPoint: \"<<currentPoint<<\" pixelValue: \"<<currentPixel<<std::endl;\n}\n pixelValues std::vector"
},
{
"answer_id": 74541814,
"author": "fana",
"author_id": 18362054,
"author_profile": "https://Stackoverflow.com/users/18362054",
"pm_score": 1,
"selected": false,
"text": "cv::Mat Img = ... //Where, this Img is 8UC1\n\n// * In this sample, extract the pixel positions\nstd::vector< cv::Point > ResultData;\n\nconst unsigned char Thresh = 50;\nfor( int y=0; y<Img.rows; ++y )\n{\n const unsigned char *p = Img.ptr<unsigned char>(y);\n for( int x=0; x<Img.cols; ++x, ++p )\n {\n if( *p > Thresh )\n {//Here, pick up this pixel's info you want.\n ResultData.emplace_back( x,y );\n }\n }\n}\n Mask cv::Mat Img = ... //Where, this Img is 8UC1\ncv::Mat Mask = ...; //Same size as Img, 8UC1\n\nstd::vector< unsigned char > ResultData; //collect pixel values\nfor( int y=0; y<Img.rows; ++y )\n{\n const unsigned char *p = Img.ptr<unsigned char>(y);\n const unsigned char *m = Mask.ptr<unsigned char>(y);\n for( int x=0; x<Img.cols; ++x, ++p, ++m )\n {\n if( *m ){ ResultData.push_back( *p ); }\n }\n}\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11090070/"
] |
74,527,120
|
<p>I've initialized the variable I wanted, but after adding it's values through a switch case, I cannot return it. Is there any solutions?`</p>
<pre><code>
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Masukkan nilai a = ");
int a = input.nextInt();
System.out.print("Masukkan nilai b = ");
int b = input.nextInt();
System.out.print("Mau diapain bang angkanya? ");
String o = input.next();
int hasil;
switch (o) {
case "+":
hasil = a + b;
break;
case "-":
hasil = a - b;
break;
case "*":
hasil = a * b;
break;
case "/":
hasil = a / b;
break;
default:
System.out.println("Operator tidak valid");
}
// Error is here, stating that I haven't initialized the variable
System.out.println(hasil);
}
}
</code></pre>
<p>`</p>
<p>I've tried putting the console out in each of the case, and it did worked. So, is my first way of doing it is not working?</p>
|
[
{
"answer_id": 74527270,
"author": "Tan Sang",
"author_id": 10297961,
"author_profile": "https://Stackoverflow.com/users/10297961",
"pm_score": 0,
"selected": false,
"text": "int hasil = 0; default default:\n hasil = 0;\n System.out.println(\"Operator tidak valid\");\n"
},
{
"answer_id": 74527287,
"author": "shanuka_payoe",
"author_id": 15604508,
"author_profile": "https://Stackoverflow.com/users/15604508",
"pm_score": 1,
"selected": false,
"text": "int hasil = 0;"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14210020/"
] |
74,527,131
|
<p>I need to push 1 item to array and save it to mongo if that item is not existed in array.</p>
<p>Sample: I have a record with an array</p>
<pre><code>{
_id: ObjectId('xxxxx'),
userEmails: [
{
email: 'xxx@gmail.com,
addedAt: ISODate('xxx')
}
]
}
</code></pre>
<p>Current query:</p>
<pre><code>db.users.updateOne(
{ _id: ObjectId('xxxxx') },
{
$push: {
userEmails: {
email: 'xxx@gmail.com',
addedAt: new Date(),
}
}
}
);
</code></pre>
<p>I expect if <code>xxx@gmail.com</code> is existed, it shouldn't pushed to array. I don't want array have duplicated items</p>
|
[
{
"answer_id": 74535423,
"author": "Dhaval Italiya",
"author_id": 12600501,
"author_profile": "https://Stackoverflow.com/users/12600501",
"pm_score": 2,
"selected": true,
"text": "db.users.updateOne(\n{ _id: ObjectId('xxxxx'),\"userEmails.email\":{$ne: \"xxx@gmail.com\"} },\n{\n $push: {\n userEmails: {\n email: 'xxx@gmail.com',\n addedAt: new Date(),\n }\n }\n});\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10787160/"
] |
74,527,145
|
<pre><code>System.out.println("Enter the Account no :");//in my main class
int accNo=sc.nextInt();
switch(n)
{
case 1 ->{
Account ac=nbank.searchAccount(accNo);//account is my other class
if(ac!=null)
{
System.out.println("Enter the Amount to Deposite :");
double amt=sc.nextDouble();
List<Trans> tr=nbank.deposite(accNo,amt);//Trans is also class and I created the list for this class and Trans contains the following below methods
System.out.println("AccNo :"+tr.getAccNo()+" TransID :"+tr.getTransId()+" type: "+tr.getType()+" Amount :"+tr.getWithAmt()+" Status :"+tr.getStatus()+" Date :"+tr.getDate());
</code></pre>
<p>From the withdraw method, I'm getting a list, but somehow I can't print the list contents using LinkedList. For every method it shows method not found. Class I made are as Trans(getter and setter), bank as logic.</p>
<p>How do I print the list for the above programs using LinkedList?</p>
<pre><code>List<Trans> withdraw(int accNo,double amt)//in my bank class where i'm implementing the logic and trying to store to other classes.
</code></pre>
<p>Here my intention is to view the withdraw the transaction done by the customer in my main():</p>
<pre><code>{
List<Trans> tr=new LinkedList<Trans>();
Account ac=searchAccount(accNo);
if(ac instanceof FDAccount)
tr=((FDAccount)ac).withdraw(amt);
else if(ac instanceof Account)
tr=ac.withdraw(amt);
return tr;
}
</code></pre>
<p>This is my withdraw method that is called by <code>List<Trans> tr=nbank.withdraw(accNo,amt);</code></p>
<pre><code>UserUI.java:189: error: cannot find symbol
System.out.println("AccNo :"+tr.getAccNo()+" TransID :"+tr.getTransId()+" type: "+tr.getType()+" Amount :"+tr.getDepAmt()+" Status :"+tr.getStatus()+" Date :"+tr.getDate());
^
symbol: method getAccNo()
location: variable tr of type List<Trans>
UserUI.java:189: error: cannot find symbol`
</code></pre>
<p>Error like this etc.</p>
|
[
{
"answer_id": 74527178,
"author": "xlm",
"author_id": 885922,
"author_profile": "https://Stackoverflow.com/users/885922",
"pm_score": 1,
"selected": false,
"text": "tr List withdraw getAccNo Trans List tr.get(0).getAccNo()\n Trans for (Trans tran : tr) {\n System.out.println(\"AccNo :\"+tran.getAccNo()+\" TransID :\"+tran.getTransId()+\" type: \"+tran.getType()+\" Amount :\"+tran.getWithAmt()+\" Status :\"+tran.getStatus()+\" Date :\"+tran.getDate());\n}\n"
},
{
"answer_id": 74527216,
"author": "OneDev",
"author_id": 17781856,
"author_profile": "https://Stackoverflow.com/users/17781856",
"pm_score": 0,
"selected": false,
"text": "//indexed loop\nfor (int i = 0; i < tr.size(); i++) {\n System.out.println(\"AccNo :\"+tr.get(i).getAccNo()+\" TransID :\"+tr.get(i).getTransId()+\" type: \"+tr.get(i).getType()+\" Amount :\"+tr.get(i).getWithAmt()+\" Status :\"+tr.get(i).getStatus()+\" Date :\"+tr.get(i).getDate());\n}\n //foreach loop\nfor (Trans trans: tr) {\n System.out.println(\"AccNo :\"+trans.getAccNo()+\" TransID :\"+trans.getTransId()+\" type: \"+trans.getType()+\" Amount :\"+trans.getWithAmt()+\" Status :\"+trans.getStatus()+\" Date :\"+trans.getDate());\n}\n for (Trans trans: tr) {\n if (accNo.equals(trans.getAccNo())) {\n System.out.println(\"AccNo :\"+trans.getAccNo()+\" TransID :\"+trans.getTransId()+\" type: \"+trans.getType()+\" Amount :\"+trans.getWithAmt()+\" Status :\"+trans.getStatus()+\" Date :\"+trans.getDate());\n }\n}\n"
},
{
"answer_id": 74527224,
"author": "Hoร ng Nguyแป
n",
"author_id": 9003926,
"author_profile": "https://Stackoverflow.com/users/9003926",
"pm_score": 1,
"selected": false,
"text": "for loop foreach tr.getAcNo()"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17282548/"
] |
74,527,151
|
<pre><code>// splashscreen.h
class SplashScreen : public QMainWindow
{
Q_OBJECT
public:
explicit SplashScreen(QWidget *parent = nullptr);
~SplashScreen();
QTimer *mtimer;
public slots:
void update();
private:
Ui_SplashScreen *ui;
};
</code></pre>
<hr />
<pre><code>// app.h
#include "splashscreen.h"
class App: public QMainWindow
{
Q_OBJECT
public:
App(QWidget *parent = nullptr);
~App();
SplashScreen s;
private:
Ui::AppClass ui;
};
</code></pre>
<hr />
<pre><code>// app.cpp
App::App(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
QGraphicsOpacityEffect* eff = new QGraphicsOpacityEffect();
s.centralWidget()->setGraphicsEffect(eff);
QPropertyAnimation* a = new QPropertyAnimation(eff, "opacity");
a->setDuration(2000);
a->setStartValue(0);
a->setEndValue(1);
a->start(QPropertyAnimation::DeleteWhenStopped);
s.show();
connect(a, &QAbstractAnimation::finished, this, [this]
{
auto *timer = new QTimer();
this->s.mtimer = timer;
QObject::connect(timer, SIGNAL(timeout()), this->s, SLOT(update()));
timer->start(100);
});
}
</code></pre>
<hr />
<p>I'm getting an error at this line: <code>QObject::connect(timer, SIGNAL(timeout()), this->s, SLOT(update()));</code></p>
<p><code>no instance of overloaded function "QObject::connect" matches the argument list</code></p>
<p><a href="https://i.stack.imgur.com/Mpd3w.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Mpd3w.png" alt="enter image description here" /></a></p>
<p>I think it's mismatching the class signal, as <code>this</code> passed to the lambda refers to <code>App</code> not <code>SplashScreen</code>.</p>
<p>When i try to pass <code>s</code> (SplashScreen) to the lambda:</p>
<pre class="lang-cpp prettyprint-override"><code>connect(a, &QAbstractAnimation::finished, this, [s]
{ ... }
</code></pre>
<p>I get an error: <code>App::s</code> is not a variable.</p>
<p>I'm confused, what is the proper way to connect in this case?</p>
|
[
{
"answer_id": 74529712,
"author": "Andrew",
"author_id": 10609288,
"author_profile": "https://Stackoverflow.com/users/10609288",
"pm_score": 0,
"selected": false,
"text": "QObject::connect(timer, &QTimer::timeout, this, &SplashScreen::update);\n"
},
{
"answer_id": 74534935,
"author": "tunglt",
"author_id": 10320907,
"author_profile": "https://Stackoverflow.com/users/10320907",
"pm_score": 2,
"selected": true,
"text": "QObject::connect(timer, &QTimer::timeout, &s, &SplashScreen::update);\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19324589/"
] |
74,527,241
|
<p>I am using Datadog to track user activity in my app. Now I need to instrument webviews. After <a href="https://docs.datadoghq.com/real_user_monitoring/android/?tab=kotlin#configuration" rel="nofollow noreferrer">initializing datadog's sdk </a>, its documentation says that I have to call the following code snippet:</p>
<p><code>DatadogEventBridge.setup(webView)</code></p>
<p>that is, I have to call the static method <strong>setup</strong> and pass to it a WebView object. But the problem is: my application has many objects like this (many webviews). Do I have to put this code in every class that has a WebView attribute? Or is it possible in somehow use a callback function which is called whenever a webview is instatiated, the in this callback I'd call DatadogEventBridge.setup(webView)?</p>
<p>I tried using lifecycle callbacks and then receive an Acitivty for every "onResume" method in order to check whether this activity has a webview. But it went wrong.</p>
|
[
{
"answer_id": 74529712,
"author": "Andrew",
"author_id": 10609288,
"author_profile": "https://Stackoverflow.com/users/10609288",
"pm_score": 0,
"selected": false,
"text": "QObject::connect(timer, &QTimer::timeout, this, &SplashScreen::update);\n"
},
{
"answer_id": 74534935,
"author": "tunglt",
"author_id": 10320907,
"author_profile": "https://Stackoverflow.com/users/10320907",
"pm_score": 2,
"selected": true,
"text": "QObject::connect(timer, &QTimer::timeout, &s, &SplashScreen::update);\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12772017/"
] |
74,527,264
|
<p>I have <code>product serializer</code> which return <code>category_offer_price</code> & <code>product_offer_price</code>,
before getting this response I want to compare both price and only return whichever is highest price.</p>
<p>#Serilaizer.py</p>
<pre><code>class ProductSerializer(ModelSerializer):
category = CategorySerializer()
product_offer_price = SerializerMethodField()
category_offer_price = SerializerMethodField()
class Meta:
model = Products
fields = [
"id",
"product_name",
"slug",
"category",
"description",
"category_offer_price",
"product_offer_price",
"base_price",
"stock",
"is_available",
"created_date",
"images",
"images_two",
"images_three",
]
def get_product_offer_price(self, obj):
try:
product_offer = ProductOffer.objects.get(product=obj)
if product_offer.is_active:
offer_price = product_offer.product_offer_price()
return offer_price
except Exception:
pass
return None
def get_category_offer_price(self, obj):
try:
category_offer = CategoryOffer.objects.get(category=obj.category)
if category_offer.is_active:
offer_price = category_offer.category_offer_price(obj)
return offer_price
except Exception:
pass
return None
</code></pre>
<p>#Models.py</p>
<pre><code>class Products(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
product_name = models.CharField(max_length=50, unique=True)
slug = models.SlugField(max_length=100, unique=True)
description = models.TextField(max_length=500)
base_price = models.IntegerField()
images = models.ImageField(upload_to="photos/products")
images_two = models.ImageField(upload_to="photos/products")
images_three = models.ImageField(upload_to="photos/products")
stock = models.IntegerField()
is_available = models.BooleanField(default=True)
created_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now=True)
class Meta:
verbose_name_plural = "Products"
def __str__(self):
return self.product_name
</code></pre>
<p>I'd like to know is it possible to compare serializer fields in a serializer class?</p>
|
[
{
"answer_id": 74527415,
"author": "Niko",
"author_id": 7100120,
"author_profile": "https://Stackoverflow.com/users/7100120",
"pm_score": 3,
"selected": true,
"text": "from django.shortcuts import get_object_or_404\n\nclass ProductSerializer(ModelSerializer):\n category = CategorySerializer()\n price = SerializerMethodField()\n\n class Meta:\n model = Products\n fields = '__all__'\n\n def get_price(self, obj):\n product_offer = get_object_or_404(ProductOffer, product=obj)\n category_offer = get_object_or_404(CategoryOffer, category=obj.category)\n\n if product_offer.is_active and category_offer.is_active:\n if product_offer.product_offer_price() > category_offer.category_offer_price(obj):\n return product_offer.product_offer_price()\n else:\n return category_offer.category_offer_price(obj)\n\n elif product_offer.is_active and not category_offer.is_active:\n return product_offer.product_offer_price()\n\n elif category_offer.is_active and not product_offer.is_active:\n return category_offer.category_offer_price(obj)\n class ProductSerializer(ModelSerializer):\n category = CategorySerializer()\n price = SerializerMethodField()\n\n class Meta:\n model = Products\n fields = '__all__'\n\n def get_price(self, obj):\n try:\n product_offer = ProductOffer.objects.filter(product=obj).first()\n category_offer = CategoryOffer.objects.filter(category=obj.category).first()\n \n if not product_offer and not category_offer:\n return obj.base_price \n elif not category_offer: \n return product_offer.product_offer_price() \n elif not product_offer:\n return category_offer.category_offer_price(obj) \n elif category_offer and product_offer:\n if category_offer.is_active and not product_offer.is_active:\n return category_offer.category_offer_price(obj) \n elif product_offer.is_active and not category_offer.is_active:\n return product_offer.product_offer_price() \n elif category_offer.is_active and product_offer.is_active:\n if category_offer.category_offer_price(obj) > product_offer.product_offer_price():\n return category_offer.category_offer_price(obj)\n else:\n return product_offer.product_offer_price()\n except:\n return obj.base_price\n"
},
{
"answer_id": 74527596,
"author": "ilyasbbu",
"author_id": 16475089,
"author_profile": "https://Stackoverflow.com/users/16475089",
"pm_score": 2,
"selected": false,
"text": "to_representation() class ProductSerializer(ModelSerializer):\n category = CategorySerializer()\n product_offer_price = SerializerMethodField()\n category_offer_price = SerializerMethodField()\n\n ...\n\n ...\n def to_representation(self, instance):\n data = super().to_representation(instance)\n # access required fields like this\n product_offer_price = data['product_offer_price']\n category_offer_price = data['category_offer_price']\n\n # do calculations here and returning the desired field as `calculated_price`\n if category_offer_price > product_offer_price:\n data['calculated_price'] = category_offer_price\n else:\n data['calculated_price'] = product_offer_price\n return data\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16853253/"
] |
74,527,290
|
<p>Hey can anyone help me here
I'm supposed to get a number count for each letter used in this string here using for loops and if statement.</p>
<p>quote= "I watched in awe as I saw her swim across the ocean"</p>
<p>The pseudocode given is this:</p>
<pre><code>for every letter in the alphabet list:
Create a variable to store the frequency of each letter in the string and assign it an initial value of zero
for every letter in the given string:
if the letter in the string is the same as the letter in the alphabet list
increase the value of the frequency variable by one.
if the value of the frequency variable does not equal zero:
print the letter in the alphabet list followed by a colon and the value of the frequency variable
</code></pre>
<p>This is what i've got so far but i cannot for the life of me figure it out.</p>
<pre><code>quote = "I watched in awe as I saw her swim across the ocean."
xquote= quote.lower()
print(xquote)
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"]
for i in alphabet:
c_alphabet= {"a": 0, "b":0, "c":0, "d":0,"e":0,"f":0,"g":0,"h":0,"i":0,"j":0,"k":0,"l":0,"m":0,"n":0,"o":0,"p":0,"q":0,"r":0,"s":0,"t":0,"u":0,"v":0,"w":0,"x":0,"y":0,"z":0}
for i in xquote:
if i == alphabet:
c_alphabet[i]+=1
print(c_alphabet)
</code></pre>
<p>I don't get an error message but I just can't seem to be able to get a total number of individual letters in the string.</p>
<p>I'd like it to output some thing like this c_alphabet = {"a": 3, "b":1, "c": 2...)</p>
|
[
{
"answer_id": 74527415,
"author": "Niko",
"author_id": 7100120,
"author_profile": "https://Stackoverflow.com/users/7100120",
"pm_score": 3,
"selected": true,
"text": "from django.shortcuts import get_object_or_404\n\nclass ProductSerializer(ModelSerializer):\n category = CategorySerializer()\n price = SerializerMethodField()\n\n class Meta:\n model = Products\n fields = '__all__'\n\n def get_price(self, obj):\n product_offer = get_object_or_404(ProductOffer, product=obj)\n category_offer = get_object_or_404(CategoryOffer, category=obj.category)\n\n if product_offer.is_active and category_offer.is_active:\n if product_offer.product_offer_price() > category_offer.category_offer_price(obj):\n return product_offer.product_offer_price()\n else:\n return category_offer.category_offer_price(obj)\n\n elif product_offer.is_active and not category_offer.is_active:\n return product_offer.product_offer_price()\n\n elif category_offer.is_active and not product_offer.is_active:\n return category_offer.category_offer_price(obj)\n class ProductSerializer(ModelSerializer):\n category = CategorySerializer()\n price = SerializerMethodField()\n\n class Meta:\n model = Products\n fields = '__all__'\n\n def get_price(self, obj):\n try:\n product_offer = ProductOffer.objects.filter(product=obj).first()\n category_offer = CategoryOffer.objects.filter(category=obj.category).first()\n \n if not product_offer and not category_offer:\n return obj.base_price \n elif not category_offer: \n return product_offer.product_offer_price() \n elif not product_offer:\n return category_offer.category_offer_price(obj) \n elif category_offer and product_offer:\n if category_offer.is_active and not product_offer.is_active:\n return category_offer.category_offer_price(obj) \n elif product_offer.is_active and not category_offer.is_active:\n return product_offer.product_offer_price() \n elif category_offer.is_active and product_offer.is_active:\n if category_offer.category_offer_price(obj) > product_offer.product_offer_price():\n return category_offer.category_offer_price(obj)\n else:\n return product_offer.product_offer_price()\n except:\n return obj.base_price\n"
},
{
"answer_id": 74527596,
"author": "ilyasbbu",
"author_id": 16475089,
"author_profile": "https://Stackoverflow.com/users/16475089",
"pm_score": 2,
"selected": false,
"text": "to_representation() class ProductSerializer(ModelSerializer):\n category = CategorySerializer()\n product_offer_price = SerializerMethodField()\n category_offer_price = SerializerMethodField()\n\n ...\n\n ...\n def to_representation(self, instance):\n data = super().to_representation(instance)\n # access required fields like this\n product_offer_price = data['product_offer_price']\n category_offer_price = data['category_offer_price']\n\n # do calculations here and returning the desired field as `calculated_price`\n if category_offer_price > product_offer_price:\n data['calculated_price'] = category_offer_price\n else:\n data['calculated_price'] = product_offer_price\n return data\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20568470/"
] |
74,527,301
|
<p>In C (let's say C11 if we need to specific), is the following program well-defined? Will it always print <code>a=3 b=4</code> or could compiler optimizations affect the output?</p>
<p>(The real-world motivation is to provide a read-only public "view" of a struct that is only supposed to be modified by a particular module, i.e. source file.)</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
struct obj_private {
int a;
int b;
};
struct obj_public {
const int a;
const int b;
};
int main(void) {
void *mem = calloc(1, sizeof(struct obj_private));
struct obj_private *priv = mem;
struct obj_public *pub = mem;
priv->a = 3;
priv->b = 4;
printf("a=%d b=%d\n", pub->a, pub->b);
return 0;
}
</code></pre>
|
[
{
"answer_id": 74527323,
"author": "dbush",
"author_id": 1687119,
"author_profile": "https://Stackoverflow.com/users/1687119",
"pm_score": 3,
"selected": true,
"text": "const struct obj_private *priv = mem;\nconst struct obj_private *pub = mem;\n"
},
{
"answer_id": 74566101,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": -1,
"selected": false,
"text": "-fstrict-aliasing void test_write(void *p)\n{\n struct foo { int x; };\n struct foo *pp = p;\n pp->x = 1;\n}\nstruct foo { int x; };\nint test_write_and_read(struct foo *p, int i, int j)\n{\n p[i].x = 2;\n return p[j].x;\n}\nstruct foo foo_arr[4];\nint test(int i)\n{\n test_write_and_read(foo_arr, 0, 1);\n test_write(foo_arr+i);\n return test_write_and_read(foo_arr, 1, 0);\n}\nint (*volatile vtest)(int) = test;\n#include <stdio.h>\nint main(void)\n{\n int result = vtest(0);\n printf(\"%d %d\\n\", result, foo_arr[0].x);\n\n}\n struct foo struct foo pp->x test_write() foo_arr[j].x test() foo_arr+j"
},
{
"answer_id": 74574210,
"author": "Lundin",
"author_id": 584518,
"author_profile": "https://Stackoverflow.com/users/584518",
"pm_score": -1,
"selected": false,
"text": "void *mem = calloc(1, sizeof(struct obj_private)); mem priv->a = 3; a int int priv->a int b pub->a const int int pub->a const int"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4086593/"
] |
74,527,325
|
<p>I have this data.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Code</th>
<th>Beg. date</th>
<th>End date</th>
<th>Class</th>
</tr>
</thead>
<tbody>
<tr>
<td>54</td>
<td>01/03/2021</td>
<td>10/10/2020</td>
<td>166</td>
</tr>
<tr>
<td>54</td>
<td>11/10/2021</td>
<td>31/12/9999</td>
<td>322</td>
</tr>
<tr>
<td>102</td>
<td>10/04/2020</td>
<td>31/08/2021</td>
<td>180</td>
</tr>
<tr>
<td>102</td>
<td>01/09/2021</td>
<td>30/06/2022</td>
<td>190</td>
</tr>
<tr>
<td>102</td>
<td>01/07/2022</td>
<td>31/12/9999</td>
<td>200</td>
</tr>
</tbody>
</table>
</div>
<p>And i need to find de class of this range</p>
<pre><code>102 | 01/05/2021 | 31/05/2021
</code></pre>
<p>The answer is 190 because is within the fourth range in the data.But i need to know how to make this kind of Vlookup to match with approximate dates and the code as a second condition.
I tried to use Vlookup and Match but didnt get result for the inmediate superior value.</p>
<p>Hope you can help me.</p>
<p>I tried to concatenate Code with Beg. Date and use VlookUp and AND but haven't have success.</p>
|
[
{
"answer_id": 74527323,
"author": "dbush",
"author_id": 1687119,
"author_profile": "https://Stackoverflow.com/users/1687119",
"pm_score": 3,
"selected": true,
"text": "const struct obj_private *priv = mem;\nconst struct obj_private *pub = mem;\n"
},
{
"answer_id": 74566101,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": -1,
"selected": false,
"text": "-fstrict-aliasing void test_write(void *p)\n{\n struct foo { int x; };\n struct foo *pp = p;\n pp->x = 1;\n}\nstruct foo { int x; };\nint test_write_and_read(struct foo *p, int i, int j)\n{\n p[i].x = 2;\n return p[j].x;\n}\nstruct foo foo_arr[4];\nint test(int i)\n{\n test_write_and_read(foo_arr, 0, 1);\n test_write(foo_arr+i);\n return test_write_and_read(foo_arr, 1, 0);\n}\nint (*volatile vtest)(int) = test;\n#include <stdio.h>\nint main(void)\n{\n int result = vtest(0);\n printf(\"%d %d\\n\", result, foo_arr[0].x);\n\n}\n struct foo struct foo pp->x test_write() foo_arr[j].x test() foo_arr+j"
},
{
"answer_id": 74574210,
"author": "Lundin",
"author_id": 584518,
"author_profile": "https://Stackoverflow.com/users/584518",
"pm_score": -1,
"selected": false,
"text": "void *mem = calloc(1, sizeof(struct obj_private)); mem priv->a = 3; a int int priv->a int b pub->a const int int pub->a const int"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14727908/"
] |
74,527,327
|
<p>I have code like the following:</p>
<pre class="lang-rust prettyprint-override"><code>enum Either<L, R> {
Left(L),
Right(R)
}
enum SomeMessageType {
// ...
}
fn do_something<T>() {
let data: Vec<Either<T, SomeMessageType>> = ...;
// ...
}
</code></pre>
<p>I want to be able to iterate over the contents of <code>data</code> without explicitly specifying the <code>Either</code> types, because having to specify the <code>Either</code> everywhere makes the API ugly and annoying to work with. The generic type <code>T</code> in <code>do_something</code> will always be an enum variant, I just don't know if it's possible to express that in Rust's generic types. Ideally, I'd like to be able to write something like:</p>
<pre class="lang-rust prettyprint-override"><code>fn do_something<...>() {
let data = ...;
matching_iterator!(data, {
SomeMessageType::... => ...
T::SomeVariant => ...
});
}
</code></pre>
<p>I have tried writing a macro like this already:</p>
<pre class="lang-rust prettyprint-override"><code>#[macro_export]
macro_rules! check_mail {
( $data:expr, { $( $pattern:pat => $handler:block )+ } ) => {
{
use $crate::build_pattern;
for data in $data.iter() {
if let $crate::build_pattern!($( $pattern )+) = message {
$( $handler )+
}
}
}
}
};
}
#[macro_export]
macro_rules! build_pattern {
( $pattern:pat ) => {
Either::Right($pattern)
};
( $pattern:pat ) => {
Either::Left($pattern)
};
}
</code></pre>
<p>but obviously this code won't compile, much less run. My intuition says I should put a differentiator of some sort at the start of each pattern, to make it easier to write the macro, but I haven't been able to get that to work. Each attempt generates the match arm code wrong, with all the matches at the start and then all the handler blocks at the end, and I'm not sure why.</p>
|
[
{
"answer_id": 74529868,
"author": "cafce25",
"author_id": 442760,
"author_profile": "https://Stackoverflow.com/users/442760",
"pm_score": 2,
"selected": true,
"text": "Left Right ; fn do_something() {\n use Either::*;\n let data = vec![Right(T::SomeVariant), Left(SomeMessageType::Good)];\n matching_iterator!(data,\n SomeMessageType::Good => {}\n ;\n T::SomeVariant => {}\n T::SomeOtherVariant => {}\n );\n}\n\n#[macro_export]\nmacro_rules! matching_iterator {\n ( $data:expr, $($lpattern:pat => $lhandler:block)+; $($rpattern:pat => $rhandler:block)+ ) => {\n {\n for data in $data.iter() {\n match data {\n $(Either::Left($lpattern) => $lhandler)+\n $(Either::Right($rpattern) => $rhandler)+\n }\n }\n }\n };\n}\n"
},
{
"answer_id": 74531954,
"author": "val",
"author_id": 1794051,
"author_profile": "https://Stackoverflow.com/users/1794051",
"pm_score": 0,
"selected": false,
"text": "fn do_something<T, F, H>(f: F, h: H)\n where F: Fn(T) -> (),\n H: Fn(SomeMessageType) -> ()\n{\n let data = ...;\n data.for_each(|either| {\n match either {\n Either::Left(t) => f(t),\n Either::Right(r) => h(r),\n }\n })\n}\n do_something(\n |t| { match t { MyEnum::Some => ... }}, \n |msg| { println!(\"I received this message: {}\", msg); }\n);\n Either do_something"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527327",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7876637/"
] |
74,527,344
|
<p>I have a problem. I want to create a calculated column call ExpectedOutcome .</p>
<p>The value of column ExpectedOutcome for 1st row where No.Session = 1 is calculated by Score + 60.
From the second row, the value of ExpectedOutcome = previous ExpectedOutcome + Score.</p>
<p>The value of ExpectedOutcome is always in the range of 0 - 100. If it < 0, then we put 0 as the value. If it > 100, then we put 100 as the value.</p>
<p>It seems like calculate a running total, but it is not. And I do not know how to solve this problem.
<img src="https://i.stack.imgur.com/TRLyV.png" alt="enter image description here" /></p>
<p><img src="https://i.stack.imgur.com/3VljQ.png" alt="The database only has 3 columns named id, No.Session, Score" /></p>
|
[
{
"answer_id": 74529868,
"author": "cafce25",
"author_id": 442760,
"author_profile": "https://Stackoverflow.com/users/442760",
"pm_score": 2,
"selected": true,
"text": "Left Right ; fn do_something() {\n use Either::*;\n let data = vec![Right(T::SomeVariant), Left(SomeMessageType::Good)];\n matching_iterator!(data,\n SomeMessageType::Good => {}\n ;\n T::SomeVariant => {}\n T::SomeOtherVariant => {}\n );\n}\n\n#[macro_export]\nmacro_rules! matching_iterator {\n ( $data:expr, $($lpattern:pat => $lhandler:block)+; $($rpattern:pat => $rhandler:block)+ ) => {\n {\n for data in $data.iter() {\n match data {\n $(Either::Left($lpattern) => $lhandler)+\n $(Either::Right($rpattern) => $rhandler)+\n }\n }\n }\n };\n}\n"
},
{
"answer_id": 74531954,
"author": "val",
"author_id": 1794051,
"author_profile": "https://Stackoverflow.com/users/1794051",
"pm_score": 0,
"selected": false,
"text": "fn do_something<T, F, H>(f: F, h: H)\n where F: Fn(T) -> (),\n H: Fn(SomeMessageType) -> ()\n{\n let data = ...;\n data.for_each(|either| {\n match either {\n Either::Left(t) => f(t),\n Either::Right(r) => h(r),\n }\n })\n}\n do_something(\n |t| { match t { MyEnum::Some => ... }}, \n |msg| { println!(\"I received this message: {}\", msg); }\n);\n Either do_something"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20568420/"
] |
74,527,369
|
<br/>
Im having a small concern if we can access a value inside a value.
<p>Eg:<br/>
myDict = {1:"Hey", 2:"Bye,1,2,3,4"}</p>
<p>As in the example above..<br/>
How can I print/access the value 4 in myDict?? Is it possible with indexing??<br/>
Eg: 4 # Printing 4 from myDict
<br/><br/>
Thanks.</p>
|
[
{
"answer_id": 74529868,
"author": "cafce25",
"author_id": 442760,
"author_profile": "https://Stackoverflow.com/users/442760",
"pm_score": 2,
"selected": true,
"text": "Left Right ; fn do_something() {\n use Either::*;\n let data = vec![Right(T::SomeVariant), Left(SomeMessageType::Good)];\n matching_iterator!(data,\n SomeMessageType::Good => {}\n ;\n T::SomeVariant => {}\n T::SomeOtherVariant => {}\n );\n}\n\n#[macro_export]\nmacro_rules! matching_iterator {\n ( $data:expr, $($lpattern:pat => $lhandler:block)+; $($rpattern:pat => $rhandler:block)+ ) => {\n {\n for data in $data.iter() {\n match data {\n $(Either::Left($lpattern) => $lhandler)+\n $(Either::Right($rpattern) => $rhandler)+\n }\n }\n }\n };\n}\n"
},
{
"answer_id": 74531954,
"author": "val",
"author_id": 1794051,
"author_profile": "https://Stackoverflow.com/users/1794051",
"pm_score": 0,
"selected": false,
"text": "fn do_something<T, F, H>(f: F, h: H)\n where F: Fn(T) -> (),\n H: Fn(SomeMessageType) -> ()\n{\n let data = ...;\n data.for_each(|either| {\n match either {\n Either::Left(t) => f(t),\n Either::Right(r) => h(r),\n }\n })\n}\n do_something(\n |t| { match t { MyEnum::Some => ... }}, \n |msg| { println!(\"I received this message: {}\", msg); }\n);\n Either do_something"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18299392/"
] |
74,527,384
|
<p>how to solved this issue? when im trying to install mongo compass
<a href="https://i.stack.imgur.com/5Lxl7.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>i dont know how to fix this issue</p>
|
[
{
"answer_id": 74529868,
"author": "cafce25",
"author_id": 442760,
"author_profile": "https://Stackoverflow.com/users/442760",
"pm_score": 2,
"selected": true,
"text": "Left Right ; fn do_something() {\n use Either::*;\n let data = vec![Right(T::SomeVariant), Left(SomeMessageType::Good)];\n matching_iterator!(data,\n SomeMessageType::Good => {}\n ;\n T::SomeVariant => {}\n T::SomeOtherVariant => {}\n );\n}\n\n#[macro_export]\nmacro_rules! matching_iterator {\n ( $data:expr, $($lpattern:pat => $lhandler:block)+; $($rpattern:pat => $rhandler:block)+ ) => {\n {\n for data in $data.iter() {\n match data {\n $(Either::Left($lpattern) => $lhandler)+\n $(Either::Right($rpattern) => $rhandler)+\n }\n }\n }\n };\n}\n"
},
{
"answer_id": 74531954,
"author": "val",
"author_id": 1794051,
"author_profile": "https://Stackoverflow.com/users/1794051",
"pm_score": 0,
"selected": false,
"text": "fn do_something<T, F, H>(f: F, h: H)\n where F: Fn(T) -> (),\n H: Fn(SomeMessageType) -> ()\n{\n let data = ...;\n data.for_each(|either| {\n match either {\n Either::Left(t) => f(t),\n Either::Right(r) => h(r),\n }\n })\n}\n do_something(\n |t| { match t { MyEnum::Some => ... }}, \n |msg| { println!(\"I received this message: {}\", msg); }\n);\n Either do_something"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20568608/"
] |
74,527,393
|
<p><br>I have the following layout for my report:<br>
<a href="https://i.stack.imgur.com/aQNiu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aQNiu.png" alt="enter image description here" /></a></p>
<p>where Cost is my dimension measure field calculated for each year at column level for different Products.<br>
Now I need to add the Year field as one of the columns, which is naturally separating the records into different rows like this:<br>
<a href="https://i.stack.imgur.com/KAKkg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KAKkg.png" alt="enter image description here" /></a></p>
<p>Is there a way that I can have the Year column without splitting my records into separate rows?</p>
|
[
{
"answer_id": 74529868,
"author": "cafce25",
"author_id": 442760,
"author_profile": "https://Stackoverflow.com/users/442760",
"pm_score": 2,
"selected": true,
"text": "Left Right ; fn do_something() {\n use Either::*;\n let data = vec![Right(T::SomeVariant), Left(SomeMessageType::Good)];\n matching_iterator!(data,\n SomeMessageType::Good => {}\n ;\n T::SomeVariant => {}\n T::SomeOtherVariant => {}\n );\n}\n\n#[macro_export]\nmacro_rules! matching_iterator {\n ( $data:expr, $($lpattern:pat => $lhandler:block)+; $($rpattern:pat => $rhandler:block)+ ) => {\n {\n for data in $data.iter() {\n match data {\n $(Either::Left($lpattern) => $lhandler)+\n $(Either::Right($rpattern) => $rhandler)+\n }\n }\n }\n };\n}\n"
},
{
"answer_id": 74531954,
"author": "val",
"author_id": 1794051,
"author_profile": "https://Stackoverflow.com/users/1794051",
"pm_score": 0,
"selected": false,
"text": "fn do_something<T, F, H>(f: F, h: H)\n where F: Fn(T) -> (),\n H: Fn(SomeMessageType) -> ()\n{\n let data = ...;\n data.for_each(|either| {\n match either {\n Either::Left(t) => f(t),\n Either::Right(r) => h(r),\n }\n })\n}\n do_something(\n |t| { match t { MyEnum::Some => ... }}, \n |msg| { println!(\"I received this message: {}\", msg); }\n);\n Either do_something"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9055800/"
] |
74,527,395
|
<p>I have just started exploring Cypress and came across such a problem:</p>
<p><strong>Is it possible to select/ or set a value in a dropdown box</strong>?, when <strong>there is no select tag in the html code</strong></p>
<p>The data (options) are from a global variables in react.</p>
<p>For example lets take this simple piece of code</p>
<pre class="lang-html prettyprint-override"><code><div class="row simulation_config">
<div class="required form-group"><label for="cc_w02qmy5l5" class="">currency</label>
<div class="Select css-b62m3t-container"><span id="react-select-4-live-region" class="css-1f43avz-a11yText-A11yText"></span><span aria-live="polite" aria-atomic="false" aria-relevant="additions text" class="css-1f43avz-a11yText-A11yText"></span>
<div class="Select__control css-1s2u09g-control">
<div class="Select__value-container css-319lph-ValueContainer">
<div class="Select__placeholder css-14el2xx-placeholder" id="react-select-4-placeholder">Select...</div>
<div class="Select__input-container css-6j8wv5-Input" data-value=""><input class="Select__input" autocapitalize="none" autocomplete="off" autocorrect="off" id="cc_w02qmy5l5" spellcheck="false" tabindex="0" type="text" aria-autocomplete="list" aria-expanded="false" aria-haspopup="true" role="combobox" value="" style="color: inherit; background: 0px center; opacity: 1; width: 100%; grid-area: 1 / 2 / auto / auto; font: inherit; min-width: 2px; border: 0px; margin: 0px; outline: 0px; padding: 0px;"></div>
</div>
<div class="Select__indicators css-1hb7zxy-IndicatorsContainer">
<div class="Select__indicator Select__dropdown-indicator css-tlfecz-indicatorContainer" aria-hidden="true"><span class="connect-icon connect-icon-caret-down"></span></div>
</div>
</div><input name="currency" type="hidden" value="">
</div>
</div>
<div class="required form-group"><label for="cc_s0ibe93kp" class="">inflationRate</label><input id="cc_s0ibe93kp" name="inflationRate" class="form-control dirty" type="text" value="2.3%" inputmode="numeric"></div>
</div>
</code></pre>
<p>How the code looks like in react side:</p>
<pre class="lang-html prettyprint-override"><code><div className="row simulation_config">
<FormSelect
key="input-currency"
name="currency"
label="currency"
required
value={currency}
data={currencies}
onChange={e => {
selectCurrencyHandler(e, setData)
}}
data-cy="currency"
/>
</code></pre>
<p>Here is what I have tried</p>
<pre class="lang-js prettyprint-override"><code>cy.get('.Select__input').first().click().select('USD') // ERROR: cy.select() can only be called on a <select>
cy.get('[name="currency"]').first().focus().type('USD',{ force: true }) // Doesnt show me the value in display
</code></pre>
<p>Example screen shot:</p>
<p><a href="https://i.stack.imgur.com/urSY3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/urSY3.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74529597,
"author": "Alapan Das",
"author_id": 4571271,
"author_profile": "https://Stackoverflow.com/users/4571271",
"pm_score": 0,
"selected": false,
"text": "cy.get('selector').click //Expands the dropdown\ncy.contains('EUR').click() //selects EUR\n"
},
{
"answer_id": 74530208,
"author": "TesterDick",
"author_id": 18366749,
"author_profile": "https://Stackoverflow.com/users/18366749",
"pm_score": 2,
"selected": false,
"text": "data-cy=\"currency\" <div className=\"row simulation_config\"> cy.get('div.row.simulation_config')\n .find('.Select')\n .click() \n\ncy.contains('[id*=\"option\"]', 'USD')\n .click()\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19586543/"
] |
74,527,418
|
<p>I'm trying to use <code>GREATEST()</code> in Snowflake, but whenever I have null values, I get <code>null</code> instead of the desired result:</p>
<pre class="lang-sql prettyprint-override"><code>select greatest(1,2,null);
-- null
</code></pre>
<p>This behavior has confused many, and it begins with the behavior of <code>GREATEST()</code> in Oracle, which Snowflake matches:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/19186283/handling-null-in-greatest-function-in-oracle">Handling Null in Greatest function in Oracle</a></li>
</ul>
<p>It has also being discussed in the Snowflake forums:</p>
<ul>
<li><a href="https://community.snowflake.com/s/question/0D50Z00009LHFw1SAH/greatest-and-null-values" rel="nofollow noreferrer">https://community.snowflake.com/s/question/0D50Z00009LHFw1SAH/greatest-and-null-values</a></li>
</ul>
<p>Sample data:</p>
<pre class="lang-sql prettyprint-override"><code>create or replace table some_nulls
as (
select $1 a, $2 b, $3 c
from values(1.1, 2.3, null::float), (null, 2, 3.5), (1, null, 3), (null, null, null)
);
select greatest(a, b)
from some_nulls;
</code></pre>
<p><a href="https://i.stack.imgur.com/bKaH6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bKaH6.png" alt="enter image description here" /></a></p>
<p>Asking here to get the best available solution.</p>
|
[
{
"answer_id": 74527419,
"author": "Felipe Hoffa",
"author_id": 132438,
"author_profile": "https://Stackoverflow.com/users/132438",
"pm_score": 2,
"selected": false,
"text": "greatest() create or replace function greatest2(x1 float, x2 float)\nreturns float\nas $$\n coalesce(greatest(x1, x2), x1, x2)\n$$;\n\nselect greatest2(a, b)\nfrom some_nulls;\n create or replace function greatest3(x1 float, x2 float, x3 float)\nreturns float\nas $$\n select iff(x='-inf', null, x)\n from (\n select greatest(nvl(x1, '-inf'), nvl(x2, '-inf'), nvl(x3, '-inf')) x\n )\n$$;\n\nselect greatest3(a, b, c)\nfrom some_nulls;\n"
},
{
"answer_id": 74527633,
"author": "Felipe Hoffa",
"author_id": 132438,
"author_profile": "https://Stackoverflow.com/users/132438",
"pm_score": 0,
"selected": false,
"text": "create or replace function greatest_a(arr array)\nreturns float\nimmutable\nas $$\n select max(value::float)\n from table(flatten(arr))\n$$;\n\nselect greatest_a([null,2,3.3])\nfrom some_nulls;\n select greatest_a([a, b, c])\nfrom some_nulls;\n\n-- Unsupported subquery type cannot be evaluated\n"
},
{
"answer_id": 74529349,
"author": "Lukasz Szozda",
"author_id": 5070879,
"author_profile": "https://Stackoverflow.com/users/5070879",
"pm_score": 2,
"selected": false,
"text": "SELECT a,b,c, GREATEST([a],[b],[c])[0]::INT\nFROM some_nulls;\n CREATE OR REPLACE TABLE some_nulls(a INT, b INT, c INT)\nAS\nSELECT 1, 2, NULL UNION\nSELECT NULL, 2, 3 UNION\nSELECT 1, NULL, 3 UNION\nSELECT NULL, NULL, NULL;\n NULL [undefined] GREATEST LEAST"
},
{
"answer_id": 74529742,
"author": "Simeon Pilgrim",
"author_id": 43992,
"author_profile": "https://Stackoverflow.com/users/43992",
"pm_score": 0,
"selected": false,
"text": "NULL select \n a,b,c\n ,greatest(a, b) as g_a_b\n ,greatest(a, c) as g_a_c\n ,greatest(b, c) as g_b_c\nfrom values\n (1.1, 2.3, null::float), \n (null, 2, 3.5), \n (1, null, 3), \n (null, null, null)\n t(a,b,c)\n -inf select a,b,c, max(f.value)\nfrom (\n select \n a,b,c\n ,array_construct_compact(a, b, c) as aa\n from values\n (1.1, 2.3, null), \n (null, 2, 3.5), \n (1, null, 3), \n (null, null, null)\n t(a,b,c)\n), table(flatten(input=>aa)) as f\ngroup by 1,2,3,f.seq\n"
},
{
"answer_id": 74539746,
"author": "Marco Roy",
"author_id": 4406793,
"author_profile": "https://Stackoverflow.com/users/4406793",
"pm_score": 0,
"selected": false,
"text": "GREATEST LEAST -inf NULL NULL WITH test AS (\n SELECT\n column1 AS a,\n column2 AS b,\n column3 AS c,\n column4 AS d\n FROM VALUES\n ('aaa', 'bbb', 'ccc', NULL),\n ('aaa', 'bbb', NULL, 'ccc'),\n ('aaa', NULL, 'bbb', 'ccc'),\n (NULL, 'aaa', 'bbb', 'ccc'),\n (NULL, NULL, NULL, NULL)\n)\nSELECT\n GREATEST(COALESCE(a, b, c, d), COALESCE(b, c, d, a), COALESCE(c, d, a, b), COALESCE(d, a, b, c)) AS _greatest,\n LEAST(COALESCE(a, b, c, d), COALESCE(b, c, d, a), COALESCE(c, d, a, b), COALESCE(d, a, b, c)) AS _least\nFROM test;\n COALESCE COALESCE GREATEST LEAST NULL NULL VARIANT GREATEST2(...) LEAST2(...)"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/132438/"
] |
74,527,422
|
<p>I would like to change the <code>top</code> property value of the <code>Positioned</code> widget according to screen orientation.</p>
<p>I didn't know how to do it.</p>
<p>Can anyone help?</p>
|
[
{
"answer_id": 74527482,
"author": "Jungwon",
"author_id": 15134376,
"author_profile": "https://Stackoverflow.com/users/15134376",
"pm_score": 3,
"selected": true,
"text": "MediaQuery.of(context).orientation Positioned(\n top: MediaQuery.of(context).orientation == Orientation.portrait ? portraitValue : landScapeValue,\nchild: //your code\n);\n"
},
{
"answer_id": 74527725,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 0,
"selected": false,
"text": "OrientationBuilder OrientationBuilder(\n builder: (context, orientation) {\n return Positioned(\n top: orientation == Orientation.portrait ? 10 : 50,\n child: /*...0*/\n );\n },\n),\n 10 50 MediaQuery.of(context).orientation printOrientation() {\n print(MediaQuery.of(context).orientation);\n }\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11878615/"
] |
74,527,424
|
<p>sorry im really new to python</p>
<p>im trying to keep the cursor within a 100x100 box but it doesnt do that, im still able to move it within a t shape spanning the whole screen and not a box in the middle of it.
it seems like its just ignoring 1 of the variables</p>
<p>what this is supposed to do is simply detect if the mouse has left the 100x100 area</p>
<p>the placeholder is simply so i can put somthing there later</p>
<pre><code>pyautogui.moveTo(550,550)
while True:
mos = pyautogui.position()
print(mos[0],mos[1])
if (500 < mos[0] < 600) or (500 < mos[1] < 600) :
pass
else:
print('placeholder')
print('f')
</code></pre>
<p>i've gotten this to work but im still confused why the first version doesnt work</p>
<pre><code>pyautogui.moveTo(550,550)
while True:
mos = pyautogui.position()
print(mos[0],mos[1])
if (500 < mos[0] < 600):
pass
else:
print('placeholder')
print('f')
if (500 < mos[1] < 600):
pass
else:
print('placeholder')
print('f')
</code></pre>
|
[
{
"answer_id": 74527482,
"author": "Jungwon",
"author_id": 15134376,
"author_profile": "https://Stackoverflow.com/users/15134376",
"pm_score": 3,
"selected": true,
"text": "MediaQuery.of(context).orientation Positioned(\n top: MediaQuery.of(context).orientation == Orientation.portrait ? portraitValue : landScapeValue,\nchild: //your code\n);\n"
},
{
"answer_id": 74527725,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 0,
"selected": false,
"text": "OrientationBuilder OrientationBuilder(\n builder: (context, orientation) {\n return Positioned(\n top: orientation == Orientation.portrait ? 10 : 50,\n child: /*...0*/\n );\n },\n),\n 10 50 MediaQuery.of(context).orientation printOrientation() {\n print(MediaQuery.of(context).orientation);\n }\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20568478/"
] |
74,527,429
|
<p>having some issues with my SPL query. The search below is creating a table from AWS cloud trail logs, and is using a lookup file containing AD data. Each row of the table contains login data from AWS like last login and number of logins, Im trying to use the AD lookup to see if the users logging in are still active on this AD file. I do not have an inactive lookup, the only thing I have to go off is that the user will no longer show up on the AD lookup. So that means it will have blanks on the table if the logins do not find a match on the ad lookup. So I want to eval a new status field based off if "identity is null". Iv'e tried base case and if. not getting anything. everything is working find except line 16.</p>
<pre><code>index=aws sourcetype="aws:cloudtrail" eventCategory=Management eventType=AwsConsoleSignin
| stats max(_time) AS last_login count AS logins by userIdentity.arn
| rename userIdentity.arn AS user
| search user="*.com"
| eval temp=split(user,":")
| eval Account_number = mvindex(temp2, 4)
| eval usr =mvindex(temp, 5)
| fields - temp
| eval temp2=split(usr,"/")
| eval role_type=mvindex(temp2,0)
| eval role=mvindex(temp2,1)
| eval user_email=mvindex(temp2,2)
| eval last_login=strftime(last_login,"%c")
| rename user_email AS email
| lookup identity_ad email OUTPUTNEW bunit memberOf identity first last
| eval status=case(identity==null, "inactive", identity!=null "active")
| table status, first, last, identity, email, bunit, role, role_type, logins, last_login
</code></pre>
<p>Everything is returning correctly in the table except the status field which is being calculated on line 16 of the query. In help or a point in the right direction would be greatly appreciated, Thanks.</p>
|
[
{
"answer_id": 74535462,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 0,
"selected": false,
"text": "lookup | rename user_email AS email\n| lookup identity_ad email OUTPUTNEW bunit memberOf identity first last\n| where isnotnull(bunit)\n bunit | where isnull(bunit)\n"
},
{
"answer_id": 74540733,
"author": "RichG",
"author_id": 2227420,
"author_profile": "https://Stackoverflow.com/users/2227420",
"pm_score": 2,
"selected": true,
"text": "isnull isnotnull index=aws sourcetype=\"aws:cloudtrail\" eventCategory=Management eventType=AwsConsoleSignin\n| stats max(_time) AS last_login count AS logins by userIdentity.arn\n| rename userIdentity.arn AS user\n| search user=\"*.com\"\n| eval temp=split(user,\":\")\n| eval Account_number = mvindex(temp2, 4)\n| eval usr =mvindex(temp, 5)\n| fields - temp\n| eval temp2=split(usr,\"/\")\n| eval role_type=mvindex(temp2,0)\n| eval role=mvindex(temp2,1)\n| eval user_email=mvindex(temp2,2)\n| eval last_login=strftime(last_login,\"%c\")\n| rename user_email AS email\n| lookup identity_ad email OUTPUTNEW bunit memberOf identity first last\n| eval status=case(isnull(identity), \"inactive\", isnotnull(identity), \"active\")\n| table status, first, last, identity, email, bunit, role, role_type, logins, last_login\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11762522/"
] |
74,527,452
|
<p>I'm trying to make a button that switchs the mode from light to dark. By default it's light mode, but for some reason, when I switch to dark mode, it works, but it won't switch back to light mode.</p>
<p>Here is the javascript code:</p>
<pre><code>const modeButton = document.getElementById('light-dark-btn');
modeButton.addEventListener('click', ()=> {
if(document.body.style.backgroundColor = 'rgb(255,255,255)'){
document.body.style.backgroundColor = 'rgb(18,18,18)';
document.body.style.color = 'rgb(255,255,255)';
}else if((document.body.style.backgroundColor = 'rgb(18,18,18)')){
document.body.style.backgroundColor = 'rgb(255,255,255)';
document.body.style.color = 'rgb(0,0,0)';
}
})
</code></pre>
<p>I'm trying to make a button that switchs the mode from light to dark.</p>
|
[
{
"answer_id": 74535462,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 0,
"selected": false,
"text": "lookup | rename user_email AS email\n| lookup identity_ad email OUTPUTNEW bunit memberOf identity first last\n| where isnotnull(bunit)\n bunit | where isnull(bunit)\n"
},
{
"answer_id": 74540733,
"author": "RichG",
"author_id": 2227420,
"author_profile": "https://Stackoverflow.com/users/2227420",
"pm_score": 2,
"selected": true,
"text": "isnull isnotnull index=aws sourcetype=\"aws:cloudtrail\" eventCategory=Management eventType=AwsConsoleSignin\n| stats max(_time) AS last_login count AS logins by userIdentity.arn\n| rename userIdentity.arn AS user\n| search user=\"*.com\"\n| eval temp=split(user,\":\")\n| eval Account_number = mvindex(temp2, 4)\n| eval usr =mvindex(temp, 5)\n| fields - temp\n| eval temp2=split(usr,\"/\")\n| eval role_type=mvindex(temp2,0)\n| eval role=mvindex(temp2,1)\n| eval user_email=mvindex(temp2,2)\n| eval last_login=strftime(last_login,\"%c\")\n| rename user_email AS email\n| lookup identity_ad email OUTPUTNEW bunit memberOf identity first last\n| eval status=case(isnull(identity), \"inactive\", isnotnull(identity), \"active\")\n| table status, first, last, identity, email, bunit, role, role_type, logins, last_login\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20487730/"
] |
74,527,469
|
<p>i want to replace string like :</p>
<p>CD7849O => CD18490</p>
<p>so if you find a char in the form of 7 and O, replace them with 1 and 0 (7 => 1, O => 0)</p>
<p>i tried with indexofchar but it's not work</p>
<pre><code>string result = "CD7849O";
string[] charToFind = { "0", "O", "I", "1", "7" };
foreach (string z in charToFind)
{
string charFind = z;
int indexOfChar = result.Trim().IndexOf(charFind);
Console.WriteLine(indexOfChar);
if (indexOfChar >= 0)
{
string y = "XXX";
string x = "XXX";
if (z == "0" && z == "1")
{
y = "O";
x = "I";
}
else if (z == "O" && z == "I")
{
y = "0";
x = "1";
}
else if (z == "O" && z == "7")
{
y = "0";
x = "1";
}
string resultY = result.Trim().Replace(charFind, y);
string resultHasil;
Console.WriteLine(resultY);
}
}
</code></pre>
|
[
{
"answer_id": 74535462,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 0,
"selected": false,
"text": "lookup | rename user_email AS email\n| lookup identity_ad email OUTPUTNEW bunit memberOf identity first last\n| where isnotnull(bunit)\n bunit | where isnull(bunit)\n"
},
{
"answer_id": 74540733,
"author": "RichG",
"author_id": 2227420,
"author_profile": "https://Stackoverflow.com/users/2227420",
"pm_score": 2,
"selected": true,
"text": "isnull isnotnull index=aws sourcetype=\"aws:cloudtrail\" eventCategory=Management eventType=AwsConsoleSignin\n| stats max(_time) AS last_login count AS logins by userIdentity.arn\n| rename userIdentity.arn AS user\n| search user=\"*.com\"\n| eval temp=split(user,\":\")\n| eval Account_number = mvindex(temp2, 4)\n| eval usr =mvindex(temp, 5)\n| fields - temp\n| eval temp2=split(usr,\"/\")\n| eval role_type=mvindex(temp2,0)\n| eval role=mvindex(temp2,1)\n| eval user_email=mvindex(temp2,2)\n| eval last_login=strftime(last_login,\"%c\")\n| rename user_email AS email\n| lookup identity_ad email OUTPUTNEW bunit memberOf identity first last\n| eval status=case(isnull(identity), \"inactive\", isnotnull(identity), \"active\")\n| table status, first, last, identity, email, bunit, role, role_type, logins, last_login\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11070430/"
] |
74,527,506
|
<p>I am trying to create a random set of 25 numbers, which are between 2 and 25, and sum up to 100 in python.</p>
<p><a href="https://stackoverflow.com/questions/70593981/create-a-list-of-n-random-numbers-with-max-and-min-value-and-total-sum">This Question</a> gives an answer, but it seems that the maximum number never ends up being close to 25.</p>
<p>I've tried creating a list, dividing each number, and recreating the list, but it essentially nullifies my min and max values since they end up getting divided by a number larger than 1 almost all of the time:</p>
<pre><code>numbers = np.random.randint(low = 2, high = 25, size = 100, dtype = int)
scale = 100 / sum(numbers) #We want weights to add up to 100%
#Scale values
for value in numbers:
nums.append(value * scale)
</code></pre>
<p>Is there any way to do this? Thanks</p>
|
[
{
"answer_id": 74535462,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 0,
"selected": false,
"text": "lookup | rename user_email AS email\n| lookup identity_ad email OUTPUTNEW bunit memberOf identity first last\n| where isnotnull(bunit)\n bunit | where isnull(bunit)\n"
},
{
"answer_id": 74540733,
"author": "RichG",
"author_id": 2227420,
"author_profile": "https://Stackoverflow.com/users/2227420",
"pm_score": 2,
"selected": true,
"text": "isnull isnotnull index=aws sourcetype=\"aws:cloudtrail\" eventCategory=Management eventType=AwsConsoleSignin\n| stats max(_time) AS last_login count AS logins by userIdentity.arn\n| rename userIdentity.arn AS user\n| search user=\"*.com\"\n| eval temp=split(user,\":\")\n| eval Account_number = mvindex(temp2, 4)\n| eval usr =mvindex(temp, 5)\n| fields - temp\n| eval temp2=split(usr,\"/\")\n| eval role_type=mvindex(temp2,0)\n| eval role=mvindex(temp2,1)\n| eval user_email=mvindex(temp2,2)\n| eval last_login=strftime(last_login,\"%c\")\n| rename user_email AS email\n| lookup identity_ad email OUTPUTNEW bunit memberOf identity first last\n| eval status=case(isnull(identity), \"inactive\", isnotnull(identity), \"active\")\n| table status, first, last, identity, email, bunit, role, role_type, logins, last_login\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20252795/"
] |
74,527,527
|
<p>My problem is that I need to take an inputted integer and return the prime factorization of it. It needs to be in the form of:</p>
<pre class="lang-none prettyprint-override"><code>int * int * int * int
</code></pre>
<p>For example, the prime factorization of 180 would return:</p>
<pre class="lang-none prettyprint-override"><code>2 * 2 * 3 * 3 * 5.
</code></pre>
<p>The code I have currently is:</p>
<pre class="lang-java prettyprint-override"><code>public static String factor(int n)
{
String str = "";
if(isPrime(n)) {
str = "" + n;
}else if(n == 2) {
str = "2";
}else{
for (int i = 2; i <= Math.sqrt(n); i++)
{
while (n % i == 0)
{
str = str + i;
}
}
}
return str;
}
</code></pre>
<p>The <code>isPrime</code> method mentioned is:</p>
<pre class="lang-java prettyprint-override"><code>public static boolean isPrime(int n)
{
if (n <= 1) {
return false;
}
for (int i = 2; i <= n/2; i++)
{
if (n % i == 0) {
return false;
}
}
return true;
}
</code></pre>
|
[
{
"answer_id": 74527674,
"author": "phatfingers",
"author_id": 1031887,
"author_profile": "https://Stackoverflow.com/users/1031887",
"pm_score": 2,
"selected": true,
"text": "n while (n % i == 0) {\n str += (str.equals(\"\") ? i : \" * \" + i);\n n /= i;\n}\n"
},
{
"answer_id": 74527951,
"author": "Syed Asad Manzoor",
"author_id": 20477563,
"author_profile": "https://Stackoverflow.com/users/20477563",
"pm_score": 1,
"selected": false,
"text": "public static void main(String[] args) throws IOException\n {\n System.out.println(factor(24));\n}\n public static String factor(int n)\n {\n String str = \"\";\n String multiplySymbol = \"\";\n if(isPrime(n)) {\n str = \"\" + n;\n }else if(n == 2) {\n str = \"2\";\n }else{\n for (int i = 2; i <= n; i++)\n {\n while (n % i == 0)\n {\n str += multiplySymbol+i ;\n multiplySymbol = \"x\";\n n /= i;\n }\n }\n }\n return str;\n }\n \n public static boolean isPrime(int n)\n {\n if (n <= 1) {\n return false;\n }\n for (int i = 2; i <= n/2; i++)\n {\n if (n % i == 0) {\n return false;\n }\n }\n return true;\n }\n \n}\n"
},
{
"answer_id": 74530100,
"author": "rossum",
"author_id": 820127,
"author_profile": "https://Stackoverflow.com/users/820127",
"pm_score": 0,
"selected": false,
"text": "// primeArray holds the previously calculated prime factors.\nfunction printPrimes(primeArray)\n separator โ \" * \"\n atFirst โ true\n\n foreach thisPrime in primeArray\n if (atFirst)\n // No separator before first prime.\n atFirst โ false\n else\n // Put separator before all the other primes.\n print(separator)\n end if\n\n // Print the number.\n print(thisPrime)\n end foreach\nend function\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20146539/"
] |
74,527,557
|
<p>I'm supposed to be outputting a report in a window. I created a method for the table and header, but when I run the program they're outputting to separate windows. I know I need to create another method to display the report, but I can't figure out what the right formals are.</p>
<p>Here's what I have and what it's supposed to look like:</p>
<p><a href="https://i.stack.imgur.com/QY1TP.png" rel="nofollow noreferrer">enter image description here</a></p>
<pre><code>import java.text.*;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class Main
{
static String name, address, city, state;
static int zip, month, date, year, code;
static double amount = 0, rate = 0;
public static void main(String[] args)
{
InputFile loanInfo;
loanInfo = new InputFile("fcrc loan data.txt");
JFrame jf;
JTextArea jta;
JScrollPane jsp;
jf = new JFrame();
jta = new JTextArea();
jsp = new JScrollPane(jta);
jf.setSize(1200, 350);
jf.setLocation(400, 250);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(jsp);
jf.setVisible(true);
while (!loanInfo.eof())
{
name = loanInfo.readString();
address = loanInfo.readString();
city = loanInfo.readString();
state = loanInfo.readWord();
zip = loanInfo.readInt();
month = loanInfo.readInt();
date = loanInfo.readInt();
year = loanInfo.readInt();
amount = loanInfo.readDouble();
rate = loanInfo.readDouble();
code = loanInfo.readInt();
displayReport();
/*I know this is probably where the issue is. I just don't know what the appropriate formals are to finish the method*/
}
}
public static void displayReport()
{
displayHeading(name, address, city, state, zip, month, date, year, amount, code, rate);
displayTable(amount);
}
public static void displayTable(double amount)
{
int paymentNumber;
double payment = 0, interest, principal, balance;
JFrame jf;
JTextArea jta;
JScrollPane jsp;
jf = new JFrame();
jta = new JTextArea();
jsp = new JScrollPane(jta);
jf.setSize(1200, 350);
jf.setLocation(400, 250);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(jsp);
jf.setVisible(true);
DecimalFormat numFormat;
numFormat = new DecimalFormat("0.00");
NumberFormat currencyFormat;
currencyFormat = NumberFormat.getCurrencyInstance();
balance = amount;
paymentNumber = 0;
double totalPayment = 0;
double totalIntPaid = 0;
while (balance > 0)
{
++paymentNumber;
String dueDate = calcDueDate(month, date, year, paymentNumber - 1);
interest = calcInterest(balance, rate);
if (balance <= payment)
{
payment = balance;
principal = balance;
balance = 0;
} else
{
payment = calcPayment(code, amount);
principal = calcPrincipal(payment, interest);
balance = calcBalance(balance, principal);
}
totalPayment = totalPayment + payment;
totalIntPaid = totalIntPaid + interest;
jta.append(paymentNumber + "\t\t" + dueDate + "\t\t$" + numFormat.format(payment) + "\t\t" + currencyFormat.format(interest) + "\t\t" + currencyFormat.format(principal) + "\t\t" + currencyFormat.format(balance) + "\n");
}
jta.append("\n");
jta.append(" " + "\t\t" + " " + "\t\t" + "Totals: " + currencyFormat.format(totalPayment) + "\t" + currencyFormat.format(totalIntPaid) + "\n");
jta.append("\n\n");
}
public static void displayHeading(String name, String address1, String city, String state, int zip, int month, int day, int year, double amount, int code, double rate)
{
DecimalFormat numFormat;
numFormat = new DecimalFormat("0.00");
NumberFormat currencyFormat;
currencyFormat = NumberFormat.getCurrencyInstance();
JFrame jf;
JTextArea jta;
JScrollPane jsp;
jf = new JFrame();
jta = new JTextArea();
jsp = new JScrollPane(jta);
jf.setSize(1200, 350);
jf.setLocation(400, 250);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(jsp);
jf.setVisible(true);
jta.append("First Community Redevelopment Corporation\n");
jta.append("101 1st Street\n");
jta.append("Bloomington, TN 41663\n");
jta.append("\n");
jta.append("\t\t\t\t" + name + "\n");
jta.append("\t\t\t\t" + address1 + "\n");
jta.append("\t\t\t\t" + city + ", " + state + ", " + zip + "\n");
jta.append("\n");
jta.append("LOAN AMOUNT:\t\t" + currencyFormat.format(amount) + "\n");
jta.append("INTEREST RATE:\t\t" + numFormat.format(rate) + "%\n");
jta.append("\n");
jta.append("Payment #\tDue Date\t\tPayment\t\tInterest\tPrincipal\tBalance\n");
jta.append("---------------------------------------------------------------------------------------------------\n");
}
public static double calcPayment(int code, double amount)
{
double payment;
payment = 0;
switch (code)
{
case 0:
payment = 50.00;
break;
case 1:
payment = 55.00;
break;
case 2:
payment = 75.00;
break;
case 3:
payment = 100.00;
break;
case 4:
payment = .05 * amount;
break;
case 5:
payment = .06 * amount;
break;
case 6:
payment = .05 * amount;
break;
case 7:
payment = .04 * amount;
break;
case 8:
payment = .03 * amount;
break;
case 9:
payment = .02 * amount;
break;
default:
System.out.println("Bad payment code");
}
return payment;
}
public static double calcInterest(double balance, double rate)
{
double interest;
interest = rate / 12 * balance;
return interest;
}
public static double calcPrincipal(double payment, double interest)
{
double principal;
principal = payment - interest;
return principal;
}
public static double calcBalance(double balance, double principal)
{
balance -= principal;
return balance;
}
public static String calcDueDate(int month, int day, int year, int payNum)
{
String monthStr = "";
month = month + payNum - 1;
year = year + (month / 12);
month = month % 12;
if (month == 0)
{
year--;
}
switch (month)
{
case 1:
monthStr = "Jan.";
break;
case 2:
monthStr = "Feb.";
break;
case 3:
monthStr = "Mar.";
break;
case 4:
monthStr = "Apr.";
break;
case 5:
monthStr = "May";
break;
case 6:
monthStr = "Jun.";
break;
case 7:
monthStr = "Jul.";
break;
case 8:
monthStr = "Aug.";
break;
case 9:
monthStr = "Sept.";
break;
case 10:
monthStr = "Oct.";
break;
case 11:
monthStr = "Nov.";
break;
case 0:
monthStr = "Dec.";
break;
default:
System.out.println("Invalid month: " + month);
}
return monthStr + " " + day + ", " + year;
}
}
</code></pre>
|
[
{
"answer_id": 74527674,
"author": "phatfingers",
"author_id": 1031887,
"author_profile": "https://Stackoverflow.com/users/1031887",
"pm_score": 2,
"selected": true,
"text": "n while (n % i == 0) {\n str += (str.equals(\"\") ? i : \" * \" + i);\n n /= i;\n}\n"
},
{
"answer_id": 74527951,
"author": "Syed Asad Manzoor",
"author_id": 20477563,
"author_profile": "https://Stackoverflow.com/users/20477563",
"pm_score": 1,
"selected": false,
"text": "public static void main(String[] args) throws IOException\n {\n System.out.println(factor(24));\n}\n public static String factor(int n)\n {\n String str = \"\";\n String multiplySymbol = \"\";\n if(isPrime(n)) {\n str = \"\" + n;\n }else if(n == 2) {\n str = \"2\";\n }else{\n for (int i = 2; i <= n; i++)\n {\n while (n % i == 0)\n {\n str += multiplySymbol+i ;\n multiplySymbol = \"x\";\n n /= i;\n }\n }\n }\n return str;\n }\n \n public static boolean isPrime(int n)\n {\n if (n <= 1) {\n return false;\n }\n for (int i = 2; i <= n/2; i++)\n {\n if (n % i == 0) {\n return false;\n }\n }\n return true;\n }\n \n}\n"
},
{
"answer_id": 74530100,
"author": "rossum",
"author_id": 820127,
"author_profile": "https://Stackoverflow.com/users/820127",
"pm_score": 0,
"selected": false,
"text": "// primeArray holds the previously calculated prime factors.\nfunction printPrimes(primeArray)\n separator โ \" * \"\n atFirst โ true\n\n foreach thisPrime in primeArray\n if (atFirst)\n // No separator before first prime.\n atFirst โ false\n else\n // Put separator before all the other primes.\n print(separator)\n end if\n\n // Print the number.\n print(thisPrime)\n end foreach\nend function\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20559901/"
] |
74,527,597
|
<p>I'm automating a web page with selenium-java where there's a checkbox with tri-state. The HTML is this:</p>
<pre><code><input data-qa-anchor="field#includeDeletedPosts" class="self-center w-5 h-5" type="checkbox" name="includeDeletedPosts">
</code></pre>
<p>I want to create a method like this:</p>
<pre><code>public void selectIncludeDeletedPosts(boolean isChecked) {
if (isChecked) {
if (!getDriver().findElement(INCLUDEDELETEDCHECKBOX).isSelected()) {
getDriver().findElement(INCLUDEDELETEDCHECKBOX).click();
} else {
getDriver().findElement(INCLUDEDELETEDCHECKBOX).click();
getDriver().findElement(INCLUDEDELETEDCHECKBOX).click();
}
}
}
</code></pre>
<p>Since it's a tri-state checkbox - there's an intermediate state where the checkbox is neither selected or unchecked. Hence, I can't use the following as isSelected can be used mainly for the regular bi-state checkboxes:</p>
<pre><code>getDriver().findElement(By.name("includeDeletedPosts").isSelected
</code></pre>
<p>Basically I want to create one method that can handle all the states of the checkbox.</p>
<p>From here: <a href="https://css-tricks.com/indeterminate-checkboxes/" rel="nofollow noreferrer">https://css-tricks.com/indeterminate-checkboxes/</a> - I found out that "You canโt make a checkbox indeterminate through HTML. There is no indeterminate attribute. It is a property of checkboxes though, which you can change via JavaScript."</p>
<p>Hence, I was thinking if there's any way we can use javascript executer here.</p>
<p>Any help here would be highly appreciated.</p>
|
[
{
"answer_id": 74536071,
"author": "BeToast",
"author_id": 15271076,
"author_profile": "https://Stackoverflow.com/users/15271076",
"pm_score": 2,
"selected": true,
"text": "JavascriptExecutor js = (JavascriptExecutor)getDriver();\nObject obj = js.executeScript(\"return document.getElementsByName('includeDeletedPosts')[0].indeterminate\");\n"
},
{
"answer_id": 74540457,
"author": "Noor Yeaser Khan",
"author_id": 8391555,
"author_profile": "https://Stackoverflow.com/users/8391555",
"pm_score": 0,
"selected": false,
"text": "public QueryPostPage setIncludeDeletedPost(CheckboxStatus checkboxStatus) {\n JavascriptExecutor js = (JavascriptExecutor) getDriver();\n Object isIndeterminate = js.executeScript(\"return document.getElementsByName('includeDeletedPosts')[0].indeterminate\");\n switch (checkboxStatus) {\n case CHECKED:\n if (isIndeterminate.equals(true)) {\n selectIncludeDeletedPost();\n break;\n } else if (!waitAndReturnElementIfDisplayed(INCLUDEDELETEDCHECKBOX).isSelected()) {\n clickOnElementRepeatedly(INCLUDEDELETEDCHECKBOX,2);\n break;\n }\n case UNCHECKED:\n if (isIndeterminate.equals(true)) {\n clickOnElementRepeatedly(INCLUDEDELETEDCHECKBOX,2);\n break;\n } else if (waitAndReturnElementIfDisplayed(INCLUDEDELETEDCHECKBOX).isSelected()) {\n selectIncludeDeletedPost();\n break;\n }\n case UNDEFINED:\n if (waitAndReturnElementIfDisplayed(INCLUDEDELETEDCHECKBOX).isSelected()) {\n clickOnElementRepeatedly(INCLUDEDELETEDCHECKBOX,2);\n } else {\n selectIncludeDeletedPost();\n }\n break;\n }\n return this;\n }\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8391555/"
] |
74,527,628
|
<pre><code>import java.util.*;
class SeriesSum
{
int x,n,i,j,k,s=1;
double f=0.0;
void accept()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the value of x and n");
x=sc.nextInt();
n=sc.nextInt();
}
void compute()
{
for(i=2;i<=n;i=i+2)
{
for(j=1;j<n;j++)
{
for(k=1;k<=j;j++)
{
s=s*k;
}
f=f+((Math.pow(x,i))/s);
}
}
System.out.println("Sum of series :"+f);
}
public static void main()
{
SeriesSum ob=new SeriesSum();
ob.accept();
ob.compute();
}
}
</code></pre>
<p>Well this is the code to find the sum of this series: (x ^ 2)/(1!) + (x ^ 4)/(3!) + (x ^ 6)/(5!) + (x ^ n)/((n - 1)!)</p>
<p>The only problem is that it's taking unlimited input</p>
<p>What should I do</p>
|
[
{
"answer_id": 74536071,
"author": "BeToast",
"author_id": 15271076,
"author_profile": "https://Stackoverflow.com/users/15271076",
"pm_score": 2,
"selected": true,
"text": "JavascriptExecutor js = (JavascriptExecutor)getDriver();\nObject obj = js.executeScript(\"return document.getElementsByName('includeDeletedPosts')[0].indeterminate\");\n"
},
{
"answer_id": 74540457,
"author": "Noor Yeaser Khan",
"author_id": 8391555,
"author_profile": "https://Stackoverflow.com/users/8391555",
"pm_score": 0,
"selected": false,
"text": "public QueryPostPage setIncludeDeletedPost(CheckboxStatus checkboxStatus) {\n JavascriptExecutor js = (JavascriptExecutor) getDriver();\n Object isIndeterminate = js.executeScript(\"return document.getElementsByName('includeDeletedPosts')[0].indeterminate\");\n switch (checkboxStatus) {\n case CHECKED:\n if (isIndeterminate.equals(true)) {\n selectIncludeDeletedPost();\n break;\n } else if (!waitAndReturnElementIfDisplayed(INCLUDEDELETEDCHECKBOX).isSelected()) {\n clickOnElementRepeatedly(INCLUDEDELETEDCHECKBOX,2);\n break;\n }\n case UNCHECKED:\n if (isIndeterminate.equals(true)) {\n clickOnElementRepeatedly(INCLUDEDELETEDCHECKBOX,2);\n break;\n } else if (waitAndReturnElementIfDisplayed(INCLUDEDELETEDCHECKBOX).isSelected()) {\n selectIncludeDeletedPost();\n break;\n }\n case UNDEFINED:\n if (waitAndReturnElementIfDisplayed(INCLUDEDELETEDCHECKBOX).isSelected()) {\n clickOnElementRepeatedly(INCLUDEDELETEDCHECKBOX,2);\n } else {\n selectIncludeDeletedPost();\n }\n break;\n }\n return this;\n }\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19886834/"
] |
74,527,667
|
<p>Thanks! Those suggestions are great. Now how would I make it if the display is style="display:none" for each column to have each column not take up blank space and just disappear altogether? When I currently attempt to do it, it still shows the space being taken up.
I'm struggling to make this collapse when not being used.</p>
<pre><code><script>function hawks() {
var x = document.getElementById("hawksSalary");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
} {
var hawks = document.getElementById("AtlantaHawks");
if (x.style.display === "block") {
hawks.style.backgroundColor = "red";
} else {
hawks.style.backgroundColor = "white";
}
}
}
</script>
<script>
function nets() {
var x = document.getElementById("netsSalary");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
} {
var nets = document.getElementById("BrooklynNets");
if (x.style.display === "block") {
nets.style.backgroundColor = "red";
} else {
nets.style.backgroundColor = "white";
}
}
}
</script>
<script>function celtics() {
var x = document.getElementById("celticsSalary");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
} {
var celtics = document.getElementById("BostonCeltics");
if (x.style.display === "block") {
celtics.style.backgroundColor = "red";
} else {
celtics.style.backgroundColor = "white";
}
}
}
</script>
<style>
.row {
display: flex;
}
.row > * {
flex: 0 0 25vw;
}}</style>
<center><header><h2>NBA Trade Maker</h2></center>
<nav>
<center>
<table>
<tr>
<th>Atlantic Division</th>
<th>Central Division</th>
<th>Southeast Division</th>
<th>Northwest Division</th>
<th>Southwest Division</th>
<th>Pacific Division</th>
</tr>
<tr>
<td id="BostonCeltics" onclick="celtics()">Boston Celtics</td>
<td>Chicago Bulls</td>
<td id="AtlantaHawks" onclick="hawks()">Atlanta Hawks</td>
<td>Denver Nuggets</td>
<td>Dallas Mavericks</td>
<td>Golden State Warriors</td>
</tr>
<tr>
<td id="BrooklynNets" onclick="nets()">Brooklyn Nets</td>
<td>Cleveland Cavaliers</td>
<td>Charlotte Hornets</td>
<td>Minnesota Timberwolves</td>
<td>Houston Rockets</td>
<td>Los Angeles Clippers</td>
</tr>
<tr>
<td id="NYKnicks" onclick="knicks()">New York Knicks</td>
<td>Detroit Pistons</td>
<td>Miami Heat</td>
<td>Oklahoma City Thunder</td>
<td>Memphis Grizzlies</td>
<td>Los Angeles Lakers</td>
</tr>
<tr>
<td>Philadelphia 76ers</td>
<td>Indiana Pacers</td>
<td>Orlando Magic</td>
<td>Portland Trail Blazers</td>
<td>New Orleans Pelicans</td>
<td>Phoenix Suns</td>
</tr>
<tr>
<td>Toronto Raptors</td>
<td>Milwaukee Bucks</td>
<td>Washington Wizards</td>
<td>Utah Jazz</td>
<td>San Antonio Spurs</td>
<td>Sacramento Kings</td>
</tr>
</table>
</center>
<br>
<br>
<br>
<div class="row">
<div class="column">
<div id="hawksSalary" style="display:none"><h2>Atlanta Hawks</h2>
<p>Trae Young (Salary Here) Send To:
<select>
<option value="Audi">Audi</option>
<option value="BMW">BMW</option>
<option value="Mercedes">Mercedes</option>
<option value="Volvo">Volvo</option>
</select></p></div>
</div>
<div class="column">
<p id="traeYoungToCeltics" style="display:none">Trae Young</p>
<div id="celticsSalary" style="display:none"><h2>Boston Celtics</h2>
<p>Some text..</p></div>
</div>
<div class="column">
<div id="netsSalary" style="display:none"><h2>Column 3</h2>
<p>Some text..</p></div>
</div>
<div class="column">
<h2>Column 4</h2>
<p>Some text..</p>
</div>
<div class="column">
<h2>Column 5</h2>
<p>Some text..</p>
</div>
<div class="column">
<h2>Column 6</h2>
<p>Some text..</p>
</div>
<div class="column">
<h2>Column 7</h2>
<p>Some text..</p>
</div>
<div class="column">
<h2>Column 8</h2>
<p>Some text..</p>
</div>
</div>
</code></pre>
|
[
{
"answer_id": 74536071,
"author": "BeToast",
"author_id": 15271076,
"author_profile": "https://Stackoverflow.com/users/15271076",
"pm_score": 2,
"selected": true,
"text": "JavascriptExecutor js = (JavascriptExecutor)getDriver();\nObject obj = js.executeScript(\"return document.getElementsByName('includeDeletedPosts')[0].indeterminate\");\n"
},
{
"answer_id": 74540457,
"author": "Noor Yeaser Khan",
"author_id": 8391555,
"author_profile": "https://Stackoverflow.com/users/8391555",
"pm_score": 0,
"selected": false,
"text": "public QueryPostPage setIncludeDeletedPost(CheckboxStatus checkboxStatus) {\n JavascriptExecutor js = (JavascriptExecutor) getDriver();\n Object isIndeterminate = js.executeScript(\"return document.getElementsByName('includeDeletedPosts')[0].indeterminate\");\n switch (checkboxStatus) {\n case CHECKED:\n if (isIndeterminate.equals(true)) {\n selectIncludeDeletedPost();\n break;\n } else if (!waitAndReturnElementIfDisplayed(INCLUDEDELETEDCHECKBOX).isSelected()) {\n clickOnElementRepeatedly(INCLUDEDELETEDCHECKBOX,2);\n break;\n }\n case UNCHECKED:\n if (isIndeterminate.equals(true)) {\n clickOnElementRepeatedly(INCLUDEDELETEDCHECKBOX,2);\n break;\n } else if (waitAndReturnElementIfDisplayed(INCLUDEDELETEDCHECKBOX).isSelected()) {\n selectIncludeDeletedPost();\n break;\n }\n case UNDEFINED:\n if (waitAndReturnElementIfDisplayed(INCLUDEDELETEDCHECKBOX).isSelected()) {\n clickOnElementRepeatedly(INCLUDEDELETEDCHECKBOX,2);\n } else {\n selectIncludeDeletedPost();\n }\n break;\n }\n return this;\n }\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20568203/"
] |
74,527,672
|
<p>Not too sure why but I have run into an issue. Essentially, I have a button in one VC which opens an action sheet. Once a user chooses a picture from their library or takes a photo and chooses that, I wanted to navigate away from that VC, onto a new VC to display that picture chosen. However, I run into this issue at the bottom. It works when everything is in one VC, but I am assuming I am not passing the image correctly. Can anyone have a look, and suggest ways to make this work? Thanks!</p>
<p><em>Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value</em></p>
<pre><code>func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let moreDetail = storyboard.instantiateViewController(identifier: "AddPostViewController") as! AddPostViewController
picker.dismiss(animated: true, completion: nil)
guard let selectedImage = info[UIImagePickerController.InfoKey.editedImage] as? UIImage else {return}
moreDetail.postImage.image = selectedImage // error
self.navigationController?.pushViewController(moreDetail, animated: true)
}
</code></pre>
|
[
{
"answer_id": 74527739,
"author": "HangarRash",
"author_id": 20287183,
"author_profile": "https://Stackoverflow.com/users/20287183",
"pm_score": 0,
"selected": false,
"text": "postImage AddPostViewController AddPostViewController UIImage AddPostViewController AddPostViewController postImage"
},
{
"answer_id": 74527842,
"author": "keyur kathrotiya",
"author_id": 10363229,
"author_profile": "https://Stackoverflow.com/users/10363229",
"pm_score": 2,
"selected": true,
"text": "func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {\n \nlet storyboard = UIStoryboard(name: \"Main\", bundle: nil)\nif let moreDetail = storyboard.instantiateViewController(identifier: \"AddPostViewController\") as? AddPostViewController {\n\n\n picker.dismiss(animated: true) {\n \n guard let selectedImage = info[UIImagePickerController.InfoKey.editedImage] \n as? UIImage else {return}\n \n moreDetail.img = selectedImage \n \n self.navigationController?.pushViewController(moreDetail, animated: true) \n }\n \n } \n\n}\n\n class AddPostViewController: UIViewController {\n\n@IBOutlet weak var postImage: UIImageView!\nvar img : UIImage ?\n\n override func viewDidLoad() {\n super.viewDidLoad()\n \n if let img = self.img {\n self.postImage.image = img\n }\n \n\n }\n\n}\n"
},
{
"answer_id": 74528393,
"author": "Shabnam Siddiqui",
"author_id": 12278098,
"author_profile": "https://Stackoverflow.com/users/12278098",
"pm_score": -1,
"selected": false,
"text": "UIImage AddPostViewController AddPostViewController UIImage UIImageView UIImage AddPostViewController var postImg : UImage?\n didFinishPickingMediaWithInfo func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {\n let storyboard = UIStoryboard(name: \"Main\", bundle: nil)\n let moreDetail = storyboard.instantiateViewController(identifier: \"AddPostViewController\") as! AddPostViewController\n picker.dismiss(animated: true, completion: nil)\n guard let selectedImage = info[UIImagePickerController.InfoKey.editedImage] as? UIImage else {return}\n moreDetail.postImg = selectedImage \n self.navigationController?.pushViewController(moreDetail, animated: true)\n}\n postImg viewDidLoad AddPostViewController if let img = postImg{\n postImage.image = img\n}\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15620333/"
] |
74,527,676
|
<p>I am new to coding generally, and have been working on a quiz program on HTML and CSS (data is from PostgreSQL, framework SpringBoot on Eclipse. PHP and JQuery not included in syllabus).</p>
<p>Here's my problem:</p>
<ol>
<li>Now I have a list of answers where the user will have to select from.</li>
<li>Was hoping to have the colours of the button-like radio input? change colour when the user clicks on it.</li>
<li>Managed to create the buttons and the cursor when it hovers over the selections, but there's no change despite my CSS.</li>
</ol>
<p>Can someone tell me where I did wrong? Big thanks in advance.</p>
<p><strong>โปUpdated HTML and CSS according to the advices in the comments + more code:</strong></p>
<p>This is the HTML code:</p>
<p>the screenshot of the id: <a href="https://i.stack.imgur.com/4IeWK.png" rel="nofollow noreferrer">https://i.stack.imgur.com/4IeWK.png</a></p>
<pre><code><body>
<form method="post" action="/result" data-th-object="${form}">
<!-- ใใใใผใฟใคใใซ -->
<div class="headerbackground">
<h6>ๆจกๆฌ่ฉฆ้จใชใณใฉใคใณ</h6>
</div>
<br>
<!-- ่ฉฆ้จๆ็คบ -->
<div class="examinstruction">
<p>่กจ็คบใใใ่จ่ใฎ่ฑๅ่ชใไปฅไธใใ้ธใณใ</p>
<p>OKใใฟใณใใฏใชใใฏใใฆใใ ใใใ</p>
</div>
<br>
<!-- question -->
<div data-th-each="list, st : ${form.list}">
<p style="text-align: center; font-size: 12px;">
<span data-th-text="${list.questionCount}">n</span> <span>/</span> <span
data-th-text="${list.questionTotal}">/n</span>
</p>
<div class="questionborder">
<p style="font-size: 22px; font-weight: bold"
data-th-text="${list.content}">question</p>
</div>
<!-- answer choice -->
<fieldset style="border: 0">
<div class="choiceradiobox"
data-th-each="choice, stat : ${list.choice}">
<input id="selectedchoice" data-th-name="|choice${st.count}|"
type="radio" data-th-value="${choice}"
/>
<label
for="selectedchoice"><span data-th-text="${choice}"></span></label>
</div>
</fieldset>
</div>
<!-- ่งฃ็ญๅฎไบใใฟใณ -->
<div class="submitsection">
<input class="btn btn-secondary" style="font-size: 25px"
type="submit" onclick=validate() value="OK!">
</div>
</form>
</body>
</code></pre>
<p>CSS:</p>
<pre><code>input[type=radio] {
display: none;
}
input[type="radio"]:checked + label {
background: #455a64;
color: #eceff1;
}
label {
display: block;
margin: auto;
width: max-content;
text-align: center;
padding-top : 0.05em;
padding-bottom: 0.05em;
padding-left: 5em;
padding-right: 5em;
line-height: 45px;
cursor: pointer;
border: solid #eceff1;
background-color: #eceff1;
padding-top: 0.05em;
}
</code></pre>
|
[
{
"answer_id": 74527739,
"author": "HangarRash",
"author_id": 20287183,
"author_profile": "https://Stackoverflow.com/users/20287183",
"pm_score": 0,
"selected": false,
"text": "postImage AddPostViewController AddPostViewController UIImage AddPostViewController AddPostViewController postImage"
},
{
"answer_id": 74527842,
"author": "keyur kathrotiya",
"author_id": 10363229,
"author_profile": "https://Stackoverflow.com/users/10363229",
"pm_score": 2,
"selected": true,
"text": "func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {\n \nlet storyboard = UIStoryboard(name: \"Main\", bundle: nil)\nif let moreDetail = storyboard.instantiateViewController(identifier: \"AddPostViewController\") as? AddPostViewController {\n\n\n picker.dismiss(animated: true) {\n \n guard let selectedImage = info[UIImagePickerController.InfoKey.editedImage] \n as? UIImage else {return}\n \n moreDetail.img = selectedImage \n \n self.navigationController?.pushViewController(moreDetail, animated: true) \n }\n \n } \n\n}\n\n class AddPostViewController: UIViewController {\n\n@IBOutlet weak var postImage: UIImageView!\nvar img : UIImage ?\n\n override func viewDidLoad() {\n super.viewDidLoad()\n \n if let img = self.img {\n self.postImage.image = img\n }\n \n\n }\n\n}\n"
},
{
"answer_id": 74528393,
"author": "Shabnam Siddiqui",
"author_id": 12278098,
"author_profile": "https://Stackoverflow.com/users/12278098",
"pm_score": -1,
"selected": false,
"text": "UIImage AddPostViewController AddPostViewController UIImage UIImageView UIImage AddPostViewController var postImg : UImage?\n didFinishPickingMediaWithInfo func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {\n let storyboard = UIStoryboard(name: \"Main\", bundle: nil)\n let moreDetail = storyboard.instantiateViewController(identifier: \"AddPostViewController\") as! AddPostViewController\n picker.dismiss(animated: true, completion: nil)\n guard let selectedImage = info[UIImagePickerController.InfoKey.editedImage] as? UIImage else {return}\n moreDetail.postImg = selectedImage \n self.navigationController?.pushViewController(moreDetail, animated: true)\n}\n postImg viewDidLoad AddPostViewController if let img = postImg{\n postImage.image = img\n}\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20518690/"
] |
74,527,683
|
<p>Why can't you do this if you try to find out whether an int is between two numbers:</p>
<pre><code>if (16.5 < value < 17.5)
</code></pre>
<p>Instead of it, you'll have to do</p>
<pre><code>if (value > 16.5 && value < 17.5)
</code></pre>
<p>which seems like a bit of overhead.</p>
|
[
{
"answer_id": 74527969,
"author": "rodpold",
"author_id": 2566770,
"author_profile": "https://Stackoverflow.com/users/2566770",
"pm_score": 1,
"selected": false,
"text": "between(value, 1, 10);\n if ( a > b )\n if (16.5 < value < 17.5)\n if (16.5 < value > 17.5)\n if (16.5 > value < 17.5)\n"
},
{
"answer_id": 74528198,
"author": "My Car",
"author_id": 16124033,
"author_profile": "https://Stackoverflow.com/users/16124033",
"pm_score": 0,
"selected": false,
"text": "if (value.clamp(16.6, 17.4) == value) {\n // Do what you want to do\n}\n .clamp"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19440771/"
] |
74,527,685
|
<p>The objective of this code snippet was to create a 2D array of shape (10,10) with</p>
<p>array[0,0]=1;</p>
<p>array[0,9]=100; and</p>
<p>array[9,0]=50.</p>
<p>Complications arose when the interval between these elements had to be equal as shown in the expected output. Rows had to increment with equal intervals up-to 100 and columns had to increment with equal intervals up-to 50.</p>
<p>I know that my code has a logical error in list-comprehension for "matrix_list". But I'm not sure what the error is.</p>
<p>The code I wrote:</p>
<pre><code>`import numpy as np`
`matrix_list = np.zeros((10,10), dtype = int)`
`matrix_list =
[(np.arange(column, 101, (100-1)/9).astype(int)) for column in np.arange(1, 51, (50-1)/9).astype(int)]`
`print(np.array(matrix_list))`
</code></pre>
<p>Expected Output:</p>
<pre><code>[ 1, 12, 23, 34, 45, 56, 67, 78, 89, 100]
[ 6, 17, 28, 39, 50, 61, 72, 83, 94, 0]
[11, 22, 33, 44, 55, 66, 77, 88, 0, 0]
[17, 28, 39, 50, 61, 72, 83, 0, 0, 0]
[22, 33, 44, 55, 66, 77, 0, 0, 0, 0]
[28, 39, 50, 61, 72, 0, 0, 0, 0, 0]
[33, 44, 55, 66, 0, 0, 0, 0, 0, 0]
[39, 50, 61, 0, 0, 0, 0, 0, 0, 0]
[44, 55, 0, 0, 0, 0, 0, 0, 0, 0]
[50, 0, 0, 0, 0, 0, 0, 0, 0, 0]
</code></pre>
<p>The output I am getting:</p>
<pre><code>[array([ 1, 12, 23, 34, 45, 56, 67, 78, 89, 100])
array([ 6, 17, 28, 39, 50, 61, 72, 83, 94])
array([11, 22, 33, 44, 55, 66, 77, 88, 99])
array([17, 28, 39, 50, 61, 72, 83, 94])
array([22, 33, 44, 55, 66, 77, 88, 99])
array([28, 39, 50, 61, 72, 83, 94]) array([33, 44, 55, 66, 77, 88, 99])
array([39, 50, 61, 72, 83, 94]) array([44, 55, 66, 77, 88, 99])
array([50, 61, 72, 83, 94])]
"""
</code></pre>
|
[
{
"answer_id": 74527969,
"author": "rodpold",
"author_id": 2566770,
"author_profile": "https://Stackoverflow.com/users/2566770",
"pm_score": 1,
"selected": false,
"text": "between(value, 1, 10);\n if ( a > b )\n if (16.5 < value < 17.5)\n if (16.5 < value > 17.5)\n if (16.5 > value < 17.5)\n"
},
{
"answer_id": 74528198,
"author": "My Car",
"author_id": 16124033,
"author_profile": "https://Stackoverflow.com/users/16124033",
"pm_score": 0,
"selected": false,
"text": "if (value.clamp(16.6, 17.4) == value) {\n // Do what you want to do\n}\n .clamp"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20506805/"
] |
74,527,702
|
<p>I have access to Kibana version 7.3</p>
<p>From this GUI is there a way I can confirm which elasticsearch version it is on? I cannot assume that both components are running the same version.</p>
<p>See question above.</p>
|
[
{
"answer_id": 74527969,
"author": "rodpold",
"author_id": 2566770,
"author_profile": "https://Stackoverflow.com/users/2566770",
"pm_score": 1,
"selected": false,
"text": "between(value, 1, 10);\n if ( a > b )\n if (16.5 < value < 17.5)\n if (16.5 < value > 17.5)\n if (16.5 > value < 17.5)\n"
},
{
"answer_id": 74528198,
"author": "My Car",
"author_id": 16124033,
"author_profile": "https://Stackoverflow.com/users/16124033",
"pm_score": 0,
"selected": false,
"text": "if (value.clamp(16.6, 17.4) == value) {\n // Do what you want to do\n}\n .clamp"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20029589/"
] |
74,527,723
|
<p>Dears,</p>
<p>I need to find the Lowest number in the loop scanner. 0 to stop the program. The issue I phased is that every time the lowest will be 0. What is wrong with this code?</p>
<pre><code>import java.util.Scanner;
public class Loop_Scanner {
public static void main(String[] args) {
int x=1;
int largest = 0;
int Lowest = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter the number: ");
if(x>0) {
while (x != 0) {
x = input.nextInt();
if (largest<=x){
largest=x;
} else if (Lowest >=x ) {
Lowest =x;
}
}
System.out.println("The Largest Number is: "+largest);
System.out.println("The Smallest Number is: "+Lowest);
}
else {
System.out.println("Wrong Value");
}
}}
</code></pre>
|
[
{
"answer_id": 74527969,
"author": "rodpold",
"author_id": 2566770,
"author_profile": "https://Stackoverflow.com/users/2566770",
"pm_score": 1,
"selected": false,
"text": "between(value, 1, 10);\n if ( a > b )\n if (16.5 < value < 17.5)\n if (16.5 < value > 17.5)\n if (16.5 > value < 17.5)\n"
},
{
"answer_id": 74528198,
"author": "My Car",
"author_id": 16124033,
"author_profile": "https://Stackoverflow.com/users/16124033",
"pm_score": 0,
"selected": false,
"text": "if (value.clamp(16.6, 17.4) == value) {\n // Do what you want to do\n}\n .clamp"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20568787/"
] |
74,527,726
|
<p>I have a derived class, <code>Wrapper</code>, that inherits from a template-defined base class. I'd like to configure <code>Wrapper</code> so that if the base class has constructor parameters, <code>Wrapper</code>'s constructor also includes the base class's constructor params so that it can forward them to the base class constructor:</p>
<pre class="lang-cpp prettyprint-override"><code>struct Base1 {
Base1(int) {}
};
struct Base2 {
Base2(std::string) {}
};
// I'd like variadic template param `Args` to be deduced to a parameter
// pack matching a valid constructor for type T, if available.
template <typename T, typename... Args>
struct Wrapper : public T {
Wrapper(int, Args&&... v) : T(std::forward<Args>(v)...) {}
};
int main() {
auto wrapper = Wrapper<Base1>(1, 2);
}
</code></pre>
<p>This example fails because the compiler is not deducing anything for <code>Args</code>, and so the resulting error is:</p>
<pre><code>no matching function for call to โWrapper<Base1>::Wrapper(int, int)โ:
candidate: โWrapper<T, Args>::Wrapper(int, Args&& ...) [with T = Base1; Args = {}]โ
candidate expects 1 argument, 2 provided
</code></pre>
<p>Is it possible to force the compiler to deduce the type(s) for the variadic template parameter <code>Args</code>, based on the deduced value of <code>T</code> and the parameters provided to <code>Wrapper</code> at construction?</p>
|
[
{
"answer_id": 74527969,
"author": "rodpold",
"author_id": 2566770,
"author_profile": "https://Stackoverflow.com/users/2566770",
"pm_score": 1,
"selected": false,
"text": "between(value, 1, 10);\n if ( a > b )\n if (16.5 < value < 17.5)\n if (16.5 < value > 17.5)\n if (16.5 > value < 17.5)\n"
},
{
"answer_id": 74528198,
"author": "My Car",
"author_id": 16124033,
"author_profile": "https://Stackoverflow.com/users/16124033",
"pm_score": 0,
"selected": false,
"text": "if (value.clamp(16.6, 17.4) == value) {\n // Do what you want to do\n}\n .clamp"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/579132/"
] |
74,527,735
|
<p>I am trying to set the theme for Emacs but I have been experiencing some errors. Currently my code is:</p>
<pre class="lang-lisp prettyprint-override"><code>;; theme
(defun set-theme-time ()
(let ((light 'modus-operandi)
(dark 'modus-vivendi))
(load-theme light t t)
(load-theme dark t t)
(run-at-time "8:00" nil
(lambda (light dark)
(disable-theme dark)
(enable-theme light)))
(run-at-time "17:00" nil
(lambda (light dark)
(disable-theme light)
(enable-theme dark)))
(message "Theme Loaded")))
(set-theme-time)
</code></pre>
<p>Everything in my config loads, and <code>message</code> does print <code>Theme Loaded</code> in the <code>*Messages*</code> buffer. However, the themes do not display, and after everything else has loaded I get this:</p>
<pre><code>Error running timer: (wrong-number-of-arguments (lambda (light dark) (disable-theme dark) (enable-theme light)) 0) [2 times]
</code></pre>
<p>How can I fix this?</p>
|
[
{
"answer_id": 74527969,
"author": "rodpold",
"author_id": 2566770,
"author_profile": "https://Stackoverflow.com/users/2566770",
"pm_score": 1,
"selected": false,
"text": "between(value, 1, 10);\n if ( a > b )\n if (16.5 < value < 17.5)\n if (16.5 < value > 17.5)\n if (16.5 > value < 17.5)\n"
},
{
"answer_id": 74528198,
"author": "My Car",
"author_id": 16124033,
"author_profile": "https://Stackoverflow.com/users/16124033",
"pm_score": 0,
"selected": false,
"text": "if (value.clamp(16.6, 17.4) == value) {\n // Do what you want to do\n}\n .clamp"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20568892/"
] |
74,527,737
|
<p>The following image is the example that was given in my computer vision class. Now I cant understand why we are getting 2 unique values of f. I can understand if mxf and myf are different, but shouldn't the focal length 'f' be the same?</p>
<p><a href="https://i.stack.imgur.com/IYixk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IYixk.png" alt="Camera intrinsic matrix found using matlab" /></a></p>
|
[
{
"answer_id": 74527969,
"author": "rodpold",
"author_id": 2566770,
"author_profile": "https://Stackoverflow.com/users/2566770",
"pm_score": 1,
"selected": false,
"text": "between(value, 1, 10);\n if ( a > b )\n if (16.5 < value < 17.5)\n if (16.5 < value > 17.5)\n if (16.5 > value < 17.5)\n"
},
{
"answer_id": 74528198,
"author": "My Car",
"author_id": 16124033,
"author_profile": "https://Stackoverflow.com/users/16124033",
"pm_score": 0,
"selected": false,
"text": "if (value.clamp(16.6, 17.4) == value) {\n // Do what you want to do\n}\n .clamp"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6768132/"
] |
74,527,764
|
<p>i have created a antd modal and i want to change modal body color to red here is my code,had applied background color but it is not showing also i want to align image and modalName in a row using flex, i have intalled antd version 4.2, and i am using styled components. dont know whats wrong.please help,and thanks in advance.</p>
<pre><code></code></pre>
<p>modal.js</p>
<pre><code>import React , {useState} from "react";
import { Modal ,Button} from "antd";
import styled from "styled-components";
import "antd/dist/antd.css";
const Modall = () => {
const [isModalVisible, setIsModalVisible] = useState(false);
const showModal = () => {
setIsModalVisible(true);
}
const handleOk = () => {
setIsModalVisible(false);
}
const handleCancel = () => {
setIsModalVisible(false);
}
return (
<Wrapper>
<div className="head">hello</div>
<Button type="primary" onClick={showModal}>
Open Modal
</Button>
<Modal
title="Basic Modal"
open={isModalVisible}
onOk={handleOk}
onCancel={handleCancel}
>
<div className="modalName">hello</div>
<div className="modalHead">
<img src='simple.svg' className="newStyle"></img>
<div className="modalName" >beautiful</div>
/div>
</Modal>
</Wrapper>
);
}
export default Modall;
const Wrapper = styled.div`
.ant-modal, .ant-modal-content .ant-modal-body .modalHead{
display:flex;
}
.ant-modal, .ant-modal-content .ant-modal-body{
background:red;
}
`
</code></pre>
|
[
{
"answer_id": 74527830,
"author": "Kamran Davar",
"author_id": 12510464,
"author_profile": "https://Stackoverflow.com/users/12510464",
"pm_score": 0,
"selected": false,
"text": "Wrapper return (\n <>\n <div className=\"head\">hello</div>\n <Button type=\"primary\" onClick={showModal}>\n Open Modal\n </Button>\n <Modal\n title=\"Basic Modal\"\n open={isModalVisible}\n onOk={handleOk}\n onCancel={handleCancel}\n className=\"modalStyle\"\n >\n <Wrapper><div className=\"modalName\">hello</div></Wrapper>\n </Modal> \n </>\n \n );\n \nconst Wrapper = styled.div`\n background:red;\n`\n"
},
{
"answer_id": 74527860,
"author": "kuuhak-u",
"author_id": 20458458,
"author_profile": "https://Stackoverflow.com/users/20458458",
"pm_score": 1,
"selected": false,
"text": " <Modal\n title=\"Basic Modal\"\n open={isModalVisible}\n onOk={handleOk}\n onCancel={handleCancel}\n bodyStyle={{\n backgroundColor: \"red\"\n }}\n \n >\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19706661/"
] |
74,527,779
|
<p>I am trying to validate a username field like this:</p>
<ol>
<li>6 alphabets mandatory</li>
<li>Might contain any number of numericals</li>
<li>Might contain any number of underscores</li>
</ol>
<p>For example: <strong>abcdef</strong>, <strong>abc9def</strong>, <strong>_testaa</strong>, <strong>__test_aa_</strong>, <strong>hello_h_9</strong>, <strong>_9helloa</strong>, <strong>9a8v6f_aaa</strong>
All these should match, that is, the number of alphabets should be more than n numbers (here 6) in the whole string, and _ and numerics can be present anywhere.</p>
<p>I have this regex: <code>[\d\_]*[a-zA-Z]{6,}[\d\_]*</code>
It matches strings like: _965hellof
But doesn't match strings like: ede_96hek</p>
<p>I also have tried this regex: <code>^(?:_?)(?:[a-z0-9]?)[a-z]{6,}(?:_?)(?:[a-z0-9])*$</code>
Even this fails to match.</p>
|
[
{
"answer_id": 74527830,
"author": "Kamran Davar",
"author_id": 12510464,
"author_profile": "https://Stackoverflow.com/users/12510464",
"pm_score": 0,
"selected": false,
"text": "Wrapper return (\n <>\n <div className=\"head\">hello</div>\n <Button type=\"primary\" onClick={showModal}>\n Open Modal\n </Button>\n <Modal\n title=\"Basic Modal\"\n open={isModalVisible}\n onOk={handleOk}\n onCancel={handleCancel}\n className=\"modalStyle\"\n >\n <Wrapper><div className=\"modalName\">hello</div></Wrapper>\n </Modal> \n </>\n \n );\n \nconst Wrapper = styled.div`\n background:red;\n`\n"
},
{
"answer_id": 74527860,
"author": "kuuhak-u",
"author_id": 20458458,
"author_profile": "https://Stackoverflow.com/users/20458458",
"pm_score": 1,
"selected": false,
"text": " <Modal\n title=\"Basic Modal\"\n open={isModalVisible}\n onOk={handleOk}\n onCancel={handleCancel}\n bodyStyle={{\n backgroundColor: \"red\"\n }}\n \n >\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10951873/"
] |
74,527,783
|
<p>I'm finding it awfully hard to see how to simply cover a rectangular XAML element with repeating copies of a bitmap! I am using WinUI 3 with Windows App SDK. I would like to use the repeating image as a background element in my app.</p>
<p>It would seem to involve the composition API. Some tantalizing clues are given by <a href="https://xamlbrewer.wordpress.com/2016/01/04/using-the-composition-api-in-uwp-apps/" rel="nofollow noreferrer">Deiderik Krohls</a> and by <a href="https://stackoverflow.com/questions/35456324/uwp-how-to-tile-a-background-image">JetChopper</a> ... however (a) there does not seem to be a stable released NuGet package for the required interface and (b) this seems like a very complicated way to do something that should be simple and (c) these solutions would seem to require extra work to integrate with WinUI 3 classes such as ImageSource and BitmapImage.</p>
<p>Any suggestions?</p>
|
[
{
"answer_id": 74527830,
"author": "Kamran Davar",
"author_id": 12510464,
"author_profile": "https://Stackoverflow.com/users/12510464",
"pm_score": 0,
"selected": false,
"text": "Wrapper return (\n <>\n <div className=\"head\">hello</div>\n <Button type=\"primary\" onClick={showModal}>\n Open Modal\n </Button>\n <Modal\n title=\"Basic Modal\"\n open={isModalVisible}\n onOk={handleOk}\n onCancel={handleCancel}\n className=\"modalStyle\"\n >\n <Wrapper><div className=\"modalName\">hello</div></Wrapper>\n </Modal> \n </>\n \n );\n \nconst Wrapper = styled.div`\n background:red;\n`\n"
},
{
"answer_id": 74527860,
"author": "kuuhak-u",
"author_id": 20458458,
"author_profile": "https://Stackoverflow.com/users/20458458",
"pm_score": 1,
"selected": false,
"text": " <Modal\n title=\"Basic Modal\"\n open={isModalVisible}\n onOk={handleOk}\n onCancel={handleCancel}\n bodyStyle={{\n backgroundColor: \"red\"\n }}\n \n >\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6090828/"
] |
74,527,788
|
<p>I've made progress (I think) with getting delegate access scope working on my custom app for my store. However, I keep getting this error:</p>
<blockquote>
<p>Error: GraphQL Error (Code: 422):
{"response":{"errors":{"delegate_access_scope":["The access scope
can't be empty."]},</p>
</blockquote>
<p>To simply get this working I'm using the example from the docs:</p>
<pre><code>const accessToken = gql`mutation {
delegateAccessTokenCreate(input: { delegateAccessScope: ["write_orders" ], expiresIn: 3600 }){
delegateAccessToken {
accessToken
}
shop {
id
}
userErrors {
field
message
}
}
}`
</code></pre>
<p>I'm kind of at my wits end here as I finally realized that the delegate.json actually needs the ADMIN key rather than the storefront even though I want to use this with the storefront API (which is weird). All I want to be able to do is create a new customer with a password via this API.</p>
<p>Thanks in advance.</p>
|
[
{
"answer_id": 74527830,
"author": "Kamran Davar",
"author_id": 12510464,
"author_profile": "https://Stackoverflow.com/users/12510464",
"pm_score": 0,
"selected": false,
"text": "Wrapper return (\n <>\n <div className=\"head\">hello</div>\n <Button type=\"primary\" onClick={showModal}>\n Open Modal\n </Button>\n <Modal\n title=\"Basic Modal\"\n open={isModalVisible}\n onOk={handleOk}\n onCancel={handleCancel}\n className=\"modalStyle\"\n >\n <Wrapper><div className=\"modalName\">hello</div></Wrapper>\n </Modal> \n </>\n \n );\n \nconst Wrapper = styled.div`\n background:red;\n`\n"
},
{
"answer_id": 74527860,
"author": "kuuhak-u",
"author_id": 20458458,
"author_profile": "https://Stackoverflow.com/users/20458458",
"pm_score": 1,
"selected": false,
"text": " <Modal\n title=\"Basic Modal\"\n open={isModalVisible}\n onOk={handleOk}\n onCancel={handleCancel}\n bodyStyle={{\n backgroundColor: \"red\"\n }}\n \n >\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1527700/"
] |
74,527,821
|
<p>Using class Based (APIView) in Django rest framework for Getting and Patch (Updating) UserInfo data.</p>
<p><strong>views.py</strong></p>
<pre><code>class getUserInfo(APIView):
permission_classes = [permissions.IsAuthenticated]
def get(self, request, format=None):
user = request.user
userinfos = user.userinfo_set.all()
serializer = UserInfoSerializers(userinfos, many=True)
return Response(serializer.data)
def patch(self, request, pk, format=None):
user = UserInfo.objects.get(id=pk)
serializer = UserInfoSerializers(instance=user, data=request.data, partial=True)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
</code></pre>
<p><strong>serializers.py</strong></p>
<pre><code>from django.contrib.auth.models import User
from .models import UserInfo
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'first_name', 'username')
class UserInfoSerializers(serializers.ModelSerializer):
user = UserSerializer(many=False, required=True)
class Meta:
model = UserInfo
fields = ('id', 'picture', 'profession', 'user')
</code></pre>
<p>Everything is working so far so good. Able to GET and PATCH (Update) logged-in user data.
While Testing the API in Postman, I found out that if User1 is logged in he can change the data of User2 by only using the pk of User2.</p>
<p><strong>urls.py</strong></p>
<pre><code>urlpatterns = [
path('userinfo/', views.getUserInfo.as_view(), name="UserInfo"),
path('userinfo/<str:pk>/', views.getUserInfo.as_view()),
path('api/token/', views.MyTokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
path('register/', views.RegisterView.as_view(), name='auth_register'),
]
</code></pre>
<p><em>Using rest_framework_simplejwt for Auth</em></p>
<p><strong>models.py</strong></p>
<pre><code>
from django.contrib.auth.models import User
class UserInfo(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
picture = models.ImageField(upload_to="profile_pics", null=True)
profession = models.CharField(max_length=200, null=True)
def __str__(self):
return "%s's Profile Picture" % self.user
</code></pre>
<p>Any help would be appreciated</p>
|
[
{
"answer_id": 74527830,
"author": "Kamran Davar",
"author_id": 12510464,
"author_profile": "https://Stackoverflow.com/users/12510464",
"pm_score": 0,
"selected": false,
"text": "Wrapper return (\n <>\n <div className=\"head\">hello</div>\n <Button type=\"primary\" onClick={showModal}>\n Open Modal\n </Button>\n <Modal\n title=\"Basic Modal\"\n open={isModalVisible}\n onOk={handleOk}\n onCancel={handleCancel}\n className=\"modalStyle\"\n >\n <Wrapper><div className=\"modalName\">hello</div></Wrapper>\n </Modal> \n </>\n \n );\n \nconst Wrapper = styled.div`\n background:red;\n`\n"
},
{
"answer_id": 74527860,
"author": "kuuhak-u",
"author_id": 20458458,
"author_profile": "https://Stackoverflow.com/users/20458458",
"pm_score": 1,
"selected": false,
"text": " <Modal\n title=\"Basic Modal\"\n open={isModalVisible}\n onOk={handleOk}\n onCancel={handleCancel}\n bodyStyle={{\n backgroundColor: \"red\"\n }}\n \n >\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18388506/"
] |
74,527,847
|
<p>I have a react application with a good amount of states. I've been looking around trying to find the best way to save the states to local storage. Honestly, none of the answers were helping so I decided to ask my own.</p>
<p>What's the best way to go about saving these states to local storage?</p>
<pre><code>function Main() {
const [thumb, setThumb] = useState();
const [timestamp, setTimestamp] = useState("1:20");
const [channelPic, setChannelPic] = useState();
const [title, setTitle] = useState("Title");
const [channelName, setChannelName] = useState("Channel");
const [views, setViews] = useState("1,000");
const [timeAgo, setTimeAgo] = useState("23");
const [increment, setIncrement] = useState("minute");
const [verified, setVerified] = useState(false);
return (
<div className="d-flex">
<Preview
thumb={thumb}
timestamp={timestamp}
channelPic={channelPic}
title={title}
channelName={channelName}
views={views}
timeAgo={timeAgo}
increment={increment}
verified={verified}
/>
<Info
setThumb={setThumb}
setTimestamp={setTimestamp}
setChannelPic={setChannelPic}
setTitle={setTitle}
setChannelName={setChannelName}
setViews={setViews}
setTimeAgo={setTimeAgo}
setIncrement={setIncrement}
setVerified={setVerified}
/>
</div>
);
}
export default Main;
</code></pre>
<p>EDIT: Since I'm rendering the states in <code><Preview /></code> but setting the states in <code><Info /></code> where am (or should I) be saving to local storage.</p>
<p>Is there a way to save all these states at the same time every time one of them is set or is that not how saving states to local storage works. Also where and when exactly should I add them to local storage, as in, where does the function to add them go? Whenever the state is changed? Or at certain increments?</p>
|
[
{
"answer_id": 74528829,
"author": "kushagra-aa",
"author_id": 14001385,
"author_profile": "https://Stackoverflow.com/users/14001385",
"pm_score": 3,
"selected": true,
"text": "localStorage.setItem('thumb',thumb);\n JSON.stringify let anObject={\n \"thumb\":thumb,\n \"timestamp\":timestamp,\n \"channelPic\":channelPic,\n \"title\":title,\n \"channelName\":channelName,\n \"views\":views,\n \"timeAgo\":timeAgo,\n \"increment\":increment,\n \"verified\":verified\n};\n\nlocalStorage.setItem('obj', JSON.stringify(anObject));\n JSON.parse anObject=JSON.parse(localStorage.getItem('obj'));\n useEffect anObject useEffec(()=>{\nanObject={\n \"thumb\":thumb,\n \"timestamp\":timestamp,\n \"channelPic\":channelPic,\n \"title\":title,\n \"channelName\":channelName,\n \"views\":views,\n \"timeAgo\":timeAgo,\n \"increment\":increment,\n \"verified\":verified\n };\n\n localStorage.setItem('obj', JSON.stringify(anObject));\n},[thumb,timestamp,channelPic,title,channelName,views,timeAgo,increment,verified])\n let anObject={};\nuseEffect(()=>{\nanObject=JSON.parse(localStorage.getItem('obj'));\nsetThumb(anObject.thumb);\nsetTimestamp(anObject.timestamp);\nsetChannelPic(anObject.channelPic);\nsetTitle(anObject.title);\nsetChannelName(anObject.channelName);\nsetViews(anObject.views);\nsetTimeAgo(anObject.timeAgo);\nsetIncrement(anObject.increment);\nsetVerified(anObject.verified);\n},[]);\n"
},
{
"answer_id": 74528903,
"author": "Azzy",
"author_id": 2122822,
"author_profile": "https://Stackoverflow.com/users/2122822",
"pm_score": 0,
"selected": false,
"text": " const initialState = {\n timestamp: \"1:20\",\n title: \"Title\",\n channelName: \"Channel\",\n views: \"1,000\",\n timeAgo: \"23\",\n increment: \"minute\",\n verified: false\n }\n \n const state_key = 'GROUP_STATE'\n \n const SomeComponent = (props) => {\n const [groupedState, setGroupedState] = useState({ ...initialState })\n \n const setThumb = (thumb) => setGroupedState(s => ({ ...s, thumb }));\n const setTimestamp] = (timestamp) = setGroupedState(s => ({ ...s, timestamp }));\n \n useEffect(() => {\n \n localStorage.setItem(state_key, JSON.stringify(setThumb));\n \n }, [setThumb]) // save makes its easy\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18060222/"
] |
74,527,893
|
<p>I have a List:</p>
<p><code>List<StudentBean> resultList</code></p>
<p>StudentBean has something like with getters and setters:</p>
<p><code>{ Integer StudentId, String StudentName, String Section}</code>.</p>
<p>I have a map with values: <code>Map<Integer, StudentBean> orginialStudentDetails</code></p>
<p>Now I want to add/replace the values from resultList to orginialStudentDetails, how can I achieve that?</p>
<p>Tried:</p>
<pre><code>for (Map.Entry<Integer, StudentBean> entry : resultList .size()){
orginialStudentDetails.put(entry.getKey(), resultList );
}
</code></pre>
|
[
{
"answer_id": 74527935,
"author": "Joxtacy",
"author_id": 8236993,
"author_profile": "https://Stackoverflow.com/users/8236993",
"pm_score": 2,
"selected": false,
"text": "StudentBean for (StudentBean studentBean : resultList) {\n originalStudentDetails.put(studentBean.getStudentId(), studentBean);\n}\n StudentBean getStudentId int Integer"
},
{
"answer_id": 74528048,
"author": "npe",
"author_id": 20561457,
"author_profile": "https://Stackoverflow.com/users/20561457",
"pm_score": 2,
"selected": false,
"text": "Map<Integer, StudentBean> map = resultList.stream().filter(t -> t != null || t.getStudentId() != null).collect(Collectors.toMap(StudentBean::getStudentId, t -> t));\n"
},
{
"answer_id": 74547339,
"author": "ETO",
"author_id": 10584605,
"author_profile": "https://Stackoverflow.com/users/10584605",
"pm_score": 0,
"selected": false,
"text": "resultList.forEach(s -> originalStudentDetails.put(s.getStudentId(), s));\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14871599/"
] |
74,527,919
|
<p>I am trying to input an array using a scanner. That part is already done. Now, I am tasked to get the maximum and minimum numbers from my input. I was able to get the maximum but with the minimum, it is returning 0.</p>
<p>Is there a misplacement of syntax perhaps?</p>
<pre><code>import java.util.Scanner;
public class App {
public static void main(String[] args) {
int in;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of elements you want to store: ");
in=sc.nextInt();
int array[] = new int[in];
int min = array[0];
int max = array[0];
for (int i=0; i < in; i++){
System.out.print("Input number "+(i+1)+" :");
array[i]=sc.nextInt();
if(array[i]>max){
max=array[i];
}
else if (array[i]<min){
min=array[i];
}
}
sc.close();
System.out.print(" The inputed array is ");
for (int i=0; i < in; i++){
System.out.print(array[i]+" ");
}
System.out.println("\n --------------------");
System.out.println("The highest number is: "+max);
System.out.println("The lowest number is: "+ min);
}
}
</code></pre>
<p>(also if you can, can y'all tell me how to get the index of the minimun and maximum value and print it?)</p>
<p>I tried different if and else if methods. I also tried nesting but I am getting the same outcome.</p>
|
[
{
"answer_id": 74528002,
"author": "lamsmallsmall",
"author_id": 13511160,
"author_profile": "https://Stackoverflow.com/users/13511160",
"pm_score": 0,
"selected": false,
"text": "else if (array[i]<min) if(i==0){\nmin = array[0];\nmax = array[0];\n}\n"
},
{
"answer_id": 74528071,
"author": "Christoph Dahlen",
"author_id": 20370596,
"author_profile": "https://Stackoverflow.com/users/20370596",
"pm_score": 0,
"selected": false,
"text": "null Integer max = null;\nInteger min = null;\n if(max == null || max < array[i]) {\n max = array[i];\n}\n\nif(min == null || min > array[i]) {\n min = array[i];\n}\n"
},
{
"answer_id": 74529794,
"author": "DevilsHnd",
"author_id": 4725875,
"author_profile": "https://Stackoverflow.com/users/4725875",
"pm_score": 1,
"selected": true,
"text": "int int array[] = new int[in];\n min max array[0] int min = 0;\nint max = 0;\n max max min min min min int int min = Integer.MAX_VALUE;\n Integer.MAX_VALUE min max int max = Integer.MIN_VALUE;\n int min = array[0];\nint max = array[0];\n int min = Integer.MAX_VALUE;\nint max = Integer.MIN_VALUE;\n"
},
{
"answer_id": 74530351,
"author": "Abirami Balasubramaniyan",
"author_id": 5755531,
"author_profile": "https://Stackoverflow.com/users/5755531",
"pm_score": 1,
"selected": false,
"text": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Scanner;\n\npublic class App {\n public static void main(String[] args) {\n\n int in;\n List<Integer> elements = new ArrayList<>();\n\n Scanner sc = new Scanner(System.in);\n System.out.print(\"Enter the number of elements you want to store: \");\n in=sc.nextInt();\n\n for (int i=0; i < in; i++){\n System.out.print(\"Input number \"+(i+1)+\" :\");\n elements.add(sc.nextInt());\n }\n sc.close();\n\n List<Integer> unsorted = new ArrayList<>(elements);\n Collections.sort(elements);\n\n int max = elements.get(elements.size()-1);\n int min = elements.get(0);\n\n System.out.println(\"\\n --------------------\");\n System.out.println(\"The highest number is: \"+max);\n System.out.println(\"The lowest number is: \"+ min);\n System.out.println(\"Index of Min Value is : \"+unsorted.indexOf(min));\n System.out.println(\"Index of Max Value is : \"+unsorted.indexOf(max));\n }\n}\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20569062/"
] |
74,527,926
|
<p>Here is my view(Ajax)</p>
<pre><code> $('#basicInfoForm').submit(function(e){
e.preventDefault();
let formData = new FormData(this);
$.ajax({
type: "POST",
url: "{{route('profile.basic_info')}}",
dataType: 'json',
data: formData,
contentType: false,
processData: false,
beforeSend:function(){
$("#fountainG").fadeIn(1000);
},
success: function(response){
$.each(response.errors, function (key, value) {
$("#fountainG").fadeOut(1000);
$('.alert-danger').fadeIn(2000);
$('.alert-danger').append('<span>'+value+'</span>'+'<br>');
setTimeout(function() {
$('.alert-danger').fadeOut(4000, 'swing');
}, 3000);
});
},
error: function(data){
iziToast.error({
title: 'Upload Error',
message: data.avatar,
position: 'topRight'
});
}
});
});
</code></pre>
<p>And, here is my controller</p>
<pre><code> public function updateBasicInformation(Request $request)
{
$basic_info = Validator::make($request->all(), [
'fullname' => 'required|min:2|max:255',
'phone_number' => 'required|numeric|min:10',
'email' => 'required|unique:users',
'country' => 'required',
'address' => 'required',
], [
'phone_number.min' => "The phone number must be at least 10 digits",
]);
if($basic_info->fails())
{
return response()->json([
'errors'=> $basic_info->errors()->all()
]);
}
}
</code></pre>
<p>So, basically, there is form with the ID:</p>
<pre><code>basicInfoForm
</code></pre>
<p>and the div with the class <code>-alert-danger</code> displays the error. But when I submit the form more than once, it keeps on duplicating the errors even the ones that have been properly validated.</p>
<p><a href="https://i.stack.imgur.com/CU6m2.png" rel="nofollow noreferrer">The error</a></p>
<p>How do I get around this, please?</p>
<p>I tried changing the <code>dataType</code> to <code>json</code> but it didn't make any difference.</p>
<p>I am new to Ajax and Laravel</p>
|
[
{
"answer_id": 74528002,
"author": "lamsmallsmall",
"author_id": 13511160,
"author_profile": "https://Stackoverflow.com/users/13511160",
"pm_score": 0,
"selected": false,
"text": "else if (array[i]<min) if(i==0){\nmin = array[0];\nmax = array[0];\n}\n"
},
{
"answer_id": 74528071,
"author": "Christoph Dahlen",
"author_id": 20370596,
"author_profile": "https://Stackoverflow.com/users/20370596",
"pm_score": 0,
"selected": false,
"text": "null Integer max = null;\nInteger min = null;\n if(max == null || max < array[i]) {\n max = array[i];\n}\n\nif(min == null || min > array[i]) {\n min = array[i];\n}\n"
},
{
"answer_id": 74529794,
"author": "DevilsHnd",
"author_id": 4725875,
"author_profile": "https://Stackoverflow.com/users/4725875",
"pm_score": 1,
"selected": true,
"text": "int int array[] = new int[in];\n min max array[0] int min = 0;\nint max = 0;\n max max min min min min int int min = Integer.MAX_VALUE;\n Integer.MAX_VALUE min max int max = Integer.MIN_VALUE;\n int min = array[0];\nint max = array[0];\n int min = Integer.MAX_VALUE;\nint max = Integer.MIN_VALUE;\n"
},
{
"answer_id": 74530351,
"author": "Abirami Balasubramaniyan",
"author_id": 5755531,
"author_profile": "https://Stackoverflow.com/users/5755531",
"pm_score": 1,
"selected": false,
"text": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Scanner;\n\npublic class App {\n public static void main(String[] args) {\n\n int in;\n List<Integer> elements = new ArrayList<>();\n\n Scanner sc = new Scanner(System.in);\n System.out.print(\"Enter the number of elements you want to store: \");\n in=sc.nextInt();\n\n for (int i=0; i < in; i++){\n System.out.print(\"Input number \"+(i+1)+\" :\");\n elements.add(sc.nextInt());\n }\n sc.close();\n\n List<Integer> unsorted = new ArrayList<>(elements);\n Collections.sort(elements);\n\n int max = elements.get(elements.size()-1);\n int min = elements.get(0);\n\n System.out.println(\"\\n --------------------\");\n System.out.println(\"The highest number is: \"+max);\n System.out.println(\"The lowest number is: \"+ min);\n System.out.println(\"Index of Min Value is : \"+unsorted.indexOf(min));\n System.out.println(\"Index of Max Value is : \"+unsorted.indexOf(max));\n }\n}\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19485666/"
] |
74,527,928
|
<p>I am already installed BERT, But I don't know how to get Non-contextual word embeddings.</p>
<p>For example:</p>
<pre><code>
input: 'Apple'
output: [1,2,23,2,13,...] #embedding of 'Apple'
</code></pre>
<p>How can i get these word embeddings?</p>
<p>Thank you.</p>
<p>I search some method, but no blogs have written the way.</p>
|
[
{
"answer_id": 74530625,
"author": "Jindลich",
"author_id": 5652313,
"author_profile": "https://Stackoverflow.com/users/5652313",
"pm_score": 1,
"selected": false,
"text": "model.embeddings.word_embeddings BertTokenizer"
},
{
"answer_id": 74534963,
"author": "edamame",
"author_id": 20569060,
"author_profile": "https://Stackoverflow.com/users/20569060",
"pm_score": 1,
"selected": true,
"text": "import torch\nfrom transformers import AutoTokenizer, AutoModel\ntokenizer = AutoTokenizer.from_pretrained(\"bert-base-uncased\")\n\nmodel = AutoModel.from_pretrained(\"bert-base-uncased\")\n\n# get the word embedding from BERT\ndef get_word_embedding(word:str):\n input_ids = torch.tensor(tokenizer.encode(word)).unsqueeze(0) # Batch size 1\n # print(input_ids)\n outputs = model(input_ids)\n last_hidden_states = outputs[0] # The last hidden-state is the first element of the output tuple\n # output[0] is token vector\n # output[1] is the mean pooling of all hidden states\n return last_hidden_states[0][1]\n\n\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20569060/"
] |
74,527,953
|
<p>So, I have a unix time as
endingTime= 1669060881
and then I do this to convert it into ISO format
this.edate = new Date(endingTime*1000).toISOString() ===> 2022-11-21T20:01:21.000Z</p>
<p>slicing it so that it can fir html local date input
this.edate = this.edate.slice(0, -8) ===> 2022-11-21T20:01</p>
<p>and then patch this value in my date time picker of form
this.userForm['endingTime']['controls'].patchValue(this.edate);</p>
<p>html
---> shows result as 21-11-22 and 8:01 as the time</p>
<p>when I put the time 1669060881 in here <a href="https://www.epochconverter.com/" rel="nofollow noreferrer">https://www.epochconverter.com/</a>
you can see two times</p>
<p>GMT: Monday, November 21, 2022 8:01:21 PM
Your time zone: Tuesday, November 22, 2022 1:31:21 AM GMT+05:30</p>
<p>I need the iso conversiton in "Your time zone" time but currentt edate val is the GMT timezone</p>
<p>pls help</p>
|
[
{
"answer_id": 74530625,
"author": "Jindลich",
"author_id": 5652313,
"author_profile": "https://Stackoverflow.com/users/5652313",
"pm_score": 1,
"selected": false,
"text": "model.embeddings.word_embeddings BertTokenizer"
},
{
"answer_id": 74534963,
"author": "edamame",
"author_id": 20569060,
"author_profile": "https://Stackoverflow.com/users/20569060",
"pm_score": 1,
"selected": true,
"text": "import torch\nfrom transformers import AutoTokenizer, AutoModel\ntokenizer = AutoTokenizer.from_pretrained(\"bert-base-uncased\")\n\nmodel = AutoModel.from_pretrained(\"bert-base-uncased\")\n\n# get the word embedding from BERT\ndef get_word_embedding(word:str):\n input_ids = torch.tensor(tokenizer.encode(word)).unsqueeze(0) # Batch size 1\n # print(input_ids)\n outputs = model(input_ids)\n last_hidden_states = outputs[0] # The last hidden-state is the first element of the output tuple\n # output[0] is token vector\n # output[1] is the mean pooling of all hidden states\n return last_hidden_states[0][1]\n\n\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13146189/"
] |
74,527,960
|
<p>Is there a more easy way to get this path when mocking functions?</p>
<p>@mock.patch('folder1.folder2.file.class.get_some_information', side_effect=mocked_information)</p>
<p>I would like to have the path for the function get_some_information generated automatically. Thanks!</p>
|
[
{
"answer_id": 74528078,
"author": "blhsing",
"author_id": 6890912,
"author_profile": "https://Stackoverflow.com/users/6890912",
"pm_score": 0,
"selected": false,
"text": "get_some_information __module__ __qualname__ '.'.join(get_some_information.__module__, get_some_information.__qualname__)\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74527960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13734142/"
] |
74,528,005
|
<p>I have a JSON I found that seems to fail to be able to remove an Array after indexing once. Here is the valid JSON below (according to jsonlint.com</p>
<p>Goal: Remove an outer array from what {was a valid JSON} on the outside.</p>
<p><strong>Steps to reproduce</strong></p>
<ol>
<li>validate JSON is valid</li>
<li>run <code>cat file.json | jq .rows</code></li>
<li>Observe works OK</li>
<li>try <code>cat file.json | jq .rows[]</code></li>
</ol>
<p>Observe my following error</p>
<p><code>zsh: no matches found: .rows[]</code></p>
<p>I also tried <code>cat file.json | jq .rows | jq .[]</code></p>
<p>For good measure, here is the exact text that is failing but I think JQ should process like this according to <a href="https://stackoverflow.com/questions/58566524/jq-how-to-define-filter-to-remove-brackets-quotes-and-commas-from-output-arra">JQ - How to define filter to remove brackets, quotes and commas from output array</a></p>
<pre><code>{
"selfLink": null,
"id": "eyJwIjoiOGMxZjRkNjAtZDhmNS00YmU2LTg1YjMtYTA0NDExNDVkYmMwIiwicFYiOjE0fQ==",
"title": "My Daily Discovery",
"rows": [{
"modules": [{
"id": "eyJwIjoiOGMxZjRkNjAtZDhmNS00YmU2LTg1YjMtYTA0NDExNDVkYmMwIiwicFYiOjE0LCJtIjoiMTg3ZGVhMTMtNWI1ZS00OWYwLWI5YjktYjc5ODk3M2M2MjVmIiwibVYiOjEsIm1IIjoiYmMyMTQ4NDkifQ==",
"type": "MIX_HEADER",
"width": 100,
"title": "",
"description": "",
"preTitle": "",
"mix": {
"id": "016574ac3abf29b2a6a1ae2c1b2f34",
"title": "My Daily Discovery",
"subTitle": "Songs by new and familiar artists inspired by your listening. Updates every morning.",
"graphic": {
"type": "SQUARES_GRID",
"text": "My Daily Discovery",
"images": [{
"id": "dummy-placeholder",
"vibrantColor": "#FFFFFF",
"type": "ARTIST"
}]
},
"images": {
"SMALL": {
"width": 320,
"height": 320,
"url": "https://images.tidal.com/0/EMACGMAC/CAEQCCIDMzI2KgcjRjlBMTkyMAQ?token=03c55020deef749a0a7608833cebe3ae2f8f33f6"
},
"MEDIUM": {
"width": 640,
"height": 640,
"url": "https://images.tidal.com/0/EIAFGIAF/CAEQCCIDMzI2KgcjRjlBMTkyMAQ?token=c391f21c624d0b58f4badc2185211b89eb2cee7f"
},
"LARGE": {
"width": 1500,
"height": 1500,
"url": "https://images.tidal.com/0/ENwLGNwL/CAEQCCIDMzI2KgcjRjlBMTkyMAQ?token=b055bb723e064256026fcb7d17a6dfa6ef839c25"
}
},
"sharingImages": null,
"mixType": "DISCOVERY_MIX",
"mixNumber": null,
"contentBehavior": "UNRESTRICTED",
"shortSubtitle": null,
"master": false,
"titleColor": "#F9A192",
"subTitleColor": "#F9A192",
"detailImages": {
"SMALL": {
"width": 320,
"height": 320,
"url": "https://images.tidal.com/0/EMACGMAC/CAEQCCIDMzI2KgcjRjlBMTkyMAQ4AQ?token=2d26406e237b5f9e830cac45b7ec6470ce71638f"
},
"MEDIUM": {
"width": 640,
"height": 640,
"url": "https://images.tidal.com/0/EIAFGIAF/CAEQCCIDMzI2KgcjRjlBMTkyMAQ4AQ?token=9406f1c8bc4061c7841f35156b0f81e9dc961d0b"
},
"LARGE": {
"width": 1500,
"height": 1500,
"url": "https://images.tidal.com/0/ENwLGNwL/CAEQCCIDMzI2KgcjRjlBMTkyMAQ4AQ?token=b8eb265be431640046cb1b376715d0ceaef19677"
}
}
},
"playbackControls": [{
"shuffle": false,
"playbackMode": "PLAY",
"title": "Play",
"icon": "play_tracks",
"targetModuleId": "eyJwIjoiOGMxZjRkNjAtZDhmNS00YmU2LTg1YjMtYTA0NDExNDVkYmMwIiwicFYiOjE0LCJtIjoiNmU5OWY3ZjUtMDk4My00Mzk5LWFkYjEtZDk2NzRmMGQ2ZDQ5IiwibVYiOjEsIm1IIjoiNDgyMDRjMGMifQ=="
}, {
"shuffle": true,
"playbackMode": "SHUFFLE",
"title": "Shuffle",
"icon": "shuffle_tracks",
"targetModuleId": "eyJwIjoiOGMxZjRkNjAtZDhmNS00YmU2LTg1YjMtYTA0NDExNDVkYmMwIiwicFYiOjE0LCJtIjoiNmU5OWY3ZjUtMDk4My00Mzk5LWFkYjEtZDk2NzRmMGQ2ZDQ5IiwibVYiOjEsIm1IIjoiNDgyMDRjMGMifQ=="
}]
}]
}, {
"modules": [{
"id": "eyJwIjoiOGMxZjRkNjAtZDhmNS00YmU2LTg1YjMtYTA0NDExNDVkYmMwIiwicFYiOjE0LCJtIjoiNmU5OWY3ZjUtMDk4My00Mzk5LWFkYjEtZDk2NzRmMGQ2ZDQ5IiwibVYiOjEsIm1IIjoiNDgyMDRjMGMifQ==",
"type": "TRACK_LIST",
"width": 100,
"title": "",
"description": "",
"preTitle": null,
"showMore": null,
"supportsPaging": false,
"quickPlay": false,
"listFormat": "COVERS",
"scroll": "VERTICAL",
"layout": "LIST",
"pagedList": {
"limit": 10,
"offset": 0,
"totalNumberOfItems": 10,
"items": [{
"id": 182220043,
"title": "Hippies and Cowboys",
"duration": 301,
"version": null,
"url": "https://tidal.com/browse/track/182220043",
"artists": [{
"id": 6364193,
"name": "Cody Jinks",
"type": "MAIN",
"picture": "bf1a2f1e-7da1-4692-8a66-2bf96157c642"
}],
"album": {
"id": 182220040,
"title": "Less Wise",
"cover": "12193ada-c3f6-48f4-9fa0-d55cb2e0a43e",
"vibrantColor": "#FFFFFF",
"videoCover": null,
"url": "https://tidal.com/browse/album/182220040",
"releaseDate": "2016-08-12"
},
"explicit": false,
"volumeNumber": 1,
"trackNumber": 3,
"popularity": 44,
"allowStreaming": true,
"streamReady": true,
"streamStartDate": "2021-05-01T00:00:00.000+0000",
"editable": false,
"replayGain": -10.58,
"audioQuality": "LOSSLESS",
"audioModes": ["STEREO"],
"mixes": {
"TRACK_MIX": "001fffe9146518c56b9ad0d015c4a2"
}
}, {
"id": 231866033,
"title": "Numb",
"duration": 156,
"version": null,
"url": "https://tidal.com/browse/track/231866033",
"artists": [{
"id": 7250145,
"name": "Marshmello",
"type": "MAIN",
"picture": "a596f1fe-3e76-4314-8530-69b27fb93fa3"
}, {
"id": 4916222,
"name": "Khalid",
"type": "MAIN",
"picture": "84e7a97a-e66c-48b3-ad88-2890066fb64e"
}],
"album": {
"id": 231866032,
"title": "Numb",
"cover": "703caf3c-8dc4-4836-a29e-aa44d9afedae",
"vibrantColor": "#9fd1df",
"videoCover": null,
"url": "https://tidal.com/browse/album/231866032",
"releaseDate": "2022-06-10"
},
"explicit": false,
"volumeNumber": 1,
"trackNumber": 1,
"popularity": 68,
"allowStreaming": true,
"streamReady": true,
"streamStartDate": "2022-06-10T00:00:00.000+0000",
"editable": false,
"replayGain": -9.46,
"audioQuality": "HI_RES",
"audioModes": ["STEREO"],
"mixes": {
"MASTER_TRACK_MIX": "0147bdf794b09b50b6d60f1d6fb903",
"TRACK_MIX": "00137d2d4dd1030005ef1ae2e64d21"
}
}, {
"id": 138872432,
"title": "I Look Good",
"duration": 102,
"version": null,
"url": "https://tidal.com/browse/track/138872432",
"artists": [{
"id": 5896451,
"name": "O.T. Genasis",
"type": "MAIN",
"picture": "6ac8210e-b1ed-4225-a44a-cbddd586d419"
}],
"album": {
"id": 138872431,
"title": "I Look Good",
"cover": "f406561e-a799-43de-9d1e-280b852a8cd3",
"vibrantColor": "#f9d46b",
"videoCover": null,
"url": "https://tidal.com/browse/album/138872431",
"releaseDate": "2020-05-01"
},
"explicit": true,
"volumeNumber": 1,
"trackNumber": 1,
"popularity": 38,
"allowStreaming": true,
"streamReady": true,
"streamStartDate": "2020-05-01T00:00:00.000+0000",
"editable": false,
"replayGain": -8.96,
"audioQuality": "HI_RES",
"audioModes": ["STEREO"],
"mixes": {
"MASTER_TRACK_MIX": "01452343b3589909390a4164019425",
"TRACK_MIX": "001f6cb8e851a11d9a68d80003f5f2"
}
}, {
"id": 125093690,
"title": "Red Line",
"duration": 182,
"version": null,
"url": "https://tidal.com/browse/track/125093690",
"artists": [{
"id": 8048820,
"name": "Geordie Kieffer",
"type": "MAIN",
"picture": null
}],
"album": {
"id": 125093689,
"title": "Red Line",
"cover": "b80983b9-f2a7-404e-b65f-1ed7860fea82",
"vibrantColor": "#b35e67",
"videoCover": null,
"url": "https://tidal.com/browse/album/125093689",
"releaseDate": "2020-01-08"
},
"explicit": true,
"volumeNumber": 1,
"trackNumber": 1,
"popularity": 8,
"allowStreaming": true,
"streamReady": true,
"streamStartDate": "2020-01-08T00:00:00.000+0000",
"editable": false,
"replayGain": -8.62,
"audioQuality": "LOSSLESS",
"audioModes": ["STEREO"],
"mixes": {
"TRACK_MIX": "00104d152616c6579359939441ab42"
}
}, {
"id": 215213468,
"title": "Gospel",
"duration": 210,
"version": null,
"url": "https://tidal.com/browse/track/215213468",
"artists": [{
"id": 3963798,
"name": "Dr. Dre",
"type": "MAIN",
"picture": "1a705aec-4f48-40ba-a146-6f67e011680a"
}, {
"id": 17275,
"name": "Eminem",
"type": "MAIN",
"picture": "480b074a-58da-469e-b4aa-d4e53fd1d5f5"
}],
"album": {
"id": 215213467,
"title": "Gospel",
"cover": "b32350b6-56e3-49cf-9207-a714ff91025e",
"vibrantColor": "#a6944d",
"videoCover": null,
"url": "https://tidal.com/browse/album/215213467",
"releaseDate": "2022-02-04"
},
"explicit": true,
"volumeNumber": 1,
"trackNumber": 1,
"popularity": 58,
"allowStreaming": true,
"streamReady": true,
"streamStartDate": "2022-02-04T00:00:00.000+0000",
"editable": false,
"replayGain": -10.74,
"audioQuality": "HI_RES",
"audioModes": ["STEREO"],
"mixes": {
"MASTER_TRACK_MIX": "014de0b796546a650cb74a3c7d3ed0",
"TRACK_MIX": "0013aa67e00d042e6608c9adb427c8"
}
}, {
"id": 70870118,
"title": "Sleeping on the Blacktop",
"duration": 192,
"version": null,
"url": "https://tidal.com/browse/track/70870118",
"artists": [{
"id": 6672522,
"name": "Colter Wall",
"type": "MAIN",
"picture": "a11692f6-e875-491f-bce4-0173f44ee7c1"
}],
"album": {
"id": 70870117,
"title": "Imaginary Appalachia",
"cover": "8da58d7c-a9d4-42a7-a135-712d60397f08",
"vibrantColor": "#e2d0af",
"videoCover": null,
"url": "https://tidal.com/browse/album/70870117",
"releaseDate": "2018-01-19"
},
"explicit": false,
"volumeNumber": 1,
"trackNumber": 1,
"popularity": 39,
"allowStreaming": true,
"streamReady": true,
"streamStartDate": "2017-03-03T00:00:00.000+0000",
"editable": false,
"replayGain": -7.13,
"audioQuality": "LOSSLESS",
"audioModes": ["STEREO"],
"mixes": {
"TRACK_MIX": "001a2a053ac274a3ac80eb7e9d4d2a"
}
}, {
"id": 237821203,
"title": "Doja",
"duration": 97,
"version": null,
"url": "https://tidal.com/browse/track/237821203",
"artists": [{
"id": 8589558,
"name": "Central Cee",
"type": "MAIN",
"picture": "137e6101-36ec-4462-8d18-c6f374a3e4ca"
}],
"album": {
"id": 237821202,
"title": "Doja",
"cover": "a4739199-f51f-4e9d-8e15-4aef11330322",
"vibrantColor": "#c7d8e9",
"videoCover": null,
"url": "https://tidal.com/browse/album/237821202",
"releaseDate": "2022-07-21"
},
"explicit": true,
"volumeNumber": 1,
"trackNumber": 1,
"popularity": 64,
"allowStreaming": true,
"streamReady": true,
"streamStartDate": "2022-07-21T16:00:00.000+0000",
"editable": false,
"replayGain": -5.98,
"audioQuality": "HI_RES",
"audioModes": ["STEREO"],
"mixes": {
"MASTER_TRACK_MIX": "014d023089eade21828a9b11774c4e",
"TRACK_MIX": "001a920815b5f4d57efb6ce11ec78b"
}
}, {
"id": 140490817,
"title": "ooh la la (feat. Greg Nice & DJ Premier)",
"duration": 181,
"version": null,
"url": "https://tidal.com/browse/track/140490817",
"artists": [{
"id": 5171527,
"name": "Run The Jewels",
"type": "MAIN",
"picture": "4c4895e6-030f-4120-be39-ca840b3caad7"
}, {
"id": 3604111,
"name": "El-P",
"type": "MAIN",
"picture": "9e6a524c-3fa2-4e1c-9aad-4e4b796073bb"
}, {
"id": 5016,
"name": "Killer Mike",
"type": "MAIN",
"picture": "1ba6de84-bab8-433a-99e1-82d1781d412b"
}, {
"id": 4082619,
"name": "DJ Premier",
"type": "FEATURED",
"picture": "f9c60d02-5eef-4662-8e58-e588e5e7b72f"
}, {
"id": 3718662,
"name": "Greg Nice",
"type": "FEATURED",
"picture": "94047994-fc96-4410-b5d5-f126fdf8e7d4"
}],
"album": {
"id": 140490815,
"title": "RTJ4",
"cover": "b13d9c84-747d-47e6-b9f2-c23c71e62e81",
"vibrantColor": "#be1574",
"videoCover": null,
"url": "https://tidal.com/browse/album/140490815",
"releaseDate": "2020-06-05"
},
"explicit": true,
"volumeNumber": 1,
"trackNumber": 2,
"popularity": 41,
"allowStreaming": true,
"streamReady": true,
"streamStartDate": "2020-06-22T00:00:00.000+0000",
"editable": false,
"replayGain": -8.53,
"audioQuality": "HI_RES",
"audioModes": ["STEREO"],
"mixes": {
"MASTER_TRACK_MIX": "0140dec298c0e46db85d6ddba6dcba",
"TRACK_MIX": "0015622125d9f15c27c30b2dbf2fb8"
}
}, {
"id": 52974885,
"title": "Weight of Sound (feat. TJ O'Neill)",
"duration": 443,
"version": null,
"url": "https://tidal.com/browse/track/52974885",
"artists": [{
"id": 4942474,
"name": "Stick Figure",
"type": "MAIN",
"picture": "eb6ed2bf-a8ab-4f97-9d07-b60b97bab27f"
}, {
"id": 4942475,
"name": "TJ O'Neill",
"type": "FEATURED",
"picture": null
}],
"album": {
"id": 52974879,
"title": "Burial Ground",
"cover": "525dbfa2-4d71-4078-96cf-0ba5804c3249",
"vibrantColor": "#ccbc85",
"videoCover": null,
"url": "https://tidal.com/browse/album/52974879",
"releaseDate": "2012-01-01"
},
"explicit": false,
"volumeNumber": 1,
"trackNumber": 6,
"popularity": 35,
"allowStreaming": true,
"streamReady": true,
"streamStartDate": "2012-06-15T00:00:00.000+0000",
"editable": false,
"replayGain": -9.1,
"audioQuality": "LOSSLESS",
"audioModes": ["STEREO"],
"mixes": {
"TRACK_MIX": "001b814bb26f42384d478f8f124133"
}
}, {
"id": 86698003,
"title": "It's Called: Freefall",
"duration": 152,
"version": null,
"url": "https://tidal.com/browse/track/86698003",
"artists": [{
"id": 5416094,
"name": "Rainbow Kitten Surprise",
"type": "MAIN",
"picture": "b3675173-8f39-48c9-8172-d0ea7c38cf78"
}],
"album": {
"id": 86697999,
"title": "How to: Friend, Love, Freefall",
"cover": "2612d792-a8cf-4e40-8df9-635485d2a263",
"vibrantColor": "#df9390",
"videoCover": null,
"url": "https://tidal.com/browse/album/86697999",
"releaseDate": "2018-04-06"
},
"explicit": true,
"volumeNumber": 1,
"trackNumber": 4,
"popularity": 37,
"allowStreaming": true,
"streamReady": true,
"streamStartDate": "2018-04-06T00:00:00.000+0000",
"editable": false,
"replayGain": -9.29,
"audioQuality": "HI_RES",
"audioModes": ["STEREO"],
"mixes": {
"MASTER_TRACK_MIX": "014069ec04995575ebd2537f5a365a",
"TRACK_MIX": "001d91e79ca357d29a3ad505287121"
}
}],
"dataApiPath": "pages/data/518d479b-3510-41ba-a62b-4c06055ec580?mixId=016574ac3abf29b2a6a1ae2c1b2f34"
},
"showTableHeaders": true
}]
}]
</code></pre>
<p>}</p>
|
[
{
"answer_id": 74528116,
"author": "ikegami",
"author_id": 589924,
"author_profile": "https://Stackoverflow.com/users/589924",
"pm_score": 3,
"selected": true,
"text": ".rows[] zsh .rows[] jq jq '.rows[]' file.json\n"
},
{
"answer_id": 74533184,
"author": "0stone0",
"author_id": 5625547,
"author_profile": "https://Stackoverflow.com/users/5625547",
"pm_score": 0,
"selected": false,
"text": "noglob noglob jq .rows[] input\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5569925/"
] |
74,528,012
|
<p>Using the image-crop-picker I am selecting an image from gallery then setting it to state. I then have the option to crop the image and in the array/state I replace the old image with the new cropped one which I am able to do so successfully but the screen doesn't update with the cropped image until I refresh it.</p>
<pre><code>import ImagePicker from 'react-native-image-crop-picker';
const [renderImages, setRenderImages] = useState([]);
//Listens for images
useEffect(() => {
renderImages;
}, [renderImages]);
//Pick images from gallery
const pickGalleryImages = () => {
let imageList = [];
ImagePicker.openPicker({
multiple: true,
mediaType: 'any',
maxFiles: 10,
cropping: true,
})
.then(response => {
response.map(imgs => {
imageList.push(imgs.path);
});
setRenderImages(imageList);
})
.catch(() => null);
};
//Crop image
const cropImage = item => {
ImagePicker.openCropper({
path: item.imgs,
width: 400,
height: 400,
})
.then(image => {
const oldImage = renderImages.findIndex(img => img.imgs === item.imgs);
renderImages[oldImage] = {imgs: image.path};
})
.catch(() => null);
};
</code></pre>
|
[
{
"answer_id": 74528116,
"author": "ikegami",
"author_id": 589924,
"author_profile": "https://Stackoverflow.com/users/589924",
"pm_score": 3,
"selected": true,
"text": ".rows[] zsh .rows[] jq jq '.rows[]' file.json\n"
},
{
"answer_id": 74533184,
"author": "0stone0",
"author_id": 5625547,
"author_profile": "https://Stackoverflow.com/users/5625547",
"pm_score": 0,
"selected": false,
"text": "noglob noglob jq .rows[] input\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16421620/"
] |
74,528,017
|
<p>I'm trying to solve Codewars task and facing issue that looks strange to me.</p>
<p>Codewars task is to write function digital_root(n) that sums digits of n until the end result has only 1 digit in it.
Example: 942 --> 9 + 4 + 2 = 15 --> 1 + 5 = 6 (the function returns 6).</p>
<p>I wrote some bulky code with supporting functions, please see code with notes below.</p>
<p>The problem - digital_root function works only if I put cout line in while loop. The function returns nonsense without this cout line (please see notes in the code of the function).</p>
<p>My questions are:</p>
<ol>
<li>Why isn't digital_root working without cout line?</li>
<li>How cout line can effect the result of the function?</li>
<li>Why does cout line fix the code?</li>
</ol>
<p>Thanks a lot in advance! I'm a beginner, spent several days trying to solve the issue.</p>
<pre><code>#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int getDigit (int, int);
int sumDigits (int);
int digital_root (int);
int main()
{
cout << digital_root (942); // expected output result is 6 because 9 + 4 + 2 = 15 -> 1 + 5 = 6
}
int getDigit (int inputNum, int position) // returns digit of inputNum that sits on a particular position (works)
{
int empoweredTen = pow(10, position-1);
return inputNum / empoweredTen % 10;
}
int sumDigits (int inputNum) // returns sum of digits of inputNum (works)
{
int sum;
int inLen = to_string(inputNum).length();
int i = inLen;
while (inLen --)
{
sum += getDigit(inputNum, i);
i --;
}
return sum;
}
int digital_root (int inputNum) // supposed to calculate sum of digits until number has 1 digit in it (abnormal behavior)
{
int n = inputNum;
while (n > 9)
{
n = sumDigits(n);
cout << "The current n is: " << n << endl; // !!! function doesn't work without this line !!!
}
return n;
}
</code></pre>
<p>I've tried to rewrite the code from scratch several times with Google to find a mistake but I can't see it. I expect digital_root() to work without any cout lines in it. Currently, if I delete cout line from while loop in digital_root(), the function returns -2147483647 after 13 seconds of calculations. Sad.</p>
|
[
{
"answer_id": 74528116,
"author": "ikegami",
"author_id": 589924,
"author_profile": "https://Stackoverflow.com/users/589924",
"pm_score": 3,
"selected": true,
"text": ".rows[] zsh .rows[] jq jq '.rows[]' file.json\n"
},
{
"answer_id": 74533184,
"author": "0stone0",
"author_id": 5625547,
"author_profile": "https://Stackoverflow.com/users/5625547",
"pm_score": 0,
"selected": false,
"text": "noglob noglob jq .rows[] input\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20567597/"
] |
74,528,026
|
<p>If you select the "tv" option, it displays a div, and if you select the "cooker" options, it displays a different div. I want to make it so when one option is selected, the prior div elements have their display become "none."</p>
<p>I've tried making it so when a value is selected, it's display is equal to block and I made an array to make the other div element displays to "none." My code doesn't work though.</p>
<p>Thank you to anyone that helps.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const tvContainer=document.getElementsByClassName("tv-options-container")[0];
const applianceType=document.getElementById("appliance-type");
// const applianceOptions=document.querySelectorAll(".appliance-type.option");
const opTest=document.querySelectorAll("appliance-type.option");
var selectedApp=null;
var optionsArr=[];
var values = Array.from(document.getElementById("appliance-type").options).map(e => e.value);
optionsArr.append(values);
function show(value_){
document.getElementById(value_).style.display="block";
for(let i=0;i<optionsArr.length;i++){
if(optionsArr[i]!=value_){
document.getElementById(optionsArr[i]).style.display="none";
}
}
// selectedApp=applianceType.value;
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
box-sizing: border-box;
}
fieldset {
padding: 0;
}
.options {
height: 30px;
-moz-appearance: none; /* Firefox */
-webkit-appearance: none; /* Safari and Chrome */
appearance: none;
padding-right: 1.25em;
padding-left: 0.25em;
border-radius: 10px;
background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' version='1.1' height='10px' width='15px'%3E%3Ctext x='0' y='11' fill='lightblue'%3E%E2%96%BE%3C/text%3E%3C/svg%3E");
background-repeat: no-repeat;
background-size: 1.5em 1em;
background-position: right center;
margin-bottom: 20px;
}
.tv-options-container,
.cooker-options-container {
display: none;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><main>
<h1>Add appliance</h1>
<p>Please provide the details for the appliance</p>
<form action="">
<fieldset style="border: none">
<label for="appliance-type">Appliance type:</label>
<select onchange="show(value)" class="options" name="appliance-type" id="appliance-type">
<option value="" selected disabled>Choose appliance</option>
<option value="tv">TV</option>
<option value="cooker">Cooker</option>
</select>
<!-- style="display:none;" -->
<div class="tv-options-container" id="tv">
<label for="manufacturer">Manufacturer: &#160;</label>
<select class="options" name="tv-manufacturer" id="tv-manufacturer">
<option value="" selected disabled></option>
<option value="narkasse">Narkasse</option>
</select>
<br />
<label for="model-name">Model Name</label>
<input type="text" name="model-name" id="model-name" />
<br />
<hr />
<label for="">Display Type</label>
<select class="option" name="" id="">
<option value="" selected disabled></option>
<option value="display-type">LED</option>
</select>
</div>
<div class="cooker-options-container" style="display: none" id="cooker">
<p>cooker</p>
<p>cooker</p>
<p>cooker</p>
</div>
</fieldset>
</form>
</main></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74528116,
"author": "ikegami",
"author_id": 589924,
"author_profile": "https://Stackoverflow.com/users/589924",
"pm_score": 3,
"selected": true,
"text": ".rows[] zsh .rows[] jq jq '.rows[]' file.json\n"
},
{
"answer_id": 74533184,
"author": "0stone0",
"author_id": 5625547,
"author_profile": "https://Stackoverflow.com/users/5625547",
"pm_score": 0,
"selected": false,
"text": "noglob noglob jq .rows[] input\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20134440/"
] |
74,528,041
|
<p>I have a dataframe with column <code>df['EVENT_DTL']</code> that looks like this;</p>
<pre><code>1. ๋ณ์ฌ์ ์ ๋ณด : Kim_******-1****** 2. ๋ฐ๊ฒฌ์ผ์ : 2013๋
05์18์ผ 13:00 3. ๋ฐ๊ฒฌ์ฅ์ : 1) ์์ฌ๊ธฐ๋ก ์ ์ฃผ์ ์ฃผ๋ฏผ๋ฑ๋ก์ ์ฃผ์ : ์ค๊ฑฐ์ฃผ์ง ์ฃผ์ : ์๋(๋ฐ๊ฒฌ)์ฅ์ ์ฃผ์ : 2) ์ค์ ์กฐ์ฌ์์ด ์
๋ ฅํ ์ฃผ์์ฃผ๋ฏผ๋ฑ๋ก์ ์ฃผ์ : ์ค๊ฑฐ์ฃผ์ง ์ฃผ์ : ์๋(๋ฐ๊ฒฌ)์ฅ์ ์ฃผ์ : ์กฐ์น(์ฌ์ ํฌํจ) : 4. ๋ฐ๊ฒฌ์ฅ์ ์ฝ๋ฉ์ฌ์ : ์ํ / 5. ๋ฐฉ๋ฒ/์๋จ : ๋ชฉ๋งค๋ฌ๊ธฐ6. ๋ฐ๊ฒฌ๊ฒฝ์ : 2013.5.18 13:00๊ฒฝ New York, in his apartment 7. ์ฃผ์์ธ ์ฝ๋ฉ์ฌ์ : Family reason 8. ๊ธฐ๋ณธ๋ฐฐ๊ฒฝ์ ๋ณด : ์๋จ๋๋งค์
/ ์๋
๋ฐ ์์ฃผ ๊ณผ ๊ฑฐ์ฃผ ๊ฒฐํผ์ํ_๋ณ๊ฑฐ 9. ์ฌํ๊ฒฝ์ ์ ์ํ : Strong depression 10. ์ฑ๊ฒฉ : ์์์์ 11. ๋์ธ๊ด๊ณ : ๋์ธ๊ด๊ณ๋ฌธ์ _๋ชจ๋ฆ,์น๊ตฌ ๊ด๋ จ 12. ์ ์์ํ : ์ฐ์ธํ ๊ธฐ๋ถ ๊ด์ฐฐ๋จ 13. ๊ฒฝ์ฐฐ ์ต์ข
์์ดํ๋จ์ ๋ฌด ๋ฐ ๋ด์ฉ : ์์ด_๊ฐ์กฑ๊ด๊ณ๋ฌธ์ _ ๋ชฉ๋งค๋ฌ๊ธฐ 14. ์ฝ๋ก๋์์ ๊ด๋ จ์ฑ : ์์_2020๋
์ด์ ์ฌ๋ง 15. ์ฝ๋ก๋์ ์์ด์ํฅ ๋ฐ ์ฃผ์์ธ : ์์_2020๋
์ด์ ์ฌ๋ง
</code></pre>
<p>NOTE: The above is one line, not a separate line. I'm just displaying it for your convenience.</p>
<p>I want to spilt <code>1. 2. 3. โฆ 15.</code> and append "\n" before the numbers.</p>
<p>Desired output looks like this:</p>
<pre><code>\n1. ๋ณ์ฌ์ ์ ๋ณด : Kim_******-1******
\n2. ๋ฐ๊ฒฌ์ผ์ : 2013๋
05์18์ผ 13:00
\n3. ๋ฐ๊ฒฌ์ฅ์ :
\n1) ์์ฌ๊ธฐ๋ก ์ ์ฃผ์
์ฃผ๋ฏผ๋ฑ๋ก์ ์ฃผ์ :
์ค๊ฑฐ์ฃผ์ง ์ฃผ์ :
์๋(๋ฐ๊ฒฌ)์ฅ์ ์ฃผ์ :
\n2) ์ค์ ์กฐ์ฌ์์ด ์
๋ ฅํ ์ฃผ์
์ฃผ๋ฏผ๋ฑ๋ก์ ์ฃผ์ :
์ค๊ฑฐ์ฃผ์ง ์ฃผ์ :
์๋(๋ฐ๊ฒฌ)์ฅ์ ์ฃผ์ :
์กฐ์น(์ฌ์ ํฌํจ) :
\n4. ๋ฐ๊ฒฌ์ฅ์ ์ฝ๋ฉ์ฌ์ : ์ํ /
\n5. ๋ฐฉ๋ฒ/์๋จ : ๋ชฉ๋งค๋ฌ๊ธฐ
\n6. ๋ฐ๊ฒฌ๊ฒฝ์ : 2013.5.18 13:00๊ฒฝ New York, in his apartment
\n7. ์ฃผ์์ธ ์ฝ๋ฉ์ฌ์ : Family reason
\n8. ๊ธฐ๋ณธ๋ฐฐ๊ฒฝ์ ๋ณด : ์๋จ๋๋งค์
/ ์๋
๋ฐ ์์ฃผ ๊ณผ ๊ฑฐ์ฃผ ๊ฒฐํผ์ํ_๋ณ๊ฑฐ
\n9. ์ฌํ๊ฒฝ์ ์ ์ํ : Strong depression
\n10. ์ฑ๊ฒฉ : ์์์์
\n11. ๋์ธ๊ด๊ณ : ๋์ธ๊ด๊ณ๋ฌธ์ _๋ชจ๋ฆ,์น๊ตฌ ๊ด๋ จ
\n12. ์ ์์ํ : ์ฐ์ธํ ๊ธฐ๋ถ ๊ด์ฐฐ๋จ
\n13. ๊ฒฝ์ฐฐ ์ต์ข
์์ดํ๋จ์ ๋ฌด ๋ฐ ๋ด์ฉ : ์์ด_๊ฐ์กฑ๊ด๊ณ๋ฌธ์ _ ๋ชฉ๋งค๋ฌ๊ธฐ
\n14. ์ฝ๋ก๋์์ ๊ด๋ จ์ฑ : ์์_2020๋
์ด์ ์ฌ๋ง
\n15. ์ฝ๋ก๋์ ์์ด์ํฅ ๋ฐ ์ฃผ์์ธ : ์์_2020๋
์ด์ ์ฌ๋ง
</code></pre>
<p>I tried this (note: there are some rows that are already starts with <code>\n</code>):</p>
<pre><code>import re
df3 = df.loc[~df.EVENT_DTL.str.contains('\n',na=False),'EVENT_DTL']
re.split('(?<=1.|(?<=2.||(?<=3.|(?<=1\)|(?<=2)|(?<=4.|(?<=5.|(?<=6.|(?<=7.|(?<=8.|(?<=9.|(?<=10.|(?<=11.|(?<=12.|(?<=13.|(?<=14.|(?<=15.',df3)
</code></pre>
<p>but it cause the error such as (sorry for the long code):</p>
<pre><code>error Traceback (most recent call last)
<ipython-input-20-3b8b06001e11> in <module>
2
3 df3 = df.loc[~df.EVENT_DTL.str.contains('\n',na=False),'EVENT_DTL']
----> 4 re.split('(?<=1.|(?<=2.||(?<=3.|(?<=1\)|(?<=2)|(?<=4.|(?<=5.|(?<=6.|(?<=7.|(?<=8.|(?<=9.|(?<=10.|(?<=11.|(?<=12.|(?<=13.|(?<=14.|(?<=15.',df3)
35 frames
/usr/lib/python3.7/re.py in split(pattern, string, maxsplit, flags)
213 and the remainder of the string is returned as the final element
214 of the list."""
--> 215 return _compile(pattern, flags).split(string, maxsplit)
216
217 def findall(pattern, string, flags=0):
/usr/lib/python3.7/re.py in _compile(pattern, flags)
286 if not sre_compile.isstring(pattern):
287 raise TypeError("first argument must be string or compiled pattern")
--> 288 p = sre_compile.compile(pattern, flags)
289 if not (flags & DEBUG):
290 if len(_cache) >= _MAXCACHE:
/usr/lib/python3.7/sre_compile.py in compile(p, flags)
762 if isstring(p):
763 pattern = p
--> 764 p = sre_parse.parse(p, flags)
765 else:
766 pattern = None
/usr/lib/python3.7/sre_parse.py in parse(str, flags, pattern)
922
923 try:
--> 924 p = _parse_sub(source, pattern, flags & SRE_FLAG_VERBOSE, 0)
925 except Verbose:
926 # the VERBOSE flag was switched on inside the pattern. to be
/usr/lib/python3.7/sre_parse.py in _parse_sub(source, state, verbose, nested)
418 while True:
419 itemsappend(_parse(source, state, verbose, nested + 1,
--> 420 not nested and not items))
421 if not sourcematch("|"):
422 break
/usr/lib/python3.7/sre_parse.py in _parse(source, state, verbose, nested, first)
728 if lookbehindgroups is None:
729 state.lookbehindgroups = state.groups
--> 730 p = _parse_sub(source, state, verbose, nested + 1)
731 if dir < 0:
732 if lookbehindgroups is None:
/usr/lib/python3.7/sre_parse.py in _parse_sub(source, state, verbose, nested)
418 while True:
419 itemsappend(_parse(source, state, verbose, nested + 1,
--> 420 not nested and not items))
421 if not sourcematch("|"):
422 break
/usr/lib/python3.7/sre_parse.py in _parse(source, state, verbose, nested, first)
728 if lookbehindgroups is None:
729 state.lookbehindgroups = state.groups
--> 730 p = _parse_sub(source, state, verbose, nested + 1)
731 if dir < 0:
732 if lookbehindgroups is None:
/usr/lib/python3.7/sre_parse.py in _parse_sub(source, state, verbose, nested)
418 while True:
419 itemsappend(_parse(source, state, verbose, nested + 1,
--> 420 not nested and not items))
421 if not sourcematch("|"):
422 break
/usr/lib/python3.7/sre_parse.py in _parse(source, state, verbose, nested, first)
728 if lookbehindgroups is None:
729 state.lookbehindgroups = state.groups
--> 730 p = _parse_sub(source, state, verbose, nested + 1)
731 if dir < 0:
732 if lookbehindgroups is None:
/usr/lib/python3.7/sre_parse.py in _parse_sub(source, state, verbose, nested)
418 while True:
419 itemsappend(_parse(source, state, verbose, nested + 1,
--> 420 not nested and not items))
421 if not sourcematch("|"):
422 break
/usr/lib/python3.7/sre_parse.py in _parse(source, state, verbose, nested, first)
728 if lookbehindgroups is None:
729 state.lookbehindgroups = state.groups
--> 730 p = _parse_sub(source, state, verbose, nested + 1)
731 if dir < 0:
732 if lookbehindgroups is None:
/usr/lib/python3.7/sre_parse.py in _parse_sub(source, state, verbose, nested)
418 while True:
419 itemsappend(_parse(source, state, verbose, nested + 1,
--> 420 not nested and not items))
421 if not sourcematch("|"):
422 break
/usr/lib/python3.7/sre_parse.py in _parse(source, state, verbose, nested, first)
728 if lookbehindgroups is None:
729 state.lookbehindgroups = state.groups
--> 730 p = _parse_sub(source, state, verbose, nested + 1)
731 if dir < 0:
732 if lookbehindgroups is None:
/usr/lib/python3.7/sre_parse.py in _parse_sub(source, state, verbose, nested)
418 while True:
419 itemsappend(_parse(source, state, verbose, nested + 1,
--> 420 not nested and not items))
421 if not sourcematch("|"):
422 break
/usr/lib/python3.7/sre_parse.py in _parse(source, state, verbose, nested, first)
728 if lookbehindgroups is None:
729 state.lookbehindgroups = state.groups
--> 730 p = _parse_sub(source, state, verbose, nested + 1)
731 if dir < 0:
732 if lookbehindgroups is None:
/usr/lib/python3.7/sre_parse.py in _parse_sub(source, state, verbose, nested)
418 while True:
419 itemsappend(_parse(source, state, verbose, nested + 1,
--> 420 not nested and not items))
421 if not sourcematch("|"):
422 break
/usr/lib/python3.7/sre_parse.py in _parse(source, state, verbose, nested, first)
728 if lookbehindgroups is None:
729 state.lookbehindgroups = state.groups
--> 730 p = _parse_sub(source, state, verbose, nested + 1)
731 if dir < 0:
732 if lookbehindgroups is None:
/usr/lib/python3.7/sre_parse.py in _parse_sub(source, state, verbose, nested)
418 while True:
419 itemsappend(_parse(source, state, verbose, nested + 1,
--> 420 not nested and not items))
421 if not sourcematch("|"):
422 break
/usr/lib/python3.7/sre_parse.py in _parse(source, state, verbose, nested, first)
728 if lookbehindgroups is None:
729 state.lookbehindgroups = state.groups
--> 730 p = _parse_sub(source, state, verbose, nested + 1)
731 if dir < 0:
732 if lookbehindgroups is None:
/usr/lib/python3.7/sre_parse.py in _parse_sub(source, state, verbose, nested)
418 while True:
419 itemsappend(_parse(source, state, verbose, nested + 1,
--> 420 not nested and not items))
421 if not sourcematch("|"):
422 break
/usr/lib/python3.7/sre_parse.py in _parse(source, state, verbose, nested, first)
728 if lookbehindgroups is None:
729 state.lookbehindgroups = state.groups
--> 730 p = _parse_sub(source, state, verbose, nested + 1)
731 if dir < 0:
732 if lookbehindgroups is None:
/usr/lib/python3.7/sre_parse.py in _parse_sub(source, state, verbose, nested)
418 while True:
419 itemsappend(_parse(source, state, verbose, nested + 1,
--> 420 not nested and not items))
421 if not sourcematch("|"):
422 break
/usr/lib/python3.7/sre_parse.py in _parse(source, state, verbose, nested, first)
728 if lookbehindgroups is None:
729 state.lookbehindgroups = state.groups
--> 730 p = _parse_sub(source, state, verbose, nested + 1)
731 if dir < 0:
732 if lookbehindgroups is None:
/usr/lib/python3.7/sre_parse.py in _parse_sub(source, state, verbose, nested)
418 while True:
419 itemsappend(_parse(source, state, verbose, nested + 1,
--> 420 not nested and not items))
421 if not sourcematch("|"):
422 break
/usr/lib/python3.7/sre_parse.py in _parse(source, state, verbose, nested, first)
728 if lookbehindgroups is None:
729 state.lookbehindgroups = state.groups
--> 730 p = _parse_sub(source, state, verbose, nested + 1)
731 if dir < 0:
732 if lookbehindgroups is None:
/usr/lib/python3.7/sre_parse.py in _parse_sub(source, state, verbose, nested)
418 while True:
419 itemsappend(_parse(source, state, verbose, nested + 1,
--> 420 not nested and not items))
421 if not sourcematch("|"):
422 break
/usr/lib/python3.7/sre_parse.py in _parse(source, state, verbose, nested, first)
728 if lookbehindgroups is None:
729 state.lookbehindgroups = state.groups
--> 730 p = _parse_sub(source, state, verbose, nested + 1)
731 if dir < 0:
732 if lookbehindgroups is None:
/usr/lib/python3.7/sre_parse.py in _parse_sub(source, state, verbose, nested)
418 while True:
419 itemsappend(_parse(source, state, verbose, nested + 1,
--> 420 not nested and not items))
421 if not sourcematch("|"):
422 break
/usr/lib/python3.7/sre_parse.py in _parse(source, state, verbose, nested, first)
728 if lookbehindgroups is None:
729 state.lookbehindgroups = state.groups
--> 730 p = _parse_sub(source, state, verbose, nested + 1)
731 if dir < 0:
732 if lookbehindgroups is None:
/usr/lib/python3.7/sre_parse.py in _parse_sub(source, state, verbose, nested)
418 while True:
419 itemsappend(_parse(source, state, verbose, nested + 1,
--> 420 not nested and not items))
421 if not sourcematch("|"):
422 break
/usr/lib/python3.7/sre_parse.py in _parse(source, state, verbose, nested, first)
728 if lookbehindgroups is None:
729 state.lookbehindgroups = state.groups
--> 730 p = _parse_sub(source, state, verbose, nested + 1)
731 if dir < 0:
732 if lookbehindgroups is None:
/usr/lib/python3.7/sre_parse.py in _parse_sub(source, state, verbose, nested)
418 while True:
419 itemsappend(_parse(source, state, verbose, nested + 1,
--> 420 not nested and not items))
421 if not sourcematch("|"):
422 break
/usr/lib/python3.7/sre_parse.py in _parse(source, state, verbose, nested, first)
728 if lookbehindgroups is None:
729 state.lookbehindgroups = state.groups
--> 730 p = _parse_sub(source, state, verbose, nested + 1)
731 if dir < 0:
732 if lookbehindgroups is None:
/usr/lib/python3.7/sre_parse.py in _parse_sub(source, state, verbose, nested)
418 while True:
419 itemsappend(_parse(source, state, verbose, nested + 1,
--> 420 not nested and not items))
421 if not sourcematch("|"):
422 break
/usr/lib/python3.7/sre_parse.py in _parse(source, state, verbose, nested, first)
734 if not sourcematch(")"):
735 raise source.error("missing ), unterminated subpattern",
--> 736 source.tell() - start)
737 if char == "=":
738 subpatternappend((ASSERT, (dir, p)))
error: missing ), unterminated subpattern at position 119
</code></pre>
|
[
{
"answer_id": 74528116,
"author": "ikegami",
"author_id": 589924,
"author_profile": "https://Stackoverflow.com/users/589924",
"pm_score": 3,
"selected": true,
"text": ".rows[] zsh .rows[] jq jq '.rows[]' file.json\n"
},
{
"answer_id": 74533184,
"author": "0stone0",
"author_id": 5625547,
"author_profile": "https://Stackoverflow.com/users/5625547",
"pm_score": 0,
"selected": false,
"text": "noglob noglob jq .rows[] input\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20376341/"
] |
74,528,046
|
<p>I have a recyclerView that loads songs from memory and when I scroll it lags,
This is my ViewBinding.</p>
<pre><code>override fun onBindViewHolder(holder: MyHolder, position: Int) {
holder.titleView.text = musicList[position].title
holder.albumName.text = musicList[position].artist
holder.duration.text = formatDuration(musicList[position].length)
Glide
.with(context)
.load(musicList[position].artUri)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.apply(RequestOptions().placeholder(R.drawable.image_as_cover).centerCrop())
.into(holder.imageView)
holder.itemView.setOnClickListener {
if (MainActivity.isSearching)
sendIntent(position = position, parameter = "MusicAdapterSearch")
else
sendIntent(position = position, parameter = "MusicAdapter")
}
}
</code></pre>
<p>I noticed that when I removed image loading from binding i.e Glide, I did not lag, and it only first scrolled each time I open the app.
How can I Handle the lag, is there any other library I should use or any caching-like thing?
Here is my XML.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:theme="@style/Theme.Music.Font">
<com.google.android.material.imageview.ShapeableImageView
android:id="@+id/imageView"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentStart="true"
android:layout_margin="5dp"
android:contentDescription="@string/cover"
android:src="@drawable/image_as_cover"
app:shapeAppearance="@style/roundedImageView" />
<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toStartOf="@+id/duration"
android:layout_toEndOf="@+id/imageView"
android:orientation="vertical">
<TextView
android:id="@+id/titleView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:fontFamily="@font/medium"
android:maxLines="1"
android:singleLine="true"
android:text="@string/love_is_gone_by_slander_forever_on_love"
android:textSize="15sp" />
<TextView
android:id="@+id/albumName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:fontFamily="@font/medium"
android:maxLines="1"
android:text="@string/albumName"
android:textSize="12sp"
android:theme="@style/Theme.Music.FontColor" />
</LinearLayout>
<TextView
android:id="@+id/duration"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:layout_margin="10dp"
android:fontFamily="@font/medium"
android:maxLines="1"
android:text="@string/duration"
android:textSize="11sp" />
</RelativeLayout>
</code></pre>
|
[
{
"answer_id": 74528305,
"author": "Kushal Prajapati",
"author_id": 14070467,
"author_profile": "https://Stackoverflow.com/users/14070467",
"pm_score": 2,
"selected": false,
"text": " RequestOptions myOptions = new RequestOptions()\n .centerCrop() // or centerCrop\n .override(800, 500);//your imageview frame size\n\n Glide.with(activity)\n .applyDefaultRequestOptions(myOptions)\n .load(list.get(position).appthumbnail)\n .error(R.drawable.no_image_available)\n .into(holder.ivImage);\n\n"
},
{
"answer_id": 74541015,
"author": "Android Newbie A",
"author_id": 20125791,
"author_profile": "https://Stackoverflow.com/users/20125791",
"pm_score": 2,
"selected": true,
"text": "relative layout linear layout constraint layout <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<androidx.constraintlayout.widget.ConstraintLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_margin=\"5dp\"\n android:theme=\"@style/Theme.Music.Font\">\n\n <com.google.android.material.imageview.ShapeableImageView\n android:id=\"@+id/imageView\"\n android:layout_width=\"50dp\"\n android:layout_height=\"50dp\"\n android:layout_alignParentStart=\"true\"\n android:layout_margin=\"5dp\"\n\n android:contentDescription=\"@string/cover\"\n android:src=\"@drawable/image_as_cover\"\n app:shapeAppearance=\"@style/roundedImageView\"\n \n app:layout_constraintTop_toTopOf=\"parent\"\n app:layout_constraintBottom_toBottomOf=\"parent\"\n app:layout_constraintStart_toStartOf=\"parent\" />\n\n\n <View\n android:id=\"@+id/linearLayout\"\n android:layout_width=\"0dp\"\n android:layout_height=\"0dp\"\n\n app:layout_constraintTop_toTopOf=\"parent\"\n app:layout_constraintBottom_toBottomOf=\"parent\"\n app:layout_constraintStart_toEndOf=\"@id/imageView\"\n app:layout_constraintEnd_toEndOf=\"parent\" />\n\n <TextView\n android:id=\"@+id/titleView\"\n android:layout_width=\"0dp\"\n android:layout_height=\"wrap_content\"\n android:layout_margin=\"5dp\"\n\n android:maxLines=\"1\"\n android:singleLine=\"true\"\n android:fontFamily=\"@font/medium\"\n android:text=\"@string/love_is_gone_by_slander_forever_on_love\"\n android:textSize=\"15sp\"\n android:text=\"123\"\n app:layout_constraintTop_toTopOf=\"@id/linearLayout\"\n app:layout_constraintBottom_toTopOf=\"@id/albumName\"\n app:layout_constraintStart_toStartOf=\"@id/linearLayout\"\n app:layout_constraintEnd_toEndOf=\"@id/linearLayout\" />\n \n <TextView\n android:id=\"@+id/albumName\"\n android:layout_width=\"0dp\"\n android:layout_height=\"wrap_content\"\n android:layout_margin=\"5dp\"\n android:fontFamily=\"@font/medium\"\n android:maxLines=\"1\"\n android:singleLine=\"true\"\n android:text=\"@string/love_is_gone_by_slander_forever_on_love\"\n android:textSize=\"15sp\"\n\n app:layout_constraintTop_toBottomOf=\"@id/titleView\"\n app:layout_constraintBottom_toTopOf=\"@id/duration\"\n app:layout_constraintStart_toStartOf=\"@id/linearLayout\"\n app:layout_constraintEnd_toEndOf=\"@id/linearLayout\" />\n\n <TextView\n android:id=\"@+id/duration\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentEnd=\"true\"\n android:layout_centerVertical=\"true\"\n android:layout_margin=\"10dp\"\n android:fontFamily=\"@font/medium\"\n android:maxLines=\"1\"\n android:text=\"@string/duration\"\n android:textSize=\"11sp\"\n\n app:layout_constraintTop_toBottomOf=\"@id/albumName\"\n app:layout_constraintBottom_toBottomOf=\"@id/linearLayout\"\n app:layout_constraintStart_toStartOf=\"@id/linearLayout\"\n app:layout_constraintEnd_toEndOf=\"@id/linearLayout\" />\n \n</androidx.constraintlayout.widget.ConstraintLayout>\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19468261/"
] |
74,528,070
|
<p><a href="https://i.stack.imgur.com/7o4ze.png" rel="nofollow noreferrer">i am getting the error "EmptyDataError No columns to parse from file" when i am reading the data from csv file to json file...</a></p>
<p>i want to insert the data from csv file to json file</p>
|
[
{
"answer_id": 74528305,
"author": "Kushal Prajapati",
"author_id": 14070467,
"author_profile": "https://Stackoverflow.com/users/14070467",
"pm_score": 2,
"selected": false,
"text": " RequestOptions myOptions = new RequestOptions()\n .centerCrop() // or centerCrop\n .override(800, 500);//your imageview frame size\n\n Glide.with(activity)\n .applyDefaultRequestOptions(myOptions)\n .load(list.get(position).appthumbnail)\n .error(R.drawable.no_image_available)\n .into(holder.ivImage);\n\n"
},
{
"answer_id": 74541015,
"author": "Android Newbie A",
"author_id": 20125791,
"author_profile": "https://Stackoverflow.com/users/20125791",
"pm_score": 2,
"selected": true,
"text": "relative layout linear layout constraint layout <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<androidx.constraintlayout.widget.ConstraintLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_margin=\"5dp\"\n android:theme=\"@style/Theme.Music.Font\">\n\n <com.google.android.material.imageview.ShapeableImageView\n android:id=\"@+id/imageView\"\n android:layout_width=\"50dp\"\n android:layout_height=\"50dp\"\n android:layout_alignParentStart=\"true\"\n android:layout_margin=\"5dp\"\n\n android:contentDescription=\"@string/cover\"\n android:src=\"@drawable/image_as_cover\"\n app:shapeAppearance=\"@style/roundedImageView\"\n \n app:layout_constraintTop_toTopOf=\"parent\"\n app:layout_constraintBottom_toBottomOf=\"parent\"\n app:layout_constraintStart_toStartOf=\"parent\" />\n\n\n <View\n android:id=\"@+id/linearLayout\"\n android:layout_width=\"0dp\"\n android:layout_height=\"0dp\"\n\n app:layout_constraintTop_toTopOf=\"parent\"\n app:layout_constraintBottom_toBottomOf=\"parent\"\n app:layout_constraintStart_toEndOf=\"@id/imageView\"\n app:layout_constraintEnd_toEndOf=\"parent\" />\n\n <TextView\n android:id=\"@+id/titleView\"\n android:layout_width=\"0dp\"\n android:layout_height=\"wrap_content\"\n android:layout_margin=\"5dp\"\n\n android:maxLines=\"1\"\n android:singleLine=\"true\"\n android:fontFamily=\"@font/medium\"\n android:text=\"@string/love_is_gone_by_slander_forever_on_love\"\n android:textSize=\"15sp\"\n android:text=\"123\"\n app:layout_constraintTop_toTopOf=\"@id/linearLayout\"\n app:layout_constraintBottom_toTopOf=\"@id/albumName\"\n app:layout_constraintStart_toStartOf=\"@id/linearLayout\"\n app:layout_constraintEnd_toEndOf=\"@id/linearLayout\" />\n \n <TextView\n android:id=\"@+id/albumName\"\n android:layout_width=\"0dp\"\n android:layout_height=\"wrap_content\"\n android:layout_margin=\"5dp\"\n android:fontFamily=\"@font/medium\"\n android:maxLines=\"1\"\n android:singleLine=\"true\"\n android:text=\"@string/love_is_gone_by_slander_forever_on_love\"\n android:textSize=\"15sp\"\n\n app:layout_constraintTop_toBottomOf=\"@id/titleView\"\n app:layout_constraintBottom_toTopOf=\"@id/duration\"\n app:layout_constraintStart_toStartOf=\"@id/linearLayout\"\n app:layout_constraintEnd_toEndOf=\"@id/linearLayout\" />\n\n <TextView\n android:id=\"@+id/duration\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentEnd=\"true\"\n android:layout_centerVertical=\"true\"\n android:layout_margin=\"10dp\"\n android:fontFamily=\"@font/medium\"\n android:maxLines=\"1\"\n android:text=\"@string/duration\"\n android:textSize=\"11sp\"\n\n app:layout_constraintTop_toBottomOf=\"@id/albumName\"\n app:layout_constraintBottom_toBottomOf=\"@id/linearLayout\"\n app:layout_constraintStart_toStartOf=\"@id/linearLayout\"\n app:layout_constraintEnd_toEndOf=\"@id/linearLayout\" />\n \n</androidx.constraintlayout.widget.ConstraintLayout>\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20569138/"
] |
74,528,080
|
<p>Facing some compilation errors when using the below example with a variable number of arguments & need some help to find some solution or some better approach.</p>
<p>I am trying to initialize the class variables based on input arguments supplied below criteria, like in the below example I am willing to initialize the "data" class methods "select_area1_object" & "select_area2_object" in which arguments are variable but I am willing to create some common way in which from main I just need to pass the type(which is area code in this example or any other input parameter) & arguments of it, from the type value passed from main class should decide which function to call and based on that it should initialize its variable number of arguments, please see below example.</p>
<pre><code>#include <iostream>
#include <functional>
using namespace std;
enum area {AREA_1, AREA_2, AREA_3};
class data {
public :
int number;
std::string name;
std::string address;
int area_code;
template <typename type, typename... args>
void create_object(type t, args&&... arg)
{
// here area1 or are2 methods should be called based on type & it should process variable arguments supplied from main.
if(t == AREA_1)
{
select_area1_object(arg...);
}
else if(t == AREA_2)
{
select_area2_object(arg...);
}
}
void select_area1_object(int num, std::string nm, std::string ad)
{
number = num;
name = nm;
address = ad;
}
void select_area2_object(int num, std::string nm)
{
number = num;
name = nm;
}
};
// trying to create a common template here so that from the main I will not have to create an object and only need to worry about passing output arguments (like number, name, address).
template <typename type, typename... args>
void request_process(type t, args&&... arg)
{
data d;
d.create_object(t, std::forward<args>(arg)...);
}
int main()
{
request_process(1, 1, "area1", "area1_address");
request_process(2, 2, "area2");
std::cout << "End of program" << endl;
}
</code></pre>
<p>seeing below errors :</p>
<pre><code>tmp/858Sn1cFdf.cpp: In instantiation of 'void data::create_object(type, args&& ...) [with type = int; args = {int, const char (&)[6], const char (&)[14]}]':
/tmp/858Sn1cFdf.cpp:45:5: required from 'void request_process(type, args&& ...) [with type = int; args = {int, const char (&)[6], const char (&)[14]}]'
/tmp/858Sn1cFdf.cpp:50:51: required from here
/tmp/858Sn1cFdf.cpp:24:13: error: no matching function for call to 'data::select_area2_object(int&, const char [6], const char [14])'
24 | select_area2_object(arg...);
| ^~~~~~~~~~~~~~~~~~~
/tmp/858Sn1cFdf.cpp:34:10: note: candidate: 'void data::select_area2_object(int, std::string)'
34 | void select_area2_object(int num, std::string nm)
| ^~~~~~~~~~~~~~~~~~~
/tmp/858Sn1cFdf.cpp:34:10: note: candidate expects 2 arguments, 3 provided
/tmp/858Sn1cFdf.cpp: In instantiation of 'void data::create_object(type, args&& ...) [with type = int; args = {int, const char (&)[6]}]':
/tmp/858Sn1cFdf.cpp:45:5: required from 'void request_process(type, args&& ...) [with type = int; args = {int, const char (&)[6]}]'
/tmp/858Sn1cFdf.cpp:51:34: required from here
/tmp/858Sn1cFdf.cpp:20:13: error: no matching function for call to 'data::select_area1_object(int&, const char [6])'
20 | select_area1_object(arg...);
| ^~~~~~~~~~~~~~~~~~~
/tmp/858Sn1cFdf.cpp:28:10: note: candidate: 'void data::select_area1_object(int, std::string, std::string)'
28 | void select_area1_object(int num, std::string nm, std::string ad)
| ^~~~~~~~~~~~~~~~~~~
/tmp/858Sn1cFdf.cpp:28:10: note: **candidate expects 3 arguments, 2 provided**
</code></pre>
<p>If I remove the AREA2 functionality from the class like its method, conditional check & calling from main "request_process(2, 2, "area2");" it's working fine, so it's not accepting variable arguments I think, the same thing tried with other project but same argument error is seen, and I am willing to write some more functionality based on this in which arguments will vary & do not want to create class object in main & let template handle class object creation and initialization of class method.</p>
<p>Please suggest to me if this has already some solution provided as I did not find similar problems described.</p>
|
[
{
"answer_id": 74528305,
"author": "Kushal Prajapati",
"author_id": 14070467,
"author_profile": "https://Stackoverflow.com/users/14070467",
"pm_score": 2,
"selected": false,
"text": " RequestOptions myOptions = new RequestOptions()\n .centerCrop() // or centerCrop\n .override(800, 500);//your imageview frame size\n\n Glide.with(activity)\n .applyDefaultRequestOptions(myOptions)\n .load(list.get(position).appthumbnail)\n .error(R.drawable.no_image_available)\n .into(holder.ivImage);\n\n"
},
{
"answer_id": 74541015,
"author": "Android Newbie A",
"author_id": 20125791,
"author_profile": "https://Stackoverflow.com/users/20125791",
"pm_score": 2,
"selected": true,
"text": "relative layout linear layout constraint layout <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<androidx.constraintlayout.widget.ConstraintLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_margin=\"5dp\"\n android:theme=\"@style/Theme.Music.Font\">\n\n <com.google.android.material.imageview.ShapeableImageView\n android:id=\"@+id/imageView\"\n android:layout_width=\"50dp\"\n android:layout_height=\"50dp\"\n android:layout_alignParentStart=\"true\"\n android:layout_margin=\"5dp\"\n\n android:contentDescription=\"@string/cover\"\n android:src=\"@drawable/image_as_cover\"\n app:shapeAppearance=\"@style/roundedImageView\"\n \n app:layout_constraintTop_toTopOf=\"parent\"\n app:layout_constraintBottom_toBottomOf=\"parent\"\n app:layout_constraintStart_toStartOf=\"parent\" />\n\n\n <View\n android:id=\"@+id/linearLayout\"\n android:layout_width=\"0dp\"\n android:layout_height=\"0dp\"\n\n app:layout_constraintTop_toTopOf=\"parent\"\n app:layout_constraintBottom_toBottomOf=\"parent\"\n app:layout_constraintStart_toEndOf=\"@id/imageView\"\n app:layout_constraintEnd_toEndOf=\"parent\" />\n\n <TextView\n android:id=\"@+id/titleView\"\n android:layout_width=\"0dp\"\n android:layout_height=\"wrap_content\"\n android:layout_margin=\"5dp\"\n\n android:maxLines=\"1\"\n android:singleLine=\"true\"\n android:fontFamily=\"@font/medium\"\n android:text=\"@string/love_is_gone_by_slander_forever_on_love\"\n android:textSize=\"15sp\"\n android:text=\"123\"\n app:layout_constraintTop_toTopOf=\"@id/linearLayout\"\n app:layout_constraintBottom_toTopOf=\"@id/albumName\"\n app:layout_constraintStart_toStartOf=\"@id/linearLayout\"\n app:layout_constraintEnd_toEndOf=\"@id/linearLayout\" />\n \n <TextView\n android:id=\"@+id/albumName\"\n android:layout_width=\"0dp\"\n android:layout_height=\"wrap_content\"\n android:layout_margin=\"5dp\"\n android:fontFamily=\"@font/medium\"\n android:maxLines=\"1\"\n android:singleLine=\"true\"\n android:text=\"@string/love_is_gone_by_slander_forever_on_love\"\n android:textSize=\"15sp\"\n\n app:layout_constraintTop_toBottomOf=\"@id/titleView\"\n app:layout_constraintBottom_toTopOf=\"@id/duration\"\n app:layout_constraintStart_toStartOf=\"@id/linearLayout\"\n app:layout_constraintEnd_toEndOf=\"@id/linearLayout\" />\n\n <TextView\n android:id=\"@+id/duration\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentEnd=\"true\"\n android:layout_centerVertical=\"true\"\n android:layout_margin=\"10dp\"\n android:fontFamily=\"@font/medium\"\n android:maxLines=\"1\"\n android:text=\"@string/duration\"\n android:textSize=\"11sp\"\n\n app:layout_constraintTop_toBottomOf=\"@id/albumName\"\n app:layout_constraintBottom_toBottomOf=\"@id/linearLayout\"\n app:layout_constraintStart_toStartOf=\"@id/linearLayout\"\n app:layout_constraintEnd_toEndOf=\"@id/linearLayout\" />\n \n</androidx.constraintlayout.widget.ConstraintLayout>\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2621476/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.