qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,621,815
|
<p>For my project, I have taken a data set which have 1296765 observations of 23 columns, I want to take just 10% of this data randomly. How can I do that in R.</p>
<p>I tried the below code but it only sampled out just 10 rows. But, I wanted to select randomly 10% of the data. I am a beginner so please help.</p>
<pre><code>library(dplyr)
x <- sample_n(train, 10)
</code></pre>
|
[
{
"answer_id": 74621824,
"author": "Vinícius Félix",
"author_id": 9696037,
"author_profile": "https://Stackoverflow.com/users/9696037",
"pm_score": 2,
"selected": false,
"text": "dplyr dplyr::slice_sample(train,prop = .1) \n"
},
{
"answer_id": 74622113,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 2,
"selected": false,
"text": "nrow() set.seed(13)\n\ntrain <- data.frame(id = 1:101, x = rnorm(101))\n\ntrain[sample(nrow(train), nrow(train) / 10), ]\n id x\n69 69 1.14382456\n101 101 -0.36917269\n60 60 0.69967564\n58 58 0.82651036\n59 59 1.48369123\n72 72 -0.06144699\n12 12 0.46187091\n89 89 1.60212039\n8 8 0.23667967\n49 49 0.27714729\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74621815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20639560/"
] |
74,621,828
|
<p>Because Enums aren't guaranteed to be of type int...</p>
<pre><code>public enum ExampleEnum : int / ulong / whatever
</code></pre>
<p>You cannot do this with enums:</p>
<pre><code>int i = (int)exampleEnum;
</code></pre>
<p>However in my case, while I don't know the exact 'type of enum' being used, I can guarantee that it will be a "int type" of enum.</p>
<p>So I can do this:</p>
<pre><code>int i = Convert.ToInt32(exampleEnum);
</code></pre>
<p>Cool. <strong>Here's the problem</strong>: I don't know of a way to do the inverse (which I need to do), as:</p>
<pre><code>Enum exampleEnum = (Enum)exampleEnum;
</code></pre>
<p>has error:</p>
<blockquote>
<p>Cannot cast expression of type 'int' to type 'Enum'</p>
</blockquote>
<p>And I cannot find an inverse of Convert.ToInt32(Enum enum)</p>
<hr />
<p>That is the question, if you think more detail on what I'm trying to do is useful, I can provide you with it. But in a nutshell I am creating a generic GUI method that takes in any type of Enum:</p>
<pre><code>public static int EditorPrefEnumField(string label, Enum defaultValue, string editorPrefString)
</code></pre>
<p>and getting it to work (the way I want) involves converting the Enum to and from an int.</p>
|
[
{
"answer_id": 74621998,
"author": "NineBerry",
"author_id": 101087,
"author_profile": "https://Stackoverflow.com/users/101087",
"pm_score": 3,
"selected": true,
"text": "Enum.ToObject() enum type Enum.ToObject() public enum TestEnum : int \n{\n A=1, B=2, C=3\n};\n\npublic T GetEnumFromInt<T>(int value) where T : Enum\n{\n return (T)Enum.ToObject(typeof(T), value);\n}\n\nprivate void button1_Click(object sender, EventArgs e) \n{\n Enum value = GetEnumFromInt<TestEnum>(2);\n MessageBox.Show(value.ToString()); // Displays \"B\" \n}\n Enum Enum"
},
{
"answer_id": 74622130,
"author": "Jeremy Thompson",
"author_id": 495455,
"author_profile": "https://Stackoverflow.com/users/495455",
"pm_score": 0,
"selected": false,
"text": "Int public class CommonError\n{\n public int Code { get; set; }\n\n public CommonError FromErrorCode(Enum code, string description = \"\")\n {\n Code = (int)Enum.Parse(code.GetType(), code.ToString()); \n return this;\n }\n}\n new CommonError().FromErrorCode((int)GeneralErrorCodes.SYSTEM_BASE_ERROR);\n Enum.GetNames(typeof(AnEmumType))\n\nEnum.GetValues(typeof(AnEmumType)).ToList();\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74621828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3079259/"
] |
74,621,877
|
<p>This function was built in to try and know how to use a dictionary properly.</p>
<pre class="lang-py prettyprint-override"><code>dict(d, 'bonjour')
hello
Unknown
Unknown
Unknown
</code></pre>
<p>It returns <code>hello</code>, and then <code>Unknown</code>. Why? It should only return <code>hello</code>. Help would be appreciated!</p>
<p>Thanks,</p>
|
[
{
"answer_id": 74621998,
"author": "NineBerry",
"author_id": 101087,
"author_profile": "https://Stackoverflow.com/users/101087",
"pm_score": 3,
"selected": true,
"text": "Enum.ToObject() enum type Enum.ToObject() public enum TestEnum : int \n{\n A=1, B=2, C=3\n};\n\npublic T GetEnumFromInt<T>(int value) where T : Enum\n{\n return (T)Enum.ToObject(typeof(T), value);\n}\n\nprivate void button1_Click(object sender, EventArgs e) \n{\n Enum value = GetEnumFromInt<TestEnum>(2);\n MessageBox.Show(value.ToString()); // Displays \"B\" \n}\n Enum Enum"
},
{
"answer_id": 74622130,
"author": "Jeremy Thompson",
"author_id": 495455,
"author_profile": "https://Stackoverflow.com/users/495455",
"pm_score": 0,
"selected": false,
"text": "Int public class CommonError\n{\n public int Code { get; set; }\n\n public CommonError FromErrorCode(Enum code, string description = \"\")\n {\n Code = (int)Enum.Parse(code.GetType(), code.ToString()); \n return this;\n }\n}\n new CommonError().FromErrorCode((int)GeneralErrorCodes.SYSTEM_BASE_ERROR);\n Enum.GetNames(typeof(AnEmumType))\n\nEnum.GetValues(typeof(AnEmumType)).ToList();\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74621877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20420123/"
] |
74,621,889
|
<p>i found strange result of javascript</p>
<pre><code>javascript
</code></pre>
<pre><code>var a=123e65;
console.log(a);
</code></pre>
<pre><code>javascript
</code></pre>
<p>result:1.23e+67 ;
why..this..?</p>
<p>I started studying JavaScript. During the study, I found strange results during various attempts. I can't figure out how to get that result...</p>
|
[
{
"answer_id": 74622012,
"author": "sigleane",
"author_id": 16470477,
"author_profile": "https://Stackoverflow.com/users/16470477",
"pm_score": 1,
"selected": false,
"text": "a e a"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74621889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19870045/"
] |
74,621,971
|
<p>So essentially it is a simple two sum problem but there are multiple solutions. At the end I would like to return all pairs that sum up to the target within a given list and then tally the total number of pairs at the end and return that as well. Currently can only seem to return 1 pair of numbers.</p>
<p>So far my solution has to been to try and implement a function that counts the amount of additions done, and while that number is less than the total length of the list the code would continue to iterate. This did not prove effective as it would still not take into account other solutions. Any help would be greatly appreciated</p>
|
[
{
"answer_id": 74622048,
"author": "Jarrod Burns",
"author_id": 16409883,
"author_profile": "https://Stackoverflow.com/users/16409883",
"pm_score": 0,
"selected": false,
"text": "my_list = [1, 2, 3, 4]\ntarget = 3\n\nout = [x for x in itertools.combinations(my_list, r=2) if sum(x) == target]\n\nprint(out)\n>>> [(0, 3), (1, 2)]\n"
},
{
"answer_id": 74622108,
"author": "NoDakker",
"author_id": 6032177,
"author_profile": "https://Stackoverflow.com/users/6032177",
"pm_score": 2,
"selected": true,
"text": "def suminlist(mylist,target):\n sumlist = []\n count = 0\n for i in range(len(mylist)):\n for x in range(i+1,len(mylist)):\n sum = mylist[i] + mylist[x]\n if sum == target:\n count += 1\n worklist = []\n worklist.append(mylist[i])\n worklist.append(mylist[x])\n sumlist.append(worklist)\n return count, sumlist\n\nlist = [0, 5, 4, -6, 2, 7, 13, 3, 1] \nprint(suminlist(list,4))\n @Dev:~/Python_Programs/SumList$ python3 SumList.py \n(2, [[0, 4], [3, 1]])\n"
},
{
"answer_id": 74631896,
"author": "Melody Ma",
"author_id": 20641133,
"author_profile": "https://Stackoverflow.com/users/20641133",
"pm_score": 0,
"selected": false,
"text": "def suminlist(mylist,target):\n # count = 0 # delete\n # while count < len(mylist): # delete\n finallist=[] # add\n for i in range(len(mylist)):\n for x in range(i+1,len(mylist)):\n sum = mylist[i]+mylist[x]\n # count = count + 1 # delete\n if sum == target:\n # sumlist = mylist[i],mylist[x] # delete\n # return sumlist # delete\n list=[] # add\n list.append(mylist[i]) # add\n list.append(mylist[x]) # add\n finallist.append(list) # add\n else: # add\n return 'No two values in the list can add up to the target value.' # add\n return finallist # add\n # return -1 # delete\n def suminlist(mylist,target):\n finallist=[]\n for i in range(len(mylist)):\n for x in range(i+1,len(mylist)):\n sum = mylist[i]+mylist[x]\n if sum == target:\n list=[]\n list.append(mylist[i])\n list.append(mylist[x])\n finallist.append(list)\n else:\n return 'No two values in the list can add up to the target value.'\n return finallist\n list = [0, 5, 4, -6, 2, 7, 13, 3, 1] \nprint(suminlist(list,100))\n# Output: No two values in the list can add up to the target value.\nprint(suminlist(list,4))\n# Output: [[0, 4], [3, 1]]\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74621971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15346274/"
] |
74,621,977
|
<p>I'm trying to make an array of unsigned char's and make a pointer which points to the first position of the array but I keep getting an error. This is my code as well as the error:</p>
<pre><code>void initBuffer
{
unsigned char buffer[size];
unsigned char *ptr;
ptr = &buffer;
}
</code></pre>
<p><a href="https://i.stack.imgur.com/OXCiP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OXCiP.png" alt="enter image description here" /></a></p>
<p>I suspect it's a very simple type error buy I'm new to C and not sure how to fix it.</p>
|
[
{
"answer_id": 74622016,
"author": "Some programmer dude",
"author_id": 440558,
"author_profile": "https://Stackoverflow.com/users/440558",
"pm_score": 2,
"selected": false,
"text": "&buffer unsigned char (*)[size] ptr unsigned char * ptr buffer &buffer[0] buffer ptr = buffer;\n"
},
{
"answer_id": 74622141,
"author": "MZM",
"author_id": 20551381,
"author_profile": "https://Stackoverflow.com/users/20551381",
"pm_score": 0,
"selected": false,
"text": "#include <stdio.h>\nint main() {\n unsigned char buffer[] = {'A','B','C','D'};\n unsigned char *ptr;\n ptr = &buffer[0]; // ptr, points to first element of array\n for(int i=0; i<4; i++)\n printf(\"%c\", ptr[i]);\n return 0;\n}\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74621977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19494871/"
] |
74,621,983
|
<p>I am following <a href="http://scipy.github.io/devdocs/dev/contributor/conda_guide.html#conda-guide" rel="nofollow noreferrer">steps in the contributor guide</a> to create a development environment. I am up to step 2.</p>
<blockquote>
<p>The Python-level dependencies for building SciPy will be installed as part of the conda environment creation - see environment.yml</p>
<p>Note that we’re installing SciPy’s build dependencies and some other software, but not (yet) SciPy itself. Also note that you’ll need to have this virtual environment active whenever you want to work with the development version of SciPy.</p>
<p>To create the environment with all dependencies and compilers, from the root of the SciPy folder, do</p>
<p><code>conda env create -f environment.yml</code></p>
</blockquote>
<p>However this gives an error that the environment file does not exist.</p>
<p><a href="https://github.com/scipy/scipy/blob/main/environment.yml" rel="nofollow noreferrer">https://github.com/scipy/scipy/blob/main/environment.yml</a> <-- environment.yml should look like this, so I have copied and put an environment.yml file in the <code>envs</code> folder.</p>
<p>I am unsure whether I should put this file in the envs folder or if I need to go to the root of the scipy version that already exist in my pkgs folder.</p>
<pre><code>C:\\Users\\micha\\anaconda3\\envs\>conda env create -f environment.yml
EnvironmentFileNotFound: 'C:\\Users\\micha\\anaconda3\\envs\\environment.yml' file not found
</code></pre>
<p>After inserting the environment.yml file:</p>
<pre><code>C:\\Users\\micha\\anaconda3\\envs\>conda env create -f environment.yml
Collecting package metadata (repodata.json): done
Solving environment: /
</code></pre>
<p>I am still awaiting the reults, however not sure if I have done the correct thing with the directory.</p>
|
[
{
"answer_id": 74622016,
"author": "Some programmer dude",
"author_id": 440558,
"author_profile": "https://Stackoverflow.com/users/440558",
"pm_score": 2,
"selected": false,
"text": "&buffer unsigned char (*)[size] ptr unsigned char * ptr buffer &buffer[0] buffer ptr = buffer;\n"
},
{
"answer_id": 74622141,
"author": "MZM",
"author_id": 20551381,
"author_profile": "https://Stackoverflow.com/users/20551381",
"pm_score": 0,
"selected": false,
"text": "#include <stdio.h>\nint main() {\n unsigned char buffer[] = {'A','B','C','D'};\n unsigned char *ptr;\n ptr = &buffer[0]; // ptr, points to first element of array\n for(int i=0; i<4; i++)\n printf(\"%c\", ptr[i]);\n return 0;\n}\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74621983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7348031/"
] |
74,622,007
|
<p>I'm trying to pass a date object as a prop in react native, and access its methods to render data.</p>
<p>The prop is passed as following:</p>
<pre><code> <Task
text={item["text"]}
date={item["date"]}
time={item["time"]}
reminder={item["reminder"]}
completed={item["completed"]}
/>
</code></pre>
<p>It is accessed as:</p>
<pre><code><View>
<View
style={[
styles.item,
completed
? { backgroundColor: "#98CBB4" }
: { backgroundColor: "#CCC9DC" },
]}
>
<View style={styles.ciricleTitle}>
<View style={styles.circular}></View>
<Text style={styles.itemText}>{text}</Text>
</View>
<Text style={styles.itemText}>{console.log(date.date)}</Text>
{/* <Text style={styles.itemText}>{date.getDay()}</Text> */}
</View>
{completed && <View style={styles.line} />}
</View>
</code></pre>
<p>i tried expanding the prop with <code>{...item['date']}</code> but it is not working</p>
|
[
{
"answer_id": 74622016,
"author": "Some programmer dude",
"author_id": 440558,
"author_profile": "https://Stackoverflow.com/users/440558",
"pm_score": 2,
"selected": false,
"text": "&buffer unsigned char (*)[size] ptr unsigned char * ptr buffer &buffer[0] buffer ptr = buffer;\n"
},
{
"answer_id": 74622141,
"author": "MZM",
"author_id": 20551381,
"author_profile": "https://Stackoverflow.com/users/20551381",
"pm_score": 0,
"selected": false,
"text": "#include <stdio.h>\nint main() {\n unsigned char buffer[] = {'A','B','C','D'};\n unsigned char *ptr;\n ptr = &buffer[0]; // ptr, points to first element of array\n for(int i=0; i<4; i++)\n printf(\"%c\", ptr[i]);\n return 0;\n}\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14075625/"
] |
74,622,053
|
<p>I want to delete duplicates from a Redshift table that are true duplicates. Below is an example of two rows that are true duplicates.</p>
<p>Since it is Redshift, there are no primary keys to the table. Any help is appreciated.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>Col 1</th>
<th>Col 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Val 1</td>
<td>Val 2</td>
</tr>
<tr>
<td>1</td>
<td>Val 1</td>
<td>Val 2</td>
</tr>
</tbody>
</table>
</div>
<p>I tried using window functions <code>row_number()</code>, <code>rank()</code>. Neither worked as when applying Delete command, SQL command cannot differentiate both rows.</p>
<p>Trial 1:</p>
<p>The below command deletes both rows</p>
<pre><code>DELETE From test_table
where (id) IN
(
select \*,row_number() over(partition by id) as rownumber from test*table where row*number !=1
);
</code></pre>
<p>Trial 2:</p>
<p>The below command retains both rows.</p>
<pre><code>DELETE From test_table
where (id) IN
(
select \*,rank() over(partition by id) as rownumber from test*table where row*number !=1
);
</code></pre>
|
[
{
"answer_id": 74622266,
"author": "Learn Hadoop",
"author_id": 8726488,
"author_profile": "https://Stackoverflow.com/users/8726488",
"pm_score": 1,
"selected": false,
"text": "create table dummy as select * from main_table where 1=2 insert into dummy(col1,col2..coln) select distinct col1,col2..coln from main_table; Alter table main_table rename to main_table_bk alter table dummy rename to main. drop main_table_bk"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18648093/"
] |
74,622,062
|
<p>I am looking to implement concurrency inside part of my app in order to speed up processing. The input array can be a large array, that I need to check multiple things related to it. This would be some sample code.</p>
<p>EDITED:
So this is helpful for looking at striding through the array, which was something else I was looking at doing, but I think the helpful answers are sliding away from the original question, due to the fact that I already have a <code>DispatchQueue.concurrentPerform</code> present in the code.</p>
<p>Within a for loop multiple times, I was looking to implement other for loops, due to having to relook at the same data multiple times. The <code>inputArray</code> is an array of structs, so in the outer loop, I am looking at one value in the struct, and then in the inner loops I am looking at a different value in the struct. In the change below I made the two inner for loops function calls to make the code a bit more clear. But in general, I would be looking to make the two <code>funcA</code> and <code>funcB</code> calls, and wait until they are both done before continuing in the main loop.</p>
<pre class="lang-swift prettyprint-override"><code>//assume the startValues and stop values will be within the bounds of the
//array and wont under/overflow
private func funcA(inputArray: [Int], startValue: Int, endValue: Int) -> Bool{
for index in startValue...endValue {
let dataValue = inputArray[index]
if dataValue == 1_000_000 {
return true
}
}
return false
}
private func funcB(inputArray: [Int], startValue: Int, endValue: Int) -> Bool{
for index in startValue...endValue {
let dataValue = inputArray[index]
if dataValue == 10 {
return true
}
}
return false
}
private func testFunc(inputArray: [Int]) {
let dataIterationArray = Array(Set(inputArray))
let syncQueue = DispatchQueue(label: "syncQueue")
DispatchQueue.concurrentPerform(iterations: dataIterationArray.count) { index in
//I want to do these two function calls starting roughly one after another,
//to work them in parallel, but i want to wait until both are complete before
//moving on. funcA is going to take much longer than funcB in this case,
//just because there are more values to check.
let funcAResult = funcA(inputArray: dataIterationArray, startValue: 10, endValue: 2_000_000)
let funcBResult = funcB(inputArray: dataIterationArray, startValue: 5, endValue: 9)
//Wait for both above to finish before continuing
if funcAResult && funcBResult {
print("Yup we are good!")
} else {
print("Nope")
}
//And then wait here until all of the loops are done before processing
}
}
</code></pre>
|
[
{
"answer_id": 74622322,
"author": "akjndklskver",
"author_id": 5318223,
"author_profile": "https://Stackoverflow.com/users/5318223",
"pm_score": 0,
"selected": false,
"text": "iterations: dataIterationArray.count DispatchQueue.concurrentPerform(iterations: 3) { iteration in \n switch iteration {\n case 0:\n for i in 1...10{\n print (\"i \\(i)\")\n }\n case 1:\n for j in 11...20{\n print (\"j \\(j)\")\n }\n case 2: \n for k in 21...30{\n print (\"k \\(k)\")\n }\n }\n}\n"
},
{
"answer_id": 74623578,
"author": "Rob",
"author_id": 1271826,
"author_profile": "https://Stackoverflow.com/users/1271826",
"pm_score": 1,
"selected": false,
"text": "concurrentPerform funcA funcB concurrentPerform concurrentPerform funcA funcB funcA funcB start end funcB funcA funcA funcB funcA funcB concurrentPerform concurrentPerform funcA funcB OperationQueue maxConcurrentOperationCount async await concurrentPerform concurrentPerform private func testFunc(inputArray: [Int]) {\n DispatchQueue.global().async {\n let array = Array(Set(inputArray))\n let syncQueue = DispatchQueue(label: \"syncQueue\")\n\n // calculate how many iterations will be needed\n\n let count = array.count\n let stride = 10\n let (quotient, remainder) = count.quotientAndRemainder(dividingBy: stride)\n let iterations = remainder == 0 ? quotient : quotient + 1\n\n // now iterate\n\n DispatchQueue.concurrentPerform(iterations: iterations) { iteration in\n\n // calculate the `start` and `end` indices\n\n let start = stride * iteration\n let end = min(start + stride, count)\n\n // now loop through that range\n\n for index in start ..< end {\n let value = array[index]\n print(\"iteration =\", iteration, \"index =\", index, \"value =\", value)\n }\n }\n\n // you won't get here until they're all done; obviously, if you \n // want to now update your UI or model, you may want to dispatch\n // back to the main queue, e.g.,\n //\n // DispatchQueue.main.async { \n // ...\n // }\n }\n}\n concurrentPerform DispatchQueue.global().async {…} print"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20078518/"
] |
74,622,097
|
<p>My system is Ubuntu</p>
<p>Here is my code:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#define LEN 16
using namespace std;
int main(){
int a[16] = {2};
for (int i=0; i<16; i++)
{
cout << a[i] << ' ';
}
}
</code></pre>
<p>I compiled it by this command in terminal : <code>g++ t1.cpp -o t1 && ./t1</code></p>
<p>but the result is</p>
<pre class="lang-none prettyprint-override"><code>2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
</code></pre>
|
[
{
"answer_id": 74622119,
"author": "Some programmer dude",
"author_id": 440558,
"author_profile": "https://Stackoverflow.com/users/440558",
"pm_score": 2,
"selected": false,
"text": "int a[16] = {2};\n int a[16] = {2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};\n std::fill int a[16];\nstd::fill(begin(a), end(a), 2);\n"
},
{
"answer_id": 74622126,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 0,
"selected": false,
"text": "2 0 std::fill const int size = 16;\n\nint main() {\n int a[size];\n\n std::fill(a, a + size, 2);\n\n return 0;\n}\n"
},
{
"answer_id": 74622134,
"author": "fwan",
"author_id": 14718214,
"author_profile": "https://Stackoverflow.com/users/14718214",
"pm_score": -1,
"selected": false,
"text": "int array[16];\nstd::fill_n(array, 16, 2);\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20639863/"
] |
74,622,105
|
<p>I am learning python and I what I need to achieve is to count how many denominations of 1000, 500, 200, 100, 50, 20, 10, 5, 1 , 0.25, 0.01 count base on my input data of <strong>1575.78</strong>.This specific code bums me out.</p>
<pre><code>def withdraw_money():
denoms = (1000, 500, 200, 100, 50, 20, 10,5,1,.25,0.01)
while True:
try:
withdraw = 1575.770
break
except Exception as e:
print('Incorrect input: %s' % e)
print("Here is the bill breakdown for the amount input")
for d in denoms:
count = withdraw // d
print('P%i = %i' % (d, count))
withdraw -= count * d
withdraw_money()
</code></pre>
<p>My current output is:</p>
<pre><code>Here is the bill breakdown for the amount input
P1000 = 1
P500 = 1
P200 = 0
P100 = 0
P50 = 1
P20 = 1
P10 = 0
P5 = 1
P1 = 0
P0.25 = 3
P0.01 = 2
</code></pre>
<p>which is wrong because the <code>P0.01 = 2</code> is suppose to be <code>P0.01 =3.</code></p>
<p>However this code is correct when running whole numbers like 1500, or 20 but large number with decimal it get wrong on the 0.01 denomination count.</p>
|
[
{
"answer_id": 74622139,
"author": "Deepan",
"author_id": 13426157,
"author_profile": "https://Stackoverflow.com/users/13426157",
"pm_score": 0,
"selected": false,
"text": "def withdraw_money():\n denoms = (1000, 500, 200, 100, 50, 20, 10, 5, 1, .25, 0.01)\n while True:\n try:\n withdraw = 1575.770\n break\n except Exception as e:\n print('Incorrect input: %s' % e)\n\n print(\"Here is the bill breakdown for the amount input\")\n for d in denoms:\n count = withdraw // d\n print(f'P{d} = {count:0.0f}')\n withdraw -= count * d\n\n\nwithdraw_money()\n\n Here is the bill breakdown for the amount input\nP1000 = 1\nP500 = 1\nP200 = 0\nP100 = 0\nP50 = 1\nP20 = 1\nP10 = 0\nP5 = 1\nP1 = 0\nP0.25 = 3\nP0.01 = 1\n"
},
{
"answer_id": 74622443,
"author": "Muntasir Aonik",
"author_id": 8663492,
"author_profile": "https://Stackoverflow.com/users/8663492",
"pm_score": 3,
"selected": true,
"text": "round() def withdraw_money():\n denoms = (1000, 500, 200, 100, 50, 20, 10,5,1,0.25,0.01)\n while True:\n try:\n withdraw = 1575.77\n break\n except Exception as e:\n print('Incorrect input: %s' % e)\n \n print(\"Here is the bill breakdown for the amount input\")\n for i in range(len(denoms)):\n if denoms[i] != 0.01: count = withdraw // denoms[i]\n else: count = withdraw / denoms[i]\n print(f'P{denoms[i]} = {count:0.0f}')\n withdraw = round(withdraw % denoms[i],2)\n \n\nwithdraw_money()\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4790677/"
] |
74,622,122
|
<p>I am new to Python and I need your help in getting the similarity between two sequences. Assuming they are not of the same length and some may have (-) gap symbols.</p>
<p>So here is my code bellow in getting the similarity in only one sequence.</p>
<pre><code>seq1 = "AAAATCCCTAGGGTCAT"
def similarity(seq1):
base_dic={}
for i in range(len(seq1)):
if seq1[i] in base_dic.keys():
base_dic[seq1[i]]+=1
else:
base_dic[seq1[i]]=1
for key in base_dic.keys():
base_dic[key]=base_dic[key]/len(seq1)*100
return base_dic
similarity(seq1)
Output:
{'A': 35.294117647058826,
'T': 23.52941176470588,
'C': 23.52941176470588,
'G': 17.647058823529413}
My question is how could I modify this code, so that it can take two sequences at a time and find the similarities?
for ex.
seq1 = "AAAATCCCTAGAAAGGTCAT"
seq2 = “AAGATC---TTTCTACT”
</code></pre>
<p>Any ideas? Thanks</p>
<p>i am expecting to get the similarity of A, T, G, C but not -. as they should be counted as unsimilar.</p>
|
[
{
"answer_id": 74622203,
"author": "Krishna Potharaju",
"author_id": 18648093,
"author_profile": "https://Stackoverflow.com/users/18648093",
"pm_score": -1,
"selected": false,
"text": "if seq1[i] == “-“:\n continue\n"
},
{
"answer_id": 74622358,
"author": "Hariharan Ragothaman",
"author_id": 3555366,
"author_profile": "https://Stackoverflow.com/users/3555366",
"pm_score": 0,
"selected": false,
"text": "from collections import Counter\n\nseq1 = \"AAAATCCCTAGGGTCAT\"\nseq2 = \"AAGATC---TTTCTACT\"\n\n\ndef get_count(s):\n H = defaultdict(int)\n n = len(s)\n s = [c for c in s if c in \"ATCG\"]\n ctr = Counter(s)\n ctr = {k: (v / n) * 100 for k, v in ctr.items()}\n return ctr\n\n\ndef calculate_similarity(s1, s2):\n result1 = get_count(seq1)\n result2 = get_count(seq2)\n print(result1)\n print(result2)\n \"\"\"\n Add some custom logic here to compute\n how similar the strings are (or)\n similarity of A, T, C & G\n \"\"\"\n\ncalculate_similarity(seq1, seq2)\n def minDistance(word1: str, word2: str) -> int:\n m, n = len(word1), len(word2)\n dp = [[0] * (n + 1) for _ in range(m + 1)]\n dp[0][0] = 0\n for i in range(m + 1):\n dp[i][0] = i\n for j in range(n + 1):\n dp[0][j] = j\n\n for i in range(1, m + 1):\n for j in range(1, n + 1):\n if word1[i - 1] == word2[j - 1]:\n dp[i][j] = dp[i - 1][j - 1]\n else:\n # dp[i-1][j] -> insert\n # dp[i][j-1] -> remove\n # dp[i-1][j-1] -> replace\n dp[i][j] = min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]) + 1\n return dp[-1][-1]\n\n# The number of operations to convert seq1 to seq2\n# This number can help you compare how similar 2 strings are.\nresult = minDistance(seq1, seq2). \n\nprint(result)\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3143761/"
] |
74,622,164
|
<p>Sorry for the vague question.
I'm trying to add ID from Table 1</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Fruit_Name</th>
<th>Fruit_ID</th>
</tr>
</thead>
<tbody>
<tr>
<td>Apple</td>
<td>01</td>
</tr>
<tr>
<td>Banana</td>
<td>02</td>
</tr>
<tr>
<td>Pear</td>
<td>03</td>
</tr>
<tr>
<td>Grape</td>
<td>04</td>
</tr>
</tbody>
</table>
</div>
<p>to table 2 ID part.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Fruit_Name</th>
<th>Fruit_ID</th>
<th>Grown In</th>
</tr>
</thead>
<tbody>
<tr>
<td>Apple</td>
<td></td>
<td>Farm A</td>
</tr>
<tr>
<td>Pear</td>
<td></td>
<td>Farm B</td>
</tr>
<tr>
<td>Apple</td>
<td></td>
<td>Farm B</td>
</tr>
</tbody>
</table>
</div>
<p>I want to put the same Fruit_ID from Table 1 into Table 2. So that it looks like
| Fruit_Name | Fruit_ID | Grown In |
| -------- | -------- | -------- |
| Apple | 01 | Farm A |
| Pear | 03 | Farm B |
| Apple | 01 | Farm B |
<a href="https://i.stack.imgur.com/3NGHg.png" rel="nofollow noreferrer">1</a></p>
<p>There are 35 rows in Table 1, and 300 rows in Table 2.
How do I do it?</p>
<p>I tried using
ALTER TABLE Table2 ADD FOREIGN KEY (Fruit_ID) REFERENCES Table1(Fruit_ID);</p>
<p>but it didn't work.</p>
|
[
{
"answer_id": 74622553,
"author": "DSalomon",
"author_id": 10402876,
"author_profile": "https://Stackoverflow.com/users/10402876",
"pm_score": 0,
"selected": false,
"text": "@Dom Anna UPDATE Table_2 \nINNER JOIN Table_1\nON Table_2.Fruit_Name=Table_1.Fruit_Name\nSET Table_2.Fruit_ID=Table_1.Fruit_ID;\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20639866/"
] |
74,622,227
|
<p>I maintain an Arduino library which uses the following code (simplified) to print results received by infrared.</p>
<pre><code>unsigned long long decodedData; // for 8 and 16 bit cores it is unsigned long decodedData;
Print MySerial;
MySerial.print(decodedData, 16);
</code></pre>
<p>Most of the 32 bit arduino cores provide the function <code>size_t Print::print(unsigned long long n, int base)</code> and compile without errors.</p>
<p>But there are 32 bit cores, which do not provide <code>size_t Print::print(unsigned long long n, int base)</code>, they only provide <code>size_t Print::print(unsigned long n, int base)</code> and there I get the expected compile time error
<code>call of overloaded 'print(decodedData, int)' is ambiguous</code>.</p>
<p>I tried to understand <a href="https://stackoverflow.com/questions/87372">Check if a class has a member function of a given signature</a> but still have no clue.</p>
<p>I want to use</p>
<pre><code> MySerial.print((uint32_t)(decodedData >> 32), 16);
MySerial.print((uint32_t)decodedData & 0xFFFFFFFF, 16);
</code></pre>
<p>in case the function <code>size_t Print::print(unsigned long long n, int base)</code> is not provided.</p>
<p>I tried</p>
<pre><code>template<typename T>
struct has_uint64_print {
template<typename U, size_t (U::*)(unsigned long long, int)> struct SFINAE {
};
template<typename U> static char test(SFINAE<U, &U::print>*);
template<typename U>
static int test(...);
static const bool has64BitPrint = sizeof(test<T>(nullptr)) == sizeof(char);
};
</code></pre>
<p>and this works (Thanks to Remy Lebeau) :-).</p>
<p>But this check does not work, since it still references the long long print function (update: and using <code>if constexpr ()</code> -which is not available for all cores- does not help).</p>
<pre><code> if(has_uint64_print<Print>::has64BitPrint){
MySerial.print(decodedData, 16);
} else {
MySerial.print((uint32_t)(decodedData >> 32), 16);
MySerial.print((uint32_t)decodedData & 0xFFFFFFFF, 16);
}
</code></pre>
<p>Is there any chance to avoid this compile error?</p>
<p>BTW. I do not want to substitute all occurences of the 64 bit print with the 2 32 bit prints, only for one seldom used and lazy implemented 32 bit core, since all mainsteam cores work well with the 64 bit print.</p>
|
[
{
"answer_id": 74642091,
"author": "sklott",
"author_id": 11680056,
"author_profile": "https://Stackoverflow.com/users/11680056",
"pm_score": 2,
"selected": true,
"text": "#include <iostream>\n#include <iomanip>\n#include <type_traits>\n\n// First implementation of printer\nclass Impl1 {\npublic:\n static void print(uint64_t value, int base) {\n std::cout << \"64-bit print: \" << std::setbase(base) << value << \"\\n\";\n }\n};\n\n\n// Second implementation of printer\nclass Impl2 {\npublic:\n static void print(uint32_t value, int base) {\n std::cout << \"32-bit print: \" << std::setbase(base) << value << \"\\n\";\n }\n};\n\n\n// Template to automatically select proper version\ntemplate<typename Impl, typename = void>\nclass Print;\n\ntemplate<typename Impl>\nclass Print<Impl, typename std::enable_if<std::is_same<decltype(Impl::print), void(uint64_t, int)>::value>::type>\n{\npublic:\n static void print(uint64_t value, int base)\n {\n Impl::print(value, base);\n }\n};\n\ntemplate<typename Impl>\nclass Print<Impl, typename std::enable_if<std::is_same<decltype(Impl::print), void(uint32_t, int)>::value>::type>\n{\npublic:\n static void print(uint64_t value, int base)\n {\n Impl::print(static_cast<uint32_t>(value >> 32), base);\n Impl::print(static_cast<uint32_t>(value), base);\n }\n};\n\nint main()\n{\n Print<Impl1>::print(0x100000001, 16);\n Print<Impl2>::print(0x100000001, 16);\n}\n #include <iomanip>\n#include <iostream>\n#include <type_traits>\n\n// Set to 1 to see effect of using 64 bit version\n#define HAS_64 0\n\nclass Print {\n public:\n size_t print(unsigned int value, int base) {\n return base + 1; // dummy\n };\n size_t print(long value, int base) {\n return base + 2; // dummy\n };\n size_t print(unsigned long value, int base) {\n return base + 3; // dummy\n };\n#if HAS_64 \n size_t print(unsigned long long value, int base) {\n return base + 4; // dummy\n };\n#endif\n};\nPrint MySerial;\n\n// If you have C++17 you can just use std::void_t, or use this for all versions\n#if __cpp_lib_void_t >= 201411L\ntemplate<typename T>\nusing void_t = std::void_t<T>;\n#else\ntemplate<typename... Ts> struct make_void { typedef void type; };\ntemplate<typename... Ts> using void_t = typename make_void<Ts...>::type;\n#endif\n\n// Detecting if we have 'print(unsigned long long value, int base)' overload\ntemplate<typename T, typename = void>\nstruct has_ull_print : std::false_type { };\ntemplate<typename T>\nstruct has_ull_print<T, void_t<decltype(std::declval<T>().print(0ull, 0))>> : std::true_type { };\n\n// Can be either class or namesapce\nnamespace PrintXYZ {\n template <typename Impl, typename std::enable_if<!has_ull_print<Impl>::value, bool>::type = true>\n size_t print(Impl &p, unsigned long long value, int base) {\n p.print(static_cast<uint32_t>(value >> 32), base);\n p.print(static_cast<uint32_t>(value), base);\n return 0; // Not sure about return value here.\n }\n\n template <typename Impl, typename std::enable_if<has_ull_print<Impl>::value, bool>::type = true>\n size_t print(Impl &p, unsigned long long value, int base) {\n return p.print(value, base);\n }\n};\n\nint main() {\n PrintXYZ::print(MySerial, 0x100000001, 16);\n}\n"
},
{
"answer_id": 74642455,
"author": "Marek R",
"author_id": 1387438,
"author_profile": "https://Stackoverflow.com/users/1387438",
"pm_score": 0,
"selected": false,
"text": "Serial::print class Serial\n{\npublic:\n ...\n void print(uint8_t x, int base);\n void print(uint16_t x, int base);\n void print(uint32_t x, int base);\n void print(uint64_t x, int base);\n};\n unsigned long long uint64_t uint64_t unsigned long long unsigned long call of overloaded 'print(decodedData, int)' is ambiguous uint64_t uint64_t decodedData;\nPrint MySerial;\nMySerial.print(decodedData, 16);\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3131332/"
] |
74,622,252
|
<p>I am trying to set a boolean value with useState but its not working, i am not sure why? Basically i am using this as a Route component. when i console the loggedIn state after calling the function in the useEffect i keep getting false which is my initial value.</p>
<pre><code>import React, {useState, useEffect} from 'react'
import axios from 'axios'
import { Navigate } from 'react-router-dom'
export default function AppLayout() {
const [loggedIn, setLoggedIn] = useState(false);
const isLoggedIn = () => {
const session_admin_item = window.localStorage.getItem("SESSION_ADMIN");
if(session_admin_item !== null){
axios.get(`/api/authenticate/checktoken/${session_admin_item}`).then((res) => {
if(res.data.message == "authenticated"){
setLoggedIn(true);
}
});
}
useEffect(() => {
isLoggedIn();
},[])
return (
loggedIn ? <Header /> : <Navigate to="/login" />
)
}
</code></pre>
<p>Thank you in advance</p>
|
[
{
"answer_id": 74642091,
"author": "sklott",
"author_id": 11680056,
"author_profile": "https://Stackoverflow.com/users/11680056",
"pm_score": 2,
"selected": true,
"text": "#include <iostream>\n#include <iomanip>\n#include <type_traits>\n\n// First implementation of printer\nclass Impl1 {\npublic:\n static void print(uint64_t value, int base) {\n std::cout << \"64-bit print: \" << std::setbase(base) << value << \"\\n\";\n }\n};\n\n\n// Second implementation of printer\nclass Impl2 {\npublic:\n static void print(uint32_t value, int base) {\n std::cout << \"32-bit print: \" << std::setbase(base) << value << \"\\n\";\n }\n};\n\n\n// Template to automatically select proper version\ntemplate<typename Impl, typename = void>\nclass Print;\n\ntemplate<typename Impl>\nclass Print<Impl, typename std::enable_if<std::is_same<decltype(Impl::print), void(uint64_t, int)>::value>::type>\n{\npublic:\n static void print(uint64_t value, int base)\n {\n Impl::print(value, base);\n }\n};\n\ntemplate<typename Impl>\nclass Print<Impl, typename std::enable_if<std::is_same<decltype(Impl::print), void(uint32_t, int)>::value>::type>\n{\npublic:\n static void print(uint64_t value, int base)\n {\n Impl::print(static_cast<uint32_t>(value >> 32), base);\n Impl::print(static_cast<uint32_t>(value), base);\n }\n};\n\nint main()\n{\n Print<Impl1>::print(0x100000001, 16);\n Print<Impl2>::print(0x100000001, 16);\n}\n #include <iomanip>\n#include <iostream>\n#include <type_traits>\n\n// Set to 1 to see effect of using 64 bit version\n#define HAS_64 0\n\nclass Print {\n public:\n size_t print(unsigned int value, int base) {\n return base + 1; // dummy\n };\n size_t print(long value, int base) {\n return base + 2; // dummy\n };\n size_t print(unsigned long value, int base) {\n return base + 3; // dummy\n };\n#if HAS_64 \n size_t print(unsigned long long value, int base) {\n return base + 4; // dummy\n };\n#endif\n};\nPrint MySerial;\n\n// If you have C++17 you can just use std::void_t, or use this for all versions\n#if __cpp_lib_void_t >= 201411L\ntemplate<typename T>\nusing void_t = std::void_t<T>;\n#else\ntemplate<typename... Ts> struct make_void { typedef void type; };\ntemplate<typename... Ts> using void_t = typename make_void<Ts...>::type;\n#endif\n\n// Detecting if we have 'print(unsigned long long value, int base)' overload\ntemplate<typename T, typename = void>\nstruct has_ull_print : std::false_type { };\ntemplate<typename T>\nstruct has_ull_print<T, void_t<decltype(std::declval<T>().print(0ull, 0))>> : std::true_type { };\n\n// Can be either class or namesapce\nnamespace PrintXYZ {\n template <typename Impl, typename std::enable_if<!has_ull_print<Impl>::value, bool>::type = true>\n size_t print(Impl &p, unsigned long long value, int base) {\n p.print(static_cast<uint32_t>(value >> 32), base);\n p.print(static_cast<uint32_t>(value), base);\n return 0; // Not sure about return value here.\n }\n\n template <typename Impl, typename std::enable_if<has_ull_print<Impl>::value, bool>::type = true>\n size_t print(Impl &p, unsigned long long value, int base) {\n return p.print(value, base);\n }\n};\n\nint main() {\n PrintXYZ::print(MySerial, 0x100000001, 16);\n}\n"
},
{
"answer_id": 74642455,
"author": "Marek R",
"author_id": 1387438,
"author_profile": "https://Stackoverflow.com/users/1387438",
"pm_score": 0,
"selected": false,
"text": "Serial::print class Serial\n{\npublic:\n ...\n void print(uint8_t x, int base);\n void print(uint16_t x, int base);\n void print(uint32_t x, int base);\n void print(uint64_t x, int base);\n};\n unsigned long long uint64_t uint64_t unsigned long long unsigned long call of overloaded 'print(decodedData, int)' is ambiguous uint64_t uint64_t decodedData;\nPrint MySerial;\nMySerial.print(decodedData, 16);\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4571267/"
] |
74,622,277
|
<p>I have a dataset like this:</p>
<pre><code>row num Group
1 3 B
2 6 A
3 12 A
4 15 B
5 16 A
6 18 A
7 20 B
8 25 A
9 27 B
10 29 B
</code></pre>
<p>In R,
I would like to compare an input number with the values in <strong>num</strong>, and I would like to find the location of the closest bigger value in <strong>Group A</strong> only.</p>
<p>For example, if the input number is 8, then the closest, bigger value in group A should be 12, and I would like to get its location which should be 3. If the input is 18, then the value returned should be 18, and the location should be 6. If the input is 20, then the value returned should be 25, and the location should be 8.</p>
<p>I tried which.min, but for some reason, index 1 is always returned regardless of my imput number.</p>
<pre><code>#called the dataset f
which.min(f$num[f$Group=="A"][f$num[f$Group=="A"]>=8])
</code></pre>
<p>I would like to still use base R if possible
I would appreciate any thoughts on which part I did wrong and how to fix it.</p>
<p>Thank you.</p>
|
[
{
"answer_id": 74622303,
"author": "Vinícius Félix",
"author_id": 9696037,
"author_profile": "https://Stackoverflow.com/users/9696037",
"pm_score": 0,
"selected": false,
"text": "dplyr library(dplyr)\n\ndf <-\n data.frame(\n row = 1:10,\n num = cumsum(rep(3,10)),\n group = c(\"B\",\"A\",\"A\",\"B\",\"A\",\"A\",\"B\",\"A\",\"B\",\"B\")\n )\n\ndf %>% \n filter(num >= 8) %>% \n slice_min(order_by = row)\n\n row num group\n1 3 9 A\n df[min(df$row[(df$num >= 8)]),]\n\n row num group\n1 3 9 A\n"
},
{
"answer_id": 74622434,
"author": "Gwang-Jin Kim",
"author_id": 9690090,
"author_profile": "https://Stackoverflow.com/users/9690090",
"pm_score": 1,
"selected": false,
"text": "nearest_bigger_num <- function(num, vec) {\n which(min(vec[num < vec]) == vec)\n}\n\nnearest_bigger_num(8, df$num)\n## 3\n nearest_bigger_num_in_group <- function(num, df, group) {\n df <- df[df$group == group]\n df <- df[num < df$num]\n df$row[which.min(df$num)]\n}\n\nnearest_bigger_num_in_group(8, df, \"A\")\n## 3\n"
},
{
"answer_id": 74622654,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 1,
"selected": true,
"text": "ifelse() NA which.min() which.min(ifelse(f$Group == \"A\" & f$num >= 8, f$num, NA))\n# 3\n\nwhich.min(ifelse(f$Group == \"A\" & f$num >= 18, f$num, NA))\n# 6\n which.min() NA"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18785196/"
] |
74,622,311
|
<p>i wanna ask my case about array and object, i still less of knowledge about this because still newbie. i have bunch of data as following:</p>
<pre><code> counterTraffic : [
{
id: 1,
daerah: "Bandung",
date:"1668790800000",
kendaraan: [
{rodaEmpat: 50},
{rodaDua: 22},
{truck: 30},
{Bus: 70},
]
}, {
id: 2,
daerah: "Tasik",
date:"1668877200000",
kendaraan: [
{rodaEmpat: 80},
{rodaDua: 15},
{truck: 10},
{Bus: 50},
]
},
{
id: 3,
daerah: "Bekasi",
date:"1669050000000",
kendaraan: [
{rodaEmpat: 30},
{rodaDua: 65},
{truck: 20},
{Bus: 100},
]
}
,
{
id: 4,
daerah: "Bandung",
date:"1668963600000",
kendaraan: [
{rodaEmpat: 20},
{rodaDua: 15},
{truck: 5},
{Bus: 150},
]
}
]
</code></pre>
<p>and i want take value data of counterTraffic.kendaraan and assign to new variable.
so when i go mapping the counterTraffic, and then assign to new variable with kendaraan data</p>
<pre><code>the result have to become: let kendaraanNew = [50,22,30,70]
</code></pre>
<p>the data above from counterTraffic[0].kendaraan that already mapping before.</p>
<p>thank you for your helping</p>
|
[
{
"answer_id": 74622303,
"author": "Vinícius Félix",
"author_id": 9696037,
"author_profile": "https://Stackoverflow.com/users/9696037",
"pm_score": 0,
"selected": false,
"text": "dplyr library(dplyr)\n\ndf <-\n data.frame(\n row = 1:10,\n num = cumsum(rep(3,10)),\n group = c(\"B\",\"A\",\"A\",\"B\",\"A\",\"A\",\"B\",\"A\",\"B\",\"B\")\n )\n\ndf %>% \n filter(num >= 8) %>% \n slice_min(order_by = row)\n\n row num group\n1 3 9 A\n df[min(df$row[(df$num >= 8)]),]\n\n row num group\n1 3 9 A\n"
},
{
"answer_id": 74622434,
"author": "Gwang-Jin Kim",
"author_id": 9690090,
"author_profile": "https://Stackoverflow.com/users/9690090",
"pm_score": 1,
"selected": false,
"text": "nearest_bigger_num <- function(num, vec) {\n which(min(vec[num < vec]) == vec)\n}\n\nnearest_bigger_num(8, df$num)\n## 3\n nearest_bigger_num_in_group <- function(num, df, group) {\n df <- df[df$group == group]\n df <- df[num < df$num]\n df$row[which.min(df$num)]\n}\n\nnearest_bigger_num_in_group(8, df, \"A\")\n## 3\n"
},
{
"answer_id": 74622654,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 1,
"selected": true,
"text": "ifelse() NA which.min() which.min(ifelse(f$Group == \"A\" & f$num >= 8, f$num, NA))\n# 3\n\nwhich.min(ifelse(f$Group == \"A\" & f$num >= 18, f$num, NA))\n# 6\n which.min() NA"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16204040/"
] |
74,622,350
|
<p>I'm new to this website and using Mysql and phpMyAdmin. I need help with one of my table and I would really appreciate it. So, I created a table that has an Integer column I want to be able to limit it to only 7(Seven) digits I'm not quiet sure if this is possible using Mysql or phpMyAdmin.</p>
<p>I haven't tried any query on it. I want to limit the Integer type to only 7(Seven) digits.</p>
|
[
{
"answer_id": 74622303,
"author": "Vinícius Félix",
"author_id": 9696037,
"author_profile": "https://Stackoverflow.com/users/9696037",
"pm_score": 0,
"selected": false,
"text": "dplyr library(dplyr)\n\ndf <-\n data.frame(\n row = 1:10,\n num = cumsum(rep(3,10)),\n group = c(\"B\",\"A\",\"A\",\"B\",\"A\",\"A\",\"B\",\"A\",\"B\",\"B\")\n )\n\ndf %>% \n filter(num >= 8) %>% \n slice_min(order_by = row)\n\n row num group\n1 3 9 A\n df[min(df$row[(df$num >= 8)]),]\n\n row num group\n1 3 9 A\n"
},
{
"answer_id": 74622434,
"author": "Gwang-Jin Kim",
"author_id": 9690090,
"author_profile": "https://Stackoverflow.com/users/9690090",
"pm_score": 1,
"selected": false,
"text": "nearest_bigger_num <- function(num, vec) {\n which(min(vec[num < vec]) == vec)\n}\n\nnearest_bigger_num(8, df$num)\n## 3\n nearest_bigger_num_in_group <- function(num, df, group) {\n df <- df[df$group == group]\n df <- df[num < df$num]\n df$row[which.min(df$num)]\n}\n\nnearest_bigger_num_in_group(8, df, \"A\")\n## 3\n"
},
{
"answer_id": 74622654,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 1,
"selected": true,
"text": "ifelse() NA which.min() which.min(ifelse(f$Group == \"A\" & f$num >= 8, f$num, NA))\n# 3\n\nwhich.min(ifelse(f$Group == \"A\" & f$num >= 18, f$num, NA))\n# 6\n which.min() NA"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20640086/"
] |
74,622,396
|
<p>If I have coordinates of center point of circle, circle radius and also coordinates of the point that need to be check if a point lies inside or on the boundary of the Circle.</p>
<ul>
<li>$circle_x and $circle_y => center point latitude and longitude of the circle</li>
<li>$rad => radius(Meter) of the circle</li>
<li>$x and $y => latitude and longitude of the point that need to be check</li>
</ul>
<p>I have tried 2 ways,</p>
<pre><code> public function pointInCircle($circle_x, $circle_y, $rad, $x, $y)
{
$dx = abs($x - $circle_x);
$dy = abs($y - $circle_y);
$R = $rad;
if ($dx + $dy <= $R) {
return "inside";
} else if ($dx > $R) {
return "outside";
} else if ($dy > $R) {
return "outside";
} else if ($dx ^ 2 + $dy ^ 2 <= $R ^ 2) {
return "inside";
} else {
return "outside";
}
}
</code></pre>
<p>Second method is,</p>
<pre><code> public function pointInCircle($circle_x, $circle_y, $rad, $x, $y)
{
if ((($x - $circle_x) * ($x - $circle_x) + ($y - $circle_y) * ($y - $circle_y)) <= ($rad * $rad)){
return "inside";
} else {
return "outside";
}
}
</code></pre>
<p>But above 2 methods couldn't provide correct result, please help to find if provided point lies inside or on the boundary of the Circle using PHP.</p>
|
[
{
"answer_id": 74623195,
"author": "MBo",
"author_id": 844416,
"author_profile": "https://Stackoverflow.com/users/844416",
"pm_score": 2,
"selected": true,
"text": "$rad function haversineGreatCircleDistance(\n $latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo, $earthRadius = 6371000)\n{\n // convert from degrees to radians\n $latFrom = deg2rad($latitudeFrom);\n $lonFrom = deg2rad($longitudeFrom);\n $latTo = deg2rad($latitudeTo);\n $lonTo = deg2rad($longitudeTo);\n\n $latDelta = $latTo - $latFrom;\n $lonDelta = $lonTo - $lonFrom;\n\n $angle = 2 * asin(sqrt(pow(sin($latDelta / 2), 2) +\n cos($latFrom) * cos($latTo) * pow(sin($lonDelta / 2), 2)));\n return $angle * $earthRadius;\n}\n if (haversineGreatCircleDistance($circle_y, $circle_x, $y, $x) < $rad)\n point i circle\n $circle_y = 48.8588336; //Paris center\n$circle_x = 2.2769953;\n\n$y = 48.80; //Versailles\n$x = 2.084;\n//$rad = 1000;\n$rad = 100000;\n\nif (haversineGreatCircleDistance($circle_y, $circle_x, $y, $x) < $rad)\n echo \"Inside\";\nelse\n echo \"OUTSIDE\";\n"
},
{
"answer_id": 74623216,
"author": "MZM",
"author_id": 20551381,
"author_profile": "https://Stackoverflow.com/users/20551381",
"pm_score": 0,
"selected": false,
"text": "function pointInCircle($circle_x, $circle_y, $rad, $x, $y)\n {\n $dx = ($x - $circle_x); \n $dy = ($y - $circle_y);\n $dx = $dx * $dx;\n $dy = $dy * $dy;\n \n $dist = $dx + $dy; //eqt of distance.\n\n \n $str = \"outside\";\n if ( $dist <= $rad * $rad)\n $str = \"inside\";\n \n return $str;\n \n }\n \n echo \" result \" . pointInCircle(0,0,25,4,4);\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10115119/"
] |
74,622,398
|
<p>I'm trying to make a navigation bar for reading information. I got the information panels to change after I click on the according tab, but the tab changes color back to its unclicked form. I want to show which tab is currently active.</p>
<p>I tried following a different person's example in here: <a href="https://stackoverflow.com/questions/68150534/color-does-not-change-corresponding-the-radio-checked-in-pure-css-tab-layout">Color does not change corresponding the radio checked in Pure CSS Tab Layout</a>
but only their text is clickable instead of the whole tab
this version below can change color on hover but not after being clicked.</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-html lang-html prettyprint-override"><code><html>
<head>
<style>
.warpper {
display: flex;
flex-direction: column;
align-items: center;
}
.navbar {
width: 100%;
overflow: auto;
}
.tab {
float: left;
padding-top: 12px;
padding-bottom: 12px;
width: 25%; /* Four links of equal widths */
text-align: center;
}
.tab:hover {
background-color: #555;
color: white;
}
.panels {
background: #fff;
min-height: 200px;
width: 100%;
border-radius: 3px;
overflow: hidden;
padding: 20px;
}
.panel {
display: none;
animation: fadein 0.8s;
}
@keyframes fadein {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
.panel-title {
font-size: 1.5em;
font-weight: bold;
}
input[type="radio"] {
display: none;
}
#one:checked ~ .panels #one-panel,
#two:checked ~ .panels #two-panel,
#three:checked ~ .panels #three-panel,
#four:checked ~ .panels #four-panel{
display: block;
}
#one:checked ~ tab #one-tab,
#two:checked ~ tab #two-tab,
#three:checked ~ tab #three-tab,
#four:checked ~ tab #four-tab{
background-color: #000;
color: #fff;
}
</style>
<body>
<div class="warpper">
<input id="one" checked name="group" type="radio" />
<input id="two" name="group" type="radio" />
<input id="three" name="group" type="radio" />
<input id="four" name="group" type="radio" />
<div class="navbar">
<div class="tabs">
<label class="tab" id="one-tab" for="one">Technical</label>
<label class="tab" id="two-tab" for="two">Business</label>
<label class="tab" id="three-tab" for="three">Cost</label>
<label class="tab" id="four-tab" for="four">Design</label>
</div>
</div>
<div class="panels">
<div class="panel" id="one-panel">
<p>During technical inspection, the car is examined to ensure it meets rule and safety requirements. Inspection is sequentially divided into scrutineering, tilt, noise, and brake tests. After each test, a sticker is placed on the car, showing that it passed. The car cannot compete without passing technical inspection.<br/>
In the scrutineering phase of the inspection, judges investigate the car for any possible rule violations. During tilt, the car is placed on a tilt stand with a driver, where it is tilted towards the fuel tank fill nozzle. It must not spill fluids up to 45 degrees and must not roll over up to 60 degrees. For the noise test, the car’s noise output from the exhaust must meet the standards set in the FSAE Rulebook. The car is also tested to ensure the kill switch is functional. To pass the brake test, a driver must accelerate the car on a short straightaway and prove brake integrity by coming to a complete stop without spinning. All four wheels must lock, and the engine must still be running.</p>
</div>
<div class="panel" id="two-panel">
<p>The business logic case is a document each team must submit to the FSAE Committee. It summarizes the business case behind the plan for production on a larger scale. The document highlights the production scale, targeted market, profitability, and key features. <br/>The presentation is given to judges at competition, where two representatives from the team, usually the Business Lead and a business team member, showcase the car and team to potential “investors”. They must also be able to answer any questions the investors may ask. The judges should be treated as if they are executives at a corporation.</p>
</div>
<div class="panel" id="three-panel">
<p>A cost report must be created and submitted before competition, which lists the cost for every part and manufacturing process required to build a complete car for production. During the event, a team representative must defend any conflicting items judges find between the car and the document submitted beforehand. Any inconsistencies that cannot be explained will be penalized in the final score. Teams are scored based on the final adjusted cost to produce their car. In addition, a real case scenario is presented to the teams requiring them to respond to a cost overrun or other production issue.</p>
</div>
<div class="panel" id="four-panel">
<p>The design event is the most heavily weighted static event. The entire team explains and defends design choices, testing, and analysis that went into building the racecar. Judges, engineers who often work in the automotive industry, question team members on their choices, and attempt to challenge every position a team takes and every fact the team states. They want to see that a team has validated every design choice, such as intake shape, suspension point locations, tire sizes/type, engine calibration, and chassis design. <br/>
A design document is submitted to support this event, which members and judges refer to when going over each system. The team is scored based on how knowledgeable the members are, the appropriateness of the parts used, and overall fit-and-finish of the car.</p>
</div>
</div>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74623195,
"author": "MBo",
"author_id": 844416,
"author_profile": "https://Stackoverflow.com/users/844416",
"pm_score": 2,
"selected": true,
"text": "$rad function haversineGreatCircleDistance(\n $latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo, $earthRadius = 6371000)\n{\n // convert from degrees to radians\n $latFrom = deg2rad($latitudeFrom);\n $lonFrom = deg2rad($longitudeFrom);\n $latTo = deg2rad($latitudeTo);\n $lonTo = deg2rad($longitudeTo);\n\n $latDelta = $latTo - $latFrom;\n $lonDelta = $lonTo - $lonFrom;\n\n $angle = 2 * asin(sqrt(pow(sin($latDelta / 2), 2) +\n cos($latFrom) * cos($latTo) * pow(sin($lonDelta / 2), 2)));\n return $angle * $earthRadius;\n}\n if (haversineGreatCircleDistance($circle_y, $circle_x, $y, $x) < $rad)\n point i circle\n $circle_y = 48.8588336; //Paris center\n$circle_x = 2.2769953;\n\n$y = 48.80; //Versailles\n$x = 2.084;\n//$rad = 1000;\n$rad = 100000;\n\nif (haversineGreatCircleDistance($circle_y, $circle_x, $y, $x) < $rad)\n echo \"Inside\";\nelse\n echo \"OUTSIDE\";\n"
},
{
"answer_id": 74623216,
"author": "MZM",
"author_id": 20551381,
"author_profile": "https://Stackoverflow.com/users/20551381",
"pm_score": 0,
"selected": false,
"text": "function pointInCircle($circle_x, $circle_y, $rad, $x, $y)\n {\n $dx = ($x - $circle_x); \n $dy = ($y - $circle_y);\n $dx = $dx * $dx;\n $dy = $dy * $dy;\n \n $dist = $dx + $dy; //eqt of distance.\n\n \n $str = \"outside\";\n if ( $dist <= $rad * $rad)\n $str = \"inside\";\n \n return $str;\n \n }\n \n echo \" result \" . pointInCircle(0,0,25,4,4);\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20640251/"
] |
74,622,412
|
<p>Sorry if this has been answered, but I couldn't quite seem to find an answer that addressed this particular issue. Here is a small sample of the data I'm using:</p>
<pre><code>precinct_no,newsom_count,dahle_count,difference
0001-100000-SAN PASQUAL,5,18,-13
0002-100090-SAN PASQUAL,567,622,-55
0003-100120-SAN PASQUAL,0,0,0
0004-100150-SAN PASQUAL,0,0,0
0005-105000-RANCHO BERNARDO,572,538,34
0006-105040-RANCHO BERNARDO,609,582,27
</code></pre>
<p>In the precinct_no column, how can I strip everything except for the middle six digits? I don't want the four digits in the beginning, the town names at the end, or the dashes. Just those middle six digits. I need to do this for about 3,000 rows.</p>
|
[
{
"answer_id": 74623195,
"author": "MBo",
"author_id": 844416,
"author_profile": "https://Stackoverflow.com/users/844416",
"pm_score": 2,
"selected": true,
"text": "$rad function haversineGreatCircleDistance(\n $latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo, $earthRadius = 6371000)\n{\n // convert from degrees to radians\n $latFrom = deg2rad($latitudeFrom);\n $lonFrom = deg2rad($longitudeFrom);\n $latTo = deg2rad($latitudeTo);\n $lonTo = deg2rad($longitudeTo);\n\n $latDelta = $latTo - $latFrom;\n $lonDelta = $lonTo - $lonFrom;\n\n $angle = 2 * asin(sqrt(pow(sin($latDelta / 2), 2) +\n cos($latFrom) * cos($latTo) * pow(sin($lonDelta / 2), 2)));\n return $angle * $earthRadius;\n}\n if (haversineGreatCircleDistance($circle_y, $circle_x, $y, $x) < $rad)\n point i circle\n $circle_y = 48.8588336; //Paris center\n$circle_x = 2.2769953;\n\n$y = 48.80; //Versailles\n$x = 2.084;\n//$rad = 1000;\n$rad = 100000;\n\nif (haversineGreatCircleDistance($circle_y, $circle_x, $y, $x) < $rad)\n echo \"Inside\";\nelse\n echo \"OUTSIDE\";\n"
},
{
"answer_id": 74623216,
"author": "MZM",
"author_id": 20551381,
"author_profile": "https://Stackoverflow.com/users/20551381",
"pm_score": 0,
"selected": false,
"text": "function pointInCircle($circle_x, $circle_y, $rad, $x, $y)\n {\n $dx = ($x - $circle_x); \n $dy = ($y - $circle_y);\n $dx = $dx * $dx;\n $dy = $dy * $dy;\n \n $dist = $dx + $dy; //eqt of distance.\n\n \n $str = \"outside\";\n if ( $dist <= $rad * $rad)\n $str = \"inside\";\n \n return $str;\n \n }\n \n echo \" result \" . pointInCircle(0,0,25,4,4);\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11287952/"
] |
74,622,426
|
<p>I'm writing a function to convert a weirdly formatted Degrees Minutes Seconds to Degrees Decimal.</p>
<p>My code is:</p>
<pre><code>def fromDMS(coordinate):
lat_dms = coordinate[0:10]
lon_dms = coordinate[11:21]
lat_sign = lat_dms[0]
lat_deg = float(lat_dms[1:3])
lat_min = float(lat_dms[3:5])
lat_sec = float(lat_dms[5:])
lon_sign = lon_dms[0]
lon_deg = float(lon_dms[1:4])
lon_min = float(lat_dms[4:6])
lon_sec = float(lat_dms[6:])
lat_deg = (lat_deg + (lat_min/60) + (lat_sec/(60 * 2)))
if lat_sign == "-": lat_deg = lat_deg * -1
lon_deg = (lon_deg + (lon_min/60) + (lon_sec/(60 * 2)))
if lon_deg == "-": lon_deg = lon_deg * -1
return lat_deg, lon_deg
</code></pre>
<p>The format in question is this string</p>
<pre><code>-365535.000+1745401.000
</code></pre>
<p>where "-365535.000" (-36 degrees, 55 minutes, 35 seconds) is the latitude and "+1745401.000" (174 degrees, 55 minutes, and 1 second) is the longitude. Using an online calculator, these values should result in "-36.926389" and "174.916944", but end up as "37.20833333333333" and "174.92499999999998". I've heard that float's can be a little weird sometimes, but not to this extent.</p>
|
[
{
"answer_id": 74622473,
"author": "John Gordon",
"author_id": 494134,
"author_profile": "https://Stackoverflow.com/users/494134",
"pm_score": 0,
"selected": false,
"text": "lon_sign = lon_dms[0]\nlon_deg = float(lon_dms[1:4])\nlon_min = float(lat_dms[4:6])\nlon_sec = float(lat_dms[6:])\n lat_dms lon_dms"
},
{
"answer_id": 74622583,
"author": "Matthew James Kraai",
"author_id": 16280918,
"author_profile": "https://Stackoverflow.com/users/16280918",
"pm_score": 3,
"selected": true,
"text": "60 * 2 60 ** 2 lon_min lon_sec lat_dms lon_dms"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10853679/"
] |
74,622,440
|
<p>I want to check if all elements of a list are not present in a string.</p>
<p>ex :</p>
<pre><code> l = ["abc","ghi"]
s1 = "xyzjkl"
s2 = "abcdef"
</code></pre>
<p>So , when l is compared with s1 it should return True,
when l is compared with s2 it should return False.</p>
<p>This is what i tried :</p>
<pre><code> all(x for x in l if x not in s1) = True
all(x for x in l if x not in s2) = True
</code></pre>
<p>I am getting True for both cases, But it should be false in second case.
Can someone please help, any solution will help, i just want to have it in a single line.</p>
<p>Thanks,</p>
|
[
{
"answer_id": 74622492,
"author": "Alexander L. Hayes",
"author_id": 12439119,
"author_profile": "https://Stackoverflow.com/users/12439119",
"pm_score": 2,
"selected": true,
"text": "all(s not in my_string for s in input_list) l = [\"abc\",\"ghi\"]\ns1 = \"xyzjkl\"\ns2 = \"abcdef\"\n\nprint(all(s not in s1 for s in l)) # True\nprint(all(s not in s2 for s in l)) # False\n"
},
{
"answer_id": 74622494,
"author": "SomeDude",
"author_id": 1410303,
"author_profile": "https://Stackoverflow.com/users/1410303",
"pm_score": 2,
"selected": false,
"text": "all all([x not in s1 for x in l])\nall([x not in s2 for x in l])\n all all(x not in s1 for x in l)\nall(x not in s2 for x in l)\n"
},
{
"answer_id": 74622500,
"author": "Martí",
"author_id": 14488888,
"author_profile": "https://Stackoverflow.com/users/14488888",
"pm_score": 1,
"selected": false,
"text": "all(x not in s1 for x in l) # True\nall(x not in s2 for x in l) # False\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20147061/"
] |
74,622,451
|
<p>I want to add virtual fields / attributes to a rails model and have it included in the attributes that get returned by default when I call <code>@my_model</code></p>
<p>Assuming I have a model called Booking that has a <code>start_at</code> and <code>end_at</code> that are both datetime fields.</p>
<pre class="lang-ruby prettyprint-override"><code>@booking = Booking.new(start_at: DateTime.now, end_at: DateTime.now + 4.hours)
</code></pre>
<p>When I print the booking or say render it as json etc I get the following:</p>
<pre class="lang-ruby prettyprint-override"><code>p @booking
# Booking
id => 1,
start_at => Wed, 30 Nov 2022 10:50:20 +0800,
end_at => Wed, 30 Nov 2022 14:50:22 +0800
</code></pre>
<p>All standard so far.</p>
<p>Now I want to add virtual attributes called <code>start_date, start_time, end_date, end_time</code> that will be derived from the <code>start_at</code> and <code>end_at</code> fields</p>
<p>So I add them as attributes to the class:</p>
<pre class="lang-ruby prettyprint-override"><code>class Booking < ApplicationRecord
attr_accessor :start_date, :start_time, :end_date, :end_time
def start_time
self.start_at.strftime('%H:%M')
end
...etc
end
</code></pre>
<p>so now I print the model again:</p>
<pre class="lang-ruby prettyprint-override"><code>
@booking
# Booking
id => 1,
start_at => Wed, 30 Nov 2022 10:50:20 +0800,
end_at => Wed, 30 Nov 2022 14:50:22 +0800
</code></pre>
<p>The virtual attributes are not shown.</p>
<p>However if I add them to the attributes method I can call <code>@booking.attributes</code>:</p>
<pre class="lang-ruby prettyprint-override"><code>
class Booking < ApplicationRecord
attr_accessor :start_date, :start_time, :end_date, :end_time
def start_time
self.start_at.strftime('%H:%M')
end
def attributes
super.merge({'start_time' => start_ime})
end
end
@booking.attributes
# Booking
id => 1,
start_at => Wed, 30 Nov 2022 10:50:20 +0800,
end_at => Wed, 30 Nov 2022 14:50:22 +0800
start_time => '10:50'
...etc
</code></pre>
<p>So my question is how can i modify what attributes get returned by default, so I don't have to call .attributes on the model every time? I would like to just do <code>render json: @booking</code> and have all attributes (including the virtual ones) included.</p>
<p>Thanks in advance</p>
|
[
{
"answer_id": 74627707,
"author": "markets",
"author_id": 3033649,
"author_profile": "https://Stackoverflow.com/users/3033649",
"pm_score": 0,
"selected": false,
"text": "as_json class Booking < ApplicationRecord\n def as_json(*)\n super(methods: %i(start_date start_time end_date end_time))\n end\nend\n as_json"
},
{
"answer_id": 74630100,
"author": "max",
"author_id": 544825,
"author_profile": "https://Stackoverflow.com/users/544825",
"pm_score": 1,
"selected": false,
"text": "attr_accessor attr_accessor :start_date start_date start_date= start_date ActiveModel::Attributes ActiveRecord::Attributes class Booking < ApplicationRecord\n attribute :start_at, type: :datetime\nend\n irb(main):005:0> Booking.new.as_json\n=> {\"id\"=>nil, \"created_at\"=>nil, \"updated_at\"=>nil, \"start_at\"=>nil} \n attr_accessor to_json methods: class Booking < ApplicationRecord\n attribute :start_at, type: :datetime\n\n def start_time\n start_at.strftime('%H:%M')\n end\nend\n irb(main):013:0> Booking.new(start_at: Time.now).as_json(methods: [:start_time])\n=> {\"id\"=>nil, \"created_at\"=>nil, \"updated_at\"=>nil, \"start_at\"=>\"2022-11-30T16:12:02.188+01:00\", \"start_time\"=>\"16:12\"}\n render json: @booking, methods: [:start_at]\n as_json"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6019903/"
] |
74,622,461
|
<p>I'm creating a website using NextJS and Docker so that I can easily deploy it. I used <code>npx-create-next-app</code> to initialize it and used <a href="https://github.com/vercel/next.js/blob/canary/examples/with-docker/Dockerfile" rel="nofollow noreferrer">this Dockerfile</a> (slightly modified) to containerize it. Since I wanted to use SSL with my server without going through the hassle of setting up a proxy, I followed <a href="https://noobgrammer.com/2021/03/07/enable-https-in-local-nextjs-application/" rel="nofollow noreferrer">this article</a>, and setup the custom server.</p>
<p>This worked fine when I ran it outside of a docker container, and performed as expected, serving over HTTPS. However when I containerized it, and tried to open the webpage over HTTPS, I came up with <code>SSL_ERROR_RX_RECORD_TOO_LONG</code>, but I could open the page using just HTTP (which I could not do when running outside of a container). Some googling led me to <a href="https://stackoverflow.com/questions/20576362/running-https-not-on-443-how-is-this-possible">this question</a>, from which I concluded that when running outside of a docker container, the custom server runs the server over HTTPS, as expected, however when I containerize it, it starts running HTTP, even though no code has been changed.</p>
<p>I'd expect the behavior to be the same when running locally or containerized.</p>
<p>At first I assumed this was due to invalid <code>key</code> and <code>cert</code> values in <code>httpsOptions</code> however I wasn't able to find anything that would make them invalid, and I don't see how that would cause this strange behavior. I tried changing the Docker run environment from <code>node:alpine-16</code> to just <code>node:latest</code> to see if it had something to do with the parent image, but that was fruitless.</p>
<p>One other minor issue I had is that <code>console.log</code> does not seem to output to the container's log for some reason, I tried googling this but didn't find much of anything pertaining to it. This has made debugging much harder as I can't really output any debug data. The only log I get when running inside of a container is <code>Listening on port 3000 url: http://localhost:3000</code>, which I assume is output by some library/package as it isn't anywhere in my code.</p>
<p>Here is my custom server code in case it would be helpful:</p>
<pre class="lang-js prettyprint-override"><code>const https = require('https');
const fs = require('fs');
const { parse } = require('url');
const next = require('next');
const dev = process.env.NODE_ENV !== 'production';
const hostname = "127.0.0.1";
const port = process.env.PORT || 3000
const app = next({ dev, hostname, port })
const handle = app.getRequestHandler()
const httpsOptions = {
key: fs.readFileSync('./cert/privkey.pem'),
cert: fs.readFileSync('./cert/fullchain.pem')
};
app.prepare().then(() => {
https.createServer(httpsOptions, async (req, res) => { // When running on docker this creates an HTTP server instead of HTTPS
const parsedUrl = parse(req.url, true)
const { pathname, query } = parsedUrl
await handle(req, res, parsedUrl)
}).listen(port, (err) => {
if(err) throw err
console.log(`Ready on https://localhost:${port}`)
})
})
</code></pre>
<p>Link to a reproducible example <a href="https://github.com/jaydevelopsstuff/Docker-HTTPS-Bug-MRE" rel="nofollow noreferrer">here</a>.</p>
|
[
{
"answer_id": 74627707,
"author": "markets",
"author_id": 3033649,
"author_profile": "https://Stackoverflow.com/users/3033649",
"pm_score": 0,
"selected": false,
"text": "as_json class Booking < ApplicationRecord\n def as_json(*)\n super(methods: %i(start_date start_time end_date end_time))\n end\nend\n as_json"
},
{
"answer_id": 74630100,
"author": "max",
"author_id": 544825,
"author_profile": "https://Stackoverflow.com/users/544825",
"pm_score": 1,
"selected": false,
"text": "attr_accessor attr_accessor :start_date start_date start_date= start_date ActiveModel::Attributes ActiveRecord::Attributes class Booking < ApplicationRecord\n attribute :start_at, type: :datetime\nend\n irb(main):005:0> Booking.new.as_json\n=> {\"id\"=>nil, \"created_at\"=>nil, \"updated_at\"=>nil, \"start_at\"=>nil} \n attr_accessor to_json methods: class Booking < ApplicationRecord\n attribute :start_at, type: :datetime\n\n def start_time\n start_at.strftime('%H:%M')\n end\nend\n irb(main):013:0> Booking.new(start_at: Time.now).as_json(methods: [:start_time])\n=> {\"id\"=>nil, \"created_at\"=>nil, \"updated_at\"=>nil, \"start_at\"=>\"2022-11-30T16:12:02.188+01:00\", \"start_time\"=>\"16:12\"}\n render json: @booking, methods: [:start_at]\n as_json"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14602745/"
] |
74,622,467
|
<p>I am new to Nextflow and I want to unzip a fastq.gz file. But It raised the error <code>gunzip: SRR1659960_05pc_R1.fastq.gz is not a regular file</code>.
I tried to run the same command directly in my console, it works well.
My Nextflow script is:</p>
<pre><code>process gz_uncompress{
input:
path fastq_r1_gz_path
output:
path fastq_r1_path
script:
"""
gunzip -kd $fastq_r1_gz_path > "fastq_r1_path.fastq"
"""
}
workflow{
gz_uncompress("/Users/test/PycharmProjects/nf-easyfuse/local_test/SRR1659960_05pc_R1.fastq.gz")
}
</code></pre>
<p>The error message is:</p>
<pre><code>local_test ywan$ nextflow run t2.nf
N E X T F L O W ~ version 22.10.3
Launching `t2.nf` [peaceful_wilson] DSL2 - revision: bf9e3bc592
executor > local (1)
[36/f8301b] process > gz_uncompress [ 0%] 0 of 1
Error executing process > 'gz_uncompress'
Caused by:
Process `gz_uncompress` terminated with an error exit status (1)
Command executed:
gunzip -kd SRR1659960_05pc_R1.fastq.gz > "fastq_r1_path.fastq"
Command exit status:
1
executor > local (1)
[36/f8301b] process > gz_uncompress [100%] 1 of 1, failed: 1 ✘
Error executing process > 'gz_uncompress'
Caused by:
Process `gz_uncompress` terminated with an error exit status (1)
Command executed:
gunzip -kd SRR1659960_05pc_R1.fastq.gz > "fastq_r1_path.fastq"
Command exit status:
1
Command output:
(empty)
Command error:
gunzip: SRR1659960_05pc_R1.fastq.gz is not a regular file
Work dir:
/Users/test/PycharmProjects/nf-easyfuse/local_test/work/36/f8301b816e9eb834597ff1e6616c51
Tip: view the complete command output by changing to the process work dir and entering the command `cat .command.out`
</code></pre>
<p>But when I ran <code>gunzip -kd SRR1659960_05pc_R1.fastq.gz > "fastq_r1_path.fastq"</code> in my console, there isn't any errors.</p>
<p>Could you please help me to figure out?</p>
|
[
{
"answer_id": 74622825,
"author": "One thousand",
"author_id": 7517120,
"author_profile": "https://Stackoverflow.com/users/7517120",
"pm_score": -1,
"selected": false,
"text": "-f process gz_uncompress2{\n input:\n path f1\n output:\n path \"*.fastq\"\n script:\n \"\"\"\n gunzip -fkd $f1 > fastq_r1_path\n \"\"\"\n}\n\nworkflow{\n path = gz_uncompress2(\"/Users/test/PycharmProjects/nf-easyfuse/local_test/SRR1659960_05pc_R1.fastq.gz\")\n path.view()\n}\n"
},
{
"answer_id": 74622847,
"author": "Steve",
"author_id": 751863,
"author_profile": "https://Stackoverflow.com/users/751863",
"pm_score": 2,
"selected": true,
"text": "StageInMode gunzip -c params.fastq = './test.fastq.gz'\n\n\nprocess gunzip_fastq {\n\n input:\n path fastq_gz\n\n output:\n path fastq_gz.baseName\n\n script:\n \"\"\"\n gunzip -c \"${fastq_gz}\" > \"${fastq_gz.baseName}\"\n \"\"\"\n}\n\nworkflow{\n\n fastq = file( params.fastq )\n\n gunzip_fastq( fastq )\n}\n zcat zcat gunzip -c"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7517120/"
] |
74,622,470
|
<p>I'm trying to create a shiny app with multiple actionButtons that render unique text to the same varbatimTextOutput. I'd like it to work like this, where buttons 1 and 2 would print different text to the same place:</p>
<p><a href="https://i.stack.imgur.com/hbygY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hbygY.png" alt="enter image description here" /></a></p>
<p>Here's what I tried:</p>
<pre><code>library(shiny)
ui <- fluidPage(
actionButton("button1", "Button 1"),
actionButton("button2", "Button 2"),
verbatimTextOutput("button_out", placeholder = TRUE)
)
server <- function(input, output) {
button_out <- eventReactive({
input$button1
}
,{
paste0("You pressed button 1!")
})
button_out <- eventReactive({
input$button2
}
,{
paste0("You pressed button 2!")
})
output$button_out <- renderText({
button_out()
})
}
shinyApp(ui = ui, server = server)
</code></pre>
<p>I was expecting this to allow both actionButtons to output to the same place, but instead only Button 2 works, I guess because the code for that is overwriting the code for button 1. I considered putting an if statement in eventReactive, but I'm not exactly sure how to do it?</p>
<p>Is there a way to do this that I'm not seeing?</p>
|
[
{
"answer_id": 74622538,
"author": "YBS",
"author_id": 13333279,
"author_profile": "https://Stackoverflow.com/users/13333279",
"pm_score": 2,
"selected": true,
"text": "reactiveValues ui <- fluidPage(\n actionButton(\"button1\", \"Button 1\"),\n actionButton(\"button2\", \"Button 2\"),\n verbatimTextOutput(\"button_out\", placeholder = TRUE)\n)\n\nserver <- function(input, output) {\n \n rv <- reactiveValues(val=NULL)\n \n observeEvent(input$button1, {\n rv$val <- paste0(\"You pressed button 1!\")\n }) \n \n observeEvent(input$button2, {\n rv$val <- paste0(\"You pressed button 2!\")\n })\n \n output$button_out <- renderText({\n rv$val\n })\n}\n\nshinyApp(ui = ui, server = server)\n"
},
{
"answer_id": 74628904,
"author": "Stéphane Laurent",
"author_id": 1100107,
"author_profile": "https://Stackoverflow.com/users/1100107",
"pm_score": 2,
"selected": false,
"text": "onclick Shiny.setInputValue library(shiny)\n\nui <- fluidPage(\n actionButton(\n \"button1\", \"Button 1\", \n onclick = \"Shiny.setInputValue('button', 1);\"\n ),\n actionButton(\n \"button2\", \"Button 2\", \n onclick = \"Shiny.setInputValue('button', 2);\"\n ),\n verbatimTextOutput(\"button_out\", placeholder = TRUE)\n)\n\nserver <- function(input, output) {\n \n output$button_out <- renderText({\n paste0(\"You clicked on button \", input$button) \n })\n}\n \nshinyApp(ui = ui, server = server)\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8228867/"
] |
74,622,475
|
<p>So I have a problem while doing the search filtering features for searching through all columns in the Datagrid table; I've implemented the search based on the selected column field, which is working just fine, and there is an option for the search input to search through the <code>All columns</code>.</p>
<p>I get all the column data dynamically from the MUI Grid API and the <code>valueTwo</code> array is the representation of the column data that I got from the MUI Grid API.</p>
<pre><code>const valueOne = [
{
name: 'Jacqueline',
reference: 'PRD-143',
active: true,
},
{
name: 'Jacqueline',
reference: 'PRD-143',
active: true,
},
{
name: 'Jacqueline',
reference: 'PRD-143',
active: true,
}
]
</code></pre>
<pre><code>const valueTwo = [
{
id: '01',
field: 'name',
headerName: 'Name'
},
{
id: '02',
field: 'reference',
headerName: 'Reference'
},
{
id: '01',
field: 'active',
headerName: 'Status'
},
]
</code></pre>
<p><a href="https://i.stack.imgur.com/I1ve2.png" rel="nofollow noreferrer">This is the application, image</a></p>
<p>This the hooks that I write</p>
<pre><code>export function useSearchTable<T>(
tableData: T[],
setTableItems: Dispatch<SetStateAction<T[]>>,
searchState: string,
) {
const [selectedColumnHeader, setSelectedColumnHeader] = useState<
ColumnHeaderInterface | any
>({
field: `allColumns`,
headerName: `All Columns`,
});
const [filteredColumnHeaders, setFilteredColumnHeaders] = useState<
GridStateColDef[] | any
>();
const debouncedSearchState = useDebounce(searchState, 500) as string;
const requestSearch = (dataItems: T[]) => {
switch (selectedColumnHeader.field) {
case `allColumns`: {
let allColumnFilter: T[] = [];
const columnTempData = [] as any[];
if (filteredColumnHeaders) {
for (const columnHeader of filteredColumnHeaders) {
columnTempData.push(columnHeader.field);
}
}
// TODO: something is broken here
columnTempData.forEach((columnName) => {
allColumnFilter = dataItems.filter((itemData: any) => {
if (
typeof itemData[columnName] === `boolean` ||
typeof itemData[columnName] === `number`
) {
String(itemData[columnName])
.toLowerCase()
.includes(debouncedSearchState.toLowerCase());
}
if (typeof itemData[columnName] === `object`) {
itemData[columnName]?.name
.toLowerCase()
.includes(debouncedSearchState.toLowerCase());
}
return itemData;
});
});
console.log(columnTempData, `itemTempData`);
console.log(allColumnFilter, `columnFilterSearch`);
setTableItems(allColumnFilter);
break;
}
default: {
const filteredSearchData = dataItems.filter((itemData: any) => {
let data = itemData[selectedColumnHeader.field];
if (typeof data === `boolean` || typeof data === `number`) {
data = String(data);
}
// TODO: quick fix, but need to research on other API data regarding the resources: vehicles, machines, standalones
if (typeof data === `object`) {
data = data?.name;
}
console.log(
data?.toLowerCase().includes(debouncedSearchState.toLowerCase()),
`data`,
);
return data
?.toLowerCase()
.includes(debouncedSearchState.toLowerCase());
});
setTableItems(filteredSearchData);
break;
}
}
};
useEffect(() => {
if (tableData) {
requestSearch(tableData);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
debouncedSearchState,
tableData,
filteredColumnHeaders,
selectedColumnHeader,
]);
return {
setFilteredColumnHeaders,
setSelectedColumnHeader,
selectedColumnHeader,
};
}
</code></pre>
<p><code>columnTempData</code> is basically an array of string containing the field name from the column header data that I set in <code>filteredColumnHeaders</code>. And things that needs to be fix is on the <code>// TODO</code> comment</p>
<p>The code that I expect is to get all the filtered data based on the search through all the columns with the column data that comes from the MUI Grid API.</p>
<p>I'm a one-man engineer and I really need your assistance here :)</p>
<p>I've tried to loop through the column field data and then looping the table list data and access each key based on the column field data, something like this:</p>
<pre><code> columnTempData.forEach((columnName) => {
allColumnFilter = dataItems.filter((itemData: any) => {
if (
typeof itemData[columnName] === `boolean` ||
typeof itemData[columnName] === `number`
) {
String(itemData[columnName])
.toLowerCase()
.includes(debouncedSearchState.toLowerCase());
}
if (typeof itemData[columnName] === `object`) {
itemData[columnName]?.name
.toLowerCase()
.includes(debouncedSearchState.toLowerCase());
}
return itemData;
});
});
</code></pre>
<p>It should have been returning the all filtered data based on the input given. so no matter what column is being search the data is going to filtered based on the input.</p>
|
[
{
"answer_id": 74622538,
"author": "YBS",
"author_id": 13333279,
"author_profile": "https://Stackoverflow.com/users/13333279",
"pm_score": 2,
"selected": true,
"text": "reactiveValues ui <- fluidPage(\n actionButton(\"button1\", \"Button 1\"),\n actionButton(\"button2\", \"Button 2\"),\n verbatimTextOutput(\"button_out\", placeholder = TRUE)\n)\n\nserver <- function(input, output) {\n \n rv <- reactiveValues(val=NULL)\n \n observeEvent(input$button1, {\n rv$val <- paste0(\"You pressed button 1!\")\n }) \n \n observeEvent(input$button2, {\n rv$val <- paste0(\"You pressed button 2!\")\n })\n \n output$button_out <- renderText({\n rv$val\n })\n}\n\nshinyApp(ui = ui, server = server)\n"
},
{
"answer_id": 74628904,
"author": "Stéphane Laurent",
"author_id": 1100107,
"author_profile": "https://Stackoverflow.com/users/1100107",
"pm_score": 2,
"selected": false,
"text": "onclick Shiny.setInputValue library(shiny)\n\nui <- fluidPage(\n actionButton(\n \"button1\", \"Button 1\", \n onclick = \"Shiny.setInputValue('button', 1);\"\n ),\n actionButton(\n \"button2\", \"Button 2\", \n onclick = \"Shiny.setInputValue('button', 2);\"\n ),\n verbatimTextOutput(\"button_out\", placeholder = TRUE)\n)\n\nserver <- function(input, output) {\n \n output$button_out <- renderText({\n paste0(\"You clicked on button \", input$button) \n })\n}\n \nshinyApp(ui = ui, server = server)\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14286178/"
] |
74,622,542
|
<p>I'm trying to extract those objects with the value required = true. I can make a forEach and push into a new array, but I would like to know how to do this with another method.</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 arr = [
{ customFields: [{ id: 0, required: true }, { id: 1, required: false }] },
{ customFields: [{ id: 2, required: false }, { id: 3, required: false }] },
{ customFields: [{ id: 4, required: false }, { id: 5, required: true }] },
]
const requireds = arr.map(x => x.customFields.filter(y => y.required ))
console.log(requireds)
// expected = [{ id: 0, required: true }, { id: 5, required: true } ]</code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74622538,
"author": "YBS",
"author_id": 13333279,
"author_profile": "https://Stackoverflow.com/users/13333279",
"pm_score": 2,
"selected": true,
"text": "reactiveValues ui <- fluidPage(\n actionButton(\"button1\", \"Button 1\"),\n actionButton(\"button2\", \"Button 2\"),\n verbatimTextOutput(\"button_out\", placeholder = TRUE)\n)\n\nserver <- function(input, output) {\n \n rv <- reactiveValues(val=NULL)\n \n observeEvent(input$button1, {\n rv$val <- paste0(\"You pressed button 1!\")\n }) \n \n observeEvent(input$button2, {\n rv$val <- paste0(\"You pressed button 2!\")\n })\n \n output$button_out <- renderText({\n rv$val\n })\n}\n\nshinyApp(ui = ui, server = server)\n"
},
{
"answer_id": 74628904,
"author": "Stéphane Laurent",
"author_id": 1100107,
"author_profile": "https://Stackoverflow.com/users/1100107",
"pm_score": 2,
"selected": false,
"text": "onclick Shiny.setInputValue library(shiny)\n\nui <- fluidPage(\n actionButton(\n \"button1\", \"Button 1\", \n onclick = \"Shiny.setInputValue('button', 1);\"\n ),\n actionButton(\n \"button2\", \"Button 2\", \n onclick = \"Shiny.setInputValue('button', 2);\"\n ),\n verbatimTextOutput(\"button_out\", placeholder = TRUE)\n)\n\nserver <- function(input, output) {\n \n output$button_out <- renderText({\n paste0(\"You clicked on button \", input$button) \n })\n}\n \nshinyApp(ui = ui, server = server)\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13662339/"
] |
74,622,561
|
<p>Operations on bits.
How to take 2 bits from byte like this:
take first 2 from 12345678 = 12;
Make new byte = 00000012</p>
<p>For example as asked in discussion by jspit :</p>
<pre><code>$char = 'z'; //is 122, 0111 1010
$b = $char & '?'; // ? is 63, 0011 1111
echo $b; //$b becomes 58 and shows ':'
//if integer used you get:
$b = $char & 63;// 63 is 0011 1111 as '?' but $char is string and you get 0 result:
echo $b; //$b becomes 0 because conversion to integer is used from string and $char becomes 0 and get 0 & 63 = 0, and here is error.
</code></pre>
<p>For clearance operation is on bits not on bytes, but bits from bytes.
'string' >> 1 not work, but this is second problem.</p>
<p><a href="https://php10.5v.pl/safetoken/" rel="nofollow noreferrer">Codes of char You can check on my site generating safe readable tokens</a>, with byte template option on. Site is in all available languages.</p>
<p>I think I found good answer here:
<a href="https://stackoverflow.com/questions/48516510/how-to-bitwise-shift-a-string-in-php">how to bitwise shift a string in php?</a></p>
<p><em>PS. Sorry I cant vote yours fine answers but I have no points reputation here to do this ;)...</em></p>
|
[
{
"answer_id": 74622538,
"author": "YBS",
"author_id": 13333279,
"author_profile": "https://Stackoverflow.com/users/13333279",
"pm_score": 2,
"selected": true,
"text": "reactiveValues ui <- fluidPage(\n actionButton(\"button1\", \"Button 1\"),\n actionButton(\"button2\", \"Button 2\"),\n verbatimTextOutput(\"button_out\", placeholder = TRUE)\n)\n\nserver <- function(input, output) {\n \n rv <- reactiveValues(val=NULL)\n \n observeEvent(input$button1, {\n rv$val <- paste0(\"You pressed button 1!\")\n }) \n \n observeEvent(input$button2, {\n rv$val <- paste0(\"You pressed button 2!\")\n })\n \n output$button_out <- renderText({\n rv$val\n })\n}\n\nshinyApp(ui = ui, server = server)\n"
},
{
"answer_id": 74628904,
"author": "Stéphane Laurent",
"author_id": 1100107,
"author_profile": "https://Stackoverflow.com/users/1100107",
"pm_score": 2,
"selected": false,
"text": "onclick Shiny.setInputValue library(shiny)\n\nui <- fluidPage(\n actionButton(\n \"button1\", \"Button 1\", \n onclick = \"Shiny.setInputValue('button', 1);\"\n ),\n actionButton(\n \"button2\", \"Button 2\", \n onclick = \"Shiny.setInputValue('button', 2);\"\n ),\n verbatimTextOutput(\"button_out\", placeholder = TRUE)\n)\n\nserver <- function(input, output) {\n \n output$button_out <- renderText({\n paste0(\"You clicked on button \", input$button) \n })\n}\n \nshinyApp(ui = ui, server = server)\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16776399/"
] |
74,622,572
|
<p>I am trying to make a program of a chess board, When a user inputs an x and y value it will either output "black" or "white".</p>
<pre><code>x = int(input("Please enter your (x) first number 1-8::"))
y = int(input("Please enter your (y) second number 1-8::"))
column = x % 2
row = y % 2
if column %2 == 0 and row %2 == 1:
print("")
print("white")
elif row %2 ==0 and column %2 == 1:
print("")
print("black")
</code></pre>
<p>Whenever i input 1 for "x" and 2 for "y" it outputs "black", great this is the correct output. But whenever i input some other numbers such as 2 and 2, it gives me a blank output. Whenever i input 1 and 4, it outputs "black" which the correct output should have been "white. How do i make it so that whenever user inputs two numbers ranging from 1 to 8, it outputs the correct colour tile? I am not trying to make the code more advanced but would appreciate some help!</p>
<p>This is the chess board i am basing the colours on.( Do not mind the text on the picture)</p>
<p><img src="https://i.stack.imgur.com/ZBAjk.png" alt="enter image description here" /></p>
|
[
{
"answer_id": 74622596,
"author": "John Gordon",
"author_id": 494134,
"author_profile": "https://Stackoverflow.com/users/494134",
"pm_score": 0,
"selected": false,
"text": "if column %2 == 0 and row %2 == 1:\n ...\n\nelif row %2 ==0 and column %2 == 1:\n ...\n"
},
{
"answer_id": 74622719,
"author": "Techie_19",
"author_id": 17673025,
"author_profile": "https://Stackoverflow.com/users/17673025",
"pm_score": 0,
"selected": false,
"text": "x = int(input(\"Please enter your (x) first number 1-8::\"))\ny = int(input(\"Please enter your (y) second number 1-8::\"))\n\ncolumn = x\nrow = y\n\n\nif (column + row) %2 == 0:\n\n print(\"\")\n print(\"black\")\n\n\nelif (column + row) %2 == 1:\n print(\"\")\n print(\"white\")\n\nelse:\n print(\"Input valid number!!\")\n"
},
{
"answer_id": 74622765,
"author": "scr",
"author_id": 18781246,
"author_profile": "https://Stackoverflow.com/users/18781246",
"pm_score": 1,
"selected": false,
"text": "if x = int(input(\"Please enter your (x) first number 1-8::\"))\ny = int(input(\"Please enter your (y) second number 1-8::\"))\n\ncolor_picker = {0: \"Black\", 1: \"White\"}\n\nif not 0<x<9 or not 0<y<9:\n print(\"Input valid number!!\")\nelse:\n color\n print(color_picker[(x+y)%2])\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20353401/"
] |
74,622,579
|
<p>As the title explains, how could I create a function <code>func</code> (using numpy or math modules) to find the nearest member of the geometric sequence (2, 4, 8, 16, 32, 64, 128 . . . )?</p>
<p>For example, <code>func(3)</code> should yield 2, <code>func(20)</code> should yield 16, and <code>func(128)</code> should yield 128.</p>
<p>I cannot find any information on this problem. Most rounding problems discuss rounding to the nearest multiple of some number, rather than to the nearest member of a geometric sequence.</p>
|
[
{
"answer_id": 74622616,
"author": "JayPeerachai",
"author_id": 12135518,
"author_profile": "https://Stackoverflow.com/users/12135518",
"pm_score": 3,
"selected": true,
"text": "import numpy as np\ndef round_to_geometric(x):\n return int(2 ** np.floor(np.log2(x)))\n > print(round_to_geometric(3))\n> print(round_to_geometric(20))\n> print(round_to_geometric(128))\n\n2\n16\n128\n"
},
{
"answer_id": 74622661,
"author": "Alexander L. Hayes",
"author_id": 12439119,
"author_profile": "https://Stackoverflow.com/users/12439119",
"pm_score": 2,
"selected": false,
"text": "def myround(i):\n return 2 ** (len(bin(i)) - 3)\n >>> [myround(i) for i in (3, 4, 5, 6, 7, 8, 20, 25, 128)]\n[2, 4, 4, 4, 4, 8, 16, 16, 128]\n bin(x) >>> bin(20)\n'0b10100'\n bin(20) 2 ** 4 0b 1s len(bin(20)) - 3 = 4"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9983167/"
] |
74,622,582
|
<p>Suppose I have a data.table like this (imagine it has many columns like "a1, ..., a100, ..." and similarly "b1, ..., b100, ...")</p>
<pre><code>dt <- data.table(id = 1:5, a1 = runif(5), a2 = runif(5), b1 = runif(5), b2 = runif(5))
</code></pre>
<p>so that the output looks like this:</p>
<pre><code> id a1 a2 b1 b2
1: 1 0.94431156 0.34668771 0.54899478 0.91512664
2: 2 0.32730005 0.87924651 0.88777763 0.90167832
3: 3 0.07438915 0.53728539 0.21463741 0.11291512
4: 4 0.23025893 0.08528074 0.68454936 0.45441690
5: 5 0.86105462 0.49976703 0.07362091 0.08834252
</code></pre>
<p>I want to create new columns <code>c1, c2</code> such that effectively I have</p>
<pre><code>dt[, c('c1', 'c2') := .(a1*b1, a2*b2)]
</code></pre>
<p>with output</p>
<pre><code> id a1 a2 b1 b2 c1 c2
1: 1 0.94431156 0.34668771 0.54899478 0.91512664 0.51842212 0.31726316
2: 2 0.32730005 0.87924651 0.88777763 0.90167832 0.29056966 0.79279752
3: 3 0.07438915 0.53728539 0.21463741 0.11291512 0.01596669 0.06066765
4: 4 0.23025893 0.08528074 0.68454936 0.45441690 0.15762361 0.03875301
5: 5 0.86105462 0.49976703 0.07362091 0.08834252 0.06339162 0.04415068
</code></pre>
<p>How can this be achieved without the use of slow loops?</p>
|
[
{
"answer_id": 74623097,
"author": "Vons",
"author_id": 2303235,
"author_profile": "https://Stackoverflow.com/users/2303235",
"pm_score": 3,
"selected": true,
"text": "dt <- data.frame(id = 1:5, a1 = runif(5), a2 = runif(5), b1 = runif(5), b2 = runif(5))\na = dt[,2:3]\nb = dt[,4:5]\nc = a * b\nnames(c) = c(\"c1\", \"c2\")\ncbind(dt, c)\n\n id a1 a2 b1 b2 c1 c2\n1 1 0.082863389 0.7108292 0.8952547 0.4530363 0.074183837 0.32203140\n2 2 0.125423227 0.8957771 0.2231827 0.1042432 0.027992292 0.09337865\n3 3 0.278592590 0.9317453 0.7910442 0.3729406 0.220379066 0.34748565\n4 4 0.004518196 0.3890797 0.5323291 0.7997701 0.002405167 0.31117430\n5 5 0.784290484 0.5499781 0.7429104 0.8106772 0.582657582 0.44585471\n"
},
{
"answer_id": 74623391,
"author": "rral",
"author_id": 2857542,
"author_profile": "https://Stackoverflow.com/users/2857542",
"pm_score": 2,
"selected": false,
"text": "set.seed(10)\ndt <- data.frame(id = 1:5, \n a1 = runif(5),\n a2 = runif(5),\n a3 = runif(5),\n a4 = runif(5),\n a5 = runif(5),\n # ....\n b1 = runif(5), \n b2 = runif(5),\n b3 = runif(5),\n b4 = runif(5),\n b5 = runif(5)\n # ....\n)\n\nn <- 1:((ncol(x)-1)/2)\nind_a <- paste0(\"a\", n)\nind_b <- paste0(\"b\", n)\nind_c <- paste0(\"c\", n)\n\nproducto <- dt[ind_a]*dt[ind_b]\nnames(producto) <- ind_c\ndt <- cbind(dt, producto)\n"
},
{
"answer_id": 74625723,
"author": "ThomasIsCoding",
"author_id": 12158757,
"author_profile": "https://Stackoverflow.com/users/12158757",
"pm_score": 1,
"selected": false,
"text": "split.defult dt dt[, c(\n dt,\n lapply(\n split.default(.SD, paste0(\"c\", gsub(\"\\\\D+\", \"\", names(.SD)))),\n function(v) do.call(`*`, v)\n )\n),\n.SDcols = patterns(\"\\\\d$\")\n]\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10124146/"
] |
74,622,588
|
<p>I have a code to solve a Sudoku recursively and print out the one solution it founds.
But i would like to find the number of multiple solutions.
How would you modify the code that it finds all possible solutions and gives out the number of solutions?
Thank you! :)</p>
<p>code:</p>
<pre><code>
board = [
[7,8,0,4,0,0,1,2,0],
[6,0,0,0,7,5,0,0,9],
[0,0,0,6,0,1,0,7,8],
[0,0,7,0,4,0,2,6,0],
[0,0,1,0,5,0,9,3,0],
[9,0,4,0,6,0,0,0,5],
[0,7,0,3,0,0,0,1,2],
[1,2,0,0,0,7,4,0,0],
[0,4,9,2,0,6,0,0,7]
]
def solve(bo):
find = find_empty(bo)
if not find:
return True
else:
row, col = find
for num in range(1,10):
if valid(bo, num, (row, col)):
bo[row][col] = num
if solve(bo):
return True
bo[row][col] = 0
return False
def valid(bo, num, pos):
# Check row
for field in range(len(bo[0])):
if bo[pos[0]][field] == num and pos[1] != field:
return False
# Check column
for line in range(len(bo)):
if bo[line][pos[1]] == num and pos[0] != line:
return False
# Check box
box_x = pos[1] // 3
box_y = pos[0] // 3
for i in range(box_y*3, box_y*3 + 3):
for j in range(box_x * 3, box_x*3 + 3):
if bo[i][j] == num and (i,j) != pos:
return False
return True
def print_board(bo):
for i in range(len(bo)):
if i % 3 == 0 and i != 0:
print("- - - - - - - - - - - - - ")
for j in range(len(bo[0])):
if j % 3 == 0 and j != 0:
print(" | ", end="")
if j == 8:
print(bo[i][j])
else:
print(str(bo[i][j]) + " ", end="")
def find_empty(bo):
for i in range(len(bo)):
for j in range(len(bo[0])):
if bo[i][j] == 0:
return (i, j) # row, col
return None
if __name__ == "__main__":
print_board(board)
solve(board)
print("___________________")
print("")
print_board(board)
</code></pre>
<p>I already tried to change the return True term at the Solve(Bo) Function to return None/ deleted it(For both return Terms) that it continues…
Then the Algorithm continues and finds multiple solutions, but in the end fills out the correct numbers from the very last found solutions again into 0’s. This is the solution then printed out.</p>
|
[
{
"answer_id": 74623097,
"author": "Vons",
"author_id": 2303235,
"author_profile": "https://Stackoverflow.com/users/2303235",
"pm_score": 3,
"selected": true,
"text": "dt <- data.frame(id = 1:5, a1 = runif(5), a2 = runif(5), b1 = runif(5), b2 = runif(5))\na = dt[,2:3]\nb = dt[,4:5]\nc = a * b\nnames(c) = c(\"c1\", \"c2\")\ncbind(dt, c)\n\n id a1 a2 b1 b2 c1 c2\n1 1 0.082863389 0.7108292 0.8952547 0.4530363 0.074183837 0.32203140\n2 2 0.125423227 0.8957771 0.2231827 0.1042432 0.027992292 0.09337865\n3 3 0.278592590 0.9317453 0.7910442 0.3729406 0.220379066 0.34748565\n4 4 0.004518196 0.3890797 0.5323291 0.7997701 0.002405167 0.31117430\n5 5 0.784290484 0.5499781 0.7429104 0.8106772 0.582657582 0.44585471\n"
},
{
"answer_id": 74623391,
"author": "rral",
"author_id": 2857542,
"author_profile": "https://Stackoverflow.com/users/2857542",
"pm_score": 2,
"selected": false,
"text": "set.seed(10)\ndt <- data.frame(id = 1:5, \n a1 = runif(5),\n a2 = runif(5),\n a3 = runif(5),\n a4 = runif(5),\n a5 = runif(5),\n # ....\n b1 = runif(5), \n b2 = runif(5),\n b3 = runif(5),\n b4 = runif(5),\n b5 = runif(5)\n # ....\n)\n\nn <- 1:((ncol(x)-1)/2)\nind_a <- paste0(\"a\", n)\nind_b <- paste0(\"b\", n)\nind_c <- paste0(\"c\", n)\n\nproducto <- dt[ind_a]*dt[ind_b]\nnames(producto) <- ind_c\ndt <- cbind(dt, producto)\n"
},
{
"answer_id": 74625723,
"author": "ThomasIsCoding",
"author_id": 12158757,
"author_profile": "https://Stackoverflow.com/users/12158757",
"pm_score": 1,
"selected": false,
"text": "split.defult dt dt[, c(\n dt,\n lapply(\n split.default(.SD, paste0(\"c\", gsub(\"\\\\D+\", \"\", names(.SD)))),\n function(v) do.call(`*`, v)\n )\n),\n.SDcols = patterns(\"\\\\d$\")\n]\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20640049/"
] |
74,622,593
|
<p>So I have a program that takes in the currently logged in user and updates their profile image.
Initially I had a function based view, and a url matching pattern (the url for accessing profile, and thereby editing it is localhost:8000/profile)</p>
<pre><code>#views.py
@login_required
def profile(request):
if request.method=="POST":
u_form=UserUpdateForm(request.POST, instance=request.user)
p_form=ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)
if u_form.is_valid() and p_form.is_valid():
u_form.save()
p_form.save()
messages.success(request, "Your account has been updated!")
return redirect('profile')
else:
u_form=UserUpdateForm(instance=request.user)
p_form=ProfileUpdateForm(instance=request.user.profile)
context={'u_form':u_form, 'p_form':p_form}
return render(request, 'users/profile.html', context)
#following line in URLpatterns of urls.py
path('profile/', user_views.ProfileUpdateView.as_view(), name='profile'),
</code></pre>
<p>It worked fine. However when I tried changing it to a class based view as below, it started giving errors</p>
<pre><code>#views.py
class ProfileUpdateView(UpdateView):
model=Profile
fields=['image']
</code></pre>
<p>Case 1: I had this in urls.py URLpatterns</p>
<pre><code> path('profile/', user_views.ProfileUpdateView.as_view(), name='profile'),
</code></pre>
<p>It gave an error -</p>
<p>(<a href="https://i.stack.imgur.com/6mXfI.png" rel="nofollow noreferrer">https://i.stack.imgur.com/6mXfI.png</a>)](<a href="https://i.stack.imgur.com/6mXfI.png" rel="nofollow noreferrer">https://i.stack.imgur.com/6mXfI.png</a>)
I don't understand why this error popped up because there is no page specific ID, like profile/1, profile/2 - just profile/ because the user is automatically identified by who is currently logged in hence no need to pass in a separate parameter in the url</p>
<p>Case 2: after I added in pk parameter</p>
<pre><code>path('profile/<int:pk>/', user_views.ProfileUpdateView.as_view(), name='profile'),
</code></pre>
<p>This error pops up
(<a href="https://i.stack.imgur.com/Op9eQ.png" rel="nofollow noreferrer">https://i.stack.imgur.com/Op9eQ.png</a>)](<a href="https://i.stack.imgur.com/Op9eQ.png" rel="nofollow noreferrer">https://i.stack.imgur.com/Op9eQ.png</a>)</p>
<p>I have been stuck for a day now. I went through the Django documentation and MDN docs as well. Still can't figure out</p>
|
[
{
"answer_id": 74623097,
"author": "Vons",
"author_id": 2303235,
"author_profile": "https://Stackoverflow.com/users/2303235",
"pm_score": 3,
"selected": true,
"text": "dt <- data.frame(id = 1:5, a1 = runif(5), a2 = runif(5), b1 = runif(5), b2 = runif(5))\na = dt[,2:3]\nb = dt[,4:5]\nc = a * b\nnames(c) = c(\"c1\", \"c2\")\ncbind(dt, c)\n\n id a1 a2 b1 b2 c1 c2\n1 1 0.082863389 0.7108292 0.8952547 0.4530363 0.074183837 0.32203140\n2 2 0.125423227 0.8957771 0.2231827 0.1042432 0.027992292 0.09337865\n3 3 0.278592590 0.9317453 0.7910442 0.3729406 0.220379066 0.34748565\n4 4 0.004518196 0.3890797 0.5323291 0.7997701 0.002405167 0.31117430\n5 5 0.784290484 0.5499781 0.7429104 0.8106772 0.582657582 0.44585471\n"
},
{
"answer_id": 74623391,
"author": "rral",
"author_id": 2857542,
"author_profile": "https://Stackoverflow.com/users/2857542",
"pm_score": 2,
"selected": false,
"text": "set.seed(10)\ndt <- data.frame(id = 1:5, \n a1 = runif(5),\n a2 = runif(5),\n a3 = runif(5),\n a4 = runif(5),\n a5 = runif(5),\n # ....\n b1 = runif(5), \n b2 = runif(5),\n b3 = runif(5),\n b4 = runif(5),\n b5 = runif(5)\n # ....\n)\n\nn <- 1:((ncol(x)-1)/2)\nind_a <- paste0(\"a\", n)\nind_b <- paste0(\"b\", n)\nind_c <- paste0(\"c\", n)\n\nproducto <- dt[ind_a]*dt[ind_b]\nnames(producto) <- ind_c\ndt <- cbind(dt, producto)\n"
},
{
"answer_id": 74625723,
"author": "ThomasIsCoding",
"author_id": 12158757,
"author_profile": "https://Stackoverflow.com/users/12158757",
"pm_score": 1,
"selected": false,
"text": "split.defult dt dt[, c(\n dt,\n lapply(\n split.default(.SD, paste0(\"c\", gsub(\"\\\\D+\", \"\", names(.SD)))),\n function(v) do.call(`*`, v)\n )\n),\n.SDcols = patterns(\"\\\\d$\")\n]\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14972173/"
] |
74,622,620
|
<p>How to let the query result be ordered by the exact order of passed items in the <code>WHERE</code> clause?</p>
<p>For example, using this query:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT id, name FROM my_table
WHERE id in (1,3,5,2,4,6)
ORDER BY id
</code></pre>
<p>Result:</p>
<pre><code>id | name
---------
1 | a
2 | b
3 | c
4 | d
5 | e
6 | f
</code></pre>
<p>What I expected:</p>
<pre><code>id | name
---------
1 | a
3 | c
5 | e
2 | b
4 | d
6 | f
</code></pre>
<p>I noticed that there is a <code>FIELD()</code> function in MySQL. Is there an equivalent function in PostgreSQL?</p>
|
[
{
"answer_id": 74622671,
"author": "Learn Hadoop",
"author_id": 8726488,
"author_profile": "https://Stackoverflow.com/users/8726488",
"pm_score": 1,
"selected": false,
"text": "id|name|\n--+----+\n 1|a |\n 3|c |\n 5|e |\n 2|b |\n 4|d |\n 6|f |\n select id, name\nfrom my_table mt\nwhere id in (1,3,5,2,4,6)\norder by array_position(array[1,3,5,2,4,6], mt.id);\n"
},
{
"answer_id": 74622729,
"author": "Erwin Brandstetter",
"author_id": 939860,
"author_profile": "https://Stackoverflow.com/users/939860",
"pm_score": 3,
"selected": true,
"text": "WITH ORDINALITY SELECT id, t.name\nFROM unnest ('{1,3,5,2,4,6}'::int[]) WITH ORDINALITY u(id, ord)\nJOIN my_table t USING (id)\nORDER BY u.ord;\n IN"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9823251/"
] |
74,622,626
|
<p>my entire code is below, I do not have a main.js file yet. Just trying to get the dropdown menu to work but regardless of what I press the dropdown menu will not drop.</p>
<p>Here is my code:</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bootstrap</title>
<link rel="stylesheet" href="/node_modules/bootstrap/dist/css/bootstrap.min.css">
</head>
<body>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</li>
<script src="/node_modules/bootstrap/dist/js/bootstrap.bundle.js"></script>
</body>
</html>
</code></pre>
<p>Thanks!</p>
|
[
{
"answer_id": 74622702,
"author": "Heet Vakharia",
"author_id": 13262683,
"author_profile": "https://Stackoverflow.com/users/13262683",
"pm_score": 2,
"selected": true,
"text": "data-bs-toggle=\"dropdown\" <!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Bootstrap</title>\n <link href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65\" crossorigin=\"anonymous\">\n \n</head>\n<body>\n <li class=\"nav-item dropdown\">\n <a class=\"nav-link dropdown-toggle\" href=\"#\" id=\"navbarDropdown\" role=\"button\" data-bs-toggle=\"dropdown\" aria-haspopup=\"true\" aria-expanded=\"false\">\n Dropdown\n </a>\n <div class=\"dropdown-menu\" aria-labelledby=\"navbarDropdown\">\n <a class=\"dropdown-item\" href=\"#\">Action</a>\n <a class=\"dropdown-item\" href=\"#\">Another action</a>\n <div class=\"dropdown-divider\"></div>\n <a class=\"dropdown-item\" href=\"#\">Something else here</a>\n </div>\n </li>\n <script src=\"https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js\" integrity=\"sha384-oBqDVmMz9ATKxIep9tiCxS/Z9fNfEXiDAYTujMAeBAsjFuCZSmKbSSUnQlmh/jp3\" crossorigin=\"anonymous\"></script>\n<script src=\"https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.min.js\" integrity=\"sha384-cuYeSxntonz0PPNlHhBs68uyIAVpIIOZZ5JqeqvYYIcEL727kskC66kF92t6Xl2V\" crossorigin=\"anonymous\"></script></script>\n</body>\n</html>\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14331539/"
] |
74,622,631
|
<p>Write a function called find that will take a list of numbers, my_list, along with one other number, key. Have it search the list for the value contained in key. Each time your function finds the key value, print the array position of the key. You will need to juggle three variables, one for the list, one for the key, and one for the position of where you are in the list.</p>
<p>Copy/paste this code to test it:</p>
<pre><code>my_list = [36, 31, 79, 96, 36, 91, 77, 33, 19, 3, 34, 12, 70, 12, 54, 98, 86, 11, 17, 17]
find(my_list, 12)
find(my_list, 91)
find(my_list, 80)
</code></pre>
<p>check for this output:</p>
<pre class="lang-none prettyprint-override"><code>Found 12 at position 11
Found 12 at position 13
Found 91 at position 5
</code></pre>
<p>Use a for loop with an index variable and a range. Inside the loop use an if statement. The function can be written in about four lines of code.</p>
<p>I tried this:</p>
<pre><code>def find(my_list, key):
index = 0
for element in my_list:
if key == element:
print(index)
index += 1
my_list = [36, 31, 79, 96, 36, 91, 77, 33, 19, 3, 34, 12, 70, 12, 54, 98, 86, 11, 17, 17]
find(my_list, 5)
</code></pre>
<p>But nothing really happened, no error, no result.</p>
<p>I've been struggling with this problem for while now, some help is really appreciated!</p>
|
[
{
"answer_id": 74622702,
"author": "Heet Vakharia",
"author_id": 13262683,
"author_profile": "https://Stackoverflow.com/users/13262683",
"pm_score": 2,
"selected": true,
"text": "data-bs-toggle=\"dropdown\" <!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Bootstrap</title>\n <link href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65\" crossorigin=\"anonymous\">\n \n</head>\n<body>\n <li class=\"nav-item dropdown\">\n <a class=\"nav-link dropdown-toggle\" href=\"#\" id=\"navbarDropdown\" role=\"button\" data-bs-toggle=\"dropdown\" aria-haspopup=\"true\" aria-expanded=\"false\">\n Dropdown\n </a>\n <div class=\"dropdown-menu\" aria-labelledby=\"navbarDropdown\">\n <a class=\"dropdown-item\" href=\"#\">Action</a>\n <a class=\"dropdown-item\" href=\"#\">Another action</a>\n <div class=\"dropdown-divider\"></div>\n <a class=\"dropdown-item\" href=\"#\">Something else here</a>\n </div>\n </li>\n <script src=\"https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js\" integrity=\"sha384-oBqDVmMz9ATKxIep9tiCxS/Z9fNfEXiDAYTujMAeBAsjFuCZSmKbSSUnQlmh/jp3\" crossorigin=\"anonymous\"></script>\n<script src=\"https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.min.js\" integrity=\"sha384-cuYeSxntonz0PPNlHhBs68uyIAVpIIOZZ5JqeqvYYIcEL727kskC66kF92t6Xl2V\" crossorigin=\"anonymous\"></script></script>\n</body>\n</html>\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20640357/"
] |
74,622,645
|
<p>In my CPP system whenever I generate a random number using rand() I always get a value between 0-32k while in some online videos and codes it is generating a value between 0-INT_MAX. I know it is dependent on RAND_MAX. So it there some way to change this value such that generated random number are of the range 0-INT_MAX
Thanks in advance for the help :)</p>
<pre><code>#include<bits/stdc++.h>
using namespace std;
int main(){
srand(time(NULL));
for(int i=1;i<=10;i++){
cout << rand() << endl;
}
}
</code></pre>
<p>I used this code and the random number generated are
5594
27457
5076
5621
31096
14572
1415
25601
3110
22442</p>
<p>While the same code on online compiler gives
928364519
654230200
161024542
1580424748
35757021
1053491036
1968560769
1149314029
524600584
2043083516</p>
|
[
{
"answer_id": 74622681,
"author": "Mark Adler",
"author_id": 1180620,
"author_profile": "https://Stackoverflow.com/users/1180620",
"pm_score": 2,
"selected": false,
"text": "rand() rand() rand() random() arc4random()"
},
{
"answer_id": 74636953,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 1,
"selected": true,
"text": "rand() INT_MAX RAND_MAX > INT_MAX RAND_MAX rand()"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19610102/"
] |
74,622,653
|
<p>In other words, does PowerShell's <code>Expand-Archive</code> have an equivalent to <code>unzip</code>'s <code>-j</code> command-line argument? If not, are there alternatives <em>on Windows</em>?</p>
<p>I have tried <code>Expand-Archive -Path thing.zip -DestinationPath "somepath" -Force</code>, which just puts the directory structure in another folder called <code>somepath</code>.</p>
|
[
{
"answer_id": 74622816,
"author": "Santiago Squarzon",
"author_id": 15339544,
"author_profile": "https://Stackoverflow.com/users/15339544",
"pm_score": 1,
"selected": false,
"text": "-DestinationPath using namespace System.IO\nusing namespace System.IO.Compression\n\nfunction Expand-ZipArchive {\n [CmdletBinding(DefaultParameterSetName = 'Path')]\n param(\n [Parameter(ParameterSetName = 'Path', Mandatory, Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)]\n [string] $Path,\n\n [Parameter(ParameterSetName = 'LiteralPath', Mandatory, ValueFromPipelineByPropertyName)]\n [Alias('PSPath')]\n [string] $LiteralPath,\n\n [Parameter()]\n [string] $DestinationPath\n )\n\n begin {\n Add-Type -AssemblyName System.IO.Compression\n $DestinationPath = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($DestinationPath)\n }\n process {\n $arguments = switch($PSCmdlet.ParameterSetName) {\n Path { $Path, $false, $false }\n LiteralPath { $LiteralPath, $false, $true }\n }\n\n $null = [Directory]::CreateDirectory($DestinationPath)\n\n foreach($item in $ExecutionContext.InvokeProvider.Item.Get.Invoke($arguments)) {\n try {\n $fileStream = $item.Open([FileMode]::Open)\n $zipArchive = [ZipArchive]::new($fileStream, [ZipArchiveMode]::Read)\n\n foreach($entry in $zipArchive.Entries) {\n try {\n # if it's a folder, exclude it\n if(-not $entry.Name) {\n continue\n }\n\n $path = [Path]::Combine($DestinationPath, $entry.Name)\n # will throw if a file with same name exists, intended\n # error handling should be implemented in `catch` block\n $fs = [FileStream]::new($path, [FileMode]::CreateNew)\n $wrappedStream = $entry.Open()\n $wrappedStream.CopyTo($fs)\n }\n catch {\n $PSCmdlet.WriteError($_)\n }\n finally {\n $fs, $wrappedStream | ForEach-Object Dispose\n }\n }\n }\n catch {\n $PSCmdlet.WriteError($_)\n }\n finally {\n $zipArchive, $fileStream | ForEach-Object Dispose\n }\n }\n }\n}\n\nExpand-ZipArchive .\\myZip.zip\n"
},
{
"answer_id": 74634278,
"author": "zett42",
"author_id": 7571258,
"author_profile": "https://Stackoverflow.com/users/7571258",
"pm_score": 0,
"selected": false,
"text": "$archiveName = 'test.zip'\n$destination = 'test'\n\n# Create temp path as a sub directory of actual destination path, so the files don't \n# need to be moved (potentially) across drives.\n$destinationTemp = Join-Path $destination \"~$((New-Guid).ToString('n'))\"\n\n# Create temp directory\n$null = New-Item $destinationTemp -ItemType Directory\n\n# Extract to temp dir\nExpand-Archive $archiveName -DestinationPath $destinationTemp\n\n# Move files from temp dir to actual destination, discarding directory structure\nGet-ChildItem $destinationTemp -File -Recurse | Move-Item -Destination $destination\n\n# Remove temp dir\nRemove-Item $destinationTemp -Recurse -Force\n -PassThru Expand-Archive $archiveName = 'test.zip'\n$destination = 'test'\n\n# Create temp path as a sub directory of actual destination path, so the files don't \n# need to be moved (potentially) across drives.\n$destinationTemp = Join-Path $destination \"~$((New-Guid).ToString('n'))\"\n\n# Create temp directory\n$null = New-Item $destinationTemp -ItemType Directory\n\n# Expand to temp dir and move to final destination, discarding directory structure\nExpand-Archive $archiveName -DestinationPath $destinationTemp -PassThru | \n Where-Object -not PSIsContainer | Move-Item -Destination $destination\n\n# Remove temp dir\nRemove-Item $destinationTemp -Recurse -Force\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1654223/"
] |
74,622,660
|
<p>I am trying to rearrange the rows in a csv based on the key given in 5th column of my data.
My data looks like this (<strong>test.csv</strong>):</p>
<pre><code>Col A,Col B,Col C,Col D,Col E
A,Data 1,Category 1,Name 1,C
B,Data 2,Category 2,Name 2,C
C,Data 3,Category 3,Name 3,C
D,Data 4,Category 4,Name 4,C
E,Data 5,Category 5,Name 5,C
F,Data 6,Category 6,Name 6,C
</code></pre>
<p>I am trying to rearrange it so that the row containing the key value in first column is at top (in this case the key value is <strong>C</strong>)</p>
<p>Desired output :</p>
<pre><code>Col A,Col B,Col C,Col D,Col E
C,Data 3,Category 3,Name 3,C
A,Data 1,Category 1,Name 1,C
B,Data 2,Category 2,Name 2,C
D,Data 4,Category 4,Name 4,C
E,Data 5,Category 5,Name 5,C
F,Data 6,Category 6,Name 6,C
</code></pre>
<p>I have written the below code and also getting the desired result doing so i am generating two temporary files , just wondering if there is a better solution :</p>
<pre><code>sed 1d test.csv > input.csv
key=`awk -F"," -v 'OFS=,' '{ print $5}' input.csv | uniq`
awk -F"," -v 'OFS=,' '{if($1 == "'$key'") print}' input.csv > temp.csv
cat temp.csv input.csv > temp2.csv
awk '!seen[$0]++' temp2.csv > output.csv
sed -i '1iCol A,Col B,Col C,Col D,Col E' output.csv
</code></pre>
<p>Please help !</p>
|
[
{
"answer_id": 74625302,
"author": "HatLess",
"author_id": 16372109,
"author_profile": "https://Stackoverflow.com/users/16372109",
"pm_score": 1,
"selected": false,
"text": "sed $ sed -Ez 's/^([^\\n]*\\n)(.*\\n)(([[:alpha:]])[^\\n]*\\4\\n)/\\1\\3\\2/woutput.csv' input_file\n$ cat output.csv\nCol A,Col B,Col C,Col D,Col E\nC,Data 3,Category 3,Name 3,C\nA,Data 1,Category 1,Name 1,C\nB,Data 2,Category 2,Name 2,C\nD,Data 4,Category 4,Name 4,C\nE,Data 5,Category 5,Name 5,C\nF,Data 6,Category 6,Name 6,C\n"
},
{
"answer_id": 74625305,
"author": "Fravadona",
"author_id": 3387716,
"author_profile": "https://Stackoverflow.com/users/3387716",
"pm_score": 2,
"selected": true,
"text": "awk -F ',' '\n !seen[$0]++ {\n if ( $1 == $5 || NR == 1 )\n print\n else\n arr[++n] = $0\n }\n END { for (i = 1; i <= n; i++) print arr[i] }\n' input.csv > output.csv\n Col A,Col B,Col C,Col D,Col E\nC,Data 3,Category 3,Name 3,C\nA,Data 1,Category 1,Name 1,C\nB,Data 2,Category 2,Name 2,C\nD,Data 4,Category 4,Name 4,C\nE,Data 5,Category 5,Name 5,C\nF,Data 6,Category 6,Name 6,C\n"
},
{
"answer_id": 74635886,
"author": "Ed Morton",
"author_id": 1745001,
"author_profile": "https://Stackoverflow.com/users/1745001",
"pm_score": 2,
"selected": false,
"text": "$ cat tst.awk\nBEGIN { FS=\",\" }\n(NR == 1) || f {\n print\n next\n}\n$1 == $5 {\n print $0 buf\n f = 1\n}\n{ buf = buf ORS $0 }\n $ awk -f tst.awk test.csv\nCol A,Col B,Col C,Col D,Col E\nC,Data 3,Category 3,Name 3,C\nA,Data 1,Category 1,Name 1,C\nB,Data 2,Category 2,Name 2,C\nD,Data 4,Category 4,Name 4,C\nE,Data 5,Category 5,Name 5,C\nF,Data 6,Category 6,Name 6,C\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8134290/"
] |
74,622,662
|
<p>I exported many reports from my system in xls in the same specific format and need to change them to another format:</p>
<p>Basically for every item description I need to insert the corresponding Account series it is in column J using pandas.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Data</th>
<th>CP</th>
<th>N0</th>
<th>N1</th>
<th>ITEM</th>
<th>DEBIT</th>
<th>CREDIT</th>
<th>NET</th>
<th>D/C</th>
</tr>
</thead>
<tbody>
<tr>
<td>Account: (663)</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>31/10/2022</td>
<td>595</td>
<td></td>
<td>12</td>
<td>ITEM DESCRIPTION 4859</td>
<td>5.564,40</td>
<td></td>
<td>59.786,28</td>
<td>C</td>
</tr>
<tr>
<td>Account: (664)</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>31/10/2022</td>
<td>596</td>
<td></td>
<td>12</td>
<td>ITEM DESCRIPTION 234243</td>
<td>3.475,34</td>
<td></td>
<td>15.492,41</td>
<td>D</td>
</tr>
<tr>
<td>31/10/2022</td>
<td>103</td>
<td></td>
<td>14</td>
<td>ITEM DESCRIPTION 456456</td>
<td></td>
<td>0,01</td>
<td>15.492,40</td>
<td>C</td>
</tr>
<tr>
<td>Account: (678)</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>31/10/2022</td>
<td>597</td>
<td></td>
<td>12</td>
<td>ITEM DESCRIPTION 2332</td>
<td>6.555,27</td>
<td></td>
<td>71.503,39</td>
<td>C</td>
</tr>
<tr>
<td>Account: (689)</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>31/10/2022</td>
<td>608</td>
<td></td>
<td>13</td>
<td>ITEM DESCRIPTION 66546</td>
<td>266.516,00</td>
<td></td>
<td>504.013,87</td>
<td>D</td>
</tr>
<tr>
<td>31/10/2022</td>
<td>608</td>
<td></td>
<td>13</td>
<td>ITEM DESCRIPTION 57567</td>
<td>5.578,67</td>
<td></td>
<td>7.656.192,54</td>
<td>D</td>
</tr>
<tr>
<td>Account: (500)</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>31/10/2022</td>
<td>608</td>
<td></td>
<td>13</td>
<td>ITEM DESCRIPTION 345345</td>
<td>54.405,00</td>
<td></td>
<td>645.175,00</td>
<td>D</td>
</tr>
</tbody>
</table>
</div>
<p>I tried to write a script but couldn't fetch a logic to fill the column. Could someone help me?</p>
<p>Desired format:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Data</th>
<th>CP</th>
<th>N0</th>
<th>N1</th>
<th>ITEM</th>
<th>DEBIT</th>
<th>CREDIT</th>
<th>NET</th>
<th>D/C</th>
<th>Account</th>
</tr>
</thead>
<tbody>
<tr>
<td>Account: (663)</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>31/10/2022</td>
<td>595</td>
<td></td>
<td>12</td>
<td>ITEM DESCRIPTION 4859</td>
<td>5.564,40</td>
<td></td>
<td>59.786,28</td>
<td>C</td>
<td>Account: (663)</td>
</tr>
<tr>
<td>Account: (664)</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>31/10/2022</td>
<td>596</td>
<td></td>
<td>12</td>
<td>ITEM DESCRIPTION 234243</td>
<td>3.475,34</td>
<td></td>
<td>15.492,41</td>
<td>D</td>
<td>Account: (664)</td>
</tr>
<tr>
<td>31/10/2022</td>
<td>103</td>
<td></td>
<td>14</td>
<td>ITEM DESCRIPTION 456456</td>
<td></td>
<td>0,01</td>
<td>15.492,40</td>
<td>C</td>
<td>Account: (664)</td>
</tr>
<tr>
<td>Account: (678)</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>31/10/2022</td>
<td>597</td>
<td></td>
<td>12</td>
<td>ITEM DESCRIPTION 2332</td>
<td>6.555,27</td>
<td></td>
<td>71.503,39</td>
<td>C</td>
<td>Account: (678)</td>
</tr>
<tr>
<td>Account: (689)</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>31/10/2022</td>
<td>608</td>
<td></td>
<td>13</td>
<td>ITEM DESCRIPTION 66546</td>
<td>266.516,00</td>
<td></td>
<td>504.013,87</td>
<td>D</td>
<td>Account: (689)</td>
</tr>
<tr>
<td>31/10/2022</td>
<td>608</td>
<td></td>
<td>13</td>
<td>ITEM DESCRIPTION 57567</td>
<td>5.578,67</td>
<td></td>
<td>7.656.192,54</td>
<td>D</td>
<td>Account: (689)</td>
</tr>
<tr>
<td>Account: (500)</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>31/10/2022</td>
<td>608</td>
<td></td>
<td>13</td>
<td>ITEM DESCRIPTION 345345</td>
<td>54.405,00</td>
<td></td>
<td>645.175,00</td>
<td>D</td>
<td>Account: (500)</td>
</tr>
</tbody>
</table>
</div>
|
[
{
"answer_id": 74625302,
"author": "HatLess",
"author_id": 16372109,
"author_profile": "https://Stackoverflow.com/users/16372109",
"pm_score": 1,
"selected": false,
"text": "sed $ sed -Ez 's/^([^\\n]*\\n)(.*\\n)(([[:alpha:]])[^\\n]*\\4\\n)/\\1\\3\\2/woutput.csv' input_file\n$ cat output.csv\nCol A,Col B,Col C,Col D,Col E\nC,Data 3,Category 3,Name 3,C\nA,Data 1,Category 1,Name 1,C\nB,Data 2,Category 2,Name 2,C\nD,Data 4,Category 4,Name 4,C\nE,Data 5,Category 5,Name 5,C\nF,Data 6,Category 6,Name 6,C\n"
},
{
"answer_id": 74625305,
"author": "Fravadona",
"author_id": 3387716,
"author_profile": "https://Stackoverflow.com/users/3387716",
"pm_score": 2,
"selected": true,
"text": "awk -F ',' '\n !seen[$0]++ {\n if ( $1 == $5 || NR == 1 )\n print\n else\n arr[++n] = $0\n }\n END { for (i = 1; i <= n; i++) print arr[i] }\n' input.csv > output.csv\n Col A,Col B,Col C,Col D,Col E\nC,Data 3,Category 3,Name 3,C\nA,Data 1,Category 1,Name 1,C\nB,Data 2,Category 2,Name 2,C\nD,Data 4,Category 4,Name 4,C\nE,Data 5,Category 5,Name 5,C\nF,Data 6,Category 6,Name 6,C\n"
},
{
"answer_id": 74635886,
"author": "Ed Morton",
"author_id": 1745001,
"author_profile": "https://Stackoverflow.com/users/1745001",
"pm_score": 2,
"selected": false,
"text": "$ cat tst.awk\nBEGIN { FS=\",\" }\n(NR == 1) || f {\n print\n next\n}\n$1 == $5 {\n print $0 buf\n f = 1\n}\n{ buf = buf ORS $0 }\n $ awk -f tst.awk test.csv\nCol A,Col B,Col C,Col D,Col E\nC,Data 3,Category 3,Name 3,C\nA,Data 1,Category 1,Name 1,C\nB,Data 2,Category 2,Name 2,C\nD,Data 4,Category 4,Name 4,C\nE,Data 5,Category 5,Name 5,C\nF,Data 6,Category 6,Name 6,C\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20640529/"
] |
74,622,675
|
<p>Here the code that I create to replace some value at txt file.
I want to replace the value 0 with 3 for lines which do not start with "#".</p>
<pre><code>using (StreamWriter sr = new StreamWriter(@"D:\Testing\Ticket_post_test.txt"))
foreach(string line in File.ReadLines(@"D:\Testing\Ticket_post.txt"))
{
string[] getFromLine = line.Split(' ');
if (getFromLine[0].Equals("#") == false)
{
if (getFromLine[10].Equals("0") == true) ;
(getFromLine[10]).Replace("0", "3");
}
sr.WriteLine(line);
}
</code></pre>
<p>Stuck at how to replace the 0 by 3 at line split[10] and write to a new txt file.
The txt file show below</p>
<pre>
*#* start time = 2021-12-03-15-14-55
*#* end time = 2021-12-03-15-15-41
*#* name = SYSTEM
bot 10 pad 11 d 4 e 6 t #0 **0** 2021-12-03-15-14-55 # - 2021-12-03-15-15-41
bot 11 pad 12 d 5 e 7 t #0 **0** 2021-12-03-15-14-55 # - 2021-12-03-15-15-41
bot 12 pad 13 d 6 e 8 t #0 **1** 2021-12-03-15-14-55 # - 2021-12-03-15-15-41
</pre>
<p>and more</p>
|
[
{
"answer_id": 74622803,
"author": "ProgrammingLlama",
"author_id": 3181933,
"author_profile": "https://Stackoverflow.com/users/3181933",
"pm_score": 3,
"selected": true,
"text": ".Split .Substring .Replace WriteLine line getFromLine[10] .Replace using (StreamWriter sr = new StreamWriter(@\"D:\\Testing\\Ticket_post_test.txt\"))\n{\n foreach (string line in File.ReadLines(@\"D:\\Testing\\Ticket_post.txt\"))\n {\n string[] getFromLine = line.Split(' ');\n if (getFromLine[0] != \"#\" && getFromLine[10] == \"0\")\n {\n getFromLine[10] = \"3\";\n }\n sr.WriteLine(String.Join(\" \", getFromLine));\n }\n}\n using (StreamWriter sr = new StreamWriter(@\"D:\\Testing\\Ticket_post_test.txt\"))\n{\n foreach (string line in File.ReadLines(@\"D:\\Testing\\Ticket_post.txt\"))\n {\n string[] getFromLine = line.Split(' ');\n if (getFromLine[0] != \"#\" && getFromLine[10] == \"0\")\n {\n getFromLine[10] = \"3\";\n sr.WriteLine(String.Join(\" \", getFromLine));\n }\n else\n {\n sr.Write(line);\n }\n }\n}\n if (getFromLine.Length >= 11 && getFromLine[0] != \"#\" && getFromLine[10] == \"0\") IndexOutOfRangeException"
},
{
"answer_id": 74624660,
"author": "protoproto",
"author_id": 2311619,
"author_profile": "https://Stackoverflow.com/users/2311619",
"pm_score": 0,
"selected": false,
"text": "using System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Text.RegularExpressions;\n\nnamespace Stack5\n{\n /// <summary>\n /// Interaction logic for MainWindow.xaml\n /// </summary>\n public partial class MainWindow\n {\n public MainWindow()\n {\n InitializeComponent();\n ReadAndWriteTextFile();\n }\n\n private static void ReadAndWriteTextFile()\n {\n // Read text file\n // (?<string> ...) = name it with \"string\" name\n // ^(?!#) = select line not begin with \"#\"\n // (\\S+\\s){10} = bypass 10 group strings include a visible characters (\\S) and a space (\\s)\n string pattern = @\"(?<one>^(?!#)(\\S+\\s){10})0(?<two>.+)\";\n string substitution = @\"${one}3${two}\";\n Regex regex = new Regex(pattern);\n // Change the path to your path\n List<string> lines = File.ReadLines(@\".\\settings.txt\").ToList();\n for (int i = 0; i < lines.Count(); i++)\n {\n // Check its value\n Debug.WriteLine(lines[i]);\n var match = Regex.Match(lines[i], pattern);\n if (match.Success)\n {\n string r = regex.Replace(lines[i], substitution);\n // Check its value\n Debug.WriteLine(\"Change the line {0} to: {1}\",i+1,r);\n lines[i] = r;\n }\n\n }\n // Write text file\n File.WriteAllLines(@\".\\settings.txt\",lines);\n }\n }\n}\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16851124/"
] |
74,622,676
|
<p>I want to make sure my executable has debug info, trying the linux equivalent doesn't help:</p>
<pre class="lang-bash prettyprint-override"><code>$ file ./my_lovely_program
./my_lovely_program: Mach-O 64-bit executable arm64 # with debug info? without?
</code></pre>
<p><strong>EDIT</strong> (from the answer of <a href="https://stackoverflow.com/users/15949328/haggbart">@haggbart</a>)</p>
<p>It seems that my executable has <em>no</em> debug info (?)</p>
<pre><code>$ dwarfdump --debug-info ./compi
./compi: file format Mach-O arm64
.debug_info contents: # <--- empty, right?
</code></pre>
<p>And with the other option, I'm not sure:</p>
<pre class="lang-bash prettyprint-override"><code>$ otool -hv ./compi
./compi:
Mach header
magic cputype cpusubtype caps filetype ncmds sizeofcmds flags
MH_MAGIC_64 ARM64 ALL 0x00 EXECUTE 19 1816 NOUNDEFS DYLDLINK TWOLEVEL WEAK_DEFINES BINDS_TO_WEAK PIE
</code></pre>
<p>This is <em>very weird</em> because I can <em>perfectly</em> debug it with lldb</p>
<pre><code>(lldb) b main
Breakpoint 1: where = compi`main + 24 at main.cpp:50:9, address = 0x0000000100018650
(lldb) run
Process 6067 launched: '/Users/oren/Downloads/compi' (arm64)
Process 6067 stopped
* thread #1, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1
frame #0: 0x0000000100018650 compi`main(argc=3, argv=0x000000016fdff7b8) at main.cpp:50:9
47 /*****************/
48 int main(int argc, char **argv)
49 {
-> 50 if (argc == 3)
51 {
52 const char *input = argv[1];
53 const char *output = argv[2];
Target 0: (compi) stopped.
</code></pre>
|
[
{
"answer_id": 74664794,
"author": "haggbart",
"author_id": 15949328,
"author_profile": "https://Stackoverflow.com/users/15949328",
"pm_score": 1,
"selected": false,
"text": "otool -hv /path/to/executable\n dwarfdump --debug-info ./my_lovely_program\n nm /path/to/executable\n file /path/to/executable\n"
},
{
"answer_id": 74665607,
"author": "Philippe",
"author_id": 2125671,
"author_profile": "https://Stackoverflow.com/users/2125671",
"pm_score": 0,
"selected": false,
"text": "dsymutil -s ./my_lovely_propgram | grep N_OSO\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3357352/"
] |
74,622,697
|
<p>I have the following code on which I perform a custom type of null checking of my parameters. I do it that way to avoid writing 3 separate if statements (adds cyclomatic complexity) and in my opinion it just looks cleaner. However, VS2022, on NET6 refuses to take away the null warning on the previously validated parameters.</p>
<p>Here's an example: I perform the custom null validation on all params and just do one manually (logger). Only the one done manually gets to be clean with no warnings. Any ideas how to make it work with custom null validations?</p>
<p><a href="https://i.stack.imgur.com/x0ddI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/x0ddI.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74625611,
"author": "Guru Stron",
"author_id": 2501279,
"author_profile": "https://Stackoverflow.com/users/2501279",
"pm_score": 3,
"selected": true,
"text": "ArgumentNullException.ThrowIfNull ArgumentNullException object x = null;\n// Throws ArgumentNullException with message \n// Value cannot be null. (Parameter 'x')\nArgumentNullException.ThrowIfNull(x); \n class Guard\n{\n public static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression(nameof(argument))] string? paramName = null)\n {\n if (argument != null)\n return;\n throw new ArgumentException($\"{paramName} can't be null\");\n }\n\n public static void ThrowIfNull<T>([NotNull] T? argument, [CallerArgumentExpression(nameof(argument))] string? paramName = null) where T:struct\n {\n if (argument != null)\n return;\n throw new ArgumentException($\"{paramName} can't be null\");\n }\n}\n"
},
{
"answer_id": 74639767,
"author": "radoslawik",
"author_id": 12473121,
"author_profile": "https://Stackoverflow.com/users/12473121",
"pm_score": 1,
"selected": false,
"text": "#nullable disable"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8139198/"
] |
74,622,727
|
<p>I'm trying to join or call only one document from multiple documents that can be repeated, all this for a unique identifier, in this case <code>code</code>, which is a numerical value.</p>
<pre><code>[
{
"_id": "6386b0e114fe6aee844af06e",
"transfer": {
"code": 2,
"author": {
"created_at": "2022-11-30T01:29:43.308Z",
"created_by": "userId",
"observation": "It is a long established fact that a reader will be distracted"
},
"output": {
"type": "Transfer out",
"quantity": 3,
"to": {
"warehouse": "6376d84a4587772c3b2d7175",
"warehouse_location": "637d6e218006a7e9609aaf2f",
"expiration_date": "2024-01-03",
"production_lot": "LOT0544522",
"product": "6366a7d99795c333b24f0981"
}
},
"entry": {
"type": "Transfer in",
"quantity": 3,
"from": {
"warehouse": "6376d6c5716fea2e60c491c6",
"warehouse_location": "637d6e1b8006a7e9609aaf2e",
"expiration_date": "2024-01-03",
"production_lot": "LOT0544522",
"product": "6366a7d99795c333b24f0981"
}
}
}
},
{
"_id": "6386b13e14fe6aee844af06f",
"transfer": {
"code": 2,
"author": {
"created_at": "2022-11-30T01:29:43.308Z",
"created_by": "userId",
"observation": "It is a long established fact that a reader will be distracted"
},
"output": {
"type": "Transfer out",
"quantity": 3,
"to": {
"warehouse": "6376d84a4587772c3b2d7175",
"warehouse_location": "637d6e218006a7e9609aaf2f",
"expiration_date": "2024-01-03",
"production_lot": "LOT0544522",
"product": "6366a7d99795c333b24f0981"
}
},
"entry": {
"type": "Transfer in",
"quantity": 3,
"from": {
"warehouse": "6376d6c5716fea2e60c491c6",
"warehouse_location": "637d6e1b8006a7e9609aaf2e",
"expiration_date": "2024-01-03",
"production_lot": "LOT0544522",
"product": "6366a7d99795c333b24f0981"
}
}
}
},
{
"_id": "6386b0e114fe6aee844af06e",
"transfer": {
"code": 1,
"author": {
"created_at": "2022-11-30T01:27:52.003Z",
"created_by": "userId",
"observation": "It is a long established fact that a reader will be distracted"
},
"output": {
"type": "Transfer out",
"quantity": 1,
"to": {
"warehouse": "6376d84a4587772c3b2d7175",
"warehouse_location": "637d6e218006a7e9609aaf2f",
"expiration_date": "2024-01-03",
"production_lot": "LOT0544522",
"product": "6366a7d99795c333b24f0981"
}
},
"entry": {
"type": "Transfer in",
"quantity": 1,
"from": {
"warehouse": "6376d6c5716fea2e60c491c6",
"warehouse_location": "637d6e1b8006a7e9609aaf2e",
"expiration_date": "2024-01-03",
"production_lot": "LOT0544522",
"product": "6366a7d99795c333b24f0981"
}
}
}
},
{
"_id": "6386b13e14fe6aee844af06f",
"transfer": {
"code": 1,
"author": {
"created_at": "2022-11-30T01:27:52.003Z",
"created_by": "userId",
"observation": "It is a long established fact that a reader will be distracted"
},
"output": {
"type": "Transfer out",
"quantity": 1,
"to": {
"warehouse": "6376d84a4587772c3b2d7175",
"warehouse_location": "637d6e218006a7e9609aaf2f",
"expiration_date": "2024-01-03",
"production_lot": "LOT0544522",
"product": "6366a7d99795c333b24f0981"
}
},
"entry": {
"type": "Transfer in",
"quantity": 1,
"from": {
"warehouse": "6376d6c5716fea2e60c491c6",
"warehouse_location": "637d6e1b8006a7e9609aaf2e",
"expiration_date": "2024-01-03",
"production_lot": "LOT0544522",
"product": "6366a7d99795c333b24f0981"
}
}
}
}
]
</code></pre>
<p>In this case I only need to retrieve one of the two documents that exist in the collection. <code>code: 1</code> and <code>code:2</code> to be displayed, something like this:</p>
<pre><code>[
{
"_id": "6386b0e114fe6aee844af06e",
"transfer": {
"code": 2,
"author": {
"created_at": "2022-11-30T01:29:43.308Z",
"created_by": "userId",
"observation": "It is a long established fact that a reader will be distracted"
},
"output": {
"type": "Transfer out",
"quantity": 3,
"to": {
"warehouse": "6376d84a4587772c3b2d7175",
"warehouse_location": "637d6e218006a7e9609aaf2f",
"expiration_date": "2024-01-03",
"production_lot": "LOT0544522",
"product": "6366a7d99795c333b24f0981"
}
},
"entry": {
"type": "Transfer in",
"quantity": 3,
"from": {
"warehouse": "6376d6c5716fea2e60c491c6",
"warehouse_location": "637d6e1b8006a7e9609aaf2e",
"expiration_date": "2024-01-03",
"production_lot": "LOT0544522",
"product": "6366a7d99795c333b24f0981"
}
}
}
},
{
"_id": "6386b13e14fe6aee844af06f",
"transfer": {
"code": 1,
"author": {
"created_at": "2022-11-30T01:27:52.003Z",
"created_by": "userId",
"observation": "It is a long established fact that a reader will be distracted"
},
"output": {
"type": "Transfer out",
"quantity": 1,
"to": {
"warehouse": "6376d84a4587772c3b2d7175",
"warehouse_location": "637d6e218006a7e9609aaf2f",
"expiration_date": "2024-01-03",
"production_lot": "LOT0544522",
"product": "6366a7d99795c333b24f0981"
}
},
"entry": {
"type": "Transfer in",
"quantity": 1,
"from": {
"warehouse": "6376d6c5716fea2e60c491c6",
"warehouse_location": "637d6e1b8006a7e9609aaf2e",
"expiration_date": "2024-01-03",
"production_lot": "LOT0544522",
"product": "6366a7d99795c333b24f0981"
}
}
}
}
]
</code></pre>
<p>The original nomenclature of the object corresponds to the following,</p>
<pre><code> [
{
"_id": "6386b13e14fe6aee844af06f",
"product": "6366a7d99795c333b24f0981",
"warehouse": "6376d84a4587772c3b2d7175",
"warehouse_location": "637d6e218006a7e9609aaf2f",
"production_lot": "LOT0544522",
"expiration_date": "2024-01-03",
"quantity": 12,
"is_deleted": false,
"movements": {
"entries": [...],
"transfers": [
{
"code": 1,
"author": {
"created_at": "2022-11-30T01:27:52.003Z",
"created_by": "userId",
"observation": "It is a long established fact that a reader will be distracted"
},
"output": {
"type": "Transfer out",
"quantity": 1,
"to": {
"warehouse": "6376d84a4587772c3b2d7175",
"warehouse_location": "637d6e218006a7e9609aaf2f",
"expiration_date": "2024-01-03",
"production_lot": "LOT0544522",
"product": "6366a7d99795c333b24f0981"
}
},
"entry": {
"type": "Transfer in",
"quantity": 1,
"from": {
"warehouse": "6376d6c5716fea2e60c491c6",
"warehouse_location": "637d6e1b8006a7e9609aaf2e",
"expiration_date": "2024-01-03",
"production_lot": "LOT0544522",
"product": "6366a7d99795c333b24f0981"
}
}
},
{
"code": 2,
"author": {
"created_at": "2022-11-30T01:29:43.308Z",
"created_by": "userId",
"observation": "It is a long established fact that a reader will be distracted"
},
"output": {
"type": "Transfer out",
"quantity": 3,
"to": {
"warehouse": "6376d84a4587772c3b2d7175",
"warehouse_location": "637d6e218006a7e9609aaf2f",
"expiration_date": "2024-01-03",
"production_lot": "LOT0544522",
"product": "6366a7d99795c333b24f0981"
}
},
"entry": {
"type": "Transfer in",
"quantity": 3,
"from": {
"warehouse": "6376d6c5716fea2e60c491c6",
"warehouse_location": "637d6e1b8006a7e9609aaf2e",
"expiration_date": "2024-01-03",
"production_lot": "LOT0544522",
"product": "6366a7d99795c333b24f0981"
}
}
}
]
}
},
{
"_id": "6386b0e114fe6aee844af06e",
"product": "6366a7d99795c333b24f0981",
"warehouse": "6376d6c5716fea2e60c491c6",
"warehouse_location": "637d6e1b8006a7e9609aaf2e",
"production_lot": "LOT0544522",
"expiration_date": "2024-01-03",
"quantity": 11,
"is_deleted": false,
"movements": {
"entries": [...],
"outputs": [...],
"transfers": [
{
"code": 1,
"author": {
"created_at": "2022-11-30T01:27:52.003Z",
"created_by": "userId",
"observation": "It is a long established fact that a reader will be distracted"
},
"output": {
"type": "Transfer out",
"quantity": 1,
"to": {
"warehouse": "6376d84a4587772c3b2d7175",
"warehouse_location": "637d6e218006a7e9609aaf2f",
"expiration_date": "2024-01-03",
"production_lot": "LOT0544522",
"product": "6366a7d99795c333b24f0981"
}
},
"entry": {
"type": "Transfer in",
"quantity": 1,
"from": {
"warehouse": "6376d6c5716fea2e60c491c6",
"warehouse_location": "637d6e1b8006a7e9609aaf2e",
"expiration_date": "2024-01-03",
"production_lot": "LOT0544522",
"product": "6366a7d99795c333b24f0981"
}
}
},
{
"code": 2,
"author": {
"created_at": "2022-11-30T01:29:43.308Z",
"created_by": "userId",
"observation": "It is a long established fact that a reader will be distracted"
},
"output": {
"type": "Transfer out",
"quantity": 3,
"to": {
"warehouse": "6376d84a4587772c3b2d7175",
"warehouse_location": "637d6e218006a7e9609aaf2f",
"expiration_date": "2024-01-03",
"production_lot": "LOT0544522",
"product": "6366a7d99795c333b24f0981"
}
},
"entry": {
"type": "Transfer in",
"quantity": 3,
"from": {
"warehouse": "6376d6c5716fea2e60c491c6",
"warehouse_location": "637d6e1b8006a7e9609aaf2e",
"expiration_date": "2024-01-03",
"production_lot": "LOT0544522",
"product": "6366a7d99795c333b24f0981"
}
}
}
]
}
}
]
</code></pre>
<p>For this reason, what I do is get to the level of each type of movement, be it transfer, inventory inputs or outputs, and I do it as follows:</p>
<pre><code>return this.connect().then((db) => {
return (
db
.collection(collection)
// The following aggregation uses the $unwind stage to output a
// document for each element in the movements.outputs array
.aggregate([
// Stage 1
{ $unwind: '$movements' },
// Stage 2
{ $unwind: '$movements.transfers' },
// Group by code field
{
$group: {
code: ...,
},
},
])
// The following project only returns the movements.transfers object
.project({
transfer: '$movements.transfers',
})
.sort({ 'transfer.code': -1 })
.toArray()
);
});
</code></pre>
<p>I have tried to use <code>merge</code> or <code>group</code> but have not been able to do what I expect based on the <code>code</code> parameter. Any other way to achieve this?</p>
|
[
{
"answer_id": 74622870,
"author": "Kal",
"author_id": 3717114,
"author_profile": "https://Stackoverflow.com/users/3717114",
"pm_score": -1,
"selected": false,
"text": "aggregate(\n [ { $sample: { size: 1 } } ]\n)\n"
},
{
"answer_id": 74624262,
"author": "nimrod serok",
"author_id": 18482310,
"author_profile": "https://Stackoverflow.com/users/18482310",
"pm_score": 1,
"selected": false,
"text": "db.collection.aggregate([\n {$group: {_id: \"$transfer.code\", data: {$first: \"$$ROOT\"}}},\n {$replaceRoot: {newRoot: \"$data\"}}\n])\n $unwind $group $unwind"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8041208/"
] |
74,622,806
|
<p>I'm running into some problems with my axios get request. I'm trying to fetch stock information using the TwelveData API. Here is my code:</p>
<pre><code>const axios = require('axios');
require('dotenv').config()
const getTickerList = async() => {
await axios.get(`https://api.twelvedata.com/stocks?apikey=${process.env.API_KEY}&symbol=AAPL&country=US`).then(response => console.log(response.data));
}
</code></pre>
<p>When I execute that code, I get a really strange data response that I have attached: <a href="https://i.stack.imgur.com/23PTv.png" rel="nofollow noreferrer">link to pic</a></p>
<p>I would appreciate any help or advice - thanks!</p>
<p>I have outlined the problem above: expected something not like that.</p>
|
[
{
"answer_id": 74622870,
"author": "Kal",
"author_id": 3717114,
"author_profile": "https://Stackoverflow.com/users/3717114",
"pm_score": -1,
"selected": false,
"text": "aggregate(\n [ { $sample: { size: 1 } } ]\n)\n"
},
{
"answer_id": 74624262,
"author": "nimrod serok",
"author_id": 18482310,
"author_profile": "https://Stackoverflow.com/users/18482310",
"pm_score": 1,
"selected": false,
"text": "db.collection.aggregate([\n {$group: {_id: \"$transfer.code\", data: {$first: \"$$ROOT\"}}},\n {$replaceRoot: {newRoot: \"$data\"}}\n])\n $unwind $group $unwind"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20640792/"
] |
74,622,833
|
<p>Given a year, return the century it is in. The first century spans from the year 1 up to and including the year 100, the second - from the year 101 up to and including the year 200, etc.</p>
<pre><code>Example
For year = 1905, the output should be
solution(year) = 20;
For year = 1700, the output should be
solution(year) = 17.
Input/Output
[execution time limit] 4 seconds (dart)
[input] integer year
A positive integer, designating the year.
Guaranteed constraints:
1 ≤ year ≤ 2005.
[output] integer
The number of the century the year is in.
</code></pre>
|
[
{
"answer_id": 74622870,
"author": "Kal",
"author_id": 3717114,
"author_profile": "https://Stackoverflow.com/users/3717114",
"pm_score": -1,
"selected": false,
"text": "aggregate(\n [ { $sample: { size: 1 } } ]\n)\n"
},
{
"answer_id": 74624262,
"author": "nimrod serok",
"author_id": 18482310,
"author_profile": "https://Stackoverflow.com/users/18482310",
"pm_score": 1,
"selected": false,
"text": "db.collection.aggregate([\n {$group: {_id: \"$transfer.code\", data: {$first: \"$$ROOT\"}}},\n {$replaceRoot: {newRoot: \"$data\"}}\n])\n $unwind $group $unwind"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11563594/"
] |
74,622,853
|
<p>Is it possible to run PostgreSQL 11's <code>VACUUM FULL</code> for a short while and then get some benefit? Or does cancelling it midway cause all of its progress to be lost?</p>
<p>I've read about <code>pg_repack</code> (<a href="https://aws.amazon.com/blogs/database/remove-bloat-from-amazon-aurora-and-rds-for-postgresql-with-pg_repack/" rel="nofollow noreferrer">https://aws.amazon.com/blogs/database/remove-bloat-from-amazon-aurora-and-rds-for-postgresql-with-pg_repack/</a>) but the way it works (creating new tables, copying data, etc.) sounds risky to me. Is that my paranoia or is it safe to use on a production database?</p>
<p>Backstory: I am working with a very large production database on AWS Aurora PostgreSQL 11. Many of the tables <em>had</em> tens of millions of records but have been pruned down significantly. The problem is that the table sizes on disk (and in the snapshots) have not decreased because <code>DELETE</code> and <code>VACUUM</code> (without <code>FULL</code>) do not shrink the files. These tables are in the hundreds of gigabytes range and I'm afraid running <code>VACUUM FULL</code> will take <em>forever</em>.</p>
|
[
{
"answer_id": 74622949,
"author": "Erwin Brandstetter",
"author_id": 939860,
"author_profile": "https://Stackoverflow.com/users/939860",
"pm_score": 3,
"selected": true,
"text": "VACUUM FULL VACUUM FULL ACCESS EXCLUSIVE"
},
{
"answer_id": 74631355,
"author": "jjanes",
"author_id": 1721239,
"author_profile": "https://Stackoverflow.com/users/1721239",
"pm_score": 2,
"selected": false,
"text": "with d as (delete from mytable where ctid>='(50000,1)' returning *) \ninsert into mytable select * from d;\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9642/"
] |
74,622,866
|
<p>I want to put items(item1, item2, item3) in "li".
When I used flex, the prefix disappeared!</p>
<p>(here, I use tailwind v2.2.19)</p>
<pre><code><ol class="list-decimal">
<li class="flex">
<div>item1</div>
<div>item2</div>
<div>item3</div>
</li>
<li>item</li>
<li>item</li>
</ol>
</code></pre>
<p>then I got ...</p>
<p><a href="https://i.stack.imgur.com/Pc3ou.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Pc3ou.png" alt="enter image description here" /></a></p>
<p>I really need the prefix, use grid is not fit for my situation.</p>
<p>please help, thanks!!!</p>
|
[
{
"answer_id": 74622949,
"author": "Erwin Brandstetter",
"author_id": 939860,
"author_profile": "https://Stackoverflow.com/users/939860",
"pm_score": 3,
"selected": true,
"text": "VACUUM FULL VACUUM FULL ACCESS EXCLUSIVE"
},
{
"answer_id": 74631355,
"author": "jjanes",
"author_id": 1721239,
"author_profile": "https://Stackoverflow.com/users/1721239",
"pm_score": 2,
"selected": false,
"text": "with d as (delete from mytable where ctid>='(50000,1)' returning *) \ninsert into mytable select * from d;\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16582278/"
] |
74,622,877
|
<p>I am trying to compute number of days between a range of dates input by the user using date picker using the following script:</p>
<pre><code> $(document).ready(function () {
$('#datepicker1').datepicker();
$('#datepicker2').datepicker();
$('#datepicker3').datepicker();
$('#datepicker4').datepicker();
$(function() {
let $fromDate = $('#fromdate'),
$toDate = $('#todate'),
$numberDays = $('#leavedays'),
$sfromDate=$('#sfromdate'),
$stoDate=$('#stodate'),
$snumberDays=$('#sleavedays');
$fromDate.datepicker().on('change', function(){
$toDate.datepicker('option', 'minDate', $(this).val());
$numberDays.val(calculateDateDiff($toDate.val(), $(this).val())+1);
});
$toDate.datepicker().on('change', function(){
$fromDate.datepicker('option', 'maxDate', $(this).val());
$numberDays.val(calculateDateDiff($(this).val(), $fromDate.val())+1);
});
$sfromDate.datepicker().on('change', function(){
$stoDate.datepicker('option', 'minDate', $(this).val());
$snumberDays.val(calculateDateDiff($stoDate.val(), $(this).val())+1);
});
$stoDate.datepicker().on('change', function(){
$sfromDate.datepicker('option', 'maxDate', $(this).val());
$snumberDays.val(calculateDateDiff($(this).val(), $sfromDate.val())+1);
});
function calculateDateDiff(endDate, startDate) {
if (endDate && startDate) {
let e = moment(endDate),
s = moment(startDate);
return e.diff(s, "days");
}
return null;
}
});
});
</code></pre>
<p>The script is able to return the correct difference between from date and to date, but I want to exclude weekend while computing the difference. Please help how to proceed for the same</p>
|
[
{
"answer_id": 74622949,
"author": "Erwin Brandstetter",
"author_id": 939860,
"author_profile": "https://Stackoverflow.com/users/939860",
"pm_score": 3,
"selected": true,
"text": "VACUUM FULL VACUUM FULL ACCESS EXCLUSIVE"
},
{
"answer_id": 74631355,
"author": "jjanes",
"author_id": 1721239,
"author_profile": "https://Stackoverflow.com/users/1721239",
"pm_score": 2,
"selected": false,
"text": "with d as (delete from mytable where ctid>='(50000,1)' returning *) \ninsert into mytable select * from d;\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6359891/"
] |
74,622,886
|
<p>I know the question can be a little weird to understand, so I'll try to explain the best I can the problem</p>
<p>I was trying to align some items but I don't know why one of them is below the other by a few pixels. [This is how it looks][1]</p>
<p>As far as I know, in my code, nothing is making that second item to be some pixels below the others</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{
text-align: center;
background: radial-gradient(circle, rgba(2,0,36,1) 0%, rgba(168,18,9,1) 35%, rgba(82,0,19,1) 100%);
font-family: 'Roboto', sans-serif;
color: white;
margin: 0;
}
header{
border-bottom: 1px solid black;
padding: 20px;
}
#primero{
display: flex;
text-align: center;
align-items: center;
align-content: center;
border-bottom: 1px solid black;
border-right: 1px solid black;
float: left;
}
h1{
margin-left: 5px;
margin-right: 5px;
}
#opciones{
display: flex;
border-bottom: 1px solid black;
height: 150px;
}
#ophome{
text-decoration: none;
color: white;
margin: 25px auto;
border-radius: 10px;
box-shadow: 0 1px 4px rgba(0, 0, 0, 1.12);
display: flex;
height: 75px;
width: 150px;
text-align: center;
align-items: center;
align-content: center;
justify-content: center;
}
#ophome:hover{
padding: 20px;
transition-duration: 0.25s;
}
#spotify{
border-bottom: 1px solid black;
}
#notifoto{
border-radius: 5px;
margin: 5px;
}
#opnoticias{
text-decoration: none;
color: white;
margin: 25px;
border-radius: 10px;
box-shadow: 0 1px 4px rgba(0, 0, 0, 1.12);
display: inline-block;
height: 250px;
width: 250px;
text-align: center;
align-items: center;
align-content: center;
justify-content: center;
}
#opnoticias:hover{
padding: 20px;
transition-duration: 0.25s;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">
<link rel="stylesheet" href="CAFestilos.css">
<title>HuancayoCAF</title>
</head>
<body>
<header>
La página oficial del mejor equipo peruano
</header>
<div id="primero">
<img src="icons/huancayoCAF.png" alt="LogoHuancayoCAF" height="150px">
<h1>HUANCAYO CAF</h1>
</div>
<div id="opciones">
<a id="ophome" href="plantilla.html">Nuestros jugadores</a>
<a id="ophome" href="et.html ">Nuestro equipo técnico</a>
<a id="ophome" href="valores.html">Nuestros valores</a>
<a id="ophome" href="https://www.youtube.com/watch?v=dQw4w9WgXcQ">Miranos entrenar aquí</a>
<a id="ophome" href="https://instagram.com/sga_go?igshid=YmMyMTA2M2Y=">Contenido HOT del equipo, aquí</a>
</div>
<div id="spotify">
<h2>Escucha tu playlist de mrd mientras miras este sinsentido</h2>
<p>(Advertencia, no se puede bajar volumen, cuidado con tus oidos)</p>
<iframe style="border-radius:12px" src="https://open.spotify.com/embed/track/2yAjjqcHMy6qUI6NNzNoVD?utm_source=generator&theme=0" width="75%" height="352" frameBorder="0" allowfullscreen="" allow="autoplay; clipboard-write; encrypted-media; fullscreen; picture-in-picture" loading="lazy"></iframe>
</div>
<!-- the problem starts here -->
<div>
<h2>Noticias</h2>
<a id="opnoticias" href="https://www.youtube.com/watch?v=dQw4w9WgXcQ"><img id="notifoto" src="icons/doping.jpg" alt="imagendoping" height="150px"><p>Kurt Fritz y Vincenzo Garavito dan positivo a 15 drogas diferentes previo al partido</p></a>
<a id="opnoticias" href="https://www.youtube.com/watch?v=dQw4w9WgXcQ"><img id="notifoto" src="icons/evasion.jpg" alt="imagendoping" height="150px"><p>Embargan la casa de Alex Valera por evasión de impuestos</p></a>
<a id="opnoticias" href="https://www.youtube.com/watch?v=dQw4w9WgXcQ"><img id="notifoto" src="icons/07290983.normal.jpg" alt="imagendoping" height="150px"><p>Deportan a Gago de Australia luego de no encontrar el paradero del bus</p></a>
<a id="opnoticias" href="https://www.youtube.com/watch?v=dQw4w9WgXcQ"><img id="notifoto" src="icons/kfc.png" alt="imagendoping" height="150px"><p>Marcus Thuram renueva en el Huancayo CAF por S/5000 y un KFC</p></a>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
<p>If someone can figure it out, it would help me a lot
[1]: <a href="https://i.stack.imgur.com/zoGNi.png" rel="nofollow noreferrer">https://i.stack.imgur.com/zoGNi.png</a></p>
|
[
{
"answer_id": 74622949,
"author": "Erwin Brandstetter",
"author_id": 939860,
"author_profile": "https://Stackoverflow.com/users/939860",
"pm_score": 3,
"selected": true,
"text": "VACUUM FULL VACUUM FULL ACCESS EXCLUSIVE"
},
{
"answer_id": 74631355,
"author": "jjanes",
"author_id": 1721239,
"author_profile": "https://Stackoverflow.com/users/1721239",
"pm_score": 2,
"selected": false,
"text": "with d as (delete from mytable where ctid>='(50000,1)' returning *) \ninsert into mytable select * from d;\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17421059/"
] |
74,622,895
|
<p>I want to print "ping" "pong", which are in same class but different method, 5 times using synchronized block.</p>
<p>The problem is that it stops after print ping pong once.</p>
<p>How can I print ping pong 5 times?</p>
<p>I think I put notifyAll() and wait() in right place.</p>
<p>print result</p>
<pre><code>ping
pong
</code></pre>
<p>here is my main class</p>
<pre><code>public class ThreadTest2 {
public static void main(String[] args) throws {
Thread thread1 = new Thread(() -> {
forLoop("a");
});
Thread thread2 = new Thread(() -> {
forLoop(null);
});
thread1.setPriority(10);
thread2.setPriority(1);
thread1.start();
thread2.start();
}
static void forLoop(String target) {
AA aa = new AA();
try {
for(int i=0; i<5; i++){
if(target != null){
aa.ping();
}
else{
aa.pong();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
</code></pre>
<p>here is my ping pong class</p>
<pre><code>public class AA {
Thread thread;
public void ping() throws InterruptedException {
synchronized (this) {
System.out.println("ping");
wait();
notifyAll();
}
}
public void pong() throws InterruptedException {
synchronized (this) {
System.out.println("pong");
notifyAll();
wait();
}
}
}
</code></pre>
<p>Thank you!</p>
<pre><code>ping
pong
ping
pong
ping
pong
ping
pong
ping
pong
</code></pre>
|
[
{
"answer_id": 74623633,
"author": "vic cao",
"author_id": 16826913,
"author_profile": "https://Stackoverflow.com/users/16826913",
"pm_score": 0,
"selected": false,
"text": "public class SynchronizedTest {\n public void ping(int count) throws InterruptedException {\n synchronized (this) {\n for (int i = 0; i <count ; i++) {\n System.out.println(\"ping\");\n notifyAll();//\n wait();\n }\n }\n }\n\n public void pong(int count) throws InterruptedException {\n synchronized (this) {\n for (int i = 0; i <count ; i++) {\n System.out.println(\"pong\");\n notifyAll();\n wait();\n }\n }\n }\n\n\n public static void main(String[] args) throws InterruptedException {\n SynchronizedTest aa = new SynchronizedTest();\n Thread thread1 = new Thread(() -> {\n try {\n aa.ping(5);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n });\n\n Thread thread2 = new Thread(() -> {\n try {\n aa.pong(5);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n });\n thread1.start();\n thread2.start();\n }\n}\n\n"
},
{
"answer_id": 74632076,
"author": "Gray",
"author_id": 179850,
"author_profile": "https://Stackoverflow.com/users/179850",
"pm_score": 2,
"selected": false,
"text": "forloop() AA AA notifyAll() AA notifyAll() wait() boolean firstPrinted true println(...) synchronized (this) {\n while (!first) {\n wait();\n }\n }\n aa.oneMoreNotify() public void oneMoreNotify() {\n synchronized (this) {\n notifyAll();\n }\n }\n thread.setPriority(...) catch (InterruptedException e) Thread.currentThread().interrupt() String target boolean message.equals(\"pong\") Thread AA"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20377813/"
] |
74,622,918
|
<p>I am trying to store a 2D vector into a .DAT file and I would like to add a space at the start of every row. An example of a desired output looks like this:</p>
<pre><code> 0.0000000E+00 0.0000000E+00
2.0020020E-03 0.0000000E+00
4.0040040E-03 0.0000000E+00
6.0060060E-03 0.0000000E+00
8.0080080E-03 0.0000000E+00
1.0010010E-02 0.0000000E+00
1.2012012E-02 0.0000000E+00
</code></pre>
<p>You can see at the front of 0, 2e-3, 4e-3, etc. there is a space. My code is trying to do that way</p>
<pre><code>data = np.column_stack((x, y))
with open('output.dat', 'w') as datfile:
for _ in range(N):
np.savetxt(datfile, data, delimiter = " ")
</code></pre>
<p>The current output looks like this:</p>
<pre><code>0.000000000000000000e+00 0.000000000000000000e+00
1.250156269533691795e-04 0.000000000000000000e+00
2.500312539067383591e-04 0.000000000000000000e+00
3.750468808601075386e-04 0.000000000000000000e+00
5.000625078134767181e-04 0.000000000000000000e+00
6.250781347668459519e-04 0.000000000000000000e+00
7.500937617202150772e-04 0.000000000000000000e+00
</code></pre>
<p>As you can see, there is no space at the front of every line. Do you have any solutions for this? Thanks!</p>
|
[
{
"answer_id": 74622943,
"author": "Alexander L. Hayes",
"author_id": 12439119,
"author_profile": "https://Stackoverflow.com/users/12439119",
"pm_score": 1,
"selected": true,
"text": "import numpy as np\n\ndata = np.zeros((5, 2), dtype=np.float64)\n\nwith open(\"out.dat\", \"w\") as fh:\n for row in data:\n x, y = row\n fh.write(f\" {x} {y}\\n\")\n 0.0 0.0\n 0.0 0.0\n 0.0 0.0\n 0.0 0.0\n 0.0 0.0\n"
},
{
"answer_id": 74622970,
"author": "svfat",
"author_id": 2419628,
"author_profile": "https://Stackoverflow.com/users/2419628",
"pm_score": 1,
"selected": false,
"text": "fmt np.savetxt fmt np.savetxt(datfile, data, fmt=\" %1.7E %1.7E\") string"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10810402/"
] |
74,622,946
|
<p>I am building a small web page as an exercise.
I'm trying to arrange three photos next to three texts aside each other and it's not working.
My idea is that they look like this:</p>
<pre><code> Photo---> text
text--->photo
photo--->text
</code></pre>
<p>And for that I wrapped the package of images and text in a
then in css I put this:</p>
<pre><code> .grid-wrapper {
display:grid;
grid-template-columns. auto auto auto;
grid-gap: 10px;
}
</code></pre>
<p>And well it hasn't worked.
I appreciate your advice</p>
|
[
{
"answer_id": 74622943,
"author": "Alexander L. Hayes",
"author_id": 12439119,
"author_profile": "https://Stackoverflow.com/users/12439119",
"pm_score": 1,
"selected": true,
"text": "import numpy as np\n\ndata = np.zeros((5, 2), dtype=np.float64)\n\nwith open(\"out.dat\", \"w\") as fh:\n for row in data:\n x, y = row\n fh.write(f\" {x} {y}\\n\")\n 0.0 0.0\n 0.0 0.0\n 0.0 0.0\n 0.0 0.0\n 0.0 0.0\n"
},
{
"answer_id": 74622970,
"author": "svfat",
"author_id": 2419628,
"author_profile": "https://Stackoverflow.com/users/2419628",
"pm_score": 1,
"selected": false,
"text": "fmt np.savetxt fmt np.savetxt(datfile, data, fmt=\" %1.7E %1.7E\") string"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20635545/"
] |
74,622,971
|
<p>I have the following TextView defined:</p>
<pre><code><TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:autoLink="web"
android:linksClickable="true"
android:id="@+id/googleplayservices"
android:layout_marginLeft="40dp"
android:layout_marginRight="15dp"
android:fontFamily="@font/inter_medium"
android:paddingTop="@dimen/_5sdp"
android:text="@string/Google_Play_Services"
android:textColor="@color/black"
android:textSize="@dimen/_12sdp" />
</code></pre>
<p>where <code>@string/Google_Play_Services</code> is a string resource that contains <code><a href="some site">Link text</a></code>.</p>
<p>Android is highlighting the links in the TextView, but they do not respond to clicks. What am I doing wrong? Do I have to set an onClickListener for the TextView in my activity for something as simple as this?</p>
|
[
{
"answer_id": 74622943,
"author": "Alexander L. Hayes",
"author_id": 12439119,
"author_profile": "https://Stackoverflow.com/users/12439119",
"pm_score": 1,
"selected": true,
"text": "import numpy as np\n\ndata = np.zeros((5, 2), dtype=np.float64)\n\nwith open(\"out.dat\", \"w\") as fh:\n for row in data:\n x, y = row\n fh.write(f\" {x} {y}\\n\")\n 0.0 0.0\n 0.0 0.0\n 0.0 0.0\n 0.0 0.0\n 0.0 0.0\n"
},
{
"answer_id": 74622970,
"author": "svfat",
"author_id": 2419628,
"author_profile": "https://Stackoverflow.com/users/2419628",
"pm_score": 1,
"selected": false,
"text": "fmt np.savetxt fmt np.savetxt(datfile, data, fmt=\" %1.7E %1.7E\") string"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20424527/"
] |
74,622,973
|
<pre><code>data=[{id: 4, lat: -33.85664180722481, long: 151.2153396118792},{..},{...}..];
</code></pre>
<p>This is my data and I have calculateDistance() function. And location is the location of where mause is clicked on map.What I want is to pass each element in data to pass my calculateDistance() function and save the result in distance array and pass it to useState hook. How can i do that?
I get output as NaN array with that code.</p>
<pre class="lang-js prettyprint-override"><code> useEffect(() =>
{
const distance = data.map((hero) => {
calculateDistance(location?.lat, location?.lng, hero?.lat,hero?.long);
return distance;
});
setDistance(distance);
},[location, data]);
</code></pre>
<p>And here is the calculate distance function</p>
<pre><code>const [distance, setDistance] = useState(null);
const data = useHeroesData();
//console.log(data);
const calculateDistance = (lat1, lon1, lat2, lon2) => {
// generally used geo measurement function
var R = 6378.137; // Radius of earth in KM
var dLat = (lat2 * Math.PI) / 180 - (lat1 * Math.PI) / 180;
var dLon = (lon2 * Math.PI) / 180 - (lon1 * Math.PI) / 180;
var a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos((lat1 * Math.PI) / 180) *
Math.cos((lat2 * Math.PI) / 180) *
Math.sin(dLon / 2) *
Math.sin(dLon / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c;
return d; // km
};
</code></pre>
|
[
{
"answer_id": 74622943,
"author": "Alexander L. Hayes",
"author_id": 12439119,
"author_profile": "https://Stackoverflow.com/users/12439119",
"pm_score": 1,
"selected": true,
"text": "import numpy as np\n\ndata = np.zeros((5, 2), dtype=np.float64)\n\nwith open(\"out.dat\", \"w\") as fh:\n for row in data:\n x, y = row\n fh.write(f\" {x} {y}\\n\")\n 0.0 0.0\n 0.0 0.0\n 0.0 0.0\n 0.0 0.0\n 0.0 0.0\n"
},
{
"answer_id": 74622970,
"author": "svfat",
"author_id": 2419628,
"author_profile": "https://Stackoverflow.com/users/2419628",
"pm_score": 1,
"selected": false,
"text": "fmt np.savetxt fmt np.savetxt(datfile, data, fmt=\" %1.7E %1.7E\") string"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74622973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7828539/"
] |
74,623,000
|
<p>This is my return function which contains all components in the renderer. Every time I press on the footerComponent in the Sectionlist, the whole screen re-renders and causes an auto-scroll to position 0.</p>
<pre><code>return (
<SafeAreaView style={styles.container}>
<ImageBackground
source={require("../assets/stars.gif")}
style={{
width: Dim.width,
height: Dim.height,
}}
resizeMode="repeat"
>
{files ? <List /> : null}
<CustomModal
visible={visible}
onPressIn={() => startRecording()}
onPressOut={() => stopRecording()}
onExitPress={() => setVisible(false)}
onConfirm={() => sendToStorage(ID, len)}
disabled={!strgUri}
onDismiss={() => setRecording(null)}
modalButton={[
styles.modal,
pressed
? { backgroundColor: Colors.clay }
: { backgroundColor: Colors.aegean },
]}
progress={progress}
loadingVisible={sending}
/>
</ImageBackground>
</SafeAreaView>
);
</code></pre>
<p>and this is my Animated SectionList component.</p>
<pre><code>const NewSectionList = Animated.createAnimatedComponent(SectionList);
const List = React.forwardRef((ref, props) => {
const respondRef = useRef();
const scrollRef = useRef().current;
function scrollToSection() {
if (respondRef.current) {
respondRef.current.measure((x, y, width, height, px, py) => {
console.log("height: ", height);
console.log("y: ", y);
setHeight(py);
});
console.log("scrolling to: ", height);
if (height != 0) {
setTimeout(() => {
console.log("wait height: ", height);
console.log("dim height: ", Dim.height);
console.log("1 height: ", Dim.height - height + Dim.height);
scrollRef?.scrollTo({
x: 0,
y: Dim.height - height + Dim.height,
animated: true,
});
}, 1000);
}
}
}
useEffect(() => {
scrollToSection();
});
const yVal = fadeAnim.interpolate({
inputRange: [0, 1],
outputRange: [900, 0],
});
const animStyle = {
transform: [
{
translateY: yVal,
},
],
};
return(
<Animated.View style={[animStyle]}>
<NewSectionList
ref={scrollRef}
stickySectionHeadersEnabled={false}
sections={files}
keyExtractor={(item) => item.id}
style={{
marginLeft: 10,
marginBottom: 110,
}}
renderItem={({ item }) => (
<View style={styles.cardContainer}>
<View
style={{
alignSelf: "flex-start",
position: "absolute",
marginTop: 5,
}}
>
<Text p4 dusk>
{new Date(item.timestamp).toDateString()}
</Text>
</View>
<TouchableOpacity
onPress={() => visitProfile(item.name, item.email)}
>
<Text p2 aegean>
{item.name}
</Text>
</TouchableOpacity>
<View styles={styles.cardTap}>
<TouchableNativeFeedback
onPress={() => {
playFile(item.url, item.id);
}}
>
<AntDesign name="stepforward" size={40} color={Colors.led} />
</TouchableNativeFeedback>
</View>
</View>
)}
renderSectionHeader={({
section: {
information,
origin,
userOrigin,
emailOrigin,
origID,
originDate,
},
}) => (
<View style={styles.headerContainer}>
<View
style={{
alignSelf: "flex-start",
position: "absolute",
marginTop: 5,
}}
>
<Text p3 led>
{new Date(originDate).toDateString()}
</Text>
</View>
<View style={styles.holder}>
<TouchableOpacity
onPress={() => visitProfile(userOrigin, emailOrigin)}
>
<Text h4 night>
{userOrigin}
</Text>
</TouchableOpacity>
</View>
<View style={styles.outerInfo}>
<Text p3 dusk style={styles.textInfo}>
{information ? information : ""}
</Text>
</View>
<View styles={styles.cardTap}>
<TouchableNativeFeedback
onPress={() => {
playFile(origin, origID);
}}
>
<AntDesign
name="stepforward"
size={40}
color={Colors.night}
/>
</TouchableNativeFeedback>
</View>
</View>
)}
renderSectionFooter={({ section: { docId, dataLen } }) => (
<TouchableOpacity
ref={respondRef}
style={styles.notPressed}
onPress={() => {
setVisible(true);
scrollToSection();
setID(docId);
setLen(dataLen);
}}
>
<Text p2 white>
add to convo
</Text>
</TouchableOpacity>
)}
refreshControl={<RefreshControl onRefresh={() => getData()} />}
/>
</Animated.View>
);
});
</code></pre>
<p>I tried to implement a scrollTo() method function to the position of the pressed button, but that is more of a hack than a real solution since it will keep re-rendering and scrolling. Also, the modal that I am trying to activate has other stateful components within it, causing more re-renders. Another attempted fix was trying to memo-ize the modal, however the official docs suggest that premature-optimization isn't not a real solution and will lead to more bugs down the . Thank you.</p>
|
[
{
"answer_id": 74622943,
"author": "Alexander L. Hayes",
"author_id": 12439119,
"author_profile": "https://Stackoverflow.com/users/12439119",
"pm_score": 1,
"selected": true,
"text": "import numpy as np\n\ndata = np.zeros((5, 2), dtype=np.float64)\n\nwith open(\"out.dat\", \"w\") as fh:\n for row in data:\n x, y = row\n fh.write(f\" {x} {y}\\n\")\n 0.0 0.0\n 0.0 0.0\n 0.0 0.0\n 0.0 0.0\n 0.0 0.0\n"
},
{
"answer_id": 74622970,
"author": "svfat",
"author_id": 2419628,
"author_profile": "https://Stackoverflow.com/users/2419628",
"pm_score": 1,
"selected": false,
"text": "fmt np.savetxt fmt np.savetxt(datfile, data, fmt=\" %1.7E %1.7E\") string"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14913313/"
] |
74,623,054
|
<p>I am building a Python library and I have the requirement inside one of the modules to get the current version of this same library and make decisions based on the current version.
Is this possible in Python? What do you think is the best approach?</p>
|
[
{
"answer_id": 74622943,
"author": "Alexander L. Hayes",
"author_id": 12439119,
"author_profile": "https://Stackoverflow.com/users/12439119",
"pm_score": 1,
"selected": true,
"text": "import numpy as np\n\ndata = np.zeros((5, 2), dtype=np.float64)\n\nwith open(\"out.dat\", \"w\") as fh:\n for row in data:\n x, y = row\n fh.write(f\" {x} {y}\\n\")\n 0.0 0.0\n 0.0 0.0\n 0.0 0.0\n 0.0 0.0\n 0.0 0.0\n"
},
{
"answer_id": 74622970,
"author": "svfat",
"author_id": 2419628,
"author_profile": "https://Stackoverflow.com/users/2419628",
"pm_score": 1,
"selected": false,
"text": "fmt np.savetxt fmt np.savetxt(datfile, data, fmt=\" %1.7E %1.7E\") string"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1166868/"
] |
74,623,061
|
<p>I'm trying to play with the setInterval method and I'm just wondering what I have done wrong here. If I program it to return an alert, no problem - it appears at every interval as expected. However, I want my background color to change every few seconds and it's not happening. The color is altered once and that's all the fun I get.</p>
<p><a href="https://i.stack.imgur.com/2w0Ta.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2w0Ta.png" alt="enter image description here" /></a></p>
<p>I've had a look at similar posts on Stack Overflow and played around, but to no avail. Any suggestions much appreciated. Thanks million!</p>
|
[
{
"answer_id": 74623087,
"author": "Yuri Santos",
"author_id": 7695619,
"author_profile": "https://Stackoverflow.com/users/7695619",
"pm_score": 1,
"selected": false,
"text": "setInterval choice1 choice1 setInverval function changeColor() {\n choice1 = /*Your random function here*/\n document.body.style.backgroundColor = choice1;\n}\n"
},
{
"answer_id": 74623100,
"author": "Hao-Jung Hsieh",
"author_id": 12598451,
"author_profile": "https://Stackoverflow.com/users/12598451",
"pm_score": 0,
"selected": false,
"text": "choice1 document.body.style.backgroundColor = oneArray[Math.floor(Math.random() * oneArray.length)]\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20166771/"
] |
74,623,066
|
<pre><code>router.get('/spotifyLogin', (req,res) => {
const state = generateRandomString(16);
const scope = 'user-read-recently-played';
const queryParams = querystring.stringify({
response_type: 'code',
client_id: client_id,
scope: scope,
redirect_uri: redirect_uri,
state: state
});
res.redirect(`https://accounts.spotify.com/authorize?${queryParams}`);
});
router.get('/callback', (req,res) => {
const authorizationCode = req.query.code || null;
const state = req.query.state || null;
axios({
method: 'post',
url: 'https://accounts.spotify.com/api/token',
data: querystring.stringify({
grant_type: 'authorization_code',
code: authorizationCode,
redirect_uri: redirect_uri,
}),
headers: {
'content-type': 'application/x-www-form-urlencoded',
Authorization: `Basic ${new Buffer.from(`${client_id}:${client_secret}`).toString('base64')}`,
},
})
.then(response => {
if (response.status === 200) {
res.send(response.data)
} else {
res.send(response);
}
})
.catch(error => {
res.send(error);
});
});
</code></pre>
<p>I am doing the spotify authorization code flow on a custom express api server
<a href="https://developer.spotify.com/documentation/general/guides/authorization/code-flow/" rel="nofollow noreferrer">https://developer.spotify.com/documentation/general/guides/authorization/code-flow/</a></p>
<p>When I make a post request to the token url, I should get a json object in my response.data, but I am getting weird characters
<a href="https://i.stack.imgur.com/GnwUJ.png" rel="nofollow noreferrer">Screenshot of response.data</a></p>
|
[
{
"answer_id": 74624928,
"author": "anshai",
"author_id": 14402919,
"author_profile": "https://Stackoverflow.com/users/14402919",
"pm_score": 2,
"selected": false,
"text": "accept-encoding * axios({\n method: 'post',\n url: 'https://accounts.spotify.com/api/token',\n data: querystring.stringify({\n grant_type: 'authorization_code',\n code: authorizationCode,\n redirect_uri: redirect_uri,\n }),\n headers: {\n 'content-type': 'application/x-www-form-urlencoded',\n Authorization: `Basic ${new Buffer.from(`${client_id}:${client_secret}`).toString('base64')}`,\n 'accept-encoding': '*'\n },\n})\n"
},
{
"answer_id": 74655634,
"author": "lenikhilsingh",
"author_id": 8104036,
"author_profile": "https://Stackoverflow.com/users/8104036",
"pm_score": 1,
"selected": false,
"text": "\"axios\": \"1.2.0\" 'accept-encoding': '*' accept-encoding"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20641141/"
] |
74,623,081
|
<p>this is the json formate by which I need to get the data `</p>
<pre><code>{
"count": 2,
"next": null,
"previous": null,
"results": [
{
"date": "2022-11-23",
"breaks_set": [],
"id": "c82af994-541a-40eb-a154-9cf8b130100c",
"clock_in_time": "2:30",
"clock_out_time": "6:30",
"on_time_clock_in": 553,
"on_time_clock_out": -313
},
{
"date": "2022-11-28",
"breaks_set": [
{
"start": "09:36:01",
"end": "09:40:12.632703",
"break_duration": 4
},
{
"start": "09:40:13.626539",
"end": "09:40:14.282107",
"break_duration": 0
},
{
"start": "09:40:14.764177",
"end": "09:40:15.606529",
"break_duration": 0
}
],
"id": "e1c21659-1c2f-4ecd-b56b-a45626bedd7c",
"clock_in_time": "9:36",
"clock_out_time": "9:40",
"on_time_clock_in": 128,
"on_time_clock_out": -124
}
]
}
</code></pre>
<p>`</p>
<p>The model class of the json is coded like this</p>
<pre><code>class BreaksSet {
String? start;
String? end;
int? breakduration;
BreaksSet({this.start, this.end, this.breakduration});
BreaksSet.fromJson(Map<String, dynamic> json) {
start = json['start'];
end = json['end'];
breakduration = json['break_duration'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = Map<String, dynamic>();
data['start'] = start;
data['end'] = end;
data['break_duration'] = breakduration;
return data;
}
}
class Result {
String? date;
List<BreaksSet?>? breaksset;
String? id;
String? clockintime;
String? clockouttime;
int? ontimeclockin;
int? ontimeclockout;
Result(
{this.date,
this.breaksset,
this.id,
this.clockintime,
this.clockouttime,
this.ontimeclockin,
this.ontimeclockout});
Result.fromJson(Map<String, dynamic> json) {
date = json['date'];
if (json['breaks_set'] != null) {
breaksset = <BreaksSet>[];
json['breaks_set'].forEach((v) {
breaksset!.add(BreaksSet.fromJson(v));
});
}
id = json['id'];
clockintime = json['clock_in_time'];
clockouttime = json['clock_out_time'];
ontimeclockin = json['on_time_clock_in'];
ontimeclockout = json['on_time_clock_out'];
}
}
class Attendance {
int? count;
String? next;
String? previous;
List<Result?>? results;
Attendance({this.count, this.next, this.previous, this.results});
Attendance.fromJson(Map<String, dynamic> json) {
count = json['count'];
next = json['next'];
previous = json['previous'];
if (json['results'] != null) {
results = <Result>[];
json['results'].forEach((v) {
results!.add(Result.fromJson(v));
});
}
}
}
</code></pre>
<p>the api calling I used DIO and the method is, here I made a connection class that contains the dio codes of all type api calling
`</p>
<pre><code>Future<List<Attendance>> getUserAttendanceData() async {
final response = await _connection.getDataWithToken(
"${KApiUrls.baseUrl}/attendance-list/",
token,
);
if (response != null) {
if (response.statusCode == 200
) {
var data = jsonDecode(response.data).cast<List<Map<String, dynamic>>>();
return List.from(
data.map((attendance) => Attendance.fromJson(attendance)));
} else {
throw Exception();
}
} else {
throw Error();
}
}
</code></pre>
<p>`</p>
<p>I am getting this error, I have to idea how to solve this, but I tried several solution for this</p>
|
[
{
"answer_id": 74624928,
"author": "anshai",
"author_id": 14402919,
"author_profile": "https://Stackoverflow.com/users/14402919",
"pm_score": 2,
"selected": false,
"text": "accept-encoding * axios({\n method: 'post',\n url: 'https://accounts.spotify.com/api/token',\n data: querystring.stringify({\n grant_type: 'authorization_code',\n code: authorizationCode,\n redirect_uri: redirect_uri,\n }),\n headers: {\n 'content-type': 'application/x-www-form-urlencoded',\n Authorization: `Basic ${new Buffer.from(`${client_id}:${client_secret}`).toString('base64')}`,\n 'accept-encoding': '*'\n },\n})\n"
},
{
"answer_id": 74655634,
"author": "lenikhilsingh",
"author_id": 8104036,
"author_profile": "https://Stackoverflow.com/users/8104036",
"pm_score": 1,
"selected": false,
"text": "\"axios\": \"1.2.0\" 'accept-encoding': '*' accept-encoding"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20107819/"
] |
74,623,133
|
<pre><code>Name email date
_________________________________________________
Dane dane_1@yahoo.com 2017-06-20
Dane dane_2@yahoo.com 2017-06-20
Dane dane_3@yahoo.com 2017-06-20
Dane dane_4@yahoo.com 2017-06-20
Kim kim@gmail.com 2017-06-10
Hong hong_1@gmail.com 2016-06-25
Hong hong_2@gmail.com 2016-06-25
Hong hong_3@gmail.com 2016-06-25
Dane dddd@gmail.com 2017-06-04
Susan Susan@gmail.com 2017-05-21
Dane kkkk@gmail.com 2017-02-01
Susan sss@gmail.com 2017-05-20
</code></pre>
<p>I can get the first entries of each unique by using <code>EmailModel.objects.all().order_by('date').distinct('Name')</code>. this returns</p>
<pre><code> Name email date
_________________________________________________
Dane dane_1@yahoo.com 2017-06-20
Kim kim@gmail.com 2017-06-10
Hong hong_1@gmail.com 2016-06-25
Susan Susan@gmail.com 2017-05-21
</code></pre>
<p>What i want to do here is to only include it in the result if the very first entry is something different like more filtering over it? for ex- i don't want to include it in the result if the first email id is dane@yahoo.com for Dave and only include it if it is something different.</p>
<p>Expected result:
if the email for Dane is not dane_1@yahoo.com then</p>
<pre><code> Name email date
_________________________________________________
Kim kim@gmail.com 2017-06-10
Hong hong_1@gmail.com 2016-06-25
Susan Susan@gmail.com 2017-05-21
</code></pre>
|
[
{
"answer_id": 74623273,
"author": "Sunderam Dubey",
"author_id": 17562044,
"author_profile": "https://Stackoverflow.com/users/17562044",
"pm_score": 0,
"selected": false,
"text": "F() __istartswith EmailModel.objects.exclude(email__istartswith=F('Name')).order_by(\"date\").distinct(\"Name\")\n Name __icontains EmailModel.objects.exclude(email__icontains=F('Name')).order_by(\"date\").distinct(\"Name\")\n"
},
{
"answer_id": 74623752,
"author": "August Infotech",
"author_id": 20289335,
"author_profile": "https://Stackoverflow.com/users/20289335",
"pm_score": -1,
"selected": false,
"text": "User.object.filter(parameters).order_by(parameters)"
},
{
"answer_id": 74639778,
"author": "Naser Fazal khan",
"author_id": 19313399,
"author_profile": "https://Stackoverflow.com/users/19313399",
"pm_score": 0,
"selected": false,
"text": " variable = modelname.objects.filter(\n ....=....).values(\n 'mention_the_column_names_if_you_need_any'\n ).order_by(\n 'mention_the_column_name_to_be_sorted'\n ).distinct()\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15759796/"
] |
74,623,137
|
<p>I am trying to create a condition where if the column headers in my dataframe are equal to
Unnamed: 0 VALUE VALUE.1 VALUE.2 then i want to do drop the first two rows and rename the headers</p>
<pre><code>Unnamed: 0 VALUE VALUE.1 VALUE.2
Name Hobbies Dislikes Favorite Color
Ben NaN NaN NaN
Alex NaN Running Red
Mike NaN Cartoons Blue
Mark NaN Pizza Yellow
</code></pre>
<p>I know i can do</p>
<pre><code> df = df.drop([0,1])
</code></pre>
<p>but i need it to be conditional</p>
<p>I tried doing</p>
<pre><code>if df.columns = {"Unnamed: 0", "VALUE", "VALUE.1", "VALUE.2"}:
df = df.drop([0,1])
df = df.rename(columns={"Unnamed: 0": "Name", "VALUE": "Hobbies", "VALUE.1": "Dislikes", "VALUE.2": "Favorite Color"})
</code></pre>
<p>but i'm running into a syntax error where i am trying to create a condition with my column names. Any clue how to fix this?</p>
|
[
{
"answer_id": 74623361,
"author": "Liu Leo",
"author_id": 20641178,
"author_profile": "https://Stackoverflow.com/users/20641178",
"pm_score": 2,
"selected": false,
"text": "import pandas as pd\n\ndf = pd.DataFrame(columns=[\"Unnamed: 0\", \"VALUE\", \"VALUE.1\", \"VALUE.2\"])\ndf.loc[0] = ['Name', 'Hobbies', 'Dislikes', 'Favorite Color']\ndf.loc[1] = ['Ben', None, None, None]\n\nprint(df)\n\nif (df.columns == [\"Unnamed: 0\", \"VALUE\", \"VALUE.1\", \"VALUE.2\"]).all():\n df = df.drop([0])\n df.columns = ['Name', 'Hobbies', 'Dislikes', 'Favorite Color']\nprint()\nprint(df)\n Unnamed: 0 VALUE VALUE.1 VALUE.2\n0 Name Hobbies Dislikes Favorite Color\n1 Ben None None None\n\n Name Hobbies Dislikes Favorite Color\n1 Ben None None None\n"
},
{
"answer_id": 74623404,
"author": "ziying35",
"author_id": 16755671,
"author_profile": "https://Stackoverflow.com/users/16755671",
"pm_score": 3,
"selected": true,
"text": "cols = pd.Index(['Unnamed:0', 'VALUE', 'VALUE.1', 'VALUE.2'])\nif df.columns.equals(cols):\n df = df.set_axis(df.iloc[0], axis=1).iloc[1:]\nprint(df)\n>>>\n Name Hobbies Dislikes Favorite Color\n1 Ben NaN NaN NaN None\n2 Alex NaN Running Red None\n3 Mike NaN Cartoons Blue None\n4 Mark NaN Pizza Yellow None\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16633745/"
] |
74,623,176
|
<p>can anyone please help me?, I created a login function with api, when the user wants to login and succeeds then it is directed to the profilescreen the user details appear, but when it switches to the homescreen and switches to the profilescreen again, the user details that previously appeared are lost and become null.</p>
<p>I thought of using sharedpreferences to save user response data after login, but I don't know if it was saved or not</p>
<pre><code>Future<LoginModels> postLogin(String email, String password) async {
var dio = Dio();
String baseurl = url;
Map<String, dynamic> data = {'email': email, 'password': password};
try {
final response = await dio.post(
'$baseurl/api/login',
data: data,
options: Options(headers: {'Content-type': 'application/json'}),
);
print('Respon -> ${response.data} + ${response.statusCode}');
if (response.statusCode == 200) {
final loginModel = LoginModels.fromJson(response.data);
return loginModel;
}
} catch (e) {
print('Error di $e');
}
return LoginModels();}
</code></pre>
<p>i tried adding sharedpreference in the part after response.statuscode == 200 , like this</p>
<pre><code> SharedPreferences pref = await SharedPreferences.getInstance();
String jsonUser = jsonEncode(loginModel);
pref.setString('userDetail', jsonUser);
print('data nih $jsonUser');
</code></pre>
<p>and the output is like this
<a href="https://i.stack.imgur.com/l5BjH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/l5BjH.png" alt="(from api (Respon -> {...})) and (i tried sharedpreferences (Data nih {...}))" /></a></p>
<pre><code>LoginModels loginModelsFromJson(String str) => LoginModels.fromJson(
json.decode(str),
);
String loginModelsToJson(LoginModels data) => json.encode(data.toJson());
class LoginModels {
LoginModels({
this.isActive,
this.message,
this.data,
});
bool? isActive;
String? message;
Data? data;
factory LoginModels.fromJson(Map<String, dynamic> json) => LoginModels(
isActive: json["is_active"],
message: json["message"],
data: Data.fromJson(json["data"]),
);
Map<String, dynamic> toJson() => {
"is_active": isActive,
"message": message,
"data": data?.toJson(),
};
}
class Data {
Data({
this.iduser,
this.nama,
this.profesi,
this.email,
this.password,
this.roleId,
this.isActive,
this.tanggalInput,
this.modified,
});
String? iduser;
String? nama;
String? profesi;
String? email;
String? password;
String? roleId;
String? isActive;
String? tanggalInput;
String? modified;
factory Data.fromJson(Map<String, dynamic> json) => Data(
iduser: json["iduser"],
nama: json["nama"],
profesi: json["profesi"],
email: json["email"],
password: json["password"],
roleId: json["role_id"],
isActive: json["is_active"],
tanggalInput: json["tanggal_input"],
modified: json["modified"],
);
Map<String, dynamic> toJson() => {
"iduser": iduser,
"nama": nama,
"profesi": profesi,
"email": email,
"password": password,
"role_id": roleId,
"is_active": isActive,
"tanggal_input": tanggalInput,
"modified": modified,
};
}
class User {
String? id;
String? nama;
String? profesi;
String? email;
String? password;
String? roleId;
String? isActive;
String? tanggalInput;
String? modified;
User();
User.fromJson(Map<String, dynamic> json)
: id = json["iduser"],
nama = json['nama'],
profesi = json['profesi'],
email = json['email'],
password = json['password'],
roleId = json['role_id'],
isActive = json['is_active'],
tanggalInput = json['tanggal_input'],
modified = json['modified'];
Map<String, dynamic> toJson() => {
'id': id,
'nama': nama,
'profesi': profesi,
'email': email,
'password': password,
'role_id': roleId,
'is_active': isActive,
'tanggal_input': tanggalInput,
'modified': modified,
};
}
</code></pre>
<p>if it is already stored how do I retrieve the data? or is there another alternative to solve the problem I have?</p>
|
[
{
"answer_id": 74623361,
"author": "Liu Leo",
"author_id": 20641178,
"author_profile": "https://Stackoverflow.com/users/20641178",
"pm_score": 2,
"selected": false,
"text": "import pandas as pd\n\ndf = pd.DataFrame(columns=[\"Unnamed: 0\", \"VALUE\", \"VALUE.1\", \"VALUE.2\"])\ndf.loc[0] = ['Name', 'Hobbies', 'Dislikes', 'Favorite Color']\ndf.loc[1] = ['Ben', None, None, None]\n\nprint(df)\n\nif (df.columns == [\"Unnamed: 0\", \"VALUE\", \"VALUE.1\", \"VALUE.2\"]).all():\n df = df.drop([0])\n df.columns = ['Name', 'Hobbies', 'Dislikes', 'Favorite Color']\nprint()\nprint(df)\n Unnamed: 0 VALUE VALUE.1 VALUE.2\n0 Name Hobbies Dislikes Favorite Color\n1 Ben None None None\n\n Name Hobbies Dislikes Favorite Color\n1 Ben None None None\n"
},
{
"answer_id": 74623404,
"author": "ziying35",
"author_id": 16755671,
"author_profile": "https://Stackoverflow.com/users/16755671",
"pm_score": 3,
"selected": true,
"text": "cols = pd.Index(['Unnamed:0', 'VALUE', 'VALUE.1', 'VALUE.2'])\nif df.columns.equals(cols):\n df = df.set_axis(df.iloc[0], axis=1).iloc[1:]\nprint(df)\n>>>\n Name Hobbies Dislikes Favorite Color\n1 Ben NaN NaN NaN None\n2 Alex NaN Running Red None\n3 Mike NaN Cartoons Blue None\n4 Mark NaN Pizza Yellow None\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18802483/"
] |
74,623,187
|
<p>"I want disable fade-in and fade-out animation after one time its apply on whole web page"</p>
<p>I need a pure JavaScript code which disable fade-in and fade-out animation after it apply one time</p>
<pre><code>.fade {
/* transition: opacity 0.9s ease-in;*/
opacity: 0;
}
.fade.visible {
transition: opacity 1s ease-in;
opacity: 1;
}
window.addEventListener('scroll', fade);
function fade()
{
let animation=document.querySelectorAll('.fade');
for (let i=0; i<animation.length; i++)
{
let windowheight=window.innerHeight;
let top=animation[i].getBoundingClientRect().top;
if (top < windowheight)
{
animation[i].classList.add('visible');
}
else
{
animation[i].classList.remove('visible');
}
}
}
</code></pre>
|
[
{
"answer_id": 74623361,
"author": "Liu Leo",
"author_id": 20641178,
"author_profile": "https://Stackoverflow.com/users/20641178",
"pm_score": 2,
"selected": false,
"text": "import pandas as pd\n\ndf = pd.DataFrame(columns=[\"Unnamed: 0\", \"VALUE\", \"VALUE.1\", \"VALUE.2\"])\ndf.loc[0] = ['Name', 'Hobbies', 'Dislikes', 'Favorite Color']\ndf.loc[1] = ['Ben', None, None, None]\n\nprint(df)\n\nif (df.columns == [\"Unnamed: 0\", \"VALUE\", \"VALUE.1\", \"VALUE.2\"]).all():\n df = df.drop([0])\n df.columns = ['Name', 'Hobbies', 'Dislikes', 'Favorite Color']\nprint()\nprint(df)\n Unnamed: 0 VALUE VALUE.1 VALUE.2\n0 Name Hobbies Dislikes Favorite Color\n1 Ben None None None\n\n Name Hobbies Dislikes Favorite Color\n1 Ben None None None\n"
},
{
"answer_id": 74623404,
"author": "ziying35",
"author_id": 16755671,
"author_profile": "https://Stackoverflow.com/users/16755671",
"pm_score": 3,
"selected": true,
"text": "cols = pd.Index(['Unnamed:0', 'VALUE', 'VALUE.1', 'VALUE.2'])\nif df.columns.equals(cols):\n df = df.set_axis(df.iloc[0], axis=1).iloc[1:]\nprint(df)\n>>>\n Name Hobbies Dislikes Favorite Color\n1 Ben NaN NaN NaN None\n2 Alex NaN Running Red None\n3 Mike NaN Cartoons Blue None\n4 Mark NaN Pizza Yellow None\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19052139/"
] |
74,623,259
|
<p><a href="https://i.stack.imgur.com/pnXwE.png" rel="nofollow noreferrer">Jupyter notebook</a></p>
<p>NOt able to write code because there is no cells.</p>
|
[
{
"answer_id": 74623361,
"author": "Liu Leo",
"author_id": 20641178,
"author_profile": "https://Stackoverflow.com/users/20641178",
"pm_score": 2,
"selected": false,
"text": "import pandas as pd\n\ndf = pd.DataFrame(columns=[\"Unnamed: 0\", \"VALUE\", \"VALUE.1\", \"VALUE.2\"])\ndf.loc[0] = ['Name', 'Hobbies', 'Dislikes', 'Favorite Color']\ndf.loc[1] = ['Ben', None, None, None]\n\nprint(df)\n\nif (df.columns == [\"Unnamed: 0\", \"VALUE\", \"VALUE.1\", \"VALUE.2\"]).all():\n df = df.drop([0])\n df.columns = ['Name', 'Hobbies', 'Dislikes', 'Favorite Color']\nprint()\nprint(df)\n Unnamed: 0 VALUE VALUE.1 VALUE.2\n0 Name Hobbies Dislikes Favorite Color\n1 Ben None None None\n\n Name Hobbies Dislikes Favorite Color\n1 Ben None None None\n"
},
{
"answer_id": 74623404,
"author": "ziying35",
"author_id": 16755671,
"author_profile": "https://Stackoverflow.com/users/16755671",
"pm_score": 3,
"selected": true,
"text": "cols = pd.Index(['Unnamed:0', 'VALUE', 'VALUE.1', 'VALUE.2'])\nif df.columns.equals(cols):\n df = df.set_axis(df.iloc[0], axis=1).iloc[1:]\nprint(df)\n>>>\n Name Hobbies Dislikes Favorite Color\n1 Ben NaN NaN NaN None\n2 Alex NaN Running Red None\n3 Mike NaN Cartoons Blue None\n4 Mark NaN Pizza Yellow None\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20096936/"
] |
74,623,286
|
<p>I have tried to switch values, numbers, variables, everything, and nothing seems to work. I am still quite new to arrays so I apologize if it is a simple fix.</p>
<p>The nested loop is supposed to find the smallest value in the array and then return it to the main method, however, every time I just get the first number in the array.
code:</p>
<pre><code> public static void main(String[] args) {
int[] arr = {2, 1, 4, 3, 6, 5, 8, 7};
int min;
min = findMin(arr);
System.out.println("Smallest value: " + min);
}
public static int findMin(int[] arr) {
int min = arr[0];
for (int i = 0; i < arr.length; i++) {
if (arr[i] < min) ;
{
min = arr[i];
}
}
return arr[min];
}
</code></pre>
|
[
{
"answer_id": 74623348,
"author": "HariHaravelan",
"author_id": 2816429,
"author_profile": "https://Stackoverflow.com/users/2816429",
"pm_score": 2,
"selected": true,
"text": "if if (arr[i] < min) \n {\n min = arr[i];\n }\n min arr[min]"
},
{
"answer_id": 74623389,
"author": "Asmeeta Rathod",
"author_id": 14990516,
"author_profile": "https://Stackoverflow.com/users/14990516",
"pm_score": 0,
"selected": false,
"text": "if(arr[i] < min); if(arr[i] < min) return arr[min]; return min;"
},
{
"answer_id": 74623413,
"author": "Miguel De Lara",
"author_id": 20391904,
"author_profile": "https://Stackoverflow.com/users/20391904",
"pm_score": 0,
"selected": false,
"text": "```` int[] arr = {2, 1, 4, 3, 6, 5, 8, 7};\n```` int min;\n```` min = findMin(arr);\n```` System.out.println(\"Smallest value: \" + min);\n```` }\n\n````public static int findMin(int[] arr)\n```` {\n```` int min = arr[0];\n```` for(int i = 0; i < arr.length; i++)\n```` {\n```` if(arr[i] < min);\n```` {\n```` min = arr[i];\n```` }\n```` }\n```` return min;\n```` }\n"
},
{
"answer_id": 74623444,
"author": "Jack",
"author_id": 20633571,
"author_profile": "https://Stackoverflow.com/users/20633571",
"pm_score": 0,
"selected": false,
"text": "int len = arr.length();\n return min;\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20443194/"
] |
74,623,289
|
<pre><code>/*
Importante:
No modificar ni el nombre ni los argumetos que reciben las funciones, sólo deben escribir
código dentro de las funciones ya definidas.
No comentar la funcion
*/
function stringMasLarga(strings) {
// La función llamada 'stringMasLarga', recibe como argumento un arreglo de strings llamado 'strings'
// y debe devolver el string más largo que hay en el arreglo (Es decir el de mayor cantidad de caracteres)
// Ej:
// stringMasLarga(['hi', 'hello', 'ni hao', 'guten tag']); debe retornar 'guten tag'
// stringMasLarga(['JavaScript', 'HTML', 'CSS']); debe retornar 'JavaScript'
// Tu código aca
let str = strings.sort(function (a,b) {
return b.length - a.length
}) [0]
return str;
}
// No modifiques nada debajo de esta linea //
module.exports = stringMasLarga
</code></pre>
<p>Alguien puede explicarme este codigo?
Can someone explain this code to me?</p>
<p>I cant understand [0].</p>
|
[
{
"answer_id": 74623348,
"author": "HariHaravelan",
"author_id": 2816429,
"author_profile": "https://Stackoverflow.com/users/2816429",
"pm_score": 2,
"selected": true,
"text": "if if (arr[i] < min) \n {\n min = arr[i];\n }\n min arr[min]"
},
{
"answer_id": 74623389,
"author": "Asmeeta Rathod",
"author_id": 14990516,
"author_profile": "https://Stackoverflow.com/users/14990516",
"pm_score": 0,
"selected": false,
"text": "if(arr[i] < min); if(arr[i] < min) return arr[min]; return min;"
},
{
"answer_id": 74623413,
"author": "Miguel De Lara",
"author_id": 20391904,
"author_profile": "https://Stackoverflow.com/users/20391904",
"pm_score": 0,
"selected": false,
"text": "```` int[] arr = {2, 1, 4, 3, 6, 5, 8, 7};\n```` int min;\n```` min = findMin(arr);\n```` System.out.println(\"Smallest value: \" + min);\n```` }\n\n````public static int findMin(int[] arr)\n```` {\n```` int min = arr[0];\n```` for(int i = 0; i < arr.length; i++)\n```` {\n```` if(arr[i] < min);\n```` {\n```` min = arr[i];\n```` }\n```` }\n```` return min;\n```` }\n"
},
{
"answer_id": 74623444,
"author": "Jack",
"author_id": 20633571,
"author_profile": "https://Stackoverflow.com/users/20633571",
"pm_score": 0,
"selected": false,
"text": "int len = arr.length();\n return min;\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20641499/"
] |
74,623,317
|
<p>Details of the program</p>
<p><a href="https://i.stack.imgur.com/10ZJL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/10ZJL.png" alt="enter image description here" /></a></p>
<p>(I am just a beginner learning visual studio)</p>
<p>I just tried to enter all the data types by creating a new component in typescript while comparing with my friends its showing different in colors</p>
|
[
{
"answer_id": 74623348,
"author": "HariHaravelan",
"author_id": 2816429,
"author_profile": "https://Stackoverflow.com/users/2816429",
"pm_score": 2,
"selected": true,
"text": "if if (arr[i] < min) \n {\n min = arr[i];\n }\n min arr[min]"
},
{
"answer_id": 74623389,
"author": "Asmeeta Rathod",
"author_id": 14990516,
"author_profile": "https://Stackoverflow.com/users/14990516",
"pm_score": 0,
"selected": false,
"text": "if(arr[i] < min); if(arr[i] < min) return arr[min]; return min;"
},
{
"answer_id": 74623413,
"author": "Miguel De Lara",
"author_id": 20391904,
"author_profile": "https://Stackoverflow.com/users/20391904",
"pm_score": 0,
"selected": false,
"text": "```` int[] arr = {2, 1, 4, 3, 6, 5, 8, 7};\n```` int min;\n```` min = findMin(arr);\n```` System.out.println(\"Smallest value: \" + min);\n```` }\n\n````public static int findMin(int[] arr)\n```` {\n```` int min = arr[0];\n```` for(int i = 0; i < arr.length; i++)\n```` {\n```` if(arr[i] < min);\n```` {\n```` min = arr[i];\n```` }\n```` }\n```` return min;\n```` }\n"
},
{
"answer_id": 74623444,
"author": "Jack",
"author_id": 20633571,
"author_profile": "https://Stackoverflow.com/users/20633571",
"pm_score": 0,
"selected": false,
"text": "int len = arr.length();\n return min;\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20641515/"
] |
74,623,353
|
<p>I have created a docker image from a spring application but there's an error where it's not able to access mysql database and I am having issues solving this.</p>
<p>I created an image using Dockerfile</p>
<pre><code>FROM openjdk:17-jdk-alpine
EXPOSE 8080
ARG JAR_FILE=./sample-service.jar
ADD ${JAR_FILE} app.jar
ENTRYPOINT ["java","-jar","/app.jar"]
</code></pre>
<p>after the image was created, I created docker-compose.yml, here's my docker-compose.yml:</p>
<pre><code>
version: "3"
services:
sample-service:
image: v2stechit/sample-service
ports:
- "8080:8080"
restart: always
environment:
SPRING_DATASOURCE_URL: jdbc:mysql://localhost:3306/buddyto_mstr_local?useSSL=false
SPRING_DATASOURCE_USERNAME: root
SPRING_DATASOURCE_PASSWORD: root
networks:
- spring-mysql
depends_on:
- mysqldb
mysqldb:
image: mysql:8.0.29
networks:
- spring-mysql
environment:
- MYSQL_ROOT_PASSWORD=root
- MYSQL_DATABASE=buddyto_mstr_local
- MYSQL_USERNAME=root
- MYSQL_PASSWORD=root
ports:
- 3306:3306
networks:
spring-mysql:
</code></pre>
<p>But it's not opening in browser so I checked the logs and got this:</p>
<p>Here's the spring docker container log: <a href="https://pastebin.com/raw/pjiscq4T" rel="nofollow noreferrer">https://pastebin.com/raw/pjiscq4T</a></p>
<p>Here's the mysql log:</p>
<pre><code>2022-11-30 05:18:01+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.29-1.el8 started.
2022-11-30 05:18:01+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
2022-11-30 05:18:01+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.29-1.el8 started.
'/var/lib/mysql/mysql.sock' -> '/var/run/mysqld/mysqld.sock'
2022-11-30T05:18:01.727948Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.29) starting as process 1
2022-11-30T05:18:01.744335Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
2022-11-30T05:18:01.892603Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
2022-11-30T05:18:02.206174Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
2022-11-30T05:18:02.206242Z 0 [System] [MY-013602] [Server] Channel mysql_main configured to support TLS. Encrypted connections are now supported for this channel.
2022-11-30T05:18:02.209090Z 0 [Warning] [MY-011810] [Server] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.
2022-11-30T05:18:02.251051Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Bind-address: '::' port: 33060, socket: /var/run/mysqld/mysqlx.sock
2022-11-30T05:18:02.251175Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.29' socket: '/var/run/mysqld/mysqld.sock' port: 3306 MySQL Community Server - GPL.
</code></pre>
<p>How do I solve this?</p>
<p>I tried using the empty password environment variable for mysql.</p>
<p>tried changing database names, changing mysql versions to 5.6, 8 and 8.0.29</p>
<p>I am not sure what to do next.</p>
<p>I am expecting for spring application to link with mysql</p>
|
[
{
"answer_id": 74623348,
"author": "HariHaravelan",
"author_id": 2816429,
"author_profile": "https://Stackoverflow.com/users/2816429",
"pm_score": 2,
"selected": true,
"text": "if if (arr[i] < min) \n {\n min = arr[i];\n }\n min arr[min]"
},
{
"answer_id": 74623389,
"author": "Asmeeta Rathod",
"author_id": 14990516,
"author_profile": "https://Stackoverflow.com/users/14990516",
"pm_score": 0,
"selected": false,
"text": "if(arr[i] < min); if(arr[i] < min) return arr[min]; return min;"
},
{
"answer_id": 74623413,
"author": "Miguel De Lara",
"author_id": 20391904,
"author_profile": "https://Stackoverflow.com/users/20391904",
"pm_score": 0,
"selected": false,
"text": "```` int[] arr = {2, 1, 4, 3, 6, 5, 8, 7};\n```` int min;\n```` min = findMin(arr);\n```` System.out.println(\"Smallest value: \" + min);\n```` }\n\n````public static int findMin(int[] arr)\n```` {\n```` int min = arr[0];\n```` for(int i = 0; i < arr.length; i++)\n```` {\n```` if(arr[i] < min);\n```` {\n```` min = arr[i];\n```` }\n```` }\n```` return min;\n```` }\n"
},
{
"answer_id": 74623444,
"author": "Jack",
"author_id": 20633571,
"author_profile": "https://Stackoverflow.com/users/20633571",
"pm_score": 0,
"selected": false,
"text": "int len = arr.length();\n return min;\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20641267/"
] |
74,623,368
|
<p>I am trying to click 1 Min button on this <a href="https://www.investing.com/technical/technical-analysis" rel="nofollow noreferrer">site</a></p>
<p>below is my python code</p>
<pre><code>url = 'https://www.investing.com/technical/technical-analysis'
driver.get(url)
events = WebDriverWait(driver, 30).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "section#leftColumn")))
print("Required elements found")
events.find_element(By.XPATH,"//a[text()='1 Min']").click()
</code></pre>
<p>Am getting the following error:
events.find_element(By.XPATH,"//a[text()='1 Min']").click()
AttributeError: 'list' object has no attribute 'find_element'</p>
<p>What can I change in the code to click the '1 Min' button succesfully?</p>
|
[
{
"answer_id": 74623873,
"author": "AbiSaran",
"author_id": 7671727,
"author_profile": "https://Stackoverflow.com/users/7671727",
"pm_score": 2,
"selected": true,
"text": "'for' 'events' events = WebDriverWait(driver, 30).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, \"section#leftColumn\")))\nprint(\"Required elements found\")\nfor event in events:\n event.find_element(By.XPATH,\"//a[text()='1 Min']\").click()\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12583731/"
] |
74,623,407
|
<p>I have looked for the past hour at least but to no avail. I'm writing a text based adventure game and I have an ArrayList storing my inventory. I am currently working on a "displayInventory" method which simply prints the inventory to console.</p>
<pre><code>public void displayInventory()
{
StringBuilder result = new StringBuilder("Inventory: \n");
String format = ("%s, %s, %s %n");
for (int i=0; i< inventory.size(); i++)
{
result.append(inventory.get(i));
}
//String result = String.join("," inventory);
System.out.format(format, result.toString());;
}
</code></pre>
<p>Now initially my issue was figuring out how to use it with StringBuilder but now I sort of have that down. But I've run into the issue where I've set the format to three strings(items from inventory) to be printed to each line. After testing it with only two items I get the errors below (which makes sense).</p>
<pre><code>Inventory:
Small BottleLarge Bottle, Exception in thread "main" java.util.MissingFormatArgumentException: Format specifier '%s'
at java.base/java.util.Formatter.format(Formatter.java:2688)
at java.base/java.io.PrintStream.format(PrintStream.java:1209)
at wonderland/gameObjects.Player.displayInventory(Player.java:41)
at wonderland/gameObjects.Test.main(Test.java:19)
</code></pre>
<p>Do I need to set up some sort of check to see if there is a multiple of three items in the players inventory and have different print statements/formats if not? Is there a way to format an unknown amount (or at least a varying amount) of strings?</p>
<p>The player could pick three items up, use one, then pick up another two. I need some way of displaying the varying amount of items that could be in their inventory.</p>
<p>I hate asking questions on SO because they almost always get declared duplicates, despite no case being identical. So I was really hesitant but couldn't take the head trauma any longer. Thank you in advance for any and all help/answers.</p>
|
[
{
"answer_id": 74623913,
"author": "モキャデ",
"author_id": 20607467,
"author_profile": "https://Stackoverflow.com/users/20607467",
"pm_score": 3,
"selected": true,
"text": "String.join() List<String> inventory = List.of(\n \"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\",\n \"J\", \"K\", \"L\", \"M\", \"N\", \"O\", \"P\", \"Q\");\n\npublic void displayInventory() { \n System.out.println(\"Inventory:\");\n for (int i = 0, size = inventory.size(); i < size; i += 3)\n System.out.println(String.join(\", \",\n inventory.subList(i, Math.min(i + 3, size))));\n} \n displayInentory();\n Inventory:\nA, B, C\nD, E, F\nG, H, I\nJ, K, L\nM, N, O\nP, Q\n"
},
{
"answer_id": 74624211,
"author": "tresf",
"author_id": 3196753,
"author_profile": "https://Stackoverflow.com/users/3196753",
"pm_score": 0,
"selected": false,
"text": "PrintStream.format() List inventory = List.of(\"Shovel\", \"Dirt\", \"Magazine\", \"Marble\", \"Orange\", \"Knife\", \"Popsicle\");\n\nStringBuilder format = new StringBuilder();\nfor(int i = 0; i < inventory.size(); i++) {\n if(i == 0) {\n // first item, prepend \"Inventory:\"\n format.append(\"Inventory:%n%s\");\n } else if(i == inventory.size() -1) {\n // last item, don't prepend or append\n format.append(\"%s\");\n } else if(i % 3 == 2) {\n // third item, append newline\n format.append(\"%s%n\");\n } else if(i < inventory.size() -1) {\n // 1st or 2nd item, append comma and space\n format.append(\"%s, \");\n }\n}\n\nSystem.out.println(\"Format: \\n\" + format + \"\\n\");\nSystem.out.format(format.toString(), inventory.toArray());;\n Format: \nInventory:%n%s%s, %s%n%s, %s, %s%n%s\n\nInventory:\nShovelDirt, Magazine\nMarble, Orange, Knife\nPopsicle\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16893190/"
] |
74,623,428
|
<p>I've been trying to replace a view in <strong>React Native</strong>, but to no success. The app closes without errors whenever I try <code><TouchableOpacity onPress={() => {handleChangeMyView();}}></code> :</p>
<p>What am I doing wrong? How can I make it work?</p>
<p>Thank you all in advance.</p>
<pre><code>import React, {
useState
} from 'react';
import {
SafeAreaView,
View,
} from 'react-native';
import MyInitialView from './MyInitialView';
const SiteContainer = () => {
let MyDynamicView = () => {
return (
<View></View>
);
};
const [MyDynamicViewArea, setMyDynamicViewArea] = useState(MyInitialView);
const handleChangeMyView = () => {
setMyDynamicViewArea(MyDynamicView);
};
return (
<SafeAreaView style={styles.siteContainer}>
{MyDynamicViewArea}
<TouchableOpacity onPress={() => {handleChagnStaceMyView();}}>
<View>
<FontAwesome name="quote-left"></FontAwesome>
</View>
</TouchableOpacity>
</SafeAreaView>
);
};
export default SiteContainer;
</code></pre>
<p><strong>MyInitialView</strong> :</p>
<pre><code>import React from 'react';
import {
View
} from 'react-native';
export default function MyInitialView() {
return (
<View></View>
);
}
</code></pre>
|
[
{
"answer_id": 74623913,
"author": "モキャデ",
"author_id": 20607467,
"author_profile": "https://Stackoverflow.com/users/20607467",
"pm_score": 3,
"selected": true,
"text": "String.join() List<String> inventory = List.of(\n \"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\",\n \"J\", \"K\", \"L\", \"M\", \"N\", \"O\", \"P\", \"Q\");\n\npublic void displayInventory() { \n System.out.println(\"Inventory:\");\n for (int i = 0, size = inventory.size(); i < size; i += 3)\n System.out.println(String.join(\", \",\n inventory.subList(i, Math.min(i + 3, size))));\n} \n displayInentory();\n Inventory:\nA, B, C\nD, E, F\nG, H, I\nJ, K, L\nM, N, O\nP, Q\n"
},
{
"answer_id": 74624211,
"author": "tresf",
"author_id": 3196753,
"author_profile": "https://Stackoverflow.com/users/3196753",
"pm_score": 0,
"selected": false,
"text": "PrintStream.format() List inventory = List.of(\"Shovel\", \"Dirt\", \"Magazine\", \"Marble\", \"Orange\", \"Knife\", \"Popsicle\");\n\nStringBuilder format = new StringBuilder();\nfor(int i = 0; i < inventory.size(); i++) {\n if(i == 0) {\n // first item, prepend \"Inventory:\"\n format.append(\"Inventory:%n%s\");\n } else if(i == inventory.size() -1) {\n // last item, don't prepend or append\n format.append(\"%s\");\n } else if(i % 3 == 2) {\n // third item, append newline\n format.append(\"%s%n\");\n } else if(i < inventory.size() -1) {\n // 1st or 2nd item, append comma and space\n format.append(\"%s, \");\n }\n}\n\nSystem.out.println(\"Format: \\n\" + format + \"\\n\");\nSystem.out.format(format.toString(), inventory.toArray());;\n Format: \nInventory:%n%s%s, %s%n%s, %s, %s%n%s\n\nInventory:\nShovelDirt, Magazine\nMarble, Orange, Knife\nPopsicle\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3663765/"
] |
74,623,434
|
<p>I am trying to display API data into a listview builder and when I try to call the data the response is 200 and there is no error.</p>
<p><a href="https://i.stack.imgur.com/Lhzgb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Lhzgb.png" alt="enter image description here" /></a></p>
<p>however, the data does not appear when you want to display it to the user.
<a href="https://i.stack.imgur.com/Y74zU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Y74zU.png" alt="enter image description here" /></a></p>
<p>Is there anyone here who has had a problem like mine?
if so, how did you handle it?
Thank You.</p>
<p>and this is the function when i call data API</p>
<pre><code>Future<NilaiMahasiswa> getNilaiMahasiswa() async {
String url = Constant.baseURL;
String token = await UtilSharedPreferences.getToken();
final response = await http.get(
Uri.parse(
'$url/auth/mhs_siakad/transkrip_nilai',
),
headers: {
'Authorization': 'Bearer $token',
},
);
print(response.statusCode);
print(response.body);
if (response.statusCode == 200) {
return NilaiMahasiswa.fromJson(jsonDecode(response.body));
} else {
throw Exception();
}
}
</code></pre>
<p>the following is when I display the data to the user</p>
<pre><code>class _NilaiMahasiswaPageState extends State<NilaiMahasiswaPage> {
List? data = [];
@override
void initState() {
super.initState();
Services().getNilaiMahasiswa();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: PreferredSize(
preferredSize: const Size.fromHeight(kToolbarHeight),
child: CustomAppbar(
title: 'Nilai Mahasiswa',
),
),
body: ListView.builder(
itemCount: data!.length,
itemBuilder: (BuildContext context, index) {
return Padding(
padding: const EdgeInsets.only(left: 12, right: 12, top: 12),
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: const BorderRadius.all(
Radius.circular(8),
),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.2),
spreadRadius: 1,
blurRadius: 9,
offset: const Offset(
1,
2,
),
),
],
),
width: double.infinity,
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
data![index]["id_mk"],
style: const TextStyle(fontSize: 16),
),
const SizedBox(
height: 12,
),
Text(
data![index]['nm_mk'],
),
],
), ...
</code></pre>
<p>and this model</p>
<pre><code>class NilaiMahasiswa {
String? status;
String? code;
List<Data>? data;
NilaiMahasiswa({this.status, this.code, this.data});
NilaiMahasiswa.fromJson(Map<String, dynamic> json) {
status = json['status'];
code = json['code'];
if (json['data'] != null) {
data = <Data>[];
json['data'].forEach((v) {
data!.add(Data.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['status'] = status;
data['code'] = code;
if (this.data != null) {
data['data'] = this.data!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Data {
String? idTranskripNilai;
String? idMk;
String? kodeMk;
String? nmMk;
int? sks;
int? smt;
String? nilaiAkhirUts;
String? nilaiHurufUts;
String? nilaiIndeksUts;
String? nilaiAkhirUas;
String? nilaiAkhir;
String? nilaiHurufAkhir;
String? nilaiIndeksAkhir;
int? statusNilaiAkhir;
int? statusNilaiUts;
String? updatedBy;
Data(
{this.idTranskripNilai,
this.idMk,
this.kodeMk,
this.nmMk,
this.sks,
this.smt,
this.nilaiAkhirUts,
this.nilaiHurufUts,
this.nilaiIndeksUts,
this.nilaiAkhirUas,
this.nilaiAkhir,
this.nilaiHurufAkhir,
this.nilaiIndeksAkhir,
this.statusNilaiAkhir,
this.statusNilaiUts,
this.updatedBy});
Data.fromJson(Map<String, dynamic> json) {
idTranskripNilai = json['id_transkrip_nilai'];
idMk = json['id_mk'];
kodeMk = json['kode_mk'];
nmMk = json['nm_mk'];
sks = json['sks'];
smt = json['smt'];
nilaiAkhirUts = json['nilai_akhir_uts'];
nilaiHurufUts = json['nilai_huruf_uts'];
nilaiIndeksUts = json['nilai_indeks_uts'];
nilaiAkhirUas = json['nilai_akhir_uas'];
nilaiAkhir = json['nilai_akhir'];
nilaiHurufAkhir = json['nilai_huruf_akhir'];
nilaiIndeksAkhir = json['nilai_indeks_akhir'];
statusNilaiAkhir = json['status_nilai_akhir'];
statusNilaiUts = json['status_nilai_uts'];
updatedBy = json['updated_by'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['id_transkrip_nilai'] = this.idTranskripNilai;
data['id_mk'] = this.idMk;
data['kode_mk'] = this.kodeMk;
data['nm_mk'] = this.nmMk;
data['sks'] = this.sks;
data['smt'] = this.smt;
data['nilai_akhir_uts'] = this.nilaiAkhirUts;
data['nilai_huruf_uts'] = this.nilaiHurufUts;
data['nilai_indeks_uts'] = this.nilaiIndeksUts;
data['nilai_akhir_uas'] = this.nilaiAkhirUas;
data['nilai_akhir'] = this.nilaiAkhir;
data['nilai_huruf_akhir'] = this.nilaiHurufAkhir;
data['nilai_indeks_akhir'] = this.nilaiIndeksAkhir;
data['status_nilai_akhir'] = this.statusNilaiAkhir;
data['status_nilai_uts'] = this.statusNilaiUts;
data['updated_by'] = this.updatedBy;
return data;
}
}
</code></pre>
|
[
{
"answer_id": 74623623,
"author": "Alwayss Bijoy",
"author_id": 8312884,
"author_profile": "https://Stackoverflow.com/users/8312884",
"pm_score": 1,
"selected": false,
"text": "NilaiMahasiswa? responseData;\n\n@override\n void initState() {\n super.initState();\n getResponseData();\n }\n\ngetResponseData()async{\n final response = await Services().getNilaiMahasiswa();\n responseData = response.data; //if response isn't work then use **response** only.\n}\n"
},
{
"answer_id": 74623870,
"author": "K K Muhammed Fazil",
"author_id": 11922179,
"author_profile": "https://Stackoverflow.com/users/11922179",
"pm_score": 3,
"selected": true,
"text": " List<Data> data = [];\n \n @override\n void initState() {\n super.initState();\n fetchData();\n }\n\n fetchData()async{\n final apiResponse = await Services().getNilaiMahasiswa();\n setState(() {\n data.addAll(apiResponse.data!);\n });\n }\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19132574/"
] |
74,623,448
|
<p>I have a string, for example:</p>
<pre><code>s = "I ? am ? a ? string"
</code></pre>
<p>And I have a list equal in length to the number of <code>?</code> in the string:</p>
<pre><code>l = ['1', '2', '3']
</code></pre>
<p>What is a pythonic way to return <code>s</code> with each consecutive <code>?</code> replaced with the values in <code>l</code>?, e.g.:</p>
<pre><code>s_new = 'I 1 am 2 a 3 string'
</code></pre>
|
[
{
"answer_id": 74623623,
"author": "Alwayss Bijoy",
"author_id": 8312884,
"author_profile": "https://Stackoverflow.com/users/8312884",
"pm_score": 1,
"selected": false,
"text": "NilaiMahasiswa? responseData;\n\n@override\n void initState() {\n super.initState();\n getResponseData();\n }\n\ngetResponseData()async{\n final response = await Services().getNilaiMahasiswa();\n responseData = response.data; //if response isn't work then use **response** only.\n}\n"
},
{
"answer_id": 74623870,
"author": "K K Muhammed Fazil",
"author_id": 11922179,
"author_profile": "https://Stackoverflow.com/users/11922179",
"pm_score": 3,
"selected": true,
"text": " List<Data> data = [];\n \n @override\n void initState() {\n super.initState();\n fetchData();\n }\n\n fetchData()async{\n final apiResponse = await Services().getNilaiMahasiswa();\n setState(() {\n data.addAll(apiResponse.data!);\n });\n }\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1733467/"
] |
74,623,450
|
<p>For a project in school, I was asked to write a program that loops through the values in an ArrayList named <em>revenues</em> and prints whether or not if the numbers withen <em>revenues</em> increased, decreased, or stayed the same while it went through the ArrayList.</p>
<p>This is what I wrote</p>
<pre><code> System.out.println("Year 1: No comperison");
for (int i = 0; i < revenues.size(); i = i + 1){
if (revenues.get(i) < revenues.get(i+1)){
System.out.println("Year "+ (i) +": increased");
} else if (revenues.get(i) > revenues.get(i+1)){
System.out.println("Year "+ (i) +": decreased");
} else {
System.out.println("Year "+ (i) +": stayed the same");
}
}
</code></pre>
<p>But whenever I ran the program, it shows me an error message because of this code.</p>
<p>This is the error</p>
<pre><code>Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 5 out of bounds for length 5
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:100)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:106)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:302)
at java.base/java.util.Objects.checkIndex(Objects.java:359)
at java.base/java.util.ArrayList.get(ArrayList.java:427)
</code></pre>
|
[
{
"answer_id": 74623623,
"author": "Alwayss Bijoy",
"author_id": 8312884,
"author_profile": "https://Stackoverflow.com/users/8312884",
"pm_score": 1,
"selected": false,
"text": "NilaiMahasiswa? responseData;\n\n@override\n void initState() {\n super.initState();\n getResponseData();\n }\n\ngetResponseData()async{\n final response = await Services().getNilaiMahasiswa();\n responseData = response.data; //if response isn't work then use **response** only.\n}\n"
},
{
"answer_id": 74623870,
"author": "K K Muhammed Fazil",
"author_id": 11922179,
"author_profile": "https://Stackoverflow.com/users/11922179",
"pm_score": 3,
"selected": true,
"text": " List<Data> data = [];\n \n @override\n void initState() {\n super.initState();\n fetchData();\n }\n\n fetchData()async{\n final apiResponse = await Services().getNilaiMahasiswa();\n setState(() {\n data.addAll(apiResponse.data!);\n });\n }\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623450",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20641596/"
] |
74,623,457
|
<p>I know we can auto delete branches when PR gets merged on Github. Is there a way we can get branches to auto delete when PR is closed?</p>
<p>I do not see an option in Settings tab of Repo for deleting branches when PR gets closed</p>
|
[
{
"answer_id": 74637236,
"author": "dtandon",
"author_id": 6463240,
"author_profile": "https://Stackoverflow.com/users/6463240",
"pm_score": 2,
"selected": true,
"text": " steps:\n - name: Delete closed PR branch\n uses: dawidd6/action-delete-branch@v3\n with:\n github_token: ${{github.token}}\n numbers: ${{github.event.pull_request.number}}\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6463240/"
] |
74,623,458
|
<p>I am having difficulty figuring out to make user-entered lists of numbers equal a quadrilateral, specifically a rhombus and square, in Python. I do not know if my code needs a function or loops or if/else statements to know if it is a rhombus or square.</p>
<p>So far, I have this, but I can't figure out how to go through each side to find out if they are equal to each other or if angle 1 equals angle 2, etc. Which afterwards, I would determine if it the numbers that the user entered made a list that equaled a rhombus or square. Excuse the confusing sentences, I tried to make my problem as clear as possible. Thank you for taking your time to help, if you do!</p>
<p>Edit: I tried a function, but found that it was too complicated by itself. I want to figure out how to search through each list's elements and make sure that they equal/match each other. Thank you!</p>
<p>A rhombus has</p>
<ol>
<li>All four sides the same length</li>
<li>Angle 1 equals Angle 3</li>
<li>Angle 2 equals Angle 4</li>
</ol>
<p>A square has</p>
<ol>
<li>All four sides the same length.</li>
<li>All angles equal to each other</li>
</ol>
<pre><code>while True:
# Input, Validation, Repetition
print("=== Please enter Sides ===\n")
sList = [] # list for sides
for i in range(0,4,1):
sides = float(input("Please enter side %i : " %(i + 1 ) ) )
if sides < 0:
sides = float(input("Value must be positive! Please enter side %i : " %(i + 1 )))
sList.append(sides)
print()
print("=== Please enter angles ===\n")
aList = [] # list for angles
for i in range(0,4,1):
angles = float(input("Please enter angle %i : " %(i + 1 ) ) )
if angles < 0:
angles = float(input("Value must be positive! Please enter angle %i : " %(i + 1 )))
aList.append(angles)
print("=======================\n")
# Rhombus
if sList == sList and aList[1] == aList[3] and aList[2] == aList[4]:
print("This is a rhombus\n")
#Square
if sList == aList:
print("This is a square!\n")
keep = input("Would you like to repeat? (1-Yes, 2-No): ")
if keep != '1':
break
</code></pre>
|
[
{
"answer_id": 74637236,
"author": "dtandon",
"author_id": 6463240,
"author_profile": "https://Stackoverflow.com/users/6463240",
"pm_score": 2,
"selected": true,
"text": " steps:\n - name: Delete closed PR branch\n uses: dawidd6/action-delete-branch@v3\n with:\n github_token: ${{github.token}}\n numbers: ${{github.event.pull_request.number}}\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18320598/"
] |
74,623,463
|
<p>i have a edit form with filled input , the values are shown on textField accordingly but on DropDown it's not showing default value , [<a href="https://i.stack.imgur.com/reuQj.png" rel="nofollow noreferrer">check Select</a>] , [<a href="https://i.stack.imgur.com/hfqhZ.png" rel="nofollow noreferrer">check other Fields</a>]</p>
<pre><code> <Select
name="active"
labelId="active-label"
id="active"
onChange={handleChange}
onBlur={handleBlur}
value={values.active}
defaultValue={values.active}
error={touched.active && Boolean(errors.active)}
>
<MenuItem value={true}>Yes</MenuItem>
<MenuItem value={false}>No</MenuItem>
</Select>
</code></pre>
<p>i just want to display this default value too , it can be solved if i used option insted of meanuItem but option will not display dropdown items as i want check my code below and image for display <a href="https://i.stack.imgur.com/t1in2.jpg" rel="nofollow noreferrer">dropdown with option</a></p>
<pre><code> <Select
native
name="active"
labelId="active-label"
id="active"
onChange={handleChange}
onBlur={handleBlur}
value={values.active}
defaultValue={values.active}
>
<option value={true} >Yes</option>
<option value={false}>No</option>
</Select>
</code></pre>
<p>the code for user binding with values :</p>
<pre><code>const [user, setUser] = useState({});
async function getData(id) {
const fetchedUser = await fetch(`${state.baseUrl}users/${id}`, {
method: "GET",
headers: {
Authorization: `Bearer ${state.loginToken}`,
},
})
.then((response) => response.json())
.catch((err) => console.error(err));
setUser(fetchedUser);}
useEffect(() => {
getData(id);
}, []);
const initialValues = {
fullName: user.fullname,
email: user.email,
userName: user.username,
organ: String(user.organization),
password: "",
role: String(user.role),
active: user.is_active};
</code></pre>
|
[
{
"answer_id": 74637236,
"author": "dtandon",
"author_id": 6463240,
"author_profile": "https://Stackoverflow.com/users/6463240",
"pm_score": 2,
"selected": true,
"text": " steps:\n - name: Delete closed PR branch\n uses: dawidd6/action-delete-branch@v3\n with:\n github_token: ${{github.token}}\n numbers: ${{github.event.pull_request.number}}\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19776108/"
] |
74,623,467
|
<p>I am evaluating frequencies using sample data in the snipped file below.</p>
<p>I have noticed that with an unordered list, the evaluation takes less than a second to return a result. However, with a vector, it takes almost a whole minute to evaluate it!</p>
<p>There are several factors I considered:</p>
<ul>
<li>Size of the data</li>
<li>The data itself</li>
</ul>
<p>After several experiments, I found that if I took out the 2nd to last data (-6) the performance is almost identical and results are returned for both in less than a second!</p>
<p><a href="https://i.stack.imgur.com/zi2s7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zi2s7.png" alt="result immediate" /></a></p>
<p>However, if I include the -6, the vector evaluation takes too long!</p>
<p><a href="https://i.stack.imgur.com/SmOXB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SmOXB.png" alt="result bad" /></a></p>
<p>I tried changing the number like -5, -4, etc. and the performance was actually pretty good!</p>
<p><a href="https://i.stack.imgur.com/Cep6V.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Cep6V.png" alt="result good" /></a></p>
<p>For some reason, only -6 before the last data/number (+125503) in the file seems to be affecting the vector performance...what's going on?</p>
<p><strong>Note:</strong> of course, I tried running them individually too by commenting out the unorderedlist logic and then the vector logic, same behavior</p>
<p><strong>code:</strong></p>
<pre><code>#include <algorithm>
#include <unordered_set>
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;
vector<int> scanFile(ifstream &file) {
vector<int> scannedFile;
string str;
while (getline(file, str)) {
scannedFile.push_back(stoi(str));
}
return scannedFile;
}
int main() {
ifstream inputFile;
vector<int> fileInfo;
string str = "";
inputFile.open("file.txt");
fileInfo = scanFile(inputFile);
inputFile.close();
int Occurrences = 0;
unordered_set<int> unordrdList; //results are immediate, even with -6!
bool found = false;
unordrdList.insert(Occurrences);
while (!found) {
for (int n : fileInfo) {
Occurrences += n;
found = unordrdList.find(Occurrences) != unordrdList.end();
unordrdList.insert(Occurrences);
if (found) {
cout << "Using Unordered_Set: The 2nd showing #: " << to_string(Occurrences) << endl;
break;
}
}
}
int Occurrnce = 0;
vector<int> vectr; //result takes too long with -6 present in the file before 2nd to last line!
bool found2 = false;
vectr.push_back(Occurrnce);
while (!found2) {
for (int n : fileInfo) {
Occurrnce += n;
found2 = find(vectr.begin(), vectr.end(), Occurrnce) != vectr.end();
vectr.push_back(Occurrnce);
if (found2) {
cout << "Using Vector: The 2nd showing #: " << to_string(Occurrnce) << endl;
break;
}
}
}
}
</code></pre>
<p><strong>text file:</strong></p>
<pre><code>-5
-2
+1
+14
+7
+5
-14
-4
-5
-12
+7
-5
+17
+5
-13
-12
+15
+22
-5
-6
-12
+20
+4
+2
+17
-1
+18
-7
-1
-17
+11
-12
-5
-2
+9
+2
-6
-17
-1
+2
-3
+15
+19
+9
-8
+13
+1
+11
+16
+3
-16
-7
-15
-15
+12
+16
+18
+1
-9
+16
-9
-19
+17
+1
-15
+13
-9
-8
-1
+7
+17
+13
+15
-17
-3
+12
-10
+5
+4
-16
+15
+3
+19
+1
-2
+19
-16
-11
+4
-10
-8
+13
+13
+19
-6
-19
+1
-4
+18
+15
+16
-18
+12
+3
-9
+8
+3
-9
+11
+4
+8
+1
+6
-10
-3
+15
+16
+15
+12
-14
+4
-14
-7
-3
+14
+4
+3
-6
-7
+11
-2
-18
+17
-3
+14
+18
+6
+8
+18
-13
-7
+17
-18
-10
-15
+13
-16
+5
-10
+15
-8
-4
+14
+13
-10
-14
+7
+5
+13
-4
+12
+3
+14
-7
+6
+12
+17
-18
+3
-6
-3
-14
-1
+13
+19
+3
+9
+4
+11
+12
+3
+1
+14
+7
-17
+12
+11
+6
-7
+4
-11
-1
+6
-19
-10
-16
-2
-19
+7
+9
-3
+5
+12
+15
+8
+11
+1
+8
+15
-9
-9
-8
-10
-3
-16
+7
-17
+9
-5
+16
-15
-4
+15
-5
-25
-6
+1
+4
+17
+19
-13
+17
+7
+19
+2
+4
+10
+16
-9
+19
+13
+3
-10
+9
+5
+1
+18
-11
-14
-4
-5
-13
-7
-12
+2
+3
+6
-16
-1
+13
-10
-4
-1
-3
+9
+22
+4
-18
+17
+11
-21
-17
-18
-8
+12
+6
+15
+12
+10
-7
+18
+10
-8
-10
-18
+11
-17
+25
+15
-9
-19
+38
-3
-6
-23
+34
-25
-5
-12
+25
+14
+17
+30
+3
+9
-8
+16
+21
+21
+4
-12
+23
-13
+9
+3
+6
+13
+15
+6
-7
+15
+12
-10
+13
+12
-7
+13
+4
-9
+18
-10
+5
+8
-7
+2
-14
-12
-1
-6
-16
-18
-3
+1
+12
-6
+15
-17
+15
+13
+6
-15
+26
+1
-21
-3
-21
-4
+14
-1
-19
-11
+13
-10
-14
+2
-17
-23
+25
-16
+8
-30
+17
-44
+13
-19
+5
-9
-12
+10
+14
+17
+24
-15
+7
-61
-103
-18
+21
-22
-6
-9
-6
-9
-7
-15
-17
+4
-1
+10
+8
+14
-4
+15
-16
-6
-16
-15
-12
+15
+10
-15
+3
+15
-10
-17
+3
-5
-12
+4
+3
-37
-7
+14
-18
-8
+6
-11
+14
+30
+7
+23
+39
-12
+11
-8
+11
-1
+56
-28
-12
+7
+34
+47
+21
+88
+61
+18
+10
-99
-287
+26
-858
-209
-61255
+2
-7
-8
+12
+18
+17
-14
-2
+14
+4
+3
+3
-15
+21
+3
+20
+1
+3
-1
-25
-2
+7
-9
+17
-19
-6
-13
+2
-4
-3
-14
-8
+12
-20
+17
-40
+11
+3
-20
-16
-18
-3
-6
-10
+4
+20
-12
-3
+11
+16
-2
+4
-9
+28
-12
+5
+17
-13
+35
+25
+2
+35
-17
-8
+31
+3
-39
-46
+3
-96
-18
-14
-14
-12
+9
+15
+3
+18
-8
+1
-2
-15
+13
+14
-13
-3
+7
-11
-15
-17
-12
-15
-17
+9
+7
-10
-8
-3
+9
+16
+3
+15
-14
-5
-9
+1
-3
+10
+3
-18
-21
-11
+2
-17
-17
-7
-11
+8
+11
-2
-7
-1
-19
-2
-16
+1
+5
+11
+18
+5
+17
+2
-5
-2
+19
-4
+12
+2
+20
-13
-20
-12
+10
+4
+14
-1
+12
+13
-10
-13
-8
-1
+14
+16
+6
+10
+18
+19
+14
-1
+6
-13
-9
+10
-20
+1
+1
-12
+6
+7
-15
-13
-2
+14
-19
-5
-10
-17
+15
-5
+8
+20
+9
+14
-6
+4
-3
+19
+18
-14
-3
-8
+4
+16
+7
-3
-5
+19
-2
+12
+19
+12
-10
-17
-40
+1
-11
+19
-27
-9
+45
-27
+31
+1
-25
+41
+58
-5
-39
-112
+1
-8
-3
-6
-15
-3
-9
+13
+13
-24
+3
-4
+13
-19
-21
+16
-20
-10
-15
-16
-1
-13
-12
-17
+16
+17
+16
-2
-9
-1
-19
+8
+5
-18
+17
-19
-19
-12
+14
-18
-12
+10
+9
-13
-8
+19
+16
+13
-5
+2
+16
-15
+17
+9
+10
+2
-5
+20
+16
-8
-4
+16
+6
-7
-2
-11
+18
+11
-1
+2
+5
+3
+40
-38
+22
-11
-15
-27
+7
-25
+4
-11
-15
-12
+15
-20
-13
+9
-13
+7
-5
+10
+18
+24
+8
+15
-6
-10
-10
-1
-4
-3
-17
+7
-15
+20
-19
-18
-14
-4
-26
-22
-5
+17
+6
+13
+9
+7
+28
-11
-8
+57
-23
-37
-11
-43
+3
-14
+3
-14
+13
-15
+6
-23
+8
+12
-8
+15
+16
+2
-9
-14
+18
+19
-1
-43
-2
-3
-13
+5
-6
-13
-20
+15
+13
-12
+3
+2
+3
+11
+7
-17
-8
-13
+18
-17
-2
-13
+5
+3
+1
-11
+20
+4
+2
-1
-19
-8
-19
+1
-6
-12
+8
-6
-5
+1
+6
+9
-12
+13
+10
-14
+20
-11
+9
+9
-3
-18
+9
-5
+9
+2
-9
-19
-4
-10
+7
-8
+68
+30
+2
-9
+12
-65
+15
-26
-9
-15
-67
-38
-36
-37
-7
+18
-20
-44
+35
-70
-85
+14
+18
-499
+209
-61690
-5
+15
-4
+3
+5
+6
+15
+16
+3
-4
+12
-14
-7
-9
-15
+2
-1
-11
-21
-8
-2
-15
+19
+7
-10
-19
-3
-14
+4
+9
+13
-16
-14
+2
+10
-19
+6
+16
+11
+7
-14
-9
-21
-7
-12
+2
+12
-6
+125503
</code></pre>
|
[
{
"answer_id": 74627435,
"author": "AlexGeorg",
"author_id": 12251738,
"author_profile": "https://Stackoverflow.com/users/12251738",
"pm_score": 1,
"selected": false,
"text": "List<> find() find()"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8397835/"
] |
74,623,481
|
<p>In this code, when the input is empty and you press submit, an error message pops up, but it pushes the button down, I’m trying to prevent the button from getting pushed down. How can I do this?</p>
<p>This code is also available as a <a href="https://codepen.io/zcode99/pen/rNKZWBp" rel="nofollow noreferrer">CodePen</a>.</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 form = document.getElementById("form");
const input = document.getElementById("input");
form.addEventListener("submit", function(e) {
e.preventDefault();
const name = input.value;
if (name === "") {
addError("Input field cannot be empty");
}
});
function addError(message) {
const small = document.querySelector("small");
small.classList.add("error");
small.innerText = message;
small.style.display = "block";
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
box-sizing: border-box;
}
body {
font-family: Arial, Helvetica, sans-serif;
}
.card {
display: flex;
min-height: 100vh;
justify-content: center;
align-items: center;
}
form {
display: flex;
flex-direction: column;
}
input {
height: 2em;
width: 15em;
}
.button {
position: relative;
top: 2em;
width: fit-content;
border: 2px solid;
margin-top: 20px;
margin: 0;
}
.button button {
cursor: pointer;
}
small {
font-style: italic;
color: red;
text-align: right;
width: 15em;
display: none;
margin: 0;
}
.error small {
display: block;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="card">
<form action="" id="form">
<h1>Please input your user name here</h1>
<div class="input"><input id="input" type="text" /></div>
<small></small>
<div class="button">
<button id="submit" type="submit">Submit</button>
</div>
</form>
</div></code></pre>
</div>
</div>
</p>
<p>This is what the vertical shift looks like before and after the error message appears.
The horizontal lines have been added to compare the positions.</p>
<p><a href="https://i.stack.imgur.com/xsMkA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xsMkA.png" alt="Side-by-side screenshots with horizontal lines added to compare heights. The element has a lower vertical position after the error message appears." /></a></p>
|
[
{
"answer_id": 74623562,
"author": "Maulik",
"author_id": 20581202,
"author_profile": "https://Stackoverflow.com/users/20581202",
"pm_score": -1,
"selected": false,
"text": "small {\n font-style: italic;\n color: red;\n text-align: right;\n width: 15em;\n visibility: hidden;\n height:10px;\n margin: 0;\n}\n\n.error small {\n visibility: visible;\n}\n function addError(message) {\n const small = document.querySelector(\"small\");\n small.classList.add(\"error\");\n small.innerText = message;\n small.style.visibility= \"visible\";\n}\n"
},
{
"answer_id": 74623580,
"author": "Carsten Massmann",
"author_id": 2610061,
"author_profile": "https://Stackoverflow.com/users/2610061",
"pm_score": 1,
"selected": false,
"text": ".preventDefault() if .textContent const form = document.getElementById(\"form\");\nconst input = document.getElementById(\"input\");\n\nform.addEventListener(\"submit\", function (e) {\n const name = input.value;\n\n if (name === \"\") {\ne.preventDefault();\naddError(\"Input field cannot be empty\");\n }\n});\n\nfunction addError(message) {\n const small = document.querySelector(\"small\");\n small.classList.add(\"error\");\n small.innerText = message;\n} * {\n box-sizing: border-box;\n}\n\nbody {\n font-family: Arial, Helvetica, sans-serif;\n}\n\n.card {\n display: flex;\n min-height: 100vh;\n justify-content: center;\n align-items: center;\n}\n\nform {\n display: flex;\n flex-direction: column;\n}\n\ninput {\n height: 2em;\n width: 15em;\n}\n\n.button {\n position: relative;\n top: 2em;\n width: fit-content;\n border: 2px solid;\n margin-top: 20px;\n margin: 0;\n}\n\n.button button {\n cursor: pointer;\n}\n\nsmall {\n font-style: italic;\n color: red;\n text-align: right;\n width: 15em;\n min-height: 20px;\n margin: 0;\n}\n\n.error small {\n display: block;\n} <div class=\"card\">\n <form action=\"somewhereelse.html\" id=\"form\">\n <h1>Please input your user name here</h1>\n <div class=\"input\"><input id=\"input\" type=\"text\" /></div>\n <small></small>\n <div class=\"button\">\n <button id=\"submit\" type=\"submit\">Submit</button>\n </div>\n </form>\n</div>"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20641575/"
] |
74,623,486
|
<p>I’m trying to click on a button that has the same class as other 5 buttons.</p>
<p>This code is working but clicks on the first button that finds the class.</p>
<pre><code>WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, ".com-ex-5"))).click()
</code></pre>
<p>How can I click on the 5th button?</p>
<p>This ain’t working :</p>
<pre><code>WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, ".com-ex-5")))[5].click()
</code></pre>
|
[
{
"answer_id": 74623562,
"author": "Maulik",
"author_id": 20581202,
"author_profile": "https://Stackoverflow.com/users/20581202",
"pm_score": -1,
"selected": false,
"text": "small {\n font-style: italic;\n color: red;\n text-align: right;\n width: 15em;\n visibility: hidden;\n height:10px;\n margin: 0;\n}\n\n.error small {\n visibility: visible;\n}\n function addError(message) {\n const small = document.querySelector(\"small\");\n small.classList.add(\"error\");\n small.innerText = message;\n small.style.visibility= \"visible\";\n}\n"
},
{
"answer_id": 74623580,
"author": "Carsten Massmann",
"author_id": 2610061,
"author_profile": "https://Stackoverflow.com/users/2610061",
"pm_score": 1,
"selected": false,
"text": ".preventDefault() if .textContent const form = document.getElementById(\"form\");\nconst input = document.getElementById(\"input\");\n\nform.addEventListener(\"submit\", function (e) {\n const name = input.value;\n\n if (name === \"\") {\ne.preventDefault();\naddError(\"Input field cannot be empty\");\n }\n});\n\nfunction addError(message) {\n const small = document.querySelector(\"small\");\n small.classList.add(\"error\");\n small.innerText = message;\n} * {\n box-sizing: border-box;\n}\n\nbody {\n font-family: Arial, Helvetica, sans-serif;\n}\n\n.card {\n display: flex;\n min-height: 100vh;\n justify-content: center;\n align-items: center;\n}\n\nform {\n display: flex;\n flex-direction: column;\n}\n\ninput {\n height: 2em;\n width: 15em;\n}\n\n.button {\n position: relative;\n top: 2em;\n width: fit-content;\n border: 2px solid;\n margin-top: 20px;\n margin: 0;\n}\n\n.button button {\n cursor: pointer;\n}\n\nsmall {\n font-style: italic;\n color: red;\n text-align: right;\n width: 15em;\n min-height: 20px;\n margin: 0;\n}\n\n.error small {\n display: block;\n} <div class=\"card\">\n <form action=\"somewhereelse.html\" id=\"form\">\n <h1>Please input your user name here</h1>\n <div class=\"input\"><input id=\"input\" type=\"text\" /></div>\n <small></small>\n <div class=\"button\">\n <button id=\"submit\" type=\"submit\">Submit</button>\n </div>\n </form>\n</div>"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8716197/"
] |
74,623,509
|
<p>I require a column which counts the number days i.e(Order Date - 01Jan2020).</p>
<p><strong>Condition is</strong> -> if Order Date lies between 01Jan2020 and 31Mar2020
then (DATE_DIFF('2020-01-31' ,Order Date, DAY))
else 0<br />
Question -> how to use this condition statement in BigQuery ?</p>
<p><strong>Table</strong> -
Customer ID | Order Date
298 | 2020-02-28
78 | 2020-04-02
31 | 2021-01-09
345 | 2021-09-09
74 | 2020-01-20</p>
<p>I tried -</p>
<pre><code>if((Order Date <'2020-01-01') and (Order Date >'2020-03-31'),(DATE_DIFF('2020-01-31' ,Order Date, DAY)
,0))
</code></pre>
|
[
{
"answer_id": 74623562,
"author": "Maulik",
"author_id": 20581202,
"author_profile": "https://Stackoverflow.com/users/20581202",
"pm_score": -1,
"selected": false,
"text": "small {\n font-style: italic;\n color: red;\n text-align: right;\n width: 15em;\n visibility: hidden;\n height:10px;\n margin: 0;\n}\n\n.error small {\n visibility: visible;\n}\n function addError(message) {\n const small = document.querySelector(\"small\");\n small.classList.add(\"error\");\n small.innerText = message;\n small.style.visibility= \"visible\";\n}\n"
},
{
"answer_id": 74623580,
"author": "Carsten Massmann",
"author_id": 2610061,
"author_profile": "https://Stackoverflow.com/users/2610061",
"pm_score": 1,
"selected": false,
"text": ".preventDefault() if .textContent const form = document.getElementById(\"form\");\nconst input = document.getElementById(\"input\");\n\nform.addEventListener(\"submit\", function (e) {\n const name = input.value;\n\n if (name === \"\") {\ne.preventDefault();\naddError(\"Input field cannot be empty\");\n }\n});\n\nfunction addError(message) {\n const small = document.querySelector(\"small\");\n small.classList.add(\"error\");\n small.innerText = message;\n} * {\n box-sizing: border-box;\n}\n\nbody {\n font-family: Arial, Helvetica, sans-serif;\n}\n\n.card {\n display: flex;\n min-height: 100vh;\n justify-content: center;\n align-items: center;\n}\n\nform {\n display: flex;\n flex-direction: column;\n}\n\ninput {\n height: 2em;\n width: 15em;\n}\n\n.button {\n position: relative;\n top: 2em;\n width: fit-content;\n border: 2px solid;\n margin-top: 20px;\n margin: 0;\n}\n\n.button button {\n cursor: pointer;\n}\n\nsmall {\n font-style: italic;\n color: red;\n text-align: right;\n width: 15em;\n min-height: 20px;\n margin: 0;\n}\n\n.error small {\n display: block;\n} <div class=\"card\">\n <form action=\"somewhereelse.html\" id=\"form\">\n <h1>Please input your user name here</h1>\n <div class=\"input\"><input id=\"input\" type=\"text\" /></div>\n <small></small>\n <div class=\"button\">\n <button id=\"submit\" type=\"submit\">Submit</button>\n </div>\n </form>\n</div>"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19565878/"
] |
74,623,525
|
<p>I can see GKE, AKS, EKS all are having nodepool concepts inbuilt but Kubernetes itself doesn't provide that support. What could be the reason behind this?</p>
<p>We usually need different Node types for different requirements such as below-</p>
<p>Some pods require either CPU or Memory intensive and optimized nodes.
Some pods are processing ML/AI algorithms and need GPU-enabled nodes. These GPU-enabled nodes should be used only by certain pods as they are expensive.
Some pods/jobs want to leverage spot/preemptible nodes to reduce the cost.</p>
<p>Is there any specific reason behind Kubernetes not having inbuilt such support?</p>
|
[
{
"answer_id": 74627095,
"author": "Harsh Manvar",
"author_id": 5525824,
"author_profile": "https://Stackoverflow.com/users/5525824",
"pm_score": 1,
"selected": true,
"text": "--cloud-provider"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2065476/"
] |
74,623,549
|
<p>In MongoDB (using <code>mongosh</code> or command-line mongo cli), you can query documents, for example using <code>db.mycollection.find({"something":true})</code> and get the following result:</p>
<pre class="lang-json prettyprint-override"><code>{
"someDate": ISODate("2022-10-24T17:21:44.980Z"),
"something": true,
"hello": "world"
}
</code></pre>
<p>This result, however, is not valid JSON (Due to <code>ISODate</code>). How can I change the query above to make MongoDB return canonical (valid) JSON?</p>
<p>I'm looking for a recursive and generalized way to do this, even for deeply nested documents.</p>
|
[
{
"answer_id": 74627195,
"author": "dangarfield",
"author_id": 3265253,
"author_profile": "https://Stackoverflow.com/users/3265253",
"pm_score": 0,
"selected": false,
"text": "db.collection.aggregate([\n {\n $match: {\n something: true\n }\n },\n {\n $project: {\n _id: 1,\n someDate: {\n $dateToString: {\n format: \"%Y-%m-%dT%H:%M:%S:%LZ\",\n date: \"$someDate\"\n }\n },\n something: 1,\n hello: 1\n }\n }\n])\n db.mycollection.find({\"something\":true}).forEach(function(doc) { \n doc.someDate = doc.someDate.toISOString() // or even .toJSON()\n})\n\n// Or with await\n\nconst records = await db.mycollection.find({\"something\":true}).map(doc => {\n doc.someDate = doc.someDate.toISOString()\n return doc\n}).toArray()\n"
},
{
"answer_id": 74629856,
"author": "user20042973",
"author_id": 20042973,
"author_profile": "https://Stackoverflow.com/users/20042973",
"pm_score": -1,
"selected": false,
"text": "mongo mongosh ISODate ISODate() mongo > db.mycollection.findOne({\"something\": true})\n{\n \"_id\" : 1,\n \"someDate\" : ISODate(\"2022-11-30T14:38:37.711Z\"),\n \"something\" : true,\n \"hello\" : \"world\"\n}\n ISODate() ISODate() JSON.stringify() > JSON.stringify( db.mycollection.findOne({\"something\": true}) )\n{\n \"_id\":1,\n \"someDate\":\"2022-11-30T14:38:37.711Z\",\n \"something\":true,\n \"hello\":\"world\"\n}\n mongosh > EJSON.serialize( db.mycollection.findOne() )\n{\n _id: 1,\n someDate: { '$date': '2022-11-30T14:38:37.711Z' },\n something: true,\n hello: 'world'\n}\n EJSON mongosh someDate"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/398441/"
] |
74,623,563
|
<p>We want to remind users to complete their workflow. These workflow events look like 'Workflow started', 'progressed stage 1', 'progressed stage 2',... 'Workflow ended' and they flow through Kafka. Each event has a unique identifier to identify a workflow attempt by the user.</p>
<p>How do we design a pipeline in Flink to detect workflows that have started but abandoned in the middle? Is there any established pattern for this?</p>
|
[
{
"answer_id": 74640603,
"author": "siliconsenthil",
"author_id": 227705,
"author_profile": "https://Stackoverflow.com/users/227705",
"pm_score": 0,
"selected": false,
"text": "Instant timerFireAt = event.getTimestamp().plusSeconds(timeoutDuration);\n\ncontext.timerService().registerProcessingTimeTimer(timerFireAt.toEpochMilli();\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/227705/"
] |
74,623,581
|
<p>I have a class in Python that initializes the attributes of an environment. I am attempting to grab the topographyRegistry attribute list of my Environment class in a separate function, which when called, should take in the parameters of 'self' and the topography to be added. When this function is called, it should simply take an argument such as addTopographyToEnvironment(self, "Mountains") and append it to the topographyRegistry of the Environment class.
When implementing what I mentioned above, I ran into an error regarding the 'self' method not being defined. Hence, whenever I call the above line, it gives me:</p>
<pre><code> print (Environment.addTopographyToEnvironment(self, "Mountains"))
^^^^
NameError: name 'self' is not defined
</code></pre>
<p>This leads me to believe that I am unaware of and missing a step in my implementation, but I am unsure of what that is exactly.
Here is the relevant code:</p>
<pre><code>class EnvironmentInfo:
def __init__(self, perceivableFood, perceivableCreatures, regionTopography, lightVisibility):
self.perceivableFood = perceivableFood
self.perceivableCreatures = perceivableCreatures
self.regionTopography = regionTopography
self.lightVisibility = lightVisibility
class Environment:
def __init__(self, creatureRegistry, foodRegistry, topographyRegistery, lightVisibility):
logging.info("Creating new environment")
self.creatureRegistry = []
self.foodRegistry = []
self.topographyRegistery = []
self.lightVisibility = True
def displayEnvironment():
creatureRegistry = []
foodRegistry = []
topographyRegistery = ['Grasslands']
lightVisibility = True
print (f"Creatures: {creatureRegistry} Food Available: {foodRegistry} Topography: {topographyRegistery} Contains Light: {lightVisibility}")
def addTopographyToEnvironment(self, topographyRegistery):
logging.info(
f"Registering {topographyRegistery} as a region in the Environment")
self.topographyRegistery.append(topographyRegistery)
def getRegisteredEnvironment(self):
return self.topographyRegistry
if __name__ == "__main__":
print (Environment.displayEnvironment()) #Display hardcoded attributes
print (Environment.addTopographyToEnvironment(self, "Mountains"))#NameError
print (Environment.getRegisteredEnvironment(self)) #NameError
</code></pre>
<p>What am I doing wrong or not understanding when using 'self'?</p>
<p>Edit: In regard to omitting 'self' from the print statement, it still gives me an error indicating a TypeError:</p>
<pre><code> print (Environment.addTopographyToEnvironment("Mountains"))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Environment.addTopographyToEnvironment() missing 1 required positional argument: 'topographyRegistery'
</code></pre>
|
[
{
"answer_id": 74623663,
"author": "alireza.2281",
"author_id": 4915494,
"author_profile": "https://Stackoverflow.com/users/4915494",
"pm_score": 0,
"selected": false,
"text": "addTopographyToEnvironment(self, newVal) Environment.addTopographyToEnvironment(\"Mountains\")\n"
},
{
"answer_id": 74624039,
"author": "Shmack",
"author_id": 3155240,
"author_profile": "https://Stackoverflow.com/users/3155240",
"pm_score": 2,
"selected": true,
"text": "def getRegisteredEnvironment(self): self self a = Environment(...) a addTopographyToEnvironment def my_class_method(self) a = my_object(); a.my_class_method(\"Mountains\") Environment.class_method() a = Environment(whatever arguments here) a.addTopographyToEnvironment(\"Mountains\") class EnvironmentInfo:\n def __init__(self, perceivableFood, perceivableCreatures, regionTopography, lightVisibility):\n self.perceivableFood = perceivableFood\n self.perceivableCreatures = perceivableCreatures\n self.regionTopography = regionTopography\n self.lightVisibility = lightVisibility\n\nclass Environment:\n def __init__(self, creatureRegistry, foodRegistry, topographyRegistery, lightVisibility):\n logging.info(\"Creating new environment\")\n self.creatureRegistry = creatureRegistry\n self.foodRegistry = foodRegistry\n self.topographyRegistery = topographyRegistery\n self.lightVisibility = lightVisibility\n\n def displayEnvironment(self):\n creatureRegistry = []\n foodRegistry = []\n topographyRegistery = ['Grasslands']\n lightVisibility = True\n print (f\"Creatures: {creatureRegistry} Food Available: {foodRegistry} Topography: {topographyRegistery} Contains Light: {lightVisibility}\")\n\n def addTopographyToEnvironment(self, environment):\n return \"Whatever this is supposed to return.\" + environment\n\n def getRegisteredEnvironment(self):\n return self.topographyRegistry\n\nif __name__ == \"__main__\":\n print (Environment.displayEnvironment()) #Display hardcoded attributes\n print (Environment.addTopographyToEnvironment(\"Mountains\"))#NameError\n print (Environment.getRegisteredEnvironment()) #NameError\n dir() class MyClass:\n def __init__(self, my_list):\n self.my_list = my_list\n\n\nif __name__ == \"__main__\":\n a = MyClass([1, 2, 3, 4, 5])\n print(a.my_list)\n # will print [1, 2, 3, 4, 5]\n a.my_list.append(6)\n print(a.my_list)\n # will print [1, 2, 3, 4, 5, 6]\n print(dir(a.my_list))\n # will print all object methods and object attributes for the list associated with object \"a\".\n super class EnvironmentInfo:\n def __init__(self, perceivableFood, perceivableCreatures, regionTopography, lightVisibility):\n self.perceivableFood = perceivableFood\n self.perceivableCreatures = perceivableCreatures\n self.regionTopography = regionTopography\n self.lightVisibility = lightVisibility\n\nclass Environment(EnvironmentInfo):\n def __init__(self, creatureRegistry, foodRegistry, topographyRegistery, lightVisibility, someOtherThingAvailableToEnvironmentButNotEnvironmentInfo):\n logging.info(\"Creating new environment\")\n super.__init__(foodRegistry, creatureRegistry, topographyRegistery, lightVisibility)\n self.my_var1 = someOtherThingAvailableToEnvironmentButNotEnvironmentInfo\n\n def displayEnvironment(self):\n creatureRegistry = []\n foodRegistry = []\n topographyRegistery = ['Grasslands']\n lightVisibility = True\n print (f\"Creatures: {creatureRegistry} Food Available: {foodRegistry} Topography: {topographyRegistery} Contains Light: {lightVisibility}\")\n\n def addTopographyToEnvironment(self, environment):\n return \"Whatever this is supposed to return.\" + environment\n\n def getRegisteredEnvironment(self):\n return self.topographyRegistry\n\n def methodAvailableToSubClassButNotSuper(self)\n return self.my_var1\n\nif __name__ == \"__main__\":\n a = Environment([], [], [], True, \"Only accessible to the sub class\")\n print(a.methodAvailableToSubClassButNotSuper())\n super()"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14652234/"
] |
74,623,587
|
<p>The IDE I used is Clion.
I wanna read the Line-separated data stored in .txt file.
Each line contains firstname, surname, gender, ID and age, which are str, str, str, int and int.</p>
<p>StudentList.txt</p>
<pre class="lang-none prettyprint-override"><code>Olivia SWANSON F 29001 20
Emma ONEILL F 7900 19
</code></pre>
<p>I try to use <code>fscanf</code> to read the data.</p>
<pre><code>FILE *fp;
char fname[20];
char sname[20];
char gender[1];
int ID;
int age;
fp = fopen("C:\\Users\\Catlover\\Desktop\\DSA\\Program2\\StudentList.txt", "r");
while(fscanf(fp, "%s %s %s %d %d", fname, sname, gender, &ID, &age)!= EOF)
{
printf("%s,%s,%s,%d,%d\n", fname, sname, gender, ID, age);
}
fclose(fp);
return 0;
</code></pre>
<p>But the result it return looks like a little bit weird becasue it doesn't output the second value.</p>
<p>Result is</p>
<pre class="lang-none prettyprint-override"><code>Olivia,,F,29001,20
Emma,,F,7900,19
</code></pre>
<p>Something shocks me is that the same code runned in PellesC lead to the correct result.</p>
<p>I used to learn C++ so there may exists some important rules in C but I didn't notice. Can anyone show that for me?</p>
|
[
{
"answer_id": 74623713,
"author": "kiran Biradar",
"author_id": 4431643,
"author_profile": "https://Stackoverflow.com/users/4431643",
"pm_score": 2,
"selected": false,
"text": "null char gender[1];\n char gender[2];\n"
},
{
"answer_id": 74623801,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 4,
"selected": true,
"text": "\"%s\" \"%s\" *scanf() char gender[1]; \"F\" fscanf(fp, \"%s %s %s %d %d\", ...) 5 EOF 5 fopen() fscanf() fclose() char fname[20 + 1];\nchar sname[20 + 1];\nchar gender[1 + 1];\nint ID;\nint age;\nFILE *fp = fopen(\"C:\\\\Users\\\\Catlover\\\\Desktop\\\\DSA\\\\Program2\\\\StudentList.txt\", \"r\");\nif (fp) {\n while(fscanf(fp, \"%20s %20s %1s %d %d\", fname, sname, gender, &ID, &age) == 5) {\n printf(\"%s,%s,%s,%d,%d\\n\", fname, sname, gender, ID, age);\n }\n fclose(fp);\n}\nreturn 0;\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20597124/"
] |
74,623,609
|
<p>I have created an add-in for excel. It's working fine for excel sheet. I want to use my add-ins in <strong>google sheet</strong>. I am not getting any idea about how to use add-in into google sheet.</p>
<p>Can anyone tell me that how to use add-in in google sheet. If any documentation is available, then please share it.</p>
|
[
{
"answer_id": 74623713,
"author": "kiran Biradar",
"author_id": 4431643,
"author_profile": "https://Stackoverflow.com/users/4431643",
"pm_score": 2,
"selected": false,
"text": "null char gender[1];\n char gender[2];\n"
},
{
"answer_id": 74623801,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 4,
"selected": true,
"text": "\"%s\" \"%s\" *scanf() char gender[1]; \"F\" fscanf(fp, \"%s %s %s %d %d\", ...) 5 EOF 5 fopen() fscanf() fclose() char fname[20 + 1];\nchar sname[20 + 1];\nchar gender[1 + 1];\nint ID;\nint age;\nFILE *fp = fopen(\"C:\\\\Users\\\\Catlover\\\\Desktop\\\\DSA\\\\Program2\\\\StudentList.txt\", \"r\");\nif (fp) {\n while(fscanf(fp, \"%20s %20s %1s %d %d\", fname, sname, gender, &ID, &age) == 5) {\n printf(\"%s,%s,%s,%d,%d\\n\", fname, sname, gender, ID, age);\n }\n fclose(fp);\n}\nreturn 0;\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19021757/"
] |
74,623,636
|
<p>I want to create a json string that contains a list of long values with the following structure:
{"document_ids":[23461504,20639162,20395579]}</p>
<p>I solved the problem with the line below, but I feel like I could do it with a cleaner command(string.Format).</p>
<pre><code>var json = "{\"document_ids\":" + JsonConvert.SerializeObject(My List<long>) + "}";
</code></pre>
<p>But the command I write with string.Format gives an error message.</p>
<pre><code>var json = string.Format("{\"document_ids\":{0}}", JsonConvert.SerializeObject(My List<long>));
</code></pre>
<p>I get this error message.
System.FormatException: 'Input string was not in a correct format.'</p>
|
[
{
"answer_id": 74623713,
"author": "kiran Biradar",
"author_id": 4431643,
"author_profile": "https://Stackoverflow.com/users/4431643",
"pm_score": 2,
"selected": false,
"text": "null char gender[1];\n char gender[2];\n"
},
{
"answer_id": 74623801,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 4,
"selected": true,
"text": "\"%s\" \"%s\" *scanf() char gender[1]; \"F\" fscanf(fp, \"%s %s %s %d %d\", ...) 5 EOF 5 fopen() fscanf() fclose() char fname[20 + 1];\nchar sname[20 + 1];\nchar gender[1 + 1];\nint ID;\nint age;\nFILE *fp = fopen(\"C:\\\\Users\\\\Catlover\\\\Desktop\\\\DSA\\\\Program2\\\\StudentList.txt\", \"r\");\nif (fp) {\n while(fscanf(fp, \"%20s %20s %1s %d %d\", fname, sname, gender, &ID, &age) == 5) {\n printf(\"%s,%s,%s,%d,%d\\n\", fname, sname, gender, ID, age);\n }\n fclose(fp);\n}\nreturn 0;\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11882732/"
] |
74,623,637
|
<p>Another total noob question: I am not sure why my answer is printing out as a decimal. Also, in the lab the dimes are expected to be listed first, not sure how I screwed that up? I appreciate the help!</p>
<p>Define a function called exact_change that takes the total change amount in cents and calculates the change using the fewest coins. The coin types are pennies, nickels, dimes, and quarters. Then write a main program that reads the total change amount as an integer input, calls exact_change(), and outputs the change, one coin type per line. Use singular and plural coin names as appropriate, like 1 penny vs. 2 pennies. Output "no change" if the input is 0 or less.</p>
<p>Your program must define and call the following function. The function exact_change() should return num_pennies, num_nickels, num_dimes, and num_quarters.
def exact_change(user_total)</p>
<pre><code>def exact_change(user_total):
return(num_dollars, num_quarters, num_dimes, num_nickles, num_pennies)
if __name__ == '__main__':
input_val = float(input())
num_dollars = input_val // 100
rem=input_val % 100
num_quarters = rem // 25
rem = rem % 25
num_dimes = rem // 10
rem = rem % 10
num_nickles = rem // 5
rem = rem % 5
num_pennies = rem
if input_val <= 0:
print("no change")
else:
num_dollars = input_val // 100
conv_dollar = str(num_dollars)
rem = input_val % 100
if num_dollars == 1:
print(conv_dollar + ' dollar')
elif num_dollars > 1:
print(conv_dollar + ' dollars')
num_quarters = rem // 25
conv_quarter = str(num_quarters)
rem = rem % 25
if num_quarters == 1:
print(conv_quarter + ' quarter')
elif num_quarters > 1:
print(conv_quarter + ' quarters')
num_dimes = rem // 10
conv_dime = str(num_dimes)
rem = rem % 10
if num_dimes == 1:
print(conv_dime + ' dime')
elif num_dimes > 1:
print(conv_dime + ' dimes')
num_nickels = rem // 5
conv_nickel = str(num_nickels)
rem = rem % 5
if num_nickels == 1:
print(conv_nickel + ' nickel')
elif num_nickels > 1:
print(conv_nickel + ' nickels')
num_pennies = rem
conv_penny = str(num_pennies)
rem = rem % 1
if num_pennies == 1:
print(conv_penny + ' penny')
elif num_pennies > 1:
print(conv_penny + ' pennies')
</code></pre>
<p>1:Compare output
0 / 1
Output differs. See highlights below.
Special character legend
Input
45
Your output
1.0 quarter
2.0 dimes
Expected output
2 dimes
1 quarter
2:Compare output
1 / 1
Input
0
Your output
no change
3:Compare output
0 / 2
Output differs. See highlights below.
Special character legend
Input
156
Your output
1.0 dollar
2.0 quarters
1.0 nickel
1.0 penny
Expected output
1 penny
1 nickel
6 quarters
4:Unit test
0 / 3
exact_change(300). Should return 0, 0, 0, 12
NameError: name 'input_val' is not defined
5:Unit test
0 / 3
exact_change(141). Should return 1, 1, 1, 5
NameError: name 'input_val' is not defined</p>
|
[
{
"answer_id": 74623713,
"author": "kiran Biradar",
"author_id": 4431643,
"author_profile": "https://Stackoverflow.com/users/4431643",
"pm_score": 2,
"selected": false,
"text": "null char gender[1];\n char gender[2];\n"
},
{
"answer_id": 74623801,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 4,
"selected": true,
"text": "\"%s\" \"%s\" *scanf() char gender[1]; \"F\" fscanf(fp, \"%s %s %s %d %d\", ...) 5 EOF 5 fopen() fscanf() fclose() char fname[20 + 1];\nchar sname[20 + 1];\nchar gender[1 + 1];\nint ID;\nint age;\nFILE *fp = fopen(\"C:\\\\Users\\\\Catlover\\\\Desktop\\\\DSA\\\\Program2\\\\StudentList.txt\", \"r\");\nif (fp) {\n while(fscanf(fp, \"%20s %20s %1s %d %d\", fname, sname, gender, &ID, &age) == 5) {\n printf(\"%s,%s,%s,%d,%d\\n\", fname, sname, gender, ID, age);\n }\n fclose(fp);\n}\nreturn 0;\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20587741/"
] |
74,623,671
|
<p>how to write a model class with getters and setters defined and returned</p>
<pre><code>public Team(Long id,String queue,Number answered,Number offered, Number answerRate,Number abandoned,String avgAbandonTime,Number totalTalkTime,Number avgTalkTime, Number unmanaged) {
this.id = id;
this.queue = queue;
this.answered = answered;
this.offered = offered;
this.answerRate = answerRate;
this.abandoned = abandoned;
this.avgAbandonTime = avgAbandonTime;
this.totalTalkTime = totalTalkTime;
this.avgTalkTime = avgTalkTime;
this.unmanaged=unmanaged;
}
//getters and setters..
}
</code></pre>
|
[
{
"answer_id": 74623713,
"author": "kiran Biradar",
"author_id": 4431643,
"author_profile": "https://Stackoverflow.com/users/4431643",
"pm_score": 2,
"selected": false,
"text": "null char gender[1];\n char gender[2];\n"
},
{
"answer_id": 74623801,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 4,
"selected": true,
"text": "\"%s\" \"%s\" *scanf() char gender[1]; \"F\" fscanf(fp, \"%s %s %s %d %d\", ...) 5 EOF 5 fopen() fscanf() fclose() char fname[20 + 1];\nchar sname[20 + 1];\nchar gender[1 + 1];\nint ID;\nint age;\nFILE *fp = fopen(\"C:\\\\Users\\\\Catlover\\\\Desktop\\\\DSA\\\\Program2\\\\StudentList.txt\", \"r\");\nif (fp) {\n while(fscanf(fp, \"%20s %20s %1s %d %d\", fname, sname, gender, &ID, &age) == 5) {\n printf(\"%s,%s,%s,%d,%d\\n\", fname, sname, gender, ID, age);\n }\n fclose(fp);\n}\nreturn 0;\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20529148/"
] |
74,623,696
|
<p>Trying to query an oracle db table having date in format: <code>2022-06-22T12:25:06.087</code> (<code>LocalDateTime.now().toString()</code>). Column type for created_time is varchar2.
Trying to query for data between two dates. I have tried the following but it results in error "date format not recognized":</p>
<pre><code>select * from MY_TABLE
where to_date(created_time, 'yyyy-MM-ddTHH:mm:ss.SSS')
between to_date('2022-07-03T10:15:06.091', 'yyyy-MM-ddTHH:mm:ss.SSS')
and to_date('2022-07-03T10:15:06.091', 'yyyy-MM-ddTHH:mm:ss.SSS');
</code></pre>
<p>Can anyone help me correct this query?</p>
|
[
{
"answer_id": 74623877,
"author": "Wernfried Domscheit",
"author_id": 3027266,
"author_profile": "https://Stackoverflow.com/users/3027266",
"pm_score": 2,
"selected": false,
"text": "created_time DATE TIMESTAMP TO_DATE() TO_TIMESTAMP() DATE DATE TIMESTAMP HH HH24 mm MM MI SSS select * \nfrom MY_TABLE\nwhere created_time\n between TO_TIMESTAMP('2022-07-03T10:15:06.091', 'yyyy-MM-dd\"T\"HH24:MI:ss.ff3') \n and TO_TIMESTAMP('2022-07-03T10:15:06.091', 'yyyy-MM-dd\"T\"HH24:MI:ss.ff3');\n"
},
{
"answer_id": 74623882,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 3,
"selected": true,
"text": "CREATED_TIME TO_DATE to_timestamp between mi mm ff3 sss SELECT *\n FROM my_table\n WHERE created_time \n BETWEEN TO_TIMESTAMP ('2022-07-03T10:15:06.091', 'yyyy-MM-dd\"T\"HH24:mi:ss.ff3')\n AND TO_TIMESTAMP ('2022-07-03T10:15:06.091', 'yyyy-MM-dd\"T\"HH24:mi:ss.ff3');\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2534054/"
] |
74,623,704
|
<p>The main problem my code doesn't do echo every time(fibonacci sequence)</p>
<pre><code>#!/bin/bash
function fib(){
if [ $1 -le 0 ]; then
echo 0
elif [ $1 -eq 1 ]; then
echo 1
else
echo $[`fib $[$1 - 2]` + `fib $[$1 - 1]` ]
fi
}
fib $1
</code></pre>
<p>i was expecting it will do echo every time. It shows:</p>
<pre><code>~/Bash$ ./fn.sh 12
144
</code></pre>
<p>but i need it to show like this:</p>
<pre><code>~/Bash$ ./fn.sh 12
0
1
1
2
3
5
8
13
21
34
55
89
144
</code></pre>
|
[
{
"answer_id": 74623877,
"author": "Wernfried Domscheit",
"author_id": 3027266,
"author_profile": "https://Stackoverflow.com/users/3027266",
"pm_score": 2,
"selected": false,
"text": "created_time DATE TIMESTAMP TO_DATE() TO_TIMESTAMP() DATE DATE TIMESTAMP HH HH24 mm MM MI SSS select * \nfrom MY_TABLE\nwhere created_time\n between TO_TIMESTAMP('2022-07-03T10:15:06.091', 'yyyy-MM-dd\"T\"HH24:MI:ss.ff3') \n and TO_TIMESTAMP('2022-07-03T10:15:06.091', 'yyyy-MM-dd\"T\"HH24:MI:ss.ff3');\n"
},
{
"answer_id": 74623882,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 3,
"selected": true,
"text": "CREATED_TIME TO_DATE to_timestamp between mi mm ff3 sss SELECT *\n FROM my_table\n WHERE created_time \n BETWEEN TO_TIMESTAMP ('2022-07-03T10:15:06.091', 'yyyy-MM-dd\"T\"HH24:mi:ss.ff3')\n AND TO_TIMESTAMP ('2022-07-03T10:15:06.091', 'yyyy-MM-dd\"T\"HH24:mi:ss.ff3');\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20641943/"
] |
74,623,706
|
<p>I have a date which is a string and looks like this:</p>
<pre><code>String day = "30-11-2022 12:27";
</code></pre>
<p>I am trying to convert the above string to DateTime object and convert the 24hr time to 12hr. I am using the following code:</p>
<pre><code>DateFormat("dd-MM-yyyy hh:mm a").parse(day);
</code></pre>
<p>It was working before but today the parsing is causing format exception error. The error message is shown below:</p>
<pre><code>[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: FormatException: Trying to read from 30-11-2022 12:27 at position 17
</code></pre>
<p>Why am I getting error while parsing now? How to fix it?</p>
|
[
{
"answer_id": 74623871,
"author": "Ante Bule",
"author_id": 17104517,
"author_profile": "https://Stackoverflow.com/users/17104517",
"pm_score": 0,
"selected": false,
"text": "final str = \"30-11-2022 12:27\";\nfinal date = DateFormat(\"dd-MM-yyyy hh:mm\").parse(str);\nfinal formated = DateFormat(\"dd-MM-yyyy h:mm a\").format(date);\n"
},
{
"answer_id": 74623914,
"author": "Sachin Kumawat",
"author_id": 11830339,
"author_profile": "https://Stackoverflow.com/users/11830339",
"pm_score": -1,
"selected": false,
"text": "String day = \"30-11-2022 15:27\";\nfinal date = DateFormat(\"dd-MM-yyyy hh:mm\").parse(day);\nfinal formatDate =DateFormat(\"dd-MM-yyyy hh:mm a\").format(date);\nprint(formatDate.toString());\n\n\noutput: 30-11-2022 03:27 PM\n"
},
{
"answer_id": 74623977,
"author": "Roslan Amir",
"author_id": 3365667,
"author_profile": "https://Stackoverflow.com/users/3365667",
"pm_score": 0,
"selected": false,
"text": "'HH:mm' add_jm() final day = '30-11-2022 12:27';\nfinal dateTime = DateFormat('dd-MM-yyyy HH:mm').parse(day);\nfinal formatted = DateFormat('dd-MM-yyy').add_jm().format(dateTime);\nprint(formatted);\n 30-11-2022 12:27 PM\n"
},
{
"answer_id": 74624065,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 0,
"selected": false,
"text": "String day = \"30-11-2022 12:27\";\n\nDateTime date = normalFormat.parse(day);\n"
},
{
"answer_id": 74624193,
"author": "vitashopper",
"author_id": 14321001,
"author_profile": "https://Stackoverflow.com/users/14321001",
"pm_score": 0,
"selected": false,
"text": "DateTime dateTime = DateFormat('yyyy/MM/dd h:m').parse(date);\nfinal DateFormat formatter = DateFormat('yyyy-MM-dd h:m a');\nfinal String formatted = formatter.format(dateTime);\n"
},
{
"answer_id": 74624514,
"author": "jamesdlin",
"author_id": 179715,
"author_profile": "https://Stackoverflow.com/users/179715",
"pm_score": 0,
"selected": false,
"text": "DateFormat a \"30-11-2022 12:27\" DateFormat h H String day = \"30-11-2022 12:27\";\nvar datetime = DateFormat(\"dd-MM-yyyy HH:mm\").parse(day);\n\n// Prints: 30-11-2022 12:27 PM\nprint(DateFormat('dd-MM-yyyy hh:mm a').format(datetime)); \n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6067774/"
] |
74,623,741
|
<p><a href="https://i.stack.imgur.com/RhAdl.png" rel="nofollow noreferrer">enter image description here</a>I have completely installed my react router and my project is build completely but the only issue is that when I imported this</p>
<pre><code>import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
</code></pre>
<p>Import in <code>App.js</code>
<a href="https://i.stack.imgur.com/BQaCv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BQaCv.png" alt="enter image description here" /></a></p>
<p>Import in <code>Navbar.js</code>
<a href="https://i.stack.imgur.com/5WnVy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5WnVy.png" alt="enter image description here" /></a></p>
<p>the <code>Link</code> is in light color in vs code compared to others that means that means it is not imported and thus I cannot replace anchor tag and href with Link to="".
Anyone can please help with the solution because without these I cannot continue further.</p>
|
[
{
"answer_id": 74623871,
"author": "Ante Bule",
"author_id": 17104517,
"author_profile": "https://Stackoverflow.com/users/17104517",
"pm_score": 0,
"selected": false,
"text": "final str = \"30-11-2022 12:27\";\nfinal date = DateFormat(\"dd-MM-yyyy hh:mm\").parse(str);\nfinal formated = DateFormat(\"dd-MM-yyyy h:mm a\").format(date);\n"
},
{
"answer_id": 74623914,
"author": "Sachin Kumawat",
"author_id": 11830339,
"author_profile": "https://Stackoverflow.com/users/11830339",
"pm_score": -1,
"selected": false,
"text": "String day = \"30-11-2022 15:27\";\nfinal date = DateFormat(\"dd-MM-yyyy hh:mm\").parse(day);\nfinal formatDate =DateFormat(\"dd-MM-yyyy hh:mm a\").format(date);\nprint(formatDate.toString());\n\n\noutput: 30-11-2022 03:27 PM\n"
},
{
"answer_id": 74623977,
"author": "Roslan Amir",
"author_id": 3365667,
"author_profile": "https://Stackoverflow.com/users/3365667",
"pm_score": 0,
"selected": false,
"text": "'HH:mm' add_jm() final day = '30-11-2022 12:27';\nfinal dateTime = DateFormat('dd-MM-yyyy HH:mm').parse(day);\nfinal formatted = DateFormat('dd-MM-yyy').add_jm().format(dateTime);\nprint(formatted);\n 30-11-2022 12:27 PM\n"
},
{
"answer_id": 74624065,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 0,
"selected": false,
"text": "String day = \"30-11-2022 12:27\";\n\nDateTime date = normalFormat.parse(day);\n"
},
{
"answer_id": 74624193,
"author": "vitashopper",
"author_id": 14321001,
"author_profile": "https://Stackoverflow.com/users/14321001",
"pm_score": 0,
"selected": false,
"text": "DateTime dateTime = DateFormat('yyyy/MM/dd h:m').parse(date);\nfinal DateFormat formatter = DateFormat('yyyy-MM-dd h:m a');\nfinal String formatted = formatter.format(dateTime);\n"
},
{
"answer_id": 74624514,
"author": "jamesdlin",
"author_id": 179715,
"author_profile": "https://Stackoverflow.com/users/179715",
"pm_score": 0,
"selected": false,
"text": "DateFormat a \"30-11-2022 12:27\" DateFormat h H String day = \"30-11-2022 12:27\";\nvar datetime = DateFormat(\"dd-MM-yyyy HH:mm\").parse(day);\n\n// Prints: 30-11-2022 12:27 PM\nprint(DateFormat('dd-MM-yyyy hh:mm a').format(datetime)); \n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20642007/"
] |
74,623,765
|
<p>Help me plz. I have two dataframes, for example:</p>
<pre><code>| 1 | 4 |
| 2 | 5 |
| 3 | 6 |
</code></pre>
<p>and</p>
<pre><code>| 7 | 10 |
| 8 | 11 |
| 9 | 12 |
</code></pre>
<p>How to join them into one vertical dataframe like this:</p>
<pre><code>| 1 | 4 |
| 2 | 5 |
| 3 | 6 |
| 7 | 10 |
| 8 | 11 |
| 9 | 12 |
</code></pre>
<p>many thx</p>
|
[
{
"answer_id": 74623871,
"author": "Ante Bule",
"author_id": 17104517,
"author_profile": "https://Stackoverflow.com/users/17104517",
"pm_score": 0,
"selected": false,
"text": "final str = \"30-11-2022 12:27\";\nfinal date = DateFormat(\"dd-MM-yyyy hh:mm\").parse(str);\nfinal formated = DateFormat(\"dd-MM-yyyy h:mm a\").format(date);\n"
},
{
"answer_id": 74623914,
"author": "Sachin Kumawat",
"author_id": 11830339,
"author_profile": "https://Stackoverflow.com/users/11830339",
"pm_score": -1,
"selected": false,
"text": "String day = \"30-11-2022 15:27\";\nfinal date = DateFormat(\"dd-MM-yyyy hh:mm\").parse(day);\nfinal formatDate =DateFormat(\"dd-MM-yyyy hh:mm a\").format(date);\nprint(formatDate.toString());\n\n\noutput: 30-11-2022 03:27 PM\n"
},
{
"answer_id": 74623977,
"author": "Roslan Amir",
"author_id": 3365667,
"author_profile": "https://Stackoverflow.com/users/3365667",
"pm_score": 0,
"selected": false,
"text": "'HH:mm' add_jm() final day = '30-11-2022 12:27';\nfinal dateTime = DateFormat('dd-MM-yyyy HH:mm').parse(day);\nfinal formatted = DateFormat('dd-MM-yyy').add_jm().format(dateTime);\nprint(formatted);\n 30-11-2022 12:27 PM\n"
},
{
"answer_id": 74624065,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 0,
"selected": false,
"text": "String day = \"30-11-2022 12:27\";\n\nDateTime date = normalFormat.parse(day);\n"
},
{
"answer_id": 74624193,
"author": "vitashopper",
"author_id": 14321001,
"author_profile": "https://Stackoverflow.com/users/14321001",
"pm_score": 0,
"selected": false,
"text": "DateTime dateTime = DateFormat('yyyy/MM/dd h:m').parse(date);\nfinal DateFormat formatter = DateFormat('yyyy-MM-dd h:m a');\nfinal String formatted = formatter.format(dateTime);\n"
},
{
"answer_id": 74624514,
"author": "jamesdlin",
"author_id": 179715,
"author_profile": "https://Stackoverflow.com/users/179715",
"pm_score": 0,
"selected": false,
"text": "DateFormat a \"30-11-2022 12:27\" DateFormat h H String day = \"30-11-2022 12:27\";\nvar datetime = DateFormat(\"dd-MM-yyyy HH:mm\").parse(day);\n\n// Prints: 30-11-2022 12:27 PM\nprint(DateFormat('dd-MM-yyyy hh:mm a').format(datetime)); \n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20181990/"
] |
74,623,812
|
<p>I observed a weird behavior while experimenting with a PLINQ query. Here is the scenario:</p>
<ul>
<li>There is a source <code>IEnumerable<int></code> sequence that contains the two items 1 and 2.</li>
<li>A Parallel LINQ <a href="https://learn.microsoft.com/en-us/dotnet/api/system.linq.parallelenumerable.select" rel="nofollow noreferrer"><code>Select</code></a> operation is applied on this sequence, projecting each item to itself (<code>x => x</code>).</li>
<li>The resulting <code>ParallelQuery<int></code> query is consumed immediately with a <code>foreach</code> loop.</li>
<li>The <code>selector</code> lambda of the <code>Select</code> projects successfully the item 1.</li>
<li>The consuming <code>foreach</code> loop throws an exception for the item 1.</li>
<li>The <code>selector</code> lambda throws an exception for the item 2, after a small delay.</li>
</ul>
<p>What happens next is that the consuming exception is lost! Apparently it is shadowed by the exception thrown afterwards in the <code>Select</code>. Here is a minimal demonstration of this behavior:</p>
<pre><code>ParallelQuery<int> query = Enumerable.Range(1, 2)
.AsParallel()
.Select(x =>
{
if (x == 2) { Thread.Sleep(500); throw new Exception($"Oops!"); }
return x;
});
try
{
foreach (int item in query)
{
Console.WriteLine($"Consuming item #{item} started");
throw new Exception($"Consuming item #{item} failed");
}
}
catch (AggregateException aex)
{
Console.WriteLine($"AggregateException ({aex.InnerExceptions.Count})");
foreach (Exception ex in aex.InnerExceptions)
Console.WriteLine($"- {ex.GetType().Name}: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"{ex.GetType().Name}: {ex.Message}");
}
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>Consuming item #1 started
AggregateException (1)
- Exception: Oops!
</code></pre>
<p><a href="https://dotnetfiddle.net/ggamsF" rel="nofollow noreferrer">Live demo</a>.</p>
<p>Chronologically the consuming exception happens first, and the PLINQ exception happens later. So my understanding is that the consuming exception is more important, and it should be propagated with priority. Nevertheless the only exception that is surfaced is the one that occurs inside the PLINQ code.</p>
<p><strong>My question is:</strong> why is the consuming exception lost, and is there any way that I can fix the query so that the consuming exception is propagated with priority?</p>
<p>The desirable output is this:</p>
<pre class="lang-none prettyprint-override"><code>Consuming item #1 started
Exception: Consuming item #1 failed
</code></pre>
|
[
{
"answer_id": 74635235,
"author": "NetMage",
"author_id": 2557128,
"author_profile": "https://Stackoverflow.com/users/2557128",
"pm_score": 3,
"selected": true,
"text": "foreach while (MoveNext()) try finally Dispose() Select finally try catch try catch Select foreach foreach Dispose AggregateException foreach var b = true;\nvar query = Enumerable.Range(1, 3)\n .AsParallel()\n .Select(x => {\n Thread.Sleep(50 * (x - 1));\n Console.WriteLine($\"Select({x})\");\n if (x >= 2) {\n throw new Exception($\"Oops {x}!\");\n }\n return x;\n });\n\ntry {\n query.ForEachAggregatingExceptions(item => {\n Console.WriteLine($\"Consuming item #{item} started\");\n if (b) {\n throw new Exception($\"Consuming item #{item} failed\");\n }\n });\n}\ncatch (AggregateException aex) {\n Console.WriteLine($\"AggregateException ({aex.InnerExceptions.Count})\");\n foreach (Exception ex in aex.InnerExceptions)\n Console.WriteLine($\"- {ex.GetType().Name}: {ex.Message}\");\n}\ncatch (Exception ex) {\n Console.WriteLine($\"{ex.GetType().Name}: {ex.Message}\");\n}\n\npublic static class ParallelQueryExt {\n public static void ForEachAggregatingExceptions<T>(this ParallelQuery<T> pq, Action<T> processFn) {\n Exception FirstException = null;\n var e = pq.GetEnumerator();\n try {\n while (e.MoveNext())\n processFn(e.Current);\n }\n catch (Exception ex) {\n FirstException = ex;\n }\n finally {\n if (e != null) {\n try {\n e.Dispose();\n }\n catch (AggregateException aex) { // combine exceptions from Dispose with FirstException if any\n if (FirstException != null) {\n throw new AggregateException(aex.InnerExceptions.Prepend(FirstException));\n }\n else\n throw;\n }\n catch (Exception ex) { // combine single exception from Dispose with FirstException if any\n throw new AggregateException(new[] { ex, FirstException });\n }\n if (FirstException != null) // re-throw FirstException if no others occurred\n throw FirstException;\n }\n }\n }\n}\n b if while if throw"
},
{
"answer_id": 74673923,
"author": "Theodor Zoulias",
"author_id": 11178549,
"author_profile": "https://Stackoverflow.com/users/11178549",
"pm_score": 0,
"selected": false,
"text": "Dispose Dispose Task Task TaskScheduler.UnobservedTaskException Dispose Task AggregateException Dispose TaskScheduler.UnobservedTaskException Task.FromException /// <summary>\n/// Suppresses the error that might be thrown by the enumerator on Dispose.\n/// The error triggers the TaskScheduler.UnobservedTaskException event.\n/// </summary>\npublic static IEnumerable<TSource> SuppressDisposeException<TSource>(\n this IEnumerable<TSource> source)\n{\n ArgumentNullException.ThrowIfNull(source);\n IEnumerator<TSource> enumerator = source.GetEnumerator();\n try\n {\n while (enumerator.MoveNext()) yield return enumerator.Current;\n try { enumerator.Dispose(); } finally { enumerator = null; }\n }\n finally\n {\n try { enumerator?.Dispose(); }\n catch (Exception ex) { _ = Task.FromException(ex); }\n }\n}\n false MoveNext Dispose IEnumerable<int> query = Enumerable.Range(1, 2)\n .AsParallel()\n .Select(x => /* ... */ x)\n .SuppressDisposeException();\n TaskScheduler.UnobservedTaskException GC.Collect Dispose break foreach"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74623812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11178549/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.